简体   繁体   English

在函数之间传递对象?

[英]Passing Objects Between functions?

I am new to programming in python and, I started writing a simple text based adventure game. 我是python编程的新手,我开始写一个简单的基于文本的冒险游戏。 I came across a problem when passing an object from one function to another. 将对象从一个函数传递到另一个函数时遇到一个问题。 Here is my code: 这是我的代码:

import random
import time
num = random.randint(0,2)
xp1 = random.randint(1,2)
class player:
    def __init__ (self, name, health, strength, defense, potion, xp, level):
        self.__health = health
        self.__strength = strength
        self.__defense = defense
        self.__name = name
        self.__potion = potion
        self.__xp = xp
        self.__level = level
        def getName(self):
            return self.__name

        def getHealth(self):
            return self.__health

        def getStrength(self):
            return self.__strength

        def getDefense(self):
            return self.__defense

        def getPotion(self):
            return self.__potion

        def getXP(self):
            return self.__xp

        def getLevel(self):
            return self.__level

        def setHealth(self):
            self.__health = 10

        def setLevel(self):
            self.__level = 1

        def subHealth(self, num):
            self.__health -= num

        def subPotion(self):
            self.__potion -= 1
            return self.__health

        def addPotion(self, num1):
            self.__potion += num1

        def addHealth(self):
            self.__health +=2

        def addStrength(self):
            self.__strength += 1

        def addDefense(self):
            self.__defense += 1

        def addXP(self):
            self.__xp += xp1

        def addLevel(self):
            self.__level += 1
            self.__addHealth += 1
            self.__defense += 1
            self.__strength += 1

    def battle(enemy, player1, name1):
        player1 = player(name1, player1.getHealth(), player1.getStrength(), player1.getDefense(), player1.getPotion(), player1.getXP(), player1.getLevel())
        enemy = player('Dongus', enemy.getHealth(), enemy.getStrength(), enemy.getDefense(), enemy.getPotion(), enemy.getXP(), enemy.getLevel())
        s = 0
        while s == 0:
            time.sleep(1)
            attack =int(input("Type 1 to attack, type 2 to use a potion."))
            if attack == 1:
                time.sleep(1)
                print("Dongus's health is", enemy.subHealth(num))
                print("Dongus hit you and your health is now at", player1.subHealth(num-player1.getDefense()))
            elif attack == 2:
                time.sleep(1)
                print("You used a potion.")
                player1.addHealth(), player1.subPotion()
                if player1.getHealth() > 10:
                    player1.setHealth()
                    print("Dongus hit you and your health is now at", player1.subHealth(num-player1.getDefense()))
            if enemy.getHealth()<=0:
                print("Congratulations, you won! You recieved", xp1, "xp!")
                player.addXP()
                s = 2
    def main():
        name1 = input("What would you like your name to be?")
        time.sleep(1)
        print("Hello,", name1, "you are on a quest to save otis from the evil Dongus. You must slay him, or Otis will poop.")
        time.sleep(2)
        player1 = player(name1, 10, 2, 1, 0, 0, 1)
        enemy = player('Dongus', 8, 4, 0, 0, 0, 0)
        print("Your stats are, health:", player1.getHealth(), "strength:", player1.getStrength(), "and defense:", player1.getDefense())
        time.sleep(2)
        print("Fight!")
        pick = input("You found a health potion! Press 'p' to pick it up.")
        p = 0
        while p == 0:
            if pick == "p":
                print("You added a potion to your inventory.")
                player1.addPotion(1)
                p = 2
            else:
                print("You have no potions, you should probably pick this one up.")
                player1.addPotion(1)
                p = 2
        battle(enemy, player1, name1)
        if self.__getXP() == 1:
            print("You leveled up. You are now level 2.")
            player1.addLevel()
            print("Your stats are, health:", player1.getHealth(), "strength:", player1.getStrength(), "and defense:", player.getDefense())       
        loot1 = int(input("Type ''1'' to loot the enemy chest."))
        if loot1 == 1:
            print("You recieved two potions!")
            player1.__addPotion(2)
        enemy.setHealth(10)
        battle(enemy, player1, name1)

main()

Now the problem is when I run the game, I get to a point where I type "1" to attack the enemy, but it says, for some reason, that after attacking the enemy, the enemies health is at "None". 现在的问题是,当我运行游戏时,我到达了键入“ 1”来攻击敌人的地步,但是由于某种原因,它说在攻击敌人之后,敌人的健康状态为“无”。 This is the same case when the enemy attacks player1, it says player1's health is at "None". 当敌人攻击玩家1时,情况相同,即玩家1的生命值处于“无”状态。 I assume that "None" is the default value in python 3.4.1, so my thinking is that the player1's object from def main() are not being transferred over to def battle() and I cannot see the reason why this is happening. 我假设“无”是python 3.4.1中的默认值,所以我的想法是def main()中的player1对象没有被转移到def Battle()中,我看不到发生这种情况的原因。 I most likely am missing something here, or it is something I do not already know about Python that is causing the issue. 我很可能在这里遗漏了一些东西,或者是我对导致问题的Python尚不了解。 Does anybody know what I can do to fix this, and why it is doing this? 有人知道我可以做些什么来解决此问题,为什么它要这样做?

BTW some of the terms I am using may be wrong, so please correct me if they are... I have only been coding for 2 weeks :p. 顺便说一句,我正在使用的某些术语可能是错误的,因此,如果它们是正确的,请更正...我只编码了2周:p。

Thanks!!! 谢谢!!!

First, received not recieved 一,收到未收到

2nd yes, If you have a Python function that does not return a value, the result is None 第二个是的,如果您有一个不返回值的Python函数,则结果为None

# dummy will return "Positive" or None
def dummy(x):
    if X > 0:
        return "Positive"

So, you probably want to change 所以,您可能想改变

def subHealth(self, num):
        self.__health -= num

to

def subHealth(self, num):
        self.__health -= num
        return self.__health

Your question re: the "player" classes from def main() are not being transferred over to def battle() does not really make sense to me. 您的问题是:def main()中的“ player”类没有转移到def Battle()中,这对我来说真的没有意义。

But, I see that in the first 2 lines of battle, you are replacing the formal parameters player1 and enemy with local variables, this seems like odd usage in your program. 但是,我看到在战斗的前两行中,您正在用局部变量替换形式参数player1和敌人,这在您的程序中似乎很奇怪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM