Python文本角色扮演

2024-06-17 12:11:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个文本角色扮演游戏,我遇到了一个问题。所以在下面的代码中,mobHP是一个全局变量,等于20000。这只是代码的一部分。所以一旦攻击发生,怪物的新生命值就会显示出来,但是在第二次攻击中,生命值再次变为20000,然后伤害被减去,再次显示另一个值,它不会从新值中减去。battlem()是战斗菜单,您可以从中攻击、使用药剂和奔跑。win()是一个def函数,用于定义用户获胜时要显示的内容。 例如,如果一个玩家命中怪物1000,那么当前生命值将显示为19000,但是当我再次攻击时,比如说命中1400,而不是19000-1400,它会从原始值中减去,变成18600。 我真的很感激你的帮助

def Attack():
damage = random.randint(120,240) - random.randint(80,120)
currentHP = 0
currentHP -=  damage
input()
print("You swing your sword at the enemy!")
print("Inflicted damage:",damage,"enemy HP:",currentHP)
if playerHP <= 0:
   death()
elif mobHP <= 0:
    win()
else:
    battlem()
currentHP=mobHP;
while(currentHP>0):
    battlem()

但是,这并不能像输出那样工作

You swing your sword at the enemy!
Inflicted damage: 95 enemy HP: -95

这是一个解决方案,但后来删除,当我进一步要求一个解决方案,没有人再回答。你知道吗

完整代码:

import random
import time


global playerHP
global inventory 
global mobHP
global mobSpeed
global mob
global boss
global level
global strength
global speed
global potions
global exp
global mithril


playerHP= 28000
level = 74
strength = 80
speed = 120
potions = 3
exp = 0
mithril = 10000
mobHP = 20000
mobstrength = 120
mobSpeed = 180
inventory = []


def prompt():
command = input("What action will you perfrom?")
return command


def death():
if  playerHP== 0:
    print("Your HP has been depleted completely")
    input()
    print("You are now dead")
    input()
    print("You will be respawned at the Misgauka")
    input()
    townone()

def townoned():
print("You are at the town of Misgauka")
print("What do you wish to do from here onwards")
print("""
Type Inn to go to the Inn
Type store to go to the store
Type grasslands to go hunt some monsters
Type dungeon to hunt harder monsters
""")
command = prompt()
if command == "Inn":
    print("You are now at the Inn, what do you wish to do?")
    input()
    print("""You can do the following:
Rest
""")
    command = prompt()
    if command == "Rest":
        rest()


if command == "Store":
    print("You make your way to the store")
    input()
    print("Welcome to Tonajta's Weapon and Supplies shop")
    input()
    print("""You can do the following:
Display Catalogue
Exit store
""")
    command = prompt()
    if command == "Display" or "display": 
        print("Open the Weapons Catalogue or the Supplies catalogue")
        input()
        command = prompt()
        if command == "Weapons":
            wepmenu()

        if command == "Supplies":
            supplymenu()

    elif command == "Exit":
        print("Thanks for coming")
        input()
        print("Please do visit again")
        input
        townone()

    def Grasslands():
        print(" You have already cleared the Grasslands")
        input()
        print("You may go there to gain more experience")
        input()
        print("Y/N")
        input()
        command = prompt()
        if command == "Y" or "y":
            print("You proceed to the grasslands")
            input()
        elif command == "N" or "n":
            townoned()
        else:
            print("You seem to be pressing the wrong command")
            Grasslands()

def win():
print("You have managed to slain the enemy")
input()
print("You now must dwell further within the greenlands")
input()

def battles():
print("A wild boar appears in front of you")
input()
print("What do you choose to do?")
input()
print("Fight or Run?")
input()
command = prompt()
if command == "Fight" or "fight":
    print("Good work senpai")
    input()
    battlem()
elif command == "Run" or "run":
    print("You turn to run")
    time.sleep(1)
    print("The pathway behind you is now blocked")
    input()
    print("Thus, you must fight")
    battlem()
else:
    battles()

def boss_battle():
print("Let's fight")
input()
command = prompt()
if command == "Fight" or "fight":
    print("You unsheath your sword")
    input()
    boss_battle_m()
else:
    print("You can't run away from this")
    input()
    boss_battle_m()

def boss_battle_m():
print("""
1. Attack   
2. Potions
""")
command = prompt()
if command == "1":
    boss_battle_s()
if command == "2":
    if potions > 0:
        print("You take a potion bottle")
        input()
        print("..........")
        input()
        pHP = playerHP +200
        print("Your HP has been refilled to",pHP)
        pHP = playerHP
    else:
        print("You have no potions left!")
        input()
        boss_battle_s()

def boss_battle_s(): 
bossdamage = random.randint(80, 220)
bossHP = 4000
bossHP = bossHP - bossdamage
print("Boss HP is now:", bossHP)
input()
if bossHP <= 0:
    win()
elif playerHP <= 0:
    death()
else:
    boss_battle_m()


def battlem():
print("""
1. Attack                 3. Run
2. Use potion           
""")
command = prompt()
if command == "1":
    Attack()
elif command == "2":
    Potiondesu()
elif command == "3":
    Run()
else:
    battlem()


#CURRENT DAMAGE BY THE CURRENT HEALTH



def Attack():
damage = random.randint(120,240) - random.randint(80,120)
currentHP = 0
currentHP -=  damage
input()
print("You swing your sword at the enemy!")
print("Inflicted damage:",damage,"enemy HP:",currentHP)
if playerHP <= 0:
   death()
elif mobHP <= 0:
    win()
else:
    battlem()
currentHP=mobHP;
while(currentHP>0):
    battlem()

def wepmenu():
print("""
1. Glorion Blades -  200 Mithril
2. Light Sword - 120 Mithril
3. Rapier - 200 Mithril
4. Dagger - 100 Mithril
Supplies Catalogue
Exit Store
""")
print("Which one do you want?")
command = prompt()
if command == "1":
    print("The Glorion Blades cost 200 mithril")
    input()
    if mithril>=200:
        print("You buy the blades")
        input()
        wepmenu()
    elif mithril<200:
        print("You cannot afford this weapon")
        input()
        print("Choose another weapon")
        wepmenu()
if command == "2":
    print("The light sword costs 120 mithril")
    input()
    if mithril>=150:
        print("You buy the sword")
        input()
        wepmenu()
    elif mithril<150:
        print("You cannot afford this weapon")
        input()
        print("Choose another weapon")
        wepmenu()
if command == "3":
    print("The Rapier costs 200 mithril")
    input()
    if mithril>=200:
        print("You buy the Rapier")
        input()
        wepmenu()
    elif mithril<200:
        print("You cannot afford this weapon")
        input()
        print("Choose another weapon")
        wepmenu()
if command == "4":
    print("The Dagger costs 100 mithril")
    input()
    if mithril>=100:
        print("You buy the blades")
        input()
        wepmenu()
    elif mithril<100:
        print("You cannot afford this weapon")
        input()
        print("Choose another weapon")
        wepmenu()
print("Gotta implement weapon stats")
if command == "Supplies" or "supplies":
    supplymenu()
elif command == "Exit":
    townone()

def supplymenu():
print("""
1. HP potion - 20 Mithril  
2. Large HP Potion  - 40 Mithril
Weapons catalogue
Exit Store
""")
print("Which one do you want?")
command = prompt()
if command == "1":
    print("The HP Potion costs 20 mithril")
    input()
    if mithril>=20:
        print("You have brought the potion")
        input()
        supplymenu()
    elif mithril<20:
        print("You cannot afford this potion")
        input()
        print("Choose another supply")
        input()
        supplymenu()
elif command == "2":
    print("The Large HP potion costs 40 mithril")
    input()
    if mithril>=40:
        print("You have brought the large potion")
        input()
        supplymenu()
    elif mithril<40:
        print("You cannot afford this potion")
        input()
        print("Choose another supply")
        supplymenu()
elif command == "Weapons":
    wepmenu()
elif command == "Exit":
    townone()



def rest_inn():
print("It will cost 20 mithril to rest at this inn for tonight")
input()
if mithril>=20:
    print("You check in")
elif mithril<20:
    print("You can't afford to rest here")
    input()
    print("Kill some monsters for some mithril")
    input()
    print("You exit the inn")
    input()
    townone()
print("Your HP has been reset to",HP,"HP")
input()
print("Please press enter to exit the inn")
input()
townone()


def townone():
print("You are at the town of Misgauka")
print("What do you wish to do from here onwards")
print("""
Type Inn to go to the Inn
Type store to go to the store
Type grasslands to go hunt some monsters
Type dungeon to hunt harder monsters

“”) 命令=提示() 如果命令==“Inn”: print(“您现在在酒店,您想做什么?”) 输入() 打印(“”您可以执行以下操作: 休息 """) 命令=提示() 如果命令==“Rest”: 休息()

if command == "Store":
    print("You make your way to the store")
    input()
    print("Welcome to Tonajta's Weapon and Supplies shop")
    input()
    print("""You can do the following:
Display Catalogue
Exit store
""")
    command = prompt()
    if command == "Display" or "display": 
        print("Open the Weapons Catalogue or the Supplies catalogue")
        input()
        command = prompt()
        if command == "Weapons":
            wepmenu()
        if command == "Supplies":
            supplymenu()

    elif command == "Exit":
        print("Thanks for coming")
        input()
        print("Please do visit again")
        input
        townone()

if command == "Grasslands":
    print("All of us have to go into the different pathways I guess")
    input()
    print("Three paths to each")
    input()
    print("Alright then, I'll take north, east and then the north pathway")
    input()
    print("Let's meet back here and gather intel")
    input()
    print("You make your way to the Grasslands")
    input()
    print("The pathway goes NORTH")
    battles()
    print("You will now proceed to the next part of the grasslands")
    input()
    print(".............")
    input()
    print("The ground rumbles.....")
    input()
    print("Another steel-plated guardian appears")
    input()
    battles()
    print("The path is finally clear")
    input()
    print("You proceed towards the EAST pathway")
    input()
    print("An approximate of two monsters will spawn here")
    input()
    print("WHOOSH")
    input()
    print("A rogue warrior emerges from within the huge bushes")
    input()
    battles()
    print("You run forward")
    input()
    print("Two more rogue warriors run towards you")
    input()
    battles()
    print("Now remains the last stage of the deadly grasslands")
    input()
    print("You make the turn")
    input()
    print("You see the other end of the Grasslands")
    input()
    print("There is a chair at a high position")
    input()
    print("Two figures seem to be running towards you")
    input()
    print("Prepare for combat")
    battles()
    input()
    battles()
    input()
    print("You seem to have beat the two orcs")
    input()
    print("Well, seems like it's time")
    input()
    print("IT's ONE OF THE HACKERS")
    input()
    print("Fight me, and I take this mask off")
    input()
    boss_battle()
    print("Ahhhhhhhhhhhhhhhhhh")
    input()
    print("This can't be happening")
    input()
    print("Now that we're done here..")
    input()
    print("Show me your face!")
    input()
    print("Pfff..")
    input()
    print("TAKES MASK OFF")
    input()
    print("Oh, so it's you Chaps")
    input()
    print("You know you won't win right")
    input()
    print("Even though you defeated me, you can't get past shad....")
    input()
    print("Who?")
    input()
    print("NOTHING, now as promised, I'll give you the location of the next          town")
    input()
    print("Where can I find the others in your pathetic group")
    input()
    print("Huh, you have a big mouth don't you")
    input()
    print("hehehehehhehhe......")
    input()
    print("HAHHAHAHHAHAHAHHAHA")
    input()
    print("A flash of blue light and the player vanishes.........")
    input()
    print("Well, he's done for")
    input()
    print("TING TING TING")
    input()
    print("Huh, what's th..........")
    input()
    print('{:^80}'.format("SERVER ANNOUNCEMENT"))
    time.sleep(2)
    print('{:^80}'.format("TOWN OF REPLAUD NOW AVAILABLE TO ALL PLAYERS"))
    time.sleep(2)
    print('{:^80}'.format("TO REACH, PLEASE CLEAR DUNGEON"))
    time.sleep(2)
    input()

elif command == "Dungeon":
    print("The dungeon cannot be accessed yet")
    input()
    print("To unlcok the dungeon, you must clear the grasslands")
    input()

else:
    print("You seem to have entered a wrong command")
    input()
    print("""Please enter either of these:
1. Inn
2. Store
3. Greenlands
4. Dungeon
  """)
    townone()



townone()

Tags: thetoyouinputifdefglobaldo
1条回答
网友
1楼 · 发布于 2024-06-17 12:11:10

不清楚是什么导致了您发布的代码中的错误,但是从您描述的行为来看,似乎您没有将mobHP定义为global。下面是一些示例代码。你知道吗

mobHP = 20000
playerHP = 30000

def check_hps():
    if mobHP <= 0:
        win()
    if playerHP <= 0:
        lose()

def broken_attack():
    attack_value = 100  # how hard you hit
    mobHP -= attack_value
    check_hps()

def fixed_attack():
    global mobHP
    attack_value = 100
    mobHP -= attack_value
    check_hps()

演示:

>>> mobHP
20000

>>> broken_attack()
>>> mobHP
20000

>>> fixed_attack()
>>> mobHP
19900

>>> fixed_attack()
>>> mobHP
19800

当然,这个代码很难维护。然而,它很容易实现。对比:

class Actor(object):

    def __init__(self, name, maxHP, min_dmg, max_dmg):
        self.name = name
        self.maxHP = maxHP
        self.currentHP = maxHP
        self.roll_dmg = lambda: random.randint(min_dmg, max_dmg)

    def attack(self, other, retaliation=False):
        other.currentHP -= self.roll_dmg()
        if not retaliation:
            other.attack(self, retaliation=True)

    def run(self, other):
        if random.random() >= 0.5:
            return True
        return False


class Battle(object):
    def __init__(self, *actors, location=None):
        self.actors = actors
        self.location = location

    def do_round(self):
        for actor in self.actors:
            choice, target = self.make_choice(actor)
            self.do_choice(choice, target)
            yield self.check_battle_over()

    def check_battle_over(self):
        for actor in self.actors:
            if actor.currentHP <= 0:
                return actor
        return None

    def do_choice(self, func, target):
        return func(target)

    def make_choice(self, actor):
        print("1. Attack\n"
              "2. Run away\n")
        choice = input(">> ")
        if choice == '1':
            action = actor.attack
        elif choice == '2':
            action = actor.run
        actor_mapping = {num:act for num,act in enumerate(
            filter(lambda a: a is not actor), start=1}
        print("Target:")
        print("\n".join(["{}. {}".format(*target) for target in actor_mapping.items()]))
        target = actor_mapping[input(">> ")]
        return (action, target)

    def start(self):
        while True:
            loser = do_round()
            if loser:
                print(loser.name + " is dead!")
                return

player = Actor(name="Player", maxHP=30000,
               min_dmg=80, max_dmg=200)
monster = Actor(name="Monster", maxHP=20000,
                min_dmg=50, max_dmg=100)

battle = Battle(player, monster)
battle.start()

相关问题 更多 >