Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Random Number Repeating
#1
Hello everyone.
I am very new to Python and coding in general and like many people I am learning from a text adventure game. I have figured out the basics of the text adventure and I am now trying to expand functions inside of it. The below code works with the exception of the "random" number always being the same. I have read multiple posts about this but, I just don't understand what I am doing wrong. Can anyone assist me with this? Thank-you.

name = input("What is your name? ")
health = 10
monsterhealth = 10
import random
attack = (random.randint(0,4))


while monsterhealth > 0:
    action = input("1.Attack 2.Potion 3.Inquiry 4.Run ").lower()
    if action == "attack":
        print ("You attack dealing",attack, "damage")
        monsterhealth -= attack
        if monsterhealth <= 0:
            print ("The monster is slain.")
        elif monsterhealth > 0:
            print("The monster still has",monsterhealth,"health remaining. It is not intimidated.")
if monsterhealth <= 0:
    print("You have successfully defeated the monster. ")
Reply
#2
you generate a random number for attack only once - on line 5. Inside the loop you never generate a random number, you use the same number generated before that on line 5

Also, not related to your question, but look at https://python-forum.io/Thread-Text-Adve...dictionary
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(Jan-13-2021, 02:07 PM)buran Wrote: you generate a random number for attack only once - on line 5. Inside the loop you never generate a random number, you use the same number generated before that on line 5

Also, not related to your question, but look at https://python-forum.io/Thread-Text-Adve...dictionary
Oh I see. I need to generate the random number inside the loop for it to change. I appreciate the link. That has some really good tips. Just for fun...here is what I ended up with thanks to your advice. It works.

name = input("What is your name? ")
health = 10
import random
monster = ["Slime", "Goblin"]
encounter = random.choice(monster)
monsterhealth = 0

option = input("1.Encounter 2.Exit ").lower()
while option == "encounter":
    if option == "encounter":
        encounter = random.choice(monster)
        print("You have encountered a",encounter)
        if encounter == ("Slime"):
            monsterhealth = 8
        elif encounter == ("Goblin"):
            monsterhealth = 10

    while monsterhealth > 0:
        encounteraction = input("1.Attack 2.Potion 3.Inquiry 4.Run ").lower()
        if encounteraction == "attack":
            attack = (random.randint(5,7))
        
        print ("You attack dealing",attack, "damage")
        monsterhealth -= attack
        if monsterhealth <= 0:
            print ("The",encounter,"is slain.")
        elif monsterhealth > 0:
            print("The monster still has",monsterhealth,"health remaining.",encounter,"is not intimidated.")
    if monsterhealth <= 0:
        print("You have successfully defeated the monster. ")
    option = input("1.Encounter 2.Exit ").lower()
Reply
#4
Adventure games are all about managing large amount of data. As you add more features your code will quickly become unmanageable. If you want to continue developing your game you'll need to learn about different ways to manage data and code complexity.

I reorganized you code using a couple of very simple complexity management ideas; functions and classes.

Since your program askes for input over and over and from different parts of the program I wrote an input function to simplify the task. The function prevents the user with choices and verifies the input.

An adventure game has a lot of "things" to keep track of; players, monsters, potions, spells, weapons, armor... Each of these "things" in turn have multiple attributes; health, skill, weapons, armor... A big part of designing your game is figuring out all the "things" you need and all the attributes for each "thing". I created a Monster class for representing Monster things. Mine is an overly simplified Monster that has a name, a probability to hit when attacking, a range of health points. It also has some "methods" that are like functions, but are specific to the Monster. I wrote a "health()" method that returns a starting health number for a monster of this type. I thought it might be more interesting if some Goblins were healthier than others. I also gave the moster an "attack()" method so it can attack players. In a real game the attack method will have to take into account the player's level and armor.

In addition to functions and classes you may want to start studying databases or JSON or some way to record and restore the state of your game.

import random

class Monster:
    def __init__(self, name, health, attack, damage):
        self.name = name
        self.attack_probability = attack
        self.health_range = health
        self.damage_range = damage

    def health(self):
        return random.randint(*self.health_range)

    def attack(self):
        if random.randint(0,100) > self.attack_probability:
            return 0
        return random.randint(*self.damage_range)

def get_input(options):
    """Ask player to select from list of options"""
    while True:
        print('\nWhat do you want to do?')
        for i, option in enumerate(options):
            print(f'{i+1}: {option}')
        choice = input(f'Enter [1..{len(options)+1}]: ')
        try:
            index = int(choice)
            return options[index-1]
        except:
            print(f'Please enter number in range 0..{len(options)+1}')
        finally:
            print('')


monsters = [
    Monster("Goblin", (8,12), 65, (5, 7)),
    Monster("Slime", (6, 10), 25, (15, 25))
]
health = 10

while health > 0:
    option = get_input(('Encounter', 'Exit'))
    if option == 'Exit':
        break;

    monster = random.choice(monsters)
    print(f'You have encountered a {monster.name}')
    monsterhealth = monster.health()
 
    while monsterhealth > 0:
        option = get_input(('Attack', 'Potion', 'Inquiry', 'Run'))
        print(option)
        if option == 'Attack':
            attack = (random.randint(5,7))
            print (f'You attack dealing {attack} damage')
        
            monsterhealth -= attack
            if monsterhealth <= 0:
                print (f'The {monster.name} is slain.')
                break
            else:
                print(f'The {monster.name} has {monsterhealth} health remaining')
                

        attack = monster.attack()
        if attack == 0:
            print(f'The {monster.name} attacked and missed')
        else:
            health -= attack
            if health <= 0:
                print('You died!')
                break
            print(f'The {monster.name} attacks!  You have {health} health remaining')

        if option == 'Run':
            break
Reply
#5
Wow. That's actually much cleaner than mine. Unfortunately...I just started coding yesterday so...a lot of that went over my head. I am finished for the day but...this is what I came up with. It still has several errors that I need to work on though. As I learn more about coding and the general language I would like to clean this up to more closely resemble that. Thank-you for sharing.

name = input("Please name your character.\n")
playerhealth = 10
import random
monster = ["Slime", "Slime", "Goblin"]
encounter = random.choice(monster)
monsterhealth = 0
monsterattack = 0
potion = 0
potion_min = 2
potion_max = 4
player_min_dmg = 0
player_max_dmg = 4
monster_min_dmg = 0
monster_max_dmg = 0


option = input("\n1.Encounter\n2.Exit\n").lower()
while option != "encounter":
    if option == "exit":
        print ("Thanks for playing.")
        break
    option = input("1.Encounter\n2.Exit\n").lower()
while option == "encounter":
    monsterattack = 0
    if option == "encounter":
        encounter = random.choice(monster)
        print("\nYou have encountered a",encounter,"\n")
        if encounter == ("Slime"):
            monsterhealth = 8
        elif encounter == ("Goblin"):
            monsterhealth = 10

    while not (monsterhealth <= 0 and playerhealth <= 0):
        if playerhealth <= 0:
            print("You have died. There is no valor in death. You are no one.")
        encounteraction = input("What would you like to do?\n1.Attack \n2.Potion \n3.Run\n").lower()
        if encounter == ("Slime"):
            monster_min_dmg = 0
            monster_max_dmg = 3
            monsterattack = (random.randint(monster_min_dmg,monster_max_dmg))
        if encounter == ("Goblin"):
            monster_min_dmg = 0
            monster_max_dmg = 5
            monsterattack = (random.randint(monster_min_dmg,monster_max_dmg))
        if encounteraction == "attack":
            attack = (random.randint(player_min_dmg,player_max_dmg))
            print ("\nYou attack dealing",attack, "damage")
            monsterhealth -= attack
            print ("The",encounter,"deals",monsterattack,"damage to you.\n")
            playerhealth -= monsterattack
        elif encounteraction == "potion":
            potion = (random.randint(potion_min,potion_max))
            playerhealth += potion
            print("You drink the potion and heal",potion," health.")
            print (encounter,"deals",monsterattack,"damage to you.")
            playerhealth -= monsterattack
        elif encounteraction == "run":
            print ("You attempt to flee the battle like a coward.")
            print (encounter,"deals",monsterattack,"damage to you.\n")
            playerhealth -= monsterattack
            print ("You successfully flee the battle.")
            break
        if monsterhealth <= 0:
            print ("The",encounter,"is slain.\n\nWhat would you like to do?")
        elif monsterhealth > 0:
            print("The monster still has",monsterhealth,"health remaining.\nThe",encounter,"is not intimidated.\n")
            print("You still have",playerhealth,"health remaining.\nDon't forget that you can use potions if you need them.\n")
    if monsterhealth <= 0:
        print("You have successfully defeated the monster. ")
Reply
#6
If you are just starting out I suggest doing some tutorials. Theoretically you can write any program without writing your own classes or functions, but it will drive you insane. Learning how the major Python parts work and work together before diving into a project of any size is going to save you time and headache.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why is 2/3 not just .666 repeating? DocFro 4 644 Dec-12-2023, 09:09 AM
Last Post: buran
  find random numbers that are = to the first 2 number of a list. Frankduc 23 3,015 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  repeating a user_input astral_travel 17 2,194 Oct-26-2022, 04:15 PM
Last Post: astral_travel
  if else repeating Frankduc 12 2,425 Jul-14-2022, 12:40 PM
Last Post: Frankduc
  matching a repeating string Skaperen 2 1,198 Jun-23-2022, 10:34 PM
Last Post: Skaperen
  matrix number assignement to the random indices juniorcoder 4 1,874 Feb-19-2022, 02:18 PM
Last Post: juniorcoder
  Generate random hex number ZYSIA 1 11,319 Jul-16-2021, 09:21 AM
Last Post: DeaD_EyE
  Random number generator charlottelol 5 3,137 Nov-10-2020, 10:51 PM
Last Post: deanhystad
  factorial, repeating Aldiyar 4 2,738 Sep-01-2020, 05:22 PM
Last Post: DPaul
  basic random number generator in replace function krug123 2 2,007 Jul-31-2020, 01:02 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020