pygame을 사용할 때 pygame 자체적으로 제공하는 Event 목록을 적절하게 이용하게 되면, 훨씬 게임을 유용하게 코딩할 수 있게 됩니다.

이벤트는 마우스, 키보드, 조이스틱, 디스플레이 및 기타 여러 가지 행동에 대한 상태 정보를 인지하여 좀 더 유용한 코딩을 가능하게 합니다.

먼저 이벤트 목록에 대해 알아보겠습니다.


00. pygame Event 목록

pygame에서 제공하는 Event 목록은 다음과 같습니다.

이벤트 이름

 이벤트 속성

 설명

 pygame.QUIT

 none

 게임 종료 버튼(창 닫기 버튼) 클릭 시 발생함

 pygame.ACTIVEEVENT

 gain, state

 화면 활성화에 대한 이벤트로, 화면(GUI)에 마우스가 들어가거나 나가면 발생함

 혹은 화면이 활성화 상태이면 발생함

 pygame.KEYDOWN

 unicode, key, mod

 키보드를 누른 후 뗄 때 발생함

 pygame.KEYUP

 key, mod

 키보드를 누를 때 발생함

 pygame.MOUSEMOTION

 pos, rel, buttons

 마우스가 움직일 때 발생함

 pygame.MOUSEBUTTONUP

 pos, button

 마우스 버튼을 누른 후 뗄 때 발생함

 pygame.MOUSEBUTTONDOWN

 pos, button

 마우스 버튼을 눌렀을 때 발생함

 pygame.JOYAXISMOTION

 joy, axis, value

 조이스틱 축이 변경되면 발생함

 pygame.JOYBALLMOTION

 joy, ball, rel

 조이스틱 볼이 움직이면(회전하면) 발생함

 pygame.JOYHATMOTION

 joy, hat, value

 조이스틱 hat이 바뀌면 발생함

 pygame.JOYBUTTONUP

 joy, button

 조이스틱 버튼을 눌렀을 때 발생함

 pygame.JOYBUTTONDOWN

 joy, button

 조이스틱 버튼을 누른 후 뗄 때 발생함

 pygame.VIDEORESIZE

 size, w, h

 디스플레이가 pygame.RESIZABLE 플래그로 설정되면, 사용자가 창 크기를 조정하기 위해 발생함

 pygame.VIDEOEXPOSE

 none

 화면의 일부를 다시 그려야 하는 경우 화면에 직접 그리는 하드웨어 디스플레이가 발생시킴

 pygame.USEREVENT

 code

 사용자가 임의로 설정하는 이벤트


위와 같이 다양한 이벤트 목록을 제공합니다.

우리는 여기서 pygame.MOUSEMOTION의 이벤트에 대해 알아보도록 하겠습니다.

만약 다른 pygame 이벤트에 대한 자료를 참고하고 싶으시다면 아래의 링크에서 선택하시면 될 것 같습니다.



종료 이벤트 QUIT

화면 활성화 이벤트 ACTIVEEVENT

키보드 입력 이벤트 KEYDOWN/UP

마우스 클릭 이벤트 MOUSEBUTTONDOWN/UP




01. pygame.MOUSEMOTION 이벤트 예제

pygame.MOUSEMOTION은 게임 화면에서 마우스가 움직이게 되면 발생하는 이벤트입니다.

다음 예제를 먼저 살펴보도록 하겠습니다.

# Import a library of functions called 'pygame'
import pygame

# Initialize the game engine
pygame.init()

# Define the colors we will use in RGB format
BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
BLUE  = (  0,   0, 255)
GREEN = (  0, 255,   0)
RED   = (255,   0,   0)

# Set the height and width of the screen
size   = [400, 300]
screen = pygame.display.set_mode(size)
font = pygame.font.SysFont("consolas", 20)

pygame.display.set_caption("Game Title")
 
#Loop until the user clicks the close button.
done  = False
flag  = None
clock = pygame.time.Clock()

# print text function
def printText(msg, color='BLACK', pos=(50, 50)):
    textSurface      = font.render(msg, True, pygame.Color(color), None)
    textRect         = textSurface.get_rect()
    textRect.topleft = pos

    screen.blit(textSurface, textRect)

while not done:

    # This limits the while loop to a max of 10 times per second.
    # Leave this out and we will use all CPU we can.
    clock.tick(10)
    
    # Main Event Loop
    for event in pygame.event.get(): # User did something
        if event.type == pygame.MOUSEMOTION: # If user release what he pressed.
            flag = True
        elif event.type == pygame.QUIT:  # If user clicked close.
            done = True                  

    
    # All drawing code happens after the for loop and but
    # inside the main while done==False loop.
     
    # Clear the screen and set the screen background
    screen.fill(WHITE)

    # Print red text if user pressed any key.
    if flag == True:
        printText('Your mouse is now moving!!', 'RED')
        flag = False

    # Print blue text if user released any key.
    elif flag == False:
        printText('Your mouse is now stopped!!', 'BLUE')

    # Go ahead and update the screen with what we've drawn.
    # This MUST happen after all the other drawing commands.
    pygame.display.flip()

# Be IDLE friendly
pygame.quit()


위의 예제의 결과는 다음과 같습니다.





02. pygame.MOUSEMOTION 이벤트 예제 설명

결과를 확인하셨다면, 어떤 원리인지 위의 예제의 특정 라인을 통해 자세히 설명해보도록 하겠습니다.


먼저 41번째 라인에서 45번째 라인을 보도록 하겠습니다.

    # Main Event Loop
    for event in pygame.event.get(): # User did something
        if event.type == pygame.MOUSEMOTION: # If user release what he pressed.
            flag = True
        elif event.type == pygame.QUIT:  # If user clicked close.
            done = True         

41번째 라인에서는 pygame.event.get() 함수를 통해 사용자가 발생시킨 이벤트를 가져옵니다.

가져온 이벤트 중 하나를 event라는 변수로 생각하고, 해당 이벤트의 type을 검사합니다.

42번째 라인에서는 pygame의 이벤트 중 MOUSEMOTION 타입인지 확인하여, 마우스가 움직이는 이벤트가 발생했는지 확인합니다.

만약 MOUSEMOTION 이벤트가 발생하면 flag를 True로 만들어줍니다.


55번째 라인에서 61번째 라인을 보도록 하겠습니다.

    # Print red text if user pressed any key.
    if flag == True:
        printText('Your mouse is now moving!!', 'RED')
        flag = False

    # Print blue text if user released any key.
    elif flag == False:
        printText('Your mouse is now stopped!!', 'BLUE')

55번째 라인에서 만약 MOUSEMOTION 이벤트가 발생하여 flag가 True가 된다면, 마우스가 움직이는지 확인할 수 있도록 문자를 출력해보았습니다.

이후 MOUSEMOTION 이벤트 상태가 지속되지 않도록 하기 위해서는 True일 때마다 flag를 False로 초기화해줍니다.

그러면 다시 마우스가 움직이지 않을 때 움직이지 않음을 나타내는 문자를 출력할 수 있습니다.


+ Recent posts