In this blog post, we’ll discuss a simplified Python code for the famous Snake game. The game’s objective is to guide a snake around a grid while consuming food to grow its length, avoiding collisions with itself or the board edges. Let’s dive into the code and understand its key components.
Game Setup
To start, we’ll define the game’s basic setup. This includes the dimensions of the game board, the initial position and direction of the snake, and the placement of the food.
pythonWIDTH, HEIGHT = 20, 20
SNAKE_START = [(5, 5), (4, 5), (3, 5)]
DIRECTION = "RIGHT"
FOOD = None
def generate_food():
# Generate a random position for the food, ensuring it's not on the snake
x = random.randint(0, WIDTH - 1)
y = random.randint(0, HEIGHT - 1)
while (x, y) in SNAKE_START:
x = random.randint(0, WIDTH - 1)
y = random.randint(0, HEIGHT - 1)
return (x, y)
FOOD = generate_food()
Game Loop
The game loop continuously updates the game state based on user input and moves the snake.
pythonimport random
import os
import time
while True:
# Handle user input
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and DIRECTION != "DOWN":
DIRECTION = "UP"
if event.key == pygame.K_DOWN and DIRECTION != "UP":
DIRECTION = "DOWN"
if event.key == pygame.K_LEFT and DIRECTION != "RIGHT":
DIRECTION = "LEFT"
if event.key == pygame.K_RIGHT and DIRECTION != "LEFT":
DIRECTION = "RIGHT"
# Move the snake
head = SNAKE_START[0]
if DIRECTION == "UP":
head = (head[0], head[1] - 1)
elif DIRECTION == "DOWN":
head = (head[0], head[1] + 1)
elif DIRECTION == "LEFT":
head = (head[0] - 1, head[1])
elif DIRECTION == "RIGHT":
head = (head[0] + 1, head[1])
# Check for collisions
if head[0] < 0 or head[0] >= WIDTH or head[1] < 0 or head[1] >= HEIGHT or head in SNAKE_START[1:]:
print("Game Over!")
break
# Check if snake ate the food
if head == FOOD:
SNAKE_START.append(head)
FOOD = generate_food()
else:
SNAKE_START = [head] + SNAKE_START[:-1]
# Render the game (simplified for this example)
os.system('cls' if os.name == 'nt' else 'clear')
for y in range(HEIGHT):
for x in range(WIDTH):
if (x, y) in SNAKE_START:
print("O", end="")
elif (x, y) == FOOD:
print("F", end="")
else:
print(".", end="")
print()
# Wait for a short time before updating the game state
time.sleep(0.1)
Note: The above code snippet uses a simplified rendering mechanism using os.system
and print
statements. In a real-world scenario, you’d likely use a graphics library like Pygame to create a more polished game interface.
Conclusion
This simplified Python code for the Snake game provides a good starting point for understanding the game’s core mechanics. You can build upon this foundation to add more features, improve the game’s visuals, or experiment with different variations of the game.