Play snake with this simple to use typed react component.
npm install react-game-snakePlay snake with this simple to use typed react component. Demo
npm install react-game-snake --save
`Usage
`
import * as React from "react";
import * as ReactDOM from "react-dom";import { Context, SnakeGame } from "react-game-snake";
ReactDOM.render(
colors={{
field: "#bdc3c7",
food: "#9b59b6",
snake: "#3498db",
}}
countOfHorizontalFields={20}
countOfVerticalFields={20}
fieldSize={20}
loopTime={200}
pauseAllowed={true}
restartAllowed={true}
onLoose={(context: Context) => alert(
You loosed with ${context.game.points} points.)}
onPause={(context: Context) => alert("paused")}
onRestart={(context: Context) => alert("restarted")}
onResume={(context: Context) => alert("onResume")}
onWin={(context: Context) => alert(You won with ${context.game.points} points.)}
/>,
document.getElementById("react"),
);
`$3
The context object gets passed to each event of the react component. This object allows you to manipulate the game entirely by just re-setting properties.Example: Getting player's points
`
context.game.points
`Example: Moving food to another position
`
context.food = { x: 1, y: 3 };
`Example: Pausing the game
`
context.updateGame({ pause: true });
`$3
Each event gets the context passed as the first parameter.| Name | Trigger |
|--------------|-------------------------------------------------------------------------|
| onLoose | The snake touches herself or one of the walls. |
| onWin | No space left to respawn new food. |
| onRestart | Player pressed R and restartAllowed = true. |
| onPause | Player pressed P, pauseAllowed = true and context.game.pause = false. |
| onResume | Player pressed P, pauseAllowed = true and context.game.pause = true. |
| onLoopStart | Before the game recalculated the context and drawn anything. |
| onLoopFinish | After the game recalculated the context and drawn everything. |
$3
| Name | Type | Description |
|------------------------- |------------------------------------------------------- |-------------------------------------------------------------------- |
| colors | `{ snake: string; food: string; field: string; }`` | Colors to draw the game in. |P will pause the game.
R will restart the game.