使用shell脚本编写猜数字游戏
时间: 2024-01-13 11:18:30 浏览: 114
Shell脚本实现猜数字游戏
以下是使用Shell脚本编写猜数字游戏的示例代码:
```shell
#!/bin/bash
# 生成一个1-100之间的随机数
number=$((RANDOM % 100 + 1))
# 提示用户输入猜测的数字
echo "Guess a number between 1 and 100:"
# 循环读取用户的输入并进行判断
while read guess; do
# 判断用户输入的是否为数字
if ! [[ "$guess" =~ ^[0-9]+$ ]]; then
echo "Invalid input. Please enter a number between 1 and 100."
# 判断用户输入的数字是否在1-100之间
elif (( guess < 1 || guess > 100 )); then
echo "Invalid input. Please enter a number between 1 and 100."
# 判断用户猜测的数字是否等于随机数
elif (( guess == number )); then
echo "Congratulations! You guessed the right number!"
exit 0
# 判断用户猜测的数字是否比随机数大
elif (( guess > number )); then
echo "Too high. Guess again:"
# 用户猜测的数字比随机数小
else
echo "Too low. Guess again:"
fi
done
```
阅读全文