let gameBoard = document.getElementById("game-board");
let tiles = [];
let score = 0;
// Create the game board
for (let i = 0; i < 16; i++) {
let tile = document.createElement("div");
tile.className = "tile";
tile.dataset.id = i;
tile.dataset.type = getRandomType();
tile.innerHTML = tile.dataset.type;
gameBoard.appendChild(tile);
tiles.push(tile);
}
// Add event listeners to tiles
tiles.forEach((tile) => {
tile.addEventListener("click", (e) => {
let tileId = e.target.dataset.id;
let adjacentTiles = getAdjacentTiles(tileId);
adjacentTiles.forEach((adjacentTile) => {
if (canSwap(tileId, adjacentTile)) {
swapTiles(tileId, adjacentTile);
checkForMatches();
}
});
});
});
// Get a random type for a tile (e.g. "red", "blue", etc.)
function getRandomType() {
let types = ["red", "blue", "green", "yellow"];
return types[Math.floor(Math.random() * types.length)];
}
// Get the adjacent tiles to a given tile
function getAdjacentTiles(tileId) {
let adjacentTiles = [];
if (tileId % 4 !== 0) {
adjacentTiles.push(tiles[tileId - 1]);
}
if (tileId % 4 !== 3) {
adjacentTiles.push(tiles[tileId + 1]);
}
if (tileId >= 4) {
adjacentTiles.push(tiles[tileId - 4]);
}
if (tileId < 12) {
adjacentTiles.push(tiles[tileId + 4]);
}
return adjacentTiles;
}
// Check if two tiles can be swapped
function canSwap(tileId1, tileId2) {
let tile1 = tiles[tileId1];
let tile2 = tiles[tileId2];
return (
Math.abs(tileId1 - tileId2) === 1 ||
Math.abs(tileId1 - tileId2) === 4
);
}
// Swap two tiles
function swapTiles(tileId1, tileId2) {
let tile1 = tiles[tileId1];
let tile2 = tiles[tileId2];
let tempType = tile1.dataset.type;
tile1.dataset.type = tile2.dataset.type;
tile2.dataset.type = tempType;
tile1.innerHTML = tile1.dataset.type;
tile2.innerHTML = tile2.dataset.type;
}
// Check for matches (rows or columns of three or more identical tiles)
function checkForMatches() {
let matches = [];
for (let i = 0; i < 16; i++) {
let tile = tiles[i];
let type = tile.dataset.type;
let match = true;
for (let j = 0; j < 3; j++) {
let adjacentTile = tiles[i + j];
if (!adjacentTile || adjacentTile.dataset.type !== type) {
match = false;
break;
}
}
if (match) {
matches.push(i);
}
}
for (let i = 0; i < 4; i++) {
let tile = tiles[i];
let type = tile.dataset.type;
let match = true;
for (let j = 0; j < 3; j++) {
let adjacentTile = tiles[i + j * 4];
if (!adjacentTile || adjacentTile.dataset.type !== type) {
match = false;
break;
}
}
if (match) {
matches.push(i);
}
}
if (matches.length >
0 टिप्पणियाँ