Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

module #2 (debakor) #30

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
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
147 changes: 125 additions & 22 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, useRef, useCallback } from "react";
import styles from "../styles/Snake.module.css";

const Config = {
Expand All @@ -12,6 +12,7 @@ const CellType = {
Snake: "snake",
Food: "food",
Empty: "empty",
Poison: "poison",
};

const Direction = {
Expand All @@ -38,6 +39,13 @@ const Cell = ({ x, y, type }) => {
width: 32,
height: 32,
};
case CellType.Poison:
return {
backgroundColor: "blue",
borderRadius: 20,
width: 32,
height: 32,
};

default:
return {};
Expand All @@ -61,6 +69,7 @@ const Cell = ({ x, y, type }) => {
const getRandomCell = () => ({
x: Math.floor(Math.random() * Config.width),
y: Math.floor(Math.random() * Config.width),
createdAt: Date.now(),
});

const Snake = () => {
Expand All @@ -69,56 +78,134 @@ const Snake = () => {
{ x: 7, y: 12 },
{ x: 6, y: 12 },
];
const grid = useRef();
// 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 [foods, setFoods] = useState([{ x: 4, y: 10 }]);
const [poisons, setPoisons] = useState([{ x: 4, y: 10 }]);
const [endGame, setEndGame] = useState(false);

const score = snake.length - 3;

// setInterval function
const useInterval = (callback, duration) => {
const time = useRef(0);
const wrappedCallback = useCallback(() => {
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 [food, setFood] = useState({ x: 4, y: 10 });
const [score, setScore] = useState(0);
// restart the game
const reStartGame = () => {
setSnake(getDefaultSnake());
setDirection(Direction.Right);
};

// 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 newHead = {
x: (head.x + direction.x + Config.width) % Config.width,
y: (head.y + direction.y + Config.height) % Config.height,
};

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

// remove tail
newSnake.pop();
if (!isFood(newHead)) {
newSnake.pop();
}
if (isPoison(newHead)) {
newSnake.pop();

setPoisons((currentPoison) =>
currentPoison.filter(
(poison) => !(poison.x === newHead.x && poison.y === newHead.y)
)
);
}

if (isSnake(newHead)) {
setEndGame(true);
} else {
setFoods((currentFoods) =>
currentFoods.filter(
(food) => !(food.x === newHead.x && food.y === newHead.y)
)
);
}
return newSnake;
});
};
const interval = setInterval(() => {
runSingleStep();
}, 200);
return () => {
clearInterval(interval);
};
}, [direction, foods]);

runSingleStep();
const timer = setInterval(runSingleStep, 500);
// food add function
const addNewFood = () => {
let newFood = getRandomCell();
while (isSnake(newFood) || isFood(newFood)) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

an object can be put to a cell only if it isn't occupied yet.
why not create a reusable function like
const isOccupied = (cell) => isSnake(cell) || isFood(cell) || isPoison(cell);

newFood = getRandomCell();
}
setFoods((currentFood) => [...currentFood, newFood]);
};

return () => clearInterval(timer);
}, [direction, food]);
// add poison function
const addPoison = () => {
let newPoison = getRandomCell();
while (isSnake(newPoison) || isFood(newPoison) || isPoison(newPoison)) {
newPoison = getRandomCell();
}
setPoisons((currentPoison) => [...currentPoison, newPoison]);
};

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

addFoods and addPoison, removeFood and removePoison works the same, you can merge them to have one addObject function, and one removeObject function.


// update score whenever head touches a food
useEffect(() => {
const head = snake[0];
if (isFood(head)) {
setScore((score) => {
return score + 1;
});

let newFood = getRandomCell();
while (isSnake(newFood)) {
newFood = getRandomCell();
}

setFood(newFood);
addNewFood();
}
}, [snake]);

// remove foods
const removeFoods = useCallback(() => {
setFoods((currentFoods) =>
currentFoods.filter((food) => Date.now() - food.createdAt <= 10 * 1000)
);
}, []);

// remove poison
const removePoison = useCallback(() => {
setPoisons((currentPoison) =>
currentPoison.filter(
(poison) => Date.now() - poison.createdAt <= 10 * 1000
)
);
}, []);

// Interval
useInterval(addNewFood, 3000);
useInterval(addPoison, 6000);
useInterval(removeFoods, 5000);
useInterval(removePoison, 8000);

useEffect(() => {
const handleNavigation = (event) => {
switch (event.key) {
Expand Down Expand Up @@ -146,7 +233,11 @@ const Snake = () => {

// ?. 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 isFood = ({ x, y }) =>
foods.some((food) => food?.x === x && food?.y === y);

const isPoison = ({ x, y }) =>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can also wrap these functions into a useCallback hook so that they don't get instantiated again

poisons.some((poison) => poison?.x === x && poison?.y === y);

const isSnake = ({ x, y }) =>
snake.find((position) => position.x === x && position.y === y);
Expand All @@ -159,6 +250,8 @@ const Snake = () => {
type = CellType.Food;
} else if (isSnake({ x, y })) {
type = CellType.Snake;
} else if (isPoison({ x, y })) {
type = CellType.Poison;
}
cells.push(<Cell key={`${x}-${y}`} x={x} y={y} type={type} />);
}
Expand All @@ -179,7 +272,17 @@ const Snake = () => {
width: Config.width * Config.cellSize,
}}
>
{cells}
{/* {cells} */}
<div style={{ textAlign: "center", fontSize: "30px" }}>
{endGame ? (
<>
<h5>Game Over</h5>
<h5>your score is: {score}</h5>
</>
) : (
cells
)}
</div>
</div>
</div>
);
Expand Down
Loading