2016-11-21 184 views
0

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

# !/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

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

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移动到绘制导弹之前。

+0

Aww,该死的。我已经太久了。这是一个真正的牛皮纸袋错误。非常感谢。我会去拍自己,然后喝点咖啡。 – headbanger