C#窗体程序石头剪刀布比赛,三局两胜,代码
时间: 2024-11-17 13:13:40 浏览: 9
在C#中创建一个简单的窗体应用程序来进行石头剪刀布游戏,涉及的主要步骤包括界面设计、用户输入处理和判断游戏结果。这里提供一个简化版的示例代码:
```csharp
using System;
using System.Windows.Forms;
public partial class MainForm : Form
{
private Random random = new Random();
public enum Choices { Rock, Paper, Scissors }
public MainForm()
{
InitializeComponent();
StartGame();
}
private void StartGame()
{
for (int i = 0; i < 2; i++)
{
ShowPlayerChoice();
ShowComputerChoice();
DisplayResult();
MessageBox.Show($"Round {i + 1} - Player wins!" if JudgeGame() else "Round {i + 1} - Computer wins!");
ClearInputs();
}
DetermineWinner();
}
// 用户输入
private void buttonRock_Click(object sender, EventArgs e)
{
textBoxPlayerChoice.Text = "Rock";
}
// 计算机随机选择
private void ChooseRandom()
{
Choices compChoice = (Choices)random.Next(0, 3);
pictureBoxCompChoice.Image = GetImageForChoice(compChoice);
}
// 判断游戏结果
private bool JudgeGame()
{
Choices playerChoice = ConvertToEnum(textBoxPlayerChoice.Text);
return Compare(playerChoice, pictureBoxCompChoice.Tag as Choices);
}
// 渲染玩家选择并显示结果
private void ShowPlayerChoice()
{
// 石头、纸、剪刀图片的设置...
pictureBoxPlayerChoice.Image = GetImageForChoice(playerChoice);
}
private void ShowComputerChoice()
{
ChooseRandom();
}
// 渲染电脑的选择并隐藏
private void DisplayResult()
{
pictureBoxCompChoice.Visible = false;
}
// 游戏结束后的操作
private void DetermineWinner()
{
if (winCount == 2)
MessageBox.Show("Player wins the game!");
else if (loseCount == 2)
MessageBox.Show("Computer wins the game!");
else
MessageBox.Show("It's a tie!");
Close();
}
// 其他辅助方法
private Choices ConvertToEnum(string text)
{
// 根据字符串转换为enum值...
}
private Image GetImageForChoice(Choices choice)
{
// 获取对应图片对象...
}
private bool Compare(Choices a, Choices b)
{
// 判断游戏规则...
}
private int winCount = 0, loseCount = 0;
private void ClearInputs()
{
textBoxPlayerChoice.Text = "";
pictureBoxPlayerChoice.Image = null;
pictureBoxCompChoice.Visible = true;
}
}
```
这个示例仅包含了基本的游戏框架,实际项目中还需要添加更多的错误检查、用户界面美化以及更细致的游戏规则判断。记住,这只是一个简化的版本,完整的代码会更复杂,需要包含更多细节和异常处理。
阅读全文