-
Notifications
You must be signed in to change notification settings - Fork 6
/
SnakeStateRevisited.elm
70 lines (55 loc) · 2.51 KB
/
SnakeStateRevisited.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
module SnakeStateRevisited where
import Foldpm
import Foldpm exposing (..)
import List exposing (head)
import Signal exposing ((<~), Signal)
import SnakeModel exposing (..)
import SnakeSignals exposing (..)
handleNewGame : Event -> SnakeState -> Maybe SnakeState
handleNewGame event _ = when (event == NewGame) initialState
handleGameOver : Event -> SnakeState -> Maybe SnakeState
handleGameOver _ state = when (state.gameOver) state
handleDirection : Event -> SnakeState -> Maybe SnakeState
handleDirection event state =
case event of
Direction newDelta ->
Just { state | delta <- if abs newDelta.dx /= abs state.delta.dx
then newDelta
else state.delta }
_ -> Nothing
handleTick : Event -> SnakeState -> Maybe SnakeState
handleTick event state =
case event of
Tick newFood ->
let state1 = if state.ticks % velocity == 0
then { state | gameOver <- collision state }
else state
in
if state1.gameOver
then Just 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
Just { state3 | ticks <- state3.ticks + 1 }
_ -> Nothing
step : Event -> SnakeState -> Maybe SnakeState
step = Foldpm.compose [handleNewGame, handleGameOver, handleDirection, handleTick]
stateSignal : Signal SnakeState
stateSignal = foldpm step initialState eventSignal