【发布时间】:2018-02-02 21:59:38
【问题描述】:
我正在编写一个模拟洗牌和抽牌的基本程序。抽完之后,我在牌组数组中为牌组的类变量赋予了 0 和 null 的值,分别代表等级和花色,以检查牌是否是从牌组中抽出的。但是,当我将卡片组数组中的卡片设置为 0 和 null 时,它也会将手数组中的卡片设置为相同。任何解决问题的建议都非常感谢。谢谢!
抽卡按钮代码:
Card drawn = new Card(0, null);
//
do
{
i++;
drawn = test.cards[i];
} while (drawn.rank == 0 || drawn.suit == null);
//
output = drawn.rank + " " + drawn.suit;
lblOutput.Text = output;
//
addToHand(drawn);
if (handCount < 5)
{
handCount++;
}
test.cards[i].suit = null;
test.cards[i].rank = 0;
//
if (i >= 51)
{
MessageBox.Show("You have drawn all the cards.");
btnDraw.Enabled = false;
btnShuffle.Enabled = false;
}
addToHand 函数:
private void addToHand(Card drawn)
{
if (handCount < 5)
{
if (hand[0].suit == null)
{
hand[0] = drawn;
button1.Text = hand[0].rank + " " + hand[0].suit;
button1.Enabled = true;
}
else if (hand[1].suit == null)
{
hand[1] = drawn;
button2.Text = hand[1].rank + " " + hand[1].suit;
button2.Enabled = true;
}
else if (hand[2].suit == null)
{
hand[2] = drawn;
button3.Text = hand[2].rank + " " + hand[2].suit;
button3.Enabled = true;
}
else if (hand[3].suit == null)
{
hand[3] = drawn;
button4.Text = hand[3].rank + " " + hand[3].suit;
button4.Enabled = true;
}
else if (hand[4].suit == null)
{
hand[4] = drawn;
button5.Text = hand[4].rank + " " + hand[4].suit;
button5.Enabled = true;
}
}
这里是甲板和卡片的类:
public class Deck
{
public Card[] cards;
public Deck() //Fills new array with 52 cards
{
cards = new Card[52];
var index = 0;
foreach (var suit in new[] { "Spades", "Hearts", "Clubs", "Diamonds", })
{
for (var rank = 1; rank <= 13; rank++)
{
cards[index++] = new Card(rank, suit);
}
}
}
}
public class Card
{
public int rank { get; set; }
public string suit { get; set; }
public Card(int rk, string st)
{
rank = rk;
suit = st;
}
}
【问题讨论】:
-
这是引用类型的基础知识。不要将
test.cards[i].suit分配给null,而是将整个卡test.cards[i]设置为null?
标签: c# visual-studio