Add number_guess.sh
This commit is contained in:
52
number_guess.sh
Normal file
52
number_guess.sh
Normal file
@@ -0,0 +1,52 @@
|
||||
#!/bin/bash
|
||||
PSQL="psql --username=freecodecamp --dbname=number_guessing_game -t --no-align -c"
|
||||
|
||||
NUMBER=$((1 + $RANDOM % 1000))
|
||||
|
||||
echo "Enter your username:"
|
||||
read USERNAME
|
||||
|
||||
USER_QUERY=$($PSQL "SELECT username, games_played, best_game FROM users WHERE username = '$USERNAME'")
|
||||
|
||||
if [[ -z $USER_QUERY ]]; then
|
||||
echo "Welcome, $USERNAME! It looks like this is your first time here."
|
||||
INSERT_USER=$($PSQL "INSERT INTO users(username) VALUES('$USERNAME')")
|
||||
BEST_GAME=""
|
||||
else
|
||||
GAMES_PLAYED=$(echo "$USER_QUERY"| cut -d'|' -f2)
|
||||
BEST_GAME=$(echo "$USER_QUERY"| cut -d'|' -f3)
|
||||
echo "Welcome back, $USERNAME! You have played $GAMES_PLAYED games, and your best game took $BEST_GAME guesses."
|
||||
fi
|
||||
|
||||
|
||||
GUESSES=1
|
||||
|
||||
echo "Guess the secret number between 1 and 1000:"
|
||||
read GUESS
|
||||
while [[ $GUESS -ne $NUMBER ]]; do
|
||||
|
||||
|
||||
if [[ ! $GUESS =~ ^[0-9]+$ ]]; then
|
||||
echo "That is not an integer, guess again:"
|
||||
read GUESS
|
||||
continue
|
||||
fi
|
||||
|
||||
if [[ $NUMBER -lt $GUESS ]]; then
|
||||
echo "It's lower than that, guess again:"
|
||||
((GUESSES++))
|
||||
else
|
||||
echo "It's higher than that, guess again:"
|
||||
((GUESSES++))
|
||||
fi
|
||||
|
||||
read GUESS
|
||||
done
|
||||
|
||||
echo "You guessed it in $GUESSES tries. The secret number was $NUMBER. Nice job!"
|
||||
|
||||
if [[ $GUESSES -lt $BEST_GAME || -z $BEST_GAME ]]; then
|
||||
UPDATE_USER=$($PSQL "UPDATE users SET best_game = $GUESSES WHERE username = '$USERNAME'")
|
||||
fi
|
||||
|
||||
UPDATE_USER=$($PSQL "UPDATE USERS SET games_played = games_played + 1 WHERE username = '$USERNAME'")
|
||||
Reference in New Issue
Block a user