Skip to content

Game

The Game class contains the core logic for running a game, including the game loop, updating the state of the game, and rendering the game onto an HTML5 canvas. It leverages a StateMachine to manage different game states and ensures consistent performance across different frame rates.

Constructor

new Game(stateMachine, context, width, height);

Creates a new Game instance.

  • Parameters:

    • stateMachine (StateMachine): An instance of the StateMachine class that manages the various states of the game.
    • context (CanvasRenderingContext2D): The canvas rendering context where the game will be drawn.
    • width (number): The width of the canvas in pixels.
    • height (number): The height of the canvas in pixels.
  • Returns: A new Game instance.

  • Example:

    const game = new Game(stateMachine, context, 800, 600);

Properties

  • stateMachine (StateMachine): The state machine that handles transitions and updates between different game states.
  • context (CanvasRenderingContext2D): The canvas rendering context used to draw the game.
  • width (number): The width of the canvas.
  • height (number): The height of the canvas.
  • lastTime (number): The timestamp of the last frame, used for calculating delta time.

Methods

start()

Starts the game by initiating the game loop.

  • Parameters: None

  • Returns: void

  • Example:

    game.start();

gameLoop([currentTime])

The main loop of the game. It is called 60 times per second (or based on the monitor’s refresh rate) using requestAnimationFrame(). This method updates the game and renders the current frame.

  • Parameters:

    • currentTime (number, optional): The current timestamp, in milliseconds, since the page loaded. Defaults to 0.
  • Returns: void

  • Example:

    game.gameLoop();

update(dt)

Updates the current state of the game. This method is called at each frame and handles the logic of the game based on the time elapsed since the last frame (delta time).

  • Parameters:

    • dt (number): The time delta between the current frame and the previous frame, in seconds.
  • Returns: void

  • Example:

    game.update(deltaTime);

render()

Renders the current state of the game onto the canvas. This method is called after update() in each frame to draw the updated state of the game.

  • Parameters: None

  • Returns: void

  • Example:

    game.render();