2010-08-18 74 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