用Java模拟骰子游戏的程序

时间:2015-07-09 19:42:11

标签: java if-statement random dice

我正在尝试制作一个骰子游戏的程序,其中三个骰子在游戏中滚动。每个“骰子”的侧面都有“1”到“6”的数字。如果数字都是6,则用户获得500分。如果两个数字匹配,但不是三个,则用户获得50分。如果用户有两个6s(但不是三个6s),那么他/她得到100分。如果没有数字匹配,则用户丢失一个点。

到目前为止,我有这个:

import java.util.Random;
public class diceGame {
    public static void main (String args[])
    {
        Random randomGenerator = new Random ();
        int a;//first face of die
        a = randomGenerator.nextInt((5)+1);
        System.out.println(a);
        int b;//second face of die
        b = randomGenerator.nextInt((5)+1);
        Random randomGenerator2 = new Random ();
        System.out.println(b);
        int c;//third face of die
        c = randomGenerator.nextInt((5)+1);
        Random randomGenerator3 = new Random ();
        System.out.println(c);
        ...
    }
    ...
}

但是当我进入嵌套的if语句时,我就会卡住。

2 个答案:

答案 0 :(得分:1)

if (a == 6 && b == 6 && c == 6){
//Add to score
}
else if ((a == b == 6 && b != c) || (b == c == 6 && c !=a)){
//Add to score
}
else if ((a == b && b != c) || (b == c && c !=a)){
//Add to score
}
//...

答案 1 :(得分:1)

如果没有完全解决您的问题,这里有一个可能的设计,它封装了您的滚动逻辑。

import java.util.Random;

public class DiceGame 
{
    private class DiceRoll {
        private static Random rng = new Random();
        private int a, b, c; // rolls
        public DiceRoll() {
            this.a = rng.nextInt(6);
            this.b = rng.nextInt(6);
            this.c = rng.nextInt(6);
        }
        public int getScore() {
            if (a == 6 && b == 6 && c == 6) 
                return 500;
            ...
            // other cases 
        }
        public String toString() {
            return String.format("Rolled a %d, %d, and %d", a, b, c);
        }
    }

    public static void main (String args[])
    {
        DiceRoll d; 
        while (true) {
            d = new DiceRoll();
            d.getScore();        // gives you how much to change the player score
        }
        // finish client
    }
}