How do I get a Different Random Choice When People Decided to Play Again? Python

Question:

I’m basically trying to get a different enemy every single time that people play/runs the code. For now, If I decided to play again the code keeps using the same values as before and I really want them to be different. Please help me. I’m New to using Python!

I left you the whole code of the program in case It helps you to help me. Thanks! I hope I will help others soon.

import random
items = []
enemy = random.choice(["Troll", "Pirate", "Gorgon", "Monster"])
weapons = random.choice(["Bow", "Axe", "Bazooka", "Sword"])


def print_pause(message_to_print):
    print(message_to_print)
    time.sleep(1)


def intro():
    print_pause("You find yourself standing in an open field, "
                "filled with grass and yellow wildflowers.")
    print_pause(f"Rumor has it that a {enemy} is somewhere around here, and "
                "has been terrifying the nearby village.")


def choice():
    while True:
        choice = input("Enter 1 to knock on the door of the house.n"
                       "Enter 2 to peer into the cave.n"
                       "What would you like to do?n"
                       "Please enter 1 or 2.n")
        if choice == '1':
            house()
        elif choice == '2':
            cave()
        else:
            print("Please enter 1 or 2.n")


def fight():
    print_pause(f"The {enemy} attacks you!")
    fight = input("Would you like to (1) fight or (2) run away?n")
    if fight == '1':
        if ({weapons}) in items:
            print_pause(f"As the {enemy} moves to attack, you unsheath "
                        f"your new {weapons}.")
            print_pause(f"The {weapons} of Ogoroth shines brightly in your "
                        "hand as you brace yourself for the attack.")
            print_pause(f"But the {enemy} takes one look at your shiny new "
                        "toy and runs away!")
            print_pause(f"You have rid the town of the {enemy}. "
                        "You are victorious!")
            play_again()
        else:
            print_pause(f"You feel a bit under-prepared for this, "
                        "what with only having a tiny dagger.")
            print_pause(f"You do your best...")
            print_pause(f"but your dagger is no match for the {enemy}.")
            print_pause(f"You have been defeated!")
            print_pause(f"G A M E   O V E R")
            play_again()

    elif fight == '2':
        print_pause("You run back into the field. Luckily, "
                    "you don't seem to have been followed.")
        choice()


def house():
    print_pause("You approach the door of the house.")
    print_pause(f"You are about to knock when the door "
                f"opens and out steps a {enemy}.")
    print_pause(f"Eep! This is the {enemy} house!")
    fight()


def cave():
    if ({weapons}) in items:
        print_pause("You've been here before, and gotten all "
                    "the good stuff. It's just an empty cave now.")
        print_pause("You walk back out to the field.")

    else:
        print_pause(f"You peer cautiously into the cave.")
        print_pause(f"It turns out to be only a very small cave.")
        print_pause(f"Your eye catches a glint of metal behind a rock.")
        print_pause(f"You have found the magical {weapons} of Ogoroth!")
        print_pause(f"You discard your silly old dagger and take "
                    f"the {weapons} with you.")
        print_pause(f"You walk back out to the field.")
        items.append({weapons})
    choice()


def play_again():
    while True:
        choice = input("Play again? [y|n]n")
        if choice == 'y':
            play_game()
        elif choice == 'n':
            print('Thanks for playing! Goodbye!')
            exit(0)
        else:
            print("(Please enter y or n.")


def play_game():
    intro()
    choice()

play_game()
Asked By: Luis Martinez

||

Answers:

enemy = You’re defining the variables storing your choices globally and there’s no part in the code changing them. I’d say the easiest way to fix the problem would be to move the assignment of those variable into a new method and upon starting the game, the method will be called.

Something along this:

import random
items = []
enemy = None
weapons = None 

def assign_random_choices():
  enemy = random.choice(["Troll", "Pirate", "Gorgon", "Monster"])
  weapons = random.choice(["Bow", "Axe", "Bazooka", "Sword"])

...

def play_game():
    assign_random_choices()
    intro()
    choice()

This will overwrite the variable (initiated empty with None) to be used in the game later on.

Answered By: white

The problem is that you’re only initialising your enemy once when the code initially runs. Therefore it doesn’t change its value when you only rerun the main game function, as the variable is defined outside the function. Instead you should probably initialise the enemy inside the fight() function, so every fight you have a unique enemy:

import random
items = []
weapons = random.choice(["Bow", "Axe", "Bazooka", "Sword"])

def fight():
    # Initialize the 'enemy' variable here, so it changes every fight.
    enemy = random.choice(["Troll", "Pirate", "Gorgon", "Monster"])
    print_pause(f"The {enemy} attacks you!")
    fight = input("Would you like to (1) fight or (2) run away?n")
    if fight == '1':
        if ({weapons}) in items:
            print_pause(f"As the {enemy} moves to attack, you unsheath "
                        f"your new {weapons}.")
            print_pause(f"The {weapons} of Ogoroth shines brightly in your "
                        "hand as you brace yourself for the attack.")
            print_pause(f"But the {enemy} takes one look at your shiny new "
                        "toy and runs away!")
            print_pause(f"You have rid the town of the {enemy}. "
                        "You are victorious!")
            play_again()
        else:
            print_pause(f"You feel a bit under-prepared for this, "
                        "what with only having a tiny dagger.")
            print_pause(f"You do your best...")
            print_pause(f"but your dagger is no match for the {enemy}.")
            print_pause(f"You have been defeated!")
            print_pause(f"G A M E   O V E R")
            play_again()

    elif fight == '2':
        print_pause("You run back into the field. Luckily, "
                    "you don't seem to have been followed.")
        choice()


Note, I only included the changed parts of the code for easier readability. You’ll still need to keep the other functions, otherwise it obviously won’t run.

Answered By: Otto Hanski

The issue is that by declaring the enemy variable at the top of the script it has global scope (that is, it is created when the script is first run and then never recreated) Note the same also applies to the weapons variable.

To fix this you just need to move the declaration into the function in which the variable is being used and then return it from that function so it can be reused for the duration of that game.

def load_game():
    weapons = random.choice(["Bow", "Axe", "Bazooka", "Sword"])
    enemy = random.choice(["Troll", "Pirate", "Gorgon", "Monster"])
    return weapons, enemy

 
def play_game():
    weapons, enemy = load_game()
    intro(enemy)
    choice(weapon, enemy)

You’ll then need to update your existing functions to take these variables:

def intro(enemy): 
    ...

def choice(weapon, enemy):
    ...

etc.

NB that items also currently has a global scope. You’ll also need to pass that around as a variable too (I’ll leave that for you to figure out).

Finally, this is just one way to tackle this (passing the variables into the functions), another population choice would be an object-oriented approach involving using a class instance to store the items. Enjoy!

Answered By: mdmjsh
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.