humanus.cpp/snake/snake_game.py

61 lines
1.8 KiB
Python

import pygame
import sys
from pygame.locals import *
class Snake:
def __init__(self, start_position, length=3):
self.body = [start_position] * length
self.direction = (0, 1) # Initially, the snake is moving to the right
def move(self):
head_x, head_y = self.body[0]
dir_x, dir_y = self.direction
new_head = (head_x + dir_x, head_y + dir_y)
self.body.insert(0, new_head)
self.body.pop()
def change_direction(self, new_direction):
if (new_direction[0] == -self.direction[0] and new_direction[1] == -self.direction[1]):
return
self.direction = new_direction
def grow(self):
self.body.append(self.body[-1])
# Initialize Pygame
pygame.init()
window_size = (400, 400)
screen = pygame.display.set_mode(window_size)
clock = pygame.time.Clock()
# Create a snake at position (20, 20)
snake = Snake((20, 20))
# Main game loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_UP:
snake.change_direction((0, -1))
elif event.key == K_DOWN:
snake.change_direction((0, 1))
elif event.key == K_LEFT:
snake.change_direction((-1, 0))
elif event.key == K_RIGHT:
snake.change_direction((1, 0))
# Move the snake
snake.move()
# Clear screen
screen.fill((0, 0, 0))
# Draw the snake (for simplicity, we will just print its position)
for part in snake.body:
print(part) # In a real game, you would draw the snake on the screen here
# Update display
pygame.display.update()
clock.tick(10) # Limit the frame rate to 10 FPS