Experiment 5
Name: Suraj Sah Roll no: 36 Class/Div: TE-CMPN/B-2
Code:
import pygame
import random
from collections import deque
# --- Settings ---
WIDTH, HEIGHT = 600, 600
ROWS = 20
CELL_SIZE = WIDTH // ROWS
WHITE = (255, 255, 255)
GREEN = (0, 200, 0)
RED = (200, 0, 0)
BLACK = (0, 0, 0)
[Link]()
win = [Link].set_mode((WIDTH, HEIGHT))
[Link].set_caption("Snake BFS AI")
clock = [Link]()
font = [Link]("Arial", 24)
# --- Helper Functions ---
def random_food(snake):
while True:
pos = ([Link](0, ROWS - 1), [Link](0, ROWS - 1))
if pos not in snake:
return pos
def bfs(start, goal, snake_body):
queue = deque([start])
visited = {start: None}
directions = [(1,0), (-1,0), (0,1), (0,-1)]
while queue:
current = [Link]()
if current == goal:
path = []
while current is not None:
[Link](current)
current = visited[current]
return path[::-1]
for dx, dy in directions:
neighbor = (current[0] + dx, current[1] + dy)
if (0 <= neighbor[0] < ROWS and
0 <= neighbor[1] < ROWS and
neighbor not in visited and
neighbor not in snake_body):
[Link](neighbor)
visited[neighbor] = current
return None
# --- Game Setup ---
snake = [(10, 10)]
food = random_food(snake)
score = 0
running = True
# --- Main Loop ---
while running:
[Link](10)
[Link](WHITE)
for event in [Link]():
if [Link] == [Link]:
running = False
# --- BFS Pathfinding ---
path = bfs(snake[0], food, snake)
if path and len(path) > 1:
next_move = path[1]
else:
moves = [(1,0), (-1,0), (0,1), (0,-1)]
[Link](moves)
next_move = None
for dx, dy in moves:
candidate = (snake[0][0] + dx, snake[0][1] + dy)
if (0 <= candidate[0] < ROWS and
0 <= candidate[1] < ROWS and
candidate not in snake):
next_move = candidate
break
if not next_move:
print("Game Over")
running = False
continue
[Link](0, next_move)
if next_move == food:
food = random_food(snake)
score += 1
else:
[Link]()
# --- Drawing Snake ---
for segment in snake:
rect = [Link](segment[0] * CELL_SIZE,
segment[1] * CELL_SIZE,
CELL_SIZE, CELL_SIZE)
[Link](win, GREEN, rect)
# --- Drawing Food ---
food_rect = [Link](food[0] * CELL_SIZE,
food[1] * CELL_SIZE,
CELL_SIZE, CELL_SIZE)
[Link](win, RED, food_rect)
# --- Score Display ---
score_text = [Link]("Score: " + str(score), True, BLACK)
[Link](score_text, (10, 10))
[Link]()
[Link]()
Output: