gpt4 book ai didi

Java二十一点计分问题

转载 作者:行者123 更新时间:2023-12-02 11:31:22 25 4
gpt4 key购买 nike

我在二十一点游戏中的得分出现问题。它可以找到正确的分数,但是当用户抽一张新卡时,它会错误地添加分数。

例如:原手牌是: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;
}
}
}

最佳答案

每次调用方法时都会循环遍历手牌,因此在执行此操作之前应重置您的点数。否则点数增加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;

关于Java二十一点计分问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49282162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com