diff --git a/Day 20/README.md b/Day 20/README.md new file mode 100644 index 0000000..b15fd09 --- /dev/null +++ b/Day 20/README.md @@ -0,0 +1,8 @@ +# Day 20 - Build the Snake Game Part 1: Animation & Coordinates + +- Made a controllable snake, and will complete the full snake game on Day 21. +- Abstracted snake logic into a Snake class. + +## Snake + +![Day_20_Snake](https://user-images.githubusercontent.com/30333942/129074881-fff5a265-a4a7-445c-93bc-fc6553c50166.gif) diff --git a/Day 20/main.py b/Day 20/main.py new file mode 100644 index 0000000..1d4ff92 --- /dev/null +++ b/Day 20/main.py @@ -0,0 +1,26 @@ +from turtle import Screen +from snake import Snake +import time + +screen = Screen() +screen.setup(width=600, height=600) +screen.bgcolor("black") +screen.title("A Snake Game!") +screen.tracer(0) + +snake = Snake() + +screen.listen() +screen.onkey(snake.up, "Up") +screen.onkey(snake.down, "Down") +screen.onkey(snake.left, "Left") +screen.onkey(snake.right, "Right") + +game_is_on = True +while game_is_on: + screen.update() + time.sleep(0.1) + + snake.move() + +screen.exitonclick() \ No newline at end of file diff --git a/Day 20/snake.py b/Day 20/snake.py new file mode 100644 index 0000000..27326a7 --- /dev/null +++ b/Day 20/snake.py @@ -0,0 +1,45 @@ +from turtle import Turtle +STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)] +MOVE_DISTANCE = 20 +UP = 90 +DOWN = 270 +LEFT = 180 +RIGHT = 0 + +class Snake: + + def __init__(self): + self.segments = [] + self.create_snake() + self.head = self.segments[0] + + def create_snake(self): + for position in STARTING_POSITIONS: + segment = Turtle(shape="square") + segment.color("white") + segment.penup() + segment.goto(position) + self.segments.append(segment) + + def move(self): + for segment_index in range(len(self.segments) - 1, 0, -1): + new_x = self.segments[segment_index - 1].xcor() + new_y = self.segments[segment_index - 1].ycor() + self.segments[segment_index].goto(new_x, new_y) + self.head.forward(MOVE_DISTANCE) + + def up(self): + if self.head.heading() != DOWN: + self.head.setheading(90) + + def down(self): + if self.head.heading() != UP: + self.head.setheading(270) + + def left(self): + if self.head.heading() != RIGHT: + self.head.setheading(180) + + def right(self): + if self.head.heading() != LEFT: + self.head.setheading(0)