python으로 게임 만들기/pygame

[pygame] 9. 텍스트 글자 삽입

bay07 2024. 2. 24. 14:21

 

게임을 하다가 글자가 필요할 때가 있다. 여기에서도 "잡았다 피카츄 !"라는 말을 프로그램 실행창 뿐 아니라 게임 화면에도 나타내고 싶은데, 그럴 때는 어떻게 하면 좋을까? (나중에 게임오버 메세지를 출력하거나, 남은 시간, 점수를 표시할 때도 사용될 것이다)

 

먼저는 글자의 폰트를 정해주는 작업이 필요하다. pygame에서는 font 함수를 제공해주는데, 홈페이지에 찾아보면 다양한 폰트가 있다는 걸 알 수 있다. (그런데 예시 코드를 보면 대부분 그냥 None으로 쓰는듯? 기본 폰트가 괜찮은가보다.) 

# 폰트 정의
# 폰트 객체 생성 (폰트, 크기)
# 디폴트 폰트 사용할 예정이라 그냥 None으로 적었음
game_font = pygame.font.Font(None, 40)

https://www.pygame.org/docs/ref/font.html

 

pygame.font — pygame v2.6.0 documentation

This creates a new Surface with the specified text rendered on it. pygame.fontpygame module for loading and rendering fonts provides no way to directly draw text on an existing Surface: instead you must use Font.render() to create an image (Surface) of the

www.pygame.org


 

메세지를 가져올 때는 game_font.render( 출력할 메세지 str형태로 입력, True, 글자 색깔) 이렇게 적어주면 된다. get_font는 위에서 우리가 정해준 이름이다. 그리고 얘네를 화면에 출력하려면 screen.blit(message, 위치)를 해주면 된다. 화면 업데이트는 매번 해줘야함. 그래야 바뀐 값이 화면에 출력된다.

# 메세지 가져오기
message = game_font.render("I caught Pikachu", True, (255,255,255))

# 화면에 메세지 출력
screen.blit(message, (150,200))

# 화면 업데이트 작업
pygame.display.update()

 

 

▷ 시연영상

 

 


▷ 전체코드

더보기
#9. 텍스트 글자 삽입

import pygame
import time

pygame.init()
screen_width = 480
screen_height = 640
screen = pygame.display.set_mode((screen_width, screen_height))

clock = pygame.time.Clock()

pygame.display.set_caption("Let's make game")
background = pygame.image.load("C:/Users/Soyoung/Desktop/pygame/background.png")
character = pygame.image.load("C:/Users/Soyoung/Desktop/pygame/pika2.jpg")
character_size = character.get_rect().size
character_width = character_size[0]
character_height = character_size[1]
character_x_pos = (screen_width/2) - (character_width/2)
character_y_pos = screen_height - character_height

ball = pygame.image.load("C:/Users/Soyoung/Desktop/pygame/ball.jpg")
ball_size = ball.get_rect().size
ball_width = ball_size[0]
ball_height = ball_size[1]
ball_x_pos = (screen_width/2) - (ball_width/2)
ball_y_pos = (screen_height/2) - (ball_height/2)

to_x =0
to_y = 0 
character_speed = 0.5

# 폰트 정의
# 폰트 객체 생성 (폰트, 크기)
# 디폴트 폰트 사용할 예정이라 그냥 None으로 적었음
game_font = pygame.font.Font(None, 40)

running = True
while running:
    FPS = 60
    dt = clock.tick(FPS)
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             running = False
                
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                to_x -= character_speed
            elif event.key == pygame.K_RIGHT:
                to_x += character_speed
            elif event.key == pygame.K_UP:
                to_y -= character_speed
            elif event.key == pygame.K_DOWN:
                to_y += character_speed

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                to_x = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                to_y = 0

    character_x_pos += to_x * dt
    character_y_pos += to_y * dt

    if character_x_pos < 0:
        character_x_pos = 0
    elif character_x_pos > screen_width - character_width:
        character_x_pos = screen_width - character_width
    if character_y_pos < 0:
        character_y_pos = 0    
    elif character_y_pos > screen_height - character_height:
        character_y_pos = screen_height - character_height       
    
    character_rect = character.get_rect()
    character_rect.left = character_x_pos
    character_rect.top = character_y_pos
    
    ball_rect = ball.get_rect()
    ball_rect.left = ball_x_pos
    ball_rect.top = ball_y_pos      
    
    if character_rect.colliderect(ball_rect):
        # 출력할 글자, 위치
        ball_message = game_font.render("I caught Pikachu", True, (255,255,255))
        screen.blit(ball_message, (150,200))
        pygame.display.update()
        time.sleep(5)
        running = False
    
    screen.blit(background, (0,0))
    screen.blit(character,(character_x_pos, character_y_pos))
    screen.blit(ball,(ball_x_pos, ball_y_pos))
    pygame.display.update()
    
    # 게임화면 업데이트 하기
    pygame.display.update()
    
screen.blit(background, (0,0))
pygame.display.update()
end_message = game_font.render("Game Finished !", True, (102,0,153))
screen.blit(end_message, (130,200))
pygame.display.update()
# 게임이 꺼지기 전에 3초정도 대기하기
pygame.time.delay(3000)

pygame.quit()

 


 

▷ 참고자료 

pygame : https://www.pygame.org/docs/ref/rect.html

나도 코딩 : https://www.youtube.com/watch?v=Dkx8Pl6QKW0

크리스마스 : https://www.youtube.com/watch?v=OblIxaCJNc8