import os
import time
from collections import deque
# Game constants
BOARD_SIZE = 10
SNAKE_START = (BOARD_SIZE // 2, BOARD_SIZE // 2)
# Directions
DIRECTIONS = [(0, 1), (1, 0), (0, -1), (-1, 0)] # Right, Down, Left, Up
class SnakeGame:
def __init__(self):
self.board = [[' ' for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
self.snake = deque([SNAKE_START])
self.food = self.spawn_food()
self.board[self.food[0]][self.food[1]] = 'F'
self.board[SNAKE_START[0]][SNAKE_START[1]] = 'S'
def spawn_food(self):
while True:
x, y = (BOARD_SIZE * random.random(), BOARD_SIZE * random.random())
x, y = int(x), int(y)
if self.board[x][y] == ' ':
return x, y
def is_valid_move(self, x, y):
return 0 <= x < BOARD_SIZE and 0 <= y < BOARD_SIZE and self.board[x][y] != 'S'
def find_path(self):
# BFS to find the shortest path to the food
q = deque([(self.snake[0], [])])
seen = set([self.snake[0]])
while q:
(x, y), path = q.popleft()
if (x, y) == self.food:
return path
for dx, dy in DIRECTIONS:
next_pos = (x + dx, y + dy)
if self.is_valid_move(*next_pos) and next_pos not in seen:
q.append((next_pos, path + [(dx, dy)]))
seen.add(next_pos)
return [] # No path found
def move_snake(self, dx, dy):
x, y = self.snake[0]
next_pos = (x + dx, y + dy)
if next_pos == self.food:
self.snake.appendleft(self.food)
self.food = self.spawn_food()
self.board[self.food[0]][self.food[1]] = 'F'
else:
self.board[self.snake[-1][0]][self.snake[-1][1]] = ' '
self.snake.pop()
self.snake.appendleft(next_pos)
self.board[next_pos[0]][next_pos[1]] = 'S'
def play(self):
while True:
os.system('clear' if os.name == 'posix' else 'cls')
self.print_board()
path = self.find_path()
if not path:
print("Game Over")
break
dx, dy = path[0]
self.move_snake(dx, dy)
time.sleep(0.5)
def print_board(self):
for row in self.board:
print(' '.join(row))
# Run the game
if __name__ == "__main__":
game = SnakeGame()
game.play()
This code defines a simple snake game where the snake automatically moves towards the food using a BFS algorithm to calculate the shortest path. The game runs in a loop, updating the snake's position based on the calculated path until no valid moves are left, indicating a game over.
Please note, this code assumes a very simple game state and does not handle all edge cases that a more complex snake game might, such as growing the snake efficiently after eating food or handling complex movement patterns. It's also quite basic in terms of user interaction, focusing instead on demonstrating the autoplay feature with BFS.
To run this code, you'll need to have Python installed on your system. Simply copy the code into a file named snake_game.py and run it from your terminal with python snake_game.py. Enjoy watching your snake automatically navigate to the food!