DEV Community

Mike Kameta
Mike Kameta

Posted on • Edited on

100 Days of Code: The Complete Python Pro Bootcamp for 2022 - Day 12 (Number Guessing Game)

Project 12 - The Number Guessing Game

from random import randint
from replit import clear
from art import logo

# Global scope
EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5

# Function to check users guess against answer
def check_answer(guess, answer, turn,):
  if guess > answer:
    print("Too high")
    return turn -1
  elif guess < answer:
    print("Too low")
    return turn -1
  else:
    print(f"You got it, the answer was {answer} ")

# Function to set difficulty
def set_difficulty():
  level = input("Choose a difficulty level. Type 'easy' or 'hard': ")
  if level == 'easy':
    return EASY_LEVEL_TURNS
  else:
    return HARD_LEVEL_TURNS

# Define game function
def play_game():
  print (logo)
  --Choosing a random number between 1 and 100
  print("Welcome to the Number Guessing Game")
  print("Choose a random number between 1 and 100: ")
  answer = randint (1, 100)
  # Print statement used for initial testing
  print(f"Psssst, the correct number is {answer}" )

  # Repeat the guesing functionality if the answer is wrong
  turns = set_difficulty()
  guess = 0
  while guess != answer:
    print(f"You have {turns} attempts remaing to guess the answer")

    # let the player guess a number
    guess = int(input("Guess again:"))

    # Track the number of turns and reduce by 1 if they get it wrong
    turns = check_answer(guess, answer, turns,)
    if turns == 0:
      print("You've run out of turns, You Lose")
      return
    elif guess != answer:
      print(f"Guess again:")
      clear()


play_game()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)