发布网友 发布时间:2022-04-27 01:05
共1个回答
热心网友 时间:2023-11-15 04:50
给你个完美版本,我刚刚在VS中写的,测试通过。
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 猜数字小游戏
{
//说明:猜一猜按钮的Name为buttonOK,由上到下三个label分别为label1、label2、label3
public partial class Form1 : Form
{
private int num = 0;
private int totalTimes = 0;//猜的总次数
public Form1()
{
InitializeComponent();
}
private void buttonOK_Click(object sender, EventArgs e)
{
int inputNum = 0;
try//可能用户输入并不是正确的数字,如输入abc,在此尝试转换
{
inputNum = Convert.ToInt32(textBoxInput.Text.Trim());
}
catch (Exception ex)
{
MessageBox.Show("发生错误,请重新输入数字:\r\n " + ex.Message);
textBoxInput.Text = "";
textBoxInput.Focus();
return;
}
totalTimes++;
label2.Text = "你已经猜了" + totalTimes.ToString() + "次";
if (inputNum != num)
{
if (inputNum > num)
{
label3.Text = "你猜的数字太大了!";
}
else
{
label3.Text = "你猜的数字太小了!";
}
textBoxInput.SelectAll();
textBoxInput.Focus();
}
else
{
MessageBox.Show("恭喜你猜对了!正确数字是" + num.ToString() + ",你一共猜了" + totalTimes.ToString() + "次");
label3.Text="恭喜你猜对了!请点击“开始游戏”重新开始新一轮游戏";
buttonStartGame.Enabled = true;
buttonOK.Enabled=false;
buttonEndGame.Enabled=false;
}
}
private void buttonStartGame_Click(object sender, EventArgs e)
{
totalTimes = 0;
label2.Text = "";
label3.Text = "";
buttonStartGame.Enabled = false;
buttonEndGame.Enabled = true;
buttonOK.Enabled = true;
textBoxInput.Text = "";
textBoxInput.Focus();
Random sourceGen = new Random();//随机数
num=sourceGen.Next(0, 101);
}
private void buttonEndGame_Click(object sender, EventArgs e)
{
buttonStartGame.Enabled = true;
buttonOK.Enabled=false;
buttonEndGame.Enabled=false;
MessageBox.Show("很遗憾你没有猜对,正确数字是"+num.ToString()+",你已经猜了"+totalTimes.ToString()+"次");//不想猜了,可直接结束游戏,以开始一个新游戏
}
private void Form1_Load(object sender, EventArgs e)
{
buttonStartGame.Enabled = true;
buttonEndGame.Enabled = false;
buttonOK.Enabled = false;
label2.Text = "";
label3.Text = "";
}
}
}