我正在构建一个Java游戏,我已经完成了最后一个部分。还有其他一些问题需要解决,这些问题很容易解决。虽然有一个问题我无法弄清楚,也就是说每次运行游戏后我都无法获得新的随机数字。
例如,如果没有人猜到计算机从数字(1-20)随机发出的数字,那么游戏就会重复。在这期间你正在玩2台计算机,它们的数字也是随机组成的(再次是1-20个值)。
以下是我制作的Player类的一些代码
import java.util.Scanner;
import java.util.Random;
public class Player {
private double currentGuess = 0;
private String firstName;
private boolean isCorrect;
Scanner myScanner = new Scanner(System.in);
public Player() {
}
public double autoGuess() {
Random randomNumber = new Random();
double number = randomNumber.nextInt(20) + 1;
return number;
}
这是我的GuessGame类,它是动作实际发生的地方。我无法弄清楚为什么当我调用autoGuess方法(来自播放器类)时,我无法在每次游戏后显示新的随机数,导致没有人猜测正确的数字。同样可以随机生成要猜测的数字(WINNING_NUMBER),在每次新游戏后它仍然保持不变。以下是我的GuessGame类的一些代码。
import java.util.Random;
public class GuessGame {
Player player1 = new Player();
Player player2 = new Player();
Player player3 = new Player();
double player2Guess = player2.autoGuess();
double player3Guess = player3.autoGuess();
int numberOfTries = 0;
public double generateWinningNumber() {
Random randomGenerate = new Random();
double randomNumber = randomGenerate.nextInt(20) + 1;
return randomNumber;
}
private final double WINNING_NUMBER = generateWinningNumber();
public void startGame() {
System.out.println("VM: Welcome we are going to play a number guessing game. I'm (the JVM)\n"
+ "going to randomly pick a number between 0 and 20. You and the 2 other\n"
+ "computer-generated players are going to try to guess that number. The game\n"
+ "will end when at least one of the players correctly guesses the number.\n");
System.out.println(WINNING_NUMBER);
System.out.print("What is your name? ");
String player1Name = player1.readName();
while (player1.isCorrect() == false)
{
System.out.print(player1Name + ", enter your guess: ");
player1.readGuess();
player2.autoGuess();
player3.autoGuess();
numberOfTries++;
if (player1.getCurrentGuess() == WINNING_NUMBER || player2Guess == WINNING_NUMBER || player3Guess == WINNING_NUMBER)
{
player1.setCorrect(true);
displayGuesses();
determineWinner();
}
else
{
displayGuesses();
displayHints();
System.out.println("No one guessed the number.\nPlayers will need to guess again.\n");
System.out.println("The winning number was: " + WINNING_NUMBER);
generateWinningNumber();
}
}
}
public void displayGuesses() {
System.out.print("Player 2's guess is: " + player2Guess + "\n");
System.out.print("Player 3's guess is: " + player3Guess + "\n\n");
}
还有更多内容,显然还有更多要解决的问题,但我正试图将此问题排除在外。我有我的驾驶员课程开始这个游戏,也知道我需要将我的数字四舍五入到Ints所以没有小数位。此外,所有提示方法都是指如果语句告诉您是否热,温或冷。这完全没问题。在我的while语句中每次新的不成功游戏之后,只需要一些帮助来弄清楚如何获得一个新的随机数。
答案 0 :(得分:0)
您的generateWinningNumber()
方法返回一个double,它实际上并不会更改任何值。另外,因为WINNING_NUMBER
是一个常量,即使你确实想要改变它,你也无法做到。你绝对不应该使WINNING_NUMBER
成为最终版本,并修改generateWinningNumber()
以便它自己修改全局变量,或者保持原样并使用其返回值分配给你的非常量{{1}全球。