UNIX数字猜测游戏 - 逻辑问题

时间:2012-03-27 15:49:07

标签: numbers logic ksh

我的UNIX猜数游戏存在逻辑问题。菜单系统工作正常(1个用于游戏,2个用于退出,否则防御性响应)。但是在游戏中我得到的输出如下:

  1. OPTIONS:
  2. (1。游戏)
  3. (2.退出)
  4. 输入数字1或2。
  5. 1
  6. 请输入你的猜测。
  7. 5
  8. pgm01 [43]:[5:找不到[没有这样的文件或目录]
  9. pgm01 [47]:[5:未找到[没有此类文件或目录]
  10. 耶!!! 5是正确的号码!!!
  11. 您的总尝试次数为0。
  12. 这是代码(FYI,这是在KSH shell中)。我猜我在某处有某种语法错误......

      #!/bin/ksh
      # CS2351 - UNIX Programming
      # Program 1
    
      x=$RANDOM%100+1
      tries=0
      guessInt=0
      userOption=0
    
      while ((1==1))
      do
         print "Welcome to the UNIX Number Guessing Game!"
         print "A random number between 1 and 20 has been selected."
         print "===========\nDirections: \n==========="
         print "1. Enter your guess. The program will tell you if it is high or low."
         print "2. The program will tell you if it is high or low."
         print "3. Change your guess."
         print "4. The computer will tell you how many guesses you had."
         print "=======\nOPTIONS\n======="
         print "1: Play \n2: Exit"
         print "Enter number 1 or 2."
    
         "Enter number 1 or 2."
    
         read userinput
         case "$userinput" in
    
         1)
            break;;
         2)
            print "Quitting program!!!"
            exit;;
         *)
            print "The input $userinput is invalid."
            print "Returning to main menu..."
            print "\n\n\n";;
         esac
      done
    
      print "Please enter you're guess."
      read guessInt
      while (($guessInt != "q"));
      do
         if [$guessInt -lt $x];
         then
            print "Your guess is too low, try again! (q to quit)."
            tries=tries+1
         elif [$guessInt -gt $x];
         then
            print "Your guess is too high, try again! (q to quit)."
            tries=tries+1
         else
            print "Yay!!! $guessInt is the right number!!!"
            break
         fi
      done
    
      print "Your total number of tries were $tries."
      exit
    

    对此问题的任何见解表示赞赏!

1 个答案:

答案 0 :(得分:1)

据我所知,你需要双括号作为条件,一些空格很重要。你需要这样的东西:

if [[ $guessInt -lt $x ]]; then

tries也应该从1开始,因为如果不先猜测你就无法获胜。

如果他们的猜测是错误的,你还应该在while循环中再次阅读guessInt,因为如果你第一次猜错了,它将永远重复(因为$guessInt的值不是在循环的迭代之间改变。)

看看these shell script syntax examples;它有很多bash的东西,但也有一些不错的ksh覆盖率。