我正在尝试在Java上创建一个随机的MultiPlayer猜谜游戏,但我遇到了麻烦。下面的代码是我到目前为止的代码。我需要插入代码,提示用户输入正在播放的人数。一旦他们这样做并开始猜测,该程序应该从每个玩家猜测,直到一个猜测正确,在那种情况下,该玩家将被跳过,直到其他玩家猜测他们的数字。该程序为每个用户分配他们自己的唯一号码。 (例如:有三个玩家。玩家猜测1.太低了。玩家两个猜测4.这是正确的!玩家三猜猜4.太高了。玩家猜测2.这是正确的!玩家三猜猜3.这是正确的! ...等)
import java.util.Random;
import java.util.Scanner;
public class MultiRandGame {
public static void main(String[] args) {
Random rand = new Random();
int NumGuess = rand.nextInt(101);
int NumTries = 0;
Scanner input = new Scanner(System.in);
int guess;
boolean Game = false;
while (Game == false) {
System.out.println("Guess a number between 1 and a 100: ");
guess = input.nextInt();
NumTries++;
if (guess == NumGuess) {
Game = true;
}
else if (guess < NumGuess) {
System.out.println("Too low!");
}
else if (guess > NumGuess) {
System.out.println("Too high!");
}
}
System.out.println("You got it!");
System.out.println("The number was " + NumGuess);
System.out.println("It took you " + NumTries + " tries!");
}
}
答案 0 :(得分:0)
如果您阅读有关命名约定的内容,则可以更轻松地理解代码。 Game
至game
,NumGuess
至numGuess
,依此类推。这是read about it.
对于玩游戏的多人来说这么简单,你可以通过每次猜测得到一个for循环,保存正确猜测的玩家数量。你还需要有一个阵列,让玩家猜对了,猜测他们的数字是什么。
int guess = 0;
int playerCount = 2;
//boolean[] won = new boolean[playerCount];
int[] numbers = new int[playerCount];
for (int i = 0; i < playerCount; i++)
numbers[i] = rand.nextInt(101);
System.out.println("Guess a number between 0 and 100.");
while (game == false) {
for (int player = 0; player < playerCount; players++) {
System.out.print("Player #"+player+" guess: ");
guess = Integer.parseInt(input.nextLine());
//if (won[player] == false) {
if (guess == numbers[player]) {
//won[player] = true;
game = true;
System.out.println("Player #" + player + ": Correct!");
break;
} else if (guess < numGuess) {
System.out.println("Player #" + player + ": Too low!");
} else if (guess > numGuess) {
System.out.println("Player #" + player + ": Too high!");
}
//}
}
//for (int i = 0; i < playerCount; i++)
// if (won[i] == true)
// game = true;
}