AI Chat
AI Image Generator
AI Video
Text to Speech
Login
AI Chat
AI Chat is an AI chatbot that writes text. You can use it to write stories,
messages, or programming code. You can use the AI chatbot as a virtual tutor in
almost any subject.
Chat History
can you write me a snake game in python code for raspberry pi.
Delete
Here's a simple implementation of the classic snake game using Python on Raspberry
Pi. This game uses the RPi.GPIO library to control the direction of the snake on
the console.
Please note that this code assumes you have a Raspberry Pi with a compatible
display (e.g., HDMI) connected to it. The game will run on the console, not on a
graphical interface.
Install necessary libraries:
Before running the code, you'll need to install the RPi.GPIO library. You can do
this by running the following command:
CopyReplit
sudo pip install RPi.GPIO
Code:
CopyReplit
import RPi.GPIO as GPIO
import time
import curses
# Set up GPIO pins
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Left arrow
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Right arrow
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Up arrow
GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Down arrow
# Initialize game variables
snake = [(0, 0)] # Initial snake position
direction = (1, 0) # Initial snake direction
food = (10, 10) # Initial food position
score = 0
# Function to clear the screen
def clear_screen():
curses.erase()
# Function to draw the snake on the screen
def draw_snake():
curses.move(0, 0)
curses.addstr("Score: " + str(score))
for i, (x, y) in enumerate(snake):
curses.move(y, x)
if i == 0:
curses.addstr("*")
else:
curses.addstr("#")
# Function to draw the food on the screen
def draw_food():
curses.move(food[1], food[0])
curses.addstr("O")
# Main game loop
while True:
try:
# Get user input
if GPIO.input(17):
direction = (-1, 0)
elif GPIO.input(23):
direction = (1, 0)
elif GPIO.input(24):
direction = (0, -1)
elif GPIO.input(25):
direction = (0, 1)
# Move the snake
new_head = (snake[0][0] + direction[0], snake[0][1] + direction[1])
snake.insert(0, new_head)
# Check for collisions with the wall or itself
if (new_head[0] < 0 or new_head[0] >= curses.getmaxyx()[1] or
new_head[1] < 0 or new_head[1] >= curses.getmaxyx()[0] or
new_head in snake[1:]):
break
# Check for food collision
if new_head == food:
score += 1
food = (random.randint(0, curses.getmaxyx()[1] - 1), random.randint(0,
curses.getmaxyx()[0] - 1))
else:
snake.pop()
# Clear and redraw the screen
clear_screen()
draw_snake()
draw_food()
time.sleep(0.1)
except KeyboardInterrupt:
break
# Clean up GPIO pins
GPIO.cleanup()