-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontrols.py
78 lines (63 loc) · 2.33 KB
/
controls.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import pygame
from snake import Move
from vector import Vector2D
def check_for_user_interaction(world):
direction_keys = {
pygame.K_UP,
pygame.K_DOWN,
pygame.K_RIGHT,
pygame.K_LEFT,
}
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if world.paused or event.key == pygame.K_p:
pause(world)
if len(world.pushedKeys) < 3 and event.key in direction_keys and not world.paused:
world.pushedKeys.append(event.key)
if event.type == pygame.QUIT:
import sys
sys.exit()
def check_for_direction_change(pushedKeys, snakeElements):
switcher = {
pygame.K_UP: go_up,
pygame.K_DOWN: go_down,
pygame.K_RIGHT: go_right,
pygame.K_LEFT: go_left,
}
if pushedKeys:
event_key = pushedKeys.pop(0)
switcher.get(event_key)(snakeElements)
def go_up(snakeElements):
element_iterator = iter(snakeElements)
head = next(element_iterator)
if head.velocity.y == 0:
change_position_cords = head.position
head.velocity.set_values(0, -1)
for element in element_iterator:
element.moves_to_make.append(Move(change_position_cords, Vector2D(0, -1)))
def go_down(snakeElements):
element_iterator = iter(snakeElements)
head = next(element_iterator)
if head.velocity.y == 0:
change_position_cords = head.position
head.velocity.set_values(0, 1)
for element in element_iterator:
element.moves_to_make.append(Move(change_position_cords, Vector2D(0, 1)))
def go_right(snakeElements):
element_iterator = iter(snakeElements)
head = next(element_iterator)
if head.velocity.x == 0:
change_position_cords = head.position
head.velocity.set_values(1, 0)
for element in element_iterator:
element.moves_to_make.append(Move(change_position_cords, Vector2D(1, 0)))
def go_left(snakeElements):
element_iterator = iter(snakeElements)
head = next(element_iterator)
if head.velocity.x == 0:
change_position_cords = head.position
head.velocity.set_values(-1, 0)
for element in element_iterator:
element.moves_to_make.append(Move(change_position_cords, Vector2D(-1, 0)))
def pause(world):
world.paused = not world.paused