用linux脚本实现石头剪刀布和AI对战,AI随机生成石头0 剪刀1 布2 ,玩家输入0、1、2和AI对战,对战10盘,输出输赢平均的次数
时间: 2024-10-13 18:03:10 浏览: 44
要在Linux脚本中实现石头剪刀布游戏与AI的对战,可以按照以下步骤编写shell脚本:
```bash
#!/bin/bash
# 定义AI随机选择的行为
AI_CHOICES=("0" "1" "2")
AI.rand_choice() {
echo "${AI_CHOICES[$RANDOM % ${#AI_CHOICES[@]}]}"
}
# 玩家与AI对战循环
total_wins=0
total_losses=0
for i in {1..10}; do
echo "Round $i:"
read -p "Please choose (0 for Rock, 1 for Scissors, 2 for Paper): " player_choice
# 检查玩家输入是否合法
if [[ ! "$player_choice" =~ ^[012]$ ]]; then
echo "Invalid input! Please try again."
continue
fi
# AI随机选择
ai_choice=$(AI.rand_choice)
# 判断胜负并计数
if [ "$player_choice" -eq "$ai_choice" ]; then
echo "It's a tie!"
elif (( (player_choice - ai_choice) % 3 == 1 )); then
total_wins=$((total_wins + 1))
echo "You win!"
else
total_losses=$((total_losses + 1))
echo "AI wins!"
fi
done
# 输出结果
average_score=$(bc <<< "scale=2; ($total_wins + $total_losses) / 10")
echo "After 10 rounds:"
echo "Wins: $total_wins"
echo "Losses: $total_losses"
echo "Average score: $average_score"
```
保存这个脚本到文件(如`rock_paper_scissors.sh`),然后通过`chmod +x rock_paper_scissors.sh`使其可执行,接着运行`./rock_paper_scissors.sh`即可开始游戏。
阅读全文