你好,我是Python的新手,这是我在这里的第一个帖子!我正在创建一个使用街机库的小游戏。其中一种叫做draw的方法是用来在屏幕上显示游戏图像的,它工作得很好。但是,我在不同的文件中重用它,并重复相同的代码,所以我试图找到一种使用继承的方法。这是我的父类FlyingObject
class FlyingObject(ABC):
def __init__(self):
# object location is Point()
self.center = Point()
self.velocity = Velocity()
self.alive = True
# self.img = img
# self.texture = arcade.load_texture(self.img)
# self.width = self.texture.width
# self.height = self.texture.height
self.radius = SHIP_RADIUS
self.angle = 0
self.speed = 0
self.direction = 0
def draw(self):
pass
def is_alive(self):
return self.alive
def advance(self):
self.wrap()
self.center.y += self.velocity.dy
self.center.x += self.velocity.dx
def wrap(self):
# wraps the objects on the screen
if self.center.x > SCREEN_WIDTH:
self.center.x -= SCREEN_WIDTH
if self.center.x < 0:
self.center.x += SCREEN_WIDTH
if self.center.y > SCREEN_HEIGHT:
self.center.y -= SCREEN_HEIGHT
if self.center.y < 0:
self.center.y += SCREEN_HEIGHT和一个名为Bullet的子类
class Bullet(FlyingObject):
def __init__(self, ship_angle, ship_x, ship_y, img):
super().__init__()
self.radius = BULLET_RADIUS
self.life = BULLET_LIFE
self.speed = BULLET_SPEED
self.angle = ship_angle - 90
self.center.x = ship_x
self.center.y = ship_y
bulletShot = Bullet("")
bulletShot.draw(self)
def fire(self):
self.velocity.dx -= math.sin(
math.radians(self.angle + 90)) * BULLET_SPEED
self.velocity.dy += math.cos(
math.radians(self.angle + 90)) * BULLET_SPEED
def draw(self):
img = "images/laser.png"
texture = arcade.load_texture(img)
width = texture.width
height = texture.height
alpha = 255 # For transparency, 1 means transparent
x = self.center.x
y = self.center.y
angle = self.angle
arcade.draw_texture_rectangle(x, y, width, height, texture, angle,
alpha)
def advance(self):
super().advance()
self.life -= 1
if self.life <= 0:
self.alive = False因此,draw()方法是以相同的方式使用不同的模块,只是不同的图像。我假设我应该在draw()中移动FlyingObject()方法,以便继承它。我怎么能做到这一点?
发布于 2022-03-19 20:43:22
准确地说,您将(覆盖)绘图方法移动到FlyingObject中,并传递参数img:
def draw(self, img):或者另一个选项,您移动绘图方法,然后将img作为init方法中类的参数:
def draw(self): # in FlyingObject
img = self.img和:
def __init__(self, ship_angle, ship_x, ship_y, img):
super().__init__()
self.img = "images/laser.png"https://stackoverflow.com/questions/71541708
复制相似问题