I can’t seem to pass one check mark for this problem. Here it is: If that username has been used before, it should print Welcome back, <username>! You have played <games_played> games, and your best game took <best_game> guesses.
, with <username>
being a users name from the database, <games_played>
being the total number of games that user has played, and <best_game>
being the fewest number of guesses it took that user to win the game
This is my script:
#!/bin/bash
# variable to query database
PSQL="psql --username=freecodecamp --dbname=number_guess -t --no-align -c"
# prompt player for username
echo -e "\nEnter your username:"
read USERNAME
# check if the user already exists in the users table
USER_DATA=$($PSQL "SELECT user_id, COUNT(game_id), MIN(number_of_guesses) FROM games JOIN users USING (user_id) WHERE username='$USERNAME' GROUP BY user_id")
if [[ -z $USER_DATA ]]
then
# greet new player
echo -e "\nWelcome, $USERNAME! It looks like this is your first time here.\n"
# add player to the database
USER_ID_RESULT=$($PSQL "INSERT INTO users(username) VALUES ('$USERNAME') RETURNING user_id")
USER_ID_RESULT=$(echo "$USER_ID_RESULT" | awk '{print $1}')
GAMES_PLAYED=0
BEST_GAME=0
else
# extract user_id, games_played, and best_game from the result
USER_ID_RESULT=$(echo "$USER_DATA" | awk '{print $1}')
GAMES_PLAYED=$(echo "$USER_DATA" | awk '{print $2}')
BEST_GAME=$(echo "$USER_DATA" | awk '{print $3}')
# welcome back message with game statistics
echo -e "Welcome back, $USERNAME! You have played $GAMES_PLAYED games, and your best game took $BEST_GAME guesses.\n"
fi
# generate random number between 1 and 1000
SECRET_NUMBER=$(( RANDOM % 1000 + 1 ))
# variable to store number of guesses/tries
GUESS_COUNT=0
# prompt first guess
echo "Guess the secret number between 1 and 1000:"
read USER_GUESS
# loop to prompt user to guess until correct
until [[ $USER_GUESS == $SECRET_NUMBER ]]
do
# check guess is valid/an integer
if [[ ! $USER_GUESS =~ ^[0-9]+$ ]]
then
# request valid guess
echo -e "\nThat is not an integer, guess again:"
read USER_GUESS
# update guess count
((GUESS_COUNT++))
else
# check inequalities and give hint
if [[ $USER_GUESS -lt $SECRET_NUMBER ]]
then
echo "It's higher than that, guess again:"
else
echo "It's lower than that, guess again:"
fi
read USER_GUESS
# update guess count
((GUESS_COUNT++))
fi
done
# loop ends when guess is correct, so update guess
((GUESS_COUNT++))
# add result to game history/database
INSERT_GAME_RESULT=$($PSQL "INSERT INTO games(user_id, secret_number, number_of_guesses) VALUES ($USER_ID_RESULT, $SECRET_NUMBER, $GUESS_COUNT)")
# winning message
echo "You guessed it in $GUESS_COUNT tries. The secret number was $SECRET_NUMBER. Nice job!"
Can anyone help me in terms of my code? Thank you