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
  Random number generator charlottelol 5 565 Nov-10-2020, 10:51 PM
Last Post: deanhystad
  factorial, repeating Aldiyar 4 553 Sep-01-2020, 05:22 PM
Last Post: DPaul
  basic random number generator in replace function krug123 2 539 Jul-31-2020, 01:02 PM
Last Post: deanhystad
  Help with a random number generator dpcalder 2 490 Jun-20-2020, 03:50 AM
Last Post: buran
  Generate only one random number for many tries Bhavika 2 534 Mar-29-2020, 12:12 PM
Last Post: Bhavika
  number repeating twice in loop JonnyEnglish 3 1,028 Nov-24-2019, 09:23 AM
Last Post: ThomasL
  Finding MINIMUM number in a random list is not working Mona 5 873 Nov-18-2019, 07:27 PM
Last Post: ThomasL
  same number everytime when using random.randint summeringpainting 5 2,650 Aug-23-2019, 11:01 AM
Last Post: Malt
  Repeating equations Tbot100 2 1,094 May-29-2019, 02:38 AM
Last Post: heiner55
  help cant do random number nonzzo 1 859 Mar-28-2019, 07:33 PM
Last Post: Yoriz

Forum Jump:

User Panel Messages

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