Advertisement
  1. Code
  2. Coding Fundamentals
  3. Game Development

Create a Complete Typing Game in Flash with AS3

Scroll to top

Leading on from my earlier tutorial on detecting keyboard combos, we'll see how to build a full game that tests your typing skills.


Final Result Preview

Let's take a look at the final result we will be working towards:

Use the letters on the screen to type English words! Invalid words will lose you points, so watch out.


Step 1: Introduction

In this tutorial we will be working on a very awesome typing game using this very useful Combo Detection class. It is very recommended that you read that tutorial before continuing here, so that you understand what that class will be doing during our game.

In our game, we will have many blocks with letters on the screen, and the player has to type a word formed with the letter blocks. If that word is valid, the blocks are removed and the player gets points and more time to play. The game will end when the time reaches zero.

If you plan on completely following this tutorial, you should grab the source files.


Step 2: Adding the Images in Flash Professional

As it was done in the previously mentioned tutorial, we will add the all the images for our game in a Flash Professional .fla file, then generate a .swc file, which will be added into our FlashDevelop project for use.

For this tutorial, we will need a background image (thanks for Petr Kovar for the awesome wood background!), a generic block image with a selected frame and the currently typed keys box. You can find everything set up in our source files.

Background imageBackground imageBackground image
Generic block image
Selected generic block image
Word boxWord boxWord box

Other images such as the preloader and the game over screen will be added as well, but these will be made during the tutorial, since it makes more sense to do so.


Step 3: The LetterBlock

Before we can begin working on our code, let's set up our FlashDevelop project. This one is going to be an AS3 Project with Preloader, so select that option on FlashDevelop! Assuming that you have read the combos tutorial, you probably know how to add a .swc file to FlashDevelop's library. If you don't, just right-click it and select "Add to library". Grab the .swc file from the source and add it. That's it. Time for action!

Our letter block will be a simple object with a TextField in it and the block image shown in Step 2. Coding that is simple. Create the LetterBlock class:

1
2
package  
3
{
4
	import ArtAssets.LetterBlockImage;
5
	import flash.display.MovieClip;
6
	import flash.display.Sprite;
7
	import flash.text.TextField;
8
	import flash.text.TextFormat;
9
	import flash.text.TextFormatAlign;
10
	
11
	public class LetterBlock extends Sprite 
12
	{
13
		private var _image:MovieClip;
14
		
15
		private var _letterText:TextField;
16
		
17
		public function LetterBlock() 
18
		{
19
			_image = new LetterBlockImage();
20
			_image.stop();
21
			
22
			_letterText = new TextField();
23
			_letterText.defaultTextFormat = new TextFormat("Verdana", 40, 0xFFFFFF, true, null, null, null, null, TextFormatAlign.CENTER);
24
			_letterText.width = 60;
25
			_letterText.x = -30;
26
			_letterText.y = -26.3;
27
			_letterText.selectable = false;
28
			_letterText.multiline = false;
29
			
30
			addChild(_image);
31
			addChild(_letterText);
32
		}
33
		
34
		public function setLetter(letter:String):void
35
		{
36
			_letterText.text = letter;
37
		} 
38
		
39
	}
40
41
}

Lines 21-28 create the text field to hold our letter text, as well as position it on the screen and give it a font, font color and size. The setLetter function is only used to set the letter of the box.


Step 4: Loading up the Words

Every typing game needs words to work with. In this step, we will load an external file through the [Embed] tag and work with the data of the file. Obviously, this file contains words to be used in our game. It is available in the source files. Also, in this step we begin to work with the ComboHandler class, so add it in your FlashDevelop project as well!

Let's look at some code:

In Main.as:

1
2
private function init(e:Event = null):void 
3
{
4
	removeEventListener(Event.ADDED_TO_STAGE, init);
5
	
6
	ComboHandler.initialize(stage);
7
	
8
	DictionaryWords.loadWords();
9
}

Line 5 above initializes the ComboHandler, as required, and line 7 calls the loadWords() method from the DictionaryWords class. This class will be created by us, and its code is right below:

1
2
package  
3
{
4
	public class DictionaryWords 
5
	{
6
		[Embed(source = "../src/Words.txt", mimeType = "application/octet-stream")]
7
		private static var _Words:Class;
8
		
9
		public static function loadWords():void
10
		{
11
			var words:String = new _Words();
12
			
13
			var wordsArray:Array = words.split("\n");
14
			
15
			var i:int;
16
			var length:int = wordsArray.length;
17
			
18
			for (i = 0; i < length; i++)
19
			{
20
				ComboHandler.registerCombo(wordsArray[i], turnIntoLetters(wordsArray[i]));
21
			}
22
		}
23
		
24
		private static function turnIntoLetters(word:String):Array
25
		{
26
			var letters:Array = word.split("");
27
			
28
			if (letters[0] == "")
29
			{
30
				letters.shift();
31
			}
32
			
33
			if (letters[letters.length - 1] == "")
34
			{
35
				letters.pop();
36
			}
37
			
38
			var i:int;
39
			
40
			for (i = 0; i < letters.length; i++)
41
			{
42
				letters[i] = String(letters[i]).charCodeAt(0);
43
			}
44
			
45
			return letters;
46
		}
47
		
48
	}
49
50
}

Line 5 is the line that loads the external file and put it in the game at compile-time. This is all possible because of the [Embed] tag. If you want more information about it, I recommend this great article on Adobe Livedocs.

Here is a section of Words.txt, so you can see what we're working with:

1
2
ABBREVIATOR
3
ABC
4
ABCOULOMB
5
ABCS
6
ABDIAS
7
ABDICABLE
8
ABDICATE
9
ABDICATION
10
ABDICATOR
11
ABDOMEN
12
ABDOMINAL
13
ABDOMINOCENTESIS
14
ABDOMINOPLASTY

Line 12 (of DictionaryWords.as) is a very important line. Basically, it turns all the words from Words.txt, which were stored in a String, to elements in an Array. Since each word is separated by a newline character, all we had to do was call the split() method of the String class.

The turnIntoLetters function just turns a word into an Array with the key codes of each letter. That way, our ComboHandler class can work with it.


Step 5: Adding Letter Blocks to the Screen

Now that we have our words ready in the game, it is time to begin working on putting the letters on the screen. This is very simple. First of all, we need a game screen. The GameScreen class will contain all the logic of our game.

1
2
package  
3
{
4
	import ArtAssets.BackgroundImage;
5
	import flash.display.Sprite;
6
	import adobe.utils.CustomActions;
7
	
8
	public class GameScreen extends Sprite
9
	{
10
		private var _background:BackgroundImage;
11
		
12
		private var _blocksOnScreen:Vector.<LetterBlock>;
13
		
14
		public function GameScreen() 
15
		{
16
			_background = new BackgroundImage();
17
			_background.x = 275;
18
			_background.y = 200;
19
			
20
			addChild(_background);
21
			
22
			_blocksOnScreen = new Vector.<LetterBlock>();
23
			
24
			populateBlocks();
25
		}
26
		
27
		private function populateBlocks():void 
28
		{
29
			var i:int;
30
			
31
			var tempBlock:LetterBlock;
32
			
33
			for (i = 0; i < 8; i++)
34
			{
35
				tempBlock = new LetterBlock();
36
				tempBlock.x = 130 + ((i % 4) * 95);
37
				tempBlock.y = 80 + int(i / 4) * 80;
38
				tempBlock.setLetter(randomLetter());
39
				
40
				addChild(tempBlock);
41
				
42
				_blocksOnScreen.push(tempBlock);
43
				
44
				tempBlock = null;
45
			}
46
		}
47
		
48
		private function randomLetter():String
49
		{
50
			return String.fromCharCode((int(Math.random() * 26) + 65));
51
		}
52
		
53
	}
54
55
}

The _blocksOnScreen Vector is the main element in this code: it will contain all the blocks on the screen, allowing us to work with them anytime we want. Note that in Line 14 we add the BackgroundImage on the screen, which is a graphic from the .swc file.

Inside the populateBlocks() function, all that we do is add a new LetterBlock at a certain position, give it a random letter (which is generated by the randomLetter() function) and add it to the screen.

Now, we need to add the game screen in Main's child. Inside Main.as:

1
2
		private var _gameScreen:GameScreen;
3
		
4
		private function init(e:Event = null):void 
5
		{
6
			removeEventListener(Event.ADDED_TO_STAGE, init);
7
			
8
			ComboHandler.initialize(stage);
9
			
10
			DictionaryWords.loadWords();
11
			
12
			_gameScreen = new GameScreen();
13
			
14
			addChild(_gameScreen);
15
		}

Compile the project and you will be able to see the blocks on the screen!


Step 6: Selecting a Block After a Key Press

In our game, we want the block to go to its "Selected" image when its corresponding key has been pressed. This is very easy to do. Go to the LetterBlock.as file and add this code:

1
2
private var _selected:Boolean;
3
4
public function select():void
5
{
6
	_selected = !_selected;
7
	
8
	_image.gotoAndStop(_selected == true ? "Selected" : "Unselected");
9
}
10
11
public function get letter():String
12
{
13
	return _letterText.text;
14
}
15
16
public function get selected():Boolean 
17
{
18
	return _selected;
19
}

The _selected variable will be used on the game's logic to check whether a block is selected or not. The same happens with letter.

All that is left is to make the block switch between "selected" and "unselected" now. Inside GameScreen.as:

1
2
import flash.events.Event;
3
import flash.events.KeyboardEvent;
4
5
// ** snip **

6
7
public function GameScreen() 
8
{
9
	_background = new BackgroundImage();
10
	_background.x = 275;
11
	_background.y = 200;
12
	
13
	addChild(_background);
14
	
15
	_blocksOnScreen = new Vector.<LetterBlock>();
16
	
17
	populateBlocks();
18
	
19
	addEventListener(Event.ADDED_TO_STAGE, onStage);
20
}
21
22
private function onStage(e:Event):void 
23
{
24
	removeEventListener(Event.ADDED_TO_STAGE, onStage);
25
	
26
	stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
27
}
28
29
private function onKeyDown(e:KeyboardEvent):void 
30
{
31
	var i:int;
32
	
33
	for (i = 0; i < _blocksOnScreen.length; i++)
34
	{
35
		if (_blocksOnScreen[i].letter == String.fromCharCode(e.keyCode) && !_blocksOnScreen[i].selected)
36
		{
37
			_blocksOnScreen[i].select();
38
			
39
			break;
40
		}
41
	}
42
}

Given that we should add our KeyboardEvent listeners to the stage, in the GameScreen's constructor, we add a listener for Event.ADDED_TO_STAGE, which will lead us to the onStage() function. This function adds the listener to the stage. The onKeyDown() function is responsible for going over all our blocks on the screen and verifying if there is any block with the letter pressed. If so, then we should select it, which is done in line 36.

After compiling the project, this is what we get:

(Press the keys on your keyboard!)


Step 7: Modifications to the ComboHandler Class

In order for our game to work the way we want, we'll need to do a few modifications to the ComboHandler class from the previous tutorial. The first modification is to make it able to only check for a combo when the user has stopped typing. This will be detected with the MAX_INTERVAL constant and through an update() function. Also, since the user has to type the exact word letters in order to "complete" it, we will change how we are checking if a combo matches the keys inside the pressedKeys Array. The last modification is to send an event even when the word typed is wrong. This will allow our game to detect the player's mistake and penalise him for that.

All the code below does what was explained:

Inside ComboHandler.as:

1
2
private static const MAX_INTERVAL:int = 500; // Milliseconds

3
4
private static var checkComboAfterClearing:Boolean;
5
6
public static function initialize(stageReference:Stage, checkComboAfterClearing:Boolean = false):void
7
{
8
	combos = new Dictionary();
9
	
10
	interval = 0;
11
	
12
	dispatcher = new EventDispatcher();
13
	
14
	ComboHandler.checkComboAfterClearing = checkComboAfterClearing;
15
	
16
	pressedKeys = [];
17
	
18
	stageReference.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
19
}
20
21
private static function onKeyDown(e:KeyboardEvent):void
22
{
23
	if (getTimer() - interval > MAX_INTERVAL)
24
	{
25
		pressedKeys = [];
26
	}
27
	
28
	interval = getTimer();
29
	
30
	pressedKeys.push(e.keyCode);
31
	
32
	if (!checkComboAfterClearing)
33
	{
34
		checkForCombo();
35
	}
36
}
37
38
public static function update():void
39
{
40
	if (getTimer() - interval > MAX_INTERVAL)
41
	{
42
		checkForCombo();
43
		
44
		pressedKeys = [];
45
	}
46
}
47
48
private static function checkForCombo():void
49
{
50
	if (pressedKeys.length == 0)
51
	{
52
		return;
53
	}
54
	
55
	var i:int;
56
	var comboFound:String = "";
57
	
58
	for (var comboName:String in combos)
59
	{
60
		if ((combos[comboName] as Array).length == 0)
61
		{
62
			continue;
63
		}
64
		
65
		if (pressedKeys.join(" ") == (combos[comboName] as Array).join(" "))
66
		{
67
			comboFound = comboName;
68
			
69
			break;
70
		}
71
	}
72
	
73
	// Combo Found

74
	//if (comboFound != "")

75
	//{

76
	//pressedKeys = [];

77
	dispatcher.dispatchEvent(new ComboEvent(ComboEvent.COMBO_FINISHED, {comboName: comboFound} ));
78
	//}

79
}

We changed our ComboHandler's constructor declaration to allow us check for combos only after the user has stopped typing. This is verified in the update() function, using the MAX_INTERVAL constant. Also, the checkForCombo() function has been modified to use a more suitable combo checking.

Now, we also must change the GameScreen class to update the ComboHandler class:

1
2
public function GameScreen() 
3
{
4
	_background = new BackgroundImage();
5
	_background.x = 275;
6
	_background.y = 200;
7
	
8
	addChild(_background);
9
	
10
	_blocksOnScreen = new Vector.<LetterBlock>();
11
	
12
	populateBlocks();
13
	
14
	addEventListener(Event.ADDED_TO_STAGE, onStage);
15
	
16
	addEventListener(Event.ENTER_FRAME, gameLoop);
17
}
18
19
private function gameLoop(e:Event):void 
20
{
21
	ComboHandler.update();
22
}

The update is being done through an Event.ENTER_FRAME event listener, since it's a simple and good approach.

The last modification is to change how we initialize the ComboHandler class inside the Main class:

1
2
private function init(e:Event = null):void 
3
{
4
	removeEventListener(Event.ADDED_TO_STAGE, init);
5
	
6
	ComboHandler.initialize(stage, true);
7
	
8
	DictionaryWords.loadWords();
9
	
10
	_gameScreen = new GameScreen();
11
	
12
	addChild(_gameScreen);
13
}

By compiling the game, this is what we get:


Step 8: Adding the Word Box

It's time to give the player something else to rely on. Right now, the player can't see the sequence of letters that was already typed, so let's add a word box in the game. This box will contain the currently typed letters, organized by order, and will be cleaned when a combo event has been received. Create the WordBox class and add this code to it:

1
2
package  
3
{
4
	import ArtAssets.TypedLettersBoxImage;
5
	import flash.display.Sprite;
6
	import flash.text.TextField;
7
	import flash.text.TextFormat;
8
	import flash.text.TextFormatAlign;
9
	
10
	public class WordBox extends Sprite
11
	{
12
		private var _image:Sprite;
13
		
14
		private var _textField:TextField;
15
		
16
		public function WordBox() 
17
		{
18
			_image = new TypedLettersBoxImage();
19
			
20
			_textField = new TextField();
21
			_textField.defaultTextFormat = new TextFormat("Verdana", 30, 0xFFFFFF, true, null, null, null, null, TextFormatAlign.CENTER);
22
			_textField.width = 500;
23
			_textField.x = -250;
24
			_textField.y = -25;
25
			_textField.selectable = false;
26
			_textField.multiline = false;
27
			_textField.text = "";
28
			
29
			addChild(_image);
30
			
31
			addChild(_textField);
32
		}
33
		
34
		public function addLetter(letter:String):void
35
		{
36
			_textField.appendText(letter);
37
		}
38
		
39
		public function clear():void
40
		{
41
			_textField.text = "";
42
		}
43
		
44
	}
45
46
}

This class is almost the same as the LetterBlock class, so no extensive explanation is necessary. The only thing that deserves attention is line 35, which contains a call to the appendText() method from the String class. This function will add text to the end of the current text, allowing us to display the typed letters always at the end of the current text from the word box.

Now, it's time to add the word box in the game. Go to GameScreen.as and add this code:

1
2
private var _wordBox:WordBox;
3
4
public function GameScreen() 
5
{
6
	_background = new BackgroundImage();
7
	_background.x = 275;
8
	_background.y = 200;
9
	
10
	addChild(_background);
11
	
12
	_blocksOnScreen = new Vector.<LetterBlock>();
13
	
14
	populateBlocks();
15
	
16
	_wordBox = new WordBox();
17
	_wordBox.x = 275;
18
	_wordBox.y = 350;
19
	
20
	addChild(_wordBox);
21
	
22
	addEventListener(Event.ADDED_TO_STAGE, onStage);
23
	
24
	addEventListener(Event.ENTER_FRAME, gameLoop);
25
}
26
27
private function onKeyDown(e:KeyboardEvent):void 
28
{
29
	var i:int;
30
	
31
	for (i = 0; i < _blocksOnScreen.length; i++)
32
	{
33
		if (_blocksOnScreen[i].letter == String.fromCharCode(e.keyCode) && !_blocksOnScreen[i].selected)
34
		{
35
			_blocksOnScreen[i].select();
36
			
37
			_wordBox.addLetter(_blocksOnScreen[i].letter);
38
			
39
			break;
40
		}
41
	}
42
}

Lines 1, 15-17 and 19 create the word box and put it on the screen. Line 36 calls the addLetter() function to add a letter in the box.

The result of this step is below. We will add the code to clear the word box in the next step.


Step 9: Integrating our ComboHandler With our GameScreen

Right now, the only changes that have been done in the ComboHandler only modified when and how to check for combos. This is the part where it gets fun: we will integrate our ComboHandler in the game. This means our ComboHandler will depend on GameScreen in order to run. Let's jump to the code, and see explanations after it!

Inside GameScreen.as:

1
2
public function GameScreen() 
3
{
4
	_background = new BackgroundImage();
5
	_background.x = 275;
6
	_background.y = 200;
7
	
8
	addChild(_background);
9
	
10
	_blocksOnScreen = new Vector.<LetterBlock>(8);
11
	
12
	populateBlocks();
13
	
14
	_wordBox = new WordBox();
15
	_wordBox.x = 275;
16
	_wordBox.y = 350;
17
	
18
	addChild(_wordBox);
19
	
20
	addEventListener(Event.ADDED_TO_STAGE, onStage);
21
	
22
	addEventListener(Event.ENTER_FRAME, gameLoop);
23
	
24
	ComboHandler.dispatcher.addEventListener(ComboEvent.COMBO_FINISHED, onWordFinished);
25
	
26
	ComboHandler.setGameInstance(this);
27
}
28
29
private function onWordFinished(e:ComboEvent):void 
30
{
31
	_wordBox.clear();
32
}
33
34
public function isKeyAvailable(key:String):Boolean
35
{
36
	var i:int;
37
	
38
	for (i = 0; i < _blocksOnScreen.length; i++)
39
	{
40
		if (_blocksOnScreen[i].letter == key && !_blocksOnScreen[i].selected)
41
		{
42
			return true;
43
		}
44
	}
45
	
46
	return false;
47
}
48
49
private function populateBlocks():void 
50
{
51
	var i:int;
52
	
53
	var tempBlock:LetterBlock;
54
	
55
	for (i = 0; i < 8; i++)
56
	{
57
		tempBlock = new LetterBlock();
58
		tempBlock.x = 130 + ((i % 4) * 95);
59
		tempBlock.y = 80 + int(i / 4) * 80;
60
		tempBlock.setLetter(randomLetter());
61
		
62
		addChild(tempBlock);
63
		
64
		_blocksOnScreen[i] = tempBlock;
65
		
66
		tempBlock = null;
67
	}
68
}

Inside GameScreen's constructor, we added an event listener to ComboHandler's dispatcher object, and called the setGameInstance() function of that class (which will be added below). This will give the current instance of the game screen to the ComboHandler class, and will clear the word box.

There's also an isKeyAvailable function created. This will be called within the combo handler to verify if it can add a key to the list of pressed keys.

Line 63 is just a fix to the change done in _blocksInScreen in the constructor.

Take a look at the code to add inside ComboHandler.as:

1
2
private static var gameInstance:GameScreen;
3
4
public static function setGameInstance(gameInstance:GameScreen):void
5
{
6
	ComboHandler.gameInstance = gameInstance;
7
}
8
9
private static function onKeyDown(e:KeyboardEvent):void
10
{
11
	if (getTimer() - interval > MAX_INTERVAL)
12
	{
13
		pressedKeys = [];
14
	}
15
	
16
	if (gameInstance.isKeyAvailable(String.fromCharCode(e.keyCode)))
17
	{
18
		interval = getTimer();
19
		
20
		pressedKeys.push(e.keyCode);
21
	}
22
	
23
	if (!checkComboAfterClearing)
24
	{
25
		checkForCombo();
26
	}
27
}

In the highlighted line we add a call to isKeyAvailable(), which is in the game screen instance stored in the ComboHandler class. This is the end of the integration between the game and the combo handler.

After compiling, you will notice that the game now clears the word box after the interval has passed:


Step 10: Act When a Word has Been Typed

In this step, we will make the game take some action when a word has been detected. First of all, we need to know when a word has been detected. Let's find out how:

Inside GameScreen.as:

1
2
public function GameScreen() 
3
{
4
	_background = new BackgroundImage();
5
	_background.x = 275;
6
	_background.y = 200;
7
	
8
	addChild(_background);
9
	
10
	_blocksOnScreen = new Vector.<LetterBlock>(8);
11
	
12
	populateBlocks();
13
	
14
	_wordBox = new WordBox();
15
	_wordBox.x = 275;
16
	_wordBox.y = 350;
17
	
18
	addChild(_wordBox);
19
	
20
	addEventListener(Event.ADDED_TO_STAGE, onStage);
21
	
22
	addEventListener(Event.ENTER_FRAME, gameLoop);
23
	
24
	ComboHandler.dispatcher.addEventListener(ComboEvent.COMBO_FINISHED, onWordFinished);
25
	
26
	ComboHandler.setGameInstance(this);
27
}
28
29
private function onWordFinished(e:ComboEvent):void 
30
{
31
	if (e.params.comboName != "")
32
	{
33
		removeSelectedLetters();
34
		populateBlocks();
35
		
36
		_wordBox.clear();
37
	}
38
}
39
40
private function removeSelectedLetters():void 
41
{
42
	var i:int;
43
	
44
	for (i = 0; i < 8; i++)
45
	{
46
		if (_blocksOnScreen[i].selected)
47
		{
48
			removeChild(_blocksOnScreen[i]);
49
			
50
			_blocksOnScreen[i] = null;
51
		}
52
	}
53
}
54
55
private function populateBlocks():void 
56
{
57
	var i:int;
58
	
59
	var tempBlock:LetterBlock;
60
	
61
	for (i = 0; i < 8; i++)
62
	{
63
		if (_blocksOnScreen[i] == null)
64
		{
65
			tempBlock = new LetterBlock();
66
			tempBlock.x = 130 + ((i % 4) * 95);
67
			tempBlock.y = 80 + int(i / 4) * 80;
68
			tempBlock.setLetter(randomLetter());
69
			
70
			addChild(tempBlock);
71
			
72
			_blocksOnScreen[i] = tempBlock;
73
		}
74
		
75
		tempBlock = null;
76
	}
77
}

In line 23 there is an event listener for ComboEvent.COMBO_FINISHED. This event will be fired every time a word has been formed or when the player has missed. If you go back to ComboHandler.as, you will notice that when the player misses, the name of the combo within the fired event will be null, or "". Due to that, we do the check in lines 28-34. The removeSelectedLetters() function will remove all selected letters, since the player has formed a word when it is called. We also changed the populateBlocks() function to only put a new block in places where there is no block - this fits what we are doing inside the function to remove blocks.

Compile the game and this is the result:


Step 11: Do Something When the Player Types a Wrong Word

Have you got any idea of what to do when a player misses a word? I was thinking of taking away time and score from the player (this will be done in later steps), as well as giving a 30% chance of modifying a selected letter from the misstyped word. The code below does exactly the latter. Move to GameScreen.as:

1
2
private function onWordFinished(e:ComboEvent):void 
3
{
4
	if (e.params.comboName != "")
5
	{
6
		removeSelectedLetters(false);
7
	}
8
	else
9
	{
10
		removeSelectedLetters(true);
11
	}
12
	
13
	populateBlocks();
14
	
15
	_wordBox.clear();
16
}
17
18
private function removeSelectedLetters(wasFromFailure:Boolean):void 
19
{
20
	var i:int;
21
	
22
	for (i = 0; i < 8; i++)
23
	{
24
		if (_blocksOnScreen[i].selected)
25
		{
26
			if ((wasFromFailure && Math.random() < 0.3) || !wasFromFailure)
27
			{
28
				removeChild(_blocksOnScreen[i]);
29
				
30
				_blocksOnScreen[i] = null;
31
			}
32
			else
33
			{
34
				_blocksOnScreen[i].select();
35
			}
36
		}
37
	}
38
}

Before looking at lines 5 and 9, let's jump to line 25: in this line, wasFromFailure is the variable that will define whether the game should "calculate" a 30% chance (through Math.random()) or just replace the block. And how is this value passed? Look at lines 5 and 9: if the name of the word is nothing, or "", that means the player has missed the word, which means we should pass true to removeSelectedLetters().

Compile the project and try to type a wrong word!


Step 12: Add a Score

It is now time to add a score in the game! First, we will create the image and place it on the screen. In the next step, we will give score to the player. For the score, we need to create a Score class, and this is the code for it:

1
2
package  
3
{
4
	import flash.display.Sprite;
5
	import flash.text.TextField;
6
	import flash.text.TextFormat;
7
	import flash.text.TextFormatAlign;
8
	
9
	public class Score extends Sprite
10
	{
11
		private var _text:TextField;
12
		
13
		private var _score:int;
14
		
15
		public function Score() 
16
		{
17
			_text = new TextField();
18
			_text.defaultTextFormat = new TextFormat("Verdana", 40, 0xFFFFFF, true, null, null, null, null, TextFormatAlign.CENTER);
19
			_text.width = 500;
20
			_text.selectable = false;
21
			_text.multiline = false;
22
			
23
			addChild(_text);
24
			
25
			_score = 0;
26
			
27
			_text.text = "Score: " + _score.toString();
28
		}
29
		
30
		public function addToScore(value:int):void
31
		{
32
			_score += value;
33
			
34
			_text.text = "Score: " + _score.toString();
35
		}
36
		
37
	}
38
39
}

I believe there is not much to say about it - we have already done text like this two times before. Now we should add this score on the screen. Inside GameScreen.as:

1
2
private var _score:Score;
3
4
public function GameScreen() 
5
{
6
	_background = new BackgroundImage();
7
	_background.x = 275;
8
	_background.y = 200;
9
	
10
	addChild(_background);
11
	
12
	_blocksOnScreen = new Vector.<LetterBlock>(8);
13
	
14
	populateBlocks();
15
	
16
	_wordBox = new WordBox();
17
	_wordBox.x = 275;
18
	_wordBox.y = 350;
19
	
20
	addChild(_wordBox);
21
	
22
	_score = new Score();
23
	_score.x = 25;
24
	_score.y = 210;
25
	
26
	addChild(_score);
27
	
28
	addEventListener(Event.ADDED_TO_STAGE, onStage);
29
	
30
	addEventListener(Event.ENTER_FRAME, gameLoop);
31
	
32
	ComboHandler.dispatcher.addEventListener(ComboEvent.COMBO_FINISHED, onWordFinished);
33
	
34
	ComboHandler.setGameInstance(this);
35
}

There you go. Compile the project and you can now see the score!


Step 13: Give and Take Score

Now that the score is already added on the screen, all we have to do is give score to the player when he completes a word, and take away score when he misses it. The code in GameScreen.as:

1
2
private function removeSelectedLetters(wasFromFailure:Boolean):void 
3
{
4
	var i:int;
5
	
6
	var count:int = 0;
7
	
8
	for (i = 0; i < 8; i++)
9
	{
10
		if (_blocksOnScreen[i].selected)
11
		{
12
			count++;
13
			
14
			if ((wasFromFailure && Math.random() < 0.3) || !wasFromFailure)
15
			{
16
				removeChild(_blocksOnScreen[i]);
17
				
18
				_blocksOnScreen[i] = null;
19
			}
20
			else
21
			{
22
				_blocksOnScreen[i].select();
23
			}
24
		}
25
	}
26
	
27
	if (wasFromFailure)
28
	{
29
		_score.addToScore( -(count * 10));
30
	}
31
	else
32
	{
33
		_score.addToScore(count * 30);
34
	}
35
}

As you can see, it is very simple: we give 30 times the number of letters of a word to the player, and take away 10 times the number of letters of the mistyped word. The compiled game is below for testing!


Step 14: Add a Timer

Adding a timer will be almost the same thing as the score. There will be only one difference: we will need to be constantly updating the timer, and the timer will have a different text. Take a look at the code for Timer.as below:

1
2
package  
3
{
4
	import flash.display.Sprite;
5
	import flash.text.TextField;
6
	import flash.text.TextFormat;
7
	import flash.text.TextFormatAlign;
8
	
9
	public class Timer extends Sprite
10
	{
11
		private var _text:TextField;
12
		
13
		private var _value:int;
14
		
15
		public function Timer() 
16
		{
17
			_text = new TextField();
18
			_text.defaultTextFormat = new TextFormat("Verdana", 20, 0xFF0000, true, null, null, null, null, TextFormatAlign.LEFT);
19
			_text.width = 200;
20
			_text.selectable = false;
21
			_text.multiline = false;
22
			
23
			addChild(_text);
24
			
25
			_value = 30;
26
			
27
			_text.text = "Time: " + timeString();
28
		}
29
		
30
		private function timeString():String
31
		{
32
			var minutes:int = _value / 60;
33
			
34
			var seconds:int = _value % 60;
35
			
36
			return minutes.toString() + ":" + seconds.toString();
37
		}
38
		
39
		public function addToTime(value:int):void
40
		{
41
			_value += value;
42
			
43
			_text.text = "Time: " + timeString();
44
		}
45
		
46
	}
47
48
}

As you may have noticed in lines 33, 35 and 37, we are creating a different text for timer. It will consist of minutes and seconds. For that to work, _value will be the time left in the game in seconds. Now the code to add the timer, in GameScreen.as:

1
2
private var _timer:Timer;
3
4
public function GameScreen() 
5
{
6
	_background = new BackgroundImage();
7
	_background.x = 275;
8
	_background.y = 200;
9
	
10
	addChild(_background);
11
	
12
	_blocksOnScreen = new Vector.<LetterBlock>(8);
13
	
14
	populateBlocks();
15
	
16
	_wordBox = new WordBox();
17
	_wordBox.x = 275;
18
	_wordBox.y = 350;
19
	
20
	addChild(_wordBox);
21
	
22
	_score = new Score();
23
	_score.x = 25;
24
	_score.y = 210;
25
	
26
	addChild(_score);
27
	
28
	_timer = new Timer();
29
	
30
	addChild(_timer);
31
	
32
	addEventListener(Event.ADDED_TO_STAGE, onStage);
33
	
34
	ComboHandler.dispatcher.addEventListener(ComboEvent.COMBO_FINISHED, onWordFinished);
35
	
36
	ComboHandler.setGameInstance(this);
37
}

There are no explanations needed in the code, so hit the compile button and take a look at your timer!

But it isn't counting down, is it? Let's do that!


Step 15: Decreasing and Increasing the Time Left

As discussed in the previous step, the timer needs to be constantly updated. This is because it is constantly decreasing, second by second. Also, we should award the player more seconds when a word is successfully completed, and take away some time when a word is mistyped. Inside GameScreen.as:

1
2
private var _updateTimer:Number;
3
4
public function GameScreen() 
5
{
6
	_background = new BackgroundImage();
7
	_background.x = 275;
8
	_background.y = 200;
9
	
10
	addChild(_background);
11
	
12
	_blocksOnScreen = new Vector.<LetterBlock>(8);
13
	
14
	populateBlocks();
15
	
16
	_wordBox = new WordBox();
17
	_wordBox.x = 275;
18
	_wordBox.y = 350;
19
	
20
	addChild(_wordBox);
21
	
22
	_score = new Score();
23
	_score.x = 25;
24
	_score.y = 210;
25
	
26
	addChild(_score);
27
	
28
	_timer = new Timer();
29
	
30
	addChild(_timer);
31
	
32
	addEventListener(Event.ADDED_TO_STAGE, onStage);
33
	
34
	addEventListener(Event.ENTER_FRAME, gameLoop);
35
	
36
	ComboHandler.dispatcher.addEventListener(ComboEvent.COMBO_FINISHED, onWordFinished);
37
	
38
	ComboHandler.setGameInstance(this);
39
	
40
	_updateTimer = 0;
41
}
42
43
private function gameLoop(e:Event):void 
44
{
45
	ComboHandler.update();
46
	
47
	_updateTimer += 1 / 30;
48
	
49
	if (_updateTimer >= 1)
50
	{
51
		_updateTimer -= 1;
52
		
53
		_timer.addToTime(-1);
54
	}
55
}
56
57
private function removeSelectedLetters(wasFromFailure:Boolean):void 
58
{
59
	var i:int;
60
	
61
	var count:int = 0;
62
	
63
	for (i = 0; i < 8; i++)
64
	{
65
		if (_blocksOnScreen[i].selected)
66
		{
67
			count++;
68
			
69
			if ((wasFromFailure && Math.random() < 0.3) || !wasFromFailure)
70
			{
71
				removeChild(_blocksOnScreen[i]);
72
				
73
				_blocksOnScreen[i] = null;
74
			}
75
			else
76
			{
77
				_blocksOnScreen[i].select();
78
			}
79
		}
80
	}
81
	
82
	if (wasFromFailure)
83
	{
84
		_score.addToScore( -(count * 10));
85
		_timer.addToTime( -count);
86
	}
87
	else
88
	{
89
		_score.addToScore(count * 30);
90
		_timer.addToTime(count * 2);
91
	}
92
}

Lines 1, 27, 29 and 33 create the timer, put it on the screen and add an event listener for Event.ENTER_FRAME. This listener will add 1/30 of a second to _updateTimer on each frame (we're assuming here that the game is running at 30 fps. If it's running at 24 fps, for example, it should add 1/24 of a second). When _updateTimer reaches one or more than one second, 1 is decreased from the timer's value. In lines 84 and 89, we decrease and increase time, respectively, based on whether the player has formed an "acceptable" word or not.

Also, when the user mistypes a word, an amount of seconds equal to the number of letters is decreased from the game timer. If a word is correct, the game awards twice the number of letters as seconds for the player.

This is your result:


Step 16: Improve our Random Letter Creation Process

In the current game, sometimes too few vowels appear on the screen. That makes it extremely hard to create words. In this step, we'll change that. The solution is extremely simple: we will use an array based on weight.

This array contains all the letters from the alphabet and we will get a letter by accessing a random index within the array's limits. However, the "weight" of each letter will be different. The "weight" is simply the number of letters in the array, so if the letter "R" has weight 2, for instance, there are two "R"s in the array. Looking from a probabilistic perspective, the more number you have of a letter, the higher your chance of accessing it.

The code will certainly help explain it. This code should be placed inside GameScreen.as:

1
2
private var _letters:Array = ["A", "A", "A", "B", "C", "D", "E", "E", "E", "F", "G", "H", "I", "I", "I", "J", "K", "L", "M", "N", "O", "O", "O", "P", "Q", "R", "R", "S", "T", "U", "U", "U", "V", "W", "X", "Y", "Z"];
3
4
private function randomLetter():String
5
{
6
	return _letters[int(Math.random() * _letters.length)];
7
}

In line 1, you can see the array of letters. Each vowel has weight 3, which means there are always 3 of them, and the letter "R" has weight 2. This is an extremely simplified array, but a lot more could be done with its idea.

Here's another way of putting it that makes the relative weights clearer:

1
2
private var _letters:Array = [
3
	"A", "A", "A", 
4
	"B", 
5
	"C", 
6
	"D", 
7
	"E", "E", "E", 
8
	"F", 
9
	"G", 
10
	"H", 
11
	"I", "I", "I", 
12
	"J", 
13
	"K", 
14
	"L", 
15
	"M", 
16
	"N", 
17
	"O", "O", "O", 
18
	"P", 
19
	"Q", 
20
	"R", "R", 
21
	"S", 
22
	"T", 
23
	"U", "U", "U", 
24
	"V", 
25
	"W", 
26
	"X", 
27
	"Y", 
28
	"Z"
29
];
30
31
private function randomLetter():String
32
{
33
	return _letters[int(Math.random() * _letters.length)];
34
}

Although not really "visible", you can check the compiled project below:


Step 17: Preloader Create the Graphics

Right now, the base of our game is complete. We will now add a preloader and a game over screen over the next steps. First of all, we need to create the preloader graphics. This will just be a rounded square bar with "Loading" written in it. You can grab the source files to get it.

Loading barLoading barLoading bar

Step 18: Preloader Write the Code

If you are familiar with FlashDevelop, this will not be difficult. We will modify the Preloader class to put our graphics in there. Jumping to the code:

1
2
import ArtAssets.LoadingImage;
3
import flash.display.Sprite;
4
// *** snip ***

5
private var _loadingImage:LoadingImage;
6
private var _loadingMask:Sprite;
7
8
public function Preloader() 
9
{
10
	if (stage) {
11
		stage.scaleMode = StageScaleMode.NO_SCALE;
12
		stage.align = StageAlign.TOP_LEFT;
13
	}
14
	addEventListener(Event.ENTER_FRAME, checkFrame);
15
	loaderInfo.addEventListener(ProgressEvent.PROGRESS, progress);
16
	loaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
17
	
18
	_loadingImage = new LoadingImage();
19
	_loadingImage.x = 275;
20
	_loadingImage.y = 200;
21
	
22
	addChild(_loadingImage);
23
	
24
	_loadingMask = new Sprite();
25
	_loadingMask.x = 75;
26
	_loadingMask.y = 175;
27
	
28
	_loadingImage.mask = _loadingMask;
29
}
30
31
private function progress(e:ProgressEvent):void 
32
{
33
	_loadingMask.graphics.clear();
34
	
35
	_loadingMask.graphics.beginFill(0x000000);
36
	_loadingMask.graphics.drawRect(0, 0, _loadingImage.width * (e.bytesLoaded / e.bytesTotal), 50);
37
	_loadingMask.graphics.endFill();
38
}
39
40
private function loadingFinished():void 
41
{
42
	removeEventListener(Event.ENTER_FRAME, checkFrame);
43
	loaderInfo.removeEventListener(ProgressEvent.PROGRESS, progress);
44
	loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, ioError);
45
	
46
	removeChild(_loadingImage);
47
	
48
	_loadingImage.mask = null;
49
	_loadingImage = null;
50
	
51
	_loadingMask = null;
52
	
53
	startup();
54
}

In the Preloader constructor, we created an instance of the loading image inside the .swc file, as well as a sprite that will be used as a mask. This mask will create the visual representation of the "loading" process.

The progress() function is the key function here: in it we update the mask by creating a rectangle of width e.bytesLoaded / e.bytesTotal times the width of the loading bar image. The bytesLoaded and bytesTotal properties of the ProgressEvent class show us how many bytes from the game have been loaded, and what are the total bytes. That way, by diving them we get the percentage of the game loaded.

In the loadingFinished() function, we have to clear every reference to the loading image and its mask. That way they can be garbage collected and will no longer use the memory reserved for the game.

Take a look at the preloader working!


Step 19: Game Over Screen Create the Graphics

Now we need to work on the game over screen. I wanted it to be very simple, only to show how to add a screen when the game has finished. The graphics are very simple: the same game background with a "Game Over" text and a fading animation. You can see the middle of the animation below:

Game over screenGame over screenGame over screen

Grab the source files to use it!


Step 20: Game Over Screen Write the Code

It is time now to add the game over screen in the game. Before doing that, we will need to have a way to know when the timer reaches 0 (which means game over). In order to do that, a getter function in Timer.as must be created:

1
2
public function get value():int 
3
{
4
	return _value;
5
}

With that, we can now create the GameOverScreen class:

1
2
package  
3
{
4
	import ArtAssets.GameOverScreenImage;
5
	import flash.display.Sprite;
6
	import flash.events.Event;
7
	
8
	public class GameOverScreen extends Sprite
9
	{
10
		private var _image:GameOverScreenImage;
11
		
12
		public function GameOverScreen() 
13
		{
14
			_image = new GameOverScreenImage();
15
			_image.x = 275;
16
			_image.y = 200;
17
			
18
			addChild(_image);
19
			
20
			addEventListener(Event.ENTER_FRAME, update);
21
		}
22
		
23
		public function update(e:Event):void
24
		{
25
			if (_image.currentFrame == _image.totalFrames)
26
			{
27
				_image.stop();
28
			}
29
		}
30
		
31
	}
32
33
}

The code inside update() was created to allow the animation to play only once. That way, the fade in effect will not loop.

Going to Main.as, add this code:

1
2
private var _gameOverScreen:GameOverScreen;
3
4
public function gameOver():void
5
{
6
	removeChild(_gameScreen);
7
	
8
	_gameOverScreen = new GameOverScreen();
9
	
10
	addChild(_gameOverScreen);
11
}

This code will be called by GameScreen when it detects that the game was lost. Now, inside GameScreen.as:

1
2
private function gameLoop(e:Event):void 
3
{
4
	ComboHandler.update();
5
	
6
	_updateTimer += 1 / 30;
7
	
8
	if (_updateTimer >= 1)
9
	{
10
		_updateTimer -= 1;
11
		
12
		_timer.addToTime(-1);
13
	}
14
	
15
	if (_timer.value < 0 && parent)
16
	{
17
		Main(parent).gameOver();
18
	}
19
}

The highlighted lines are the only change to this function. They will detect when the timer has reached less than 0 and whether it still has a parent (which means it wasn't removed by Main yet). At this point, it will call the gameOver() function of Main.

Compile the project, let the timer reach 0 and see what you get:


Conclusion

Great job -- you've created a basic yet full typing game! What's next? I suggest you try making a better timer, adding block letter transitions, and adding more effects.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.