石头剪刀布笔记

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;
            }
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值