global var从级别收集分数,然后在结尾显示

时间:2012-07-10 19:47:46

标签: actionscript-3 flash global-variables

var scoreTotal:String = "Global"; //in the engine but not in the package

if (currentKey is Left && leftKey) //in each level to score points to score on stage and scoreTotal
{
    score += scoreBonus;
    scoreTotal += scoreBonus;
    currentKey.active = false;
}

public var score7:int = scoreTotal;// This is in the last level to print the score

我收到错误1120:访问未定义的属性scoreTotal。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

使用全局变量不是一个好主意,在AS3中没有这样的东西。而是创建一个Score类,其中包含与跟踪分数相关的任何内容。在主应用程序中保留此类的单个实例。然后使用事件和侦听器通知应用程序导致分数更新的游戏事件:

public class Score {
    private var total:int;
    private var levels:Array;

    public function addPoints ( level:int, points:int ) : void {
        total += points;
        levels[level] += points;
    }

    public function get scoreTotal() : int {
        return total;
    }

    public function getLevelScore( level:int ) : int {
        return levels[level];
    }

    public function Score(numLevels:int) : void {
        total = 0;
        levels = [];
        var i:int = -1;
        while( ++i < numLevels) levels[i] = 0;
    }
}


public class Main {
    private var score:Score = new Score( 7 );

    private var gameEngine:GameEngine;

    ....


    private function initGameScore() : void {
        gameEngine.addEventListener ( GameEvent.SCORE, onGameScore );
        gameEngine.addEventListener ( GameEvent.BONUS, onGameBonus );
    }

    private function onGameScore( ev:GameEvent ) : void {
        addPoints( ev.points );
    }

    ....
}

当然,GameEvent必须派生自flash.events.Event并包含字段points:int。无论何时发生任何值得评分的事情,你都会从GameEngine派遣那些人。

然后,更高级的版本是保留事件和点的哈希表,并使得实际评分(即事件到点的映射)独立于GameEngine而发生。