Tell us what’s happening:
Tests For returning user and correct guess won’t pass, even though everything works fin e in the terminal.
Your code so far
#!/bin/bash
PSQL="psql --username=freecodecamp --dbname=number_guess -t --no-align -c"
# -- GET USER --
while true; do
echo "Enter your username:"
read USERNAME
# if more than 22 chars,
if [ ${#USERNAME} -gt 22 ]; then
echo "Your username can be no more than 22 characters"
elif [[ -z $USERNAME ]]
then
echo "Username cannot be blank."
else
break
fi
done
USER_DATA=$($PSQL "SELECT games_played, best_game FROM users WHERE username = '$USERNAME'")
if [[ -z $USER_DATA ]]
then
echo -e "\nWelcome, $USERNAME! It looks like this is your first time here."
# create new user in db
NEW_USER=$($PSQL "INSERT INTO users(username, games_played) VALUES('$USERNAME', 0);")
else
IFS="|" read GAMES_PLAYED BEST_GAME <<< "$USER_DATA"
echo -e "\nWelcome back, $USERNAME! You have played $GAMES_PLAYED games, and your best game took $BEST_GAME guesses."
fi
# Generate a random number between 0 and 1000
SECRET_NUMBER=$(( 0 + RANDOM % 1000 ))
TURN_PROMPT() {
if [[ $1 ]]
then
echo -e "\n$1"
else
echo "Guess the secret number between 1 and 1000:"
fi
read GUESS
}
#start game
TURN_PROMPT "Guess the secret number between 1 and 1000:"
# -- BEGIN LOOP --
NUMBER_OF_GUESSES=0
while true
do
# if not an integer,
if [[ ! $GUESS =~ ^[0-9]+$ ]]
then
TURN_PROMPT "That is not an integer, guess again:"
# don't increment NUMBER_OF_GUESSES here
continue
fi
# Convert GUESS to a number so a string such as '9p' won't error out
GUESS_NUM=$(echo $GUESS | grep -E '^[0-9]+$')
if [[ $SECRET_NUMBER -lt $GUESS_NUM ]]
then
(( NUMBER_OF_GUESSES++ ))
TURN_PROMPT "It's lower than that, guess again:"
elif [[ $SECRET_NUMBER -gt $GUESS_NUM ]]
then
(( NUMBER_OF_GUESSES++ ))
TURN_PROMPT "It's higher than that, guess again:"
elif [[ $SECRET_NUMBER -eq $GUESS_NUM ]]
then
(( NUMBER_OF_GUESSES++ ))
break
fi
done
# if guesses < best_game, update best game variable to guesses
if [[ -z $BEST_GAME ]] || [[ $NUMBER_OF_GUESSES -lt $BEST_GAME ]]
then
BEST_GAME=$NUMBER_OF_GUESSES
fi
# save new stats
UPDATE_GAMES_PLAYED=$($PSQL "UPDATE users SET games_played = games_played + 1, best_game = '$BEST_GAME' WHERE username = '$USERNAME'")
# print final output
echo -e "\nYou guessed it in $NUMBER_OF_GUESSES tries. The secret number was $SECRET_NUMBER. Nice job!"
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36
Challenge Information:
Number Guessing Game - Build a Number Guessing Game