Snake Game in Python
Below is a basic implementation of the classic Snake game in Python, using the random and time modules for game logic and the os module for clearing the terminal screen.
import random
import time
import os
class SnakeGame:
def __init__(self, width=20, height=20):
self.width = width
self.height = height
self.snake = [(0, 0)]
self.direction = 'right'
self.apple = self.generate_apple()
def generate_apple(self):
while True:
x = random.randint(0, self.width - 1)
y = random.randint(0, self.height - 1)
if (x, y) not in self.snake:
return (x, y)
def clear_screen(self):
os.system('cls' if os.name == 'nt' else 'clear')
def draw_game(self):
self.clear_screen()
for y in range(self.height):
for x in range(self.width):
if (x, y) in self.snake:
print('S', end=' ')
elif (x, y) == self.apple:
print('A', end=' ')
else:
print('.', end=' ')
print()
def update_game(self):
head = self.snake[-1]
if self.direction == 'right':
new_head = (head[0] + 1, head[1])
elif self.direction == 'left':
new_head = (head[0] - 1, head[1])
elif self.direction == 'up':
new_head = (head[0], head[1] - 1)
elif self.direction == 'down':
new_head = (head[0], head[1] + 1)
if (new_head[0] < 0 or new_head[0] >= self.width or
new_head[1] < 0 or new_head[1] >= self.height or
new_head in self.snake[:-1]):
return False
self.snake.append(new_head)
if new_head == self.apple:
self.apple = self.generate_apple()
else:
self.snake.pop(0)
return True
def play(self):
while True:
self.draw_game()
command = input("Enter direction (W/A/S/D): ")
if command.lower() == 'w' and self.direction != 'down':
self.direction = 'up'
elif command.lower() == 's' and self.direction != 'up':
self.direction = 'down'
elif command.lower() == 'a' and self.direction != 'right':
self.direction = 'left'
elif command.lower() == 'd' and self.direction != 'left':
self.direction = 'right'
if not self.update_game():
self.draw_game()
print("Game Over!")
break
time.sleep(0.5)
if __name__ == "__main__":
game = SnakeGame()
game.play()
How to Run:
- Save the above code in a file named
snake_game.py.
- Open a terminal or command prompt in Windows.
- Navigate to the directory where you saved the file using the
cd command.
- Run the game by typing
python snake_game.py and pressing Enter.
- Use the W/A/S/D keys to control the snake's direction.
Note: This game will run in the terminal, and the screen will be cleared and updated after each move. The game will end if the snake collides with the boundary or itself.