Upload 9 files
Browse filesFiles changed (9)
- snake-pathfinding-AI/README.mdAdded+29
- snake-pathfinding-AI/__pycache__/pathfinding.cpython-312.pycAdded
- snake-pathfinding-AI/__pycache__/settings.cpython-312.pycAdded
- snake-pathfinding-AI/__pycache__/snake.cpython-312.pycAdded
- snake-pathfinding-AI/main.pyAdded+85
- snake-pathfinding-AI/pathfinding.pyAdded+62
- snake-pathfinding-AI/settings.pyAdded+21
- snake-pathfinding-AI/snake.pyAdded+53
- snake-pathfinding-AI/test_snake.pyAdded+95
1234567891011121314151617181920212223242526272829## Snake Game with Pathfinding
This project implements the Snake game using Python and Pygame library. The Snake moves around the screen, eating apples to grow longer. The game ends if the Snake collides with itself or with the screen's boundaries.
## Features
- Snake movement: The Snake moves around the screen based on a predefined pathfinding algorithm (BFS).
- Apple spawning: Apples spawn randomly on the screen for the Snake to eat.
- Collision detection: Detects when the Snake collides with itself or the screen's boundaries.
- Pathfinding: Implements Breadth-First Search (BFS) algorithm to find the shortest path from the Snake to the nearest Apple.
## Installation
1. Clone the repository:
```bash
git clone https://github.com/your-username/snake-game.git
2. Install dependencies:
```bash
pip install pygame
4. Run the game:
```bash
python main.py
## Usage
- The snake will automatically find the shortest path to the nearest apple using the BFS algorithm.
## Tests
- To run unit tests:
- ```bash
python -m unittest test_snake.py12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import pygame
from snake import Apple, Snake
from pathfinding import BFS
from settings import *
def drawGrid():
for x in range(0, WIDTH, BLOCK_SIZE):
for y in range(0, HEIGHT, BLOCK_SIZE):
rect = pygame.Rect(x, y, BLOCK_SIZE, BLOCK_SIZE)
pygame.draw.rect(SCREEN, GRID_CLR, rect, 1)
def handle_events():
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
return True
def update_snake_direction(snake, path):
''' Extract moves from the path and update snake's direction '''
if path:
next_x, next_y = path[0], path[1]
if next_x > 0 and snake.pos != [-1, 0]:
snake.pos = [1, 0]
elif next_x < 0 and snake.pos != [1, 0]:
snake.pos = [-1, 0]
elif next_y > 0 and snake.pos != [0, 1]:
snake.pos = [0, 1]
elif next_y < 0 and snake.pos != [0, -1]:
snake.pos = [0, -1]
# Remove the current move pair from the path
path = path[2:]
return path
def main():
pygame.init()
running = True
clock = pygame.time.Clock()
font = pygame.font.SysFont('timesnewroman', BLOCK_SIZE * 2)
score = font.render("1", True, "white")
score_rect = score.get_rect(center = (WIDTH / 2, HEIGHT / 20)) # Position score at the top center
drawGrid()
snake = Snake()
apple = Apple()
while running:
running = handle_events()
path = BFS(snake, apple, snake.pos)
path = update_snake_direction(snake, path)
snake.drawSnake()
SCREEN.fill(SURFACE_CLR)
drawGrid()
apple.checkSpawn(snake.body)
apple.drawApple()
score = font.render(f"{len(snake.body)}", True, GRID_CLR)
pygame.draw.rect(SCREEN, SNAKE_CLR, snake.head)
for square in snake.body:
pygame.draw.rect(SCREEN, SNAKE_CLR, square)
SCREEN.blit(score, score_rect)
# Grow the snake
if len(snake.body) < 1:
if(snake.head.x == apple.x and snake.head.y == apple.y):
snake.body.append(pygame.Rect(snake.x, snake.y, BLOCK_SIZE, BLOCK_SIZE))
else:
# Differentiates apple from the snake's body
if(snake.head.x == apple.x and snake.head.y == apple.y):
snake.body.append(pygame.Rect(square.x, square.y, BLOCK_SIZE, BLOCK_SIZE))
pygame.display.update()
clock.tick(FPS)
pygame.quit()
if __name__ == "__main__":
main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162from settings import *
from queue import Queue
def get_neighbours(position):
'''
Get neighbouring positions from the current position
Args:
- position: Tuple representing the current position (x, y)
Returns:
- List of neighbouring positions
'''
neighbours = [[position[0] + BLOCK_SIZE, position[1]],
[position[0] - BLOCK_SIZE, position[1]],
[position[0], position[1] + BLOCK_SIZE],
[position[0], position[1] - BLOCK_SIZE]]
neighbours_within_grid = []
for pos in neighbours:
if pos in GRID:
neighbours_within_grid.append(pos)
return neighbours_within_grid
def BFS(snake, apple, current_direction):
'''
Perform Breadth-First Search (BFS) to find the shortest path from the snake's head to the apple
Args:
- snake: Snake object
- apple: Apple object
- current direction: Tuple representing current direction of the snake (x, y)
Returns:
- List representing the sequence of moves to the apple'''
queue = Queue()
head_pos = (snake.head.x, snake.head.y)
apple_pos = (apple.apple.x, apple.apple.y)
queue.put((head_pos, [])) # Initialize queue with snake's head position and empty path
visited = set()
visited.add(head_pos)
while not queue.empty():
current_pos, path = queue.get()
# Return path if apple is found
if current_pos == apple_pos:
return path # Sequence of moves towards the apple
# Explore neighbours
neighbours = get_neighbours(current_pos)
for neighbour in neighbours:
if neighbour not in snake.body:
direction = [neighbour[0] - current_pos[0], neighbour[1] - current_pos[1]]
if direction != [-current_direction[0], -current_direction[1]]:
if tuple(neighbour) not in visited:
visited.add(tuple(neighbour))
new_path = path + direction
queue.put((tuple(neighbour), new_path))
return [] # If no path is found123456789101112131415161718192021import pygame
WIDTH = 800
HEIGHT = 800
BLOCK_SIZE = 50
ROWS = WIDTH // BLOCK_SIZE
GAP_SIZE = 2
# Set up display
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake")
SURFACE_CLR = (0, 0, 0)
GRID_CLR = (255, 255, 255)
SNAKE_CLR = (0, 255, 0)
APPLE_CLR = (255, 0, 0)
FPS = 10
INITIAL_SNAKE_LEN = 1
GRID = [[x,y] for x in range(0, WIDTH, BLOCK_SIZE) for y in range(0, HEIGHT, BLOCK_SIZE)]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import random
from settings import *
class Snake:
def __init__(self):
# Initialize the snake at the center of the screen
self.x, self.y = 0, 0
self.pos = [1, 0] # [x, y] direction, initially set to right
self.head = pygame.Rect(self.x, self.y, BLOCK_SIZE, BLOCK_SIZE)
self.body = [] # List to keep track of snake's body segments
self.dead = False
def drawSnake(self):
# Check if snake has gone out of bounds
if self.head.x not in range(0, WIDTH) or self.head.y not in range(0, HEIGHT):
self.dead = True
print('game over')
# Check if snake has hit itself
for square in self.body:
if self.head.x == square.x and self.head.y == square.y:
self.dead = True
print('game over')
self.body.append(self.head)
# Move body segments to follow head
for i in range(len(self.body) - 1):
self.body[i].x, self.body[i].y = self.body[i + 1].x, self.body[i + 1].y
# Update head position based on current direction
self.head.x += self.pos[0] * BLOCK_SIZE
self.head.y += self.pos[1] * BLOCK_SIZE
self.body.remove(self.head)
class Apple:
def __init__(self):
self.spawn()
def spawn(self):
''' Spawn a new apple ont he screen at a random position '''
# Randomly spawn apple
self.x = random.randrange(0, WIDTH, BLOCK_SIZE)
self.y = random.randrange(0, HEIGHT, BLOCK_SIZE)
self.apple = pygame.Rect(self.x, self.y, BLOCK_SIZE, BLOCK_SIZE)
def drawApple(self):
pygame.draw.rect(SCREEN, APPLE_CLR, self.apple)
def checkSpawn(self, snake: list):
''' Check if the apple collides with the snake. If so, respawn the apple. '''
for square in snake:
if self.apple.colliderect(square):
self.spawn() # Respawn apple if it collides with snake1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495import unittest
import pygame
from snake import Snake, Apple # Make sure the Snake and Apple classes are imported correctly
from settings import *
class TestSnakeGame(unittest.TestCase):
def setUp(self):
pygame.init()
self.snake = Snake()
self.apple = Apple()
def tearDown(self):
pygame.quit()
def test_initial_state(self):
# Test initial snake position
self.assertEqual(self.snake.head.x, 0)
self.assertEqual(self.snake.head.y, 0)
# Test initial snake length
self.assertEqual(len(self.snake.body), 0)
def test_movement(self):
# Test snake movement to the right
self.snake.pos = [1, 0]
self.snake.drawSnake()
self.assertEqual(self.snake.head.x, BLOCK_SIZE)
self.assertEqual(self.snake.head.y, 0)
# Test snake movement left
self.snake.pos = [-1, 0]
self.snake.drawSnake()
self.assertEqual(self.snake.head.x, 0)
self.assertEqual(self.snake.head.y, 0)
# Test snake movement downwards
self.snake.pos = [0, -1]
self.snake.drawSnake()
self.assertEqual(self.snake.head.x, 0)
self.assertEqual(self.snake.head.y, -50)
# Test snake movement upwards
self.snake.pos = [0, 1]
self.snake.drawSnake()
self.assertEqual(self.snake.head.x, 0)
self.assertEqual(self.snake.head.y, 0)
def test_apple_spawn(self):
# Test apple spawning within the grid
self.apple.spawn()
self.assertTrue(0 <= self.apple.apple.x < WIDTH)
self.assertTrue(0 <= self.apple.apple.y < HEIGHT)
self.assertEqual(self.apple.apple.width, BLOCK_SIZE)
self.assertEqual(self.apple.apple.height, BLOCK_SIZE)
def test_eating_apple(self):
# Place apple directly in front of the snake
self.apple.apple.x = self.snake.head.x + BLOCK_SIZE
self.apple.apple.y = self.snake.head.y
self.snake.pos = [1, 0]
self.snake.drawSnake()
# Simulate snake eating the apple
if self.snake.head.colliderect(self.apple.apple):
self.snake.body.append(pygame.Rect(self.snake.head.x, self.snake.head.y, BLOCK_SIZE, BLOCK_SIZE))
self.apple.spawn()
self.assertEqual(len(self.snake.body), 1)
self.assertNotEqual((self.apple.apple.x, self.apple.apple.y), (self.snake.head.x, self.snake.head.y))
def test_collision_with_wall(self):
# Move snake to the right until it hits the wall
self.snake.pos = [-1, 0]
self.snake.drawSnake()
self.snake.pos = [-1, 0]
self.snake.drawSnake()
self.assertTrue(self.snake.dead)
def test_collision_with_self(self):
# Create a situation where the snake will collide with itself
self.snake.body = [
pygame.Rect(WIDTH / 2, HEIGHT / 2, BLOCK_SIZE, BLOCK_SIZE),
pygame.Rect(WIDTH / 2 - BLOCK_SIZE, HEIGHT / 2, BLOCK_SIZE, BLOCK_SIZE),
pygame.Rect(WIDTH / 2 - 2 * BLOCK_SIZE, HEIGHT / 2, BLOCK_SIZE, BLOCK_SIZE)
]
self.snake.pos = [1, 0]
self.snake.drawSnake() # Move right
self.snake.pos = [0, -1]
self.snake.drawSnake() # Move up
self.snake.pos = [-1, 0]
self.snake.drawSnake() # Move left (collide with body)
self.assertTrue(self.snake.dead)
if __name__ == '__main__':
unittest.main()snake-pathfinding-AI/README.mdAdded+29
snake-pathfinding-AI/__pycache__/pathfinding.cpython-312.pycAdded
snake-pathfinding-AI/__pycache__/settings.cpython-312.pycAdded
snake-pathfinding-AI/__pycache__/snake.cpython-312.pycAdded
snake-pathfinding-AI/main.pyAdded+85
snake-pathfinding-AI/pathfinding.pyAdded+62
snake-pathfinding-AI/settings.pyAdded+21
snake-pathfinding-AI/snake.pyAdded+53
snake-pathfinding-AI/test_snake.pyAdded+95