linux实现石头剪刀布和AI对战,AI随机生成石头0 剪刀1 布2 ,玩家输入0、1、2和AI对战,对战10盘,输出输赢平均的次数
时间: 2024-10-12 11:11:45 浏览: 37
在Linux上实现石头剪刀布游戏与AI对战的基本步骤如下:
1. **创建程序**:
首先,你可以使用Bash脚本或者Python等简单易读的语言编写程序。例如,如果你选择Python,可以创建一个`rock_paper_scissors.py`文件。
```python
import random
def player_choice():
choices = ['0', '1', '2']
return input("请输入你的选择(0-石头, 1-剪刀, 2-布):").strip()
def ai_choice():
return str(random.randint(0, 2))
def play_round(player, ai):
if player == ai:
print(f"平局!你选了{player},AI也选了{ai}")
elif (player == '0' and ai == '1') or (player == '1' and ai == '2') or (player == '2' and ai == '0'):
print(f"你赢了!你选了{player},AI选了{ai}")
else:
print(f"AI赢了!你选了{player},AI选了{ai}")
def main():
total_rounds = 10
wins_player = 0
wins_ai = 0
for _ in range(total_rounds):
player_choice_str = player_choice()
ai_choice_str = ai_choice()
play_round(player_choice_str, ai_choice_str)
if player_choice_str == ai_choice_str:
continue
elif int(player_choice_str) > int(ai_choice_str):
wins_player += 1
else:
wins_ai += 1
avg_wins_player = wins_player / total_rounds
avg_wins_ai = wins_ai / total_rounds
print(f"经过10轮比赛,你赢了{wins_player}次,输了{total_rounds - wins_player}次,平均胜率大约为{avg_wins_player*100:.2f}%")
print(f"AI赢了{wins_ai}次,输了{total_rounds - wins_ai}次,平均胜率为{avg_wins_ai*100:.2f}%")
if __name__ == "__main__":
main()
```
2. **运行游戏**:
打开终端,导航到包含上述Python脚本的目录,并运行`python rock_paper_scissors.py`。
在这个游戏中,玩家每轮会与AI进行一次对战,总共10轮。程序会统计双方的胜利次数并计算平均胜率。
阅读全文