【问题标题】:How do I pass variables around in Python?如何在 Python 中传递变量?
【发布时间】:2014-10-25 08:26:36
【问题描述】:

我想制作一个基于文本的格斗游戏,但为了做到这一点,我需要使用几个函数并传递诸如伤害、武器和生命值之类的值。

请允许此代码能够在我的代码中传递“武器”“伤害”“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()

【问题讨论】:

  • 你有什么问题?您预期的输入/输出是什么?此外,你的格式都搞砸了。该程序不会运行。

标签: python variables parameters python-idle


【解决方案1】:

有几个选项。

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

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

另一种可能更好的方法是使用面向对象编程。如果您的函数是在某个类中定义的方法(例如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

【讨论】:

  • 我会为每个玩家开设课程,但我同意 OOP 方法是正确的方法。
猜你喜欢
  • 2013-11-09
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多