Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 136 additions & 53 deletions pages/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import dynamic from "next/dynamic";
import { useEffect, useState, useRef } from "react";
import { useEffect, useState, useCallback, useRef } from "react";
import styles from "../styles/Snake.module.css";

const Config = {
Expand All @@ -21,7 +21,7 @@ const Direction = {
Bottom: { x: 0, y: 1 },
};

const Cell = ({ x, y, type }) => {
const Cell = ({ x, y, type, remaining }) => {
const getStyles = () => {
switch (type) {
case CellType.Snake:
Expand All @@ -33,18 +33,21 @@ const Cell = ({ x, y, type }) => {

case CellType.Food:
return {
backgroundColor: "darkorange",
backgroundColor: "tomato",
borderRadius: 20,
width: 32,
height: 32,
transform: `scale(${0.5 + remaining / 20})`,
};

default:
return {};
}
};

return (
<div
key={`${x}-${y}`}
className={styles.cellContainer}
style={{
left: x * Config.cellSize,
Expand All @@ -53,89 +56,157 @@ const Cell = ({ x, y, type }) => {
height: Config.cellSize,
}}
>
<div className={styles.cell} style={getStyles()}></div>
<div className={styles.cell} style={getStyles()}>
{remaining}
</div>
</div>
);
};

const getRandomCell = () => ({
x: Math.floor(Math.random() * Config.width),
y: Math.floor(Math.random() * Config.width),
createdAt: Date.now(),
});

const Snake = () => {
const getInitialDirection = () => Direction.Right;

const useInterval = (callback, duration) => {
const time = useRef(0);

const wrappedCallback = useCallback(() => {
// don't call callback() more than once within `duration`
if (Date.now() - time.current >= duration) {
time.current = Date.now();
callback();
}
}, [callback, duration]);

useEffect(() => {
const interval = setInterval(wrappedCallback, 1000 / 60);
return () => clearInterval(interval);
}, [wrappedCallback, duration]);
};

const useSnake = () => {
const getDefaultSnake = () => [
{ x: 8, y: 12 },
{ x: 7, y: 12 },
{ x: 6, y: 12 },
];
const grid = useRef();

// snake[0] is head and snake[snake.length - 1] is tail
const [snake, setSnake] = useState(getDefaultSnake());
const [direction, setDirection] = useState(Direction.Right);
const [direction, setDirection] = useState(getInitialDirection());

const [food, setFood] = useState({ x: 4, y: 10 });
const [score, setScore] = useState(0);
const [foods, setFoods] = useState([]);

// move the snake
useEffect(() => {
const runSingleStep = () => {
setSnake((snake) => {
const head = snake[0];
const newHead = { x: head.x + direction.x, y: head.y + direction.y };
const score = snake.length - 3;

// make a new snake by extending head
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
const newSnake = [newHead, ...snake];
// useCallback() prevents instantiation of a function on each rerender
// based on the dependency array

// remove tail
newSnake.pop();
// resets the snake ,foods, direction to initial values
const resetGame = useCallback(() => {
setFoods([]);
setDirection(getInitialDirection());
}, []);

return newSnake;
});
};
const removeFoods = useCallback(() => {
// only keep those foods which were created within last 10s.
setFoods((currentFoods) =>
currentFoods.filter((food) => Date.now() - food.createdAt <= 10 * 1000)
);
}, []);

runSingleStep();
const timer = setInterval(runSingleStep, 500);
// ?. is called optional chaining
// see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
const isFood = useCallback(
({ x, y }) => foods.some((food) => food.x === x && food.y === y),
[foods]
);

return () => clearInterval(timer);
}, [direction, food]);
const isSnake = useCallback(
({ x, y }) =>
snake.find((position) => position.x === x && position.y === y),
[snake]
);

// update score whenever head touches a food
useEffect(() => {
const head = snake[0];
if (isFood(head)) {
setScore((score) => {
return score + 1;
});
const addFood = useCallback(() => {
let newFood = getRandomCell();
while (isSnake(newFood) || isFood(newFood)) {
newFood = getRandomCell();
}
setFoods((currentFoods) => [...currentFoods, newFood]);
}, [isFood, isSnake]);

// move the snake
const runSingleStep = useCallback(() => {
setSnake((snake) => {
const head = snake[0];

// 0 <= a % b < b
// so new x will always be inside the grid
const newHead = {
x: (head.x + direction.x + Config.height) % Config.height,
y: (head.y + direction.y + Config.width) % Config.width,
};

// make a new snake by extending head
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
const newSnake = [newHead, ...snake];

let newFood = getRandomCell();
while (isSnake(newFood)) {
newFood = getRandomCell();
// reset the game if the snake hit itself
if (isSnake(newHead)) {
resetGame();
return getDefaultSnake();
}

setFood(newFood);
}
}, [snake]);
// remove tail from the increased size snake
// only if the newHead isn't a food
if (!isFood(newHead)) {
newSnake.pop();
} else {
setFoods((currentFoods) =>
currentFoods.filter(
(food) => !(food.x === newHead.x && food.y === newHead.y)
)
);
}

return newSnake;
});
}, [direction, isFood, isSnake, resetGame]);

useInterval(runSingleStep, 200);
useInterval(addFood, 3000);
useInterval(removeFoods, 100);

useEffect(() => {
const handleDirection = (direction, oppositeDirection) => {
setDirection((currentDirection) => {
if (currentDirection === oppositeDirection) {
return currentDirection;
} else return direction;
});
};

const handleNavigation = (event) => {
switch (event.key) {
case "ArrowUp":
setDirection(Direction.Top);
handleDirection(Direction.Top, Direction.Bottom);
break;

case "ArrowDown":
setDirection(Direction.Bottom);
handleDirection(Direction.Bottom, Direction.Top);
break;

case "ArrowLeft":
setDirection(Direction.Left);
handleDirection(Direction.Left, Direction.Right);
break;

case "ArrowRight":
setDirection(Direction.Right);
handleDirection(Direction.Right, Direction.Left);
break;
}
};
Expand All @@ -144,26 +215,38 @@ const Snake = () => {
return () => window.removeEventListener("keydown", handleNavigation);
}, []);

// ?. is called optional chaining
// see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
const isFood = ({ x, y }) => food?.x === x && food?.y === y;

const isSnake = ({ x, y }) =>
snake.find((position) => position.x === x && position.y === y);

const cells = [];
for (let x = 0; x < Config.width; x++) {
for (let y = 0; y < Config.height; y++) {
let type = CellType.Empty;
let type = CellType.Empty,
remaining = undefined;
if (isFood({ x, y })) {
type = CellType.Food;
remaining =
10 -
Math.round(
(Date.now() -
foods.find((food) => food.x === x && food.y === y).createdAt) /
1000
);
} else if (isSnake({ x, y })) {
type = CellType.Snake;
}
cells.push(<Cell key={`${x}-${y}`} x={x} y={y} type={type} />);
cells.push(
<Cell key={`${x}-${y}`} x={x} y={y} type={type} remaining={remaining} />
);
}
}

return {
snake,
cells,
score,
};
};

const Snake = () => {
const { cells, score } = useSnake();
return (
<div className={styles.container}>
<div
Expand Down
4 changes: 4 additions & 0 deletions styles/Snake.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,8 @@
.cell {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
color: white;
}