shell脚本石头剪刀布五局三胜
时间: 2023-10-28 14:06:45 浏览: 188
可以为您提供一个简单的shell脚本来实现石头剪刀布游戏。下面是一个示例:
```shell
#!/bin/bash
player_score=0
computer_score=0
rounds=5
wins_required=3
declare -a options=("石头" "剪刀" "布")
function generate_computer_choice {
computer_choice=$((RANDOM % 3))
}
function determine_winner {
player_choice=$1
computer_choice=$2
if [[ $player_choice -eq $computer_choice ]]; then
echo "平局!"
elif [[ ($player_choice -eq 0 && $computer_choice -eq 1) || ($player_choice -eq 1 && $computer_choice -eq 2) || ($player_choice -eq 2 && $computer_choice -eq 0) ]]; then
echo "你赢了这局!"
((player_score++))
else
echo "电脑赢了这局!"
((computer_score++))
fi
}
function print_scores {
echo "你的得分:$player_score"
echo "电脑的得分:$computer_score"
}
echo "欢迎来到石头剪刀布游戏!"
while [[ $player_score -lt $wins_required && $computer_score -lt $wins_required && $rounds -gt 0 ]]; do
echo "请选择(输入序号):"
for index in "${!options[@]}"; do
echo "$index. ${options[$index]}"
done
read -p "你的选择: " player_choice
if [[ $player_choice =~ ^[0-2]$ ]]; then
generate_computer_choice
echo "你选择了:${options[$player_choice]}"
echo "电脑选择了:${options[$computer_choice]}"
determine_winner $player_choice $computer_choice
((rounds--))
print_scores
else
echo "无效的选择,请重新输入!"
fi
done
if [[ $player_score -eq $wins_required ]]; then
echo "恭喜,你赢得了比赛!"
elif [[ $computer_score -eq $wins_required ]]; then
echo "很遗憾,电脑赢得了比赛!"
else
echo "比赛结束,没有胜出者!"
fi
```
您可以将以上代码保存为一个.sh文件(例如:game.sh),然后通过运行 `bash game.sh` 或 `./game.sh` 来执行脚本。
这个脚本允许玩家与电脑进行石头剪刀布游戏,共进行5局,其中一方先获得3局胜利即为最终胜利。每次游戏后会显示双方的得分。最终会显示比赛结果。
阅读全文