fp-games
fp-games copied to clipboard
Predictability of validMove function
Problems:
-
When moving right, and press down and left rapidly (within the same draw), the left will be rejected because it fails the check against the first item in the movement array. Expected behavior should be that rapid key press will perform both moves.
-
Valid move does not check if the move is the same as the current direction, so rapid presses of key fills up the array with junk. Expected behavior is that pressing the key in the direction of travel is completely ignored.
Proposed valid move function: const validMove = move => state =>{ let indexLast = state.moves.length - 1 let OppositeDirection = state.moves[indexLast].x == -move.x || state.moves[indexLast].y == -move.y let SameDirection = state.moves[indexLast].x == move.x && state.moves[indexLast].y == move.y return (!SameDirection && !OppositeDirection) }
The above should be placed into snake.js replacing the existing const validMove. It will make the game feel much more responsive.
PS indexLast can be turned into a method and placed in base.js for modularity
Aha! Excellent catch! Great explanation and great suggestion! If you would like to create a pull request that would be prime! :) Otherwise just let me know and I'll do it.
I would suggest also breaking out oppositeDirection
and sameDirection
into their own functions, which would render sameDirection
the same function as pointEq
, which would suggest that oppositeDirection
could be named pointOp
(as in "opposite") so that:
const pointEq = p1 => p2 => p1.x == p2.x && p1.y == p2.y
const pointOp = p1 => p2 => p1.x == -p2.x && p1.y == -p2.y
And if we extract lastMove
like this:
const lastMove = state => state.moves[state.moves.length - 1]
We can transform the validMove
function you suggested into this:
const validMove = move => state =>
!pointEq(move)(lastMove(state)) && !pointOp(move)(lastMove(state))