【问题标题】:Simulate a program for a dice game in Java用Java模拟一个骰子游戏的程序
【发布时间】:2015-09-28 09:05:24
【问题描述】:

我正在尝试为骰子游戏制作一个程序,其中三个骰子在游戏中滚动。每个“骰子”的侧面都有从“1”到“6”的数字。如果数字都是 6,则用户获得 500 分。如果两个数字匹配,但不是三个,则用户获得 50 分。如果用户有两个 6(但不是三个 6),那么他/她得到 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 语句,我就会卡住。

【问题讨论】:

  • 您不想为每次使用创建一个新的 Random() 对象,只需每次重新使用 randomGenerator 即可。您的问题接下来需要的是决定如何评分的逻辑,这将涉及一些 if 语句来检查每种可能性。

标签: java if-statement random dice


【解决方案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
    }
}

【讨论】:

    【解决方案2】:
    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
    }
    //...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      • 2014-03-16
      • 2011-01-19
      • 2018-10-19
      • 1970-01-01
      • 2016-02-07
      • 2013-03-07
      相关资源
      最近更新 更多