因此,我应该为“猜我的数字”游戏创建两个 bash 脚本。一个脚本用于庄家,另一个脚本用于玩家。
每个脚本都应等待对方生成响应(通过文件)后再继续。因此,当播放器启动时,它首先需要等待庄家的响应。当检测到响应时,播放器会获取庄家的响应并进行处理。当播放器做出猜测时,播放器会通过文件将该猜测传达给庄家。
当玩家猜测时,庄家会等待玩家的响应(通过文件)。当庄家检测到玩家的响应时,庄家会从文件中获取响应并继续进行。
下面是我在 bash 脚本中执行“猜我的数字”的 bash 脚本,但这仅在一个文件时才有效。
有人能告诉我如何将其拆分为两个脚本 (player_response.bash deal_response.bash) 并让它们通过文件进行通信并同时运行以实现相同的结果吗?非常感谢您的帮助!
#!/bin/bash
# this program random numbers between 1 and 100.
clear
echo "Hello, "${USER}
date;
guess=1
## Start loop of game here
while true; do
n1=$(( ( RANDOM % 100 ) +1 ))
echo -n "I'm think of a number between 1 and 100. Guess: "
while read n2; do
if [[ $n2 -eq $n1 ]]; then
break;
else
if [[ $n2 -gt $n1 ]]; then
echo -n "Sorry, your guess is too high. Guess again: "
elif [[ $n2 -lt $n1 ]]; then
echo -n "Sorry, your guess is too low. Guess again: "
fi
fi
guess=$(( $guess + 1 ))
done
echo
echo "Congratulations! You win!"
if [[ $guess == 1 ]]; then
echo "It took you $guess guess to get $n1."
else
echo "It took you $guess guesses to get $n1."
fi
echo
read -p "Do you want to try again (y/n)? " choice
case $choice in
[Yy]* ) guess=1;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
## End loop of game here
done
答案1
有专门用于此目的的文件(即 IPC)称为命名管道。您可以使用命令创建它们mkfifo
。以下是根据您的代码的一个非常基本的示例。dealer.sh
必须首先执行,因为它负责创建和删除命名管道。
经销商.sh:
#!/bin/bash
dealerResponse=dealerResponse
playerResponse=playerResponse
mkfifo $dealerResponse
mkfifo $playerResponse
# delete the named pipes on exit
trap "rm $playerResponse $dealerResponse" EXIT
guess=1
n1=$(( ( RANDOM % 100 ) +1 ))
# this blocks until the player has read from the pipe
echo -n "Please make a guess: " > $dealerResponse
while read n2 < $playerResponse; do
if [[ $n2 -eq $n1 ]]; then
echo You win! > $dealerResponse
break
else
if [[ $n2 -gt $n1 ]]; then
echo -n "Sorry, your guess is too high. Guess again: " > $dealerResponse
elif [[ $n2 -lt $n1 ]]; then
echo -n "Sorry, your guess is too low. Guess again: " > $dealerResponse
fi
fi
guess=$(( $guess + 1 ))
done
播放器
#!/bin/bash
dealerResponse=dealerResponse
playerResponse=playerResponse
while true; do
read line < $dealerResponse
echo -n "$line "
read guess
echo $guess > $playerResponse
done