编写shell函数 实现剪刀石头布 有几种方法
时间: 2023-12-29 22:04:28 浏览: 75
jsp实现石头剪刀布
以下是几种使用 Shell 函数实现剪刀石头布游戏的方法:
方法一:使用 if-elif-else 语句实现
```bash
#!/bin/bash
function play_game {
options=("剪刀" "石头" "布")
random_index=$((RANDOM % 3))
computer_choice=${options[random_index]}
echo "欢迎来到剪刀石头布游戏!"
echo "请出拳:剪刀、石头、布"
read user_choice
echo "你出了:$user_choice"
echo "电脑出了:$computer_choice"
if [ "$user_choice" == "$computer_choice" ]; then
echo "平局!"
elif [ "$user_choice" == "剪刀" ] && [ "$computer_choice" == "布" ]; then
echo "你赢了!"
elif [ "$user_choice" == "石头" ] && [ "$computer_choice" == "剪刀" ]; then
echo "你赢了!"
elif [ "$user_choice" == "布" ] && [ "$computer_choice" == "石头" ]; then
echo "你赢了!"
else
echo "你输了!"
fi
}
play_game
```
方法二:使用 case 语句实现
```bash
#!/bin/bash
function play_game {
options=("剪刀" "石头" "布")
random_index=$((RANDOM % 3))
computer_choice=${options[random_index]}
echo "欢迎来到剪刀石头布游戏!"
echo "请出拳:剪刀、石头、布"
read user_choice
echo "你出了:$user_choice"
echo "电脑出了:$computer_choice"
case "$user_choice $computer_choice" in
"剪刀 布" | "石头 剪刀" | "布 石头")
echo "你赢了!"
;;
"剪刀 石头" | "石头 布" | "布 剪刀")
echo "你输了!"
;;
*)
echo "平局!"
;;
esac
}
play_game
```
方法三:使用数组和循环实现
```bash
#!/bin/bash
function play_game {
options=("剪刀" "石头" "布")
random_index=$((RANDOM % 3))
computer_choice=${options[random_index]}
echo "欢迎来到剪刀石头布游戏!"
echo "请出拳:剪刀、石头、布"
read user_choice
echo "你出了:$user_choice"
echo "电脑出了:$computer_choice"
for i in "${!options[@]}"; do
if [ "${options[$i]}" == "$user_choice" ]; then
user_index=$i
fi
if [ "${options[$i]}" == "$computer_choice" ]; then
computer_index=$i
fi
done
diff=$(($user_index - $computer_index))
if [ "$diff" == "0" ]; then
echo "平局!"
elif [ "$diff" == "-1" ] || [ "$diff" == "2" ]; then
echo "你赢了!"
else
echo "你输了!"
fi
}
play_game
```
注意,以上三种方法都是基于 Bash Shell 实现的,可在 Linux 和 macOS 等系统中运行。
阅读全文