PythonerLMAO
PythonerLMAO

Reputation: 41

How to attach an image to a rect in pygame?

I need help attaching an image to a rectangle in pygame.. I am trying to make a snake game in python(you know, the one that eats the apples and grows lol) and I wanna attach my teacher's face to head of the snake.

I've already tried defining a variable to import the image and then renaming the rectangle to be that image, but nothing seems to work.

snakeFace = pygame.image.load("Morrison.jpg").convert_alpha()
rect = snakeFace.get_rect()
screenWidth = 500
X=50
y= 50
height = 20
vel = 20
run = True
lastKey = None
while run:
    pygame.time.delay(10) #1/2 milisecond delay
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        run = False #this controls the "X" button
    if event.type == pygame.KEYDOWN:
        lastKey = event.key

    keys = pygame.key.get_pressed()
    if lastKey == pygame.K_LEFT and x > vel:
        x-=vel
    if lastKey == pygame.K_RIGHT and x< screenWidth - width -vel:
        x+=vel
    if lastKey == pygame.K_DOWN and y < screenWidth - height - vel:
        y+= vel
    if lastKey == pygame.K_UP and y > vel:
        y-=vel

    win.fill((0,0,0))
    pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
    pygame.display.update()

I expected there to be a square with my teachers face on it that runs around on the screen after a particular key is pressed on the screen but its just the regular old red square.

Upvotes: 1

Views: 2775

Answers (2)

Jan97
Jan97

Reputation: 21

Here is the full example code that I use to add images to rect objects.

 import pygame

  vel = 5

  pygame.init()

  screen = pygame.display.set_mode((800,600))

pygame.display.set_caption('captions')
icon = pygame.image.load('test123.jpg')
pygame.display.set_icon(icon)

playerimg = pygame.image.load('test123.jpg')
playerx = 370
playery = 480


def player():
    screen.blit(playerimg,(playerx,playery))

running = True
while running:

    screen.fill((0, 0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        keys = pygame.key.get_pressed()

        if keys[pygame.K_a] and playerx > vel:
            playerx += vel

    player()
    pygame.display.update()

Upvotes: 0

Kingsley
Kingsley

Reputation: 14906

It's a red square because the code is drawing a red square:

pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))

Paint the snakeFace bitmap instead:

win.blit(snakeFace, (x, y))

Upvotes: 2

Related Questions