Python Game
5. Frame per second
_션샤인
2024. 7. 8. 17:06
pygame 불러오기 및 초기화
import pygame
pygame.init() # 초기화 (반드시 필요, 만들기 전에 반드시 init 호출해서 초기화)
화면 크기 및 타이틀 설정
screen_width = 480 # 가로 크기
screen_height = 640 # 세로 크기
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Sieon Game") # 게임 이름
- display.set_mode : 게임창의 크기와 특성을 튜플 형태로 정의, 주로 (width, height)
- display.set_caption : 게임창의 제목 설정
1. FPS 설정
clock = pygame.time.Clock()
배경 불러오기
background = pygame.image.load("C:/Users/my/PythonWorkSpace/pygame_basic/background.png")
background (배경 지정) 할 건데,
pygame.image.load 메서드로 소괄호 안에 주소 넣기
캐릭터 불러오기
character = pygame.image.load("C:/Users/my/PythonWorkSpace/pygame_basic/character.png")
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 # 화면 세로 크기 가장 아래에 해당하는 곳에 위치
- character.get_rect() : 이미지의 바운딩 박스를 가져오는 메서드로 위치, 크기 정의
- .size : 바운딩 박스의 크기를 튜플 형태로 반환함 (width, height)
이동할 좌표 설정
to_x = 0
to_y = 0
2. 이동 속도 설정
character_speed = 0.6
이벤트 루프
- 프로그램이 종료되지 않도록 대기하는 것
- 중간에 사용자가 키보드/마우스로 뭔가 입력하는지 체크
- 입력이 된다면 키보드에 맞는 이미지를 움직이는 등 동작 실행
running = True # 게임이 진행중인가?
while running :
3. 게임화면에서의 FPS 설정
dt = clock.tick(30) #게임 화면의 초당 프레임 수를 설정
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 -= 5 # to_x = to_x - 5
elif event.key == pygame.K_RIGHT: # 캐릭터를 오른쪽으로
to_x += 5 # to_x = to_x + 5
elif event.key == pygame.K_UP:
to_y -= 5 # to_y = to_x - y
elif event.key == pygame.K_DOWN:
to_y += 5 # to_y = to_y + 5
키보드를 누르지 않았을 때 멈추도록 설정
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
character_y_pos += to_y
가로 경계값 처리
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
배경, 캐릭터 그리기
screen.blit(background, (0, 0)) # 배경 그리기
screen.blit(character, (character_x_pos, character_y_pos)) # 캐릭터 그리기
pygame.display.update() # 게임화면을 다시 그리기, 반드시 매 번 호출이 되어야함
- blit : 이미지를 화면에 그리는 것
게임 종료
pygame.quit()