스네이크 게임

스네이크 게임 제작기 2

잡코신 2024. 3. 13. 18:00
728x90
반응형

지난 시간

지난번엔 지렁이가 움직이는 것까지 구현했다.

이번엔 사과를 먹고 몸이 늘어나는 기능을 구현한다.

스네이크 게임 만들기

사과도 객체이기에 사과 클래스를 만들어준다.

class Apple:
    def __init__(self):
        self.position = (random.randint(0, screen_width // cell_size - 1) * cell_size,
                         random.randint(0, screen_height // cell_size - 1) * cell_size)

    def draw(self, screen):
        pygame.draw.rect(screen, RED, (self.position[0], self.position[1], cell_size, cell_size))

클래스에 대해선 지난시간에 설명했기에 코드를 보면 바로 사과 클래스라는 것을 알 수 있다.

  • __init__: 클래스의 초기화 메서드다. 사과의 초기 위치를 랜덤하게 설정한다.
  • draw: 빨간 사과를 화면에 그리는 클래스다.
class Snake:
    def __init__(self):
        self.segments = [
            (screen_width // 2, screen_height // 2),
            (screen_width // 2 - cell_size, screen_height // 2),
            (screen_width // 2 - 2 * cell_size, screen_height // 2)
        ]
        self.direction = random.choice(['up', 'down', 'left', 'right'])
        self.grow = False  # 사과를 먹으면 True로 설정하여 몸이 늘어나도록 함

    def move(self):
        x, y = self.segments[0]
        if self.direction == 'up':
            y -= cell_size
        elif self.direction == 'down':
            y += cell_size
        elif self.direction == 'left':
            x -= cell_size
        elif self.direction == 'right':
            x += cell_size
        self.segments.insert(0, (x, y))
        if not self.grow:  # grow가 False일 때는 꼬리를 제거하여 몸이 늘어나지 않도록 함
            self.segments.pop()
        else:
            self.grow = False

    def change_direction(self, direction):
        if direction == 'up' and self.direction != 'down':
            self.direction = 'up'
        elif direction == 'down' and self.direction != 'up':
            self.direction = 'down'
        elif direction == 'left' and self.direction != 'right':
            self.direction = 'left'
        elif direction == 'right' and self.direction != 'left':
            self.direction = 'right'

    def draw(self, screen):
        for segment in self.segments:
            pygame.draw.rect(screen, GREEN, (segment[0], segment[1], cell_size, cell_size))

지렁이 클래스를 사과를 먹으면 꼬리가 늘어나도록 수정한다.

   apple = Apple()
   
   apple.draw(screen)
   
   if snake.segments[0] == apple.position:
        apple = Apple()
        snake.grow = True  # 사과를 먹으면 grow를 True로 설정하여 몸이 늘어나도록 함

사과를 만들고 사과를 먹으면 사과를 다시 생겨나도록 하는 코드도 만들어준다.

 

하다보니 조금 심심한 것 같아 점수 시스템을 넣어보려고한다.

    score = 0
    
    if snake.segments[0] == apple.position:
        score += 1
        apple = Apple()
        snake.grow = True
        
print('score : ', score)

점수를 저장할 변수를 만들고 사과를 먹을 때마다 1씩 추가한다 그리고 게임이 종료되면 점수를 출력해준다.

 

 

스네이크 게임(ver.2) 플레이하기

import pygame
import random

# 색깔 상수 정의
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

# 게임 화면 크기 설정
screen_width = 800
screen_height = 600
cell_size = 20

# 지렁이 클래스 정의
class Snake:
    def __init__(self):
        self.segments = [
            (screen_width // 2, screen_height // 2),
            (screen_width // 2 - cell_size, screen_height // 2),
            (screen_width // 2 - 2 * cell_size, screen_height // 2)
        ]
        self.direction = random.choice(['up', 'down', 'left', 'right'])
        self.grow = False  # 사과를 먹으면 True로 설정하여 몸이 늘어나도록 함

    def move(self):
        x, y = self.segments[0]
        if self.direction == 'up':
            y -= cell_size
        elif self.direction == 'down':
            y += cell_size
        elif self.direction == 'left':
            x -= cell_size
        elif self.direction == 'right':
            x += cell_size
        self.segments.insert(0, (x, y))
        if not self.grow:  # grow가 False일 때는 꼬리를 제거하여 몸이 늘어나지 않도록 함
            self.segments.pop()
        else:
            self.grow = False

    def change_direction(self, direction):
        if direction == 'up' and self.direction != 'down':
            self.direction = 'up'
        elif direction == 'down' and self.direction != 'up':
            self.direction = 'down'
        elif direction == 'left' and self.direction != 'right':
            self.direction = 'left'
        elif direction == 'right' and self.direction != 'left':
            self.direction = 'right'

    def draw(self, screen):
        for segment in self.segments:
            pygame.draw.rect(screen, GREEN, (segment[0], segment[1], cell_size, cell_size))

# 사과 클래스 정의
class Apple:
    def __init__(self):
        self.position = (random.randint(0, screen_width // cell_size - 1) * cell_size,
                         random.randint(0, screen_height // cell_size - 1) * cell_size)

    def draw(self, screen):
        pygame.draw.rect(screen, RED, (self.position[0], self.position[1], cell_size, cell_size))

# 게임 초기화
pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("지렁이 게임")

clock = pygame.time.Clock()

snake = Snake()
apple = Apple()

score = 0

game_over = False

# 게임 루프
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:
                snake.change_direction('up')
            elif event.key == pygame.K_DOWN:
                snake.change_direction('down')
            elif event.key == pygame.K_LEFT:
                snake.change_direction('left')
            elif event.key == pygame.K_RIGHT:
                snake.change_direction('right')

    snake.move()

    if snake.segments[0] == apple.position:
        score += 1
        apple = Apple()
        snake.grow = True  # 사과를 먹으면 grow를 True로 설정하여 몸이 늘어나도록 함

    if (snake.segments[0][0] < 0 or snake.segments[0][0] >= screen_width or
            snake.segments[0][1] < 0 or snake.segments[0][1] >= screen_height or
            snake.segments[0] in snake.segments[1:]):
        print('score : ', score)
        game_over = True

    screen.fill(BLACK)

    snake.draw(screen)
    apple.draw(screen)

    pygame.display.flip()
    clock.tick(10)

pygame.quit()

최종 코드다. 실행해보자

스네이크 게임 ver2

잘 실행 되는 것을 확인 할 수 있었다.

 

Next

다음엔 게임 시작과 종료를 만들어보겠다.

728x90
반응형

'스네이크 게임' 카테고리의 다른 글

스네이크 게임 제작기 4  (0) 2024.04.10
스네이크 게임 제작기 3  (0) 2024.03.20
스네이크 게임 제작기 1  (1) 2024.03.06