c# - 无法让简单的 c# 掷骰子游戏正常工作
问题描述
在掷骰子中,掷出两个 6 面骰子。如果结果是 7 或 11。玩家或自动获胜。如果掷出 2、3 或 12,则玩家自动输掉。但是,如果滚动另一个数字,则该数字将成为“点”。玩家再次掷骰,直到再次掷出点数或掷出 7。如果重新掷出点数,则玩家获胜。如果掷出 7,这一次是输。
我的代码有两个问题
- 当玩家需要再次滚动并且没有获胜时,我的分数计数器会在分数上加一
- 点数和总数总是相等的,所以它只是继续要求再次滚动。
状态用于表示这是第一次滚动还是后续滚动中的一个。我省略了一些仅用于显示骰子图像的代码。
int die1;
int die2;
int total;
int state = 1;
int point =0;
int point2;
int score = 0;
Random rand = new Random();
die1 = rand.Next(1, 7);
die2 = rand.Next(1, 7);
total = (die1 + die2);
txtDie1.Text = die1.ToString();
txtDie2.Text = die2.ToString();
txtTotal.Text = total.ToString();
if (state == 1)
{
if (total == 7 || total == 11)
{
txtStatus.Text = "You are a winner!";
score++;
txtScore.Text = Convert.ToString(score);
state = 1;
}
if (total == 2 || total == 3 || total == 12)
{
txtStatus.Text = "You lose. Play again!";
score --;
txtScore.Text = Convert.ToString(score);
state = 1;
}
if (total == 4 || total == 5 || total == 6 || total == 8 || total == 9 || total == 10)
{
txtStatus.Text = "Roll again!";
point = int.Parse(txtTotal.Text);
txtPoint.Text = point.ToString();
state = 2;
}
}
if (state == 2)
{
if (total == point)
{
txtStatus.Text = "You are a winner!";
score ++;
txtScore.Text = Convert.ToString(score);
state = 1;
}
if (total == 7)
{
txtStatus.Text = "You lose. Play again!";
score --;
txtScore.Text = Convert.ToString(score);
state = 1;
}
if (total != 7 || total != point)
{
txtStatus.Text = "Roll again!";
state = 2;
}
}
解决方案
首先,将您的代码更改为阅读
else if (state == 2)
如所写,您的代码首先通过该if (state==1)
部分,然后立即进入该if (state==2)
部分。
此外,您还遗漏了代码的循环和流控制部分。您可能会在每次传递时重新定义 state=1 - 确保当state==2
.
推荐阅读
- python - ModuleNotFoundError:没有名为“googleapiclient”的模块
- python - 如何在cx_Oracle和python3中实现DBMS_METADATA.GET_DDL并获取表的ddl?
- nginx - 这个重定向非 www 域到 nginx 中的 www 域真的有效吗?
- java - 如何在 java 中使用 .pem 文件证书发布数据
- object - 泡菜适合对象
- javascript - Cheerio,如何将其提取到 json 中?
- spring - Spring JPA 存储库找到所有不存在的
- delphi - Datasnap 会话已过期
- ios - 如何在 ios ionic build 中解决“'FIRInstanceID' 没有可见的@interface 声明选择器'token'”
- html - 我的本地 Html Ref 由于某种原因无法正常工作