如何在pygame上使用具有相同精灵的多个图像?

时间:2016-08-14 08:12:36

标签: python pygame sprite

我正在学习如何使用pygame,我正在尝试使用相同精灵的多个图像。当我按下键盘上的按钮时,我想要更改精灵图像。每当我按下右箭头键并尝试更改精灵图像时,我都会收到错误:

Traceback (most recent call last):
  File "C:\Users\theotheo36\workspace\NomadsPie\main.py", line 55, in <module>
    game.execute()
  File "C:\Users\theotheo36\workspace\NomadsPie\main.py", line 50, in execute
    self.render()
  File "C:\Users\theotheo36\workspace\NomadsPie\main.py", line 32, in render
    self.all.draw(self.screen)
  File "C:\Users\theotheo36\Downloads\WinPython-64bit-3.4.4.3Qt5\python-3.4.4.amd64\lib\site-packages\pygame\sprite.py", line 475, in draw
    self.spritedict[spr] = surface_blit(spr.image, spr.rect)
TypeError: invalid destination position for blit

这是我的代码:

import pygame
from pygame.locals import *
class Camel(pygame.sprite.Sprite):
    def __init__(self,x,y):
        super().__init__()
        self.faceleft=True
        self.faceright=False
        self.image=pygame.image.load('camel.png').convert()
        self.rect=self.image.get_rect()
        self.rect.x=x
        self.rect.y=y
    def look(self):
        if self.faceleft==True:
            self.image=pygame.image.load('camel.png').convert()
            self.rect=self.image.get_rect()
        elif self.faceright==True:
            self.image=pygame.image.load('camelright.png').convert()
            self.rect=self.image.get_rect



class Game(Camel):
    def __init__(self):
        pygame.init()
        self.screen=pygame.display.set_mode((800,800))
        self.all=pygame.sprite.Group()
        self.camel=Camel(200,200)
        self.all.add(self.camel)
        self.running=True
    def render(self):
        self.screen.fill((255,255,255))
        self.all.draw(self.screen)
        pygame.display.update()
    def events(self,event):
        if event.type==pygame.QUIT:
            self.running=False
        if event.type==KEYDOWN:
            if event.key==K_RIGHT:
                self.camel.faceleft=False
                self.camel.faceright=True
                self.camel.look()
            if event.key==K_LEFT:
                self.camel.faceright=False
                self.camel.faceleft=True
                self.camel.look()
    def collisons(self):
        pass
    def execute(self):
        while (self.running):
            self.render()
            for event in pygame.event.get():
                self.events(event)

game=Game()
game.execute()

1 个答案:

答案 0 :(得分:0)

请勿在{{1​​}}方法中忘记self.rect=self.image.get_rect后的括号。没有括号look被分配给函数而不是返回的矩形。由于此矩形用于绘制图像,因此会导致此位置错误。