A React Component that uses Web Workers to play a simple snake game.
import SnakeGame from '@ulises-codes/bite-me/snake';
import FoodURL from './assets/food.png';
import AudioURL from './assets/echo.mp3';
import DingURL from './assets/ding.mp3';
import GameOverURL from './assets/game-over.mp3';
export default function MyComponent() {
return (
<SnakeGame
style={{ backgroundColor: '#24748F' }}
food={{ src: ImageURL }}
audioSrc={AudioURL}
dingSrc={DingURL}
gameOverSrc={GameOverURL}
text={{
color: '#2a2a2a',
subtitleColor: '#fafafa',
titleColor: '#F1DD6D',
}}
snakeStyle={{
color: ['#BF43A1', '#F26463', '#F1DD6D', '#2BACB3'],
}}
workerPaths={{
snakeWorker: newURL(
'@ulises-codes/bite-me/dist/workers/snakeWorker',
import.meta.url
),
}}
/>
);
}
This project includes two Web Workers.
- snakeWorker.js (SnakeGame and OffscreenGame components) handles most of the computations behind the snake's position and the game's timer
- canvasWorker.js (OffscreenSnake component only) is handles the Offscreen Canvas for browsers that support it
If a browser supports OffscreenCanvas, you can import the OffscreenSnake component, which offloads the canvas rendering logic to a web worker for a slight increase in performance and most of all, reliability.
The OffscreenSnake component accepts the same props as the regular Snake component.
import SnakeGame from '@ulises-codes/bite-me/offscreen';
export default function MyComponent() {
return (
<OffscreenSnake
// Takes same props as SnakeGame, plus the
// public path to the web worker
workerPaths={{
snakeWorker: newURL(
'@ulises-codes/bite-me/dist/workers/snakeWorker',
import.meta.url
),
canvasWorker: new URL(
'@ulises-codes/bite-me/dist/workers/canvasWorker',
import.meta.url
),
}}
/>
);
}
Start game | SPACE or one finger tap |
Help page | h or two finger tap |
Quit | q |
p | Pause |
Mute | m |
Volume Up / Volume Down | 1 / 2 |
Move Snake | Arrow or Swipe |
Both Components Accept the Same Props | ||
---|---|---|
Prop Name | Type | Details |
style | { backgroundColor?: string } | Optional. Passed to Canvas Element. Currently only accepts a backgroundColor. ex: style = {{ backgroundColor: '#000000' }}
|
food | { src?: string } | Optional. The path to the image that will represent the 'food' that the snake eats. |
audioSrc | string? | Optional. The path to the track that while play while the game is active. |
dingSrc | string? | Optional. The path to a sound that will play when the snake eats some food. |
gameOverSrc | string? | Optional. The path to a sound that will play when the user loses a game. |
text | { color: string, subtitleColor?: string, titleColor?: string } | Colors that will be used for the title, instructions, and gameOver screens. |
snakeStyle | string | string[] | This is where it gets fun. The color of the snake itself. If passed an array, each block of the snake will correspond to each color in the array. |