Snake Game
Snake Game Using Python Turtle
from tkinter import StringVar, Tk, Label, Button, Radiobutton, messagebox
import random
import turtle
#Level
def ask_level():
global level, level_var
ask_level = Tk()
ask_level.eval('tk::PlaceWindow . center')
ask_level.geometry("150x120")
ask_level.resizable(0, 0)
ask_level.config(background="cyan")
l = Label(ask_level, text="Choose Level:")
l.pack()
l.config(background="cyan")
level_var = StringVar()
level= Radiobutton(ask_level, text="Easy", value= "easy", variable= level_var)
level.pack(anchor="w")
level.config(background="cyan")
level.select()
level = Radiobutton(ask_level, text="Medium", value= "medium", variable= level_var)
level.pack(anchor="w")
level.config(background="cyan")
level = Radiobutton(ask_level, text="Hard", value= "hard", variable= level_var)
level.pack(anchor="w")
level.config(background="cyan")
def get_val():
ask_level.destroy()
button = Button(ask_level, text= "Start Game", command= get_val)
button.pack()
ask_level.mainloop()
# Program constants
width = 500
height = 500
def delay_var():
global delay
ask_level()
if level_var.get() == "easy":
delay = 400 #milliseconds
elif level_var.get() == "medium":
delay = 250 #milliseconds
elif level_var.get() == "hard":
delay = 100 #milliseconds
delay_var()
food_size = 10 #pixels
score = 0
offsets = {
"up" : (0, 20),
"down" : (0, -20),
"left" : (-20, 0),
"right" : (20, 0)
}
#Create a window
screen = turtle.Screen()
screen.setup(width, height)
screen.cv._rootwindow.resizable(False, False)
screen.title("Snake Game")
screen.bgcolor("cyan")
screen.tracer(0) #Disables the automatic animation
#Create snake as a list of co-ordinate pairs.
snake = [[0, 0], [20, 0], [40, 0], [60, 0]]
snake_direction = "up"
#Turtle
cursor = turtle.Turtle()
cursor.shape("circle")
cursor.penup()
#Direction controls
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"
#Snake movement function
def game_loop():
cursor.clearstamps() #Remove existing stamps made by cursor
new_head = snake[-1].copy()
new_head[0] += offsets[snake_direction][0]
new_head[1] += offsets[snake_direction][1]
#check collisions
if new_head in snake or new_head[0] < - width/2 or new_head[0] > width/2\
or new_head[1] < - height/2 or new_head[1] > height/2:
ask_exit = Tk()
ask_exit.withdraw()
exit = messagebox.askyesno("", f"Your Score: {score}\n Oops!! Want to retry?")
if exit == 1:
reset()
else:
screen.bye()
else:
#Add new head to the snake body
snake.append(new_head)
#Check food collision
if not food_collision():
snake.pop(0) #Kepps the snake same length until fed
#Draw snake
for segment in snake:
cursor.goto(segment[0], segment[1])
cursor.stamp() #Makes a copy of the cursor
#Refresh Screen and update score
screen.title(f"Snake Game\tScore: {score}")
screen.update()
#Repeat interval
turtle.ontimer(game_loop, delay)
#Get random food position
def get_random_food_pos():
x = random.randint(-width/2+food_size, width/2-food_size)
y = random.randint(-height/2+food_size, height/2-food_size)
return (x, y)
#Get Distance
def get_distance(pos1, pos2):
x1, y1 = pos1
x2, y2 = pos2
a = ((x2 - x1) ** 2)
b = ((y2 - y1) ** 2)
distance = ((a + b) ** 0.5) #Pythagorean Theorem
return distance
#Reset Game
def reset():
global score, snake, snake_direction, food_pos, food
score = 0
snake = [[0, 0], [20, 0], [40, 0], [60, 0]]
snake_direction = "up"
food_pos = get_random_food_pos()
food.goto(food_pos)
game_loop()
# Food collision
def food_collision():
global food_pos, score
if get_distance(snake[-1], food_pos) < 20:
score += 1
food_pos = get_random_food_pos()
food.goto(food_pos)
return True
return False
#Event handler
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")
screen.onkey(go_right, "Right")
#Draw snake for the first time.
for segment in snake:
cursor.goto(segment[0], segment[1])
cursor.stamp() #Makes a copy of the cursor
#Food
def snake_food():
global food_pos, food
food = turtle.Turtle()
food.color("red")
food.shape("circle")
food.shapesize(food_size/20)
food.penup()
food_pos = get_random_food_pos()
food.goto(food_pos)
snake_food()
#Set animation in motion
game_loop()
#Finish
turtle.done()
Post a Comment