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 gridy
: the y coordinate of the tile on the gridvalue
: 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:
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