【发布时间】:2021-03-19 12:09:12
【问题描述】:
我想让我的班级的两个变量动态化,因此它们具有不同的值,具体取决于为游戏选择的难度。我在__init__ 中做错了什么还是问题出在哪里?如果我从__init__ 中删除两个参数speed_top_border, speed_bottom_border 并输入静态值,一切都会正常工作。
# Obstacle class
class Obstacle(object):
# Init
def __init__(self, speed_top_border, speed_bottom_border):
self.obstacleImg = 'rock.png'
self.obstacleX = random.randint(700, 800)
self.obstacleY = random.randint(0, ScreenHeight - 64)
self.obstacleX_change = random.uniform(self.speed_top_border, self.speed_bottom_border)
# Keep window running (Infinite-Loop)
running = 1
# Menu-loop
while running == 1:
# Insert Background
screen1.blit(background, (0, 0))
for event in pygame.event.get():
# Quit game
if event.type == pygame.QUIT:
running = 0
if event.type == pygame.KEYDOWN:
# Difficulty easy
if event.key == pygame.K_1:
speed_top_border = -1
speed_bottom_border = -0.5
# Start game
if event.key == pygame.K_SPACE:
running = 2
# Game While-Loop
while running == 2:
# Creation of instancet of class obstacle each iteration
if timer1_current - timer1_start >= interval:
timer1_start = time.time() # Timer of start set to current time
obstacle = Obstacle(speed_top_border, speed_bottom_border) # Create instance of class obstacle
obstacle_list.append(obstacle) # Append instance to list
print(obstacle) # Print created instance for check
score += 100 * score_multiplier # Increase score
错误信息
Traceback (most recent call last):
File "C:\Users\Timo\PycharmProjects\2DFlugzeugspiel\main.py", line 221, in <module>
obstacle = Obstacle(speed_top_border, speed_bottom_border) # Create instance of class obstacle
File "C:\Users\Timo\PycharmProjects\2DFlugzeugspiel\main.py", line 89, in __init__
self.obstacleX_change = random.uniform(self.speed_top_border, self.speed_bottom_border)
AttributeError: 'Obstacle' object has no attribute 'speed_top_border'
【问题讨论】:
-
究竟是什么在这里不能正常工作?如果您遇到错误,请在您的问题中包含完整的错误回溯。如果您没有得到预期的行为,请说明您的实际行为与预期行为是什么。
-
@ThierryLathuille 哦,对不起,我添加了它
-
请始终包含 complete 错误回溯...
-
另外,请注意您将
speed_top_border传递给__init__,但您从未将其存储在任何地方。您可能打算使用self.speed_top_border = speed_top_border创建一个属性。 -
@ThierryLathuille 感谢您的提示。我现在添加了完整的消息
标签: python class object parameters pygame