Tell us what’s happening:
I feel my code is working fine with all the test cases but somehow it doesn’t only two of them which generally print statements.
I’ve even copied the same test to not to miss spaces, yet there’s no success.
Your code so far
#!/bin/bash
PSQL="psql --username=freecodecamp --dbname=number_guess -t --no-align -c"
echo "Enter your username:"
read USER_NAME
\# Escape single quotes (basic SQL safety)
USER_NAME=$(echo "$USER_NAME" | sed "s/'/''/g")
\# Get user stats (single query)
RESULT=$($PSQL "
SELECT u.user_id, u.name, COUNT(g.game_id), MIN(g.number_of_guesses)
FROM users u
LEFT JOIN games g ON u.user_id = g.user_id
WHERE u.name = '$USER_NAME'
GROUP BY u.user_id, u.name;
")
if \[\[ -z $RESULT \]\]
then
\# New user
echo "Welcome, $USER_NAME! It looks like this is your first time here."
INSERT_RESULT=$($PSQL "INSERT INTO users(name) VALUES('$USER_NAME') RETURNING user_id ;")
USER_ID=$($PSQL "select user_id from users where name='$USER_NAME';")
else
\# Existing user -> parse values
IFS="|" read USER_ID NAME TOTAL_GAMES BEST_GAME <<< "$RESULT"
echo "Welcome back, $NAME! You have played $TOTAL_GAMES games, and your best game took $BEST_GAME guesses."
fi
GUESS_GAME() {
USER_ID=$1
SECRET_NUMBER=$(( RANDOM % 1000 + 1 ))
COUNT=0
echo "Guess the secret number between 1 and 1000:"
while true
do
read GUESS
\# Validate integer input
if ! \[\[ "$GUESS" =\~ ^\[0-9\]+$ \]\]
then
echo "That is not an integer, guess again:"
continue
fi
if \[\[ $GUESS -eq $SECRET_NUMBER \]\]
then
break
elif \[\[ $GUESS -gt $SECRET_NUMBER \]\]
then
COUNT=$((COUNT + 1))
echo "It's lower than that, guess again:"
else
COUNT=$((COUNT + 1))
echo "It's higher than that, guess again:"
fi
done
GAME_INSERT=$($PSQL "INSERT INTO games(user_id, number_of_guesses) VALUES($USER_ID, $COUNT);")
echo -e "You guessed it in $COUNT tries. The secret number was $SECRET_NUMBER. Nice job!"
\# Insert game result
}
GUESS_GAME $USER_ID
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:148.0) Gecko/20100101 Firefox/148.0
Challenge Information:
Build a Number Guessing Game - Build a Number Guessing Game
