Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion src/freegames/snake.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,50 @@
food = vector(0, 0)
snake = [vector(10, 0)]
aim = vector(0, -10)
started = False


def change(x, y):
"""Change snake direction."""
if not started:
return

aim.x = x
aim.y = y


def start_game(x, y):
"""Start the game when the start button is clicked."""
global started

if started or not (-80 <= x <= 80 and -25 <= y <= 25):
return

started = True
onscreenclick(None)
clear()
move()


def draw_start_button():
"""Draw the start button."""
up()
goto(-80, -25)
color('black', 'light gray')
down()
begin_fill()
for _ in range(2):
forward(160)
left(90)
forward(50)
left(90)
end_fill()
up()
goto(0, -18)
color('black')
write('Start Game', align='center', font=('Arial', 16, 'bold'))


def inside(head):
"""Return True if head inside boundaries."""
return -200 < head.x < 190 and -200 < head.y < 190
Expand Down Expand Up @@ -66,5 +102,6 @@ def move():
onkey(lambda: change(-10, 0), 'Left')
onkey(lambda: change(0, 10), 'Up')
onkey(lambda: change(0, -10), 'Down')
move()
draw_start_button()
onscreenclick(start_game)
done()
17 changes: 17 additions & 0 deletions tests/test_snake.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
def test_snake():
random.seed(0)
mockturtle.events.clear()
mockturtle.state.clear()
mockturtle.events += [
('click', 0, 0),
('timer',),
('key Left',),
('timer',),
Expand All @@ -26,3 +28,18 @@ def test_snake():
]
mockturtle.events += [('timer', True)] * 300
runpy.run_module('freegames.snake')


def test_snake_waits_for_start_click():
mockturtle.state.clear()
mockturtle.events[:] = [('timer', True)]
runpy.run_module('freegames.snake')
assert 'timer' not in mockturtle.state

mockturtle.state.clear()
mockturtle.events[:] = [
('click', 0, 0),
('timer', True),
]
runpy.run_module('freegames.snake')
assert 'timer' in mockturtle.state