我正在制作一个 pygame 程序来动画精灵,但问题不是一个特定的错误:
import sys
import os
import pygame
from pygame.locals import *
pygame.init ()
WHITE = ( 255, 255, 255 )
BLACK = ( 0, 0, 0 )
Surface = pygame.display.set_mode ((400, 400), 0, 32)
pygame.display.set_caption ('Animation Test')
class Processes (object):
@staticmethod
def load_image (imagefile):
image = pygame.image.load (imagefile) #Remember to call imagefile as a string statement
return image, image.get_rect ()
class Sprite (pygame.sprite.Sprite):
def __init__ (self):
pygame.sprite.Sprite.__init__ (self)
self.image, self.rect = Processes.load_image ('frame1.jpg')
self.blindrect = pygame.Rect ((self.rect.top - 289, self.rect.left - 289), (self.rect.width, self.rect.height))
def animation (self, key_event = None, mouse_event = None):
blindpass = 0
if key_event == K_LEFT:
self.rect.centerx = self.rect.centerx - 10
if key_event == K_RIGHT:
self.rect.centerx = self.rect.centerx + 10
if key_event == K_UP:
self.rect.centery = self.rect.centery - 10
if key_event == K_DOWN:
self.rect.centery = self.rect.centery + 10
if mouse_event == MOUSEBUTTONDOWN:
self.rect.centerx, self.rect.centery = pygame.mouse.get_pos ()
if blindpass > 0:
if key_event == K_LEFT:
self.blindrect.centerx = self.blindrect.centerx - 10
if key_event == K_RIGHT:
self.blindrect.centerx = self.blindrect.centerx + 10
if key_event == K_UP:
self.blindrect.centery = self.blindrect.centery - 10
if key_event == K_DOWN:
self.blindrect.centery = self.blindrect.centery + 10
if mouse_event == MOUSEBUTTONDOWN:
self.rect.centerx, self.rect.centery = pygame.mouse.get_pos ()
mecha = Sprite ()
allsprites = pygame.sprite.RenderPlain ((mecha, ))
while True:
Surface.fill (WHITE)
for event in pygame.event.get ():
if event.type == KEYDOWN:
mecha.animation (key_event = event.key)
if event.type == MOUSEBUTTONDOWN:
mecha.animation (mouse_event = event.type)
if event.type == QUIT:
pygame.quit ()
sys.exit (0)
allsprites.draw (Surface)
pygame.display.update ((mecha.rect, mecha.blindrect))
现在,错误有点奇怪。输出是精灵确实出现在屏幕上,当我提供键和鼠标输入时它会移动,但问题是它会留下痕迹。这就是为什么我创建了一个矩形来跟踪精灵矩形,该矩形应该在每次游戏循环循环时用白色填充。但事实并非如此。至少,直到我最小化窗口并再次拉起它,所有的痕迹都消失了,背景变成了白色而不是黑色。但是当我移动图像时,轨迹又开始形成。我最小化,它们按预期消失。