GRID Game Example

Let's say we are creating a grid-based game where the player navigates through a maze represented by a string of characters, where # represents a wall, . represents a path, and P represents the player's position.

let maze = "#.#.#.#.#P.#.#.#.#.#";

We can use the indexOf(searchValue) method to find the current position of the player in the maze and determine where the player can move next:

let currentPosition = maze.indexOf("P");
let leftPosition = currentPosition - 1;
let rightPosition = currentPosition + 1;
let leftTile = maze.charAt(leftPosition);
let rightTile = maze.charAt(rightPosition);

if (leftTile === "#") {
  console.log("Can't move left, there's a wall!");
} else {
  console.log("Player can move left");
}

if (rightTile === "#") {
  console.log("Can't move right, there's a wall!");
} else {
  console.log("Player can move right");
}

We can use the replace(searchValue, replaceValue) method to update the player's position in the maze when the player moves:

function move(direction) {
  let newPosition;
  if (direction === "left") {
    newPosition = leftPosition;
  } else if (direction === "right") {
    newPosition = rightPosition;
  }
  maze = maze.replace("P", ".");
  maze = maze.substring(0, newPosition) + "P" + maze.substring(newPosition + 1);
}

In this way, we use the string method to check the next position where the player can move and update the maze with the new position of the player, this can help to simplify the code and make it more readable, using the string methods we can handle the logic of the game in a simpler and more intuitive way.

Last updated