温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-15 02:29:07 来源:脚本之家 阅读:151 作者:xxiaowen 栏目:编程语言

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

ChoiceAnswer.java

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

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算法相关内容感兴趣的读者可查看本站专题:《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI