前面打了那麼多小怪,但都還沒打到BOSS,今天他來了!!
今天要來實作一個小遊戲:猜數字遊戲
首先先拉出這樣的介面
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
using System.Windows.Forms;
using System.Linq.Expressions;
namespace ithome2023
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int guess, count, min, max;
private void Form1_Load(object sender, EventArgs e)
{
Random r = new Random();
guess = r.Next(1, 100);
min = 0; max = 100; count = 0;
lab_title.Text = min + " < ? < " + max;
lab_msg.Text = "共猜了 " + count + " 次";
btn_ok.Enabled = true;
txt_guess.Text = "";
}
private void btn_ok_Click(object sender, EventArgs e)
{
count++;
int myguess = 0;
try
{
myguess = int.Parse(txt_guess.Text);
}
catch
{
MessageBox.Show("請輸入數字");
}
if (myguess >= min && myguess < max)
{
if (myguess == guess)
{
MessageBox.Show("猜對了~~");
btn_ok.Enabled = false;
}
else if (myguess > guess)
{
max = myguess;
MessageBox.Show("小一點");
}
else if (myguess < guess)
{
min = myguess;
MessageBox.Show("大一點");
}
}
else
MessageBox.Show("請輸入範圍內數字");
lab_msg.Text = "共猜了 " + count + " 次";
lab_title.Text = min + " < ? < " + max;
}
private void btn_retry_Click(object sender, EventArgs e)
{
Form1_Load(sender, e);
}
private void btn_end_Click(object sender, EventArgs e)
{
if (MessageBox.Show("請問是否離開遊戲嗎?", "離開", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
Application.Exit();
}
}
}
今天就到這邊啦,大家辛苦了
2023鐵人賽