Skip to content

Instantly share code, notes, and snippets.

@mrpjevans
Created October 1, 2024 10:11
Show Gist options
  • Save mrpjevans/c2dad9e8041d5b308db4049ba9112326 to your computer and use it in GitHub Desktop.
Save mrpjevans/c2dad9e8041d5b308db4049ba9112326 to your computer and use it in GitHub Desktop.
Simple Snake game for Pimoroni's PicoSystem (MicroPython firmware)
import utime
import urandom
# Reset everything
pen();cursor();camera();clip();alpha()
# Reset so we have a 2-block snake and food
def game_reset():
global snake, move
snake = [[55,60], [60,60]]
move = [5, 0]
add_food()
# Add new food in a random place
def add_food():
global food_x, food_y
food_x = urandom.randint(0, 23) * 5
food_y = urandom.randint(0, 23) * 5
def update(tick):
global direction, move, snake
# Detect a change in direction
if pressed(UP): move = [0, -5]
elif pressed(RIGHT): move = [5, 0]
elif pressed(DOWN): move = [0, 5]
elif pressed(LEFT): move = [-5, -0]
head = snake[len(snake) - 1]
new_head = [head[0] + move[0], head[1] + move[1]]
# Remove the tail
snake.pop(0)
# Check whether the new 'head' will collide with the rest of the body
for segment in snake:
if new_head[0] is segment[0] and new_head[1] is segment[1]:
game_reset()
return
# Has the snake reached edge of the screen?
if new_head[0] is 0 or new_head[0] is 120 or new_head[1] is 0 or new_head[1] is 120:
game_reset()
# Has the snake eaten some food?
if new_head[0] is food_x and new_head[1] is food_y:
snake.append([head[0] + move[0], head[1] + move[1]])
add_food()
# Add the head
snake.append(new_head)
def draw(tick):
# Clear the screen
pen(0, 0, 0)
clear()
pen(15, 15, 15)
flip()
# Draw each segment of the snake
for segment in snake:
frect(segment[0], segment[1], 5, 5)
# Draw the food
pen(0, 15, 0)
frect(food_x, food_y, 5, 5)
# Controls the speed of the game
utime.sleep(0.2)
# Start the game
game_reset()
start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment