Recent Posts
Recent Comments
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Today
Total
관리 메뉴

DH의 개발 공부로그

[TypeScript] JavaScript 슈팅게임에 TypeScript 적용하기! #3 - start() & SpaceShip 본문

TypeScript

[TypeScript] JavaScript 슈팅게임에 TypeScript 적용하기! #3 - start() & SpaceShip

DeveloperDH 2023. 2. 23. 22:37
728x90

start() & SpaceShip

이번에 TypeScript로 변환할 부분은 Game안에 start 함수와 SpaceShip부분 입니다.
Game안의 start함수에 사용자가 조종을 할 spaceShip가 인스턴스 되기 때문에 start와 함께
spaceShip를 같이 묶어서 변환을 해보겠습니다.
우선 기존 JavaScript 코드 먼저 봐보겠습니다.

1. spaceShip

class SpaceShip {
  constructor(game, x, y) {
    this.game = game;
    this.lev = 1;
    this.x = x;
    this.y = y;
  }
  update() {
    if (score >= this.lev * 15) {
      this.lev += 1;
    }
  }
}

spaceShip의 자바스크립트 코드는 위와 같습니다.
이것을 다음과 같이 변환을 해주었습니다.

class SpaceShip {
  constructor(
    public game: Game;
    public x: number;
    public y: number;
    public lev: number;
  ) { }
  public update() {
    if (score >= this.lev * 15) {
      this.lev += 1;
    }
  }
}

2. start()

class Game {
  start() {
    this.changeScreen("game");

    this.spaceShip = new SpaceShip(
      this,
      this.canvas.width / 2 - 32,
      this.canvas.height - 84 // 우주선 크기 & 바닥 공간 20
    );

    this.loadImage();
    this.keyEvent();
    this.createMonster();
    this.main();
  }
}

기존 코드를 ts 파일로 옮기면 this.spaceShip부분이 오류가 뜹니다.
오류의 내용은 다음과 같습니다.

Property 'spaceShip' does not exist on type 'Game'

바로 spaceShipGame에 존재하지 않는다는 뜻입니다.
Game에서 spaceShip이 따로 선언을 하거나 타입을 지정을 해주지 않고 사용을 했기 때문에
오류가 생긴 것이기 때문에 spaceShip타입을 지정을 해주어야 합니다.

class Game {
  public canvas: HTMLCanvasElement;
  public ctx: CanvasRenderingContext2D;
  public spaceShip?: SpaceShip | null 

  constructor() {
    ...
  }

  public start() {
    this.changeScreen("game");

    this.spaceShip = new SpaceShip(
      this,
      this.canvas.width / 2 - 32,
      this.canvas.height - 84, // 우주선 크기 & 바닥 공간 20
      1 // lev
    );

    this.loadImage();
    this.keyEvent();
    this.createMeteor();
    this.main();
  }
}
728x90
Comments