重置变量功能错误

时间:2018-08-01 22:39:11

标签: python variables global reset init

所以我是Python的新手,我在RPG上工作很多,但是在尝试重置或刷新类中的变量时遇到了一个问题。

在用户成功逃离怪物的那一刻,使用妖精进入下一场战斗将导致妖精共享与前一个相同的统计数据。例如,用户以Goblin_1的损害赔偿5,意味着其生命值为25/30。如果用户成功逃走,则下次用户打地精时,其初始健康值为25/30。

这个问题还会影响到杀死怪物时获得的经验和金币。我相当确定,如果在用户成功逃跑后重置了变量,那么只要我将其转移到获胜条件下,就可以解决所有问题。

简而言之,我们有Goblin_1Goblin_1的生命值5受到了伤害,现在为25/30。如果用户逃跑,Goblin_2将覆盖Goblin_1的统计信息,而不是从25/30生命值开始。

任何帮助都是很棒的伴侣。

import sys 
import os
import random
import pickle
import time

## Weapons
weapon1 = {"long sword":10}
weapon2 = {"great sword":40}

## Potions
healthpot = {"health potion": 10}

# User Statistics
class Player:
    def __init__(self, name):
        self.name = name
        self.exp = 0
        self.maxhealth = 100
        self.health = self.maxhealth
        self.base_attack = 10
        self.gold = 0
        self.pots_health = 0
        self.weap = ["rusty sword"]
        self.curweap = "Rusty Sword"

# Attack Modifiers
    @property 
    def attack(self):
        attack = self.base_attack
        if self.curweap == "rusty sword":
            attack += 2

        if self.curweap == "long sword":
            attack += 10

        if self.curweap == "great sword":
            attack += 20

        return attack

## Monsters
class Goblin:
    def __init__(self, name):
        self.name = name
        self.maxhealth = 30
        self.health = self.maxhealth
        self.attack = random.randint(3,8)
        self.goldgain = random.randint(5,10)
        self.expgain = random.randint(9,15)
GoblinIG = Goblin("Goblin")

class Skeleton:
    def __init__(self, name):
        self.name = name
        self.maxhealth = 25
        self.health = self.maxhealth
        self.attack = random.randint(2,7)
        self.goldgain = random.randint(0,10)
        self.expgain = random.randint(5,10)
SkeletonIG = Skeleton("Skeleton")

class Colbolt:
    def __init__(self, name):
        self.name = name
        self.maxhealth = 50
        self.health = self.maxhealth
        self.attack = random.randint(7,15)
        self.goldgain = random.randint(10,20)
        self.expgain = random.randint(9,20)
ColboltIG = Colbolt("Colbolt")

# Functions

# Start Up Prompt
def main():
    os.system('clear')
    print ("Basic Text RPG game.\nCreated on July 24, 2018.\n\n")
    print ("Select an option\n")
    print ("1.) Start")
    print ("2.) Load")
    print ("3.) Exit")
    raw_input = input (">>> ")
    option = raw_input
    if option == "start":
        start()
    elif option == "load":
        if os.path.exists("savefile") == True:
            os.system('clear')
            with open('savefile', 'rb') as f:
                global PlayerIG
                PlayerIG = pickle.load(f)
            print ("Loaded Save State...\n")
            option = raw_input
            start1()
        else:
            print ("You have no save file for this game.")
            option = raw_input
            main()
    elif option == "exit":
        sys.exit()
    else:
        print ("Error 404: Unknown command")
        main()

# Goining User Infomation
def start():
    os.system('clear')
    print ("Hello, what is your name?")
    raw_input = input (">>> ")
    option = raw_input
    global PlayerIG
    PlayerIG = Player(option)
    start1()

# Main Page - What The User Chooses To Do
def start1():
    os.system('clear')
    print ("Name: %s" % PlayerIG.name)
    print ("Experience: %i" % PlayerIG.exp)
    print ("Attack: %i" % PlayerIG.attack)
    print ("Gold: %d" % PlayerIG.gold)
    print ("Current Weapons: %s" % PlayerIG.curweap)
    print ("Health Potions: %d" % PlayerIG.pots_health)
    print ("Health: %i/%i\n" % (PlayerIG.health, PlayerIG.maxhealth))
    print ("1.) Fight")
    print ("2.) Drink Health Potion")
    print ("3.) Shop")
    print ("4.) Save")
    print ("5.) Inventory")
    print ("6.) Exit")
    os.system('clear')
    raw_input = input (">>> ")
    option = raw_input
    if option == "fight":
        os.system('clear')
        prefight()
    elif option == "shop":
        shop()
    elif option == "drink health potion":
        drinkpot_health_startpage()
    elif option == "drink health":
        drinkpot_health_startpage()
    elif option == "health potion":
        drinkpot_health_startpage()
    elif option == "save":
        os.system('clear')
        with open('savefile', 'wb') as f:
            pickle.dump(PlayerIG, f)
            print ("\nGame has been saved!\n")
        option = raw_input
        start1()
    elif option == "exit":
        sys.exit()
    elif option == "inventory":
        inventory()
    else:
        print ("\n")
        start1()

# Accessing The Inventory Of The User
def inventory():
    os.system('clear')
    print ("What do you want to do?")
    print ("1.) Equip Weapon")
    print ("2.) Exit")
    raw_input = input (">>> ")
    option = raw_input
    if option == "equip weapon":
        equip()

    elif option == "exit":
        start1()

    else:
        os.system('clear')
        print ("Error 404: Unknown Command\n")
        inventory()

# Equiping Gear
def equip():
    os.system('clear')
    print ("What do you want to equip?\n")
    for weapon in PlayerIG.weap:
        print (weapon.title())
    print ("Back")
    print ("Exit")
    raw_input = input (">>> ")
    option = raw_input
    if option == PlayerIG.curweap:
        print ("You already have that weapon equipped\n")
        option = raw_input
        equip()
    elif option == "back":
        inventory()
    elif option == "exit":
        start1()
    elif option in PlayerIG.weap:
        PlayerIG.curweap = option
        print ("You have equipped %s." % option, "\n")
        option = raw_input
        equip()
    else:
        print ("You don't have %s in your inventory" % option, "\n")
        equip()

## Deciding Monster Spawn Type
def prefight():
    global enemy
    if PlayerIG.exp <= 50:
        enemynum = random.randint(1, 2)
        if enemynum == 1:
            enemy = GoblinIG
        if enemynum == 2:
            enemy = SkeletonIG
        fight()
    if PlayerIG.exp >= 50 <= 100: 
        enemynum = random.randint(1, 3)
        if enemynum == 1:
            enemy = GoblinIG
        elif enemynum == 2:
            enemy = SkeletonIG
        else:
            enemy = ColboltIG
        fight()

# Determining What The User Wants To Do
def fight():
    os.system('clear')
    print ("%s     vs      %s" % (PlayerIG.name, enemy.name))
    print ("%s's Health: %d/%d    %s's Health: %i/%i" % (PlayerIG.name, PlayerIG.health, PlayerIG.maxhealth, enemy.name, enemy.health, enemy.maxhealth))
    print ("Health Potions %i\n" % PlayerIG.pots_health)
    print ("1.) Attack")
    print ("2.) Drink Health Potion")
    print ("3.) Run")
    raw_input = input (">>> ")
    option = raw_input
    if option == "attack":
        os.system('clear')
        attack()
    elif option == "run":
        run()
    elif option == "drink heatlh potion":
        drinkpot_health_fightpage()
    elif option == "drink heatlh":
        drinkpot_health_fightpage()
    elif option == "heatlh potion":
        drinkpot_health_fightpage()
    else:
        print ("What the hell does that mean?")
        fight()

# Calculating Attacking Statistics + Running Fight Outcomes
def attack():
    PAttack = int(random.uniform(PlayerIG.attack // 2, PlayerIG.attack))
    EAttack = int(random.uniform(enemy.attack // 2, enemy.attack))
    if PAttack <= PlayerIG.attack // 2:
        print ("You miss!")
    else:
        enemy.health == PAttack
        print ("You deal %i damage!" % PAttack)
        enemy.health -= PAttack
    if enemy.health <= 1:
        win()
    os.system('clear')
    if EAttack <= enemy.attack // 2:
        print ("The enemy missed!")
    else:
        PlayerIG.health -= EAttack
        print ("The enemy deals %i damage!" % EAttack)
    if PlayerIG.health <= 0:
        dead()
    else:
        fight()

# If The User Drinks Health Potions From 'Start1()'
def drinkpot_health_startpage():
    os.system('clear')
    if PlayerIG.pots_health == 0:
        print ("You don't have any health potions!\n")
        start1()
    else:
        PlayerIG.health += 25
        if PlayerIG.health > PlayerIG.maxhealth:
            PlayerIG.health = PlayerIG.maxhealth
        print ("You drank a health potion!\n")
        PlayerIG.pots_health -= 1
        start1()

# If The User Drinks Health Potions From 'Fight()'
def drinkpot_health_fightpage():
    os.system('clear')
    if PlayerIG.pots_health == 0:
        print ("You don't have any health potions!\n")
        fight()
    else:
        PlayerIG.health += 25
        if PlayerIG.health > PlayerIG.maxhealth:
            PlayerIG.health = PlayerIG.maxhealth
        print ("You drank a health potion!\n")
        PlayerIG.pots_health -= 1
        fight()

# Calcualting And Running Statistics If The User Runs      
def run():
    os.system('clear')
    runnum = random.randint(1, 5)
    if runnum <= 3:
        print ("You have successfully ran away!")
        os.system('clear')
        start1()
    else:
        print ("You failed to get away!")
        os.system('clear')
        EAttack = random.randint(enemy.attack // 2, enemy.attack)
        if EAttack == enemy.attack/2:
            print ("The enemy missed!")
        else:
            PlayerIG.health -= EAttack
            print ("The enemy deals %i damage!" % EAttack)
        fight()
        if PlayerIG.health <= 0:
            dead()
        else:
            fight()

# When User Defeats Monster - Calculates What User Gained
def win():
    os.system('clear')
    enemy.health = enemy.maxhealth
    PlayerIG.gold += enemy.goldgain
    PlayerIG.exp += enemy.expgain
    print ("You have defeated the %s" % enemy.name)
    print ("You gained %i experience points!" % enemy.expgain)
    print ("You found %i gold!" % enemy.goldgain, "\n")
    start1()

# When User Dies
def dead():
    os.system('clear')
    print ("You have died\n")
    restart()

# Prompting User To Restart
def restart():
    os.system('clear')
    print ("Would you like to Restart?")
    raw_input = input (">>> ")
    option = raw_input
    if option == "yes" or "restart":
        text1 = "Restarting"
        for char in text1:
            sys.stdout.write(char)
            sys.stdout.flush()
            time.sleep(0.1)
        text2 = "...\n\n"
        for char in text2:
            sys.stdout.write(char)
            sys.stdout.flush()
            time.sleep(0.7)
        start()
    if option == "no":
        print ("Game Over")

# Accessing The Shop
def shop():
    os.system('clear')
    print ("Rhaast's Weapons Shop\n")
    print ("\nWhat would you like to buy?\n")
    print ("1.) Long Sword 10gp")
    print ("2.) Great Sword 40gp")
    print ("3.) Health Potion 10gp")
    print ("Back")
    print (" ")
    raw_input = input (">>> ")
    option = raw_input

    if option in weapon1:
        if PlayerIG.gold >= weapon1[option]:
            os.system('clear')
            PlayerIG.gold -= weapon1[option]
            PlayerIG.weap.append(option)
            print ("You have bought %s!" % option, "\n")
            option = raw_input
            shop()
        else:
            os.system('clear')
            print ("You don't have enough gold\n")
            option = raw_input
            shop()

    if option in weapon2:
        if PlayerIG.gold >= weapon2[option]:
            os.system('clear')
            PlayerIG.gold -= weapon2[option]
            PlayerIG.weap.append(option)
            print ("You have bought %s!" % option, "\n")
            option = raw_input
            shop()
        else:
            os.system('clear')
            print ("You don't have enough gold\n")
            option = raw_input
            shop()

    if option in healthpot:
        if PlayerIG.gold >= healthpot[option]:
            os.system('clear')
            PlayerIG.gold -= healthpot[option]
            PlayerIG.pots_health += 1
            print("You have bought %s!" % option, "\n")
            option = raw_input
            shop()
        else:
            os.system('clear')
            print ("You don't have enough gold\n")
            option = raw_input
            shop()

    elif option == "back":
        start1()

    else:
        os.system('clear')
        print ("That item does not exist\n")
        option = raw_input
        shop()

##__main__##
main()

1 个答案:

答案 0 :(得分:0)

您的问题的简短答案是:

(对不起,我没有复制粘贴您的代码,太长了) 例如替换行

  

敌人= GoblinIG

使用

  

敌人=地精(“地精”)

还删除GoblinIG(“ Goblin”)等,因为从现在开始您将不再使用它们。 这样,每次您使用“预选”功能时,它都会创建 new 对象。

长答案将教您关于global and local variables(您似乎只使用全局的)和argument passing的知识。这些将使您的代码变得更加轻松,从而使您的代码变得更好。

不要误会我的意思,我不是要刻薄,而是要指出方向。您的代码可以使用,但现在不是您编程的方式。