Pygame

[Pygame(파이게임)] 플레이어 움직이기1 (상하좌우 이동)

namu999 2025. 4. 24. 12:48
728x90

이전 글에서는 게임 창을 띄우고, 임의의 상자 하나를 추가하기까지 하였다.

이제 상자를 키보드의 상하좌우 키로 움직여 볼 것이다.


우선 ←(왼쪽 방향키), →(오른쪽 방향키로) 상자를 이동시켜보자.

import pygame

#사용 할 색상들 미리 변수로 저장
WHITE, RED = (255,255,255), (255,0,0)

pygame.init()
pygame.display.set_caption("START!")
screen = pygame.display.set_mode((800,600))
clock = pygame.time.Clock()


#플레이어의 위치,속도 모두 0으로 초기화
p_x,dx=0,0

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done=True

        #키가 눌렸을때,
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:dx=-5
            elif event.key == pygame.K_RIGHT:dx=5
                
        #키가 떨어졌을때,
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:dx=0

    #한 틱마다 p_x 의 위치 변경
    p_x+=dx

    
    screen.fill(WHITE)
    pygame.draw.rect(screen,RED,[p_x,500,10,10],0)
    
    pygame.display.flip()
    clock.tick(60)
    
pygame.quit()

상자는 pygame.draw.rect(screen,RED,[p_x,500,10,10],0) 로 그려지고 있다.

y좌표는 500으로 고정된 상태에서 x좌표만 변수 p_x에 따라 바뀔 수 있다.

이 p_x는 아래 코드를 통해 바뀐다.

        #키가 눌렸을때,
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:dx=-5
            elif event.key == pygame.K_RIGHT:dx=5
                
        #키가 떨어졌을때,
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:dx=0

pygame.event.get() 에서 가져온 이벤트들 중에서,

  • 키가 눌렸는지, 떼졌는지에 대한 이벤트인지
  • 눌리거나 떼진  키가 왼쪽 방향키인지, 오른쪽 방향키인지

에 따라서 각각 속도의 방향과 크기를 조절한다.

그리고 이후,

    #한 틱마다 p_x 의 위치 변경
    p_x+=dx

이 코드에서 발생한 이벤트에 따라 바뀐 속도를 위치(p_x)에 반영한다.


y축 이동도 같은 방식으로 진행된다.

import pygame

#사용 할 색상들 미리 변수로 저장
WHITE, RED = (255,255,255), (255,0,0)

pygame.init()
pygame.display.set_caption("START!")
screen = pygame.display.set_mode((800,600))
clock = pygame.time.Clock()


#플레이어의 위치,속도 모두 0으로 초기화
p_x,dx=400,0
p_y,dy=300,0
done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done=True

        #키가 눌렸을때,
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:dx=-5
            elif event.key == pygame.K_RIGHT:dx=5
            elif event.key == pygame.K_UP:dy=-5
            elif event.key == pygame.K_DOWN:dy=5
                
        #키가 떨어졌을때,
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:dx=0
            elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:dy=0

    #한 틱마다 위치 변경
    p_x+=dx
    p_y+=dy

    screen.fill(WHITE)
    pygame.draw.rect(screen,RED,[p_x,p_y,10,10],0)
    
    pygame.display.flip()
    clock.tick(60)
    
pygame.quit()

 

728x90