首页 > 解决方案 > 从 OOP 开始 - 骰子游戏问题

问题描述

您好我正在尝试掌握面向对象的编程(OOP)。我正在制作一个骰子游戏,但我有点卡住了 -

package ch6CLASSES;
import java.util.Scanner;
public class getDie {
    public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.println("A simple dice game.");
    int COUNT =10;

    for (int i=0;i<COUNT;i++) {
    Die userDie = new Die();
    System.out.println("user: "+userDie.getValue());

    Die computerDie = new Die();
    System.out.println("computer: "+computerDie.getValue());

    System.out.println();
    }
}
}

所以我有另一堂课,我计算了所有内容 - 但现在我的问题是......在我拥有的 for 循环中,我想计算计算机或用户在每一轮后获胜的次数,有什么帮助吗?

标签: java

解决方案


首先,您需要有某种方法来确定计算机或用户是否获胜。(由于您正在练习 OOP,因此一种方法可能是最合适的)查看您的代码,看起来每个代码Die都只有一个值,因此您必须不断重新创建对象。我建议使用一个roll()返回 1 到 6 之间随机数的方法。这样您就不必在循环的每次迭代中创建新对象。

其次,您需要一种方法来确定用户是否获胜。一种简单的方法是让该方法接受一个int参数,然后将其与当前Die对象的值进行比较。这里有一些代码可以让你朝着正确的方向开始:

public int roll() {
   //generate random number
}

public boolean wonRoll(int value) {
     if(this.getValue() > value) {
        return true;
     } else {
        return false;
     }
}

然后在你的循环中:

int computerWins = 0;
int userWins = 0;
Die userDie = new Die();
Die computerDie = new Die();
for (int i=0;i<COUNT;i++) {

    System.out.println("user: "+userDie.getValue());  
    System.out.println("computer: "+computerDie.getValue());
    if(userDie.wonRoll(computerDie.getValue()) {
        userWins++;
    } else {
        computerWins++;
    }

}
System.out.println("Computer won " + computerWins + " many times");
System.out.println("User won " + userWins + " many times");

推荐阅读