파이썬에서는 여러가지 게임을 만들 수 있다. 그 중에 기본적이면서 아주 많이 알려진 게임이 있는데 바로 지렁이게임이다. 지렁이 게임은 코드가 그렇게 어렵지도 않으면서 만드는 사람에 따라 여러가지 모습으로 표현되어진다. 파이썬에서 제공하는 pygmae 라이브러리를 사용하여 만들어볼 수 있다. 만약 pygame이 설치 된 경우 설치를 건너뛰고 바로 지렁이 게임 코드를 입력해도 된다.
![[파이썬 게임] 지렁이게임 만들기 (with pygame) 2 지렁이게임](https://www.shindeacon.co.kr/wp-content/uploads/2023/09/지렁이게임-optimized.png)
Table of Contents
1. pygame 모듈 설치하기
pygmae 설치는 매우 간단하게 설치를 할 수 있다. 먼저 윈도우 검색창에서 cmd를 입력하여 ‘명령 프롬프트’를 찾아 실행하거나 “윈도우키 + R” 를 눌러 실행에서 cmd를 입력하여 실행을 하면 된다.
![[파이썬 게임] 지렁이게임 만들기 (with pygame) 3 실행](https://www.shindeacon.co.kr/wp-content/uploads/2023/09/실행-300x155-optimized.png)
명령 프롬프트 화면에서 ‘pip install pygame‘을 입력하여 설치를 완료하면 된다. 만약 오류가 날 경우 다른 방법을 찾아야 한다. 예를 들어 ‘pip3 install pygame’를 입력해본다.
그래도 안된다면 버전을 변경하여 설치를 해야한다.
![[파이썬 게임] 지렁이게임 만들기 (with pygame) 4 pip](https://www.shindeacon.co.kr/wp-content/uploads/2023/09/화면-캡처-2023-09-24-161814-300x94-optimized.png)
2. 게임설정
이번에 만드는 지렁이게임은 아래의 조건을 포함한 코드로 작성되었다.
# 화면 크기 설정 : 800 * 600
# 색상 설정
– 배경 : black(0, 0, 0)
– 지렁이 색상 : white(255, 255, 255)
– 먹이 색상 : green(0, 255, 0)
# 점수 표시하기
# 2초 대기 후 게임 시작하기
# 게임 오버시 “GAME OVER” 메시지 띄우기
# 화면밖으로 나가거나 몸통 부딪힐 경우 게임 오버
# 게임 오버 후 자동으로 창이 닫히지 않기
3. 지렁이게임 코드 작성
import pygame
import sys
import random
# Pygame 초기화
pygame.init()
# 화면 크기 설정
screen_width = 800
screen_height = 600
cell_size = 20
# 색상 설정
white = (255, 255, 255)
black = (0, 0, 0)
green = (0, 255, 0)
# 화면 생성
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("지렁이 게임")
# 초기 위치 설정
snake_x = screen_width // 2
snake_y = screen_height // 2
# 초기 방향 설정
direction = "RIGHT"
# 초기 뱀 길이와 몸통 위치 설정
snake_length = 1
snake_body = [(snake_x, snake_y)]
# 초기 음식 위치 설정
food_x = random.randint(0, (screen_width // cell_size) - 1) * cell_size
food_y = random.randint(0, (screen_height // cell_size) - 1) * cell_size
# 게임 변수 설정
game_over = False
score = 0
# 게임 오버 메시지 설정
font = pygame.font.Font(None, 36)
game_over_text = font.render("Game Over", True, white)
game_over_text_rect = game_over_text.get_rect(center=(screen_width // 2, screen_height // 2))
# 2초 대기
pygame.time.delay(2000)
# 게임 루프
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != "DOWN":
direction = "UP"
elif event.key == pygame.K_DOWN and direction != "UP":
direction = "DOWN"
elif event.key == pygame.K_LEFT and direction != "RIGHT":
direction = "LEFT"
elif event.key == pygame.K_RIGHT and direction != "LEFT":
direction = "RIGHT"
# 뱀 머리 이동
if direction == "UP":
snake_y -= cell_size
elif direction == "DOWN":
snake_y += cell_size
elif direction == "LEFT":
snake_x -= cell_size
elif direction == "RIGHT":
snake_x += cell_size
# 뱀 머리와 음식 충돌 검사
if snake_x == food_x and snake_y == food_y:
score += 1
food_x = random.randint(0, (screen_width // cell_size) - 1) * cell_size
food_y = random.randint(0, (screen_height // cell_size) - 1) * cell_size
snake_length += 1
# 뱀 몸통 길이 관리
snake_body.append((snake_x, snake_y))
if len(snake_body) > snake_length:
del snake_body[0]
# 화면 초기화
screen.fill(black)
# 음식 그리기
pygame.draw.rect(screen, green, (food_x, food_y, cell_size, cell_size))
# 뱀 그리기
for segment in snake_body:
pygame.draw.rect(screen, white, (segment[0], segment[1], cell_size, cell_size))
# 게임 오버 조건 추가: 화면 경계를 벗어났을 때
if (
snake_x >= screen_width
or snake_x < 0
or snake_y >= screen_height
or snake_y < 0
):
game_over = True
# 점수 표시
font = pygame.font.Font(None, 36)
text = font.render("Score: " + str(score), True, white)
screen.blit(text, (10, 10))
# 게임 오버 상태일 때 게임 오버 메시지 표시
if game_over:
screen.blit(game_over_text, game_over_text_rect)
# 화면 업데이트
pygame.display.update()
# 게임 속도 조절
pygame.time.Clock().tick(10)
# 게임 종료 시 창을 닫을 때까지 대기
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()