存储积分的最佳方式

时间:2017-01-29 19:14:52

标签: javascript arrays typescript point

我正在制作类似战舰的游戏。我需要在电路板上存储一个字段网格。每个字段值都是其当前状态 - 空/发货。 我声明了如下所示的二维数组:

//from createEmptyBoard() function in loop
playerBoard[x][y] = FIELD_EMPTY;

现在我想用类重写代码。 我定义了类 GameBoard Field

Class GameBoard (TypeScript):

class GameBoard {
  private verticalFields: number;
  private horizontalFields: number;
  private fields = Array<Field>();

  constructor(verticalFields: number, horizontalFields: number) {
    this.verticalFields = verticalFields;
    this.horizontalFields = horizontalFields;
  }

  private initializeEmptyFields() {
    for (let x = 0; x < this.verticalFields; x++) {
      for (let y = 0; y < this.horizontalFields; y++) {
        this.addField(x, y);
      }
    }
  }

  private addField(x, y) {
    this.fields.push(new Field(x, y));
  }
//...

字段(TypeScript):

class Field {
  private x: number;
  private y: number;
  private status: number;

  private static readonly FIELD_EMPTY = 0;
  private static readonly FIELD_SHIP = 1;
  private static readonly FIELD_MISS = 2;
  private static readonly FIELD_HIT = 3;


  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.status = Field.FIELD_EMPTY;
  }

  public setAsEmpty() {
    this.status = Field.FIELD_EMPTY;
  }

  public setAsShip() {
    this.status = Field.FIELD_SHIP;
  }

在另一种方法中,我检查用户点击的字段是空的还是有船。在旧代码中我以这种方式做到了:

function fieldIsEmpty(x,y) {
  return playerBoard[x][y] == FIELD_FIELD_EMPTY;
}

但现在我不知道如何通过坐标获得一个字段。寻找具有 x y 属性的对象,我在循环中寻找并不是最有效的方式。

如何存储有可能通过坐标获取字段的字段?

1 个答案:

答案 0 :(得分:0)

你可以在<div class="mainContent"> <div>Left</div> <div>Middle</div> <div>Right</div> </div>上编写这样的函数:

GameBoard