3
\$\begingroup\$

I am new and trying to learn programming and have been working on a battle simulator that I hope to eventually develop into a RPG game with characters, areas to explore, etc. I have been working on the battle between you and an enemy and have most of the base mechanics done however I would like to clean up and improve my code by reducing the need of if statements and I would like to begin learning and implementing classes and more OOP styles. However, making and using classes is a concept I seem to be struggling with, if anyone could look over my code and tell me how it looks now as is, how I can improve (please be nitpicky I don't mind), and help me to understand classes and how I can implement them to help take this game a step further. I really feel if I can figure out classes and how to utilize them I can really make this game and code great! Thank you for taking the time all feedback is appreciated!

#Name:Shane
#Date:3/28/2020
#Description:

# Imports random function for computer choice
import random


# Tracks users wins and losses each round
win_cnt = 0
losses_cnt = 0


# creates game function
def game_main():


    # Prompts user about game   
    print(user_name + " will face off against the computer!\nIn this duel you and the computer will face off by taking turns battling, the first to fall loses! Their are barricades to hide behind and ammo or potions laying around for you to grab! You and your opponents can only hold six (6) bullets and up to three (3) potions at a time! Remember to use nearby cover and to grab ammo and potions BEFORE you attack or heal!")

    # Creates variables needed for tracking computer and users health, ammo, and damage.
    global user_potion
    global com_potion
    user_potion = 0
    com_potion = 0
    global user_ammo
    global com_ammo
    user_ammo = 0
    com_ammo = 0
    user_heal = 10
    com_heal = 10
    user_atk = 10
    com_atk = 10
    user_HP = 30
    com_HP = 30

    # Battle loop that loops as long as both players health is above 0    
    while user_HP > 0 and com_HP > 0:
        # Prompts user to choose a move        
        user_move = get_user_move()

        # Uses random to generate a random integer between 1 and 3
        com_move = com_move_generator()

        # Branching if elif else statements that compare users and computers choice and decide outcome    
        # if user attacks and has at least 1 ammo
        if user_move == 1 and user_ammo > 0:
            user_ammo -= 1
            if random.randint(0,100) > 25:
                com_HP -= user_atk
                if com_move == 1 and com_ammo > 0:
                    com_ammo -= 1
                    if random.randint(0,100) > 50:
                        user_HP -= com_atk
                        print(user_name + " and the enemy both attack! You hit eachother! You now have " , user_HP , "HP and " , user_ammo , "ammo! The enemy has" , com_HP , "HP!")
                    else:
                        print("You and the enemy both attack! The enemy misses but you hit him! He now has ", com_HP , "HP and " , " ammo!")
                elif com_move == 2:
                    com_HP += 10
                    print("The enemy blocked your attack! You now have " , user_ammo , " ammo and he still has " , com_HP , "HP!")
                elif com_move == 3:
                    com_ammo += 1
                    print(user_name + " attacks as the enemy reloads! He now has " , com_HP , "HP!")
                elif com_move == 4:
                    com_potion -= 1
                    print("The enemy attempts to use a healing potion! But you hit him! He now has " , com_HP , "!")
                else:
                    com_potion += 1
                    print("The enemy grabs a health potion as you fire! You hit him! He now has " , com_HP , "HP!")

            # if user tries t fire with no ammo        
            else:
                if com_move == 1 and com_ammo > 0:
                    com_ammo -= 1
                    if random.randint(0,100) > 50:
                        user_HP -= com_atk
                        print("You missed and the enemy fires! You now have " , user_HP , "HP and " , user_ammo , "ammo!")
                    else:
                        print("You both miss! You now have " , user_ammo , " ammo!")
                elif com_move == 2:
                    print("You missed and the enemy took cover! You now have " , user_ammo , "ammo!")
                elif com_move == 3:
                    print("You missed and the enemy reloads!")
                elif com_move == 4:
                    com_HP += com_heal
                    print("You missed! The enemy uses a healing potion! He now has " , com_HP , "HP!")
                else:
                    com_potion += 1
                    print("You missed! The enemy quickly grabs a healing potion! You now have " , user_ammo , " ammo!")

        # If user attempts to attack with no ammo        
        elif user_move == 1 and user_ammo <= 0:
            if com_move == 1 and com_ammo > 0: 
                if random.randint(0,100) > 50:
                    user_HP = user_HP - com_atk
                    com_ammo -= 1
                    print("You must reload before attacking! The enemy fires! You now have" , user_HP , "HP!")
                else:
                    com_ammo -= 1
                    print("You must reload before attacking! The enemy fires but misses!")
            elif com_move == 2:
                print("You must reload before attacking! The enemy takes cover!")    
            elif com_move == 3:
                com_ammo += 1
                print("You must reload before attacking! The enemy reloads!")
            elif com_move == 4:
                com_HP = com_HP + com_heal
                com_potion -= 1
                print("You must reload before attacking! The enemy uses a health potion! He now has " , com_HP , "HP!")
            else:
                com_potion += 1
                print("You must reload before attacking! The enemy grabs a health potion!")

        # If user blocks    
        if user_move == 2:
            if com_move == 1 and com_ammo > 0:
                if random.randint(0,100) > 50:
                    com_ammo -= 1
                    print(user_name + " blocked the enemys attack! You still have " , user_HP , "HP!")
                else:
                    print("The enemy fires as you run for cover! His attack misses!")
            elif com_move == 2:
                print(user_name + " and the enemy both block!")
            elif com_move == 3:
                com_ammo += 1
                print(user_name + " finds cover as the enemy reloads!")
            elif com_move == 4:
                com_HP = com_HP + com_heal
                com_potion -= 1
                print(user_name + " runs for cover as the enemy uses a health potion! He now has " , com_HP , "HP!")
            else:
                com_potion += 1
                print("You run for cover as the enemy grabs a potion!")

        # If user reloads                
        if user_move == 3:
            user_ammo += 1
            if com_move == 1 and com_ammo > 0:
                if random.randint(0,100) > 50:
                    user_HP = user_HP - com_atk
                    com_ammo -= 1
                    print(user_name + " reloads as the enemy fires! He hits! You now have " , user_HP, "HP and " , user_ammo , " ammo!")
                else:
                    print("You reload as the enemy attacks! His attack misses! You know have" , user_ammo , " ammo!")
            elif com_move == 2:
                print(user_name + " reloads as the enemy finds cover! You now have " , user_ammo , " ammo!")
            elif com_move == 3:
                com_ammo += 1
                print(user_name + " and the enemy both reload! You now have " , user_ammo , " ammo!")
            elif com_move == 4:
                com_HP = com_HP + com_heal
                com_potion -= 1
                print("You reload as the enemy uses a health potion! He now has " , com_HP , "HP! You have " , user_ammo , " ammo!")
            else:
                com_potion += 1
                print("You reload as the enemy grabs a potion! You now have " , user_ammo , " ammo!")

        # If user uses health potion and has at least one
        if user_move == 4 and user_potion > 0:
            user_potion -= 1
            if com_move == 1 and com_ammo > 0:
                if random.randint(0,100) > 50:
                    com_ammo -= 1
                    print("You use a health potion as the enemy fires and hits! You have " , user_HP , "HP!")
                else:
                    user_HP = user_HP + user_heal
                    com_ammo -=1
                    print("You use a health potion as the enemy fires! They miss and you gain +10HP! You now have " , user_HP , "HP!")
            elif com_move == 2:
                user_HP = user_HP + user_heal
                print("The enemy runs for cover as you quickly drink a healing potion! You gain +10HP! You now have " , user_HP , "HP!")
            elif com_move == 3:
                user_HP = user_HP + user_heal
                com_ammo += 1
                print("The enemy reloads as you drink a healing potion! You now have" , user_HP , "HP!")
            elif com_move == 4:
                user_HP = user_HP + user_heal
                com_HP = com_HP + com_heal
                com_potion -= 1
                print("You and the enemy both drink healing potions! You now have " , user_HP , "HP and he has" , com_HP , "HP!")
            else:
                user_HP = user_HP + user_heal
                com_potion += 1
                print("You drink a healing potion and gain +10HP! You now have " , user_HP , "HP and" , user_potion , " potions! The enemy grabs a healing potion!")

        # If user tries to use potion but has none
        elif user_move == 4 and user_potion <= 0:
          if com_move == 1 and com_ammo > 0:
                if random.randint(0,100) > 50:
                    com_ammo -= 1
                    user_HP = user_HP - com_atk
                    print("You attempt to use a health potion but have none! The enemy fires and hits! You now have " , user_HP , "HP!")
                else:
                    com_ammo -=1
                    print("You attempt to use a health potion as the enemy fires! You have no more potions but their attack miss!")
          elif com_move == 2:
            print("The enemy runs for cover as you attempt to drink a healing potion! You have no potions!")
          elif com_move == 3:
            com_ammo += 1
            print("The enemy reloads as you reach for a healing potion! You have none!")
          elif com_move == 4:
            com_HP = com_HP + com_heal
            com_potion -= 1
            print("You are out of potions! The enemy quickly drinks a healing potion!")
          else:
            print("You attempt to drink a healing potion but have none! The enemy grabs a healing potion!")

        # If user grabs a potion
        if user_move == 5:
            user_potion += 1
            if com_move == 1 and com_ammo > 0:
                com_ammo -= 1
                if random.randint(0,100) > 50:
                    user_HP = user_HP - com_atk
                    print("You grab a potion as the enemy fires! He hits! You now have " , user_HP , "HP and " , user_potion , " potions!")
                else:
                    print("You grab a potion as the enemy fires! He misses! You now have " , user_potion , " potions!")
            elif com_move == 2:
                print("You grab a potion as the enemy runs for cover! You now have " , user_potion , " potions!")
            elif com_move == 3:
                com_ammo += 1
                print("You grab a healing potion as the enemy reloads!")
            elif com_move == 4:
                com_HP =  com_HP + com_heal
                com_potion -= 1
                print("You grab a potion a the enemy uses a potion! You now have " , user_potion , " potions and he has " , com_HP , "HP!")
            else:
                com_potion += 1
                print("You and the enemy both grab a potion! You now have " , user_potion , " potions!")

    # If user or computers health falls to 0 than game ends and prompts user to play again
    else:
        print("GAME OVER!")
        if com_HP <= 0 and user_HP <= 0:
            print("You killed eachother...")
            replay_game()
        elif com_HP <= 0:
            win()
            replay_game()   
        elif user_HP <= 0:
            losses()
            replay_game()


# Declaration of function to get users move and handle any exceptions 
def get_user_move():
    try:        
        user_move = int(input("What would you like to do? 1) Attack 2) Block 3) Reload 4) Heal 5) Grab Bandage(potion)?"))
    except ValueError:
        print("Invalid Input! Please enter a number!")
        return get_user_move()
    if user_move < 0 or user_move > 5:
        print("Invalid Input! Move must be 1-5")
        return get_user_move()
    elif user_move == 3 and user_ammo == 6:
        while user_move == 3:
            print("You cannot hold anymore ammo! Please try something else! 1)Attack 2)Block 4)Heal 5) Grab Potion?")
            return get_user_move()
    elif user_move == 5 and user_potion == 3:
        while user_move == 5:
            print("You cannot hold anymore potions! Please try something else! 1)Attack 2)Block 3)Reload 4)Heal?")
            return get_user_move()
    # Valid input
    else:
        return user_move


def com_move_generator():
    # Randomly generates computers move
    com_move = random.randint(1,5)
    # Logic to control computers decision and will loop if ammo or potion limit reached or attempts to use a potion with none
    if com_move == 3 and com_ammo == 6:
        while com_move == 3:
            return com_move_generator()
    elif com_move == 4 and com_potion == 0:
        while com_move == 4:
            return com_move_generator()
    elif com_move == 5 and com_potion == 3:
        com_move = random.randint(1,4)
    else:
        return com_move


# Declaration for replay_game function
def replay_game():
    try:
        # Prompts user to play again and saves value in variable game_loop    
        game_loop = input("Would you like to play again? (Y/N)")
    except ValueError:
        print("Invalid Input! Yes or No? (Y/N)")
        return replay_game()
    # If game_loop variable is equal to Y then replay if not end game    
    if game_loop == 'Y' or 'y':
        game_main()
    else:
        print("Thanks for playing!")


# Declaration for the win function    
def win():
# Declares variable win_cnt as global and increments value by +1
    global win_cnt
    win_cnt += 1
    print("You won! You have " , win_cnt , " wins and " , losses_cnt , " losses!") 


# Declaration of the the losses function
def losses():
# Declares variable losses_cnt as global and increments its value by +1
    global losses_cnt 
    losses_cnt += 1
    print("You lost and now have " , losses_cnt , " losses and " , win_cnt , " wins!")


if __name__ == '__main__':
    # Welcome user and prompt for their name
    print("Welcome to the duel!")
    user_name = input("What is your name? ")
    #game = Game(user_name)
    #game.start()
    # Begin game function
    game_main()
\$\endgroup\$
1
\$\begingroup\$

The first thing I would recommend is using triple-quotes to make the opening text display in a more manageable box of text instead of a single, long string. For example:

print(user_name + 'will face off against the computer!')
print()
print('''In this duel you and the computer will face off by taking turns 
battling, the first to fall loses! There* are barricades to hide behind 
and ammo or potions laying around for you to grab! You and your opponents 
can only hold six (6) bullets and up to three (3) potions at a time! 
Remember to use nearby cover and to grab ammo and potions BEFORE you 
attack or heal!''')

Now, to cut back on repeated information, I would add a whos_turn parameter to each of your functions, and program it so that the computer player takes actions through the same function, rather than having to type in every possible computer action for every possible player action. You can set random.randint(0, 1) to determine initiative each turn (will the computer chug that potion before or after I shoot?).

So, instead of one long game_main() function, you can separate it into functions based on each possible action, with a parameter determining whether it is the player or the computer performing the action. For example:

import random

def turn_order():
    initiative = random.randint(0,1)

def choose_actions(initiative)
    possible_actions =['ATTACK', 'RELOAD', 'GRAB', 'DRINK']
    player_action = ''
    computer_action = ''
    while player_action not in possible_actions:
        player_action = input('Do you want to ATTACK, RELOAD, GRAB a potion, or DRINK a potion? ').upper()
        print('You chose %s' % (player_action))

    if initiative == 0:     
        player_action = (player_action.upper())
        print('You chose to %s' % (player_action))
        if player_action == 'ATTACK':
            attack(player)
        elif player_action == 'RELOAD':
            reload(player)
        elif player_action == 'GRAB':
            grab(player)
        elif player_action == 'DRINK':
            drink(player)

    if initiative == 1:
        computer_action = random.choice(possible_actions)
        print(computer_action)
        print('The computer chose to %s' % (computer_action))
        if computer_action == 'ATTACK':
            attack(computer)
        elif computer_action == 'RELOAD':
            reload(computer)
        elif computer_action == 'GRAB':
            grab(computer)
        elif computer_action == 'DRINK':
            dring(computer)

def attack(attacker):


initiative = turn_order()
choose_actions(initiative)

and so on.

\$\endgroup\$
1
  • \$\begingroup\$ Nice answer! You could move the if player_action == 'ATTACK' into another function too, or use a dictionary to do ACTIONS[player_action](player). \$\endgroup\$ – Peilonrayz May 19 '20 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.