Friday 16 October 2020

Phaser 3 Circular Dependency Issue

How to solve a circular dependency in Phaser 3

Background

I'm making a game with Phaser 3, TypeScript and Parcel. I have added some classes that implement some interfaces but the interfaces import and use each other. I started using eslint with airbnb ruleset. One of the rules they implement is import/no-cycle But I feel like my game needs it.

Example code

GameInterface.ts

import { Scene } from 'phaser';
import PlayerInterface from '../../entities/player/PlayerInterface'; // circular

interface GameInterface extends Scene {
  player: PlayerInterface;
}

export default GameInterface;

PlayerInterface.ts

import GameInterface from '../../scenes/game/GameInterface'; // circular

interface PlayerInterface extends Phaser.Physics.Arcade.Sprite {
  scene: GameInterface;
  speed: number;
}

export default PlayerInterface;

Question

A "Player" is added to the "Game" and the Player Class has a scene. So they both need to be in the interface. Since this is only a type file can I ignore this rule? Or is there a cleaver restructure I can do?

Edit 1

Additionally here is a link to the full repo.

Edit 2

Here are the 2 classes that implement these interfaces.

Game.ts

class Game extends Scene implements GameInterface {
  player: PlayerInterface;

  constructor() {
    super({
      key: 'Game',
    });
  }

  preload(): void {
    /* preload code */
  }

  create(): void {
   /* create code */ 
  }
}

Player.ts

class Player extends Phaser.Physics.Arcade.Sprite implements PlayerInterface {
  scene: GameInterface;

  constructor(scene: GameInterface) {
    super(scene, x, y, 'player');
    this.scene = scene;
    this.scene.add.existing(this);
    this.scene.physics.add.existing(this);
  }

  static preload(scene: GameInterface): void {
    /* preload */
  }
}

As you can see the game class creates the player, but the player is also passed a scene when created.



from Phaser 3 Circular Dependency Issue

No comments:

Post a Comment