服务器之家

服务器之家 > 正文

Java实现的剪刀石头布游戏示例

时间:2021-03-08 13:28     来源/作者:xxiaowen

本文实例讲述了Java实现的剪刀石头布游戏。分享给大家供大家参考,具体如下:

ChoiceAnswer.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class ChoiceAnswer {
    String texts[] = { "石头", "剪刀", "布" };
    int value; // 【1】石头\t【2】剪刀\t【3】布
    String getText() {
        return texts[value - 1];
    }
    ChoiceAnswer(int value) {
        this.value = value;
    }
    /**
     * 返回0表示平手,返回1表示赢,返回-1表示输
     */
    int compTo(ChoiceAnswer c) {
        if (value == c.value) {
            return 0;
        }
        if (value + 1 == c.value || (value == 3 && c.value == 1)) {
            return 1;
        }
        return -1;
    }
}

Game.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.Scanner;
public class Game {
    void p(String s) {
        System.out.println(s);
    }
    void showWelcome() {
        p("欢迎使用······");
        p("请选择:【1】石头\t【2】剪刀\t【3】布");
    }
    @SuppressWarnings("resource")
    ChoiceAnswer getUserChoice() {
        Scanner sc = new Scanner(System.in);
        int userChoice = Integer.parseInt(sc.nextLine());
        while (userChoice < 1 || userChoice > 3) {
            p("你输入的不正确!请重新输入!");
            userChoice = Integer.parseInt(sc.nextLine());
        }
        return new ChoiceAnswer(userChoice);
    }
    ChoiceAnswer getComputerChoice() {
        int computerChoice = (int) ((Math.random() * 3) + 1);
        return new ChoiceAnswer(computerChoice);
    }
    void showResult(ChoiceAnswer userChoice, ChoiceAnswer computerChoice) {
        int result = userChoice.compTo(computerChoice);
        if (result == 0) {
            System.out.println("平手,您和电脑均选择了:" + userChoice.getText());
        } else if (result == 1) {
            System.out.println("恭喜,您赢了!您选择了:" + userChoice.getText()
                    + ";   电脑选择了:" + computerChoice.getText());
        } else {
            System.out.println("对不起,您败了!您选择了:" + userChoice.getText()
                    + ";电脑选择了:" + computerChoice.getText());
        }
    }
    void start() {
        showWelcome();
        ChoiceAnswer userChoice = getUserChoice();
        ChoiceAnswer computerChoice = getComputerChoice();
        showResult(userChoice, computerChoice);
    }
    public static void main(String a[]) {
        System.out.println("服务器之家测试结果:");
        new Game().start();
    }
}

运行结果:

Java实现的剪刀石头布游戏示例

希望本文所述对大家java程序设计有所帮助。

原文链接:http://blog.csdn.net/wenzhilanyu2012/article/details/8733661

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部