Second Python Project: Number Guessing Game

Before starting the project assignment, I organized the requirements for the assignment in a notepad.

Requirements for the Number Guessing Game:

1. Guess a number between 1 and 100.
2. Choose a difficulty level: 'Easy' or 'Hard'.
3. If the 'Hard' difficulty is chosen, the player is allowed only 5 attempts to guess the number.
4. After the player inputs a guessed number, if it is not correct, provide feedback on whether the guess is too high or too low.
5. Prompt the player to guess again and indicate how many attempts are remaining.
6. When the player guesses the number correctly, end the game and display a prompt asking if they want to play again.

 

My Code

import logo
import random
import os

easy = 10
hard = 5

def set_number():
    """ Computer choose random number """
    return random.randint(1, 100)

def set_level(level):
    """ User choose the level"""
    if level == "easy":
        print("You have 10 attempts")
        return easy
    elif level == "hard":
        print("You have 5 attempts")
        return hard
    else:
        print("Enter easy and hard correctly")
        return set_level(input("Choose a difficulty, Type 'easy' or 'hard': "))

def compare(user_number, computer_number):
    """Compare the user Number is right"""
    if user_number == computer_number:
        print("Win")
        return True
    elif user_number > computer_number:
        print("Too high")
    elif user_number < computer_number:
        print("Too low")
    return False

def attempt_count_down(attempts):
    attempts -= 1
    if attempts == 0:
        print("You have no attempts left.")
        print("You lose")
        return 0
    else:
        print(f"You have {attempts} attempts remaining.")
        return attempts

def startGame():
    print(logo)
    computer_number = set_number()
    print("I'm thinking of number between 1 and 100")
    level = input("Choose a difficulty, Type 'easy' or 'hard': ")
    attempts = set_level(level)

    game_over = False
    while attempts > 0 and not game_over:
        user_number = int(input("Make a guess: "))
        if compare(user_number, computer_number):
            game_over = True
        else:
            attempts = attempt_count_down(attempts)
            if attempts == 0:
                game_over = True

    play_again = input("Do you want to play again? Type 'yes' or 'no': ")
    if play_again == 'yes':
        os.system("cls" if os.name == "nt" else "clear")  # 'cls' for Windows, 'clear' for Unix
        startGame()
    else:
        print("Thanks for playing! Goodbye.")

startGame()

 

While writing the code, I discovered through online research that using the os.system() method in this way works on both Linux and Unix systems.

For my second project, the number guessing game, the code functioned as required.

Later, when I reviewed the code written by the teacher, I found that my code was 69 lines long, whereas the teacher’s code was only 51 lines.

There was a difference of 18 lines.

 

Teacher Code

from random import randint
from art import logo

EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5

#Function to check user's guess against actual answer.
def check_answer(guess, answer, turns):
  """checks answer against guess. Returns the number of turns remaining."""
  if guess > answer:
    print("Too high.")
    return turns - 1
  elif guess < answer:
    print("Too low.")
    return turns - 1
  else:
    print(f"You got it! The answer was {answer}.")

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

def game():
  print(logo)
  #Choosing a random number between 1 and 100.
  print("Welcome to the Number Guessing Game!")
  print("I'm thinking of a number between 1 and 100.")
  answer = randint(1, 100)
  print(f"Pssst, the correct answer is {answer}") 

  turns = set_difficulty()
  #Repeat the guessing functionality if they get it wrong.
  guess = 0
  while guess != answer:
    print(f"You have {turns} attempts remaining to guess the number.")

    #Let the user guess a number.
    guess = int(input("Make a guess: "))

    #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 guesses, you lose.")
      return
    elif guess != answer:
      print("Guess again.")
game()

 

 

There are clear differences between the teacher's code and my code:

1. Guess verification:
   - The teacher's code uses the `check_answer()` function to verify guesses and return the remaining turns.
   - My code uses the `compare()` function to verify guesses and manages attempt counts separately with the `attempt_count_down()` function.

2. Game ending conditions:
   - The teacher's code ends when the number of turns reaches 0 or the correct answer is guessed within the while loop.
   - My code uses a `game_over` variable to manage the game's end.

3. Random number generation:
   - The teacher's code directly imports `randint`.
   - My code imports the entire `random` module.

My code includes more exception handling for incorrect user inputs, considering the user's perspective. However, overall, the teacher's code is more concise and focused on the core game logic.

Moreover, when another programmer reads the code, the teacher's code logic is more easily understandable than mine.

I remember a professor's words from a college lecture:
"When studying coding, learn by recognizing the differences between your inadequate student-level code and clean code."

I believe that someday I will become someone who can write clean code proficiently.

'Python' 카테고리의 다른 글

Fourth Python Project: Turtle Racing Game  (0) 2024.08.04
Third Python Project: Quiz game  (1) 2024.08.03
Second Python Project: Number guessing game  (0) 2024.08.03
First Python Project: Blackjack  (1) 2024.07.20
Reason for studying python  (0) 2024.05.13