[visual-studio]Windows 窗体应用程序-C# 随机号码竞猜游戏

发布时间: 2014/3/1 1:00:54
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我需要在 visual studio 中随机号码猜测游戏的有点帮助。首当其冲的代码了,但我有困难,随机数字生成器和随机编号到端口进入的单击事件。与往常一样,我真的不需要代码但一些指导和/或解释,说明我做错了,如果有更有效的方法去做学习的初级阶段。下面是我的代码,评论是我有故障的部件。感谢帮助我收到了日期作为任何帮助了鹳。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace LAB6B
{
    public partial class game : Form
    {
        public game()
        {
            InitializeComponent();

            //Generate Random number between 1 and 100
         //Not sure if there is a better way?
            Random rand1 = new Random();
            int num1 = rand1.Next(1,50);
            int num2 = rand1.Next(1,50);
            int answer = num1 + num2;

        }

        private void evaluate_Click(object sender, EventArgs e)
        {
            int count = 0;
            int choice = Convert.ToInt32(guess);


            if (guess.Text != string.Empty)
            {
                // set counter to keep track of how many tries
                // should this be done by a loop or will it count without a loop?
                count++;

                //compare user input against random number
          //Can’t import the random number for comparision
                if (choice < answer)
                {
                    Evaluate.Visible = false;
                    lblMessage.Visible = true;
                    lblMessage.Text = "Too Low!";
                    Clear.Visible = true;
                    BackColor = Color.LightSeaGreen;
                }
                else if (choice > answer)
                {
                    Evaluate.Visible = false;
                    lblMessage.Visible = true;
                    lblMessage.Text = "Too High!";
                    Clear.Visible = true;
                    BackColor = Color.SlateBlue;
                }
                else
                {
                    //Display correct message along with how many times it took to get it
                    MessageBox.Show(" Eso es CORRECTO! It took you {0} tries. ", count);
                }
            }
        }

        private void Clear_Click(object sender, EventArgs e)
        {
            guess.Text = "";
            Evaluate.Visible = true;
            lblMessage.Visible = false;
            Clear.Visible = false;
            BackColor = Color.PowderBlue;
        }
    }
}

解决方法 1:

作为 rand1answer 在构造函数内定义的变量,您仅可以访问它们的构造函数中。定义 answer 类上水平将解决大部分的问题,如你将能够访问它既从构造函数并单击处理程序,像这样:

private int answer;
private int count;

public game()
{
  InitializeComponent();

  //Generate Random number between 1 and 100
  Random random= new Random();
  // no need for num1 and num2, it's just as random
  answer = random.Next(1,101);
}
赞助商