我有一個可能非常基本的問題,但我似乎無法在堆棧中找到它(並且我發現的東西非常複雜),所以如果它已經出來,我很抱歉那裏有地方。如何調用並執行方法
我正在用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();
}
}
}
}
分解一個複雜的過程分成一系列更小的,獨立的,並且在邏輯上不同的步驟是,一般地,總是一個好主意。在像Java這樣的面向對象的語言中,這應該作爲對象模型的自然結果發生。我注意到你正在寫一個紙牌遊戲,所以看起來自然的域對象似乎是'Card',但你的項目似乎並沒有面向對象的抽象抽象。 – scottb