How do I get a return out of a nested IF statement inside a function?

I’m working myself through this game in exercise 36

I have a function which contains a while loop and then when the while loop finishes it goes to an if statement to see if the player won the game or not.
If the player loses, I’m trying to have a counter that subtracts 1 from the live variable.
If the player wins, I’m trying to set the Villain_dead variable = True

I can’t figure out how to get a return out from the nested IF statement inside the game function.
Is this possible or am I going around it in the entirely wrong way?

def game(opponent):
    villain_choice = ['Scissor', 'Rock', 'Paper']
    my_options = ['1) Scissor', '2) Rock', '3) Paper']
    my_choice = ['Scissor', 'Rock', 'Paper']
    round_current = 0
    win_current = 0
    lost_current = 0
    opponent_name = opponent

    print('Lets go. Best out of 3.')

    while win_current < 3 > lost_current:
        print('\nYour options are:')
        #make a for loop to print all the options from my_options list
        for x in my_options:
            print(x)

        print("What's your move?")
        choice = input('> ')

        if choice == "1":
            #randomised opponents move with random.choice() from the villain_choice list
            villain_move = random.choice(villain_choice)
            #shows what I chose and pics it out of my_choice list - the first option in a list is always 0
            print("\nYou chose:", my_choice[0],"\nVillain chooses: ", villain_move )

            #Makes 3 variables that is filled in from a return in game_rules.
            win, round, lost = game_rules(my_choice[0], villain_move)

            #Adds a 1 to every win a 1 to every lost and a 1 to every round.
            win_current += win
            round_current += round
            lost_current += lost
            print(f"You've won: {win_current}\nLost: {lost_current}\nRound: {round_current}")

        elif choice == "2":
            villain_move = random.choice(villain_choice)
            print("You chose", my_choice[1] )
            print("Villain chooses: '", villain_move,"'")

            win, round, lost = game_rules(my_choice[1], villain_move)
            win_current += win
            round_current += round
            lost_current += lost
            print(f"You've won: {win_current}\nLost: {lost_current}\nRound: {round_current}")
        elif choice == "3":
            villain_move = random.choice(villain_choice)
            print("You chose", my_choice[2] )
            print("Villain chooses: '", villain_move,"'")

            win, round, lost = game_rules(my_choice[1], villain_move)
            win_current += win
            round_current += round
            lost_current += lost
            print(f"You've won: {win_current}\nLost: {lost_current}\nRound: {round_current}")
        else:
            print("Not sure what that means")

    #print('While = True - loop finised')
    if win_current>2:
        print(f"You lucky bastard you pulled it off!\nThe {opponent_name} is dead")
        print("Lets fo back to the cross road")
        return True
        where_to_go(opponent_name, dead)


    elif lost_current>2:
        print(f"You're donzo.\nThe {opponent_name} fucked you up")
        print("You'll have to start over!")
    else:
        print("Something is wrong here")

Villain_dead=False
lives = 3

def game('Villain')

Hello @ktrager

I found one error while reading through the code.
At the last row you have define the main function again instead of just calling it.

def main(‘Villain’)

should be:

main(‘Villain’)

I used pdb to step through the code.
The debugger told me that: ‘game_rules is not defined’.
It’s not in this code. But I found that function in another post of yours.
How do they connect? Will you import one of them?

I have a suggestion.
Have a look at my code for a rock, scissor, paper game
(I don’t know the english name for this game)
It does not do all of what your game do.
But you can copy from this if you want and add the funtionality you want in your game.

from random import randint
import random

computer_choices = {1:'rock', 2:'paper', 3:'scissor'}
win_loose = [('scissor','paper'), ('rock','scissor'), ('paper','rock')] 
value = random.randint(1,3)

def scissor_game():
    players_points = 0
    computers_points = 0
    while True:
        rand = computer_choices.get(random.randint(1,3))
        players_choice = input('your choice >' )
        game = (players_choice, rand)
        print('-' * 30)
        print('computer choices', rand)
        print('-' * 30)
        if players_choice ==rand:
            print('even')
            print('*' * 30)
        elif game in win_loose:
            print('Player wins')
            print('+' * 30)
            players_points +=1
        else:
            print('computer wins')
            computers_points += 1
            print('-' * 30)
    
        print('player:', players_points, 'computer:', computers_points)
        print('%' * 30)
        if players_points >4:
            return False
        if computers_points >4:
            return False

scissor_game()

Hi @ulfen69

Thank you for this :pray: - your code does defiantly look more appetising than mine, I’ll study it and see where I can learn.

However I might have confused everyone. My Rock, Paper, Scissor game is working.
I just took the part of my code that I got a problem with, but can see know how that might be super confusing - sorry about that.
Below is my complete code that should not contain any bugs.

My game goes through 3 phases.

  1. START (All Villains are alive)
  2. CROSS ROAD (Decide what Villain to play Rock, Paper, Scissor against)
  3. VILLAINS (meet a villain and play rock paper scissor - for now I only got one)

Player starts at ‘START’, goes to the ‘CROSSROAD’ where he chooses what ‘VILLAIN’ to play, if he wins, he is send back to the ‘CROSS ROAD’ to choose another ‘VILLAIN’.
My problem is I can’t figure out to explain my code that once the player wins the villain has been conquered/dead and the player can’t go back and play against it again.

What I don’t know is how to through the sequences and once I hit a win change

villain1_dead = False

to

villain1_dead = True

MY FULL CODE (should not have any bugs):


from sys import exit
import random

def ressurect(togo):
    if togo > 1:
        print(f"""Welcome back to life.
        You now have {togo} lives left""")

    else:
        print(f"""Welcome back to life.
        You now have {togo} live left - it's now or never or you'll forever stay trapped.""")

def cross_road():
    print("You're now at a crossroad and there are 3 signs:\n1) Go left to the 'Valley of blunt scissors'\n2) Continue straight to the 'Canyon of crumbled paper'\n3) Right to the 'Mountain of broken rocks'")

    choice_count=0

    while True:
        choice = input('Where do you want to go?\n >')

        if choice == '1':
            print("You're on the way to the 'Valley of blunt scissors'\nI hope you brought some grit.")
            input()
            villain1()

        elif choice == '2':
            print("You're on the way to the 'Canyon of crumbled paper' - I hope you a sharp.")

        elif choice == '3':
            print("You're on the way to the 'Mountain of broken rocks' - I hope you are all wrapped up.")

        elif choice_count == 0 and (choice != '1' or choice != '2' or choice != '3'):
            print("I got no idea what means, try again.")
            choice_count += 1

        elif choice_count == 1 and (choice != '1' or choice != '2' or choice != '3'):
            print(f"For fuck sake {name}, learn to count to 3.")
            print("""Last warning!
            get it wrong again and you'll be dead""")
            choice_count += 1

        elif choice_count == 2 and (choice != '1' or choice != '2' or choice != '3'):
            exit()


def villain1():
    print("As you walk into the valley, you pass alot of cut-up paper.")
    print("It looks like the office malculator had a Christmas party.")
    print("Out of nowhere jumps a huge scissor.\nIt looks fucked up and blunt as hell but still big enough to cut you in two.")
    print("\nWhat do you want to do?\n1) Stay and fight for your life?\n2) Look what's in your backpack?\n3) Get the fuck out?")

    choice = input("> \n")

    if choice == "1":
        print('lets gamble')
        game('Fucked up scissor')

    elif choice == "2":
        print('your backpack is currently: ')
    elif choice == "3":
        print('Fair enough!')
        cross_road()



#This is the main structure of the game - which is linked to the 'rules' of the game.

def game(opponent):
    villain_choice = ['Scissor', 'Rock', 'Paper']
    my_options = ['1) Scissor', '2) Rock', '3) Paper']
    my_choice = ['Scissor', 'Rock', 'Paper']
    round_current = 0
    win_current = 0
    lost_current = 0
    opponent_name = opponent

    print('Lets go. Best out of 3.')

    while win_current < 3 > lost_current:
        print('\nYour options are:')
        #make a for loop to print all the options from my_options list
        for x in my_options:
            print(x)

        print("What's your move?")
        choice = input('> ')

        if choice == "1":
            #randomiseds opponents move with random.choice() from the villain_choice list
            villain_move = random.choice(villain_choice)
            #shows what I chose and pics it out of my_choice list - the first option in a list is always 0
            print("\nYou chose:", my_choice[0],"\nVillain chooses: ", villain_move )

            #Makes 3 variables that is filled in from a return in game_rules.
            win, round, lost = game_rules(my_choice[0], villain_move)

            #Adds a 1 to every win a 1 to every lost and a 1 to every round.
            win_current += win
            round_current += round
            lost_current += lost
            print(f"You've won: {win_current}\nLost: {lost_current}\nRound: {round_current}")

        elif choice == "2":
            villain_move = random.choice(villain_choice)
            print("You chose", my_choice[1] )
            print("Villain chooses: '", villain_move,"'")

            win, round, lost = game_rules(my_choice[1], villain_move)
            win_current += win
            round_current += round
            lost_current += lost
            print(f"You've won: {win_current}\nLost: {lost_current}\nRound: {round_current}")
        elif choice == "3":
            villain_move = random.choice(villain_choice)
            print("You chose", my_choice[2] )
            print("Villain chooses: '", villain_move,"'")

            win, round, lost = game_rules(my_choice[1], villain_move)
            win_current += win
            round_current += round
            lost_current += lost
            print(f"You've won: {win_current}\nLost: {lost_current}\nRound: {round_current}")
        else:
            print("Not sure what that means")

    #print('loop finised')
    if win_current>2:
        print(f"You lucky bastard you pulled it off!\nThe {opponent_name} is dead")
        print("Lets go back to the cross road")
        cross_road()


    elif lost_current>2:
        print(f"You're donzo.\nThe {opponent_name} fucked you up")
        print("You'll have to start over!")
    else:
        print("Something is wrong here")




# This is the underlaying game rules that explain what beats what.
# It returns a won round, lost lost round and
def game_rules(me, villain):
    if me == villain:
        print(f"Close call - you both chose {me}")
        print("It's an even")
        #Returns the a 0 win, +1 round and 0 lost because the game is even
        return 0, 1, 0 #win, round, lost

    elif me == 'Scissor' and villain == 'Paper':
        print("You win")
        return 1, 1, 0

    elif me == 'Scissor' and villain == 'Rock':
        print("You loose")
        return 0, 1, 1

    elif me == 'Rock' and villain == 'Scissor':
        print("You win")
        return 1, 1, 0

    elif me == 'Rock' and villain == 'Paper':
        print("You loose")
        return 0, 1, 1

    elif me == 'Paper' and villain == 'Rock':
        print("You win")
        return 1, 1, 0

    elif me == 'Paper' and villain == 'Scissor':
        print("You loose")
        return 0, 1, 1

    else:
        print('Something is wrong')


villain1_dead = False

print("You're trapped inside the brain of 12 year old girl, the only way out is to go around her brain find a way out.")
name = input("What's your name? \n > ")

cross_road()

I don’t know if I understand you right. Do you want to call a function if something is true? That’s possible.
I coded a little function to illustrate this. While the first if and elif exit the program after a print statement the else clause returns the function dead() and calls it, when exits the program.

def dead():
    print("your dead man!")

def decision(word):
    if word == "One":
        print("Funny")
    elif word == "Two":
        print("Funny again")
    else:
        dead()


decision("blablabla")

The output:

$ python3.6 test.py
your dead man!

Hej @DidierCH

Thanks for this.
I tried to code a smaller version of what I’m trying to do


def dead():
    print("your dead man!")

def opponent():

    opponent1_dead=False
    opponent2_dead=False

    print("Who do you want to play:\n1) Oppponent1\n2) Opponent2")
    choice = input('> ')

    if choice == '1' and opponent1_dead == False:
        play()
    elif choice == '2' and opponent2_dead==False:
        play()
    elif choice == '1' and opponent1_dead==True:
        print("Opponent1 is dead - Try again")
        opponent()
    elif choice == '2' and opponent2_dead==True:
        print("Opponent2 is dead - Try again")
        opponent()
    else:
        print('press 1 or 2')


def play():
    right_guess=0
    wrong_guess=0

    while right_guess<3>wrong_guess:

        choice=int(input('Write a number bigger than 10\n>'))

        if choice < 10:
            wrong_guess += 1
            print(f"You've now lost {wrong_guess} times.")

        elif choice > 10:
            right_guess += 1
            print(f"You've now won: {right_guess} times ")
        else:
            print("You've hit 10")

    if right_guess==3 :
        print("You win it all")
        #If player wins I want to set opponent1_dead=True or opponent2_dead=True depending on what input is chosen in opponent function
        opponent()

    else:
        print("You loose it all")
        dead()


opponent()

What I’m trying to do is if I choose to play opponent1 and I hit this

    if right_guess==3 :
        print("You win it all")
        #If player wins I want to set opponent1_dead=True or opponent2_dead=True, depending on what input is chosen in opponent function
        opponent()

It changes

opponent1_dead=False

to

opponent1_dead=True

Does that make sense?

I think you have two things you want at once:

  1. You want to have a variable like round_current be updated and accessible by two different functions.
  2. You want to exit a function from anywhere.

For number 1, do this:

round_current = 0

def fun1():
   global round_current
   round_current += 1

def fun2():
   global round_current
   round_current -= 1

For #2 you just return, anywhere, and it immediately exits the function and returns that:

def nestynasty():
   if x:
      while y:
         if j:
            return True
         else:
            return False

res = nestynasty()

The return exits the function immediately and returns whatever you gave as a value.

Let me know if that’s it.

2 Likes

Hi @zedshaw

Thanks for this.
It definitely answers some of my questions.
If I call global on a variable does that mean the system will.

However my main problem is I can’t figure out how to go and play against VillainX and if I win change the variable VillainX_dead = True back in the first first function.

I might have gone overboard, but I made this flowchart which I hope will easier explain what I’m trying to do.
Everything works until I come to the end where I have to go back to crossroad() and either change villain1_dead = True, villain2_dead = True or villain3_dead = True (depending on which route the player has taken.)

Yes, you did go overboard but that’s how you learn. You’ll need a global variable defined at the top that all the functions use to figure out what’s going on with the villain. Like this:

villian1_dead = False
villian2_dead = False

def villian1():
   global villian1_dead
   if villian1_dead:
      # do stuff when dead
   else:
      # do stuff 'cause alive
      # say villain dies:
      villian1_dead = True

def villian2():
   global villain1_dead
   # imagine villain2 can only be accessed if villain1 is dead
   if villain1_dead:
      # ok great they can play villain2
      # now imagine villain2 has died
      villain2_dead = True
   else:
      # oops, they need to kill villain1 send them back
      villain1()

Eventually you learn to use objects to keep this straight, but for now try to work this out. Also, it might help to scrap this code and start over with a clean file that only has the functions, the globals, and how people move around in them. No other mechanics, then use that to build out the rest of the game. Build the skeleton then put muscles and flesh on it.

1 Like

I’m getting this to work now - thank you.

I played around with global a little.

I tried to specify a variable inside a function and call it with a global inside another function which didn’t sit too well with Python.
Is the rule that global can only call variables if they have been specified outside functions?

1 Like

Hi @ulfen69

I’m just going through your code bit by bit trying to understand it.
And I have 2 questions I hope you can help me with.
I think they’re more about Python in general, and less so about your code.

from random import randint
import random

The way I’ve understood the import is random is the parent library to randint?
Isn’t it enough to import random randint is included?

rand = computer_choices.get(random.randint(1,3))

I tried this that also seems to work.

rand = computer_choices[random.randint(1,3)]

I tried to read up on what get() does, but it just seems to grab things from a ‘dictionary’.
Does get() do anything special in your case?

A huge caveat is I’m so new to programming that the things I’ve pointed out is probably just me not understanding python yet. But I thought it’s better to ask one time too many.

Hello @ktrager

Unfortunately I have no better explanation than this:
You have to import the module (random).
And you have to import the function from the module (randint).
Appearantly it wasnt neccesary to import the module first.
But I guess it looks better to do so.

When it comes to the get function I’ ll try my best to explain.

computer_choises is my dictionary with keys: (1, 2 and 3) and values: (rock, scissor and paper).
The get function takes one argument, lookup which key that matches this and then gives the value connected to this key.

In my case I got a argument from randint which give 1, 2 or 3.
This will return ’rock’ , ’scissor’ or ’paper’

Does this help you anything?

1 Like

Hey @ktrager that are to independent questions at once :slight_smile:

Imports
You are right, random IS the library or in this case the python module. There is a lot of discussion and confusion on how to import properly.

For a nice read up I recommend reading that real python article:

The official guide is in the PEP8 documentation of Python:

get()
You have different possibilities to retrieve a value from a dict (It seems that the random.randint function returns a dictionary).
The classic way to get a value from a dictionary is to use the square brackets dict = [some_key].
It is a cool and quick way but it has the drawback that you get an error when the “key” does not exist. With the get() method you can avoid that. You don’t get an error. See my little example (run it on your computer):

capitals = {"England": "London", "France": "Paris", "USA": "Washington"}

# get a value from a dictionary with the saver get() method
print(capitals.get("England"))
print(capitals.get("Sweden"))
print(capitals.get("Sweden", "1")) # You can provide a default value like "1" if the key does not exist

# get a value from a dictionary (classic way)
print(capitals["England"])
print(capitals["Sweden"])

For more information you can look here (official docs):
https://docs.python.org/3.1/library/stdtypes.html#mapping-types-dict
A more “beginner-friendly” explanation you can find here:

Or just googe for python dictionary get

1 Like

Thank you @ulfen69 & @DidierCH for both your explanation.

I need a few more import under my belt to fully understand it.

As far as I understand it the only thing that differs from the ‘traditional’ way og getting things out of a dictionary is get() has the option to give default value incase what’s being asked for is not in the dictionary?

Thank you @zedshaw, @ulfen69 & @DidierCH

I managed to make a game that works - and as a result has a much better understanding of alot of the Python functions.

The game is probably not going to be picked up by Blizzard any time soon, and I could tweak the usability more, but it’ll bring me down a rabbit hole I’ll not get out off again before in 3 months.
However I’m pretty chuffed with my outcome see below.

import random
import time
import sys


villain1_dead = False
villain2_dead = False

villain1_name = 'Evil Jim'
villain2_name ='Bad Bob'
villain3_name = 'Big bad Ben'

life = 3

def start():
    print("Ready to get going?")
    input()
    crossroad()


def crossroad():
    #print('Villain1 dead', villain1_dead)
    #print('Villain2 dead', villain2_dead)
    global life
    global villain1_dead
    global villain2_dead


    if villain1_dead == True and villain2_dead == True and life>0:
        drumroll()
        print("You'll have to play a Colonel Blotto game")
        drumroll()
        blotto()
    elif life>0:

        choice = input(f'Where to go?\n1) Go to {villain1_name}\n2) Go to {villain2_name}\n>>')

        if choice == '1' and villain1_dead==False:
            print('-'*30,f"\nYou're on the way to {villain1_name}\n",'-'*30)
            villain1()

        elif choice == '2' and villain2_dead==False:
            print('-'*30,f"\nYou're on the way to {villain2_name}\n",'-'*30)
            villain2()

        elif (choice == '1' and villain1_dead ==True) or (choice == '2' and villain2_dead ==True):
            print('The beast is dead - try someone else')
            crossroad()

        else:
            print('not sure what you want?')
            crossroad()
    else:
        print("YOU'RE GAME OVER\nYou'll have to start again")
        life=3
        villain1_dead=False
        villain2_dead=False
        start()



def villain1():
    print(f'You can see {villain1_name} in the distance' )
    #brings variable villain1_dead into the function
    global villain1_dead

    #first the scripts test if villain1 is dead
    if villain1_dead==False:
        #If not dead it prints 'Time to play'
        print(f"{'-'*30}\nTime to play")
        #Then it sets villain1_dead to whatever play() returns once played
        villain1_dead=stone_rock_scissor(villain1_dead, villain1_name)
        #Then it goes to crossroads
        crossroad()

    else:
        #If Villain1 is dead then it goes here and returns to crossroad()
        print(f"{'-'*30}\n{villain1_name} is dead - there is nothing to do here.\nGo back")
        crossroad()


def villain2():
    print(f'You can see {villain2_name} in the distance\n','-'*30 )
    global villain2_dead

    if villain2_dead==False:
        print(f"{'-'*30}\nTime to play")
        villain2_dead=stone_rock_scissor(villain2_dead, villain1_name)

        crossroad()

    else:
        print(f"{'-'*30}\n{villain1_name} is dead - there is nothing to do here.\nGo back")
        crossroad()

def play():

    return True

def stone_rock_scissor(state, name):
    global life
    #{} are used to define a dictionary.
    #: are used to attached the number to a string. Like a word is attached to a definition.
    #computer_choises[1]=rock
    choices = {1: 'rock', 2: 'paper', 3: 'scissor'}

    #Assigns a random number between 1 and 2 to value.
    value = random.randint(1,3)

    #This is winning sequences. Where Player will win.
    #Is used later in game variable to determine if its a win or loose
    win_sequence = [('rock', 'scissor'), ('paper', 'rock'), ('scissor', 'paper')]

    player_point = 0
    computer_point = 0

    while player_point<3>computer_point:
        #get() is used to take things out of python dictionaries
        #Takes random sample from computer_choice which is what the computer has chosen.

        #I could also use: rand = choices.get(random.randint(1,3))
        rand = choices[random.randint(1,3)]

        #My players_choice
        players_choice = input(f"1) {choices[1]}\n2) {choices[2]}\n3) {choices[3]}\nyour choice > ")

        #matches my choice with the 'choices-dictionary'
        #get() is used to take things out of dictionaries. In this case i converts my input to a number then it matches that number with the string in choices variable
        players_choice2 = choices.get(int(players_choice))
        game = (players_choice2, rand)
        print('-'*30)
        print('Computer chooses', rand)
        print('You chose', players_choice2)


        if players_choice2==rand:
            print('even')
            print('My points: ', player_point)
            print('Computer point: ', computer_point)
            print('-'*30)

        #in and not in is membership operators that tests whether a value or a variable is part of a sequence
        elif game in win_sequence:
            print('I win')
            player_point+=1
            print('My points: ', player_point)
            print('Computer point: ', computer_point)
            print('-'*30)
        else:
            print('I loose')
            computer_point+=1
            print('My points: ', player_point)
            print('Computer point: ', computer_point)
            print('-'*30)

    #once while loop = False
    if player_point>2:
        print('You win it all')
        return True

    else:
        print('You lost it all')
        life -=1
        crossroad()

def blotto():
    print(f"\t⓵ You have a hundred soldiers, and {villain3_name} have a hundred soldiers.\n\t⓶ Each has to allocate a their 100 soldier to 3 different battle fields.\n\t⓷ The person who wins the most battle fields will win it all.")

    player_soldiers = 100
    computer_soldier = 100
    round_allo = 1

    player_win = 0
    computer_win = 0


    while round_allo<3:

        if round_allo == 1:
            round1_allocation  = int(input("How many soldiers do you allocate in round ⓵ ?\n>"))
            if round1_allocation > player_soldiers:
                print(f"You only have {player_soldiers} soldiers left\n>")
            else:
                player_soldiers -= round1_allocation
                round_allo +=1

                computer1_allocation = random.randint(1,computer_soldier)
                #print(f'Computer chose: {computer1_allocation}')
                computer_soldier -= computer1_allocation

                if round1_allocation>computer1_allocation:
                    player_win +=1
                    round1_winner = 'You won'
                elif round1_allocation<computer1_allocation:
                    computer_win +=1
                    round1_winner = 'Computer won'
                else:
                    round1_winner = 'Every soldier got killed it was an even'

        if round_allo == 2:
            print(f'You now got {player_soldiers} left')
            round2_allocation = int(input("How many soldiers do you allocate in round ⓶ ?\n>"))
            if round2_allocation > player_soldiers:
                print(f"You only have {player_soldiers} soldiers left\n>")
            else:
                player_soldiers -= round2_allocation
                round_allo +=1

                computer2_allocation = random.randint(1,computer_soldier)
                #print(f'Computer chose: {computer2_allocation}')
                computer_soldier -= computer2_allocation

                if round2_allocation>computer2_allocation:
                    player_win +=1
                    round2_winner = 'You won'
                elif round2_allocation<computer2_allocation:
                    computer_win +=1
                    round2_winner = 'Computer won'
                else:
                    round2_winner = 'Every soldier got killed it was an even'

        if round_allo ==3:
            round3_allocation = player_soldiers
            computer3_allocation = computer_soldier
            print(f"You have {round3_allocation} soldiers left which you'll play on the last round")
            #print(f"Computer has {computer3_allocation} soldiers for the last battle field")

            if round3_allocation>computer3_allocation:
                player_win +=1
                round3_winner = 'You won'
            elif round3_allocation<computer3_allocation:
                computer_win +=1
                round3_winner = 'Computer won'
            else:
                player_win +=0
                computer_win +=1
                round3_winner = 'Every soldier got killed it was an even'




    print('ready see if you win or loose?')
    input()

    drumroll()
    print(f"You played: {round1_allocation} soldiers")
    print(f"{villain3_name} played {computer1_allocation}")
    print(f"{round1_winner}")

    input("ready for round ⓶ ?")
    drumroll()
    print(f"You played: {round2_allocation} soldiers")
    print(f"{villain3_name} played {computer2_allocation}")
    print(f"{round2_winner}")

    input("ready for round ⓷ ?")
    drumroll()
    print(f"You played: {round3_allocation} soldiers")
    print(f"{villain3_name} played {computer3_allocation}")
    print(f"{round3_winner}")

    time.sleep(0.3)
    print(f"that means you have won: {player_win} battles\nand the {villain3_name} has won: {computer_win} battles")

    drumroll()
    if player_win>computer_win:
        print("🎉🎉🎉🎉🎉🎉\nYOU ARE A BEAST")
    if player_win<computer_win:
        global villain1_dead
        global villain2_dead

        villain1_dead = False
        villain2_dead = False

        print("GAME OVER\nYou'll have to start over.")
        start()


    else:
        print("This is very rare you have won the same amount of battles. You'll have to do best out of 3 again")
        blotto()



def drumroll():
    text="🥁🥁🥁🥁🥁🥁🥁🥁\n"

    for l in text:
        sys.stdout.write(l)
        sys.stdout.flush()
        time.sleep(0.1)

start()

Hey @ktrager I like you’re game. First it’s nice to play and second you’re code looks clean and clear.

The get() method is often the best way to get data out of a dictionary because it does not throw an error if a key does not exist and you have a lot of possibilities to adjust the call to the dictionary, like the default value.

1 Like

Any time you want to know what something does you should look at the docs:

https://docs.python.org/3/library/stdtypes.html

Googling for something like this is tough but it’s .get on a dict type so I googled: python dict api

In this case the .get is a way of saying “get this key and if not give me None”. If you don’t do this, and it tries to get a key that doesn’t exist, then it will throw an exception.

2 Likes