Hello freeCodeCampers,
So I decided to give this incredibly hard project another try after a few months. Now, I’m absolutely sure that this script that I have created passes all of the tests – I tested and re-tested… yet I only got as far as “Your script should randomly generate a number that users have to guess”.
Here’s my code right here:
#!/bin/bash
MAX=1000
MIN=1
GUESSES=0
SECRET_NUMBER=$((RANDOM % (MAX - MIN + 1) + MIN))
PSQL="psql --username=freecodecamp --dbname=number_guess -t --no-align -c"
read -p "Enter your username:" USERNAME
USERNAME_EXISTS=$($PSQL "SELECT username FROM users WHERE username = '$USERNAME';")
if [[ -z $USERNAME_EXISTS ]]; then
INSERT_USERNAME=$($PSQL "INSERT INTO users (username, best_game, games_played) VALUES ('$USERNAME', 0, 0);")
echo "Welcome, $USERNAME! It looks like this is your first time here."
else
BEST_GAME=$($PSQL "SELECT best_game FROM users WHERE username = '$USERNAME'")
GAMES_PLAYED=$($PSQL "SELECT games_played FROM users WHERE username = '$USERNAME'")
echo "Welcome back, $USERNAME! You have played $GAMES_PLAYED games, and your best game took $BEST_GAME guesses."
fi
read -p "Guess the secret number between 1 and 1000:" GUESS
until [[ $GUESS -eq $SECRET_NUMBER ]]
do
if [[ $GUESS =~ ^-?[0-9]+$ ]]; then
if [[ $GUESS -lt $SECRET_NUMBER ]]; then
read -p "It's higher than that, guess again:" GUESS
((GUESSES++))
else
read -p "It's lower than that, guess again:" GUESS
((GUESSES++))
fi
else
read -p "That is not an integer, guess again:" GUESS
fi
done
((GUESSES++))
((GAMES_PLAYED++))
if [[ $BEST_GAME -eq 0 || $GUESSES -lt $BEST_GAME ]]; then
UPDATE_BEST_GAME=$($PSQL "UPDATE users SET best_game = $GUESSES, games_played = $GAMES_PLAYED")
else
UPDATE_GAMES_PLAYED=$($PSQL "UPDATE users SET games_played = $GAMES_PLAYED")
fi
echo "You guessed it in $GUESSES tries. The secret number was $SECRET_NUMBER. Nice job!"
When I ran this code through ChatGPT just to see if it would say all of the tests would pass, it said that it did. Wait a second… did I forget the line breaks?