A controllable snake!

A controllable snake!

Added snake in README!
This commit is contained in:
rzmk 2021-08-11 13:10:12 -04:00
parent 8f4c47043d
commit 735ff97d0d
3 changed files with 79 additions and 0 deletions

8
Day 20/README.md Normal file
View file

@ -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)

26
Day 20/main.py Normal file
View file

@ -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()

45
Day 20/snake.py Normal file
View file

@ -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)