Open kimpro82 opened 1 year ago
By ChatGPT
to insert an image into the puzzle, you can use the HTML tag to display the image and use CSS to position it correctly. Here's an updated example implementation that allows the user to select an image and then uses it as the background of the game board:
<!DOCTYPE html>
<html>
<head>
<title>Sliding Puzzle Game</title>
<style>
#game-board {
display: flex;
flex-wrap: wrap;
width: 300px;
height: 300px;
margin: 0 auto;
background-size: cover;
background-position: center;
}
.tile {
display: flex;
align-items: center;
justify-content: center;
font-size: 48px;
font-weight: bold;
width: 90px;
height: 90px;
border: 2px solid black;
box-sizing: border-box;
}
</style>
</head>
<body>
<input type="file" accept="image/*" onchange="loadImage(event)">
<div id="game-board"></div>
<script src="./game.ts"></script>
</body>
</html>
interface Tile {
value: number;
x: number;
y: number;
element: HTMLElement;
}
const BOARD_SIZE = 3;
const TILE_SIZE = 90;
let tiles: Tile[] = [];
let emptyTile: Tile;
function initGame(imageUrl: string): void {
const gameBoard = document.getElementById("game-board");
gameBoard?.style.setProperty("background-image", `url(${imageUrl})`);
for (let i = 0; i < BOARD_SIZE; i++) {
for (let j = 0; j < BOARD_SIZE; j++) {
const tileValue = i * BOARD_SIZE + j + 1;
const tile = createTile(tileValue, j, i);
tiles.push(tile);
gameBoard?.appendChild(tile.element);
}
}
emptyTile = tiles[BOARD_SIZE ** 2 - 1];
emptyTile.element.style.backgroundColor = "white";
emptyTile.element.innerText = "";
shuffleTiles();
}
function createTile(value: number, x: number, y: number): Tile {
const tile = document.createElement("div");
tile.classList.add("tile");
tile.innerText = value.toString();
tile.style.left = `${x * TILE_SIZE}px`;
tile.style.top = `${y * TILE_SIZE}px`;
tile.style.backgroundPosition = `-${x * TILE_SIZE}px -${y * TILE_SIZE}px`;
const tileObj: Tile = {
value,
x,
y,
element: tile,
};
tile.addEventListener("click", () => {
if (isAdjacent(tileObj, emptyTile)) {
moveTile(tileObj);
}
});
return tileObj;
}
function shuffleTiles(): void {
for (let i = 0; i < 100; i++) {
const adjacentTiles = getAdjacentTiles(emptyTile);
const randomIndex = Math.floor(Math.random() * adjacentTiles.length);
const randomTile = adjacentTiles[randomIndex];
moveTile(randomTile);
}
}
function isAdjacent(tile1: Tile, tile2: Tile): boolean {
const dx = Math.abs(tile1.x - tile2.x);
const dy = Math.abs(tile1.y - tile2.y);
return (dx === 1 && dy === 0) || (dx === 0 && dy === 1);
}
function getAdjacentTiles(tile: Tile): Tile[] {
The answer stopped here.
By ChatGPT
Here is an example implementation of the Sliding Puzzle game using HTML5 and TypeScript.