Hi ! Rewrite, enhance and optimize the following game : import random

# Global variables for game state
health = 100          # Starting health
lives = 3             # Starting lives
score = 0             # Starting score
resources = {'food': 50, 'water': 50, 'gold': 20}  # Initial resources
reputation = 50      # Initial reputation (0-100)
inventory = []       # Player's inventory
allies = 0           # Number of allies

def main():
    global health, lives, score, resources, reputation, inventory, allies

    print("====================================================")
    print("Welcome to the Strategic Forest Adventure Game!")
    print("====================================================")
    print("You are Azul Doctor TENKHI, an adventurer seeking the legendary Treasure of Tenkhi.")
    print("You stand at the entrance of the enigmatic Dark Forest.")
    print("A voice echoes from within: 'I am <PRESIDIO_ANONYMIZED_PERSON>, guardian of this forest. Choose your path wisely!'\n")

    while lives > 0:
        choice = get_choice(
            "What will you do?",
            ["enter the forest", "manage resources", "check status", "quit"]
        )

        if choice == "enter the forest":
            enter_forest()
        elif choice == "manage resources":
            manage_resources()
        elif choice == "check status":
            check_status()
        elif choice == "quit":
            print("You decide to quit the adventure. Farewell!")
            break

        # Check health and lives
        if health <= 0:
            lives -= 1
            if lives > 0:
                print(f"\nYou have lost a life! Lives remaining: {lives}.")
                health = 100  # Reset health on life loss
                # Penalty for losing a life
                reputation -= 10
                score -= 30
                print("Reputation decreased by 10 and score decreased by 30 due to your setback.\n")
            else:
                print("\nGame Over! You have no lives left. Better luck next time!")
                break

def get_choice(prompt, options):
    options_lower = [option.lower() for option in options]
    while True:
        choice = input(f"{prompt} ({'/'.join(options)}) ").strip().lower()
        if choice in options_lower:
            return choice
        else:
            print(f"Invalid choice. Please choose from: {', '.join(options)}")

def enter_forest():
    global health, score, resources, reputation, allies
    print("\nYou step into the Dark Forest. The trees tower above you, and the path splits into two.")

    choice = get_choice("Which path will you take?", ["North Path", "South Path"])

    if choice == "north path":
        north_path()
    else:
        south_path()

def north_path():
    global health, score, resources, reputation, allies
    print("\nYou take the North Path. It's quiet and shadows linger.")

    event = random_event()
    if event == "ally":
        print("You encounter a fellow traveler willing to join you.")
        join = get_choice("Do you accept the ally?", ["yes", "no"])
        if join == "yes":
            allies += 1
            reputation += 5
            score += 20
            print("An ally joins your quest! Reputation increased by 5 and score by 20.\n")
        else:
            print("You decide to continue alone.\n")
    elif event == "resource_found":
        found = find_resources()
        if found:
            print("You found additional resources on the path.\n")
    elif event == "challenge":
        print("A wild beast appears!")
        outcome = battle()
        if outcome:
            print("You defeated the beast! Score increased by 50.\n")
            score += 50
        else:
            print("You were injured in the battle.")
            health -= 30
            print("Health decreased by 30.\n")
    else:
        print("Nothing significant happens on this path.\n")

def south_path():
    global health, score, resources, reputation, allies
    print("\nYou take the South Path. The area feels more alive with sounds of wildlife.")

    event = random_event()
    if event == "treasure":
        print("You stumble upon a hidden treasure chest!")
        open_chest = get_choice("Do you open it?", ["yes", "no"])
        if open_chest == "yes":
            gold_found = random.randint(20, 100)
            resources['gold'] += gold_found
            score += 40
            print(f"You found {gold_found} gold! Gold increased by {gold_found} and score by 40.\n")
        else:
            print("You leave the treasure chest untouched.\n")
    elif event == "trap":
        print("You fall into a hidden trap!")
        health -= 40
        print("Health decreased by 40.\n")
    elif event == "merchant":
        print("A wandering merchant offers you supplies.")
        trade = get_choice("Do you trade with the merchant?", ["yes", "no"])
        if trade == "yes":
            trade_with_merchant()
        else:
            print("You decide not to trade and continue your journey.\n")
    else:
        print("You enjoy the serene environment and move forward.\n")

def random_event():
    events = ["ally", "resource_found", "challenge", "nothing", "treasure", "trap", "merchant"]
    return random.choice(events)

def find_resources():
    global resources, score
    found_food = random.randint(10, 30)
    found_water = random.randint(10, 30)
    resources['food'] += found_food
    resources['water'] += found_water
    score += 10
    print(f"You gathered {found_food} food and {found_water} water. Resources updated.")
    return True

def battle():
    global reputation
    print("Engaging in battle...")
    outcome = random.choice([True, False])
    if outcome:
        reputation += 5
        return True
    else:
        reputation -= 5
        return False

def trade_with_merchant():
    global resources, score
    print("The merchant offers you two deals:")
    deal = get_choice("Choose your deal", ["trade food for water", "trade gold for health"])
    if deal == "trade food for water":
        if resources['food'] >= 20:
            resources['food'] -= 20
            resources['water'] += 30
            score += 15
            print("Traded 20 food for 30 water. Score increased by 15.\n")
        else:
            print("Not enough food to trade.\n")
    else:
        if resources['gold'] >= 30:
            resources['gold'] -= 30
            health += 20
            score += 25
            print("Traded 30 gold for 20 health. Score increased by 25.\n")
        else:
            print("Not enough gold to trade.\n")

def manage_resources():
    global resources, health, score
    print("\n--- Manage Resources ---")
    print(f"Food: {resources['food']}")
    print(f"Water: {resources['water']}")
    print(f"Gold: {resources['gold']}")
    print("-------------------------")

    choice = get_choice("What would you like to do?", ["use food", "use water", "buy supplies", "back"])

    if choice == "use food":
        consume = get_choice("Consume food to gain health?", ["yes", "no"])
        if consume == "yes":
            if resources['food'] >= 10:
                resources['food'] -= 10
                health += 20
                score += 10
                print("Consumed 10 food, gained 20 health and 10 score.\n")
            else:
                print("Not enough food to consume.\n")
    elif choice == "use water":
        consume = get_choice("Consume water to maintain health?", ["yes", "no"])
        if consume == "yes":
            if resources['water'] >= 10:
                resources['water'] -= 10
                health += 10
                score += 5
                print("Consumed 10 water, gained 10 health and 5 score.\n")
            else:
                print("Not enough water to consume.\n")
    elif choice == "buy supplies":
        buy = get_choice("Buy supplies with gold?", ["yes", "no"])
        if buy == "yes":
            print("1. Purchase Food (+30)")
            print("2. Purchase Water (+30)")
            supply_choice = get_choice("Choose what to buy", ["food", "water"])
            if supply_choice == "food":
                if resources['gold'] >= 20:
                    resources['gold'] -= 20
                    resources['food'] += 30
                    score += 20
                    print("Bought 30 food for 20 gold. Score increased by 20.\n")
                else:
                    print("Not enough gold.\n")
            else:
                if resources['gold'] >= 20:
                    resources['gold'] -= 20
                    resources['water'] += 30
                    score += 20
                    print("Bought 30 water for 20 gold. Score increased by 20.\n")
                else:
                    print("Not enough gold.\n")
    else:
        print("Returning to main menu.\n")

def check_status():
    print("\n--- Player Status ---")
    print(f"Health: {health}")
    print(f"Lives: {lives}")
    print(f"Score: {score}")
    print(f"Reputation: {reputation}")
    print(f"Allies: {allies}")
    print("Resources:")
    for resource, amount in resources.items():
        print(f"  {resource.capitalize()}: {amount}")
    print("Inventory:", inventory if inventory else "Empty")
    print("---------------------\n")

    choice = get_choice("Do you want to use an item from your inventory?", ["yes", "no"])

    if choice == "yes":
        if inventory:
            print("Your Inventory:")
            for idx, item in enumerate(inventory, 1):
                print(f"{idx}. {item}")
            item_choice = input("Enter the number of the item to use: ").strip()
            if item_choice.isdigit():
                item_choice = int(item_choice)
                if 1 <= item_choice <= len(inventory):
                    use_item(inventory.pop(item_choice - 1))
                else:
                    print("Invalid item number.\n")
            else:
                print("Invalid input.\n")
        else:
            print("Your inventory is empty.\n")

def use_item(item):
    global health, resources, score
    print(f"Using {item}...")
    if item == "healing potion":
        health += 50
        score += 30
        print("Health increased by 50 and score by 30.\n")
    elif item == "elixir":
        resources['water'] += 50
        score += 25
        print("Water increased by 50 and score by 25.\n")
    else:
        print("Nothing happens.\n")

def random_event():
    events = ["ally", "resource_found", "challenge", "nothing"]
    return random.choice(events)

if __name__ == "__main__":
    main()