-
Notifications
You must be signed in to change notification settings - Fork 0
/
Snake.elm
138 lines (98 loc) · 2.68 KB
/
Snake.elm
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
module Snake exposing (Snake, Model, Msg, view, update, init, step, subscriptions)
import Collage exposing (collage, Form, group)
import Color exposing (Color)
import Block exposing (Location, BlockSize, draw)
import Keyboard exposing (KeyCode, ups)
import Dict exposing (Dict)
type alias Model =
{ snake : Snake
, direction : Direction
}
init : Model
init =
{ snake = [ ( 1, 1 ), ( 1, 2 ), ( 1, 3 ) ]
, direction = Up
}
subscriptions : Sub Msg
subscriptions =
Sub.batch [ Keyboard.ups KeyDown ]
type alias Scale =
Location
type alias Snake =
List Scale
type Direction
= Up
| Down
| Right
| Left
| Nowhere
type Msg
= KeyDown Int
update : Msg -> Model -> ( Model, Cmd a )
update msg model =
case msg of
KeyDown keyCode ->
handleDirection model keyCode ! []
handleDirection : Model -> KeyCode -> Model
handleDirection model keyCode =
let
candidate =
toDirection keyCode
in
if opposite model.direction candidate then
model
else
{ model | direction = candidate }
toDirection : KeyCode -> Direction
toDirection keyCode =
case Dict.get keyCode keyCodeToDirection of
Nothing ->
Nowhere
Just direction ->
direction
keyCodeToDirection : Dict KeyCode Direction
keyCodeToDirection =
Dict.fromList
[ ( 37, Left ), ( 38, Up ), ( 39, Right ), ( 40, Down ) ]
opposite : Direction -> Direction -> Bool
opposite a b =
List.member [ a, b ] oppositors
oppositors : List (List Direction)
oppositors =
[ [ Left, Right ], [ Right, Left ], [ Up, Down ], [ Down, Up ] ]
step : Model -> Model
step model =
let
removeLast snake =
List.take (List.length snake - 1) snake
addFirst snake =
case List.head snake of
Just scale ->
(move scale) :: snake
Nothing ->
snake
move =
case model.direction of
Up ->
\( x, y ) -> ( x, y + 1 )
Down ->
\( x, y ) -> ( x, y - 1 )
Left ->
\( x, y ) -> ( x - 1, y )
Right ->
\( x, y ) -> ( x + 1, y )
Nowhere ->
identity
newSnake =
model.snake
|> removeLast
|> addFirst
in
{ model | snake = newSnake }
view : BlockSize -> Model -> Form
view size { snake } =
let
block scale =
Block.draw size { location = scale, color = Color.green }
in
List.map block snake |> group