I have unsolvable problems with tasks:
- 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 - When the secret number is guessed, your script should print
You guessed it in <number_of_guesses> tries. The secret number was <secret_number>. Nice job!
and finish running
Here is my code:
#!/bin/bash
PSQL="psql --username=freecodecamp --dbname=number_guess -t --no-align -c"
RANDOM_NUMBER=$((1 + RANDOM % 1000))
COUNT=0
GAME_PLAY() {
echo "Guess the secret number between 1 and 1000:"
read GUESS
if [[ ! $GUESS =~ ^[0-9]+$ ]]; then
echo "That is not an integer, guess again:"
GAME_PLAY
else
COUNT=$((COUNT + 1))
if [[ $GUESS -gt $RANDOM_NUMBER ]]; then
echo "It's lower than that, guess again:"
GAME_PLAY
elif [[ $GUESS -lt $RANDOM_NUMBER ]]; then
echo "It's higher than that, guess again:"
GAME_PLAY
else
echo -e "You guessed it in $COUNT tries. The secret number was $RANDOM_NUMBER. Nice job!"
return
fi
fi
}
echo "Enter your username: "
read USERNAME
USER_NAME=$($PSQL "SELECT user_name FROM users WHERE user_name='$USERNAME'")
if [[ -z $USER_NAME ]]; then
echo -e "Welcome, $USERNAME! It looks like this is your first time here.\n"
else
GAME_COUNT=$($PSQL "SELECT COUNT(*) FROM users WHERE user_name='$USERNAME'")
BEST_GAME=$($PSQL "SELECT MIN(guess_num) FROM users WHERE user_name='$USERNAME'")
echo "Welcome back, $USERNAME! You have played $GAME_COUNT games, and your best game took $BEST_GAME guesses."
fi
GAME_PLAY
INSERT_STATUS=$($PSQL "INSERT INTO users(user_name,guess_num) VALUES('$USERNAME',$COUNT)")