0

在我的滚动代码中,您只需编写 r 然后按回车键,但似乎没有读取它并转到重新启动 while 循环的 else 。让它滚动的唯一方法是输入除 r 以外的其他内容,而不是 (standard_in) 1: parse error。

#!/bin/bash
#this is a game that is two player and it is a race to get to 
#100 before the other player

echo "Player 1 name?"
read p1
echo "Player 2 name?"
read p2
echo "Okay $p1 and $p2. $p1 will go first"
p1s=0
p2s=0
pt=1
while [ $pt -eq 1 ]; do
echo "roll or stay"
read choice
if [ $choice == r ]; then

die=$(($RANDOM%6+1))

elif [ $die -eq 1 ]; then
p1s=$(echo "$p1s-$count" |bc)
echo "You rolled a 1. Your score is $p1s"
echo "$p2 turn now."
sleep 1
count=0
pt=2

elif [ $die -gt 1 ]; then
p1s=$(echo "$p1s+$die" |bc)
count=$(echo "$count+$die" |bc)
echo "You rolled a $die. Your score is $p1s"
pt=1

else

if [ $choice == s ]; then
echo "Okay $p1 your score is $p1s"
echo "$p2 turn now"
sleep 1
count=0
pt=2

else
if [ $p1s -gt 99 ]; then
echo "$p1 won. $p2 lost"
echo "would you like to play again?"
read again
elif [ $again  yes ]; then
echo "Okay one second."
sleep 1
clear
bash num.sh
elif [ $again == no ]; then
exit

else

pt=1
fi
fi
fi

done

不要担心他们不是第二个玩家的第二个。我把它删掉了,因为它与玩家二的代码完全相同。

样本输入/输出

Player 1 name?
guy1
Player 2 name?
guy2
Okay guy1 and guy2. guy1 will go first
roll or stay
r
roll or stay
rr
(standard_in) 1: parse error
You rolled a 5. Your score is 5
roll or stay
roll
(standard_in) 1: parse error
You rolled a 5. Your score is 10
roll or stay
s
(standard_in) 1: parse error
You rolled a 5. Your score is 15
roll or stay
4

2 回答 2

4

好的,关于您的代码的一些评论。

  • 由于缺少缩进,这真的很难阅读。嵌套事物时,缩进嵌套的内容。使用缩进,您可以查看循环的开始和结束位置、哪些代码属于哪个 if/else 等。
  • 在 bash 中,您应该始终引用变量以避免意外扩展。例如,如果有人输入星号 ( *) 而不是“r”,会发生什么情况?你的if陈述会做奇妙而神秘的事情。
  • 您使用错误的运算符。在 bash 中,使用带有 的单方括号if,将字符串等效性与单个等号 ( =) 进行比较,而不是双等号。如果你想要数值相等,你有-eq. 尽管您可能想使用双方括号查看 bash 的扩展测试。(有关详细信息,请查看手册页。)
  • 尽量不要将外部工具用于 bash 可以自己完成的事情。 bc例如,整数算术不需要。

所以......大家都说,这是你的一个代码段,重写了一点。

while [ "$pt" -eq 1 ]; do

    read -p "Roll or stay (r/s)? " choice

    if [ "$choice" = r ]; then

        die=$(($RANDOM%6+1))

    elif [ "$die" -eq 1 ]; then

        p1s=$((p1s - count))
        echo "You rolled a 1. Your score is $p1s"
        echo "$p2 turn now."
        sleep 1 
        count=0 
        pt=2    

    elif [ $die -gt 1 ]; then

        p1s=$((p1s + die))
        count=$((count + die))
        echo "You rolled a $die. Your score is $p1s"
        pt=1    

    else

请注意,我并没有就您的程序逻辑是否合理做出任何声明。

到底是num.sh什么?那很重要么?

于 2012-11-09T03:37:00.577 回答
0

在查看了正确缩进的代码之后(参见ghoti的重写代码段),我看到顶层 if 块是

if [ $choice == r ]; then
    die=... #roll the die
elif [ $die -eq 1 ]...
elif [ $die -gt 1 ]...
else
    do something...
fi

问题是,如果[ $choice == r ]是真的,您将掷骰子并跳过其余的elif-else条目。所以你将不做任何事情就进入下一个迭代(除了掷骰子)

解决此问题的一种方法是检查$choice$die作为单独的if块,即

if [ $choice == r ]; then
    #roll the die
else
    #break or something...
fi

if [ $die -eq 1 ]; then
    #do something
elif the rest of $die-related checks  
于 2012-11-09T07:12:40.177 回答