Stone's LIFE
혼자 게임 만들기
그라운드스톤
2023. 10. 29. 21:54
728x90
c언어가 우선이지만...
우연히 유튜브에서 파이썬으로 게임 만드는 영상을 봤다. 파이게임이라는 일종의 모듈을 활용하는 것 같은데 나는 아진 코딩초보인지라 뭐가 뭔 말인지는 잘 모르겠다. 영상을 보며 무작정 따라 했다.
필요하면 함수를 정의하고 사용하면서 하나하나 만들어나가는 과정이 새삼 흥미롭다.
언어가 조금 익숙해지기 시작했다면 무작정 게임 만들기를 따라 하는 게 좋은 것 같다. 지금껏 배운 여러 연산자와 문법을 실제로 활용하는 경험을 할 수 있다.
import pygame
from random import *
# 레벨 설정
def setup(level):
global display_time
display_time = 5 - (level // 3)
display_time = max(display_time, 1)
num_count = (level // 3) + 5
num_count = min(num_count, 20)
shuffle_grid(num_count)
def shuffle_grid(num_count):
rows = 5
columns = 9
grid = [[0 for col in range(columns)] for row in range(rows)]
cellsize = 130
buttonsize = 110
screen_left_mar = 55
screen_top_mar = 20
number = 1
while number <= num_count:
row_idx = randrange(0, rows)
col_idx = randrange(0, columns)
if grid[row_idx][col_idx] == 0:
grid[row_idx][col_idx] = number
number += 1
center_x = screen_left_mar + (col_idx * cellsize) + (cellsize / 2)
center_y = screen_top_mar + (row_idx * cellsize) + (cellsize / 2)
button = pygame.Rect(0, 0, buttonsize, buttonsize)
button.center = (center_x, center_y)
number_buttons.append(button)
print(grid)
# 시작화면
def display_start_screen():
pygame.draw.circle(screen, WHITE, start_button.center, 60, 5)
msg = gamefont.render(f"{curr_level}", True, WHITE)
msg_rect = msg.get_rect(center= start_button.center)
screen.blit(msg, msg_rect)
def check_buttons(pos):
global start, start_tick
if start:
check_num_but(pos)
elif start_button.collidepoint(pos):
start = True
start_tick = pygame.time.get_ticks()
def check_num_but(pos):
global hidden, start, curr_level
for button in number_buttons:
if button.collidepoint(pos):
if button == number_buttons[0]:
print("correct")
del number_buttons[0]
if not hidden:
hidden = True
else:
game_over()
break
if len(number_buttons) == 0:
start = False
hidden = False
curr_level += 1
setup(curr_level)
def game_over():
global running
running = False
msg = gamefont.render(f"Your Level is {curr_level} .", True, WHITE)
msg_rect = msg.get_rect(center=(screen_width / 2, screen_height / 2))
screen.fill(BLACK)
screen.blit(msg, msg_rect)
def display_game_screen():
global hidden
if not hidden:
elapsed_time = (pygame.time.get_ticks() - start_tick) / 1000
if elapsed_time > display_time:
hidden = True
for idx, rect in enumerate(number_buttons, start=1):
if hidden:
pygame.draw.rect(screen, GRAY, rect)
else:
celltxt = gamefont.render(str(idx), True, WHITE)
txt_rect = celltxt.get_rect(center=rect.center)
screen.blit(celltxt, txt_rect)
# 반지름은 60, 선두꼐는 5
# 게임 초기화
pygame.init()
screen_width = 1280
screen_height = 720
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Memory Game")
gamefont = pygame.font.Font(None, 120)
# 시작버튼
start_button = pygame.Rect(0, 0, 120, 120)
start_button.center = (120, screen_height - 120)
# 색
BLACK = (0, 0, 0) # rgb
WHITE = (255, 255, 255)
GRAY = (50, 50, 50)
number_buttons = []
curr_level = 1
display_time = None
start_tick = None
# 게임시작 여부
start = False
hidden = False
setup(curr_level)
# 게임 루프
running = True
while running:
click_pos = None
# 이벤트루프
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONUP:
click_pos = pygame.mouse.get_pos()
print(click_pos)
screen.fill(BLACK)
if start:
display_game_screen()
else:
display_start_screen()
# 사용자 클릭 값
if click_pos:
check_buttons(click_pos)
# 시작화면
display_start_screen()
# 화면 업데이트
pygame.display.update()
pygame.time.delay(8000)
# 게임 종료
pygame.quit()
약간 HTML 보는 것도 같다.
일단 내가 따라 하면서도 일부 조정해 봤다.
색이나 사이즈 같은 것은 굳이 똑같이 카피할 필요 없으니까
나중에 내가 조금 더 전문가가 된다면 하나하나 더 조정해 볼 생각이다.
하나하나 뜯어보면서 배워나가면 개념을 조금 더 익히기 쉽지 않을까?
카피지만 이렇게 뭔가를 만들어보니 컴퓨터언어에 더 관심이 생긴다.
백준에 올라와있는 문제를 풀면서도 성취감을 느꼈지만 뭔가를 창조한다는 건 차원이 다르다.
42 경산 라 피신 기간에는 더 많은 걸 물어보고 더 많은 걸 얻을 수 있겠지라는 기대감도 생긴다.
이왕 이렇게 된 거 끝까지 한 번 가보자
728x90