背景;我正在尝试为多玩家创建一个骰子游戏,你可以在游戏中选择你想要多少玩家,骰子和骰子。并且每个玩家都会轮流掷骰子,每次掷骰都会将得分附加到玩家类playerScore属性中。一旦玩家达到X点数,玩家就会被宣布为胜利者。
问题;以下代码是“Game”类的一部分。当我编译代码时,游戏完成了我期望的大部分内容;每个玩家每回合掷5个骰子,并将积分附加到所述玩家,但是一旦玩家达到100分,玩家就会被宣布为胜利者,但是对于另一个玩家,骰子会再次滚动,尽管while循环无效。我看到它的方式,问题是for循环,但我不知道如何解决这个问题,我尝试“破解”,但它只是从if语句中断开。
我的课程有3个班级;死,玩家,游戏。如果您需要更多信息或屏幕截图。我可以提供它们。
P.S。如果您认为此代码可以改进,请发表评论,我很高兴听到它。
答案 0 :(得分:4)
if语句弄乱了你的流程。为什么呢?
if (gameEnded || playerArray[i].PlayerScore >= maxPoints)
{
Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.",playerArray[i].PlayerName, playerArray[i].PlayerScore);
gameEnded = true;
break;
}
else if (!gameEnded )
{
playerArray[i].PlayerScore += rollAllDice();
Console.WriteLine("'{0}': {1}", playerArray[i].PlayerName, playerArray[i].PlayerScore);
}
在这里,您正在检查当前玩家是否已达到最终分数。如果是这样,你打破循环并设置gameEnded = true,同时打破while循环。但这会检查当前玩家的得分;它不会检查当前玩家是否达到了分数。这样,你只会发现玩家A是否在下一轮赢得比赛,而不是当前。
这样,只要玩家达到分数,游戏就会结束:
public void StartGame(int maxPoints)
{
playerArray[0].PlayerTurn = true; // Not sure why you're doing this, so I'm gonna leave this here
Player winner = null;
while (!gameEnded)
{
for (int i = 0; i < playerArray.Length; i++)
{
Player currentPlayer = playerArray[i];
currentPlayer.PlayerScore += rollAllDice();
Console.WriteLine("'{0}': {1}", currentPlayer.PlayerName, currentPlayer.PlayerScore);
if (currentPlayer.PlayerScore >= maxPoints)
{
winner = currentPlayer;
gameEnded = true;
break;
}
}
}
Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.", winner.PlayerName, winner.PlayerScore);
}
此代码中只有一个“问题”:一旦玩家达到分数,就会结束游戏。它不等待这一轮结束..
答案 1 :(得分:2)
你可以这样做:
public void StartGame(int maxPoints)
{
//playerArray[0].PlayerTurn = true; // Is it necessary?
while (true)
{
for (int i = 0; i < playerArray.Length; i++)
{
Player currentPlayer = playerArray[i];
currentPlayer.PlayerScore += rollAllDice();
Console.WriteLine("'{0}': {1}", currentPlayer.PlayerName, currentPlayer.PlayerScore);
if (currentPlayer.PlayerScore >= maxPoints)
{
Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.", currentPlayer.PlayerName, currentPlayer.PlayerScore);
return;
}
}
}
}
答案 2 :(得分:1)
我认为你的流量只是一点点,这可能会更好。对我来说真正的问题是你应该首先掷骰子,然后检查它是否是一个胜利。这将使你的WHILE正常工作。
public void StartGame(int maxPoints)
{
while (!gameEnded)
{
for (int i = 0; i < playerArray.Length; i++)
{
playerArray[i].PlayerScore += rollAllDice();
Console.WriteLine("'{0}': {1}", playerArray[i].PlayerName, playerArray[i].PlayerScore);
if(playerArray[i].PlayerScore >= maxPoints){
Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.",playerArray[i].PlayerName, playerArray[i].PlayerScore);
gameEnded = true;
break;
}
}
}
}