🐛 Fixed random infinite game generation

This commit is contained in:
2024-02-18 18:43:15 +01:00
parent 272af85c74
commit dce5862d36
2 changed files with 9 additions and 11 deletions
+2 -2
View File
@@ -30,7 +30,7 @@ export const useActions = (grid: GridType, setGrid: React.Dispatch<React.SetStat
// Start the game with making sure the clicked cell will be empty after generation
if (gameState.status === 'idle') {
const { grid: newGrid, bombsCount: _bombsCount } = startGame(prev, gameState.difficulty as Difficulty, true, rowIndex, colIndex);
const { grid: newGrid, bombsCount: _bombsCount } = startGame(gameState.gridSize, gameState.difficulty as Difficulty, true, rowIndex, colIndex);
prev = newGrid;
bombsCount = _bombsCount;
@@ -83,7 +83,7 @@ export const useActions = (grid: GridType, setGrid: React.Dispatch<React.SetStat
// Start the game without making sure the clicked cell will be empty after generation
if (gameState.status === 'idle') {
const { grid: newGrid, bombsCount: _bombsCount } = startGame(prev, gameState.difficulty as Difficulty, false);
const { grid: newGrid, bombsCount: _bombsCount } = startGame(gameState.gridSize, gameState.difficulty as Difficulty, false);
prev = newGrid;
bombsCount = _bombsCount;
+7 -9
View File
@@ -7,7 +7,6 @@ export const genGrid = (size: number): GridType => {
let grid: GridType = Array.apply(null, Array(size)).map(() => {
return Array.apply(null, Array(size)).map(() => {
return {
// hidden: false,
hidden: true,
value: 'empty',
flag: false,
@@ -15,9 +14,6 @@ export const genGrid = (size: number): GridType => {
});
});
// grid = genBombs(grid, 'beginner');
// grid = genNumbers(grid);
return grid;
};
@@ -148,24 +144,26 @@ export const revealAllGrid = (grid: GridType, excludeGoodFlags: boolean = true)
});
};
export const startGame = (grid: GridType, difficulty: Difficulty, needEmpty: boolean = true, rowIndex?: number, colIndex?: number): { grid: GridType; bombsCount: number } => {
export const startGame = (size: number, difficulty: Difficulty, needEmpty: boolean = true, rowIndex?: number, colIndex?: number): { grid: GridType; bombsCount: number } => {
let grid = genGrid(size);
if (needEmpty) {
if (rowIndex === undefined || rowIndex < 0 || rowIndex >= grid.length) {
if (rowIndex === undefined || rowIndex < 0 || rowIndex >= size) {
throw Error('Missing rowIndex and/or colIndex parameters.');
} else if (colIndex === undefined || colIndex < 0 || colIndex >= grid[rowIndex].length) {
} else if (colIndex === undefined || colIndex < 0 || colIndex >= size) {
throw Error('Missing rowIndex and/or colIndex parameters.');
}
let bombsCount = 0;
do {
grid = genGrid(size);
const { grid: bombsGrid, bombsCount: bombsCountFromGen } = genBombs(grid, difficulty as Difficulty);
grid = bombsGrid;
grid = genNumbers(bombsGrid);
bombsCount = bombsCountFromGen;
} while (grid[rowIndex][colIndex].value !== 'empty');
grid = genNumbers(grid);
return { grid, bombsCount };
}