Pygame精灵没有画出来

时间:2016-11-21 14:56:38

标签: python-3.x pygame sprite

我正在玩Python,尝试编写一个(非常)简单的太空入侵者游戏 - 但是我的子弹精灵并没有被绘制出来。我现在正在使用相同的图形 - 只要我有其他一切工作,我就会对图形进行美化。这是我的代码:

# !/usr/bin/python

import pygame

bulletDelay = 40

class Bullet(object):
    def __init__(self, xpos, ypos, filename):
        self.image = pygame.image.load(filename)
        self.rect = self.image.get_rect()
        self.x = xpos
        self.y = ypos

    def draw(self, surface):
        surface.blit(self.image, (self.x, self.y))


class Player(object):
    def __init__(self, screen):
        self.image = pygame.image.load("spaceship.bmp")       # load the spaceship image
        self.rect = self.image.get_rect()                     # get the size of the spaceship
        size = screen.get_rect()
        self.x = (size.width * 0.5) - (self.rect.width * 0.5) # draw the spaceship in the horizontal middle
        self.y = size.height - self.rect.height               # draw the spaceship at the bottom

    def current_position(self):
        return self.x

    def draw(self, surface):
        surface.blit(self.image, (self.x, self.y))            # blit to the player position


pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
player = Player(screen)                                       # create the player sprite
missiles = []                                                 # create missile array
running = True
counter = bulletDelay

while running: # the event loop
    counter=counter+1
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             running = False
    key = pygame.key.get_pressed()
    dist = 1                   # distance moved for each key press
    if key[pygame.K_RIGHT]:    # right key
        player.x += dist
    elif key[pygame.K_LEFT]:   # left key
        player.x -= dist
    elif key[pygame.K_SPACE]:  # fire key
        if counter > bulletDelay:
            missiles.append(Bullet(player.current_position(),1,"spaceship.bmp"))
            counter=0

    for m in missiles:
        if m.y < (screen.get_rect()).height and m.y > 0:
            m.draw(screen)
            m.y += 1
        else:
            missiles.pop(0)

    screen.fill((255, 255, 255))  # fill the screen with white
    player.draw(screen)           # draw the spaceship to the screen
    pygame.display.update()       # update the screen
    clock.tick(40)

有没有人有任何建议为什么我的子弹没有被抽出?

手指交叉,你可以提供帮助,并提前感谢你。

1 个答案:

答案 0 :(得分:1)

正在绘制子弹。但是由于你编写代码的方式,你永远不会看到它!首先绘制所有子弹,然后立即用白色填充屏幕。这种情况发生得如此之快,以至于您无法看到它们。试试这个,你会明白我的意思:

for m in missiles:
    if m.y < (screen.get_rect()).height and m.y > 0:
        m.draw(screen)
        m.y += 1
    else:
        missiles.pop(0)

# screen.fill((255, 255, 255))  # fill the screen with white
player.draw(screen)           # draw the spaceship to the screen
pygame.display.update()       # update the screen
clock.tick(40)

一种解决方案是在绘制导弹之前将screen.fill移动到。