请使用C#窗体应用程序编写一个游戏
时间: 2024-02-01 19:16:42 浏览: 85
好的,以下是一个简单的猜数字游戏,使用C#窗体应用程序编写:
```C#
using System;
using System.Windows.Forms;
namespace GuessNumberGame
{
public partial class MainForm : Form
{
private int numberToGuess;
private int numberOfGuesses;
public MainForm()
{
InitializeComponent();
StartNewGame();
}
private void StartNewGame()
{
Random random = new Random();
numberToGuess = random.Next(1, 101);
numberOfGuesses = 0;
guessButton.Enabled = true;
guessTextBox.Enabled = true;
guessTextBox.Text = "";
guessResultLabel.Text = "";
numberOfGuessesLabel.Text = "Number of Guesses: 0";
}
private void guessButton_Click(object sender, EventArgs e)
{
int guess;
if (int.TryParse(guessTextBox.Text, out guess))
{
numberOfGuesses++;
numberOfGuessesLabel.Text = "Number of Guesses: " + numberOfGuesses;
if (guess < numberToGuess)
{
guessResultLabel.Text = "Too low!";
}
else if (guess > numberToGuess)
{
guessResultLabel.Text = "Too high!";
}
else
{
guessResultLabel.Text = "You guessed it! The number was " + numberToGuess + ".";
guessButton.Enabled = false;
guessTextBox.Enabled = false;
}
}
else
{
MessageBox.Show("Invalid guess, please enter a number.");
}
}
private void newGameButton_Click(object sender, EventArgs e)
{
StartNewGame();
}
}
}
```
在这个游戏中,玩家需要在1到100之间猜一个随机数。每次猜测后,程序会告诉玩家猜得是高了还是低了,直到玩家猜中为止。游戏还会记录玩家猜的次数,并且提供一个新游戏按钮以重新开始游戏。
阅读全文