我想制作一个基于文本的格斗游戏,但是为了做到这一点,我需要使用一些功能并传递诸如伤害,武器和健康之类的值。
请允许该代码在我的代码中始终传递“武器”,“伤害”,“ 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()
有一些选择。
一种是将值作为参数传递,并从各种函数中返回值。您已经与这两名球员的名字,这是作为参数传递从这样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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句