我有一个可能非常基本的问题,但我似乎无法在堆栈上找到它(我发现它非常复杂)所以我很抱歉,如果它已经在某处了。
我正在用java编写一个纸牌游戏,我想将绘制新卡片的代码移动到一个单独的方法中,这样我就可以随时调用它,而不是出现相同的代码片段每当我需要它时,一次又一次。
唯一的问题是我不知道使用什么类型的方法或如何调用它,因为它不会返回任何东西,只需要做一堆代码。
这是我的代码中的一张牌,如果这有助于展示我的目标。
if (event.getSource() == hit && endOfRound == false) {
Continue = true;
while (Continue == true) //If the random number has been drawn before, loop the random number generator again
{
cardID = (int) RandomNumber.GetRandomNumber(52);
if (cardsLeft[cardID] == true) //If a new card is drawn, continue normally
{
Continue = false; //Stop the loop that draws a new card
cardsLeft[cardID] = false; //save that the card was drawn
stay.setBackground(Color.green);
plyrSum += BlackJack.value(cardID); //add value to sum
plyrSumLabel.setText("Your sum: " + plyrSum); //display new sum
cardLabel[plyrCardCounter].setIcon(cardImage[cardID]); //Display card
plyrCardCounter++;
if (cardID >= 48) //record how many aces are in the hand so the program knows how many times it can reduce the sum.
plyrAceCounter++;
while (plyrSum > 21 && plyrAceCounter > 0) //If bust, reduce the value of an ace by 10 (from 11 to 1).
{
plyrSum -= 10;
plyrSumLabel.setText("Your sum: " + plyrSum);
plyrAceCounter--;
}
if (plyrSum > 21) //Automatically end the round if someone busts (player)
{
stay.doClick();
}
}
}
}
答案 0 :(得分:0)
声明返回void的方法 drawCard()。现在复制 if 中的块并将其粘贴到方法中。 然后重写 if 部分:
if (event.getSource() == hit && endOfRound == false) drawCard();