shell人机石头剪刀布游戏
时间: 2024-12-10 14:45:04 浏览: 19
在Shell中实现一个简单的石头、剪刀、布游戏可以使用read命令获取用户的输入,然后用if-else语句判断用户的选择是否匹配预设的选项。下面是一个基础的示例:
```bash
#!/bin/bash
# 石头、剪刀、布的选项
choices=("rock" "paper" "scissors")
# 输出游戏规则
echo -e "Let's play Rock-Paper-Scissors!\n"
echo "Type 'rock', 'paper', or 'scissors'."
# 读取用户输入
while true; do
read -p "Your choice: " user_choice
if [[ "$user_choice" =~ ^(rock|paper|scissors)$ ]]; then
break
else
echo "Invalid input! Please try again."
fi
done
# 随机选择电脑的选择
computer_choice=$((RANDOM % 3 + 1))
case $computer_choice in
1) computer_choice="rock";;
2) computer_choice="paper";;
3) computer_choice="scissors";;
esac
# 比较双方的选择并输出结果
echo "Computer chose: $computer_choice"
if [ "$user_choice" == "$computer_choice" ]; then
echo "It's a tie!"
elif [ "$user_choice" = "rock" ] && [ "$computer_choice" = "scissors" ]; then
echo "You win!"
elif [ "$user_choice" = "paper" ] && [ "$computer_choice" = "rock" ]; then
echo "You win!"
elif [ "$user_choice" = "scissors" ] && [ "$computer_choice" = "paper" ]; then
echo "You win!"
else
echo "Computer wins!"
fi
# 游戏结束提示
echo "Game over!"
```
每次运行这个脚本,你会看到游戏流程和最终的结果。
阅读全文