gpt4 book ai didi

java - 重新启动程序/游戏

转载 作者:行者123 更新时间:2023-12-01 10:15:32 27 4
gpt4 key购买 nike

我正在开发这个随机数猜测游戏。在游戏结束时,我希望用户可以选择再次玩(或让其他人玩)。我发现了几个类似的线程和问题,但没有一个能够帮助我解决这个小问题。我很确定我可以以某种方式使用我的 while 循环,但不知 Prop 体如何..

对 Java 非常陌生,所以请了解这是否是一个简单的修复方法..

   import java.util.Scanner;
import java.util.Random;

public class GuessingGame {
public static void main(String[] args){

Random rand = new Random();
int correctNumber = rand.nextInt(100);
int numberOfGuesses = 0;
Scanner input = new Scanner(System.in);
int guess;
boolean win = false;
String username = "";

System.out.println("Hello, it is time to play a guessing game.");
System.out.println("We will generate a random number between 0-99, and you will have to try to guess the number in as few attempts as possible.");
System.out.println("You can also choose to give up by pressing \"q\" on your keyboard. \n\nTo get started, press \"s\" on your keyboard.");
input.nextLine();

System.out.println("\nEnter a username: ");
username = input.nextLine();
System.out.println("\nNew username registered: " + username);


while(win == false){

System.out.println("\nGuess a number between 0-99: ");
guess = input.nextInt();
numberOfGuesses++;

if (guess == correctNumber){
win = true;
}
else if(guess < correctNumber){
System.out.println("Too low. Try again!");
}else if(guess > correctNumber){
System.out.println("Too high. Try again!");
}
}

System.out.println("\nYou guessed the correct number which was " + correctNumber + ". Congrats!");
System.out.println("\n" + username + " your number of guesses were: " + numberOfGuesses);

win = false;
}

// System.out.println("\nTo play again (let someone else try) press \"s\", to quit press \"q\".");
// input.nextLine();
// if (input.next().equalsIgnoreCase("q")){
// System.out.println("\nThanks for playing!");
// }
// }else if(input.nextLine().equalsIgnoreCase("s")){

}

//}

最佳答案

您所描述的称为“游戏循环”。基本上,您会将整个游戏包装在一个循环中,该循环将根据某些条件重复。在这种情况下,条件是用户是否想再次玩。

在 Java-ish 伪代码中,结构如下所示:

boolean keepPlaying = true;
while (keepPlaying) {

boolean hasWon = false;
while (!hasWon) {
// play a round in the game
}

keepPlaying = promptUser("Would you like to play again?");
}

该伪代码的“伪”部分当然是最后一行。只需询问用户是否想再玩一次,并将响应转换为游戏循环使用的逻辑值。

所以游戏本身就是一个“回合”循环,不断重复直到发生胜利或失败。 程序是一个“游戏”循环,不断重复直到用户退出。

关于java - 重新启动程序/游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35921669/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com