Search code examples
pythonpygame

I want my player (image) to move left and right


I'm new to programing and I need help to move my player (image) to left and right (hopefully with keybindings)

I really don't know what I'm doing and I just need help, please help

Here's my code so far:


import pygame

# Intialize the pygame
pygame.init()

# Resulution?
screen = pygame.display.set_mode((800, 600))

# Title and Logo
pygame.display.set_caption("Båtisens Herre")
icon = pygame.image.load('img.png')
pygame.display.set_icon(icon)

#Background
background = pygame.image.load("bakgrunn.png")

# Player
playerImg = pygame.image.load('King Arthur2.png')
playerX = 100
playerY = 200

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

#game loop 

running = True
while running:

    # RGB (red, green blue)
    screen.fill((248, 58, 226))
    playerY -=0
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

#Background(2)
    screen.blit(background, (0, 0,))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

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


Solution

  • You have to change the x-coordinate of the player. For instance move the player by pressing a and d:

    #game loop 
    
    clock = pygame.time.Clock()
    running = True
    while running:
        clock.tick(100)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
    
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
            playerX -= 1
        if keys[pygame.K_d]:
            playerX += 1
    
        screen.blit(background, (0, 0,))
        player(playerX, playerY)
        pygame.display.update() 
    

    Explanations:

    pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.


    pygame.event.get() get all the messages and remove them from the queue. See the documentation:. See the documentation:

    This will get all the messages and remove them from the queue. [...]

    If pygame.event.get() is called in multiple event loops, only one loop receives the events, but never all loops receive all events. As a result, some events appear to be missed.


    Use pygame.time.Clock to control the frames per second and thus the game speed.

    The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick():

    This method should be called once per frame.

    That means that the loop:

    clock = pygame.time.Clock()
    run = True
    while run:
       clock.tick(100)
    

    runs 100 times per second.