import java.util.Random; import java.util.Scanner; // 创建一个代表玩家的类 class Player { private String name; private int score; public Player(String name) { this.name = name; this.score = 0; } public String getName() { return name; } public int getScore() { return score; } public void increaseScore() { score++; } } // 创建一个代表游戏的类 class Game { private Player player; private Player computer; private Random random; public Game(String playerName) { this.player = new Player(playerName); this.computer = new Player("电脑"); this.random = new Random(); }
public void play() { Scanner scanner = new Scanner(System.in); System.out.println("开始游戏!"); System.out.println("请输入你的选择(1-石头,2-剪刀,3-布):"); int playerChoice = scanner.nextInt(); int computerChoice = random.nextInt(3) + 1; System.out.println(player.getName() + "选择了" + getChoice(playerChoice)); System.out.println(computer.getName() + "选择了" + getChoice(computerChoice)); if (playerChoice == computerChoice) { System.out.println("平局!"); } else if (playerChoice == 1 && computerChoice == 2 || playerChoice == 2 && computerChoice == 3 || playerChoice == 3 && computerChoice == 1) { player.increaseScore(); System.out.println(player.getName() + "赢了!"); } else { computer.increaseScore(); System.out.println(computer.getName() + "赢了!"); } System.out.println("当前得分:"); System.out.println(player.getName() + ": " + player.getScore()); System.out.println(computer.getName() + ": " + computer.getScore()); }
private String getChoice(int choice) { String result = ""; switch (choice) { case 1: result = "石头"; break; case 2: result = "剪刀"; break; case 3: result = "布"; break; } return result; } }
public class shitoujiandaobu { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("欢迎来到石头剪刀布游戏!"); System.out.println("请输入你的名字:"); String playerName = scanner.nextLine(); Game game = new Game(playerName); while (true) { game.play(); System.out.println("是否继续游戏?(y/n)"); String choice = scanner.nextLine(); if (!choice.equalsIgnoreCase("y")) { System.out.println("游戏结束!"); break; } } } }