Puzzle game example

Imagine you are building a puzzle computer game where the player can move tiles on a grid to solve a puzzle. The grid is represented as a 2D array of tiles, where each tile is an object with the following properties:

  • x: the x coordinate of the tile on the grid

  • y: the y coordinate of the tile on the grid

  • value: the value of the tile (e.g. a number or a symbol)

You can use immutability to ensure that the grid is not modified directly, and to create a new grid each time the player moves a tile. Here is an example of how you could do this:

const initialGrid = [
  [{ x: 0, y: 0, value: 1 }, { x: 1, y: 0, value: 2 }, { x: 2, y: 0, value: 3 }],
  [{ x: 0, y: 1, value: 4 }, { x: 1, y: 1, value: 5 }, { x: 2, y: 1, value: 6 }],
  [{ x: 0, y: 2, value: 7 }, { x: 1, y: 2, value: 8 }, { x: 2, y: 2, value: 9 }]
];

function moveTile(grid, fromX, fromY, toX, toY) {
  const newGrid = grid.map(row => [...row]); // Create a new grid by spreading each row of the old grid
  const fromTile = newGrid[fromY][fromX];
  const toTile = newGrid[toY][toX];
  newGrid[fromY][fromX] = toTile;
  newGrid[toY][toX] = fromTile;
  return newGrid;
}

let currentGrid = initialGrid;

// Move tile at (0, 0) to (1, 0)
currentGrid = moveTile(currentGrid, 0, 0, 1, 0);

console.log(initialGrid[0][0]); // { x: 0, y: 0, value: 1 }
console.log(currentGrid[0][0]); // { x: 1, y: 0, value: 2 }

In this example, the moveTile() function takes the current grid, the x and y coordinates of the tile to move, and the x and y coordinates of the destination. It creates a new grid by spreading each row of the old grid, and then swaps the tiles at the specified coordinates. The currentGrid variable is updated to the new grid, and the old grid is not modified.

Using immutability in this way allows you to keep track of the player's progress and revert to previous states if necessary, without having to worry about modifying the original grid. It also makes it easier to debug any issues that may arise, because the grid's state is not changed unexpectedly.

Last updated