# 간단 예제
import pygame
import sys
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
def main():
pygame.init() # pygame 모듈 초기화
pygame.display.set_caption('First') # 윈도우에 표시할 타이틀 지정
screen = pygame.display.set_mode((800, 600)) # 스크린 초기화
clock = pygame.time.Clock() # clock 오브젝트 초기화
font = pygame.font.Font(None, 80) # font 오브젝트 초기화
tmr = 0
while True:
tmr += 1
for event in pygame.event.get(): # pygame 이벤트 반복 처리
if event.type == pygame.QUIT: # 윈도우의 'X' 버튼을 누른 경우
pygame.quit()
sys.exit()
txt = font.render(str(tmr), True, WHITE) # Surface에 문자열 표시
screen.fill(BLACK) # 지정한 색으로 스크린 전체 채움
screen.blit(txt, [300, 200]) # 문자열 표시한 Surface를 스크린으로 전송
pygame.display.update() # 화면 업데이트
clock.tick(10) # Framerate 지정
if __name__ == '__main__':
main()
첫 번째 예제로 단순하게 검은 화면에 시간에 따라 증가하는 숫자를 표기한다.
render 명령으로 문자열과 색을 지정하고 문자열을 그릴 Surface를 만든다. 두번째 인수를 True로 지정하면 문자 테두리가 부드러워 진다.
# 이미지 표현
import pygame
import sys
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
def main():
pygame.init()
pygame.display.set_caption('Image')
screen = pygame.display.set_mode((640, 360))
clock = pygame.time.Clock()
img_bg = pygame.image.load('Python_workspace\mini_game\image_dir\pg_bg.png') # 배경 이미지 로딩
img_chara = [
pygame.image.load('Python_workspace\mini_game\image_dir\pg_chara0.png'), #캐릭터 이미지 로딩
pygame.image.load('Python_workspace\mini_game\image_dir\pg_chara1.png')
]
tmr = 0
while True:
tmr += 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN: # 키를 누르는 이벤트 발생 처리
if event.key == pygame.K_F1: # F1일 때
screen = pygame.display.set_mode((640, 360), pygame.FULLSCREEN) # 전체 화면으로 전환
if event.key == pygame.K_F2 or event.key == pygame.K_ESCAPE: # F2나 ESC일 때
screen = pygame.display.set_mode((640, 360)) # 일반 스크린 모드로 전환
x = tmr % 160
for i in range(5):
screen.blit(img_bg, [i * 160 - x, 0]) # 배경이미지 표시
screen.blit(img_chara[tmr % 2], [224, 160]) # 캐릭터를 애니메이션해서 표시, blit(이미지를 로딩할 변수, [x좌표, y좌표])
pygame.display.update()
clock.tick(5)
if __name__ == '__main__':
main()
이미지를 표시하는 프로그램인데 두 이미지를 번갈아가면서 표시해서 걸어가는 것 처럼 보이게 한다.
여기서는 사용하지 않았지만 이미지 확대, 축소 및 회전도 가능하다.
이미지 동작 | 코드 |
---|---|
확대/축소 | img_s = pygame.transform.scale(img, [폭, 높이]) |
회전 | img_r = pygame.transform.rotate(img, 회전각) |
회전 + 확대/축소 | img_rz = pygame.transform.rotozoom(img, 회전각, 확대 비율) |
# 도형 표시
import pygame
import sys
import math
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
GOLD = (255, 216, 0)
SILVER = (192, 192, 192)
COPPER = (192, 112, 48)
def main():
pygame.init()
pygame.display.set_caption('Shape')
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
tmr = 0
while True:
tmr += 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(BLACK)
pygame.draw.line(screen, RED, [0, 0], [100, 200], 10) # 선 표시
pygame.draw.lines(screen, BLUE, False, [[50, 300], [150, 400], [50, 500]]) # 선 표시
pygame.draw.rect(screen, RED, [2000, 50, 120, 80]) # 사각형 표시
pygame.draw.rect(screen, GREEN, [200, 200, 60, 180], 5) # 사각형 표시
pygame.draw.polygon(screen, BLUE, [[250, 400], [200, 500], [300, 500]], 10) # 다각형 표시
pygame.draw.circle(screen, GOLD, [400, 100], 60) # 원 표시
pygame.draw.ellipse(screen, SILVER, [400 - 80, 300 - 40, 160, 80]) # 타원 표시
pygame.draw.ellipse(screen, COPPER, [400 - 40, 500 - 80, 80, 160], 20) # 타원 표시
ang = math.pi * tmr / 36 # 원호 각도 계산
pygame.draw.arc(screen, BLUE, [600 - 100, 300 - 200, 200, 400], 0, math.pi * 2) # 원호 표시
pygame.draw.arc(screen, WHITE, [600 - 100, 300 - 200, 200, 400], ang, ang + math.pi / 2, 8) # 원호 표시
pygame.display.update()
clock.tick(10)
if __name__ == '__main__':
main()
도형들을 화면에 표시하는 코드다.
도형 | 코드 |
---|---|
선 | pygame.draw.line(Surface, color, start_pos, end_pos, widht=1) |
선(좌표 연속 지정) | pygame.draw.lines(Surface, color, closed, pointlist, width=1) |
사각형 | pygame.draw.rect(Surface, color, Rect, width=0) |
다각형 | pygame.draw.polygon(Surface, color, pointlist, width=0) |
원 | pygame.draw.circle(Surface, color, pos, radius, width=0) |
타원 | pygame.draw.ellipse(Surface, color, Rect, width=0) |
원호 | pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle, width=1) |
- Surface : 도형을 표시할 화면
- color : 10진수 RGB 값
- Rect : [x, y, 폭, 높이]
- pointlist [[x0, y0], [x1, y1], [x2, y2], ...] 여러 좌표 지정
- width : 선의 굵기, 아무것도 지정하지 않으면 도형 내부를 칠함
- start_angle, stop_angle : 시작 각과 종료 각은 라디안으로 지정
- lines : 시작점과 완료점을 연결하려면 closed를 True로 지정
# 키 입력
import pygame
import sys
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
def main():
pygame.init()
pygame.display.set_caption('Key Event')
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 60)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
key = pygame.key.get_pressed() # 리스트 key에 모든 키 상태 입력
txt1 = font.render('UP' + str(key[pygame.K_UP]) + ' DOWN' + str(key[pygame.K_DOWN]), True, WHITE, GREEN) # 방향키 상/하 리스트 값을 표시할 Surface
txt2 = font.render('LEFT' + str(key[pygame.K_LEFT]) + ' RIGHT' + str(key[pygame.K_RIGHT]), True, WHITE, BLUE) # 방향키 좌/우 리스트 값을 표시할 Surface
txt3 = font.render('SPACE' + str(key[pygame.K_SPACE]) + ' ENTER' + str(key[pygame.K_RETURN]), True, WHITE, RED) # 스페이스/엔터 리스트 값을 표시할 Surface
screen.fill(BLACK)
screen.blit(txt1, [100, 100]) # 문자열을 표시한 Surface를 스크린에 전송
screen.blit(txt2, [100, 200])
screen.blit(txt3, [100, 300])
pygame.display.update()
clock.tick(10)
if __name__ == '__main__':
main()
키 입력 이벤트를 처리한 것이다.
# 마우스 입력
import pygame
import sys
BLACK = (0, 0, 0)
LBLUE = (0, 192, 255)
PINK = (255, 0, 224)
def main():
pygame.init()
pygame.display.set_caption('Mouse Event')
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 60)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
mouseX, mouseY = pygame.mouse.get_pos() # 변수에 마우스 포인터 좌표 대입
txt1 = font.render('{}, {}'.format(mouseX, mouseY), True, LBLUE) # 좌표 값을 표시할 Surface
mBtn1, mBtn2, mBtn3 = pygame.mouse.get_pressed() # 변수에 마우스 버튼 상태 대입
txt2 = font.render('{}:{}:{}'.format(mBtn1, mBtn2, mBtn3), True, PINK) # 마우스 버튼 상태를 표시할 Surface
screen.fill(BLACK)
screen.blit(txt1, [100, 100])
screen.blit(txt2, [100, 200])
pygame.display.update()
clock.tick(10)
if __name__ == '__main__':
main()
마우스 이벤트를 받는다.