이 글에서는 Python으로 간단한 게임을 만드는 방법을 소개합니다. Python 3.9 환경에서 테스트된 8가지 게임 예제를 포함하며, 각 게임의 구현 코드와 함께 설명합니다.
1. 테트리스
Python의 Tkinter 라이브러리를 사용하여 구현된 테트리스 게임입니다.
from tkinter import *
import random
import time
import tkinter.messagebox
# 게임 보드 크기 정의
BOARD_HEIGHT = 20
BOARD_WIDTH = 10
ACTIVE = 1
PASSIVE = 0
TRUE = 1
FALSE = 0
# 블록 모양 정의 (회전 상태 포함)
# J, T, L, Z, S, O, I 순서
block_styles = [
[[(0,0),(0,1),(1,1),(2,1)],[(1,0),(1,1),(1,2),(0,2)],[(0,1),(1,1),(2,1),(2,2)],[(1,0),(2,0),(1,1),(1,2)]], # J
[[(1,0),(1,1),(1,2),(2,1)],[(1,0),(0,1),(1,1),(2,1)],[(1,0),(1,1),(1,2),(0,1)],[(0,1),(1,1),(2,1),(1,2)]], # T
[[(0,1),(1,1),(2,1),(2,0)],[(0,0),(1,0),(1,1),(1,2)],[(0,1),(1,1),(2,1),(0,2)],[(1,0),(1,1),(1,2),(2,2)]], # L (reversed)
[[(0,0),(0,1),(1,1),(1,2)],[(2,1),(1,1),(1,2),(0,2)],[(0,0),(0,1),(1,1),(1,2)],[(2,1),(1,1),(1,2),(0,2)]], # Z (reversed)
[[(1,0),(1,1),(0,1),(0,2)],[(0,1),(1,1),(1,2),(2,2)],[(1,0),(1,1),(0,1),(0,2)],[(0,1),(1,1),(1,2),(2,2)]], # S (reversed)
[[(0,0),(0,1),(1,1),(1,0)],[(0,0),(0,1),(1,1),(1,0)],[(0,0),(0,1),(1,1),(1,0)],[(0,0),(0,1),(1,1),(1,0)]], # O
[[(1,0),(1,1),(1,2),(1,3)],[(0,1),(1,1),(2,1),(3,1)],[(1,0),(1,1),(1,2),(1,3)],[(0,1),(1,1),(2,1),(3,1)]] # I
]
root = Tk()
root.title('Tetris')
class TetrisGame(Frame):
def __init__(self, master):
Frame.__init__(self)
# 키 입력 바인딩
master.bind('<Up>', self.rotate_block)
master.bind('<Left>', self.move_left)
master.bind('<Right>', self.move_right)
master.bind('<Down>', self.move_down)
master.bind('<space>', self.drop_block)
master.bind('', self.show_author_info)
master.bind('', self.toggle_pause)
master.bind('', self.start_game_with_s)
# 색상 정의
self.background_color = "#%02x%02x%02x" % (120, 150, 30) # 메인 배경색
self.next_block_color = "#%02x%02x%02x" % (40, 120, 150) # 다음 블록 창 배경색
self.sub_background_color = "#%02x%02x%02x" % (150, 100, 100) # 다음 블록 창 보조 배경색
self.flash_color = "#%02x%02x%02x" % (210, 130, 100) # 줄 삭제 시 깜빡임 색상
# 게임 정보 표시 레이블
self.lines_label_display = Label(master, text='Lines: ', bg='black', fg='red')
self.lines_label = Label(master, text='0', bg='black', fg='red')
self.score_label_display = Label(master, text='Score: ', bg='black', fg='red')
self.score_label = Label(master, text='0', bg='black', fg='red')
self.time_label_display = Label(master, text='Time: ', bg='black', fg='red')
self.time_label = Label(master, text='0.0', bg='black', fg='red')
self.lines_label_display.grid(row=BOARD_HEIGHT - 2, column=BOARD_WIDTH, columnspan=2)
self.lines_label.grid(row=BOARD_HEIGHT - 2, column=BOARD_WIDTH + 2, columnspan=3)
self.score_label_display.grid(row=BOARD_HEIGHT - 1, column=BOARD_WIDTH, columnspan=2)
self.score_label.grid(row=BOARD_HEIGHT - 1, column=BOARD_WIDTH + 2, columnspan=3)
self.time_label_display.grid(row=BOARD_HEIGHT - 4, column=BOARD_WIDTH, columnspan=2)
self.time_label.grid(row=BOARD_HEIGHT - 4, column=BOARD_WIDTH + 2, columnspan=3)
self.total_time = 0.0
self.total_lines = 0
self.total_score = 0
self.is_game_over = FALSE
self.is_paused = FALSE
self.is_started = FALSE
self.next_block_preview_list = []
self.next_block_row_list = []
self.current_block_row = 0
self.current_block_col = 0 # 현재 블록의 기준점 좌표
# 다음 블록 미리보기 창 렌더링
r, c = 0, 0
for k in range(4 * 4):
lbl = Label(master, text=' ', bg=str(self.sub_background_color), fg='white', relief=FLAT, bd=3)
lbl.grid(row=r, column=BOARD_WIDTH + c, sticky=N+E+S+W)
self.next_block_row_list.append(lbl)
c += 1
if c >= 4:
r += 1
c = 0
self.next_block_preview_list.append(self.next_block_row_list)
self.next_block_row_list = []
# 게임 보드 렌더링
self.block_state_list = [] # 보드 상태 (0: 빈칸, 1: 채워짐)
self.label_widget_list = [] # 각 셀의 Label 위젯
self.block_row_state_list = []
self.label_row_widget_list = []
row, col = 0, 0
for i in range(BOARD_HEIGHT * BOARD_WIDTH):
lbl = Label(master, text=' ', bg=str(self.background_color), fg='white', relief=FLAT, bd=4)
lbl.grid(row=row, column=col, sticky=N+E+S+W)
lbl.row_idx = row # Label 위젯에 행 인덱스 저장
lbl.col_idx = col # Label 위젯에 열 인덱스 저장
lbl.is_active = PASSIVE # 블록이 활성화 상태인지 여부
self.block_row_state_list.append(0) # 보드 셀 초기화
self.label_row_widget_list.append(lbl)
col += 1
if col >= BOARD_WIDTH:
row += 1
col = 0
self.block_state_list.append(self.block_row_state_list)
self.label_widget_list.append(self.label_row_widget_list)
self.block_row_state_list = []
self.label_row_widget_list = []
# 게임 기록 파일 처리
try:
with open('tetris_scores.txt', 'a') as f:
pass # 파일 존재 여부 확인 및 필요시 생성
has_header = FALSE
with open('tetris_scores.txt', 'r') as f:
if f.read(5) == 'score':
has_header = TRUE
self.score_file = open('tetris_scores.txt', 'a')
if not has_header:
self.score_file.write('Score Lines Time ScorePerTime LinesPerTime ScorePerLine Date\n')
self.score_file.flush()
except IOError:
print("Error: Could not open score file.")
self.score_file = None
self.fall_speed_ms = 1000 # 블록 낙하 속도 (밀리초)
self.on_timer_update()
def __del__(self):
if self.score_file:
self.score_file.close()
def toggle_pause(self, event):
self.is_paused = not self.is_paused
if self.is_paused:
print("Game Paused")
else:
print("Game Resumed")
def rotate_block(self, event):
if not self.is_started or self.is_paused:
return
current_style = block_styles[self.current_block_type][self.current_block_rotation]
next_rotation = (self.current_block_rotation + 1) % 4
next_style = block_styles[self.current_block_type][next_rotation]
self.current_block_rotation = next_rotation # UP 키 반응 시 업데이트 중요
# print(f"Current Style: {current_style} =====>> Next Style: {next_style}")
source_coords = []
dest_coords = []
# 현재 블록 위치 계산
for i in range(4):
source_coords.append([current_style[i][0] + self.current_block_row, current_style[i][1] + self.current_block_col])
# 회전 후 예상 위치 계산
can_rotate = TRUE
for i in range(4):
new_row = next_style[i][0] + self.current_block_row
new_col = next_style[i][1] + self.current_block_col
# 경계 및 충돌 검사
if new_row < 0 or new_row >= BOARD_HEIGHT or new_col < 0 or new_col >= BOARD_WIDTH or \
(self.block_state_list[new_row][new_col] == 1 and self.label_widget_list[new_row][new_col].is_active == PASSIVE):
can_rotate = FALSE
break
dest_coords.append([new_row, new_col])
if can_rotate:
# 현재 블록 지우기
for r, c in source_coords:
self.clear_cell(r, c)
# 새 위치에 블록 그리기
for r, c in dest_coords:
self.fill_cell(r, c)
def move_left(self, event):
if not self.is_started or self.is_paused:
return
can_move = TRUE
for r in range(BOARD_HEIGHT):
for c in range(BOARD_WIDTH):
if self.label_widget_list[r][c].is_active == ACTIVE:
if c - 1 < 0: # 왼쪽 경계 검사
can_move = FALSE
break
# 충돌 검사: 왼쪽 셀이 채워져 있고 비활성 상태인지 확인
if self.block_state_list[r][c - 1] == 1 and self.label_widget_list[r][c - 1].is_active == PASSIVE:
can_move = FALSE
break
if not can_move:
break
if can_move:
self.current_block_col -= 1
for r in range(BOARD_HEIGHT):
for c in range(BOARD_WIDTH):
if self.label_widget_list[r][c].is_active == ACTIVE and c - 1 >= 0 and self.block_state_list[r][c - 1] == 0:
self.fill_cell(r, c - 1)
self.clear_cell(r, c)
def move_right(self, event):
if not self.is_started or self.is_paused:
return
can_move = TRUE
for r in range(BOARD_HEIGHT):
for c in range(BOARD_WIDTH):
if self.label_widget_list[r][c].is_active == ACTIVE:
if c + 1 >= BOARD_WIDTH: # 오른쪽 경계 검사
can_move = FALSE
break
# 충돌 검사: 오른쪽 셀이 채워져 있고 비활성 상태인지 확인
if self.block_state_list[r][c + 1] == 1 and self.label_widget_list[r][c + 1].is_active == PASSIVE:
can_move = FALSE
break
if not can_move:
break
if can_move:
self.current_block_col += 1
for r in range(BOARD_HEIGHT - 1, -1, -1):
for c in range(BOARD_WIDTH - 1, -1, -1):
if self.label_widget_list[r][c].is_active == ACTIVE and c + 1 < BOARD_WIDTH and self.block_state_list[r][c + 1] == 0:
self.fill_cell(r, c + 1)
self.clear_cell(r, c)
def move_down(self, event):
if not self.is_started or self.is_paused:
return
can_move = TRUE
for r in range(BOARD_HEIGHT):
for c in range(BOARD_WIDTH):
if self.label_widget_list[r][c].is_active == ACTIVE:
if r + 1 >= BOARD_HEIGHT: # 아래쪽 경계 검사
can_move = FALSE
break
# 충돌 검사: 아래 셀이 채워져 있고 비활성 상태인지 확인
if self.block_state_list[r + 1][c] == 1 and self.label_widget_list[r + 1][c].is_active == PASSIVE:
can_move = FALSE
break
if not can_move:
break
if can_move:
self.current_block_row += 1
for r in range(BOARD_HEIGHT - 1, -1, -1):
for c in range(BOARD_WIDTH - 1, -1, -1):
if self.label_widget_list[r][c].is_active == ACTIVE and r + 1 < BOARD_HEIGHT and self.block_state_list[r + 1][c] == 0:
self.fill_cell(r + 1, c)
self.clear_cell(r, c)
else:
# 블록이 더 이상 내려갈 수 없으면 고정
for r in range(BOARD_HEIGHT):
for c in range(BOARD_WIDTH):
if self.label_widget_list[r][c].is_active == ACTIVE:
self.label_widget_list[r][c].is_active = PASSIVE
self.check_full_lines()
if self.is_game_over:
messagebox.showinfo('Game Over', 'Game Over!')
self.reset_game()
return FALSE
self.spawn_new_block()
self.clear_next_block_preview()
self.place_next_block_preview()
return can_move
def drop_block(self, event):
if not self.is_started or self.is_paused:
return
while self.move_down(None): # move_down 함수에 None을 전달하여 event 객체가 없어도 동작하도록 함
pass
def on_timer_update(self):
if self.is_started and not self.is_paused:
self.total_time += float(self.fall_speed_ms) / 1000
self.time_label.config(text=str(round(self.total_time, 1)))
# 블록 낙하 속도 조절 (점수 기반)
if self.total_score >= 1000: self.fall_speed_ms = 900
if self.total_score >= 2000: self.fall_speed_ms = 750
if self.total_score >= 3000: self.fall_speed_ms = 600
if self.total_score >= 4000: self.fall_speed_ms = 400
self.move_down(None) # 자동으로 블록 내리기
self.after(self.fall_speed_ms, self.on_timer_update)
def check_full_lines(self):
lines_cleared = 0
lines_to_remove = []
full_line_pattern = [1] * BOARD_WIDTH
# 완성된 줄 찾기
for r in range(BOARD_HEIGHT):
if self.block_state_list[r] == full_line_pattern:
lines_to_remove.append(r)
lines_cleared += 1
# 완성된 줄 깜빡임 효과
for c in range(BOARD_WIDTH):
self.label_widget_list[r][c].config(bg=str(self.flash_color))
self.label_widget_list[r][c].update()
if lines_cleared > 0:
self.after(100) # 깜빡임 효과를 위해 잠시 대기
# 완성된 줄 삭제 및 위쪽 줄 내리기
for row_to_remove in sorted(lines_to_remove, reverse=True):
for r in range(row_to_remove, 0, -1):
self.block_state_list[r] = self.block_state_list[r-1][:]
for c in range(BOARD_WIDTH):
self.label_widget_list[r][c]['relief'] = self.label_widget_list[r-1][c].cget('relief')
self.label_widget_list[r][c]['bg'] = self.label_widget_list[r-1][c].cget('bg')
self.label_widget_list[r][c].is_active = self.label_widget_list[r-1][c].is_active
# 맨 윗줄 초기화
self.block_state_list[0] = [0] * BOARD_WIDTH
for c in range(BOARD_WIDTH):
self.label_widget_list[0][c].config(relief=FLAT, bg=str(self.background_color))
self.label_widget_list[0][c].is_active = PASSIVE
# 점수 및 줄 수 업데이트
self.total_lines += lines_cleared
score_multiplier = {1: 1, 2: 3, 3: 6, 4: 10}
self.total_score += score_multiplier.get(lines_cleared, 0) * BOARD_WIDTH
self.lines_label.config(text=str(self.total_lines))
self.score_label.config(text=str(self.total_score))
def fill_cell(self, r, c):
# 블록이 놓일 때 게임 오버 검사
if self.block_state_list[r][c] == 1 and self.label_widget_list[r][c].is_active == PASSIVE:
self.is_game_over = TRUE
self.block_state_list[r][c] = 1
self.label_widget_list[r][c].is_active = ACTIVE
self.label_widget_list[r][c].config(relief=RAISED, bg=str(self.next_block_color))
def clear_cell(self, r, c):
if 0 <= r < BOARD_HEIGHT and 0 <= c < BOARD_WIDTH:
self.block_state_list[r][c] = 0
self.label_widget_list[r][c].is_active = PASSIVE
self.label_widget_list[r][c].config(relief=FLAT, bg=str(self.background_color))
def show_author_info(self, event):
messagebox.showinfo('Made in China', '^_^')
def fill_next_block_preview(self, r, c):
if 0 <= r < 4 and 0 <= c < 4:
self.next_block_preview_list[r][c].config(relief=RAISED, bg=str(self.next_block_color))
def clear_next_block_preview(self, r=None, c=None):
if r is None and c is None: # 모든 미리보기 셀 지우기
for r_idx in range(4):
for c_idx in range(4):
self.next_block_preview_list[r_idx][c_idx].config(relief=FLAT, bg=str(self.sub_background_color))
elif 0 <= r < 4 and 0 <= c < 4: # 특정 셀 지우기
self.next_block_preview_list[r][c].config(relief=FLAT, bg=str(self.sub_background_color))
def reset_game(self):
# 게임 기록 저장
if self.score_file and self.total_score != 0:
score_entry = '%-9u%-8u%-8.2f%-14.2f%-13.2f%-14.2f%s\n' % (
self.total_score, self.total_lines, self.total_time,
self.total_score / self.total_time if self.total_time else 0,
self.total_lines / self.total_time if self.total_time else 0,
float(self.total_score) / self.total_lines if self.total_lines else 0,
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
)
self.score_file.seek(0, 2) # 파일 끝으로 이동
self.score_file.write(score_entry)
self.score_file.flush()
# 게임 상태 초기화
for r in range(BOARD_HEIGHT):
for c in range(BOARD_WIDTH):
self.clear_cell(r, c)
self.total_lines = 0
self.total_score = 0
self.total_time = 0.0
self.lines_label.config(text=str(self.total_lines))
self.score_label.config(text=str(self.total_score))
self.time_label.config(text=str(self.total_time))
self.is_game_over = FALSE
self.is_started = FALSE
self.fall_speed_ms = 1000 # 초기 낙하 속도
self.clear_next_block_preview()
def place_next_block_preview(self):
next_block_shape = block_styles[self.next_block_type][self.next_block_rotation]
for i in range(4):
self.fill_next_block_preview(int(next_block_shape[i][0]), int(next_block_shape[i][1]))
def spawn_new_block(self):
self.current_block_type = self.next_block_type
self.current_block_rotation = self.next_block_rotation
self.current_block_col = random.randint(0, BOARD_WIDTH - 4) # 블록이 처음 나타날 때 좌우 위치 랜덤
self.current_block_row = 0 # 항상 위에서 시작
current_block_shape = block_styles[self.current_block_type][self.current_block_rotation]
# 새 블록 배치
for i in range(4):
row_offset = current_block_shape[i][0]
col_offset = current_block_shape[i][1]
if self.fill_cell(int(row_offset), int(col_offset) + self.current_block_col) == FALSE:
self.is_game_over = TRUE # 블록이 놓이지 않으면 게임 오버
self.is_started = TRUE # 게임 시작 플래그 설정
def generate_random_block(self):
self.next_block_type = random.randint(0, 6) # 블록 종류 랜덤 선택 (0-6)
self.next_block_rotation = random.randint(0, 3) # 블록 회전 상태 랜덤 선택 (0-3)
def show_ranking(self):
if not self.score_file:
messagebox.showinfo('Ranking', 'Score file not available.')
return
self.score_file.seek(0) # 파일 처음으로 이동
header_line = self.score_file.readline()
rankings = []
for line in self.score_file:
try:
parts = line.strip().split()
if len(parts) >= 7:
score = int(parts[0])
rankings.append((score, line))
except ValueError:
continue # 잘못된 형식의 줄은 건너뜀
# 점수 기준으로 내림차순 정렬
sorted_rankings = sorted(rankings, key=lambda x: x[0], reverse=True)
ranking_display = header_line.strip() + "\n"
for i in range(min(10, len(sorted_rankings))): # 상위 10개만 표시
ranking_display += sorted_rankings[i][1].strip() + "\n"
messagebox.showinfo('Ranking', ranking_display)
def start_game_with_s(self, event):
self.generate_random_block()
self.spawn_new_block()
self.place_next_block_preview()
def start_game(self):
self.reset_game()
self.generate_random_block()
self.spawn_new_block()
self.place_next_block_preview()
def end_game(self):
self.reset_game()
def settings_menu(self):
print("Settings feature is under development...")
# 메뉴 생성
main_menu = Menu(root)
root['menu'] = main_menu
# 게임 메뉴
game_menu = Menu(main_menu)
main_menu.add_cascade(label='Game', menu=game_menu)
game_menu.add_command(label='Start', command=lambda: app.start_game())
game_menu.add_command(label='End', command=lambda: app.end_game())
game_menu.add_separator()
game_menu.add_command(label='Exit', command=root.quit)
# 설정 메뉴
settings_menu = Menu(main_menu)
main_menu.add_cascade(label='Settings', menu=settings_menu)
settings_menu.add_command(label='Options', command=lambda: app.settings_menu())
# 랭킹 메뉴
ranking_menu = Menu(main_menu)
main_menu.add_cascade(label='Ranking', menu=ranking_menu)
ranking_menu.add_command(label='Show Ranking', command=lambda: app.show_ranking())
# 애플리케이션 인스턴스 생성 및 메인 루프 시작
app = TetrisGame(root)
root.mainloop()
2. 뱀 게임
Pygame 라이브러리를 사용하여 구현된 고전적인 뱀 게임입니다.
import random
import pygame
import sys
from pygame.locals import *
# 게임 설정
SNAKE_SPEED = 9
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 500
CELL_SIZE = 20
# 셀 크기가 창 크기의 배수가 되도록 보장
assert WINDOW_WIDTH % CELL_SIZE == 0, "Window width must be a multiple of cell size."
assert WINDOW_HEIGHT % CELL_SIZE == 0, "Window height must be a multiple of cell size."
CELL_WIDTH = int(WINDOW_WIDTH / CELL_SIZE)
CELL_HEIGHT = int(WINDOW_HEIGHT / CELL_SIZE)
# 색상 정의
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
DARK_GREEN = (0, 155, 0)
DARK_GRAY = (40, 40, 40)
YELLOW = (255, 255, 0)
RED_DARK = (150, 0, 0)
BLUE = (0, 0, 255)
BLUE_DARK = (0, 0, 150)
BACKGROUND_COLOR = BLACK
# 방향 정의
UP = 'up'
DOWN = 'down'
LEFT = 'left'
RIGHT = 'right'
HEAD = 0 # 뱀 머리 인덱스
def main():
global DISPLAYSURF, BASICFONT, SnakeSpeedClock
pygame.init()
SnakeSpeedClock = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
pygame.display.set_caption('Snake Game')
show_start_screen()
while True:
run_game()
show_game_over_screen()
def run_game():
# 뱀의 시작 위치 무작위 설정
start_x = random.randint(5, CELL_WIDTH - 6)
start_y = random.randint(5, CELL_HEIGHT - 6)
worm_coords = [{'x': start_x, 'y': start_y},
{'x': start_x - 1, 'y': start_y},
{'x': start_x - 2, 'y': start_y}]
direction = RIGHT
# 사과 무작위 위치 설정
apple = get_random_location()
while True:
# 이벤트 처리 루프
for event in pygame.event.get():
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN:
if (event.key == K_LEFT) and direction != RIGHT:
direction = LEFT
elif (event.key == K_RIGHT) and direction != LEFT:
direction = RIGHT
elif (event.key == K_UP) and direction != DOWN:
direction = UP
elif (event.key == K_DOWN) and direction != UP:
direction = DOWN
elif event.key == K_ESCAPE:
terminate()
# 뱀이 자신 또는 벽에 부딪혔는지 확인
if worm_coords[HEAD]['x'] == -1 or worm_coords[HEAD]['x'] == CELL_WIDTH or \
worm_coords[HEAD]['y'] == -1 or worm_coords[HEAD]['y'] == CELL_HEIGHT:
return # 게임 오버
for worm_body in worm_coords[1:]:
if worm_body['x'] == worm_coords[HEAD]['x'] and worm_body['y'] == worm_coords[HEAD]['y']:
return # 게임 오버
# 뱀이 사과를 먹었는지 확인
if worm_coords[HEAD]['x'] == apple['x'] and worm_coords[HEAD]['y'] == apple['y']:
apple = get_random_location() # 새로운 사과 위치 설정
else:
del worm_coords[-1] # 뱀 꼬리 제거
# 뱀 이동 (이동 방향으로 새로운 머리 추가)
if direction == UP:
new_head = {'x': worm_coords[HEAD]['x'], 'y': worm_coords[HEAD]['y'] - 1}
elif direction == DOWN:
new_head = {'x': worm_coords[HEAD]['x'], 'y': worm_coords[HEAD]['y'] + 1}
elif direction == LEFT:
new_head = {'x': worm_coords[HEAD]['x'] - 1, 'y': worm_coords[HEAD]['y']}
elif direction == RIGHT:
new_head = {'x': worm_coords[HEAD]['x'] + 1, 'y': worm_coords[HEAD]['y']}
worm_coords.insert(0, new_head)
# 화면 그리기
DISPLAYSURF.fill(BACKGROUND_COLOR)
draw_grid()
draw_worm(worm_coords)
draw_apple(apple)
draw_score(len(worm_coords) - 3)
pygame.display.update()
SnakeSpeedClock.tick(SNAKE_SPEED)
def draw_press_key_msg():
press_key_surf = BASICFONT.render('Press a key to play.', True, WHITE)
press_key_rect = press_key_surf.get_rect()
press_key_rect.topleft = (WINDOW_WIDTH - 200, WINDOW_HEIGHT - 30)
DISPLAYSURF.blit(press_key_surf, press_key_rect)
def check_for_key_press():
if len(pygame.event.get(QUIT)) > 0:
terminate()
key_up_events = pygame.event.get(KEYUP)
if len(key_up_events) == 0:
return None
if key_up_events[0].key == K_ESCAPE:
terminate()
return key_up_events[0].key
def show_start_screen():
title_font = pygame.font.Font('freesansbold.ttf', 100)
title_surf1 = title_font.render('Snake!', True, WHITE, DARK_GREEN)
degrees1 = 0
degrees2 = 0
while True:
DISPLAYSURF.fill(BACKGROUND_COLOR)
rotated_surf1 = pygame.transform.rotate(title_surf1, degrees1)
rotated_rect1 = rotated_surf1.get_rect()
rotated_rect1.center = (WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2)
DISPLAYSURF.blit(rotated_surf1, rotated_rect1)
draw_press_key_msg()
if check_for_key_press():
pygame.event.get() # 이벤트 큐 비우기
return
pygame.display.update()
SnakeSpeedClock.tick(SNAKE_SPEED)
degrees1 += 3
degrees2 += 7
def terminate():
pygame.quit()
sys.exit()
def get_random_location():
return {'x': random.randint(0, CELL_WIDTH - 1), 'y': random.randint(0, CELL_HEIGHT - 1)}
def show_game_over_screen():
game_over_font = pygame.font.Font('freesansbold.ttf', 100)
game_surf = game_over_font.render('Game', True, WHITE)
over_surf = game_over_font.render('Over', True, WHITE)
game_rect = game_surf.get_rect()
over_rect = over_surf.get_rect()
game_rect.midtop = (WINDOW_WIDTH / 2, 10)
over_rect.midtop = (WINDOW_WIDTH / 2, game_rect.height + 10 + 25)
DISPLAYSURF.blit(game_surf, game_rect)
DISPLAYSURF.blit(over_surf, over_rect)
draw_press_key_msg()
pygame.display.update()
pygame.time.wait(500)
check_for_key_press() # 이벤트 큐 비우기
while True:
if check_for_key_press():
pygame.event.get() # 이벤트 큐 비우기
return
def draw_score(score):
score_surf = BASICFONT.render('Score: %s' % (score), True, WHITE)
score_rect = score_surf.get_rect()
score_rect.topleft = (WINDOW_WIDTH - 120, 10)
DISPLAYSURF.blit(score_surf, score_rect)
def draw_worm(worm_coords):
for coord in worm_coords:
x = coord['x'] * CELL_SIZE
y = coord['y'] * CELL_SIZE
worm_segment_rect = pygame.Rect(x, y, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(DISPLAYSURF, DARK_GREEN, worm_segment_rect)
worm_inner_segment_rect = pygame.Rect(x + 4, y + 4, CELL_SIZE - 8, CELL_SIZE - 8)
pygame.draw.rect(DISPLAYSURF, GREEN, worm_inner_segment_rect)
def draw_apple(coord):
x = coord['x'] * CELL_SIZE
y = coord['y'] * CELL_SIZE
apple_rect = pygame.Rect(x, y, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(DISPLAYSURF, RED, apple_rect)
def draw_grid():
for x in range(0, WINDOW_WIDTH, CELL_SIZE): # 수직선 그리기
pygame.draw.line(DISPLAYSURF, DARK_GRAY, (x, 0), (x, WINDOW_HEIGHT))
for y in range(0, WINDOW_HEIGHT, CELL_SIZE): # 수평선 그리기
pygame.draw.line(DISPLAYSURF, DARK_GRAY, (0, y), (WINDOW_WIDTH, y))
if __name__ == '__main__':
try:
main()
except SystemExit:
pass
3. 꺼지지 않는 창
Tkinter를 사용하여 사용자를 혼란시키는 간단한 창 게임입니다.
from tkinter import *
class AnnoyingWindow:
def __init__(self):
self.window = Tk()
self.window.title("Question")
self.window.geometry("300x200") # 창 크기 설정
self.label = Label(self.window, text='Do you like me?')
self.label.place(x=80, y=70)
self.button_yes = Button(self.window, text='Yes', width=6, height=1)
self.button_no = Button(self.window, text='No', width=6, height=1)
self.button_yes.place(x=40, y=130)
self.button_no.place(x=120, y=130)
# 마우스 커서가 버튼에 들어왔을 때 이벤트 바인딩
self.button_yes.bind('<Enter>', self.move_button_yes)
self.button_no.bind('<Enter>', self.move_button_no)
self.window.mainloop()
def move_button_yes(self, event):
# 'Yes' 버튼을 무작위 위치로 이동
new_x = random.randint(0, self.window.winfo_width() - 50)
new_y = random.randint(0, self.window.winfo_height() - 50)
self.button_yes.place(x=new_x, y=new_y)
# 'No' 버튼 텍스트 변경
self.button_no.config(text='Yes')
def move_button_no(self, event):
# 'No' 버튼을 무작위 위치로 이동
new_x = random.randint(0, self.window.winfo_width() - 50)
new_y = random.randint(0, self.window.winfo_height() - 50)
self.button_no.place(x=new_x, y=new_y)
# 'Yes' 버튼 텍스트 변경
self.button_yes.config(text='No')
# 메인 창 (이 창은 닫을 수 없음)
main_window = Tk()
main_window.title("Unclosable Window")
main_window.geometry("300x200")
label_main = Label(main_window, text='Closing this window won\'t change the fact that you like me.')
label_main.place(x=2, y=80)
button_ok = Button(main_window, text='OK', command=main_window.destroy)
button_ok.place(x=80, y=150)
# AnnoyingWindow 인스턴스 생성 (이 창은 닫기 버튼이 작동하지 않음)
annoying_app = AnnoyingWindow()
main_window.mainloop()
4. 장미 그리기
Turtle 그래픽 라이브러리를 사용하여 아름다운 장미를 그리는 코드입니다.
import turtle
import time
pen = turtle.Turtle()
pen.speed(5) # 펜 속도 설정
# 초기 위치 및 설정
pen.penup()
pen.left(90)
pen.forward(200)
pen.pendown()
pen.right(90)
pen.pensize(2)
# 꽃술
pen.fillcolor("red")
pen.begin_fill()
pen.circle(10, 180)
pen.circle(25, 110)
pen.left(50)
pen.circle(60, 45)
pen.circle(20, 170)
pen.right(24)
pen.forward(30)
pen.left(10)
pen.circle(30, 110)
pen.forward(20)
pen.left(40)
pen.circle(90, 70)
pen.circle(30, 150)
pen.right(30)
pen.forward(15)
pen.circle(80, 90)
pen.left(15)
pen.forward(45)
pen.right(165)
pen.forward(20)
pen.left(155)
pen.circle(150, 80)
pen.left(50)
pen.circle(150, 90)
pen.end_fill()
# 꽃잎 1
pen.left(150)
pen.circle(-90, 70)
pen.left(20)
pen.circle(75, 105)
pen.setheading(60)
pen.circle(80, 98)
pen.circle(-90, 40)
# 꽃잎 2
pen.left(180)
pen.circle(90, 40)
pen.circle(-80, 98)
pen.setheading(-83)
# 잎 1
pen.forward(30)
pen.left(90)
pen.forward(25)
pen.left(45)
pen.fillcolor("green")
pen.begin_fill()
pen.circle(-80, 90)
pen.right(90)
pen.circle(-80, 90)
pen.end_fill()
pen.right(135)
pen.forward(60)
pen.left(180)
pen.forward(85)
pen.left(90)
pen.forward(80)
# 잎 2
pen.right(90)
pen.right(45)
pen.fillcolor("green")
pen.begin_fill()
pen.circle(80, 90)
pen.left(90)
pen.circle(80, 90)
pen.end_fill()
pen.left(135)
pen.forward(60)
pen.left(180)
pen.forward(60)
pen.right(90)
pen.circle(200, 50) # 반지름 200, 각도 50도로 원 일부 그리기
# 창 자동 닫힘 방지
turtle.done()
5. 화려한 무지개 줄
Turtle 그래픽을 사용하여 다채로운 무지개 효과를 내는 코드입니다.
import turtle
pen = turtle.Turtle()
screen = turtle.Screen()
screen.bgcolor("black") # 배경색을 검은색으로 설정
sides = 7 # 줄의 수
colors = ["red", "orange", "yellow", "green", "cyan", "blue", "purple"]
for x in range(360):
pen.pencolor(colors[x % sides]) # 색상 순환
pen.forward(x * 3 / sides + x) # 전진 거리 증가
pen.left(360 / sides + 1) # 회전 각도 증가
pen.width(x * sides / 200) # 펜 두께 증가
6. 실시간 시계
Turtle 그래픽을 사용하여 아날로그 시계를 구현하고 현재 시간을 표시합니다.
# -*- coding:utf-8 -*-
import turtle as t
import datetime as d
def skip(step): # 펜을 들고 이동
t.penup()
t.forward(step)
t.pendown()
def draw_clock(radius): # 시계 판 그리기
t.speed(0) # 최대 속도
t.mode("logo") # 로고 좌표계 사용
t.hideturtle() # 거북이 숨기기
t.pensize(7) # 펜 두께
t.home() # 원점으로 이동
for j in range(60):
skip(radius)
if (j % 5 == 0): # 5분마다 긴 선
t.forward(20)
skip(-radius - 20)
else: # 그 외에는 점
t.dot(5)
skip(-radius)
t.right(6) # 6도씩 회전 (360 / 60)
def make_pointer_shape(point_name, length): # 시침, 분침, 초침 모양 생성
t.penup()
t.home()
t.begin_poly()
t.back(0.1 * length) # 약간 뒤로 이동하여 중심 맞추기
t.forward(length * 1.1) # 길이를 약간 넘어서 그리도록
t.end_poly()
poly = t.get_poly()
t.register_shape(point_name, poly) # 모양 등록
def draw_pointers(): # 시침, 분침, 초침 생성 및 등록
global hour_pointer, minute_pointer, second_pointer, font_writer
make_pointer_shape("hour_pointer", 100)
make_pointer_shape("minute_pointer", 120)
make_pointer_shape("second_pointer", 140)
hour_pointer = t.Turtle() # 시침 Turtle 객체
hour_pointer.shape("hour_pointer")
hour_pointer.shapesize(1, 1, 6) # 크기 조절
minute_pointer = t.Turtle() # 분침 Turtle 객체
minute_pointer.shape("minute_pointer")
minute_pointer.shapesize(1, 1, 4)
second_pointer = t.Turtle() # 초침 Turtle 객체
second_pointer.shape("second_pointer")
second_pointer.pencolor('red') # 초침 색상
font_writer = t.Turtle() # 날짜/요일 표시용 Turtle
font_writer.pencolor('gray')
font_writer.hideturtle()
def get_weekday_name(weekday): # 요일 숫자를 이름으로 변환
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
return weekdays[weekday]
def get_date_string(year, month, day): # 날짜 문자열 포맷
return f"{year:04d}-{month:02d}-{day:02d}"
def update_time(): # 실시간 시계 업데이트
current_time = d.datetime.now()
year = current_time.year
month = current_time.month
day = current_time.day
hour = current_time.hour
minute = current_time.minute
second = current_time.second
weekday = current_time.weekday()
t.tracer(False) # 화면 업데이트 비활성화 (부드러운 애니메이션)
# 시침, 분침, 초침 각도 설정
second_pointer.setheading(360 / 60 * second)
minute_pointer.setheading(360 / 60 * minute + 6 * second / 60) # 분은 초에 따라 약간씩 이동
hour_pointer.setheading(360 / 12 * hour + 30 / 60 * minute) # 시는 분에 따라 약간씩 이동
# 날짜 및 요일 표시
font_writer.clear()
font_writer.penup()
font_writer.home()
font_writer.forward(80)
font_writer.write(get_weekday_name(weekday), align="center", font=("Courier", 14, "bold"))
font_writer.forward(-160) # 반대 방향으로 이동
font_writer.write(get_date_string(year, month, day), align="center", font=("Courier", 14, "bold"))
t.tracer(True) # 화면 업데이트 활성화
# 1000ms (1초) 후에 다시 update_time 호출
t.ontimer(update_time, 1000)
def main():
t.tracer(False) # 초기 화면 그리기 전에 업데이트 비활성화
draw_clock(160) # 시계 판 그리기
draw_pointers() # 시침, 분침, 초침 그리기
update_time() # 실시간 시계 업데이트 시작
t.tracer(True) # 화면 업데이트 활성화
t.mainloop()
if __name__ == '__main__':
main()
7. 페파피그 그리기
Turtle 그래픽 라이브러리를 사용하여 인기 캐릭터 페파피그를 그리는 코드입니다.
# -*- coding: utf-8 -*-
import turtle as t
t.screensize(400, 300) # 화면 크기 설정
t.pensize(4) # 펜 두께
t.colormode(255) # 색상 모드를 0-255 범위로 설정
t.color((255, 155, 192), "pink") # 펜 색상 및 채우기 색상 설정 (핑크)
t.setup(840, 500) # 메인 창 크기 설정
t.speed(10) # 펜 속도 설정
# 코 (Nose)
t.pu()
t.goto(-100, 100)
t.pd()
t.seth(-30) # 각도 설정
t.begin_fill()
a = 0.4
for i in range(120):
if 0 <= i < 30 or 60 <= i < 90:
a = a + 0.08
t.lt(3)
t.fd(a)
else:
a = a - 0.08
t.lt(3)
t.fd(a)
t.end_fill()
# 콧방울 (Nostrils)
t.pu()
t.seth(90)
t.fd(25)
t.seth(0)
t.fd(10)
t.pd()
t.pencolor(255, 155, 192)
t.seth(10)
t.begin_fill()
t.circle(5)
t.color(160, 82, 45) # 갈색
t.end_fill()
t.pu()
t.seth(0)
t.fd(20)
t.pd()
t.pencolor(255, 155, 192)
t.seth(10)
t.begin_fill()
t.circle(5)
t.color(160, 82, 45)
t.end_fill()
# 머리 (Head)
t.color((255, 155, 192), "pink")
t.pu()
t.seth(90)
t.fd(41)
t.seth(0)
t.fd(0)
t.pd()
t.begin_fill()
t.seth(180)
t.circle(300, -30)
t.circle(100, -60)
t.circle(80, -100)
t.circle(150, -20)
t.circle(60, -95)
t.seth(161)
t.circle(-300, 15)
# 코 다시 그리기 (머리 위에 겹치도록)
t.pu()
t.goto(-100, 100)
t.pd()
t.seth(-30)
a = 0.4
for i in range(60):
if 0 <= i < 30 or 60 <= i < 90:
a = a + 0.08
t.lt(3)
t.fd(a)
else:
a = a - 0.08
t.lt(3)
t.fd(a)
t.end_fill()
# 귀 (Ears)
t.color((255, 155, 192), "pink")
t.pu()
t.seth(90)
t.fd(-7)
t.seth(0)
t.fd(70)
t.pd()
t.begin_fill()
t.seth(100)
t.circle(-50, 50)
t.circle(-10, 120)
t.circle(-50, 54)
t.end_fill()
t.pu()
t.seth(90)
t.fd(-12)
t.seth(0)
t.fd(30)
t.pd()
t.begin_fill()
t.seth(100)
t.circle(-50, 50)
t.circle(-10, 120)
t.circle(-50, 56)
t.end_fill()
# 눈 (Eyes)
t.color((255, 155, 192), "white")
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-95)
t.pd()
t.begin_fill()
t.circle(15)
t.end_fill()
t.color("black")
t.pu()
t.seth(90)
t.fd(12)
t.seth(0)
t.fd(-3)
t.pd()
t.begin_fill()
t.circle(3)
t.end_fill()
t.color((255, 155, 192), "white")
t.pu()
t.seth(90)
t.fd(-25)
t.seth(0)
t.fd(40)
t.pd()
t.begin_fill()
t.circle(15)
t.end_fill()
t.color("black")
t.pu()
t.seth(90)
t.fd(12)
t.seth(0)
t.fd(-3)
t.pd()
t.begin_fill()
t.circle(3)
t.end_fill()
# 뺨 (Cheeks)
t.color((255, 155, 192))
t.pu()
t.seth(90)
t.fd(-95)
t.seth(0)
t.fd(65)
t.pd()
t.begin_fill()
t.circle(30)
t.end_fill()
# 입 (Mouth)
t.color(239, 69, 19)
t.pu()
t.seth(90)
t.fd(15)
t.seth(0)
t.fd(-100)
t.pd()
t.seth(-80)
t.circle(30, 40)
t.circle(40, 80)
# 몸통 (Body)
t.color("red", (255, 99, 71))
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-78)
t.pd()
t.begin_fill()
t.seth(-130)
t.circle(100, 10)
t.circle(300, 30)
t.seth(0)
t.fd(230)
t.seth(90)
t.circle(300, 30)
t.circle(100, 3)
t.color((255, 155, 192), (255, 100, 100))
t.seth(-135)
t.circle(-80, 63)
t.circle(-150, 24)
t.end_fill()
# 팔 (Arms)
t.color((255, 155, 192))
t.pu()
t.seth(90)
t.fd(-40)
t.seth(0)
t.fd(-27)
t.pd()
t.seth(-160)
t.circle(300, 15)
t.pu()
t.seth(90)
t.fd(15)
t.seth(0)
t.fd(0)
t.pd()
t.seth(-10)
t.circle(-20, 90)
t.pu()
t.seth(90)
t.fd(30)
t.seth(0)
t.fd(237)
t.pd()
t.seth(-20)
t.circle(-300, 15)
t.pu()
t.seth(90)
t.fd(20)
t.seth(0)
t.fd(0)
t.pd()
t.seth(-170)
t.circle(20, 90)
# 다리 (Legs)
t.pensize(10)
t.color((240, 128, 128)) # 옅은 빨강
t.pu()
t.seth(90)
t.fd(-75)
t.seth(0)
t.fd(-180)
t.pd()
t.seth(-90)
t.fd(40)
t.seth(-180)
t.color("black") # 신발
t.pensize(15)
t.fd(20)
t.pensize(10)
t.color((240, 128, 128))
t.pu()
t.seth(90)
t.fd(40)
t.seth(0)
t.fd(90)
t.pd()
t.seth(-90)
t.fd(40)
t.seth(-180)
t.color("black")
t.pensize(15)
t.fd(20)
# 꼬리 (Tail)
t.pensize(4)
t.color((255, 155, 192))
t.pu()
t.seth(90)
t.fd(70)
t.seth(0)
t.fd(95)
t.pd()
t.seth(0)
t.circle(70, 20)
t.circle(10, 330)
t.circle(70, 30)
t.done()
8. 해커 코드 비
Pygame을 사용하여 영화 "The Matrix" 스타일의 코드 비 효과를 시뮬레이션합니다.
# -*- coding: utf-8 -*-
import pygame
import random
from pygame.locals import *
from random import randint
# 창 설정 및 폰트 로드
SCREEN_WIDTH = 900
SCREEN_HEIGHT = 600
MIN_SPEED = 4 # 최소 글자 이동 속도
MAX_SPEED = 10 # 최대 글자 이동 속도
FONT_COLOR = (0, 255, 0) # 글자 색상 (녹색)
FONT_SIZE = 5 # 글자 크기
FONT_NUM = 20 # 화면에 표시될 글자 수 (0부터 시작)
FONT_NAME = "consola.ttf" # 사용할 폰트 파일명 (실제 파일과 이름 일치해야 함)
FREQUENCY = 10 # 화면 갱신 빈도
times = 0 # 시간 초기화
# 난수 생성 함수
def random_speed():
return randint(MIN_SPEED, MAX_SPEED)
def random_position():
return randint(0, SCREEN_WIDTH), randint(0, SCREEN_HEIGHT)
def random_value():
return randint(0, 9) # 0-9 사이의 난수 생성 (코드 비 효과)
# 스프라이트 클래스
class CodeChar(pygame.sprite.Sprite):
def __init__(self, start_pos):
pygame.sprite.Sprite.__init__(self)
self.value = str(random_value()) # 표시할 숫자
try:
self.font = pygame.font.Font(FONT_NAME, FONT_SIZE)
except pygame.error: # 폰트 파일이 없을 경우 기본 폰트 사용
self.font = pygame.font.SysFont(None, FONT_SIZE)
self.image = self.font.render(self.value, True, FONT_COLOR)
self.speed = random_speed() # 이동 속도
self.rect = self.image.get_rect()
self.rect.topleft = start_pos # 시작 위치
def update(self):
# 글자를 아래로 이동
self.rect = self.rect.move(0, self.speed)
# 화면 아래로 벗어나면 제거
if self.rect.top > SCREEN_HEIGHT:
self.kill()
# 초기화
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Code Rain")
clock = pygame.time.Clock()
sprite_group = pygame.sprite.Group()
char_spacing = SCREEN_WIDTH // FONT_NUM # 글자 간 간격
# 메인 루프
running = True
while running:
time_passed = clock.tick(FREQUENCY) # 프레임 속도 설정
# 이벤트 처리
for event in pygame.event.get():
if event.type == QUIT:
running = False
# 화면 배경 채우기
screen.fill((0, 0, 0)) # 검은색 배경
# 새로운 글자 생성 및 그룹에 추가
for i in range(char_spacing):
sprite_group.add(CodeChar((i * FONT_NUM, -FONT_SIZE))) # 화면 위에서 시작
# 스프라이트 업데이트 및 그리기
sprite_group.update()
sprite_group.draw(screen)
# 화면 업데이트
pygame.display.update()
pygame.quit()
sys.exit()
이 예제들은 Python의 다양한 라이브러리를 활용하여 재미있는 게임과 그래픽 효과를 만드는 방법을 보여줍니다. 각 코드 블록은 독립적으로 실행 가능하며, 필요에 따라 수정하거나 확장하여 자신만의 프로젝트를 만들 수 있습니다.
참고: 일부 코드는 특정 라이브러리(예: Pygame)의 설치가 필요할 수 있습니다. pip install pygame 명령어를 사용하여 설치할 수 있습니다.