心血來潮想要來寫個撲克牌,就動手下去寫了,卡片有Color跟Point兩個屬性,卡組有Group屬性與GetRandowmCard()、ReadGroup()、Shuffle()以及建構子CardGroup()。
物件:卡牌。若是要繼續延伸為大老二遊戲的話,enum可以用來比較花色。
class Card
{
private int _point;
private int _color;
public int Point { get => _point; set => _point = value; }
public int Color { get => _color; set => _color = value; }
public enum EColor
{
Spades = 0,
Heart = 1,
Diamond = 2,
Plum = 3
}
}
卡組:建構子。i決定點數,j決定花色,這樣一建立起來的卡組會排序好的卡組。
public CardGroup()
{
for (int i = 0; i < 13; i++)
{
for (int j = 0; j < 4; j++)
{
Card Card = new Card();
Card.Color = j;
Card.Point = i + 1;
Group.Add(Card);
}
}
}
卡組:隨機抽一張牌。52張牌中隨機抽一張牌回傳,並刪除在卡組中的這張牌。
public Card GetRandowmCard()
{
Random random = new Random(Guid.NewGuid().GetHashCode());
int Cardindex = random.Next(Group.Count);
Card Card = new Card
{
Point = Group[Cardindex].Point,
Color = Group[Cardindex].Color
};
Group.RemoveAt(Cardindex);
return Card;
}
卡牌:洗牌,實際上是使用上一個抽牌的方法,抽52次到新的卡組,由新的卡組給予卡組。
public void Shuffle()
{
List<Card> NewGroup = new List<Card>();
CardGroup CardGroup = new CardGroup();
foreach (Card Card in Group)
{
NewGroup.Add(CardGroup.GetRandowmCard());
}
Group = NewGroup;
}
下列是完整程式碼
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class CardGroup
{
public List<Card> Group = new List<Card>();
public CardGroup()
{
for (int i = 0; i < 13; i++)
{
for (int j = 0; j < 4; j++)
{
Card Card = new Card();
Card.Color = j;
Card.Point = i + 1;
Group.Add(Card);
}
}
}
public Card GetRandowmCard()
{
Random random = new Random(Guid.NewGuid().GetHashCode());
int Cardindex = random.Next(Group.Count);
Card Card = new Card
{
Point = Group[Cardindex].Point,
Color = Group[Cardindex].Color
};
Group.RemoveAt(Cardindex);
return Card;
}
public void ReadGroup()
{
foreach (Card Card in Group)
{
Console.WriteLine("Point = " + Card.Point.ToString().PadLeft(2, ' ') + " Color = " + (Card.EColor)Card.Color);
}
}
public void Shuffle()
{
List<Card> NewGroup = new List<Card>();
CardGroup CardGroup = new CardGroup();
foreach (Card Card in Group)
{
NewGroup.Add(CardGroup.GetRandowmCard());
}
Group = NewGroup;
}
}
class Card
{
private int _point;
private int _color;
public int Point { get => _point; set => _point = value; }
public int Color { get => _color; set => _color = value; }
public enum EColor
{
Spades = 0,
Heart = 1,
Diamond = 2,
Plum = 3
}
}
class Program
{
static void Main(string[] args)
{
CardGroup CardGroup = new CardGroup();
CardGroup.Shuffle();
CardGroup.ReadGroup();
Console.ReadKey();
}
}
}
這程式其實已經可以做到發牌了,我覺得真正的困難點是遊戲的規則,例如大老二要怎麼判斷出牌的類別,而且若是要多人連線會使用到TCP/IP,期望我之後能完成。