您好,我是 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()以便我可以繼承它。我怎么能做到這一點?
uj5u.com熱心網友回復:
確切地說,您將 draw 方法移動(覆寫)到FlyingObject并傳遞引數 img:
def draw(self, img):
或者另一種選擇,移動 draw 方法,然后將 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://www.uj5u.com/houduan/446821.html
下一篇:從其屬性訪問類物件
