My object is not moving

I create it with pygame. In the program there is a red image wich should moving with the arrows, but nothing is happening

Replit link: https://replit.com/@TasosKhatzes/Moving-objects?v=1

import pygame, sys
from pygame.locals import QUIT
pygame.init()
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption('moving')
object0 = pygame.image.load('object.png')
object = pygame.transform.scale(object0, [50, 50])
x = 300
y = 30
while True:
	screen.blit(object, [x , y])
	for event in pygame.event.get():
		if event.type == QUIT:
			pygame.quit()
			sys.exit()
		if event.type == pygame.KEYDOWN:
			if event.type == pygame.K_UP:
				y -= 5
			if event.type == pygame.K_DOWN:
				y += 5
			if event.type == pygame.K_RIGHT:
				x += 5
			if event.type == pygame.K_LEFT:
				x -= 5


	pygame.display.update()

Is anything wrong?

Hi there @TasosKhatzes! All you need to do is change your key comparisons to compare with the key attribute, not the type attribute of the event object.

e.g.

import pygame, sys
from pygame.locals import QUIT
pygame.init()
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption('moving')
object0 = pygame.image.load('object.png')
object = pygame.transform.scale(object0, [50, 50])
x = 300
y = 30
while True:
    screen.blit(object, [x , y])
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                y -= 5
            if event.key == pygame.K_DOWN:
                y += 5
            if event.key == pygame.K_RIGHT:
                x += 5
            if event.key == pygame.K_LEFT:
                x -= 5


    pygame.display.update()
4 Likes

Another thing with the above code (not sure if this is intentional), is that it leaves the last block on the screen.

If this is not intentional you can just add the line screen.fill((0,0,0)) above screen.blit(object, [x , y])

2 Likes

Thank you very much. It works. But I want it to work if I press the buttons continuously.

For this you can use pygame.key.get_pressed!

An example of this code can be seen below:

while running:
    keys = pygame.key.get_pressed()  #checking pressed keys
    if keys[pygame.K_UP]:
        y1 -= 1
    if keys[pygame.K_DOWN]:
        y1 += 1

Just adjust the variable change and your good to go.
Good luck!

3 Likes

I tried it it doesn’t work.
check out my code to see if I did something wrong: https://replit.com/@TasosKhatzes/Moving-objects?v=1