我一直收到这个错误,我完全不知道为什么,我有 3 个文件相互导入信息,但是这个主要文件只从 Monster_01.py 及其 player.py 中提取信息。
TypeError: player_attack() missing 1 required positional argument: 'self'
Run Code Online (Sandbox Code Playgroud)
---主要代码---
'''Player class
Fall 2014
@author Myles Taft (mbt6)
'''
import random
import monster_01
class Player():
def __init__(self, strength = 0, player_hp = 0):
self.strength = 1
self.player_hp = 100
print(self.strength, self.player_hp)
def battle():
def player_attack(self):
print('success')
while self.enemy_hp > 0:
monster_01()
self.dice1 = random.randint(1,6)
self.dice2 = random.randint(1,6)
self.dice_sum = dice1 + dice2
self.attack = dice1 + dice2
self.decide_roll = input('Type "roll" to roll the dice:')
self.roll = print('First die:' + dice1, 'Second die:' + dice2, 'Sum of dice:' + dice_sum)
if self.roll == 2 or 4 or 6 :
print('Hit!')
self.enemy_hp == strength
print(enemy_hp)
elif self.roll == 1 or 3 or 5:
print('Miss!')
def player_block(self):
self.dice1 = random.randint(1,6)
self.dice2 = random.randint(1,6)
self.decide_roll = input('Type "roll" to roll the dice:')
self.roll = print('First die:' + dice1, 'Second die:' + dice2, 'Sum of dice:' + dice_sum)
if self.roll == 2 or 4:
print('Blocked!')
self.player_hp -= int((enemy_strength)/2)
if self.roll == 1 or 3:
self.player_hp -= int(enemy_strength)
def choice(self):
get_player_attack(get_player_attack)
self.player_choice = input('Do you attack or block?') #self.player_hp, self.strength)
if self.player_choice == 'attack':
self.player_attack()
elif self.player_choice == 'block':
self.player_block()
def get_player_attack(self):
player_attack()
choice(choice)
Player.battle()
Run Code Online (Sandbox Code Playgroud)
我已经在这段代码上下了一百次,任何帮助将不胜感激。
小智 5
问题出在你的get_player_attack方法上:
def get_player_attack(self):
player_attack()
Run Code Online (Sandbox Code Playgroud)
它player_attack就像一个独立的函数而不是另一个方法一样调用。但是player_attack 是类的方法,Player因此只能在 的实例上调用Player。
该函数应该像这样调用:
self.player_attack()
Run Code Online (Sandbox Code Playgroud)
另外,像这样的东西:
if self.roll == 2 or 4 or 6 :
Run Code Online (Sandbox Code Playgroud)
只是一个等待发生的问题。应该写成:
if self.roll in (2, 4, 6):
Run Code Online (Sandbox Code Playgroud)
否则,if 语句的条件将被解释为:
if (self.roll == 2) or (4) or (6):
Run Code Online (Sandbox Code Playgroud)
这将始终评估为True. 有关更多信息,请参阅如何针对多个值测试一个变量?
最后,您不应该将所有方法都放在另一个名为battle. 我不知道你想在这里做什么,但方法定义应该就在类头下面:
class MyClass: # Class header
def method1(self): # Definition of the first method
...
def method2(self): # Definition of the next method
...
...
Run Code Online (Sandbox Code Playgroud)
我真的认为阅读一些关于 Python 类和 OOP 的教程对您有好处。以下是一些可以帮助您入门的内容:
| 归档时间: |
|
| 查看次数: |
2411 次 |
| 最近记录: |