파이썬 기초문법

파이썬 스네이크 게임 만들기(Code Llama)

Family in August 2023. 10. 26. 10:32
반응형


import pygame
from pygame.locals import *
from sys import exit

# Initialize Pygame
pygame.init()

# Set up the window dimensions
width = 640
height = 480
screen = pygame.display.set_mode((width, height))

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)

# Create the snake game objects
class Snake:
    def __init__(self, color, speed):
        self.color = color
        self.speed = speed
        self.body = []
        self.direction = "right"

    def move(self):
        # Move the snake in the specified direction
        if self.direction == "right":
            self.body.append((self.body[-1][0] + self.speed, self.body[-1][1]))
        elif self.direction == "left":
            self.body.append((self.body[-1][0] - self.speed, self.body[-1][1]))
        elif self.direction == "up":
            self.body.append((self.body[-1][0], self.body[-1][1] + self.speed))
        else:
            self.body.append((self.body[-1][0], self.body[-1][1] - self.speed))

        # Remove the tail from the body
        del self.body[0]

class Food:
    def __init__(self, color, x, y):
        self.color = color
        self.x = x
        self.y = y
        self.size = 10

# Set up the game clock
clock = pygame.time.Clock()

# Set up the game objects
snake = Snake(GREEN, 10)
food = Food(WHITE, width // 2, height // 2)

# Game loop
while True:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                snake.direction = "left"
            elif event.key == pygame.K_RIGHT:
                snake.direction = "right"
            elif event.key == pygame.K_UP:
                snake.direction = "up"
            elif event.key == pygame.K_DOWN:
                snake.direction = "down"

    # Move the snake
    snake.move()

    # Check for collisions with walls and itself
    if any(x < 0 or x >= width or y < 0 or y >= height for x, y in snake.body):
        print("Game Over!")
        pygame.quit()
        sys.exit()

    # Check for collision with food
    if snake.can_eat(food):
        # Eat the food
        snake.body.insert(0, food.x, food.y)
        food.x = width // 2
        food.y = height // 2

    # Clear the screen
    screen.fill(BLACK)

    # Draw the snake
    snake.draw(screen)

    # Draw the food
    food.draw(screen)

    # Update the screen
    pygame.display.flip()

    # Limit the frame rate
    clock.tick(snake.speed)



이제 이 코드는 실행 가능하며 간단한 Snake 게임을 실행할 것입니다. 이는 여전히 기본 구현이며 점수 추가, 행렬을 사용한 충돌 감지 구현, 이동 애니메이션 부드럽게 처리 등 개선할 수 있는 방법이 많습니다.

위 결과는 코드 생성 툴에 의한 결과로 정상동작하지 않고 있어 수정 진행 예정입니다.

반응형