mustafa bolat
mustafa bolat

Reputation: 37

Pygame when you press on key move image to position

Hey I want to learn how to move your image to a position.

I searched on Google and Youtube but I got a little bit information.

This is my code

import pygame as pg

pg.init()

# Create screen
screen = pg.display.set_mode((1100, 700))

# Background
background = pg.image.load('map.png')

# Player
playerImg = pg.image.load('player.png')
playerX = 80
playerY = 595


def player(x, y):
    screen.blit(playerImg, (x, y))

# Game Loop
running = True
while running:
    # Background image
    screen.blit(background, (0, 0))

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

        # If keystroke is pressed check whether its right or left
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_q:
                screen.blit(playerImg, [80, 598])

            if event.key == pg.K_w:
                screen.blit(playerImg, [370, 598])

            if event.key == pg.K_e:
                screen.blit(playerImg, [665, 598])

            if event.key == pg.K_r:
                screen.blit(playerImg, [950, 598])


    if playerX <= 80:
        playerX = 80
    elif playerX >= 950:
        playerX = 950

    player(playerX, playerY)
    pg.display.update()

The problem what I have now

When I press one of the keys it shows the image but for like 1 second.

What I want

When I press the key it show the image and when I press the second key

I want that the image go to the new position.

Upvotes: 1

Views: 298

Answers (1)

Rabbid76
Rabbid76

Reputation: 210968

If you don't want to show the image a the beginning, then init the player coordinates with an off screen position. If a key is pressed, then you have to change the position (playerX, playerY):

playerX = -100
playerY = -100

running = True
while running:
    # Background image
    screen.blit(background, (0, 0))

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

        # If keystroke is pressed check whether its right or left
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_q:
                playerX, playerY = 80, 598

            if event.key == pg.K_w:
                playerX, playerY = 370, 598

            if event.key == pg.K_e:
                playerX, playerY = 665, 598

            if event.key == pg.K_r:
                playerX, playerY = 950, 598

    player(playerX, playerY)
    pg.display.update()

screen.blit(playerImg, ...) would just draw a 2nd player at a different position, for 1 single frame. That is hardly noticeable and may just cause a short flicker of a 2nd player image.
Note, the KEYDOWN event occurs once only, when the button is pressed. In that case your code blit a player, but it gets "cleared" immediately in the next frame by screen.blit(background, (0, 0)).

Upvotes: 1

Related Questions