我正在努力制造Yahtzee ......但是我有问题..我可以编写掷骰子的方法吗?如果所有骰子必须相等并且称之为Yahtzee,我该如何编写方法。
public class YahtzeeDice {
private final int DiceCount = 5; // There are 5 dice in the game
private final Die die; // But we only need 1
private int rolledValues[]; // We roll it 5 times and record the values
/**
* This is the normal constructor for YahtzeeDice. It creates a new object
* and initializes the rolledValues by rolling the dice, since dice are always
* showing some kind of value.
* @param generator variable of type Random
*/
public YahtzeeDice(Random generator) {
this.die = new Die(generator);
this.rolledValues = new int[this.DiceCount];
this.RollDice();
}
/**
* This constructor exists for unit testing purposes. You can create a new
* object with explicit values of each of the 5 dice. Useful for testing the
* IsAYahtzee() method.
* @param generator variable of type Random
* @param initialValues an array of initial dice values
*/
public YahtzeeDice(Random generator, int initialValues[] ) {
this(generator); // call the other rconstructor
for (int i = 0; i < this.DiceCount; i++) {
this.rolledValues[i] = initialValues[i];
}
}
/**
* Rolls all 5 Yahtzee dice. It should be implemented by rolling the 1 die
* 5 times are recording the value of the roll 5 times.
*/
public void RollDice() {
//TODO: Implement this method here
for(int i = 0; i < this.DiceCount; i++) {
System.out.print((this.die.Roll() +1));
}
}
/**
* Checks for a Yahtzee condition - all 5 dice are the same value.
* @return true when Yahtzee, false otherwise
*/
public boolean IsAYahtzee() {
// TODO: Implement this method here
for (int i = 0; i < this.DiceCount; i++) {
}
return true;
}
/**
* Prints out the current values of the dice rolls for example if you
* rolled a 1,5,3,2,2 it would return the String [1|5|3|2|2]
* @return String representation of the dice values.
*/
@Override
public String toString() {
String result = "[";
for (int i = 0; i < this.DiceCount-1; i++) {
result += this.rolledValues[i] + "|";
}
result += this.rolledValues[this.DiceCount-1] + "]";
return result;
}
}
答案 0 :(得分:0)
使用Random(http://docs.oracle.com/javase/7/docs/api/java/util/Random.html)类生成随机数。得到的骰子值的比较不应该太难。
答案 1 :(得分:0)
伪代码:
微优化,不要访问for循环中数组中的第一个值。
答案 2 :(得分:0)
它有点冗长,但要确定一个Yahtzee,你不能这样做
if ( this.rolledValues[0] == this.rolledValues[1] && this.rolledValues[1] == this.rolledValues[2] && this.rolledValues[2] == this.rolledValues[3] && this.rolledValues[3] == this.rolledValues[4] ) {
假设你有五个骰子,当然。
答案 3 :(得分:0)
//添加骰子rollsholder(例如下面的rollsValues [])
private int [] diceRolls = new int [5];
public void RollDice(){
for(int i = 0; i < this.DiceCount; i++) {
diceRolls[i] = (this.die.Roll() +1)
System.out.print(diceRolls[i]);
}
}
public boolean IsAYahtzee(){
for (int i = 0; i < this.DiceCount; i++) {
if(i < (this.DiceCount-1) && diceRolls[i] != diceRolls[i+1] ){
return false;
}
}
return true;
}