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.ACTIVEEVENT의 이벤트에 대해 알아보도록 하겠습니다.

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



종료 이벤트 QUIT

키보드 입력 이벤트 KEYDOWN/UP

마우스 움직임 이벤트 MOUSEMOTION

마우스 클릭 이벤트 MOUSEBUTTONDOWN/UP






01. pygame.ACTIVEEVENT 이벤트 예제

pygame.ACTIVEEVENT은 게임 화면에 마우스가 있는지 없는지에 따라 발생하는 이벤트입니다.

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

# 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  = True
clock = pygame.time.Clock()

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.ACTIVEEVENT: # If user's mouse in the display or out.
            flag ^= True
        elif event.type == pygame.QUIT:
            done  = True                     # If user clicked close.

 
    # 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)

    # Drawing House If User Mouse Is In Display.
    if flag == True:
        pygame.draw.polygon(screen, GREEN, [[30, 150], [125, 100], [220, 150]], 5)
        pygame.draw.polygon(screen, GREEN, [[30, 150], [125, 100], [220, 150]], 0)
        pygame.draw.lines(screen, RED, False, [[50, 150], [50, 250], [200, 250], [200, 150]], 5)
        pygame.draw.rect(screen, BLACK, [75, 175, 75, 50], 5)
        pygame.draw.rect(screen, BLUE, [75, 175, 75, 50], 0)
        pygame.draw.line(screen, BLACK, [112, 175], [112, 225], 5)
        pygame.draw.line(screen, BLACK, [75, 200], [150, 200], 5)

    # Print Message If User Mouse Is In Outside.
    else:
        textSurface      = font.render('Mouse is outside!!', True, pygame.Color('BLACK'), None)
        textRect         = textSurface.get_rect()
        textRect.topleft = (50, 50)

        screen.blit(textSurface, textRect)

    # 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.ACTIVEEVENT 이벤트 예제 설명

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


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

    # Main Event Loop
    for event in pygame.event.get(): # User did something
        if event.type == pygame.ACTIVEEVENT: # If user's mouse in the display or out.
            flag ^= True
        elif event.type == pygame.QUIT:
            done  = True                     # If user clicked close.

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

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

34번째 라인에서는 pygame의 이벤트 중 ACTIVEEVENT 타입인지 확인하고, 35번째 라인은 ACTIVEEVENT가 발생할 때 변화를 보여주기 위한 flag 값입니다.

해당 이벤트는 게임 창에 마우스가 들어가거나 나갈 때 발생하거나, 활성화의 상태에 따라 달라집니다.

그외의 36번째 ~ 37번째 라인은 닫기 버튼을 누르면 게임이 꺼질 수 있도록 pygame.QUIT 이벤트에 루프를 벗어나기 위한 설정을 해두었습니다.


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

    # Drawing House If User Mouse Is In Display.
    if flag == True:
        pygame.draw.polygon(screen, GREEN, [[30, 150], [125, 100], [220, 150]], 5)
        pygame.draw.polygon(screen, GREEN, [[30, 150], [125, 100], [220, 150]], 0)
        pygame.draw.lines(screen, RED, False, [[50, 150], [50, 250], [200, 250], [200, 150]], 5)
        pygame.draw.rect(screen, BLACK, [75, 175, 75, 50], 5)
        pygame.draw.rect(screen, BLUE, [75, 175, 75, 50], 0)
        pygame.draw.line(screen, BLACK, [112, 175], [112, 225], 5)
        pygame.draw.line(screen, BLACK, [75, 200], [150, 200], 5)

    # Print Message If User Mouse Is In Outside.
    else:
        textSurface      = font.render('Mouse is outside!!', True, pygame.Color('BLACK'), None)
        textRect         = textSurface.get_rect()
        textRect.topleft = (50, 50)

        screen.blit(textSurface, textRect)

46번째 라인은 위의 35번째 라인에서 flag라는 변수가 True혹은 False로 바뀌었을 때 출력되도록 설정한 코드입니다.

마우스가 밖으로 나가거나 화면 안으로 들어올 때마다 True 혹은 False로 바뀌도록 하였습니다.

57번째 라인부터 62번째 라인은 화면에 글씨가 출력될 수 있도록 하는 코드입니다.

이는 추후에 다루도록 하겠습니다.

<

+ Recent posts