import pygame, sys
from pygame.locals import *

pygame.init()

WIDTH = 700
HEIGHT = 600

DISPLAYSF = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Title")

col_arr = [(255, 0, 0),(0, 255, 0),(0, 0, 255)]
col = 0
run = True
player_pos = [300,250]

while run:
    DISPLAYSF.fill((255,255,255))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            col += 1

    # 키 상태를 지속적으로 확인
    keys = pygame.key.get_pressed()
    if keys[pygame.K_RIGHT]:    
        player_pos[0] += 0.5
    elif keys[pygame.K_LEFT]:
        player_pos[0] -= 0.5

    rect = pygame.Rect(player_pos[0],player_pos[1],100,100)
    pygame.draw.rect(DISPLAYSF,col_arr[col%3],rect)

    pygame.display.update()
    
pygame.quit()
sys.exit()

코드 설명:

1. Pygame 초기화 및 화면 설정

import pygame, sys
from pygame.locals import *

pygame.init()

WIDTH = 700
HEIGHT = 600

DISPLAYSF = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Title")

2. 변수 초기화

col_arr = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
col = 0
run = True
player_pos = [300, 250]

3. 게임 루프

while run:
    DISPLAYSF.fill((255, 255, 255))

4. 이벤트 처리

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        run = False
    if event.type == pygame.KEYDOWN:
        col += 1