Perfect maze generation with AS3

Read all posts about "" game

I already talked about perfect mazes a couple of years ago with Step by step perfect maze generation with php and Perfect maze generation with Flash actionscript, but now it’s time to make it with AS3 and understand how can we use a perfect maze.

Think about a perfect maze as a maze with no loops.

Apart from the classic game where someone is trapped into a maze filled with enemies and items to collect, it’s not that hard turning a perfect maze into a randomly generated dungeon to make roguelike games.

From Wikipedia: The roguelike genre of computer games is characterized by randomization for replayability, permanent death, ASCII graphics, and turn-based movement. Games are typically dungeon crawls, with many monsters, items, and environment features. Death is frequent and often avoidable. Many roguelikes employ the majority of the keyboard to facilitate interaction with items and the environment. The name of the genre comes from the 1980 game, Rogue.

The script I am going to introduce uses backtracking.

From Wikipedia: Backtracking is a general algorithm for finding all (or some) solutions to some computational problem, that incrementally builds candidates to the solutions, and abandons each partial candidate c (“backtracks”) as soon as it determines that c cannot possibly be completed to a valid solution [1] [2] [3].

Let’s see the code:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	public class as3maze extends Sprite {
		// maze width and height, in cells
		var maze_width=24;
		var maze_height=19;
		// wall size, in pixels
		var wall_size=20;
		// array that will contain maze information
		var maze = new Array();
		// array to keep track of my moves
		var my_moves = new Array();
		// sprite to visually display the maze
		var maze_draw:Sprite = new Sprite();
		public function as3maze() {
			// determining the number of cells in the maze
			var cell_count=maze_width*maze_height;
			// random starting position
			var pos=Math.floor(Math.random()*cell_count);
			// I am on a cell, so I visited one. Let's count visited cells...
			var visited=1;
			for (var i=0; i=0) && (maze[pos-maze_width][0] == 0)) {
					possible=possible+"N";
				}
				// if a move exists, crash a wall && mark new cell as visited     
				if (possible) {
					// increasing number of visited cells
					visited++;
					// saving my position the moves array
					my_moves.push(pos);
					// choosing a random direction
					var way=possible.charAt(Math.floor(Math.random()*possible.length));
					switch (way) {
						case "N" :
							// going north: crashing walls and updating position
							maze[pos][1]=0;
							maze[pos-maze_width][2]=0;
							pos-=maze_width;
							break;
						case "S" :
							// going south: crashing walls and updating position
							maze[pos][2]=0;
							maze[pos+maze_width][1]=0;
							pos+=maze_width;
							break;
						case "E" :
							// going east: crashing walls and updating position
							maze[pos][3]=0;
							maze[pos+1][4]=0;
							pos++;
							break;
						case "W" :
							// going west: crashing walls and updating position
							maze[pos][4]=0;
							maze[pos-1][3]=0;
							pos--;
							break;
					}
					// set the cell as visited
					maze[pos][0]=1;
					// if I cannot movie anymore, backtrack to a previously saved cell
				} else {
					pos=my_moves.pop();
				}
			}
			// start of maze drawing routine
			addChild(maze_draw);
			// black line
			maze_draw.graphics.lineStyle(1);
			maze_draw.graphics.moveTo(10,10);
			var start_y=10-wall_size;
			var start_x=0;
			// drawing walls: I only draw east and south walls, because a cell's south wall is southern cell's north wall
			// and same thing for the east/west ones
			for (i=0; i

and this is the result:

Next time I'll show you how to turn a maze into a dungeon.

Download the source code.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers