Java猜数小游戏:
public class RockPaperScissors {
public static void main(String[] args) {
// 游戏循环
while (true) {
int playerMove = getPlayerMove();
int computerMove = getComputerMove();
int result = determineWinner(playerMove, computerMove);
displayResult(result);
if (!playAgain()) {
break;
}
}
}
// 获取玩家的行动
public static int getPlayerMove() {
System.out.println("0. 石头\n1. 布\n2. 剪刀");
Scanner scanner = new Scanner(System.in);
int move = scanner.nextInt();
return move;
}
// 获取电脑的随机行动
public static int getComputerMove() {
Random random = new Random();
int move = random.nextInt(3);
return move;
}
// 确定胜者
public static int determineWinner(int playerMove, int computerMove) {
if ((playerMove == 0 && computerMove == 1) ||
(playerMove == 1 && computerMove == 2) ||
(playerMove == 2 && computerMove == 0)) {
return 1; // 玩家获胜
} else if (playerMove == computerMove) {
return 2; // 平局
} else {
return 0; // 电脑获胜
}
}
// 显示结果
public static void displayResult(int result) {
switch (result) {
case 0:
System.out.println("电脑获胜!");
break;
case 1:
System.out.println("玩家获胜!");
break;
case 2:
System.out.println("平局!");
break;
}
}
// 询问玩家是否要再玩一轮
public static boolean playAgain() {
System.out.println("你想再玩一轮吗?(y/n)");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
return input.equalsIgnoreCase("y");
}
}