Skip to content

Commit

Permalink
fix: implemented food
Browse files Browse the repository at this point in the history
  • Loading branch information
Shibi Suriya committed Sep 30, 2023
1 parent 23b02ae commit e9c5622
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 55 deletions.
46 changes: 40 additions & 6 deletions packages/game-client/src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import React, { useState, useEffect, useRef } from 'react';
import { generateKey, getOppositeDirection } from './utils';
import { DIRECTIONS, NUMBER_OF_COLUMNS, NUMBER_OF_ROWS, DEFAULT_DIRECTION } from './constants';
import { generateKey, getOppositeDirection, generateRandomNumber } from './utils';
import { DIRECTIONS, NUMBER_OF_COLUMNS, NUMBER_OF_ROWS } from './constants';
import { GRID_MAP } from './computed';
console.log(GRID_MAP);
import { useFood } from './hooks';
import Grid from './Grid';

const SPEED = 1 * 100;
Expand Down Expand Up @@ -37,6 +37,7 @@ function App() {
}, []);

const [snakeId, setSnakeId] = useState(1);
const { food, setFood, removeFood, isFood } = useFood();
// const playerId = useRef(2);

// Keep the direction of the snakes inside useRef since we don't
Expand All @@ -54,7 +55,7 @@ function App() {
const initialState = {
1: {
headColor: 'red',
bodyColor: 'black',
bodyColor: 'green',
hash: {
'0-0': { x: 0, y: 0 },
'0-1': { x: 0, y: 1 },
Expand Down Expand Up @@ -83,7 +84,7 @@ function App() {
},
3: {
headColor: 'yellow',
bodyColor: 'black',
bodyColor: 'red',
hash: {
'10-0': { x: 10, y: 0 },
'10-1': { x: 10, y: 1 },
Expand All @@ -97,6 +98,39 @@ function App() {
};
const [snakes, setSnakes] = useState(initialState);

const getSnakeCells = () => {
// return cells that are occupied by snakes.
return Object.values(snakes).reduce((hash, snake) => {
// TODO: check if the data is consistent here.
Object.assign(hash, snake.hash);
return hash;
}, {});
};

const spawnFood = () => {
const snakeCells = getSnakeCells();
const emptyCells = {};

for (const [key, value] of Object.entries(GRID_MAP)) {
if (!(key in snakeCells) && !(key in food)) {
Object.assign(emptyCells, { [key]: value });
}
}
const keys = Object.keys(emptyCells);
if (keys.length > 0) {
const randomEmptyCell = emptyCells[keys[generateRandomNumber(keys.length)]];
const { x, y } = randomEmptyCell;
setFood(x, y);
}
};

useEffect(() => {
const timer = setInterval(spawnFood, 1 * 50);
return () => {
clearInterval(timer);
};
}, [food]);

const getDirection = (snakeId) => {
return directions.current[snakeId];
};
Expand Down Expand Up @@ -249,7 +283,7 @@ function App() {
</option>
))}
</select>
<Grid snakes={snakes} />
<Grid snakes={snakes} food={food} />
</div>
);
}
Expand Down
62 changes: 20 additions & 42 deletions packages/game-client/src/Grid.jsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,8 @@
import React from 'react';
import styles from './grid.module.css';
import { CELL_DIMENSION, NUMBER_OF_COLUMNS, NUMBER_OF_ROWS, GRID_HEIGHT, GRID_WIDTH } from './constants';
import { generateKey } from './utils';
import { CELL_DIMENSION, GRID_HEIGHT, GRID_WIDTH } from './constants';

const grid = [];
for (let i = 0; i < NUMBER_OF_ROWS; i++) {
const row = [];
for (let j = 0; j < NUMBER_OF_COLUMNS; j++) {
row.push([i, j]);
}
grid.push(row);
}

function Cell({ x, y, body, head, color }) {
// const cellColor = () => {
// if (body) {
// return { backgroundColor: 'red' };
// } else if (head) {
// return { backgroundColor: 'black' };
// } else {
// return { backgroundColor: 'white' };
// }
// };
const cellColor = () => {
return { backgroundColor: color };
};
function Cell({ x, y, color }) {
return (
<div
className={styles.cell}
Expand All @@ -33,31 +11,31 @@ function Cell({ x, y, body, head, color }) {
left: `${y * CELL_DIMENSION}px`,
height: `${CELL_DIMENSION}px`,
width: `${CELL_DIMENSION}px`,
...cellColor(),
backgroundColor: color,
}}
></div>
);
}

function Grid({ snakes }) {
function isSnakeCell(key) {
for (const snake of Object.keys(snakes)) {
if (snakes[snake].hash[key]) {
return snakes[snake].headColor;
}
}
return 'white';
}

const makeCell = (cell) => {
const [x, y] = cell;
const key = generateKey(x, y);
return <Cell x={x} y={y} key={key} head={true} color={isSnakeCell(key)} />;
};

function Grid({ snakes, food }) {
return (
<div className={styles.grid} style={{ width: `${GRID_WIDTH}px`, height: `${GRID_HEIGHT}px` }}>
{grid.map((rows) => rows.map((col) => makeCell(col)))}
{Object.values(snakes).map((snake) => {
const { hash, headColor, bodyColor } = snake;
const [headKey] = snake.list;
return Object.entries(hash).map(([key, value]) => {
const { x, y } = value;
if (key == headKey) {
return <Cell x={x} y={y} key={key} color={headColor} />;
} else {
return <Cell x={x} y={y} key={key} color={bodyColor} />;
}
});
})}
{Object.entries(food).map(([key, value]) => {
const { x, y } = value;
return <Cell x={x} y={y} key={key} head={true} color={'purple'} />;
})}
</div>
);
}
Expand Down
4 changes: 0 additions & 4 deletions packages/game-client/src/grid.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@
border: 3px solid black;
}

:global(*) {
outline: 1px dashed red !important;
}

.cell {
position: absolute;
}
3 changes: 0 additions & 3 deletions packages/game-client/src/index.css
Original file line number Diff line number Diff line change
@@ -1,3 +0,0 @@
* {
outline: 1px dashed red !important;
}
6 changes: 6 additions & 0 deletions packages/game-client/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,9 @@ export const getOppositeDirection = (direction) => {
throw new Error(`Invalid direction, ${direction}.`);
}
};

export const generateRandomNumber = (max, min = 0) => {
const randomDecimal = Math.random();
const randomInRange = randomDecimal * (max - min) + min;
return Math.floor(randomInRange);
};

0 comments on commit e9c5622

Please sign in to comment.