import random
import time
import os
# Define game board dimensions
WIDTH = 20
HEIGHT = 10
# Define snake body parts
SNAKE_HEAD = 'O'
SNAKE_BODY = 'o'
FOOD = '*'
EMPTY = ' '
class SnakeGame:
def __init__(self):
self.board = [[EMPTY for _ in range(WIDTH)] for _ in range(HEIGHT)]
self.snake = [(WIDTH // 2, HEIGHT // 2)]
self.direction = 'right'
self.food = self.generate_food()
self.game_over = False
def generate_food(self):
while True:
x = random.randint(0, WIDTH - 1)
y = random.randint(0, HEIGHT - 1)
if self.board[y][x] == EMPTY:
return (x, y)
def print_board(self):
os.system('cls' if os.name == 'nt' else 'clear')
for row in self.board:
print(''.join(row))
def update_snake(self):
head_x, head_y = self.snake[0]
if self.direction == 'up':
head_y -= 1
elif self.direction == 'down':
head_y += 1
elif self.direction == 'left':
head_x -= 1
elif self.direction == 'right':
head_x += 1
# Check for game over conditions
if (
head_x < 0 or head_x >= WIDTH or
head_y < 0 or head_y >= HEIGHT or
self.board[head_y][head_x] == SNAKE_BODY
):
self.game_over = True
return
self.snake.insert(0, (head_x, head_y))
if (head_x, head_y) == self.food:
self.food = self.generate_food()
else:
self.snake.pop()
def draw_board(self):
for y in range(HEIGHT):
for x in range(WIDTH):
if (x, y) in self.snake:
self.board[y][x] = SNAKE_HEAD if (x, y) == self.snake[0] else SNAKE_BODY
elif (x, y) == self.food:
self.board[y][x] = FOOD
else:
self.board[y][x] = EMPTY
def bfs_autoplay(self):
queue = [(self.snake[0], [])] # (position, path)
visited = set([self.snake[0]])
while queue:
(x, y), path = queue.pop(0)
if (x, y) == self.food:
return path
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nx, ny = x + dx, y + dy
if (
0 <= nx < WIDTH and
0 <= ny < HEIGHT and
(nx, ny) not in visited and
self.board[ny][nx] != SNAKE_BODY
):
queue.append(((nx, ny), path + [(dx, dy)]))
visited.add((nx, ny))
return [] # No path found
def play(self):
while not self.game_over:
self.draw_board()
self.print_board()
path = self.bfs_autoplay()
if path:
dx, dy = path[0]
if dx == 1:
self.direction = 'right'
elif dx == -1:
self.direction = 'left'
elif dy == 1:
self.direction = 'down'
elif dy == -1:
self.direction = 'up'
self.update_snake()
time.sleep(0.2)
print("Game Over!")
if __name__ == "__main__":
game = SnakeGame()
game.play()
Explanation:
Initialization:
Sets up the game board, snake, initial direction, and generates the first food.
generate_food():
Randomly places food on an empty cell.
print_board():
Clears the terminal and prints the current state of the board.
update_snake():
Moves the snake based on the current direction.
Checks for collisions with walls or the snake's own body.
Grows the snake if it eats food.
draw_board():
Updates the board list with the snake's position, food, and empty cells.
bfs_autoplay():
Implements the Breadth-First Search (BFS) algorithm to find the shortest path to the food.
Returns a list of movement directions (dx, dy) to reach the food.
play():
Main game loop:
Draws the board.
Uses bfs_autoplay() to get the path to the food.
Updates the snake's direction based on the path.
Updates the snake's position.
Pauses for a short time to control the game speed.
Prints "Game Over!" when the game ends.
How to Run:
Save the code as a Python file (e.g., snake_bfs.py).
Open a terminal and navigate to the directory where you saved the file.
Run the command python snake_bfs.py.
The game will start in the terminal, and the snake will automatically move towards the food using the BFS algorithm.
“Create a terminal based snake game in python with autoplay with BFS algo.” Conversation with gemma-2-27b-it, from the LMArena Human Preference 100K dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m851rf84jvkc40r433w7s2z9