Skip to content

Commit 28cd7fa

Browse files
committed
Add movement to snake
1 parent 55fd348 commit 28cd7fa

2 files changed

Lines changed: 78 additions & 0 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import time
2+
from turtle import Turtle, Screen
3+
from snake import Snake
4+
5+
screen = Screen()
6+
screen.setup(width=600, height=600)
7+
screen.bgcolor('black')
8+
screen.title("My Snake Game")
9+
screen.tracer(0)
10+
11+
snake = Snake()
12+
13+
screen.listen()
14+
screen.onkey(snake.up, "Up")
15+
screen.onkey(snake.down, "Down")
16+
screen.onkey(snake.left, "Left")
17+
screen.onkey(snake.right, "Right")
18+
19+
game_is_on = True
20+
while game_is_on:
21+
screen.update()
22+
time.sleep(0.1)
23+
24+
# snake._random_direction_change(p=0.5)
25+
snake.move()
26+
27+
screen.exitonclick()
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
from turtle import Turtle
2+
import numpy as np
3+
MOVE_DISTANCE = 20
4+
STARTING_POSITION = [(0,0), (-20,0), (-40,0)]
5+
6+
class Snake():
7+
"Class that represents the snake in the Snake Game."
8+
def __init__(self, shape="square", color="white"):
9+
self.shape = shape
10+
self.color = color
11+
12+
self.segments = None
13+
self.initialize_segments()
14+
15+
def initialize_segments(self):
16+
"""Initialize the three first segments of the snake at a fixed position."""
17+
snake_segment = []
18+
19+
for start_pos in STARTING_POSITION:
20+
new_segment = Turtle()
21+
new_segment.penup()
22+
new_segment.shape(self.shape)
23+
new_segment.color(self.color)
24+
new_segment.goto(start_pos)
25+
snake_segment.append(new_segment)
26+
27+
self.segments = snake_segment
28+
29+
def move(self):
30+
"""Move the snake in the direction is already heading"""
31+
for idx in reversed(range(1, len(self.segments))):
32+
newx, newy = self.segments[idx-1].pos()
33+
self.segments[idx].goto(newx, newy)
34+
self.segments[0].forward(MOVE_DISTANCE)
35+
36+
def _random_direction_change(self, p):
37+
"""Randomly changes the direction the snake is heading to"""
38+
if np.random.rand() < p:
39+
self.segments[0].setheading(np.random.choice([0,90,180,270]))
40+
41+
def up(self):
42+
self.segments[0].setheading(90)
43+
44+
def down(self):
45+
self.segments[0].setheading(270)
46+
47+
def right(self):
48+
self.segments[0].setheading(0)
49+
50+
def left(self):
51+
self.segments[0].setheading(180)

0 commit comments

Comments
 (0)