Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import turtle
- import time
- import random
- delay = 0.1
- #window
- print("hello")
- wn = turtle.Screen()
- wn.title("Snake Game")
- wn.bgcolor("green")
- wn.setup(width=600, height=600)
- wn.tracer(0)
- #snake
- head = turtle.Turtle()
- head.speed(0)
- head.shape("square")
- head.color("black")
- 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 = []
- #functions
- def go_up():
- head.direction = "up"
- def go_down():
- head.direction = "down"
- def go_right():
- head.direction = "right"
- def go_left():
- head.direction = "left"
- #keyboard bindings
- wn.listen()
- wn.onkeypress(go_up, "w")
- wn.onkeypress(go_down, "s")
- wn.onkeypress(go_left, "a")
- wn.onkeypress(go_right, "d")
- 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)
- #mainloop
- while True:
- wn.update()
- #check for collision with food
- if head.distance(food) < 20:
- #move food
- 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("black")
- new_segment.penup()
- segments.append(new_segment)
- #move last segments first
- for index in range(len (segments)-1, 0, -1):
- x = segments[index-1].xcor()
- y = segments[index-1].ycor()
- segments[index].goto(x, y)
- #Move 0 to where head is
- if len(segments) > 0:
- x = head.xcor()
- y = head.ycor()
- segments[0].goto(x, y)
- #check if snake is off border
- if head.xcor()>300 or head.xcor()<-300 or head.ycor()>300 or head.ycor()<-300:
- time.sleep(1)
- head.goto(0,0)
- head.direction = "stop"
- #Hide the segments
- for segments in segments:
- segments.goto(1000, 1000)
- #clear segments
- segments.clear()
- move()
- time.sleep(delay)
- wn.mainloop()
- turtle.done()
Advertisement
Add Comment
Please, Sign In to add comment