Home > Enterprise >  [textRPG]How to keep random creating of class and class atrributes every time i run a program[Python
[textRPG]How to keep random creating of class and class atrributes every time i run a program[Python

Time:03-28

I am trying some text based rpg game as a beginner in python. But i am struggling to get done one thing.

If i use while loop to run program 5 times. So i want repeat killing monster but without saving his attributes. If you run this code, character kills a monster in couple of moves and appends his experience to himself and monster hp decreases to <= 0 and dies.

Looping whole program does not work, randomly created monster is still the same, i just want to create new monster with new random attributes every time i loop program. It is possible? I am new to this and can't figure it out at this moment. Some tips ?

Here is some code but without while loop: final output is to loop this menu and fight simulator to gain exp and items from random monsters.

import random
import time

# List of items to drop
normal_items = ['Copper ore', 'Apple', 'Animal skin', 'Stone', 'Feather', 'Rotten egg', 'Bag of sand', "Simple dagger", "Blue flower"]
rare_items = ['Energized wand', 'Staff of purity', 'Enhanced gloves', 'Adamant chest plate']
legendary_items = ['Crown of Immortality', 'Robe of fire-dragon']

drop_chance_dice = random.randint(1, 100)

# Simple drop chance function


def dice():

    if drop_chance_dice <= 70:
        random_choice = (random.choice(normal_items))
        print(f"You got: {random_choice} ")
    if 70 <= drop_chance_dice <= 98:
        random_choice = (random.choice(rare_items))
        print(f"You got: {random_choice} ")
    if 99 <= drop_chance_dice <= 100:
        random_choice = (random.choice(legendary_items))
        print(f"Congratulations! You got an legendary item: {random_choice}")
# Instances and mobs

rat_nest= ['Rat', 'Giant Rat', 'Leader of Rats']

northern_forest = ['Snake', 'Wolf', 'Witch']


# My Character Class
class YourCharacter:

    def __init__(self, intro, name, attack, exp, level, hp):
        self.intro = intro
        self.name = name
        self.attack = attack
        self.exp = exp
        self.level = level
        self.hp = hp


# Creating my character(preset)
my_character = YourCharacter("Your character \n", 'FroGres', 16, 0, 1, 100)

# Introduction
def introduction_of_player(my_character):
    print(f"{my_character.intro}")
    print(f"{my_character.name}")
    print(f"Attack: {my_character.attack}")
    print(f"Experience: {my_character.exp}")
    print(f"Level: {my_character.level}")
    print(f"HP: {my_character.hp}")

# Monsters class build
class Monster:

    def __init__(self, intro, name, attack, exp, level, hp):
        self.intro = intro
        self.name = name
        self.attack = attack
        self.exp = exp
        self.level = level
        self.hp = hp


# Monsters attributes    list of mobs (for testing - to be upgraded)
# rat nest
rat = Monster("You fight vs: \n", "Rat", random.randint(4, 6), random.randint(8, 14), random.randint(1, 3),
              random.randint(50, 100))
giant_rat = Monster("You fight vs: \n", "Giant Rat", random.randint(6, 8), random.randint(10, 18), random.randint(2, 4),
                    random.randint(80, 130))
rat_boss = Monster("You fight vs: \n", "Leader of Rats", random.randint(4, 6), random.randint(8, 14),
                   random.randint(1, 3),
                   random.randint(50, 100))

# northern forest
#Witch = Monster("You fight vs: \n", "Witch", random.randint(8, 12), random.randint(12, 20), random.randint(3, 6), random
               # .randint(120, 200))

list_of_mobs = [rat, giant_rat, rat_boss]

event_mob = random.choice(list_of_mobs)   # Random pick monster , USED in function
# Introduction of Monster

def introduction_of_monster_ratnest(list_of_mobs):
    print(f"{list_of_mobs.intro}")
    print(f"{list_of_mobs.name}")
    print(f"Attack: {list_of_mobs.attack}")
    print(f"Experience: {list_of_mobs.exp}")
    print(f"Level: {list_of_mobs.level}")
    print(f"HP: {list_of_mobs.hp}")

def escape_or_fight():

    take_input = input("[a]ttack or [r]un?")
    if take_input == 'a':
        return attack()
    if take_input == 'r':
        print("You run as fast as possible.. ")
        print("You returning to your hideout..")
    else:
        print("Something wrong")


# Menu of actions
def menu_dungs():
    asking = input("Where do you want to go?: 1.Rat Nest or 2.Northern Forest :")
    if asking == "1":
        print("You entering rat nest.. good luck!\n")
        time.sleep(1)
        print("Some ugly creature stays on your way!")
        print(f"{event_mob.name} is looking at you!")
        if event_mob == rat:
            introduction_of_monster_ratnest(rat)
            escape_or_fight()
        elif event_mob == giant_rat:
            introduction_of_monster_ratnest(giant_rat)
            escape_or_fight()
        elif event_mob == rat_boss:
            introduction_of_monster_ratnest(rat_boss)
            escape_or_fight()
        else:
            print("Something went horribly wrong.. Don't even ask..")

    elif asking == "2":
        print("You entering northern forest.. good luck!\n")
        print("Dungeon unavailable at this moment, try another one")
        pass
        # Not in use
    else:
        print("Try again and choose correct location\n")
        menu_dungs()

def attack():

    gain_exp = event_mob.exp   my_character.exp
    rounds = 0
    while event_mob.hp > 0:
        event_mob.hp = event_mob.hp - my_character.attack
        rounds  = 1
        print(f"You hit with: {my_character.attack} damage.  Enemy HP is {event_mob.hp}")
        print(f"Enemy HP after your attack is {event_mob.hp}", "\n")

    if event_mob.hp <= 0:
        print(f"{event_mob.name} has died..")
        print(f"It tok you: {rounds} moves to kill that creature! \n")
        print("Congratulations! Here is your loot")
        dice()
        print(f"You got: {event_mob.exp} experience from that fight.")
        print(f"Your experience is now: {gain_exp}")

menu_dungs()

I tried: to create new unique monster with new randomly created attributes every time i run program. I used while loop but monster is not "respawning"

I expect: Some sort of simulator, after i kill monster, program creates new one and my character gains experience and items every fight.

I wonder: If there is some method to makes this class unique every loop.

CodePudding user response:

Here is HOW-TO to achieve all goals in your question:

  1. each time generate monsters with different parameters
  2. respawn monsters

First you create 3 sepreate functions that would return a new monster - the class of returned value is always the same (Monster) but they return new instances on each call:

def get_rat():
    return Monster("You fight vs: \n", "Rat", ...)

def get_giant_rat():
    return Monster(...)

def get_rat_boss():
    reutrn Monster(...)

You will also need to modify how you select monsters. I would suggest to create list of functions - so instead of selecting a monster you select a function, that generates monster:

# This should replace the list_of_mob
list_of_mob_generators = [get_rat, get_giant_rat, get_rat_boss]

And the last - you should select monster on each loop interation in main menu (so the monster could respawn). The shortest way is to change your global variable:

event_mob = None  # we change event_mob initially to None - we will select in later

def menu_dungs():
    global event_mob  # this is new
    asking = input("Where do you want to go?: 1.Rat Nest or 2.Northern Forest :")
    if asking == "1":
        event_mob_generator = random.choice(list_of_mob_generators)  # get one of the functions
        event_mob = event_mob_generator()  # call the function to get monster

        print("You entering rat nest.. good luck!\n")
        time.sleep(1)
        print("Some ugly creature stays on your way!")
        print(f"{event_mob.name} is looking at you!")
        # and this condition has changed, since we do not have one instance of each monster anymore
        if event_mob.name == 'Rat':
            introduction_of_monster_ratnest(event_mob)
            escape_or_fight()
        elif event_mob.name == 'Giant Rat':
            introduction_of_monster_ratnest(event_mob)
            escape_or_fight()
        elif event_mob.name == 'Rat Boss':
            introduction_of_monster_ratnest(event_mob)
            escape_or_fight()
        else:
            print("Something went horribly wrong.. Don't even ask..")
    ... # and so on

and of course do not forget a while loop for main menu =)

while True:
    menu_dungs()

CodePudding user response:

Thanks for help, program works as i wanted but still shows me 8 yellow errors in attack() function. Cannot find reference 'hp' in 'None' etc. maybe because this event_mob = None ? Could you run this code and see what is going on ? very likely i did put something in wrong place..

import random
import time

# List of items to drop
normal_items = ['Copper ore', 'Apple', 'Animal skin', 'Stone', 'Feather', 'Rotten egg', 'Bag of sand', "Simple dagger", "Blue flower"]
rare_items = ['Energized wand', 'Staff of purity', 'Enhanced gloves', 'Adamant chest plate']
legendary_items = ['Crown of Immortality', 'Robe of fire-dragon']

drop_chance_dice = random.randint(1, 100)

# Simple drop chance function


def dice():

    if drop_chance_dice <= 70:
        random_choice = (random.choice(normal_items))
        print(f"You got: {random_choice} ")
    if 70 <= drop_chance_dice <= 98:
        random_choice = (random.choice(rare_items))
        print(f"You got: {random_choice} ")
    if 99 <= drop_chance_dice <= 100:
        random_choice = (random.choice(legendary_items))
        print(f"Congratulations! You got an legendary item: {random_choice}")
# Instances and mobs

rat_nest= ['Rat', 'Giant Rat', 'Leader of Rats']

#not in use
northern_forest = ['Snake', 'Wolf', 'Witch']


# My Character Class
class YourCharacter:

    def __init__(self, intro, name, attack, exp, level, hp):
        self.intro = intro
        self.name = name
        self.attack = attack
        self.exp = exp
        self.level = level
        self.hp = hp


# Creating my character(preset)
my_character = YourCharacter("Your character \n", 'FroGres', 16, 0, 1, 100)

# Introduction
def introduction_of_player(my_character):
    print(f"{my_character.intro}")
    print(f"{my_character.name}")
    print(f"Attack: {my_character.attack}")
    print(f"Experience: {my_character.exp}")
    print(f"Level: {my_character.level}")
    print(f"HP: {my_character.hp}")

# Monsters class build
class Monster:

    def __init__(self, intro, name, attack, exp, level, hp):
        self.intro = intro
        self.name = name
        self.attack = attack
        self.exp = exp
        self.level = level
        self.hp = hp


# Monsters getting functions
# rat nest
def get_rat():
    return Monster("You fight vs: \n", "Rat", random.randint(4, 6), random.randint(8, 14), random.randint(1, 3),
              random.randint(50, 100))
def get_giant_rat():
    return Monster("You fight vs: \n", "Giant Rat", random.randint(6, 8), random.randint(10, 18), random.randint(2, 4),
                    random.randint(80, 130))
def get_rat_boss():
    return Monster("You fight vs: \n", "Rat Boss", random.randint(4, 6), random.randint(8, 14),random.randint(1, 3),
                   random.randint(50, 100))

# northern forest
# def get_witch():
#   return Monster("You fight vs: \n", "Witch", random.randint(8, 12), random.randint(12, 20), random.randint(3, 6), random
               # .randint(120, 200))

list_of_mobs_generators = [get_rat, get_giant_rat, get_rat_boss]


def escape_or_fight():

    take_input = input("[a]ttack or [r]un?")
    if take_input == 'a':
        return attack()
    if take_input == 'r':
        print("You run as fast as possible.. ")
        print("You returning to your hideout..")
    else:
        print("Something wrong")


# Menu of actions
event_mob = None
def menu_dungs():
    global event_mob
    asking = input("Where do you want to go?: 1.Rat Nest or 2.Northern Forest :")
    if asking == "1":
        event_mob_generator = random.choice(list_of_mobs_generators)
        event_mob = event_mob_generator()
        def introduction_of_monster_ratnest(event_mob):
            print(f"{event_mob.intro}")
            print(f"{event_mob.name}")
            print(f"Attack: {event_mob.attack}")
            print(f"Experience: {event_mob.exp}")
            print(f"Level: {event_mob.level}")
            print(f"HP: {event_mob.hp}")

        print("You entering rat nest.. good luck!\n")
        time.sleep(1)
        print("Some ugly creature stays on your way!")
        print(f"{event_mob.name} is looking at you!")
        if event_mob.name == 'Rat':
            introduction_of_monster_ratnest(event_mob)
            escape_or_fight()
        elif event_mob.name == 'Giant Rat':
            introduction_of_monster_ratnest(event_mob)
            escape_or_fight()
        elif event_mob.name == 'Rat Boss':
            introduction_of_monster_ratnest(event_mob)
            escape_or_fight()
        else:
            print("Something went horribly wrong.. Don't even ask..")

    elif asking == "2":
        print("You entering northern forest.. good luck!\n")
        print("Dungeon unavailable at this moment, try another one")
        pass
        # Not in use
    else:
        print("Try again and choose correct location\n")


def attack():
    gain_exp = event_mob.exp   my_character.exp
    rounds = 0
    while event_mob.hp > 0:
        event_mob.hp = event_mob.hp - my_character.attack
        rounds  = 1
        print(f"You hit with: {my_character.attack} damage.  Enemy HP is {event_mob.hp}")
        print(f"Enemy HP after your attack is {event_mob.hp}", "\n")

    if event_mob.hp <= 0:
        print(f"{event_mob.name} has died..")
        print(f"It tok you: {rounds} moves to kill that creature! \n")
        print("Congratulations! Here is your loot")
        dice()
        print(f"You got: {event_mob.exp} experience from that fight.")
        print(f"Your experience is now: {gain_exp}")


while True:
    menu_dungs()

  • Related