美文网首页Java学习笔记
面向对象分析与设计示例:骰子游戏

面向对象分析与设计示例:骰子游戏

作者: 033a1d1f0c58 | 来源:发表于2016-09-19 16:20 被阅读87次

    代码:

    class Die {
        int faceValue;
    
        public Die() {
            faceValue = 0;
        }
    
        public int getFaceValue() {
            return faceValue;
        }
    
        public void roll() {
            faceValue = (int) (1 + Math.random() * 7);
        }
    }
    
    class MyDiceGame {
        Die die1, die2;
    
        public MyDiceGame() {
            die1 = new Die();
            die2 = new Die();
        }
    
        public Boolean play() {
            die1.roll();
            int fv1 = die1.getFaceValue();
            die2.roll();
            int fv2 = die2.getFaceValue();
            return fv1 + fv2 == 7;
        }
    
        public int getFaceValue1() {
            return die1.getFaceValue();
        }
    
        public int getFaceValue2() {
            return die2.getFaceValue();
        }
    }
    
    public class Player {
    
        public static void main(String[] args) {
            MyDiceGame game = new MyDiceGame();
            if (game.play()) {
                System.out.println("Win " + game.getFaceValue1() + " " + game.getFaceValue2());
            } else {
                System.out.println("Lose " + game.getFaceValue1() + " " + game.getFaceValue2());
            }
        }
    
    }
    

    相关文章

      网友评论

        本文标题:面向对象分析与设计示例:骰子游戏

        本文链接:https://www.haomeiwen.com/subject/ayrnettx.html