pygame image 삽입

# 다운받은 image 불러오기

# create start Img
start = pygame.image.load(
    "avoidvirus\\img sources\\start.png")
start = pygame.transform.scale(start, (400, 600))
recStart = start.get_rect()

# create background
background = pygame.image.load(
    "avoidvirus\\img sources\\background.jpg")
recBackground = background.get_rect()
background_size = background.get_rect().size
background_width = background_size[0]
background_height = background_size[1]

# create ending Img
ending = pygame.image.load(
    "avoidvirus\\img sources\\ending.jpg")
ending = pygame.transform.scale(ending, (400, 600))
recEnding = ending.get_rect()
# load한 image 화면에 띄우기

def startImg():
    SCREEN.blit(start, recStart)

def backgroundImg():
    SCREEN.blit(background, recBackground)


def endingImg():
    SCREEN.blit(ending, recEnding)

위 코드는 내가 만든 슈팅 게임의 코드 요약본이다.

  • pygame.image.load(“이미지 경로”)

    이미지 경로를 적어주면 이미지를 저장할 수 있다.

  • pygame.transform.scale(이미지를 저장한 변수, (너비, 높이))

    저장한 이미지를 설정한 튜플 형식의 해상도로 조정한다.

  • 이미지를 저장한 변수.get_rect()

    저장한 이미지를 사각형 객체로 만들어준다.

  • SCREEN.blit(이미지를 저장한 변수, 변수를 그려넣을 좌표)

    여기서 SCREEN은 앞서 선언한 SCREEN = pygame.display.set_mode((400, 600)) 변수, 즉 화면을 나타낸다. 내가 만든 코드에서 변수를 그려넣을 좌표는 모두 rec변수명 이런 식으로 지어주었기 때문에 SCREEN.blit(start, recStart) 는 start이미지를 recStart에 지정된 좌표에 그려주겠다는 의미이다.

  • background_size = background.get_rect().size

    background에 저장한 이미지의 사이즈를 가져온다.

  • background_width = background_size[0] background_height = background_size[1]

    background에 저장한 이미지에서 [0] : 가로 크기, [1] : 세로 크기를 각 변수에 지정해준다.

이미지를 화면에 띄워주는 blit() 메서드를 각각 함수로서 지정하여 마지막 game loop 반복문에서 불러와주었다.

pygame text 삽입

mFont = pygame.font.SysFont("arial", 20, True, False)
SCREEN.blit(mFont.render(
        f': player', True, "black"), (85, 150, 0, 0))
SCREEN.blit(mFont.render(
        f' : avoid this virus!', "test", "black"), (80, 210, 0, 0))

text를 삽입하는 큰 맥락은 SysFont()로 시스템의 폰트를 가져오고, 가져온 폰트를 담은 객체를 render() 메서드를 통해 텍스트를 Surface객체(이미지를 로드했을 때 썼던 방식)에 그려준 다음에 blit()함수를 통해 screen에 옮기게 되는 것이다.

  • SysFont(“fontname”, font-size, bold, italic)

    bold : 굵기(True / False)

    italic : 기울기(True / False)

import pygame
#font 종류 불러오기
for i in pygame.font.get_fonts():
    print(i)

굉장히 많은 폰트가 있는 것을 알 수 있다.

  • render(Text, antialias, color, background=None)

    Text : 글 입력

    antialias : true이면 글자가 부드러운 모서리로 표시

    background : 글자의 background로 설정