So I was following some videos on youtube on how to create Pacman using Pygame and it only showed how to draw a simple yellow circle, I'm trying to replace that simple shape with an actual sprite but I couldn't make it work here's my code, I have a class called "Player" where I draw my pacman character, I use pygame's draw function to draw a simple yellow circle
def draw(self):
pygame.draw.circle(self.app.screen,PLAYER_COLOUR, (int(self.pix_pos.x), int(self.pix_pos.y)),
self.app.cell_width//2-2)
and then I have another class called "app_class" where I make a new instance of "Player" class and place it in the correct position
I tried replacing draw with image.load but it didn't work.
The module pygame.draw
only contains functions for drawing simple shapes. If that's not what you want, then you have to use another module.
pygame.image.load
is a function that will load an image from your hardrive into main memory. You can think of it like getting an image from your computer into your program. So it doesn't do anything other than making the image available.
To be able to draw the image, you have to explicitly tell pygame to do so. You do it by calling the method blit
on the Surface object, in your case the screen.
So first load in the image at the start of your program. You shouldn't call this function every game loop, because it's expensive. Only call this once.
my_image = pygame.image.load('path/to/my_image.jpg').convert()
The convert
method is just a method to make the image more efficient in your program. It'll convert the image so it'll have the right color format. You should see no difference if you exclude it, but you'll gain performance if you do.
The you need to blit ('draw') it onto the screen. In your case, you'd do something like this:
def draw(self):
self.app.screen.blit(my_image, (x, y))
where x and y is the position you want the image to be at, or more precisely, where you want the top-left corner to be located at. Currently, the x and y is undefined, so you have to define them yourself. Either make them global or put them into your class and access them with self.x
and self.y
.
Also, the image might not be the size you want. To fix it, you could resize it right after loading it in, like so:
width = 50 # Or whatever size you want it to be.
height = 50
my_image = pygame.image.load('path/to/my_image.jpg').convert()
my_image = pygame.transform.scale(my_image, (width, height))