Stealth Game Example

Here is an example of object-oriented programming in JavaScript for a hypothetical stealth computer game:

class GameObject {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  
  move(deltaX, deltaY) {
    this.x += deltaX;
    this.y += deltaY;
  }
}

class Player extends GameObject {
  constructor(x, y, name) {
    super(x, y);
    this.name = name;
    this.stealth = 100;
  }
  
  hide() {
    this.stealth = 100;
  }
  
  sneak(deltaX, deltaY) {
    this.stealth -= 10;
    super.move(deltaX, deltaY);
  }
}

class Guard extends GameObject {
  constructor(x, y) {
    super(x, y);
  }
  
  chase(player) {
    let deltaX = player.x - this.x;
    let deltaY = player.y - this.y;
    this.move(deltaX, deltaY);
  }
}

const player = new Player(10, 10, "Bob");
const guard = new Guard(50, 50);

player.sneak(1, -1);
console.log(player.stealth); // 90
guard.chase(player);
console.log(guard.x); // 11
console.log(guard.y); // 9

In this example, we have a base GameObject class that represents any object in the game that has a position (x, y). The Player class and the Guard class both extend the GameObject class, so they inherit its properties and methods. The Player class has additional properties and methods, such as name and stealth, and the Guard class has a chase method that moves the guard towards the player.

Last updated