Статьи

Совет: простой дисплей для флеш-игр

Почти во всех играх используется система подсчета очков, чтобы помочь игрокам увидеть свой прогресс. Важно показать счет игрока в ясной и веселой форме. В этом кратком совете мы узнаем, как это сделать!


Нажмите кнопку, чтобы добавить 20 000 баллов к вашему счету:

В этом кратком совете мы узнаем, как создать отображение счета. Чтобы улучшить качество нашего дисплея, мы собираемся сделать две вещи:

  1. Добавьте запятые к нашему счету, чтобы он показывал 1 600 000 вместо 1600 000. Это позволяет игроку легче определить, насколько велик его или ее счет.
  2. Сделайте наш результат перехода между значениями, вместо того, чтобы изменить сразу. Это дает игроку чувство достижения, потому что он или она фактически видит, что его счет растет.

В конце у нас будет очень простой и полезный класс, который вы можете легко использовать в любом из ваших проектов.

Этот класс будет заниматься только отображением оценки, а не ее подсчетом.


Прежде всего давайте создадим наш класс; Я назвал это ScoreDisplay :

01
02
03
04
05
06
07
08
09
10
11
12
package
{
    import flash.display.Sprite;
     
    public class ScoreDisplay extends Sprite
    {
        public function ScoreDisplay()
        {
             
        }
    }
}

Давайте медленно добавим некоторые переменные:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
package
{
    import flash.display.Sprite;
     
    public class ScoreDisplay extends Sprite
    {
        //the score which is being shown, whilst it is increasing
        public var currentScore:uint;
         
        //the player’s score
        private var score:uint;
         
         
        public function ScoreDisplay()
        {
             
        }
    }
}

Мы собираемся показать наш счет в TextField . Если вы хотите использовать Symbol при работе с ScoreDisplay , вам не нужно создавать текстовое поле по коду. Однако, если вы не хотите использовать Symbol, вам нужно вызвать createScoreField() .

Помните, что если вы хотите использовать свой собственный символ, вы должны дать текстовому полю внутри этого символа имя экземпляра currentScoreField .

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package
{
    import flash.display.Sprite;
    import flash.text.TextField;
     
    public class ScoreDisplay extends Sprite
    {
        //the text field which will show currentScore
        public var currentScoreField:TextField;
         
        //the score which is being shown, whilst it is increasing
        public var currentScore:uint;
         
        //the player’s score
        private var score:uint;
         
        public function ScoreDisplay()
        {
             
        }
         
        //if the developer won’t link this class to a symbol, this method must be called
        public function createScoreField():void
        {
            currentScoreField = new TextField();
            addChild(currentScoreField);
        }
    }
}

Теперь давайте начнем думать, что бы мы хотели сделать с нашим классом ScoreDisplay . Мы хотели бы иметь возможность установить счет, а также добавить или вычесть из счета игрока. Итак, давайте создадим эти методы!

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package
{
    import flash.display.Sprite;
    import flash.text.TextField;
     
    public class ScoreDisplay extends Sprite
    {
        //the text field which will show currentScore
        public var currentScoreField:TextField;
         
        //the player’s score
        private var score:uint;
         
        //the score which is being shown, whilst it is increasing
        private var currentScore:uint;
         
        public function ScoreDisplay()
        {
             
        }
         
        //if the developer won’t link this class to a symbol, this method must be called
        public function createScoreField():void
        {
            currentScoreField = new TextField();
            addChild(currentScoreField);
        }
         
        public function setScore(_value:uint):void
        {
            score = _value;
        }
         
        public function changeScore(_change:uint):void
        {
            score += _change;
        }
    }
}

Пока все хорошо, теперь мы можем устанавливать и изменять значение счета. Но как мы это отобразим? Даже если это покажется не очень полезным, мы будем использовать прослушиватель события enter frame. Не волнуйтесь, это будет иметь смысл!

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.text.TextField;
     
    public class ScoreDisplay extends Sprite
    {
        //the text field which will show currentScore
        public var currentScoreField:TextField;
         
        //the player’s score
        private var score:uint;
         
        //the score which is being shown, whilst it is increasing
        private var currentScore:uint;
         
        public function ScoreDisplay()
        {
            addEventListener(Event.ENTER_FRAME, showScore, false, 0, true);
        }
         
        //if the developer won’t link this class to a symbol, this method must be called
        public function createScoreField():void
        {
            currentScoreField = new TextField();
            addChild(currentScoreField);
        }
         
        public function setScore(_value:uint):void
        {
            score = _value;
        }
         
        public function changeScore(_change:uint):void
        {
            score += _change;
        }
         
        private function showScore(event:Event):void
        {
            currentScoreField.text = String(score);
        }
    }
}

Если бы мы хотели использовать наш класс в проекте, он бы выглядел следующим образом. Кажется, работает правильно — оценка меняется — но мы еще не закончили. Помните, что мы хотели сделать?

  1. Добавьте к нашему счету запятые, чтобы вместо 1600000 читалось 160000.
  2. Сделайте наш результат перехода между значениями, вместо того, чтобы изменить сразу.

Начнем с первой цели, добавив запятые.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.text.TextField;
     
    public class ScoreDisplay extends Sprite
    {
        //the text field which will show currentScore
        public var currentScoreField:TextField;
         
        //the player’s score
        private var score:uint;
         
        //the score which is being shown, whilst it is increasing
        private var currentScore:uint;
         
        public function ScoreDisplay()
        {
            addEventListener(Event.ENTER_FRAME, showScore, false, 0, true);
        }
         
        //if the developer won’t link this class to a symbol, this method must be called
        public function createScoreField():void
        {
            currentScoreField = new TextField();
            addChild(currentScoreField);
        }
         
        public function setScore(_value:uint):void
        {
            score = _value;
        }
         
        public function changeScore(_change:uint):void
        {
            score += _change;
        }
         
        private function showScore(event:Event):void
        {
            currentScoreField.text = addCommas(score);
        }
         
        private function addCommas(_score:uint):String
        {
            //a string, which will have the score with commas
            var scoreString:String = new String();
             
            //the amount of characters our score (without commas) has
            var scoreLength:uint = _score.toString().length;
            scoreString = «»;
             
            //add the commas to the string
            for (var i:uint=0; i<scoreLength; i++) {
                if ((scoreLength-i)%3 == 0 && i != 0) {
                    scoreString += «,»;
                }
                scoreString += _score.toString().charAt(i);
            }
             
            return scoreString;
        }
    }
}

Теперь давайте работать над нашей второй целью; переход между значениями баллов вместо немедленного перехода к новому значению.

Для этого мы можем использовать потрясающие возможности класса Tween . В большинстве случаев мы думаем о классе Tween для перемещения экранных объектов, но вы можете использовать его для изменения любого числового значения, включая нашу оценку.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package
{
    import fl.transitions.Tween;
    import fl.transitions.easing.*;
     
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.text.TextField;
     
    public class ScoreDisplay extends Sprite
    {
        //the amount of time (in ms) which is needed to transition from one score value to another one
        private static const TRANSITION_LENGTH:uint = 500;
         
        //the score which is being shown, whilst it is increasing
        public var currentScore:uint;
         
        //the player’s score
        private var score:uint;
         
        //the text field which will show currentScore
        private var currentScoreField:TextField;
         
        //this will tween the current score’s value
        private var currentScoreTween:Tween;
         
        public function ScoreDisplay()
        {
            addEventListener(Event.ENTER_FRAME, showScore, false, 0, true);
        }
         
        //if the developer won’t link this class to a symbol, this method must be called
        public function createScoreField():void
        {
            currentScoreField = new TextField();
            addChild(currentScoreField);
        }
         
        public function setScore(_value:uint):void
        {
            score = _value;
             
            tweenCurrentScore();
        }
         
        public function changeScore(_change:uint):void
        {
            score += _change;
             
            tweenCurrentScore();
        }
         
        private function showScore(event:Event):void
        {
            currentScoreField.text = addCommas(currentScore);
        }
         
        private function tweenCurrentScore():void
        {
            currentScoreTween = new Tween(this, «currentScore», None.easeNone, currentScore, TRANSITION_LENGTH, true);
        }
         
        private function addCommas(_score:uint):String
        {
            //a string, which will have the score with commas
            var scoreString:String = new String();
             
            //the amount of characters our score (without commas) has
            var scoreLength:uint = _score.toString().length;
            scoreString = «»;
             
            //add the commas to the string
            for (var i:uint=0; i<scoreLength; i++) {
                if ((scoreLength-i)%3 == 0 && i != 0) {
                    scoreString += «,»;
                }
                scoreString += _score.toString().charAt(i);
            }
             
            return scoreString;
        }
    }
}

Вот и все! Вы можете расширить этот класс и, возможно, добавить некоторые звуки или «причудливую графику». Я надеюсь, что вы прекрасно провели время и чему-то научились, ура!