我在我的二十一点游戏中得分有问题。它可以找到正确的分数,但当用户抽出一张新卡片时,它会错误地添加分数。
例如:原始手势是:4和5(因此分数为9),用户画出的是10,而不是19,而是19+9或28。
下面是我的代码:评分方法:
public int getHandValue() {
boolean ace = false;
for (int i = 0; i < this.hand.size(); i++) {
if (this.hand.get(i).getRank().value > 10) {
points += 10;
} else if (this.hand.get(i).getRank().value == 1) {
ace = true;
} else {
points += this.hand.get(i).getRank().value;
}
if (ace == true && points + 11 <= 21) {
points += 11;
}
}
return points;
}播放方法:
public void play(Deck deck) {
boolean isDone = false;
if (this.getHandValue() > 21){
System.out.println("You have busted!");
isDone = true;
this.lose();
}
takeCard(deck.drawCard());
takeCard(deck.drawCard());
System.out.println("Here are your cards and your score:");
System.out.println(this.hand.toString());
System.out.println("Score: " + getHandValue());
ListItemInput hitOrPass = new ListItemInput();
hitOrPass.add("h", "hit");
hitOrPass.add("p", "pass");
while (!isDone){
System.out.println("Hit or pass?");
hitOrPass.run();
if (hitOrPass.getKey().equalsIgnoreCase("h")) {
String result = "";
this.takeCard(deck.drawCard());
result += "You hand is now " + this.hand.toString() + "\n";
result += "Your score is now " + this.getHandValue();
System.out.println(result);
} else {
System.out.println("You have chosen to pass.");
isDone = true;
}
}
}发布于 2018-03-14 23:51:11
每次调用你的方法时,你都会循环遍历手部,所以在这样做之前,你的点应该被重置。否则,点数将增加2倍+手中额外的卡片。在循环手部之前重置该值
public int getHandValue() {
boolean ace = false;
points = 0; //<--- reset the point total
for (int i = 0; i < this.hand.size(); i++) {
if (this.hand.get(i).getRank().value > 10) {
points += 10;
} else if (this.hand.get(i).getRank().value == 1) {
ace = true;
} else {
points += this.hand.get(i).getRank().value;
}
if (ace == true && points + 11 <= 21) {
points += 11;
}
}
return points;发布于 2018-03-14 23:53:15
我假设points是在这个方法之外声明的。
因为你要返回点,所以最好不要使用类范围的变量。你最终会得到像这样意想不到的结果。相反,在方法范围内使用变量,如下所示。
public int getHandValue() {
boolean ace = false;
int value = 0;
for (int i = 0; i < this.hand.size(); i++) {
if (this.hand.get(i).getRank().value > 10) {
value += 10;
} else if (this.hand.get(i).getRank().value == 1) {
ace = true;
} else {
value += this.hand.get(i).getRank().value;
}
if (ace == true && points + 11 <= 21) {
value += 11;
}
}
return value;
}https://stackoverflow.com/questions/49282162
复制相似问题