我正在爲Java構建遊戲,並且已經歸結爲最後部分之一。還有其他需要解決的問題,這些問題很容易解決。雖然我無法弄清楚一個問題,那就是每次運行遊戲後我都無法得到新的隨機數字。在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語句每次新的不成功的遊戲之後,弄清楚如何獲得一個新的隨機數。
...並在循環外部創建Random()對象。 – 2014-10-28 19:40:35
要添加到Mike說的話,您的autoGuess()也會返回一個double值,並且不會更改任何值。而不是以double形式返回變量號,函數應該將currentGuess設置爲變量號並返回void。 – user1521640 2014-10-28 19:43:15
@LeeDanielCrocker不是已經有了嗎?隨機對象是在不同的方法中創建的,所以它們不會被重用。 – 2014-10-28 19:43:39