# Step 4¶

## Moving the fruit¶

When the snake eats a fruit we will need another unoccupied location for the new fruit.

Let's first compute the list of locations that are unoccupied.

 ``` 1 2 3 4 5 6 7 8 9 10 11 12``` ``````(defshards get-free-locations [snake fruit] [] >= .locations ;; (1) (ForRange ;; (2) :From 0 :To (- grid-cols 1) :Action ;; (3) (-> >= .a (ForRange :From 0 :To (- grid-rows 1) :Action (-> >= .b [.a .b] (ToInt2) >= .location (When (-> snake (IndexOf .location) (Is -1) (And) fruit (IsNot .location)) ;; (4) (5) (6) (-> .location (Push .locations))))))) ;; (7) .locations) ``````
1. `[]` is an empty sequence.
2. `(ForRange)` iterates a range of values (including both `:From` and `:To` ends).
3. `(- a b)` is a built-in function that can act on constant values (as opposed to `(Math.Subtract)` that can act on constants and variables).
4. `(When)` is similar to `(If)`, except it is "passthrough" by default (don't worry about that concept for now).
5. `(Is)` and `(IsNot)` compare two values.
6. `(And)` is a logic operator.
7. `(Push)` adds a value to a sequence.

The function takes the positions of the snake body (incl. head and tail) and the current fruit position. It then iterates through all possible coordinates skipping the ones that are either occupied by the snake or the current fruit. The sequence of potential locations is then returned as the function's output.

Now all we need to do is select a random position from this sequence and that will be our next fruit position.

 ```1 2 3 4 5``` ``````(defshards move-fruit [fruit snake] (get-free-locations fruit snake) >= .free-loc (Count .free-loc) >= .max ;; (1) (RandomInt .max) >= .next-fruit-loc ;; (2) .free-loc (Take .next-fruit-loc) (ToInt2)) ;; (3) (4) ``````
1. `(Count)` returns the number of elements in a sequence.
2. `(RandomInt)` returns a random value between 0 and the given maximum (exclusive).
3. We have already seen `(Take)` in step 2.
4. `(ToInt2)` ensures that we return an `int2` value.

## Moving the snake¶

In the snake game, the snake moves by one cell either horizontally or vertically. We could "move" every cell of its body one by one, but there is a clever trick we can use: we can just remove the first element (tail) from the snake's sequence and add one for the new head position.

When the snake is growing (after eating a fruit) we only add the new head (in place of the fruit element) but keep the tail such that snake seems to grow in the direction of the fruit it just ate.

 ```1 2 3``` ``````(defshards move-snake [snake offset grow] snake (RTake 0) (Math.Add offset) (Push snake) ;; (1) (WhenNot (-> grow) (DropFront snake))) ;; (2) (3) ``````
1. We have already seen `(RTake)` in step 3.
2. `(WhenNot)` is similar to `(When)` but with the opposite logic.
3. `(DropFront)` removes the first element of a sequence.

Now we need the snake to move at a regular interval in the direction chosen by the player.

Let's first listen to the player input. We will use the keyboard's arrow keys (up, down, left, right) for this.

 ```1 2 3 4``` ``````(Inputs.KeyDown "up" (-> "up" > .direction)) ;; (1) (Inputs.KeyDown "right" (-> "right" > .direction)) (Inputs.KeyDown "down" (-> "down" > .direction)) (Inputs.KeyDown "left" (-> "left" > .direction)) ``````
1. `(Inputs.KeyDown)` executes an action when a key is down. It has a sibling event: `(Inputs.KeyUp)`. `(>)` is an alias for `Push`.

We also want to prevent the player from accidentally selecting the opposite direction (e.g. down while the snake is going up) since that would immediately end the game (as the snake would immediately turn backwards to eat its own body starting with its neck). One easy way to do this is to compare the newly chosen direction with the previous one.

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16``` ``````(Inputs.KeyDown "up" (When (-> .prev-direction (IsNot "down")) (-> "up" > .direction))) (Inputs.KeyDown "right" (When (-> .prev-direction (IsNot "left")) (-> "right" > .direction))) (Inputs.KeyDown "down" (When (-> .prev-direction (IsNot "up")) (-> "down" > .direction))) (Inputs.KeyDown "left" (When (-> .prev-direction (IsNot "right")) (-> "left" > .direction))) ``````

Finally, the snake will move at a regular interval. We can do that by comparing the current time and the time since the last update.

 ```1 2 3 4 5 6 7``` `````` (When (-> (Time.Now) (Math.Subtract .last-tick) (IsMoreEqual 0.50)) ;; (1) (-> (Time.Now) > .last-tick ; move the snake .direction (Match ["up" (move-snake .snake (int2 0 -1) .grow) "right" (move-snake .snake (int2 1 0) .grow) "down" (move-snake .snake (int2 0 1) .grow) "left" (move-snake .snake (int2 -1 0) .grow)]))) ``````
1. `(Time.Now)` returns the time elapsed since the start of the game.

Now the snake will move every half a second. We could change this value to vary the difficulty of the game.

## Let's try it out!¶

Putting together all that we have seen so far, and adding a bit of initialization (that we conveniently put in its own function to allow us to reinitialize the game if the player hits the space bar), we have the following code.

 ``` 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 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162``` ``````(def grid-cols 12) (def grid-rows 10) (def empty-grid [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]) (defshards get-index [] (| (Take 0) >= .x) (| (Take 1) >= .y) .y (Math.Multiply grid-cols) (Math.Add .x)) (defshards get-free-locations [fruit snake] [] >= .locations (ForRange :From 0 :To (- grid-cols 1) :Action (-> >= .a (ForRange :From 0 :To (- grid-rows 1) :Action (-> >= .b [.a .b] (ToInt2) >= .location (When (-> snake (IndexOf .location) (Is -1) (And) fruit (IsNot .location)) (-> .location (Push .locations))))))) .locations) (defshards move-fruit [fruit snake] (get-free-locations fruit snake) >= .free-loc (Count .free-loc) >= .max (RandomInt .max) >= .next-fruit-loc .free-loc (Take .next-fruit-loc) (ToInt2)) (defshards move-snake [snake offset grow] snake (RTake 0) (Math.Add offset) (Push snake) (WhenNot (-> grow) (DropFront snake))) (defshards populate-grid [fruit snake] >= .tmp-grid ; first the snake tail and body snake (Take 0) (get-index) >= .tail-index [.tail-index 4] (Assoc .tmp-grid) snake (Slice 1 -1) (ForEach (-> (get-index) >= .limb-index [.limb-index 3] (Assoc .tmp-grid))) ; then the fruit fruit (get-index) >= .fruit-index [.fruit-index 1] (Assoc .tmp-grid) ; finally the snake head snake (RTake 0) (get-index) >= .head-index [.head-index 2] (Assoc .tmp-grid) ; return the populated grid .tmp-grid) (def cell-size 18) (def x-offset 48) (def y-offset 36) (defn render-cells [n] (if (= n -1) nil (-> (| (int2 (% n grid-cols) (/ n grid-cols)) (ToFloat2) (Math.Multiply (float2 cell-size)) (Math.Add (float2 x-offset y-offset)) > .position) (| (Take n) (UI.Area :Position .position :Contents (-> (Match [0 (-> ".") ; empty 1 (-> "F") ; fruit 2 (-> "H") ; head 3 (-> "B") ; body 4 (-> "T") ; tail ]false) (UI.Label)))) (render-cells (- n 1))))) (defshards initialize [] [(int2 1 2) (int2 2 2) (int2 3 2) (int2 3 3) (int2 4 3)] >= .snake false >= .grow (move-fruit (int2 0 0) .snake) >= .fruit "right" >= .direction >= .prev-direction (Time.Now) >= .last-tick ; do it once to not wait the next tick empty-grid (populate-grid .fruit .snake) >= .grid) (defloop main-wire (Once (initialize)) ; logic (When (-> (Time.Now) (Math.Subtract .last-tick) (IsMoreEqual 0.33)) (-> (Time.Now) > .last-tick ; move the snake .direction (Match ["up" (move-snake .snake (int2 0 -1) .grow) "right" (move-snake .snake (int2 1 0) .grow) "down" (move-snake .snake (int2 0 1) .grow) "left" (move-snake .snake (int2 -1 0) .grow)]) .snake (RTake 0) >= .head ; did the snake eat the fruit? (If (-> .head (Is .fruit)) (-> true > .grow (move-fruit .fruit .snake) > .fruit) (-> false > .grow) :Passthrough true) ; update empty-grid (populate-grid .fruit .snake) > .grid .direction > .prev-direction)) ; window (GFX.MainWindow :Title "Snake game" :Width 480 :Height 360 :Contents (-> (Setup (GFX.DrawQueue) >= .ui-draw-queue (GFX.UIPass .ui-draw-queue) >> .render-steps) .ui-draw-queue (GFX.ClearQueue) (UI .ui-draw-queue (-> .grid (Setup (float2 0) >= .position) (render-cells (- (* grid-cols grid-rows) 1)))) (GFX.Render :Steps .render-steps) (Inputs.KeyDown "up" (When (-> .prev-direction (IsNot "down")) (-> "up" > .direction))) (Inputs.KeyDown "right" (When (-> .prev-direction (IsNot "left")) (-> "right" > .direction))) (Inputs.KeyDown "down" (When (-> .prev-direction (IsNot "up")) (-> "down" > .direction))) (Inputs.KeyDown "left" (When (-> .prev-direction (IsNot "right")) (-> "left" > .direction))) (Inputs.KeyDown "space" (initialize))))) (defmesh root) (schedule root main-wire) (run root (/ 1.0 60)) ``````

Note

`(Once)` is executed only once and thus is not repeated every frame.