반응형
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 게임을 실행할 것입니다. 이는 여전히 기본 구현이며 점수 추가, 행렬을 사용한 충돌 감지 구현, 이동 애니메이션 부드럽게 처리 등 개선할 수 있는 방법이 많습니다.
위 결과는 코드 생성 툴에 의한 결과로 정상동작하지 않고 있어 수정 진행 예정입니다.
반응형
'파이썬 기초문법' 카테고리의 다른 글
이터레이터(Iterator) vs 제너레이터(Generator) - 파이썬 대용량 데이터 처리의 지름길 (0) | 2024.05.10 |
---|---|
파이썬 코딩의 혁신! __slots__로 메모리 절약하기 (0) | 2024.05.10 |
파이썬 selenium을 활용한 블로그 검색 및 자동 댓글 남기기 (2) | 2023.09.13 |
[Python] 정규식을 활용하여 알파벳과 숫자가 섞인 단어 제거 (0) | 2023.08.11 |
[Python 문법] groupby 고유 아이템 종류 카운트 (0) | 2023.07.11 |