如何在Python中传递变量?

时间:2014-10-25 08:26:37

标签: python variables parameters python-idle

我想做一个基于文本的格斗游戏,但为了做到这一点,我需要使用几个函数并传递值,如伤害,武器和健康。

请允许此代码能够通过"武器" "损伤" " p1 n p2"在我的代码中。正如你所看到的,我已经尝试使用参数p1 n p2,但我有点新手。


import random

def main():
    print("Welcome to fight club!\nYou will be fighting next!\nMake sure you have two people ready to       play!")
    p1=input("\nEnter player 1's name ")
    p2=input("Enter player 2's name ")
    print("Time to get your weapons for round one!\n")
    round1(p1,p2)

def randomweapons(p1,p2):
    weapon=["Stick","Baseball bat","Golf club","Cricket bat","Knife",]
    p1weapon=random.choice(weapon)
    p2weapon=random.choice(weapon)
    print(p1 +" has found a "+p1weapon)
    print(p2 +" has found a "+p2weapon)

def randomdamage():
    damage=["17","13","10","18","15"]
    p1damage=random.choice(damage)
    p2damage=random.choice(damage)

def round1(p1,p2):
    randomweapons(p1,p2)

def round2():
    pass
def round3():
    pass
def weaponlocation():
    pass

main()

1 个答案:

答案 0 :(得分:1)

有几个选择。

一种是将值作为参数传递,并从各种函数返回值。您已使用两个播放器的名称进行此操作,这两个播放器的名称从main传递到round1,然后从randomweapons传递到return。你只需要决定还需要传递什么。

当信息需要流向另一个方向时(从被调用的函数返回给调用者),请使用randomweapons。例如,您可能会return p1weapon, p2weapon将所选择的武器返回到调用它的任何函数(使用w1, w2 = randomweapons(p1, p2))。然后,您可以使用Python的元组解包语法MyGame将函数的返回值赋值给变量或多个变量,从而将武器保存在调用函数中。从那时起,调用函数可以对这些变量做任何想做的事情(包括将它们传递给其他函数)。

另一种可能更好的方法是使用面向对象的编程。如果您的函数是某些类中定义的方法(例如self),则可以将各种数据作为属性保存在类的实例上。这些方法将实例作为第一个参数自动传入,该参数通常命名为class MyGame: # define the class def play(self): # each method gets an instance passed as "self" self.p1 = input("Enter player 1's name ") # attributes can be assigned on self self.p2 = input("Enter player 2's name ") self.round1() self.round2() def random_weapons(self): weapons = ["Stick", "Baseball bat", "Golf club", "Cricket bat", "Knife"] self.w1 = random.choice(weapons) self.w2 = random.choice(weapons) print(self.p1 + " has found a " + self.w1) # and looked up again in other methods print(self.p2 + " has found a " + self.w2) def round1(self): print("Lets pick weapons for Round 1") self.random_weapons() def round2(self): print("Lets pick weapons for Round 2") self.random_weapons() def main(): game = MyGame() # create the instance game.play() # call the play() method on it, to actually start the game 。这是一个有点粗略的例子:

{{1}}