본문 바로가기

코딩/파이썬 pygame

파이썬 게임 005. pygame.Surface.fill 함수로 게임 배경색 변경

Game - Python - Pygame

 

Pygame 패키지의 Surface.fill() 함수를 이용해 게임 배경색을 변경해 본다.

 

본 글에서 사용한 함수 및 참고되는 함수는 다음과 같다.

 

pygame.Surface.fill(color , rect=None, special_flags=0) -> Rect

pygame.Rect(left, top, width, height) -> Rect

pygame.display.update(rectangle=None) -> None

예제 코드 1

<코드 1>

# python 3.9.6
# pygame 2.0.1

import pygame


def main():
    pygame.init()

    screen = pygame.display.set_mode((640, 480))
    print(type(screen))

    rect = screen.fill((255, 255, 0))
    print(type(rect))
    print(rect)

    pygame.display.update()

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT\
                    or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False
                break
        if not running:
            continue

    pygame.quit()


if __name__ == '__main__':
    main()

 

 

<코드 1>을 실행하면 게임 배경색은 노란색으로 그려진다.

 

코드 print(type(screen))의 실행 결과로 알 수 있듯이 pygame.display.set_mode((640, 480)) 코드는 Surface 타입의 데이터를 반환한다.

 

<class 'pygame.Surface'>

 

코드 print(type(rect))와 print(rect)의 실행 결과로 알 수 있듯이 screen.fill((255, 255, 0)) 코드는 Rect 타입의 데이터를 반환한다.

 

<class 'pygame.Rect'>
<rect(0, 0, 640, 480)>

 

코드 pygame.display.update()를 통해 게임 화면을 업데이트한다.

예제 코드 2

<코드 2>

# python 3.9.6
# pygame 2.0.1

import pygame


def main():
    pygame.init()

    screen = pygame.display.set_mode((640, 480))

    screen.fill((255, 0, 0), (100, 100, 300, 300))
    screen.fill((0, 255, 0), (140, 140, 220, 220))
    screen.fill((0, 0, 255), (180, 180, 140, 140))

    pygame.display.update()

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT\
                    or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False
                break
        if not running:
            continue

    pygame.quit()


if __name__ == '__main__':
    main()

 

 

<코드 2>를 실행하면 게임 배경색은 기본 검정색 외에 빨간색, 녹색, 파란색이 추가로 그려진다.