JavaScript Tutorial
  • 🍼Introduction
  • 🥛Hello Gamers
  • 🍯Variables
    • Action Game Example
  • 🌰Strings
    • RPG Example
  • 🍪Character Acces
    • Simulation Example
  • 🍩Plus (+) operator
    • Strategy Game Example
  • 🥜Functions
    • Adventure Game Example
  • 🍿Template strings
    • Strategy Game Example
  • 🍫Numbers
    • Sports Game Example
  • 🍬Converting Numbers to Strings
    • Fighting Game Example
  • 🍭Operations
    • FPS Game Example
  • 🍮Conditions
    • Platformer Game Example
  • 🎂Arrays
    • Puzzle Game Example
  • 🍰Objects
    • Racing Game Example
  • 🧁Arrow Functions
    • Rhythm Game Example
  • 🔌Shameless Plug
  • 🥧Implicit Return
    • Platform Game Example
  • 🍦String Methods
    • GRID Game Example
  • 🍨Object Literals
    • Board Game Example
  • 🍧DynamicProperty
    • Political Game Example
  • 🍡Reading Dynamic Property
    • Hide & Seek Game
  • 🥮Objects Continued
    • Medieval Game Example
  • 🥠Object Shorthands
    • Trivia Game example
  • 🔌Shameless Plug (again)
  • 🍥Destructuring & Concatenation
    • Dig a hole game example
  • 🍏Optional Chaining
    • Action Game Example
  • 🍐Nullish coalescing operator
    • Adventure Game Example
  • 🍊Refactoring If Conditions
    • Arcade Game Example
  • 🍋Implicit Conversion & Falcy Values
    • Strategy Game Example
  • 🍌Arrays of objects
    • Sports Game Example
  • 🍉Transforming Array of Objects
    • Fighters Game Example
  • 🍇Some important array methods
    • FPS Example
  • 🫐Reducing arrays of objects
    • Third Person Shooter Example
  • 🍓Try....catch
    • Platformer Example
  • 🍈Immutability
    • Puzzle game example
  • 🍒Creating new arrays or objects
    • Racing Game Example
  • 🔌Shameless Plug (again)
  • 🍑Immutable object operations
    • Basics
    • Rhythm Game Example
  • 🥭Classes
    • Basics
    • Platformer Game Example
  • 🍍Instance Method
    • Basics
    • Role-playing game example
  • 🥥Object Oriented Programming
    • Basics
    • Stealth Game Example
  • 🥝Getters & Setters
    • Basics
    • Survival Game Example
  • 🍅Static Methods & Chaining
    • Basics
    • Tactical Role Playing Game
  • 🍆Class Inheritance
    • Tower Defense Game Example
  • 🥑Use of Super
    • Vehicular Combat Game example
  • 🫒Public Class Field
    • MMORPG Example
  • 🥦Private class fields
    • Battle Royale Games Example
  • 🥬Aysnc/Await
    • Collectible Card Game example
    • Video Board game example
  • 🫑SetTimeout
    • Dice game example
  • 🥒Execution Order
    • Digital Collectible Card Game example
  • 🌶️The callback pattern
    • Life Simulation Game example
  • 🌽Promises
    • Music Game Example
  • 🥕Writing a function that returns a promise
    • Party game example
  • 🧄Introduction to JSON
    • Tile based game example
  • 🧅JSON.parse(string) / JSON.stringify(object)
    • Rhythm action game example
  • 🍠JSON Example for a game
    • Fetching JSON game data
  • 🥐Handling fetch errors
    • Fetch and HTTP Requests
  • 🥯ES Modules
    • Tower Defence Game Example
  • 🍞Default Export
    • Strategy Adventure Game Example
  • 🥖Fetch Wrapper
    • Strategy Role-playing game example
  • 🔌Final Shameless Plug
  • 🫓Lexical Scope and Arrow Functions
    • Vehicular Combat Game Example
  • 🥨Passing Functions
    • Vehicular simulation game example
  • 🥚Dynamic Imports
    • Video card game example
  • 🍠What is a closure
    • Video casino game example
  • 🎆Congratulations
Powered by GitBook
On this page
  1. Immutability

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.

PreviousImmutabilityNextCreating new arrays or objects

Last updated 2 years ago

🍈