c#窗体猜数字小游戏(初级版)

怼烎@ 2021-09-22 12:44 599阅读 0赞

小游戏的简单实现,这种小游戏非常适合初学者,能够提升对编程的兴趣。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace WindowsFormsApp1
  11. {
  12. public partial class Form1 : Form
  13. {
  14. int n;//全局变量
  15. public Form1()
  16. {
  17. InitializeComponent();
  18. }
  19. private void button1_Click(object sender, EventArgs e)
  20. {
  21. Random a = new Random(); //用随机数赋值
  22. n = a.Next(1, 101); //答案的值
  23. int x = 10;
  24. int y = 60;
  25. for(int i=0;i<100;i++) //创建100个按钮
  26. {
  27. label1.Visible = false;
  28. Button bt = new Button();
  29. bt.BackColor = System.Drawing.Color.Blue;//改变按钮的背景色
  30. bt.Text = (i + 1).ToString(); //给按钮的text属性赋值
  31. bt.Name = (i + 1).ToString(); //给按钮的名字赋值
  32. bt.Width = 40; //设置按钮的宽和高
  33. bt.Height = 40;
  34. bt.Location = new Point(x, y); //设置按钮的位置
  35. bt.Click += new EventHandler(bt_Click); //给按钮点击添加事件
  36. x += 36;
  37. if((i+1)%10==0) //每十个换一行
  38. {
  39. x = 10;
  40. y += 36;
  41. }
  42. Controls.Add(bt); //将按钮放入窗体控件集合中
  43. }
  44. }
  45. private void bt_Click(object sender,EventArgs e)
  46. {
  47. Button but = (Button)sender;
  48. int t = int.Parse(but.Text); //把按钮的Text的值转换为整型
  49. if(t==n)
  50. {
  51. label1.Text = "恭喜你答对了!";
  52. label1.Visible = true;
  53. but.BackColor = System.Drawing.Color.Red;
  54. }
  55. else if (t<n)
  56. but.Text = "小";
  57. else
  58. but.Text = "大";
  59. }
  60. private void button2_Click(object sender, EventArgs e)
  61. {
  62. Application.Exit();
  63. }
  64. }
  65. }

还有很多功能没有实现,希望大家多提意见!

界面设计(比较丑…):

20180610162453643

发表评论

表情:
评论列表 (有 0 条评论,599人围观)

还没有评论,来说两句吧...

相关阅读