import pygame, random
pygame.init()
screen = pygame.display.set_mode((640, 480))
class Ship(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.screen = screen
self.image = pygame.image.load("ship.jpg")
self.image = self.image.convert()
self.rect = self.image.get_rect()
self.rect.center = (320, 400)
self.dx = 0
self.dy = 0
self.x = self.rect.centerx
self.y = self.rect.centery
def update(self):
self.checkBounds()
def checkBounds(self):
screen = self.screen
if self.x > screen.get_width():
self.x = screen.get_width()
if self.x < 0:
self.x = 0
class Missile(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("missile.jpg")
self.image = self.image.convert()
self.rect = self.image.get_rect()
self.reset()
def update(self):
self.rect.centery += self.dy
if self.rect.top > screen.get_height():
self.reset()
def reset(self):
self.rect.bottom = 0
self.rect.centerx = random.randrange(0, screen.get_width())
self.dy = random.randrange(5, 10)
def main():
background = pygame.Surface(screen.get_size())
background.fill((0, 0, 0))
screen.blit(background, (0, 0))
ship = Ship()
missile = Missile()
allSprites = pygame.sprite.Group(missile, ship)
clock = pygame.time.Clock()
keepGoing = True
while keepGoing:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoing = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
ship.rect.centerx = ship.rect.centerx-10
elif event.key == pygame.K_RIGHT:
ship.rect.centerx = ship.rect.centerx + 10
elif event.type == pygame.KEYUP:
ship.rect.centerx = ship.rect.centerx + 0
elif event.key == pygame.K_DOWN:
ship.rect.centerx = ship.rect.centerx - 0
if pygame.sprite.collide_rect(ship,missile) == True:
self.image = pygame.image.load("explosion.jpg")
allSprites.clear(screen, background)
allSprites.update()
allSprites.draw(screen)
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
答案 0 :(得分:3)
self.image = pygame.image.load("explosion.jpg")
此行不属于任何类。这里没有self
。我想你的意思是
ship.image = pygame.image.load("explosion.jpg")
或类似的东西。可能也是
missile.image = pygame.image.load("explosion.jpg")