我需要一条出路

时间:2010-08-18 08:03:57

标签: actionscript-3

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 == field [3] [4],c2 == field [4] [4],c3 == field [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 个答案:

答案 0 :(得分: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