【问题标题】:Can't get simple c# craps game to work correctly无法让简单的 c# 掷骰子游戏正常工作
【发布时间】:2018-10-10 19:58:09
【问题描述】:

掷骰子时,掷出两个 6 面骰子。如果结果是 7 或 11。玩家或自动获胜。如果掷出 2、3 或 12,则玩家自动输掉。但是,如果滚动另一个数字,则该数字将成为“点”。玩家再次滚动,直到他们再次滚动点或 7。如果重新滚动点,则玩家获胜。如果掷出 7,这一次就输了。

我的代码有两个问题

  1. 当玩家需要再次滚动但没有获胜时,我的计分器会加一分
  2. 点数和总数总是相等的,所以它只是继续要求再次滚动。

State 用于表示这是第一次滚动还是后续滚动中的一个。我省略了一些仅用于显示骰子图像的代码。

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;
    }
}

【问题讨论】:

  • 你解决了吗?

标签: c#


【解决方案1】:

首先,将你的代码改为阅读

else if (state == 2)  

正如所写,您的代码首先通过if (state==1) 部分,然后立即进入if (state==2) 部分。

此外,您还省略了代码的循环和流控制部分。您可能会在每次传递时都重新定义 state=1 —— 确保 state==2 时它在循环之外。

【讨论】:

    猜你喜欢
    • 2012-02-29
    • 1970-01-01
    • 2015-12-24
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多