0
votes

Im learning how to use pygame and I'm trying to use multiple images with the same sprite. I want the sprites image to change when i press a button on my keyboard. Whenever i press the right arrow key and attempt to change the sprites image I get the error:

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

Here is my code:

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
Just FYI: Don't inherit Camel into Game. That's not how you should model the relationship. Camel is in the Game, Game should not be of type Camel. - shadowbq

1 Answers

0
votes

Don't forget the parentheses after self.rect=self.image.get_rect in your look method. Without parenthesis self.rect is assigned to the function instead of the returned rectangle. Since this rectangle is used to draw the image it will cause this position error.