[英]Stuck in loop making war game
我正在制作戰爭卡片游戲。 我只能上一堂課。 當我運行此程序時,它會正確分配card1
和card2
值,運行循環並可以正常打印,但它只分配一次RNG值,我需要它打破循環並每次都重新分配值,直到有人獲勝。
我嘗試破壞它,但這僅結束了整個代碼。 我不是在尋找答案,只是在尋找一些輸入和幫助。 除非是平局,否則它應該發揮作用,從失敗者的點數中減去贏家的點數。 然后它運行War並扣除3,然后加3(用於所使用的卡數)。 一擊至零,游戲停止並顯示獲勝者。
import java.util.Random;
public class warGame {
public static void main(String[] args) {
String p1 = "Player 1";
String p2 = "Player 2";
int s = 10;
int p1Score = s;
int p2Score = s;
Random card = new Random();
int card1 = card.nextInt(14);
int card2 = card.nextInt(14);
int t = 1;
int war1 = card.nextInt(14);
int war2 = card.nextInt(14);
System.out.println("Let's play War!");
//Do while loop that runs the entirety of the program inside.
do {
System.out.println("Turn " + t++ + " -- Player 1's card: " + card1 + " Player 2's card: " + card2);
//determines cards, calculates values and runs proper loop
if (card1 > card2) {
System.out.println("Player 1 wins!");
p1Score += 1;
p2Score -= 1;
System.out.println("Scores -- " + "Player 1: " + p1Score + " Player 2: " + p2Score);
} else if (card1 == card2) {
System.out.println("Time for war!");
System.out.println("Player 1's war card is: " + war1 + " Player 2's war card is: " + war2);
if (war1 > war2) {
System.out.println("Player 1 wins the war!");
p1Score += 3;
p2Score -= 3;
} else {
System.out.println("Player 2 wins the war!");
p1Score -= 3;
p2Score += 3;
}
} else {
System.out.println("Player 2 wins!");
p1Score -= 1;
p2Score += 1;
System.out.println("Scores -- " + "Player 1: " + p1Score + " Player 2: " + p2Score);
}
} while (p1Score > 0 && p2Score > 0);
//The following will print out the winner and end the game.
if (p1Score == 0) {
System.out.println("Player 2 wins the game!");
} else {
System.out.println("Player 1 wins the game!");
}
}
}
答案很簡單:您可以在do-while循環外分配卡的值。 這意味着除非您在循環中進行更改,否則這些值將永遠不會更改。
如果希望循環具有不同的結果,則需要為其提供不同的值。
當您這樣做時:
int card1 = card.nextInt(14);
int card2 = card.nextInt(14);
int war1 = card.nextInt(14);
int war2 = card.nextInt(14);
您正在為這四個變量分配隨機值。 但是,這些值永遠不會改變。
我將這些行替換為:
int card1;
int card2;
int war1;
int war2;
接着:
do {
// update card values
card1 = card.nextInt(14);
card2 = card.nextInt(14);
war1 = card.nextInt(14);
war2 = card.nextInt(14);
System.out.println("Turn " + t++ + " -- Player 1's card: " + card1 + " Player 2's card: " + card2);
這次,變量值在每次迭代中都會有所不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.