用c#做一个石头剪刀布程序
时间: 2024-10-11 14:03:16 浏览: 16
C# Winform实现石头剪刀布游戏
在C#中制作一个简单的石头、剪刀、布游戏可以分为以下几个步骤:
1. **创建控制台应用**:
首先,打开Visual Studio,创建一个新的控制台应用程序项目。
2. **添加枚举**:
创建一个枚举(Enum)来代表三种选项:
```csharp
public enum GameMove { Rock, Paper, Scissors }
```
3. **用户输入**:
使用`Console.ReadLine()`获取玩家的输入,并转换成相应的枚举值:
```csharp
Console.WriteLine("请输入你的选择(R for Rock, P for Paper, S for Scissors):");
string input = Console.ReadLine().ToUpper();
GameMove playerMove = input switch {
"R" => GameMove.Rock,
"P" => GameMove.Paper,
"S" => GameMove.Scissors,
_ => throw new ArgumentException("无效的选择")
};
```
4. **电脑随机选择**:
定义一个方法生成电脑的选择:
```csharp
Random random = new Random();
GameMove computerMove = (GameMove)random.Next(0, 3);
```
5. **比较结果**:
根据规则判断胜负并输出结果:
```csharp
if (playerMove == computerMove)
Console.WriteLine("平局!");
else if ((playerMove == GameMove.Rock && computerMove == GameMove.Scissors) ||
(playerMove == GameMove.Paper && computerMove == GameMove.Rock) ||
(playerMove == GameMove.Scissors && computerMove == GameMove.Paper))
Console.WriteLine("你赢了!");
else
Console.WriteLine("电脑赢了!");
```
6. **循环和再玩一次**:
可以加上一个`while`循环让用户有再来一局的机会:
```csharp
Console.WriteLine($"你想再玩一轮吗?(Y/N)");
string playAgain = Console.ReadLine();
while (playAgain.ToUpper() == "Y")
{
// 重复以上步骤...
playAgain = Console.ReadLine();
}
```
阅读全文