DEV Community

Cover image for Create a Snake clone with Hyperapp, part 1

Create a Snake clone with Hyperapp, part 1

Avalander on August 02, 2018

(Cover picture by Dominik Vanyi on Unsplash) Here is a demo of what we are going to build. In this tutorial I'm going to cover how to create a sn...
Collapse
 
biri profile image
Guillaume

Great work!
However, unless I am wrong, your updateSnake action is not pure (since it mutates the snake input and thus the state), which is not recommanded in hyperapp.
You can write a pure function like this.

const updateSnake = (snake, direction) => {
const head = {x: snake[0].x + SIZE * DIRECTIONS[direction].x,
y: snake[0].y + SIZE * DIRECTIONS[direction].y};
return [head].concat(snake).slice(0, -1);
}

Collapse
 
avalander profile image
Avalander • Edited

Thanks for the observation 😄

You are right that the function updateSnake is not pure because it mutates the snake, however, if you look at the action updateSnake, you'll see that it returns a shallow copy of the state, so hyperapp won't get confused (as far as I know, when you return the same state object the view is not updated, but there are no problems returning shallow copies).

const actions = {
    updateSnake: () => state => ({
        ...state,
        snake: updateSnake(state.snake, state.direction),
    }),
}

Maybe naming both the action and the function updateSnake was a poor choice, though.

I would definitely choose your update method over the naïve approach if I hadn't put it as an exercise for the reader at the end of the second part :)

Collapse
 
justaguyfrombr profile image
Misael Braga de Bitencourt

Man, thats great! I thinking about hyperapp with canvas...

Collapse
 
avalander profile image
Avalander

Yeah, I've been thinking about it for a while as well. I wonder how a declarative API for canvas would look like.

Collapse
 
okwolf profile image
Wolfgang

Great work! Just you wait until Hyperapp 2.0 brings FX and subscription support into core. I think you'll like it.

Collapse
 
avalander profile image
Avalander

Thanks! Yeah, I'm really looking forward to HAV2.