猜拳游戏:1表示石头,2表示剪刀,3表示布 接收用户输入的拳 并输出 ,然后电脑随机产生一个数 对比输赢

整体思路:首先定义各种局数,用户先猜拳,然后电脑随机猜拳,最后判断俩者猜拳的大小从而决出输赢

Random类的简单应用,.nextInt的用法(int值在0到自己所定义的数字范围,不包含自己所定义的数字)

public static void main(String[] args) {
        int winyonghu = 0;
        int windiannao = 0;
        int pingju = 0;
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("欢迎来到游戏中心");
            System.out.println("请用户猜拳,1.石头 2.剪刀 3.布");
            int yonghu = scanner.nextInt();
            int diannao = new Random().nextInt(3) + 1;
            System.out.println("您的出拳是"+choose(yonghu) );
            System.out.println("电脑出拳是"+choose(diannao) );
            if (yonghu - diannao == 0) {
                pingju++;
            } else if (yonghu - diannao == -1) {
                winyonghu++;
            } else if (yonghu - diannao == -2) {
                windiannao++;
            } else if (yonghu - diannao == 1) {
                windiannao++;
            } else {
                winyonghu++;
            }
            System.out.println("您赢了" + winyonghu + "次");
            System.out.println("电脑赢了" + windiannao + "次");
            System.out.println("平局了" + pingju + "次");
        }
    }
    public static String choose(int b) {
        if (b == 1) {
            return "石头";
        }
        if (b == 2) {
            return "剪刀";
        }
        if (b == 3) {
            return "布";
        }
        return "";
    }

输出结果:

欢迎来到游戏中心
请用户猜拳,1.石头 2.剪刀 3.布
1
您的出拳是石头
电脑出拳是布
您赢了0次
电脑赢了1次
平局了0次
欢迎来到游戏中心
请用户猜拳,1.石头 2.剪刀 3.布

猜你喜欢

转载自blog.csdn.net/weixin_71243923/article/details/125535979
今日推荐