使用shell脚本写石头剪刀布的脚本,三局两胜,无论谁赢,两局胜利后退出循环
时间: 2024-12-23 13:17:05 浏览: 11
当然可以,下面是一个简单的Shell脚本来实现石头、剪刀、布游戏,采用三局两胜制:
```bash
#!/bin/bash
# 定义三个选项和对应的数字
options=("rock" "paper" "scissors")
values=(1 2 3)
# 函数用于随机选择玩家的选择
choose_player() {
echo -n "Player 1 (type 1 for rock, 2 for paper, 3 for scissors): "
read player1
if [[ ! $player1 =~ ^[1-3]$ ]]; then
echo "Invalid choice, try again."
choose_player
else
player1=$((player1 - 1))
fi
}
# 函数判断胜负
judge() {
result=$((2 - ($player1 % 3)))
if [ "$player1" -eq "$result" ]; then
echo "Tie!"
elif [ "$player1" -eq "$((result - 1))" ] || [ "$player1" -eq "$((result + 2))" ]; then
echo "Player 1 wins!"
else
echo "Player 2 wins!"
fi
}
# 游戏循环
for ((i = 0; i < 3; i++)); do
choose_player
player2=$values[$RANDOM % 3]
judge
if [[ $(($i+1)) -eq 2 ]]; then
break
fi
echo "Now let's play another round!"
done
echo "Game Over! The winner is..."
if [ "$player1" -eq 2 ]; then
echo "Player 1"
else
echo "Player 2"
fi
```
当你运行这个脚本,它会引导用户输入,根据随机选择的结果判断胜负,直到有一方赢得两局。每轮结束后会询问是否继续游戏,如果只玩三局,则在第二局获胜者后结束。
阅读全文