Snake Game Made by Python
Snake Game Made by Python
Snake Game Made by Python
import random
WIDTH = 500
HEIGHT = 500
FOOD_SIZE = 10
DELAY = 100
offsets = {
"right": (20, 0)
def reset():
snake = [[0, 0], [0, 20], [0, 40], [0, 50], [0, 60]]
snake_direction = "up"
food_pos = get_random_food_pos()
food.goto(food_pos)
# screen.update() Only needed if we are fussed about drawing food before next call to `draw_snake()`.
move_snake()
def move_snake():
global snake_direction
new_head = snake[-1].copy()
# Check self-collision
if new_head in snake[:-1]:
reset()
else:
snake.append(new_head)
if not food_collision():
snake[-1][0] -= WIDTH
snake[-1][0] += WIDTH
snake[-1][1] -= HEIGHT
snake[-1][1] += HEIGHT
pen.clearstamps()
# Draw snake
pen.goto(segment[0], segment[1])
pen.stamp()
# Refresh screen
screen.update()
turtle.ontimer(move_snake, DELAY)
def food_collision():
global food_pos
food_pos = get_random_food_pos()
food.goto(food_pos)
return True
return False
def get_random_food_pos():
return (x, y)
def get_distance(pos1, pos2):
x1, y1 = pos1
x2, y2 = pos2
return distance
def go_up():
global snake_direction
if snake_direction != "down":
snake_direction = "up"
def go_right():
global snake_direction
if snake_direction != "left":
snake_direction = "right"
def go_down():
global snake_direction
if snake_direction != "up":
snake_direction = "down"
def go_left():
global snake_direction
if snake_direction != "right":
snake_direction = "left"
# Screen
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT)
screen.title("Snake Game")
screen.bgcolor("black")
screen.setup(500, 500)
screen.tracer(0)
# Pen
pen = turtle.Turtle("square")
pen.penup()
pen.pencolor("yellow")
# Food
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.penup()
# Event handlers
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")
# Let's go
reset()
turtle.done()