我对 OOP 和 Pygame 比较陌生,一直在尝试编写塔防游戏,但遇到了障碍。我不断收到此错误:
AttributeError: type object 'Game' has no attribute 'path'
我曾尝试阅读有相同问题的人的帖子,但似乎没有任何修复对我有用。
我试图在我的游戏中有几个不同的级别,它们具有不同的背景,因此具有不同的路径。我试图通过创建一个父Game
类然后为每个级别创建一个子类来做到这一点。(我程序中的每个类都有不同的 .py 文件。)理想情况下,每个关卡子类都有自己的path
属性,该属性将覆盖path
游戏类中的属性。然后将其path
传递到我的Enemy
班级,其中有使敌人跟随路径的代码。
我可以通过将self.path
(在我的游戏类中)放在构造函数之上并将其定义为path
. 但是在这样做时,我无法或不知道如何覆盖子类中的属性。
此外,在我的敌人类中,我试图通过将游戏类放在较低的位置来规避与游戏类进行循环导入的问题,我认为这可能与它有关,但是,我不确定。
如果是这种情况,是否有更好的方法让我的敌人班级访问该路径?
这是我的关卡选择文件的相关代码:
# If button is pressed then execute its corresponding function
if event.type == pygame.MOUSEBUTTONDOWN:
# If level 1 button is pressed then instantiate Level 1
if level1.buttonPress(pos):
level1_class = Level1(self.screen)
# Runs the main game loop for the instantiated level
level1_class.run()
这是我班级的相关代码Enemy:
import pygame
lightGreen = (0, 255, 0)
red = (200, 0, 0)
# Creates Enemy class
class Enemy(pygame.sprite.Sprite):
imgs = []
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.width = 150
self.height = 150
self.max_health = 100
self.health = 100
self.path = [(0, 0)]
self.x = self.path[0][0]
self.y = self.path[0][1]
self.img = None
self.animation = 0
self.speed = 1
self.i = 1
self.pos_check = 0
# Draws the sprite to the screen
def draw(self, screen):
# Only works for the first time it is called
if self.pos_check == 0:
self.pos_check += 1
# Sets starting x and y as the first co-ordinates of the path
from Game import Game
self.x = Game.path[0][0]
self.y = Game.path[0][1]
# Chooses an image from a list of images based on the number of self.animation
self.img = self.imgs[self.animation]
# Draws image
screen.blit(self.img, (self.x - self.width / 2, self.y - self.height / 2))
# Draws health bar
self.draw_health_bar(screen)
慕少森
相关分类