以下是石头剪刀布游戏的Java代码:
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissorsGame {
enum Move {
ROCK,
PAPER,
SCISSORS
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 游戏主循环
while (true) {
System.out.println("欢迎来到石头、剪刀、布游戏!");
System.out.println("请输入你的选择(石头:r,剪刀:s,布:p):");
// 获取用户输入
String userMoveInput = scanner.next();
Move userMove = parseMove(userMoveInput);
// 如果用户输入无效,则重新输入
if (userMove == null) {
System.out.println("无效的选择,请重新输入。");
continue;
}
// 生成计算机的选择
Random rand = new Random();
int computerChoice = rand.nextInt(3);
Move computerMove = null;
switch (computerChoice) {
case 0:
computerMove = Move.ROCK;
break;
case 1:
computerMove = Move.PAPER;
break;
case 2:
computerMove = Move.SCISSORS;
break;
}
// 判断胜负
String result = determineWinner(userMove, computerMove);
// 输出结果
System.out.println("你的选择是:" + userMove);
System.out.println("计算机的选择是:" + computerMove);
System.out.println(result);
// 询问用户是否继续游戏
System.out.println("是否继续游戏?(是:y,否:n)");
String continueGame = scanner.next();
if (!"y".equalsIgnoreCase(continueGame)) {
break;
}
}
scanner.close();
}
// 解析用户输入为Move枚举
private static Move parseMove(String input) {
switch (input.toLowerCase()) {
case "r":
return Move.ROCK;
case "s":
return Move.SCISSORS;
case "p":
return Move.PAPER;
default:
return null;
}
}
// 判断胜负
private static String determineWinner(Move userMove, Move computerMove) {
if (userMove == computerMove) {
return "平局!";
} else if ((userMove == Move.ROCK && computerMove == Move.SCISSORS)
|| (userMove == Move.SCISSORS && computerMove == Move.PAPER)
|| (userMove == Move.PAPER && computerMove == Move.ROCK)) {
return "你赢了!";
} else {
return "你输了!";
}
}
}
在这个游戏中,我们首先定义了一个Move
枚举来表示石头、剪刀、布三种可能的动作。然后,我们使用一个while
循环来让用户反复进行游戏,直到他们选择不再继续为止。在每个回合中,我们获取用户的输入,并将其解析为Move
枚举值。然后,我们使用Random
类来随机生成计算机的选择。接着,我们调用determineWinner
方法来判断胜负,并输出结果。最后,我们询问用户是否继续游戏,并根据他们的回答来决定是否退出循环。