Find the answer to your Linux question:
Results 1 to 4 of 4
Hey everyone, I am trying to figure out the below script. I have to create a number guessing game which creates a random number (did that) and then it will ...
  1. #1
    Just Joined!
    Join Date
    Jan 2011
    Posts
    2

    Number game Bash script

    Hey everyone,

    I am trying to figure out the below script. I have to create a number guessing game which creates a random number (did that) and then it will tell you if the number is to low or to high or correct. Also to create a counter on how many attempts it took for you to reach that guess. I am halfway there, I keep getting an error that it just keeps saying "The number is smaller than your guess" no matter what I type in. Not sure how to make a counter in this script. Any help most appreciated!!!

    #!/bin/bash
    clear
    RANGE=60
    num=$RANDOM
    let "num %= $RANGE"
    counter=0
    guess=-1
    while [ " $guess" != "$num" ]
    do
    echo -n "I am thinking of a number between 1 and 60. Enter your guess:"
    read guess
    if [ "$guess" = "" ]
    then
    echo "Please enter a number."
    elif
    [ "$guess" = "$num" ]
    then
    echo "$guess is the correct answer!"
    elif
    [ "$guess" -gt "$num" ]
    then
    echo "The secret number is greater than your guess. Try again."
    else
    echo "The secret number is smaller than your guess. Try again."
    fi
    done
    ~

  2. #2
    Linux User
    Join Date
    Jan 2005
    Location
    Saint Paul, MN
    Posts
    262
    This looks like homework, we do not do assignments for people.

  3. #3
    Just Joined!
    Join Date
    Dec 2010
    Location
    India
    Posts
    45
    in your code messages are wrong reverse them .
    echo "The secret number is greater than your guess. Try again."
    else
    echo "The secret number is smaller than your guess. Try again."
    for e.g ig random no. generated is 40 . and you guess is 39 it will print
    The secret number is greater than your guess. Try again which is reverse .
    just echo the numbers in your script and debug it .

    and regarding counter u can implement that using for loop .

  4. #4
    Just Joined! cfajohnson's Avatar
    Join Date
    May 2007
    Location
    Toronto, Canada
    Posts
    52

    Please put code inside code tags:
    Code:
    clear
    RANGE=60
    num=$RANDOM
    let "num %= $RANGE"

    Code:
    num=$(( $RANDOM % $RANGE + 1 ))
    Code:
    counter=0
    guess=-1
    while [ " $guess" != "$num" ]

    There should be no space after the quotes:
    Code:
    while [ "$guess" != "$num" ]
    Then fix the logic as pointed out by the previous poster.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...