[pygame] 화면상에 글씨 보이게 하기

서희찬·2021년 4월 6일

pygame 에서 화면상의 글씨를 보이게할려면
일반적으로 pygame.draw.line()만 사용하면 엄청나게 호출해야해서 미친다..
(좌표를 일일이 계산해야하기때문..)

그래서 pygame은 유용한 함수를 제공한다
이를 통해 글씨를 보이게 할려면 다음 6단계를 따르면 된다.

  1. pygame.font.Font() 객체 생성
  2. Font 객체의 render() 메소드를 써서 텍스트를 그릴 Surface 생성
  3. Surface 객체의 get_rect() 메스드 써서 Rect 객체 생성
  4. 특성 값을 바꿔 Rect 객체의 위치 설정
  5. 텍스트가 있는 Surface 객체를 pygame.display.set_mode() 에서 반환한 Surface 객체상으로 보이게 한다.
  6. pygame.display.update() 호출해서 Surface 객체가 화면상에 보이도록 한다.
import pygame, sys
from pygame.locals import *

pygame.init() #pygame 초기화
DISPLAYSURF = pygame.display.set_mode((400,300))
pygame.display.set_caption("Chans World")

BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0)
GREEN = (0,255,0)

fontObj = pygame.font.Font("freesansbold.ttf",32)
textSurfaceObj = fontObj.render("Chans World!",True,GREEN,RED)
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (200,150)


while True: #main game Loop
    DISPLAYSURF.fill(WHITE)
    DISPLAYSURF.blit(textSurfaceObj,textRectObj)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        pygame.display.update()

profile
Carnegie Mellon University Robotics Institute | Research Associate | Developing For Our Lives, 세상에 기여하는 삶을 살고자 개발하고 있습니다

0개의 댓글