一个猜数字的小游戏
要点在于按钮的布局和对控件的使用及删除
namespace NumberGame { public partial class Form1 : Form { public Form1() { InitializeComponent(); T_time.Interval = 1; } Random G_random = new Random(); int G_int_num = 0; DateTime G_time_time; /// <summary> /// 点击开始后,生成布局 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { RemoveControl(); T_time.Start(); G_time_time = DateTime.Now; G_int_num = G_random.Next(1, 101); int l_int_x = 11; int l_int_y = 44; for (int i = 0; i < 100; i++) { Button bt = new Button(); bt.Text = (i + 1).ToString(); bt.Name = (i + 1).ToString(); bt.Width = 39; bt.Height = 39; bt.Location = new Point(l_int_x, l_int_y); bt.Click += new EventHandler(bt_click); l_int_x += 42; if ((i + 1) % 10 == 0) { l_int_x = 11; l_int_y += 44; } Controls.Add(bt); } button1.Enabled = false; } /// <summary> /// 按下按钮后,与随机数进行比较 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void bt_click(object sender, EventArgs e) { Control l_control = sender as Control; int num = Int32.Parse(l_control.Text); if (num > G_int_num) { l_control.Text = "大"; l_control.BackColor = Color.Red; l_control.Enabled = false; } if (num < G_int_num) { l_control.Text = "小"; l_control.BackColor = Color.Yellow; l_control.Enabled = false; } if (num == G_int_num) { T_time.Stop(); button1.Enabled = true; l_control.BackColor = Color.Green; MessageBox.Show(string.Format("共猜了{0}次", GetCount())); } } /// <summary> /// 取得已按按钮的数量 /// </summary> /// <returns></returns> string GetCount() { int l_int_count = 0; foreach (Control c in Controls) { if (!c.Enabled) l_int_count++; } return l_int_count.ToString(); } /// <summary> /// 清除按钮 /// </summary> void RemoveControl() { for (int i = 0; i < 100; i++) { if (Controls.ContainsKey((i + 1).ToString())) { for (int j = 0; j < Controls.Count; j++) { if (Controls[j].Name == (i + 1).ToString()) { Controls.RemoveAt(j); break; } } } } } /// <summary> /// 开始布局时计算按钮的长宽及间隔 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_MouseMove(object sender, MouseEventArgs e) { Point p = new Point(); p.X = e.X; p.Y = e.Y; textBox1.Text = p.X.ToString() + "," + p.Y.ToString(); } /// <summary> /// 计算用时 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void T_time_Tick(object sender, EventArgs e) { DateTime l_time = DateTime.Now; TimeSpan l_span = l_time - G_time_time; label1.Text = string.Format("用时:{0}秒", l_span.Seconds.ToString()); } } }
浮躁的人容易问:我到底该学什么;----别问,学就对了; 浮躁的人容易问:JS有钱途吗;----建议你去抢银行; 浮躁的人容易说:我要中文版!我英文不行!----不行?学呀! 浮躁的人分两种:只观望而不学的人;只学而不坚持的人; 浮躁的人永远不是一个高手。