Advertisement
Guest User

python snake game

a guest
Feb 4th, 2021
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. # import
  2. import turtle
  3. import time
  4. import random
  5.  
  6. # turtle head
  7. delay = 0.1
  8.  
  9. wn = turtle.Screen()
  10. wn.title("Snake Game")
  11. wn.bgcolor("green")
  12. wn.setup(width=600, height=600)
  13. wn.tracer(0)
  14.  
  15. head = turtle.Turtle()
  16. head.speed(0)
  17. head.shape("square")
  18. head.color("black")
  19. head.penup()
  20. head.goto(0,0)
  21. head.direction = "stop"
  22.  
  23. # snake food
  24. food = turtle.Turtle()
  25. food.speed(0)
  26. food.shape("circle")
  27. food.color("red")
  28. food.penup()
  29. food.goto(0,100)
  30.  
  31. segments = ()
  32.  
  33. # functions
  34. def go_up():
  35.     head.direction = "up"
  36.  
  37. def go_down():
  38.     head.direction = "down"
  39.  
  40. def go_left():
  41.     head.direction = "left"
  42.  
  43. def go_right():
  44.     head.direction = "right"
  45.  
  46. def move():
  47.     if head.direction == "up":
  48.         y = head.ycor()
  49.         head.sety(y + 20)
  50.  
  51.     if head.direction == "down":
  52.         y = head.ycor()
  53.         head.sety(y - 20)
  54.  
  55.     if head.direction == "left":
  56.         x = head.xcor()
  57.         head.setx(x - 20)
  58.  
  59.     if head.direction == "right":
  60.         x = head.xcor()
  61.         head.setx(x + 20)
  62.  
  63. # keyboard bindings
  64. wn.listen()
  65. wn.onkeypress(go_up, "w")
  66. wn.onkeypress(go_down, "s")
  67. wn.onkeypress(go_left, "a")
  68. wn.onkeypress(go_right, "d")
  69.  
  70.  
  71. # main game loop
  72. while True:
  73.     wn.update()
  74.  
  75.     if head.distance(food) < 20:
  76.         x = random.randint(-290, 290)
  77.         y = random.randint(-290, 290)
  78.         food.goto(x,y)
  79.  
  80.         # add a segment
  81.         new_segment = turtle.Turtle()
  82.         new_segment.speed(0)
  83.         new_segment.shape = "square"
  84.         new_segment.color("grey")
  85.         new_segment.penup()
  86.         segments.append(new_segment)
  87.  
  88.     for index in range(len(segments)-1, 0, -1):
  89.         x = segments[index-1].xcor()
  90.         y = segments[index-1].ycor()
  91.         segments[index].goto(x, y)
  92.  
  93.     if len(segments) > 0:
  94.         x = head.xcor()
  95.         y = head.ycor()
  96.         segments[0].goto(x, y)
  97.  
  98.  
  99.     move()
  100.  
  101.     time.sleep(delay)
  102.  
  103. wn.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement