2010-08-18 93 views
0
public class NCell 
{ 
    private var _player: NPlayer; 
    public function set player(value: NPlayer):void 
    { 
     this._player = value; 
    } 
    public function get player():NPlayer {return this._player} 
} 

public class NPlayer 
{ 
    private var _cell: NCell; 
    public function set cell(value: NCell):void 
    { 
     if (this._cell != null) 
     { 
      this._cell.player = null; 
     } 

     this._cell = value; 

     if (this._cell != null) 
     { 
      this._cell.player = this; 
      this.position  = this.cell.position; 
     } 
    } 
} 

所以,我有一個NCells(大小20x15)和其上的幾個球員的領域。移動球員我寫我需要一個出路

player.cell = field[4][4]; 

當它的球員知道他的細胞(和位置)和細胞有一個鏈接到球員。因此我有一切來計算可用的移動。有時玩家有「單元格」,但單元格中的「玩家」== null。這不好。這是因爲當我計算移動時,我存儲玩家位置,然後移動玩家,然後繼續搜索,當遊戲點數變爲0時,恢復玩家位置並繼續搜索。例如。我有c1 ==字段[3] [4],c2 ==字段[4] [4],c3 ==字段[5] [4],p1.cell == c1,p2.cell == c2。 p2移動到c3,然後p1移動到c1。然後我恢復位置:

//c2.player == p1 
p2.cell = c2;//now c2.player == c2 but p1.cell == c2 
p1.cell = c1;//and here c2.player == null 

並且它不依賴於恢復順序。如何避免鏈接擦除?

+1

不能幫助你解決問題,但我喜歡標題:d – Blindy 2010-08-18 08:15:45

回答

0

嗯,我不太確定你存儲數據的方式是否最好。如果你真的想要這種聯繫,你可能要考慮讓一個能夠容納多個玩家的單元格。這將解決您當前的問題,並且稍後會更加靈活。

基本上,你的問題是可以解決這樣的:

public class NPlayer 
{ 
    private var _cell: NCell; 
    public function set cell(value: NCell):void 
    { 
     if (this._cell != null && this._cell.player == this) //only the owner may remove a link! 
     { 
      this._cell.player = null; 
     } 

     this._cell = value; 

     if (this._cell != null) 
     { 
      this._cell.player = this; 
      //this.position  = this.cell.position; <-- no need for that, see below 
     } 
    } 
} 

除非你每幀訪問NPlayer::position一個極大倍,存在存儲它沒有任何意義。這隻會引入潛在的錯誤來源。如果玩家沒有細胞(或引發異常,如果不應該發生),則應該通過簡單地返回this.cell.position或有意義的默認值來計算屬性。

格爾茨
back2dos

+0

>好了,我不是很確定你的方式存儲數據是最好的。 你能舉個例子嗎?我用它來知道有一個單元玩家和玩家在哪裏。我有時間重寫這部分遊戲。 我已經嘗試過你的提示,但它沒有幫助。也許我在別的地方有一個bug。難以找到它。 – ChessMax 2010-08-18 17:37:39