A Word Guessing Game In Python

PHOTO EMBED

Sat Jul 15 2023 15:20:41 GMT+0000 (Coordinated Universal Time)

Saved by @pythonHub #python #python-hub #day11

import random
from os import system

# Word categories
categories = {
    "Coding": ["Python", "Variable", "Function", "Loop", "Algorithm", "Debugging", "Syntax", "Class", "Recursion", "Library"],
    "Gaming": ["Console", "Controller", "Quest", "Level", "Avatar", "Powerup", "Multiplayer", "Strategy", "Virtual", "Adventure"],
    "Movies": ["Action", "Comedy", "Thriller", "Drama", "Romance", "SciFi", "Fantasy", "Horror", "Animation", "Mystery"],
    "Travel": ["Beach", "Adventure", "Culture", "Explore", "Passport", "Destination", "Backpack", "Journey", "Sightseeing", "Vacation"]
}

# Get player name
player = input("Enter your name: ")

print()
print(f"\t\t\tWelcome to this word guessing game {player}.")
print("\t\t\tYou will get 10 chances to guess the word.")
print(f"\t\t\t\t\t\tAll The Best {player}")
print("\n\n")

# Print available categories
for i in categories.keys():
    print(f"{i}")

# Select category
category = input("Select category: ").title()
if category not in categories:
    print("Invalid category!")
    exit()

# Select a random word from the chosen category
word = random.choice(categories[category])

# Initialize guessed and wrong variables
guessed = len(word) * '_'
wrong = ""
chances = 10  # Total number of guesses

# Clear the console screen
system('cls')

# Display initial word with underscores
for i in word:
    print("_", end=" ")
print()
# Main game loop
while chances > 0:
    word = word.lower()
    guessed = guessed.lower()

    # Check if the player has guessed all the characters correctly
    if sorted(guessed) == sorted(word):
        print(f"Congrats {player}, you win!!")
        print(f"The correct word was, {word}")
        break

    # Ask the player to enter a character
    guess = input("Enter a character: ").lower()

    # Check if the guessed character is correct
    if guess in word:
        for i in range(len(word)):
            if word[i] == guess:
                tempg = list(guessed)
                tempg.pop(i)
                tempg.insert(i, guess)
                guessed = ''.join([elem for elem in tempg])
        
        # Display the current progress
        for i in range(len(word)):
            if word[i] == guessed[i]:
                print(word[i], end=" ")
            else:
                print("_", end=" ")
        
        print("\nYou are correct!!\n\n")
   
    # If the guessed character is incorrect
    elif guess not in word:
        wrong += guess
        print("\nYou are wrong!!\n\n")
        print(f"Chances left = {chances}")
        chances -= 1
        
# Player has used all the chances
if chances == 0:
    print(f"Alas {player}, You Lose!")
    print("Better luck next time...")
    print(f"The correct word was, {word}")
    print("Thanks for Playing, Have a nice day!")
content_copyCOPY