Guest User

Untitled

a guest
Mar 30th, 2020
414
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. import turtle
  2. import random
  3.  
  4. WIDTH = 500
  5. HEIGHT = 500
  6. SNAKE_CELL_SIZE = 20
  7. FOOD_SIZE = 10
  8. SQUARE_SIZE = 20 # Default size of turtle "square" shape
  9. DELAY = 200 # milliseconds
  10.  
  11. def move_snake():
  12. for index in range(len(segments) - 1, 0, -1):
  13. x = segments[index - 1].xcor()
  14. y = segments[index - 1].ycor()
  15. segments[index].goto(x, y)
  16.  
  17. # Move segment 0 to where the head is
  18. if len(segments) > 0:
  19. x = head.xcor()
  20. y = head.ycor()
  21. segments[0].goto(x, y)
  22.  
  23. if head.direction == "up":
  24. head.sety(head.ycor() + SNAKE_CELL_SIZE)
  25. elif head.direction == "right":
  26. head.setx(head.xcor() + SNAKE_CELL_SIZE)
  27. elif head.direction == "down":
  28. head.sety(head.ycor() - SNAKE_CELL_SIZE)
  29. elif head.direction == "left":
  30. head.setx(head.xcor() - SNAKE_CELL_SIZE)
  31.  
  32. def check_food_collision():
  33. if head.distance(food) < SNAKE_CELL_SIZE:
  34. x = random.randint(- WIDTH / 2 + FOOD_SIZE, WIDTH / 2 - FOOD_SIZE)
  35. y = random.randint(- HEIGHT / 2 + FOOD_SIZE, HEIGHT / 2 - FOOD_SIZE)
  36. food.goto(x, y)
  37.  
  38. # Add new segment
  39. new_segment = turtle.Turtle()
  40. new_segment.shape("square")
  41. new_segment.color("cyan")
  42. new_segment.penup()
  43. segments.append(new_segment)
  44.  
  45.  
  46. def go_up():
  47. if head.direction != "down":
  48. head.direction = "up"
  49.  
  50. def go_right():
  51. if head.direction != "left":
  52. head.direction = "right"
  53.  
  54. def go_down():
  55. if head.direction != "up":
  56. head.direction = "down"
  57.  
  58. def go_left():
  59. if head.direction != "right":
  60. head.direction = "left"
  61.  
  62. def play():
  63. move_snake()
  64. check_food_collision()
  65. screen.update()
  66. turtle.ontimer(play, DELAY)
  67.  
  68.  
  69. # Set up screen
  70. screen = turtle.Screen()
  71. screen.title("Snake Game")
  72. screen.bgcolor("pink")
  73. screen.setup(500, 500)
  74. screen.tracer(0)
  75.  
  76.  
  77. # Event handlers
  78. screen.listen()
  79. screen.onkey(go_up, "Up")
  80. screen.onkey(go_right, "Right")
  81. screen.onkey(go_down, "Down")
  82. screen.onkey(go_left, "Left")
  83.  
  84.  
  85. # Snake head
  86. head = turtle.Turtle()
  87. head.speed(0)
  88. head.shape("square")
  89. head.color("black")
  90. head.penup()
  91. head.goto(100, 100)
  92.  
  93.  
  94. # Food
  95. food = turtle.Turtle()
  96. food.shape("circle")
  97. food.color("red")
  98. food.shapesize(FOOD_SIZE / SQUARE_SIZE)
  99. food.penup()
  100.  
  101. # Let's go!
  102. segments = []
  103. head.direction = "up"
  104. play()
  105. turtle.done()
Advertisement
Add Comment
Please, Sign In to add comment