Created
April 14, 2020 18:25
-
-
Save Raagh/2f8c18b1659f3627204a573f9af279ea to your computer and use it in GitHub Desktop.
Functional Snake Game - Part 2 - Input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// index.js | |
const setupInput = () => { | |
readline.emitKeypressEvents(process.stdin) | |
process.stdin.setRawMode(true) | |
process.stdin.on("keypress", (str, key) => { | |
if (key.ctrl && key.name === "c") process.exit() | |
const options = { | |
UP: addMove(direction.NORTH), | |
LEFT: addMove(direction.WEST), | |
DOWN: addMove(direction.SOUTH), | |
RIGHT: addMove(direction.EAST), | |
} | |
const move = options[key.name.toUpperCase()] | |
uglyMutableState = move(uglyMutableState) | |
}) | |
} | |
// snake.js | |
const direction = { | |
NORTH: point(0, -1), | |
SOUTH: point(0, 1), | |
WEST: point(-1, 0), | |
EAST: point(1, 0), | |
} | |
const initialState = { | |
snake: [point(4, 3)], | |
apple: point(5, 5), | |
move: direction.EAST, | |
} | |
const addMove = r.curry((direction, state) => | |
isValidMove(direction, state.move) ? { ...state, move: direction } : state | |
) | |
// Comprueba que la serpiente siempre se mueve hacia adelante y | |
// no pueda cambiar a la dirección opuesta | |
const isValidMove = (direction, move) => | |
direction.x + move.x !== 0 && direction.y + move.y !== 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment