Hide & Seek Game

Here is an example of reading a dynamic property in the context of a hide and seek computer game in JavaScript:

function Player(name) {
  this.name = name;
  this.score = 0;
}

Player.prototype.found = function() {
  this.score++;
}

const player1 = new Player("Alice");
const player2 = new Player("Bob");

while (player1.score < 10 && player2.score < 10) {
  // simulate the game
  const winner = Math.random() < 0.5 ? player1 : player2;
  winner.found();
}

console.log(`${player1.name}'s score: ${player1.score}`);
console.log(`${player2.name}'s score: ${player2.score}`);

In this example, the Player constructor function is defined with a single argument, name. The found method is added to the prototype of the Player constructor, which increases the score property of the player object by 1.

Two player objects, player1 and player2, are created using the Player constructor. Each player has a name property and a score property, which is initially set to 0.

The game is simulated in a while loop, which continues until either player1 or player2 reaches a score of 10. At each iteration of the loop, a random player is chosen to be the winner using the ternary operator, and the found method is called on that player to increase their score.

After the loop finishes, the scores of both players are logged to the console. The score property is a dynamic property of the player objects, as it is not defined as a property of the Player constructor function, but is created and modified by the found method. This allows the game to track the score of each player, even though the players are different objects with different properties.

Last updated