Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Error? why does it leave blocks behind after the first one
- # Simple Snake Game in Python 3 for beginners
- import turtle
- import time
- import random
- delay = 0.1
- # Set up the screen
- wn = turtle.Screen()
- wn.title("Snake game")
- wn.bgcolor("blue")
- wn.setup(width=600, height=600)
- wn.tracer(0)
- #Snake head
- head = turtle.Turtle()
- head.speed(0)
- head.shape("square")
- head.color("pink")
- head.penup()
- head.goto(0,0)
- head.direction = "stop"
- # Snake food
- food = turtle.Turtle()
- food.speed(0)
- food.shape("circle")
- food.color("green")
- food.penup()
- food.goto(0,100)
- segments = []
- #Functions
- def go_up():
- head.direction = "up"
- def go_down():
- head.direction = "down"
- def go_left():
- head.direction = "left"
- def go_right():
- head.direction = "right"
- #Functions
- 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 a collision with the food
- if head.distance(food)<20:
- # Move food to random spot
- 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("pink")
- new_segment.penup()
- segments.append(new_segment)
- #print(segments)
- #Move the end segments first in reverse order
- 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 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()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement