步骤 1:创建 Winform 项目并设计界面

步骤 2:编写代码实现切换逻辑
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace 可控制输赢的剪刀石头布游戏
{
/// <summary>
/// 定义一个枚举(Enumeration),用来表示“石头”、“剪刀”、“布”这三种出拳选项。
/// 每个枚举值都被赋予了一个对应的整数(石头=1,剪刀=2,布=3),便于后续的逻辑计算。
/// </summary>
public enum Code
{
石头 = 1,
剪刀,
布
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//设置显示电脑出拳结果的 textBox2 为只读模式
textBox2.ReadOnly = true;
//遍历窗体上所有的 Button 控件,并为它们统一绑定 Click 事件处理器 CalcResult
IEnumerable<Button> buttons = this.Controls.OfType<Button>();
foreach (Button button in buttons)
{
button.Click += CalcResult;
}
// 遍历窗体上所有的 RadioButton 控件,并为它们统一绑定 CheckedChanged 事件处理器 StateCheckedChanged
IEnumerable<RadioButton> radioButtons = this.Controls.OfType<RadioButton>();
foreach (RadioButton radioButton in radioButtons)
{
radioButton.CheckedChanged += StateCheckedChanged;
}
}
// 定义一个总次数
private static int TotalCount = 0;
// 定义一个赢的次数
private static int WinCount = 0;
//用于存储当前选择的游戏模式("随机"、"赢"、"输")
private static string State = "随机";
// 创建一个随机对象
Random random = new Random();
//单选按钮
private void StateCheckedChanged(object sender, EventArgs e)
{
// 将触发事件的控件(sender)转换为 RadioButton 类型
RadioButton radioButton = sender as RadioButton;
// 检查这个单选按钮是否被选中。
if (radioButton.Checked)
{
// 如果被选中,就将其 Text 属性(如 "随机"、"赢")赋值给全局状态变量 State。
State = radioButton.Text;
}
}
// 自定义一个方法 用于计算猜拳结果
private void CalcResult(object sender, EventArgs e)
{
// 总次数累加1
TotalCount++;
// 先获取你点击的是哪一个button
Button button = sender as Button;
// 获取按钮上显示的文本
string playerText = button.Text;
// 把玩家的字符串信息先转换成数字
int playerNum = (int)Enum.Parse(typeof(Code), playerText);
// 电脑出拳 应该怎么出
/*
假设石头=1 剪刀=2 布=3
玩家的值是确定的
State的值来确定电脑应该出什么值
玩家赢:player - computer == -1 || player - computer == 2
平局: player - computer == 0
玩家输(else):---->玩家输
*/
//int computerNum = [条件1] ? [表达式1] : [条件2] ? [表达式2] : [条件3] ? [表达式3] : [表达式4];
//int computerNum = [条件1] ? [表达式1] : ([条件2] ? [表达式2] : ([条件3] ? [表达式3] : [表达式4]));
int computerNum = State == "随机" ? random.Next(1, 4) : State == "赢" ? playerNum == 3 ? 1 : playerNum + 1 : State == "输" ? playerNum == 1 ? 3 : playerNum - 1 : playerNum;
// 来表达三种结果
if (playerNum - computerNum == -1 || playerNum - computerNum == 2)
{
// 玩家赢
WinCount++;
textBox3.Text = "玩家赢";
}
else if (playerNum == computerNum)
{
textBox3.Text = "平局";
}
else
{
textBox3.Text = "玩家输";
}
textBox1.Text = playerText;// 玩家出拳信息
textBox2.Text = ((Code)computerNum).ToString();// 电脑出拳信息
label7.Text = "总次数:" + TotalCount + "次";
label8.Text = "赢次数:" + WinCount + "次";
label9.Text = "胜率:" + Math.Round(WinCount * 1.0 / TotalCount * 100, 2) + "%";
}
}
}
步骤3: 测试演示

希望对大家有所帮助。感谢大家的关注和点赞。
8029



被折叠的 条评论
为什么被折叠?



