Video icon 64
Learning to code? Skill up faster with our practical video courses. Start your free trial today.
Advertisement

Create a Flash "Alphabet Soup" Wordsearch Game

by

Today I'll show you how to create a simple wordsearch with a neat "highlighter" interface, which is easy to modify with your own words and layout. We'll be using Flash and AS3. Read on!


Final Result Preview

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


Step 1: Brief Overview

In this tutorial we'll use a series of ActionScript classes to create a classic Alphabet Soup wordsearch game. The objective of the game is to highlight letters to form a word. You will be able to create your own alphabet soup and include your own words.


Step 2: Flash Document Settings

Open Flash and create a 320x480px document. Set the Frame rate to 24fps.


Step 3: Interface

A simple orange interface will be used, featuring several shapes, buttons and MovieClips; continue to the next steps to build this GUI.


Step 4: Background

This background was created in Flash using simple rectangle shapes. The hex color for the orange is #EE923F.


Step 5: Title


To create the Title, first select the Text Tool (T), change the color to #EEEEEE, and write your title text. Then, duplicate the textfield (Cmd+ D), change the color to #C97B35, and send the new textfield backwards to create the letterpress effect.


Step 6: Buttons

Use again the Text Tool to create two buttons as shown in the image above. Convert them to buttons and give them descriptive instance names to easily use them later in the code. Convert the graphics in stage to a single MovieClip and name it TitleView - remember to check the Export for ActionScript box.


Step 7: Game Screen


This is the Game Screen - well, its background, as everything in this screen will be created dynamically using ActionScript 3.


Step 8: About Screen


The About screen will appear in front of the Title Screen; use the graphics and fonts used before to lay it out. Name it AboutView and remember to check the Export for ActionScript box.


Step 9: Alert


An alert will be shown when all the words are found, it will display a game over message and instructions. Use the Rectangle Tool to create it and set its instance name to AlertView, . Again mark the Export for ActionScript box.


Step 10: Sounds

We'll use sound effects to enhance the feeling of the game. You can find the sound used in this example in Soungle.com using the keyword bell.


Step 11: TweenNano

We'll use a different tween engine from the default included in flash, this will increase performace as well as it is easier to use.

You can download TweenNano from its official website.


Step 12: Set Document Class


We'll make our application interactive by using an external class. Add its name (Main) to the Class field in the Publish section of the Properties panel to associate the FLA with the Main document class.


Step 13: Create a New Class


Create a new (Cmd + N) ActionScript 3.0 Class and save it as Main.as in your class folder. This will be the document class.


Step 14: Class Structure

Create your basic class structure to begin writing your code.

 
package  
{ 
	import flash.display.Sprite; 
	 
	public class Main extends Sprite 
	{ 
		public function Main():void 
		{ 
			// constructor code 
		} 
	} 
}

Step 15: Required Classes

These are the classes we'll need to import for our class to work. The import directive makes externally defined classes and packages available to your code.

 
import flash.display.Sprite; 
import flash.text.TextField; 
import flash.text.TextFormat; 
import flash.text.TextFieldAutoSize; 
import flash.display.Shape; 
import flash.events.MouseEvent; 
import flash.display.MovieClip; 
import com.greensock.TweenNano; 
import com.greensock.easing.Bounce; 
import flash.net.navigateToURL; 
import flash.net.URLRequest;

Step 16: Variables

These are the variables we'll use; read the comments in the code to know more about them. Some of their names are self explaining so there will be no comment there.

 
private var titleView:TitleView = new TitleView(); 
private var about:AboutView; 
//words to find 
private const L1:Vector.<String> = new <String>['CLASS', 'PUBLISH', 'DEFAULT', 'SETTINGS', 'FLASH'];  
//Used to position the words in the stage 
private const L1Map:Array = [[0, 0, 'C', 0, 0, 0, 0, 0, 0, 0], 
                            [0, 0, 'L', 0, 0, 0, 0, 0, 0, 0], 
                            [0, 0, 'A', 0, 0, 0, 0, 0, 0, 'S'], 
                            [0, 0, 'S', 0, 0, 0, 0, 0, 0, 'E'], 
                            [0, 0, 'S', 0, 0, 0, 0, 0, 0, 'T'], 
                            [0, 0, 0, 0, 0, 0, 0, 0, 'F', 'T'], 
                            ['D', 'E', 'F', 'A', 'U', 'L', 'T', 0, 'L', 'I'], 
                            [0, 0, 0, 0, 0, 0, 0, 0, 'A', 'N'], 
                            [0, 0, 0, 0, 0, 0, 0, 0, 'S', 'G'], 
                            [0, 0, 'P', 'U', 'B', 'L', 'I', 'S', 'H', 'S'], 
                            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
                            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]; 
 
private var alphabet:Vector.<String> = new <String>['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; 
private var soupFmt:TextFormat = new TextFormat('Arial', 19, 0x666666); 
private var wordsFmt:TextFormat = new TextFormat('Arial', 12, 0xEEEEEE); 
private var wordsList:TextField = new TextField(); 
private var line:Shape = new Shape(); 
private var tfs:MovieClip = new MovieClip(); 
private var bell:Bell = new Bell(); 
private var correct:int = 0; //number of words found so far

Step 17: Constructor

The constructor is a function that runs when an object is created from a class, this code is the first to execute when you make an instance of an object, or runs when the FLA is loaded if part of the Document Class.

It calls the necessary functions to start the game. Check those functions in the next steps.

 
public final function Main():void 
{ 
	//Code 
}

Step 18: Add Title View

We start by adding the TitleView from the Library to the stage.

 
addChild(titleView);

Step 19: Add Button Listeners

This will add the mouse listeners to the buttons in the title view, which will take us to the game or credits screen.

 
private final function startButtonListeners(action:String = 'add'):void 
{ 
	if(action == 'add') 
	{ 
		titleView.aboutBtn.addEventListener(MouseEvent.MOUSE_UP, showCredits); 
		titleView.startBtn.addEventListener(MouseEvent.MOUSE_UP, showGameView); 
	} 
	else 
	{ 
		titleView.aboutBtn.removeEventListener(MouseEvent.MOUSE_UP, showCredits); 
		titleView.startBtn.removeEventListener(MouseEvent.MOUSE_UP, showGameView); 
	} 
}

Step 20: Show Credits

The Credits screen is shown when the user clicks the credits button; a mouse listener is added to the full MovieClip to remove it.

 
private final function showCredits(e:MouseEvent):void 
{ 
	titleView.aboutBtn.visible = false; 
	titleView.startBtn.visible = false; 
	about = new AboutView(); 
	about.y = stage.stageHeight + about.height; 
	addChild(about); 
	TweenNano.to( 
         about,  
         0.3,  
         { 
          y:stage.stageHeight-about.height, 
          onComplete:function():void{ 
           about.addEventListener(MouseEvent.MOUSE_UP, hideCredits); 
          } 
         } 
        ); 
}

Step 21: Hide Credits

When the Credits screen is clicked it will be tweened back and removed from the stage.

 
private final function hideCredits(e:MouseEvent):void 
{ 
	TweenNano.to( 
         about,  
         0.3,  
         { 
          y:stage.stageHeight+about.height,  
          onComplete:function():void{ 
           titleView.aboutBtn.visible = true;  
           titleView.startBtn.visible = true;  
           about.removeEventListener(MouseEvent.MOUSE_UP, hideCredits);  
           removeChild(about);  
           about = null; 
          } 
         } 
        ); 
}

Step 22: Show Game View

The following lines remove the Title screen and leave the Game screen visible. It also calls the necessary functions to start the game - we'll add these functions in the next steps.

 
private final function showGameView(e:MouseEvent):void 
{ 
	TweenNano.to( 
         titleView,  
         0.3,  
         { 
          y:-titleView.height, 
          onComplete:function():void{ 
           startButtonListeners('rmv'); 
           removeChild(titleView);  
           titleView = null; 
          } 
         } 
        ); 
	buildSoup(); 
	gameListeners('add'); 
}

Let's stop here to do a quick test and make sure that our game code is working:

Keep in mind that some lines have been commented out as some functions haven't been created yet.

Remember that the Milestone files are included in the source download, so if for some reason your file doesn't mimic this one take a look at the source to see what can be causing that.


Step 23: Game Listeners

This function adds the mouse listeners required to draw the line that will highlight the letters.

 
private final function gameListeners(action:String):void 
{ 
	if(action == 'add') 
	{ 
		stage.addEventListener(MouseEvent.MOUSE_DOWN, startDraw); 
		stage.addEventListener(MouseEvent.MOUSE_UP, detectLetters); 
	} 
	else 
	{ 
		stage.removeEventListener(MouseEvent.MOUSE_DOWN, startDraw); 
		stage.removeEventListener(MouseEvent.MOUSE_UP, detectLetters); 
	} 
}

Step 24: Build Soup

One of the most important functions in the game. It will create and position the characters to build the alphabet soup. We'll code its behavior over the next few steps.

 
private final function buildSoup():void 
{ 
	//Code... 
}

Step 25: Create Character TextFields

Nested for-loops are used to read the multidimensional array; a TextField is created for every element found and a position is given to that textfield.

 
for(var i:int = 0; i < 10; i++) 
{ 
	for(var j:int = 0; j < 12; j++) 
	{ 
		var tf:TextField = new TextField(); 
		tf.width = 22; 
		tf.height = 22; 
		tf.defaultTextFormat = soupFmt; 
		tf.selectable = false; 
		tf.x = 10 + (31.3 * i); 
		tf.y = 10 + (35 * j)

Step 26: Display Random Character

The words are already set in the original letters array, so the following code will change the 0s to random characters obtained from the Alphabet array. As this only changes the 0s the original characters will not be changed.

 
                        /* Change 0's to Random Letters */ 
			 
			if(L1Map[j][i] == 0) 
			{ 
				L1Map[j][i] = alphabet[Math.floor(Math.random() * alphabet.length)]; 
			} 
			 
			tf.text = L1Map[j][i]; 
			 
			addChild(tfs); 
			tfs.addChild(tf); 
		}

Step 27: Add Words List TextField

This TextField shows the words to find, it is placed at the bottom of the stage.

 
	/* Add Words List */ 
	 
	wordsList.selectable = false; 
	wordsList.x = 5; 
	wordsList.y = 430; 
	wordsList.autoSize = TextFieldAutoSize.LEFT; 
	wordsList.defaultTextFormat = wordsFmt;

Step 28: List Words

In order to correctly display the words from the array we can cast it to a string, but we need to remove the commas that are added automatically.

 
	/* Remove ',' */ 
	 
	var string:String = ''; 
	for(var k:int = 0; k < L1.length; k++) 
	{ 
		string += String(String(L1[k]).replace(',', '')) + '   '; 
	} 
	 
	wordsList.text = string; 
	addChild(wordsList);

This concludes the buildSoup() function.


Step 29: Start Selection Line

The selection line will start drawing when the user clicks on the stage; this function creates the shape and adds a listener to follow the mouse movement.

 
private final function startDraw(e:MouseEvent):void 
{ 
	line = new Shape(); 
	addChild(line); 
	 
	line.graphics.moveTo(mouseX, mouseY); 
	line.graphics.lineStyle(16, 0xFF8E2A, 0.4); 
	stage.addEventListener(MouseEvent.MOUSE_MOVE, drawLine); 
}

Step 30: Draw Selection Line

The next code draws the line in the direction of the mouse.

 
private final function drawLine(e:MouseEvent):void 
{ 
	line.graphics.lineTo(mouseX, mouseY); 
}

Let's stop here to do a quick test and make sure that our game code is working:

It draws the line, but doesn't stop. We'll deal with that in the next step.

Keep in mind that some lines have been commented as some functions haven't been created yet.

Remember that the Milestones are included in the source files, so if for some reason your file doesn't mimic this one take a look at the source to see what could be causing that.


Step 31: Detect Letters Function

When the mouse button is up, the draw method stops and the code to detect the highlighted words runs. I explain this code in the next steps.

 
private final function detectLetters(e:MouseEvent):void 
{

Step 32: Get Selected Letters

To detect the highlighted characters we create a string variable that will store the TextFields that are hit by the selection line.

 
	/* Get selected letters */ 
	 
	var selectedWord:String = ''; 
	 
	for(var i:int = 0; i < tfs.numChildren; i++) 
	{ 
		if(line.hitTestObject(tfs.getChildAt(i))) 
		{ 
			selectedWord += (tfs.getChildAt(i) as TextField).text; 
		} 
	}

Step 33: Check Whether Word is on List

Next we compare the result to every word in the predefined array; if the word is found a sound is played, the correct variable gets incremented, and the word changes its color in the bottom bar.

 
	/* Check if word is on list */ 
	 
	for(var j:int = 0; j < L1.length; j++) 
	{ 
		if(selectedWord == L1[j]) 
		{ 
			wordsList.htmlText = wordsList.htmlText.replace( 
			 selectedWord,  
			 "<font color='#FF8E2A'>" + selectedWord + "</font>" 
			); 
			bell.play(); 
			correct++; 
		} 
	}

Step 34: Check for Game Over

This code calls and alert when all the words are found.

 
	if(correct == L1.length) 
	{ 
		alert(); 
	}

Step 36: Alert

This function will stop the game and show the game over message, it also adds a mouse listener to reset the game when clicked.

 
private final function alert():void 
{ 
	gameListeners('rm'); 
	 
	var alert:AlertView = new AlertView(); 
	addChild(alert); 
	alert.addEventListener(MouseEvent.MOUSE_UP, restart);//or next level! 
	TweenNano.from(alert.messageBox, 0.5, {y: -alert.messageBox.height, ease:Bounce.easeOut}); 
}

This concludes the detectLetters() function.


Step 37: Restart Function

The next function will reload the SWF, resetting any variables and methods and returning to the first screen.

 
private final function restart(e:MouseEvent):void 
{ 
	navigateToURL(new URLRequest(stage.loaderInfo.url), '_level0'); 
}

Step 38: Test Game

We are now ready to test our game and see if everything works as expected.


Step 39: Change Word List

You can change the word list by simply changing this line in the code:

 
private const L1:Vector.<String> = new <String>['CLASS', 'PUBLISH', 'DEFAULT', 'SETTINGS', 'FLASH']; //Words to find

This will only change the list of words that the code should detect; to make the words actually appear in the alphabet soup read the next step.


Step 40: Change Map Arrays

The Alphabet soup is created based on this 10x12 map array. Simply change the letters to the desired ones to add and position the words and use 0s for everything else. The quotes may make the process difficult so I recommend writting the characters only at first and then adding the quotes when the map is ready.

 
private const L1Map:Array = [[0, 0, 'C', 0, 0, 0, 0, 0, 0, 0], 
                             [0, 0, 'L', 0, 0, 0, 0, 0, 0, 0], 
                             [0, 0, 'A', 0, 0, 0, 0, 0, 0, 'S'], 
                             [0, 0, 'S', 0, 0, 0, 0, 0, 0, 'E'], 
                             [0, 0, 'S', 0, 0, 0, 0, 0, 0, 'T'], 
                             [0, 0, 0, 0, 0, 0, 0, 0, 'F', 'T'], 
                             ['D', 'E', 'F', 'A', 'U', 'L', 'T', 0, 'L', 'I'], 
                             [0, 0, 0, 0, 0, 0, 0, 0, 'A', 'N'], 
                             [0, 0, 0, 0, 0, 0, 0, 0, 'S', 'G'], 
                             [0, 0, 'P', 'U', 'B', 'L', 'I', 'S', 'H', 'S'], 
                             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
                             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]];

Conclusion

Create your own alphabet soups using the map array above.

I hope you liked this tutorial, thank you for reading!

Advertisement