escortKim의 블로그
[pygame]똥피하기 게임 만들기 본문
이 글에서는 pygame에 관한 내용을 담고 있습니다.
오늘 만들 것은 python에서 pygame을 이용해 똥피하기 게임을 만들기 위한
기본 틀을 알아 볼 것입니다.
import pygame
pygame.init() # pygame 초기화
파이게임 모듈을 import하고, pygame을 초기화합니다.
#화면 크기 설정
screen_width = 480 #가로크기
screen_height = 640 #세로크기
screen = pygame.display.set_mode((screen_width, screen_height))
화면 가로, 세로 길이를 설정합니다.
#게임 타이틀
pygame.display.set_caption("game title")
게임창에 뜰 이름을 설정합니다.
#FPS(frame per second)
clock = pygame.time.Clock()
프레임 수치를 설정해줍니다.
#배경이미지
background = pygame.image.load("background.png")
배경 이미지를 설정합니다. 따옴표 안에들어가는 주소는 사진이 저장된 주소를 넣으면 됩니다.
#캐릭터 생성
character = pygame.image.load("character.png")
character_size = character.get_rect().size # 이미지 크기를 구해옴.
character_width = character_size[0] # 캐릭터 가로 크기
character_height = character_size[1] # 캐리턱 세로 크기
character_xpos = (screen_width / 2) - (character_width / 2)
character_ypos = screen_height - character_height
캐릭터를 생성하고, 캐릭터 기본 위치를 설정합니다.
#이동할 좌표
to_x = 0
to_y = 0
나중에 키보드로 캐릭터를 움직일 때 필요한 변수입니다.
#이동 속도
character_speed = 0.5
기본 이동 속도를 설정하는 변수입니다.
#적 생성
enemy = pygame.image.load("enemy.png")
enemy_size = enemy.get_rect().size
enemy_width = enemy_size[0]
enemy_height = enemy_size[1]
enemy_xpos = (screen_width / 2) - (enemy_width / 2)
enemy_ypos = (screen_height / 2) - (enemy_height / 2)
적을 생성하고, 기본 위치를 설정합니다.
total_time = 10 #게임 플레이 총 시간
start_ticks = pygame.time.get_ticks()
게임플레이 총 시간을 설정합니다.
#이벤트
running = True
while running:
dt=clock.tick(30)
이벤트를 True로 설정하여 while문이 실행되도록 합니다.
그리고 FPS값을 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 = to_x - character_speed
if event.key == pygame.K_RIGHT: #오른쪽 방향키 입력
to_x = to_x + character_speed
if event.key == pygame.K_UP: #위쪽 방향키 입력
to_y -= character_speed # to_y = to_y - 5
if 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
어떤 이벤트가 발생하였는지 판단하는 for문을 넣어주고,
만약 창닫기 이벤트가 발생하였다면 while문을 False로 바꿔주어 창을 닫게 합니다.
그리고 이벤트가 key가 눌린 것이라면 또 어떤 키가 눌린 것인지 확인하고,
그 방향으로 움직이도록 합니다.
만약 key가 눌렸다 올라와서 key를 누르지 않는 상태가 되면,
더 이상 움직이지 않게 to_x와 to_y를 0으로 설정합니다.
# 캐릭터 이동
character_xpos += to_x * dt
character_ypos += to_y * dt
캐릭터가 이동하도록 좌표를 바꿔줍니다.
# 경계값 설정
if character_xpos < 0: #가로 경계
character_xpos = 0
elif character_xpos > screen_width - character_width:
character_xpos = screen_width - character_width
if character_ypos < 0: #세로 경계
character_ypos = 0
elif character_ypos > screen_height - character_height:
character_ypos = screen_height - character_height
캐릭터가 화면 밖으로 나가면 안되기 때문에 경계값을 설정하여
캐릭터가 화면 밖으로 나가지 않게 설정합니다.
#충돌
character_rect = character.get_rect()
character_rect.left = character_xpos
character_rect.top = character_ypos
enemy_rect = enemy.get_rect()
enemy_rect.left = enemy_xpos
enemy_rect.top = enemy_ypos
if character_rect.colliderect(enemy_rect):
print("충돌!!")
running = False
적과 충돌했을시 게임을 중단하기 위해 충돌 이벤트를 추가합니다.
# 타이머
elapsed_time = (pygame.time.get_ticks() - start_ticks) / 1000
# 경과시간 ms 이므로 100으로 나누어 초단위로 표시
timer = game_font.render(str(int(total_time - elapsed_time)), True, (255, 255, 255))
# 출력할 글자, , 색상
타이머를 넣어 전체 게임시간이 얼마 남았는지 보여줍니다.
screen.blit(background, (0,0))
screen.blit(character, (character_xpos,character_ypos))
screen.blit(enemy, (enemy_xpos,enemy_ypos))
screen.blit(timer, (10,10))
화면에 배경화면, 캐릭터, 적, 타이머를 나오게 합니다.
#화면 새로고침
pygame.display.update()
화면을 새로고침해 지금까지 한것들을 보이게 합니다.
#pygame 종료
pygame.quit()
다른 것들이 다 실행되면 종료합니다.
'컴퓨터' 카테고리의 다른 글
[기초]자료구조와 프로그래밍 (4)(함수) (1) | 2020.05.17 |
---|---|
[기초]자료구조와 프로그래밍 (3)(if문, for문, while문) (0) | 2020.05.17 |
[기초]자료구조와 프로그래밍 (2)(python, 변수, 자료형, print, 연산자) (1) | 2020.05.16 |
[기초]자료구조와 프로그래밍 (1)(자료구조) (1) | 2020.05.16 |