code a snake game using python
- User
code a snake game using python
- Assistant
Creating the full snake game is quite long, but I'll provide you with a basic structure and a few essential components of the game to get you started. You can customize and add more features to polish the game later. For this implementation, we'll use the
turtlemodule. You may need to install it usingpip install PythonTurtleif not already installed.import turtle import time import random # Set up the screen wn = turtle.Screen() wn.title("Snake Game") wn.bgcolor("black") wn.setup(width=600, height=600) wn.tracer(0) # Snake head head = turtle.Turtle() head.shape("square") head.color("white") head.penup() head.goto(0, 0) head.direction = "Stop" # Snake food food = turtle.Turtle() food.speed(0) food.shape("circle") food.color("red") food.penup() food.goto(0, 100) segments = [] delay = 0.1 # Set the directions def go_up(): if head.direction != "down": head.direction = "up" def go_down(): if head.direction != "up": head.direction = "down" def go_left(): if head.direction != "right": head.direction = "left" def go_right(): if head.direction != "left": head.direction = "right" def move(): if head.direction == "up": y = head.ycor() head.sety(y + 20) if head.direction == "down": y = head.ycor() head.sety(y - 20) if head.direction == "left": x = head.xcor() head.setx(x - 20) if head.direction == "right": x = head.xcor() head.setx(x + 20) # Keyboard bindings wn.listen() wn.onkeypress(go_up, "w") wn.onkeypress(go_down, "s") wn.onkeypress(go_left, "a") wn.onkeypress(go_right, "d") # Main game loop while True: wn.update() # Check for collision with food if head.distance(food) < 20: x = random.randint(-290, 290) y = random.randint(-290, 290) food.goto(x, y) # Add a segment new_segment = turtle.Turtle() new_segment.speed(0) new_segment.shape("square") new_segment.color("grey") new_segment.penup() segments.append(new_segment) # Move the end segments first in reverse order for i in range(len(segments) - 1, 0, -1): x = segments[i - 1].xcor() y = segments[i - 1].ycor() segments[i].goto(x, y) # Move segment 0 to where the head is if len(segments) > 0: x = head.xcor() y = head.ycor() segments[0].goto(x, y) move() time.sleep(delay) wn.mainloop()This code sets up a basic snake game with a black background, a white snake that moves with "w", "a", "s", "d" keys, and red food appearing randomly on the screen for the snake to eat. When the snake eats food, it grows in length. You can extend this code to include a border, collision detection with the border and the snake body, and a scoring system.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.