C#實現猜數字小遊戲
阿新 • • 發佈:2020-03-11
本文例項為大家分享了C#實現猜數字小遊戲的具體程式碼,供大家參考,具體內容如下
效果如圖:
程式碼:
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 _1csz { public partial class Form1 : Form { int x;///定義的是一個全域性變數 public Form1() { InitializeComponent(); } private void button1_Click(object sender,EventArgs e)///產生一個隨機數 { Random rd = new Random(); x = rd.Next(100); } private void button2_Click(object sender,EventArgs e)///顯示正確答案 { label4.Visible = true; label4.Text = x.ToString(); } private void button3_Click(object sender,EventArgs e)///退出鍵 { Application.Exit(); } private void Form1_Load(object sender,EventArgs e)///窗體初始化 { label3.Visible = false; label4.Visible = false; } private void textBox1_KeyDown(object sender,KeyEventArgs e)///KeyDown事件:當焦點在文字框時按下任何鍵都觸發該事件 { if (e.KeyCode==Keys.Enter)///KeyCode屬性獲取KeyUp和KeyDown事件的鍵盤程式碼,其值用Keys列舉成員名 { if (x==int.Parse(textBox1.Text)) { label3.Visible = true; label3.Text = "猜對了,你真棒!"; } else if (int.Parse(textBox1.Text) > x) { label3.Visible = true; label3.Text = "真是,猜大了!"; } else { label3.Visible = true; label3.Text = "真是,猜小了!"; } } } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。