coinsweeprs
Fri Oct 04 2024 04:07:37 GMT+0000 (Coordinated Universal Time)
Saved by @zahidhasan
class CoinsweepersGame { constructor(gridSize) { this.gridSize = gridSize; this.grid = this.initializeGrid(); this.hiddenMines = this.placeMines(); } // Initialize the game grid initializeGrid() { try { const grid = Array.from({ length: this.gridSize }, () => Array(this.gridSize).fill(false)); return grid; } catch (error) { console.error("Error initializing the grid:", error); throw new Error("Grid initialization failed."); } } // Place mines randomly on the grid placeMines() { const mineCount = Math.floor(this.gridSize * this.gridSize * 0.2); // 20% of the grid const mines = new Set(); while (mines.size < mineCount) { const x = Math.floor(Math.random() * this.gridSize); const y = Math.floor(Math.random() * this.gridSize); mines.add(`${x},${y}`); } return mines; } // Reveal a cell in the grid revealCell(x, y) { try { if (x < 0 || x >= this.gridSize || y < 0 || y >= this.gridSize) { throw new RangeError("Coordinates are out of bounds."); } if (this.hiddenMines.has(`${x},${y}`)) { console.log(`Mine revealed at (${x}, ${y})! Game Over.`); return true; // Game over } else { console.log(`Safe cell revealed at (${x}, ${y}).`); return false; // Continue playing } } catch (error) { if (error instanceof RangeError) { console.error("Invalid input:", error.message); } else { console.error("An unexpected error occurred:", error); } return null; // Indicate an error occurred } } } // Example usage const game = new CoinsweepersGame(5); // Create a 5x5 grid game.revealCell(2, 3); // Attempt to reveal a cell game.revealCell(5, 5); // Attempt to reveal an out-of-bounds cell
Comments