从其他班级获得价值

时间:2015-04-18 11:16:33

标签: java

我正在写一个涉及掷骰子的游戏。

在引擎类中,有一个名为calculateResult的方法。在这种方法中,我需要获得每个玩家的骰子值并比较它们以查看哪个玩家的骰子总和更大。

我尝试使用int total=dicePair.getDice1()+dicePair.getDice2(),它看起来根本不起作用。

这是引擎类,其中包含滚动玩家骰子的方法。

public class GameEngineImpl implements GameEngine {
    public static int NUM_FACES = 6;

    Collection<Player> players = new ArrayList<Player>();
    GameEngineCallback gameEngineCallback;
    DicePair dicePair;

    public void rollPlayer(Player player, int initialDelay, int finalDelay, int delayIncrement) {
        for(int i = initialDelay; i <= finalDelay; i += delayIncrement) {
            int dice1 = (int) (Math.random() * NUM_FACES + 1);
            int dice2 = (int) (Math.random() * NUM_FACES + 1);
            DicePairImpl dicePairImpl = new DicePairImpl(dice1, dice2);
            gameEngineCallback.intermediateResult(player, dicePairImpl, this);
            try {
                Thread.sleep(initialDelay);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        int dice1 = (int) (Math.random() * NUM_FACES + 1);
        int dice2 = (int) (Math.random() * NUM_FACES + 1);
        DicePairImpl dicePairImpl = new DicePairImpl(dice1, dice2);
        gameEngineCallback.result(player, dicePairImpl, this);
        player.setRollResult(dicePairImpl);
    }
}

这是回调类,它打印骰子值和总数。

public class GameEngineCallbackImpl implements GameEngineCallback {
    public void intermediateResult(Player player, DicePair dicePair,
        GameEngine engine) {
        int dice1 = dicePair.getDice1();
        int dice2 = dicePair.getDice2();
        int total = dice1 + dice2;
        System.out.println("FINE: Player:" + player + ", intermediate result=Dice 1:" + dice1 + ",Dice2:" + dice2 + ".. Total:" + total);
    }
}

1 个答案:

答案 0 :(得分:0)

你正在掷骰子,但你永远不会保存骰子。所以你应该做的事情如下:

player.setRollResult(dicePairImpl);//after this line
dicePair = dicePairImpl;//save the reference

然后您可以在dicePair方法中使用calculate