如何创建第二个播放器/计算机

时间:2015-11-26 22:53:31

标签: c# .net forms visual-studio

我正在努力创建一个双人骰子游戏,玩家可以与其他用户或计算机一起玩。我很难搞清楚如何制作双人游戏。我不确定是否必须为每个用户创建单独的类,然后创建该类的对象以具有两个单独的玩家,或者如果我只需要创建一个像

这样的变量
static int player = 1;

并将其分配到特定区域并使用模数来确定哪个玩家已经启动。

另外,在我的roll_Btn方法下,你会看到我试图让它切换到下一个用户,当骰子滚动一个" 1"并清除它所指定的字段,但是当我尝试再次掷骰子时,然后程序结束于我。请参阅下面的代码。谢谢你的帮助和指导。

public partial class Game : Form
{
    public Game()
    {
        InitializeComponent();
    }
    static int player = 1;
    private void Game_Load(object sender, EventArgs e)
    {
        oneNameTxt.Text = diceFrm.player1.ToUpper();
        twoNameTxt.Text = diceFrm.player2.ToUpper();
    }

    private void endBtn_Click(object sender, EventArgs e)
    {
        diceFrm end = new diceFrm();
        end.Show();
        this.Hide();
    }
    private void standBtn_Click(object sender, EventArgs e)
    {
        oneScoreTxt.Text = totalTxt.Text;
    }

    private void rollBtn_Click(object sender, EventArgs e)
    {
        int t1 = Convert.ToInt32(turnsTxt.Text);
        int t2 = t1 + 1;
        turnsTxt.Text = t2.ToString();

        Random rand = new Random();
        int dice = rand.Next(1, 7);
        rollTxt.Text = dice.ToString();
        int d1 = Convert.ToInt32(totalTxt.Text);
        int d2 = d1 + dice;
        totalTxt.Text = d2.ToString();
        if(dice == 1)
        {
            player++;
            rollTxt.Text = String.Empty;
            turnsTxt.Text = String.Empty;
            totalTxt.Text = String.Empty;
        }
    }
    private void oneScoreTxt_TextChanged(object sender, EventArgs e)
    {
        int score1 = Convert.ToInt32(oneScoreTxt.Text);
        int score2 = Convert.ToInt32(twoScoreTxt.Text);

        if (score1 >= 100 || score2 >= 100)
        {
            whatLbl.Text = "Winner";
        }
        else
        {
            whatLbl.Text = "Turn";
        }
    }

1 个答案:

答案 0 :(得分:0)

正如Ogul Ozgul所说,

    private void rollBtn_Click(object sender, EventArgs e)
    {
        ...
        if (dice == 1)
        {
            ...
            turnsTxt.Text = String.Empty;
            ...
        }
    }

滚动1时,你的turnsTxt.Text = String.Empty,因此当你下次滚动时,

    private void rollBtn_Click(object sender, EventArgs e)
    {
        int t1 = Convert.ToInt32(turnsTxt.Text); // program crash
        ...
    }

你的程序会崩溃。

解决方案:我建议您在整个代码中使用TryParse而不是Convert。它会更强大。

例如

    private void rollBtn_Click(object sender, EventArgs e)
    {
        int t1 = 0;
        int.TryParse(turnsTxt.Text, out t1)
        int t2 = t1 + 1;
        turnsTxt.Text = t2.ToString(); 
        ...
        //rest of your code
    }