Puzzle Game Example

Let's say we are creating a sliding puzzle game where the player needs to rearrange the tiles to complete the puzzle. Each tile is represented by an image, and the images are stored in an array.

let puzzleTiles = [
  "tile1.jpg",
  "tile2.jpg",
  "tile3.jpg",
  "tile4.jpg",
  "tile5.jpg",
  "tile6.jpg",
  "tile7.jpg",
  "tile8.jpg",
  "tile9.jpg"
];

We can use the shuffle() function to randomly rearrange the elements of the array and create a new puzzle configuration.

function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
}
shuffle(puzzleTiles);

When the player moves a tile, we can use the splice() method to remove the tile from its current position and insert it into a new position.

function moveTile(currentIndex, newIndex) {
  let tile = puzzleTiles.splice(currentIndex, 1)[0];
  puzzleTiles.splice(newIndex, 0, tile);
}

We can also use the join() method to check if the puzzle is complete by comparing the current configuration of the puzzleTiles array to the winning configuration.

let winningConfiguration = [
  "tile1.jpg",
  "tile2.jpg",
  "tile3.jpg",
  "tile4.jpg",
  "tile5.jpg",
  "tile6.jpg",
  "tile7.jpg",
  "tile8.jpg",
  "tile9.jpg"
];

function checkWin() {
  let currentConfiguration = puzzleTiles.join();
  let winningConfiguration = winningConfiguration.join();
  if (currentConfiguration === winningConfiguration) {
    console.log("You win!");
  }
}

In this way, arrays can be used to store and manipulate the data of a puzzle game, such as the images of the tiles, the current configuration of the puzzle, and the winning configuration.

It's worth to mention that this is just one example and arrays can be used in many different ways depending on the complexity of the game and the requirements of the game logic.

Last updated