-
Notifications
You must be signed in to change notification settings - Fork 6
/
SnakeState.elm
49 lines (43 loc) · 2.03 KB
/
SnakeState.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
module SnakeState where
import List exposing (head)
import Signal exposing (Signal, foldp)
import SnakeModel exposing (..)
import SnakeSignals exposing (..)
stateSignal : Signal SnakeState
stateSignal = foldp step initialState eventSignal
step : Event -> SnakeState -> SnakeState
step event state =
case (event,state.gameOver) of
(NewGame,_) -> initialState
(_,True) -> state
(Direction newDelta,_) ->
{ state | delta <- if abs newDelta.dx /= abs state.delta.dx
then newDelta
else state.delta }
(Tick newFood, _) ->
let state1 = if state.ticks % velocity == 0
then { state | gameOver <- collision state }
else state
in if state1.gameOver
then state1
else let state2 = { state1
| snake <-
if state1.ticks % velocity == 0
then moveSnakeForward state1.snake state1.delta state1.food
else state1.snake
}
state3 = { state2
| food <-
case state2.food of
Just f ->
if state2.ticks % velocity == 0 &&
head state2.snake.front == Just f
then Nothing
else state2.food
Nothing ->
if isInSnake state2.snake newFood
then Nothing
else Just newFood
}
in { state3 | ticks <- state3.ticks + 1 }
(Ignore,_) -> state