我的代码在尝试确定概率随机数时挂起



我正在制作一个模拟网球比赛的程序。对于那些了解规则的人来说,这很简单,但这是我的快速回顾:对于每场比赛,玩家必须得到 4 分,如果他没有领先两分,玩家继续比赛,直到其中一人得分比对手多 2 分或更多才能赢得比赛。赢得一盘相同的规则 - 需要比对手多 2 个。游戏在用户输入的X组数后结束。

非常简单,但我也实现了决定玩家 A 技能的变量。例如,如果玩家技能超过60,理论上他赢得比赛的机会更大。

所以这是我的代码。问题是,如果我将变量numberOfSets设置为 10,将变量playerSkill设置为大于 55 或小于 45,程序挂起,CPU 使用率上升(不多,我只看到小峰值到大约 15%),除了停止程序之外,我似乎无能为力。如果我将numberOfSets变量设置为像 1 或 2 这样的低值,程序似乎运行正常,即使像 1 或 99 这样的愚蠢值playerSkill也是如此。我对编程相当陌生,所以肯定有一些我省略的东西,这可能是显而易见的,或者我做了一些非常愚蠢的事情,不应该有。

int playerAGamesWon = 0;
int playerBGamesWon = 0;
int playerSkill = 50;
int numberOfSets = 10;
int numberOfGames = 6;
int numberOfPoints = 4;

void SimulateTennis()
{
txtData.Text = "Simulating game of tennis"+Environment.NewLine;
Random rand = new Random();
for (int i = 0; i < numberOfSets; i++)
{
while (true)
{
calculatePlayerPoints(rand);
if (playerAGamesWon >= numberOfGames || playerBGamesWon >= numberOfGames)
{
if (playerAGamesWon - playerBGamesWon >= 2)
{
playerASetWon++;
txtData.Text += "Player A won the Set with " + playerAGamesWon + " games to " + playerBGamesWon + Environment.NewLine + Environment.NewLine;
playerAGamesWon = 0;
playerBGamesWon = 0;
break;
}
else if (playerBGamesWon - playerAGamesWon >= 2)
{
playerBSetWon++;
txtData.Text += "Player B won the Set with "+ playerBGamesWon + " games to " + playerAGamesWon + Environment.NewLine + Environment.NewLine;
playerAGamesWon = 0;
playerBGamesWon = 0;
break;
}
else
{
continue;
}
}
}
}
}
void calculatePlayerPoints(Random rand)
{
int apoints = 0;
int bpoints = 0;
while (true)
{
int prob = rand.Next(100);
if (prob <= playerSkill)
{
apoints++;
}
else
{
bpoints++;
}
if (apoints >= numberOfPoints)
{
if (apoints - bpoints >= 2)
{
playerAGamesWon++;
updateScoreText(apoints, bpoints);
break;
}
}
//else if statement of (bpoints >= numberOfPoints) was unreachable when if statement of (apoints >= numberOfPoints) was true
//I should use if statement
//else if (bpoints >= numberOfPoints)
if (bpoints >= numberOfPoints)
{
if (bpoints - apoints >= 2)
{
playerBGamesWon++;
updateScoreText(apoints, bpoints);
break;
}
}
}
}

calculatePlayerPoints方法中输入无限循环。如果比较apoints和点数的结果是true,但条件if (apoints - bpoints> = 2)false,则不会发生bpointsnumberOfPoints的比较。您必须删除else if (bpoints> = numberOfPoints)中的else

最新更新