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

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

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

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        int n;//全局变量
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Random a = new Random();                //用随机数赋值
            n = a.Next(1, 101);                     //答案的值
            int x = 10;
            int y = 60;
            for(int i=0;i<100;i++)                  //创建100个按钮
            {
                label1.Visible = false;
                Button bt = new Button();
                bt.BackColor = System.Drawing.Color.Blue;//改变按钮的背景色
                bt.Text = (i + 1).ToString();           //给按钮的text属性赋值
                bt.Name = (i + 1).ToString();           //给按钮的名字赋值
                bt.Width = 40;                          //设置按钮的宽和高
                bt.Height = 40;
                bt.Location = new Point(x, y);          //设置按钮的位置
                bt.Click += new EventHandler(bt_Click); //给按钮点击添加事件
                x += 36;
                if((i+1)%10==0)                         //每十个换一行
                {
                    x = 10;
                    y += 36;
                }
                Controls.Add(bt);                   //将按钮放入窗体控件集合中
            } 
        }
         private void bt_Click(object sender,EventArgs e)
        {
            Button but = (Button)sender;
            int t = int.Parse(but.Text);            //把按钮的Text的值转换为整型
                if(t==n)
                {
                label1.Text = "恭喜你答对了!";
                label1.Visible = true;
                but.BackColor = System.Drawing.Color.Red;
                }
                else if (t

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

界面设计(比较丑...):

c#窗体猜数字小游戏(初级版)_第1张图片

你可能感兴趣的:(c#笔记)