2017-01-29 11 views
1

私は戦艦に似たゲームを作成しています。私はボードにフィールドのグリッドを格納する必要があります。各フィールドの値は現在の状態(空/船)です。 は、私は、以下に示すような2次元配列を宣言:ポイントを保存する最も良い方法

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

今、私はクラスを使用してコードを書き直したいと思います。 私はクラスはGameBoardフィールドを定義

クラスはGameBoard(活字体):

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)); 
    } 
//... 

クラスフィールド(活字体):

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; 
    } 

別の方法ではIユーザーがクリックしたフィールドが空であるか、船があるかどうかを確認します。古いコードでは、私はこのようにしました:

しかし、今私はどのように座標でフィールドを取得するか分かりません。 xyのループを探しているオブジェクトを探すのが最も効率的な方法ではありません。

どのように座標を取得する可能性のあるフィールドを保存するには?

答えて

0

あなたはGameBoardにこのような関数を書くことができます。

public getField(x, y) { 
    return this.fields[x + this.verticalFields * y]; 
} 
関連する問題