Boxing game: 1 means rock, 2 means scissors, and 3 means cloth. Receive the punch input by the user and output it, and then the computer randomly generates a number to compare the winning and losing

The overall idea: first define the number of rounds, the user first guesses punches, then the computer randomly guesses punches, and finally judges the size of the two punches to determine the winner or loser

The simple application of the Random class, the usage of .nextInt (the int value ranges from 0 to the number defined by itself, excluding the number defined by itself)

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 "";
    }

output result:

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

Guess you like

Origin blog.csdn.net/weixin_71243923/article/details/125535979