java - 我在JAVA中的猪骰子游戏不会保存每个玩家的分数,即使达到分数游戏也不会停止
问题描述
我的计算机科学课上的猪骰子游戏不会在每回合后保存每个单独的分数,即使玩家达到最高分数,我的游戏也不会停止(我知道 boo 倾斜是原因,但是,我不知道还有什么用)。同样,当玩家拒绝再次滚动时,分数会归零。如果有人帮我解决这个问题,那就太好了!!谢谢你。
import java.util.*;
import java.util.Random;
public class PigDiceGamebyJian {
public static Scanner sc = new Scanner(System.in);
public static Random gen = new Random();
public static void main(String[] args) {
//char repeat;
System.out.println(" Welcome to the Pig Dice Game ");
System.out.println("This game requires two players");
System.out.println("How to play: each player will take turn rolling the dice (adding up the turns) until the sum is 30");
System.out.println("First one to get to 30 wins, though if on a turn, if you roll a 1, ");
System.out.println("you will give the dice to the other player, and you will not add anything to your score because 1 = 0");
System.out.println("Enough with the boring rules.");
String p1 = getName();
String p2 = getName();
System.out.println("Hello " + p1 + " and " + p2 + ".");
System.out.println("Please enter a score that you would like to play up to");
final int fin = sc.nextInt();
System.out.println(p1 + " will be going first.");
int p1score = roll(p1, 0, fin);
int p2score = roll(p2, 0, fin);
while (p1score < fin && p2score < fin ) {
p1score += roll(p1, 0, fin);
p2score += roll(p2, 0, fin);
}
}
private static int roll(String player, int score, int fin) {
boolean go = true;
int counter = 0;
while(go) {
int dice = gen.nextInt(6) + 1;
if (dice == 1) {
System.out.println(player + " You rolled 1, your turn is over.");
System.out.println(player + " your total is " + counter);
return 0;
}
System.out.println(player + " you rolled a " + dice);
counter = counter + dice;
System.out.println(player + " Your turn score is " + counter + " Do you want to roll again? (y)es (n)o");
String ans = sc.next();
if (ans.equals("n")) {
go = false;
System.out.println(player + " your score is " + score);
return score;
}
if (score > fin) {
go = false;
System.out.println(player + " you've won the PIG DICE GAME!!");
}
}
return score;
}
private static String getName() {
System.out.println("Enter the name for a player.");
String player = sc.next();
return player;
}
}
解决方案
您的程序存在逻辑缺陷。您使用 score = 0 作为参数调用 roll 函数。
int p1score = roll(p1, 0, fin);
int p2score = roll(p2, 0, fin);
while (p1score < fin && p2score < fin ) {
p1score += roll(p1, 0, fin);
p2score += roll(p2, 0, fin);
}
在您的滚动方法中,您要么返回 0,要么返回每次都为 0 的分数。因此,根据 roll 函数返回的内容确定的 p1score 和 p2score 都将永远为 0。
这就是为什么您的游戏不会停止的原因,因为它卡在了 while 循环中。
您需要更改滚动函数以返回分数 + 您滚动的值。
推荐阅读
- c# - .cs 页面未显示正确的字符串
- ios - 如何在 UITabBarController 中使用自定义初始化程序注入依赖项?
- shell - Rsync:如何排除文件夹中除一个特定文件之外的所有文件?
- python - 表单清理方法 vs 模型清理方法 vs 模型字段验证器
- c++ - 如何检查 std::vector 的调整大小是否获得了适当的内存
- python - 有没有办法将 RASA_NLU 配置从 Visual c++ 14.0 更改为 MinGW
- laravel - Laravel - belongsTo 关系的条件
- javascript - 在 Windows 上滚动在最近的选择器上添加类
- django - 'using' 是此函数的无效关键字参数 (serializer.save(using='tableNew'))
- asp.net - ASP.NET Core Web API 如何临时保存已验证的电话号码