C#Windows窗体做一个随机猜数(1~100)
public partial class Form1 : Form
{
public int k = 0; //接收随机数的值
int count = 0; // 计数
InitializeComponent();
}
/// <summary>
/// 新游戏按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
///
private void butNewGame_Click(object sender, EventArgs e)
{
this.txtNum.Enabled = true;
this.btnGuess.Enabled = true;
Random r = new Random();
k = r.Next(1, 100);//返回一个1~100的整数(包含1,但不包含100)
txtanswer.Text = Convert.ToString(k);//谜底Text框
/// <summary>
/// 猜一猜按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGuess_Click(object sender, EventArgs e)
{
//循环判断猜大还是猜小并计数
do
{
number = Convert.ToInt32(txtNum.Text);
if (number > k)
{
MessageBox.Show("大了,再猜!!", Hint, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
count++;
}
else if (number < k)
{
MessageBox.Show("小了,再猜!!", Hint, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
count++;
}
break;
} while (number !=k);
if (number == k )
{
count++;
MessageBox.Show("恭喜你,猜中了!!一共猜了" + count + "次", Hint, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
/// <summary>
/// 退出按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
{
public int k = 0; //接收随机数的值
int count = 0; // 计数
int number = 0; //输入猜的数值
public Form1()
{InitializeComponent();
}
/// <summary>
/// 新游戏按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
///
private void butNewGame_Click(object sender, EventArgs e)
{
this.txtNum.Enabled = true;
this.btnGuess.Enabled = true;
Random r = new Random();
k = r.Next(1, 100);//返回一个1~100的整数(包含1,但不包含100)
txtanswer.Text = Convert.ToString(k);//谜底Text框
}
public const string Hint = "提示";/// <summary>
/// 猜一猜按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGuess_Click(object sender, EventArgs e)
{
//循环判断猜大还是猜小并计数
do
{
number = Convert.ToInt32(txtNum.Text);
if (number > k)
{
MessageBox.Show("大了,再猜!!", Hint, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
count++;
}
else if (number < k)
{
MessageBox.Show("小了,再猜!!", Hint, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
count++;
}
break;
} while (number !=k);
if (number == k )
{
count++;
MessageBox.Show("恭喜你,猜中了!!一共猜了" + count + "次", Hint, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
/// <summary>
/// 退出按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}