May-25-2021, 04:40 PM
Here's something that hopefully helps. It shows the arrow keys, continuous movement by holding a key down, and smooth movement using an fps clock/delta time, as well as clamping the values so you don't fly off the screen.
import pygame as pg BLACK = (0, 0, 0) WHITE = (255, 255, 255) def main(screen, max_x, max_y): x, y = 50, 50 width, height = 50, 50 clock = pg.time.Clock() x_movement = 0 delta = 0 while True: for event in pg.event.get(): if event.type == pg.QUIT: return if event.type == pg.KEYDOWN: # start moving left/right if the keys are pressed if event.key == pg.K_LEFT: x_movement = -1 elif event.key == pg.K_RIGHT: x_movement = 1 elif event.type == pg.KEYUP: # stop movement if the key is un-pressed if event.key in [pg.K_LEFT, pg.K_RIGHT]: x_movement = 0 x += (delta * x_movement) # clamp x if x <= 0: x = 0 elif x >= max_x - width: x = max_x - width screen.fill(BLACK) pg.draw.rect(screen, WHITE, (x, y, width, height), 0) pg.display.update() delta = clock.tick(60) if __name__ == "__main__": pg.init() width, height = 500, 800 screen = pg.display.set_mode((width, height)) main(screen, width, height)