Understanding Phaser array utilities using ArrayUtils class

Since Phaser is mainly a HTML5 framework, you may think you can use it to draw, animate and tween stuff on canvas to create your games, while other kind of routines like array management must be scripted directly with pure JavaScript.

It’s not true, because Phaser comes with some interesting utilities which will help you during the creation and the manipulation of arrays, handling some commons operations such as array population, picking a random array item, and some other interesting stuff we are going to see in this post.

The class responsible of array operations is ArrayUtils, and you can find the official docs at this page, however I found this class very interesting so I decided to write a more detailed guide.

We start with the creation of an empty array called testArray:

var testArray = [];

Launching a console.log of the array, we get:

[]

Now that we have an empty array, let’s see what can we do with it.

POPULATING ARRAYS

With numberArray(start, end) we can populate the array with the inclusive range of numbers from start to end, determined increasing start by one.

testArray = Phaser.ArrayUtils.numberArray(0, 10);

This way we get 11 items in the array, with integer numbers from 0 to 10, both included

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

What if we pass non integers arguments?

testArray = Phaser.ArrayUtils.numberArray(0.5, 10);

While start is included, this time end is not included and the array ends with the highest number lower than end:

[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]

What if start and end have the same value?

testArray = Phaser.ArrayUtils.numberArray(10, 10);

We’ll have an array with one item:

[10]

What if start is greater than end?

testArray = Phaser.ArrayUtils.numberArray(10, 0);

We’ll have an rmpty array:

[]

numberArrayStep is a bit more complete than numberArray because it allows us to define a step during the creation of the array, so if we want start to be greater than end, for example, we just have to write:

testArray = Phaser.ArrayUtils.numberArrayStep(10, 0, -1);

Look, this time is not inclusive:

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

end is never included in the generated array in using numberArrayStep:

testArray = Phaser.ArrayUtils.numberArrayStep(0, 20, 2);

look, there’s no 20 in the array

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

You can also use float numbers:

testArray = Phaser.ArrayUtils.numberArrayStep(0, 20, 1.5);

and you’ll get:

[0, 1.5, 3, 4.5, 6, 7.5, 9, 10.5, 12, 13.5, 15, 16.5, 18, 19.5]

Just remember JavaScript has some inaccuracy with float numbers, and this code:

testArray = Phaser.ArrayUtils.numberArrayStep(0.5, 1, 0.1);

Won’t return the result you may expect:

[0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999]

Also, both numberArray and numberArrayStep methods do not add items to an array but they actually create an array with such items, so these two lines of code:

testArray = Phaser.ArrayUtils.numberArray(1, 10);
testArray = Phaser.ArrayUtils.numberArray(11, 20);

Will return:

[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

You can also create multi-dimensional arrays, such as:

testArray = [Phaser.ArrayUtils.numberArray(1, 10), Phaser.ArrayUtils.numberArray(11, 20), Phaser.ArrayUtils.numberArray(21, 30)];

Which will return

[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [21, 22, 23, 24, 25, 26, 27, 28, 29, 30]]

SHUFFLING ARRAYS

To shuffle an array, shuffle method will apply the Fisher-Yates algorithm to return the shuffled array. The Fisher–Yates shuffle is an algorithm for generating a random permutation of a finite set. In plain terms, the algorithm shuffles the set and you can find a lot of interesting information in this Wikipedia page.

Long story short, it’s a good way to shuffle arrays, here it is:

testArray = Phaser.ArrayUtils.numberArray(1, 10);
Phaser.ArrayUtils.shuffle(testArray);

And the result is the shuffled array.

[1, 3, 2, 4, 7, 5, 9, 8, 10, 6]

Results vary each time you call shuffle method

shuffle is also not recursive, so it will work partially when shuffling multi-dimensional arrays:

testArray = [Phaser.ArrayUtils.numberArray(1, 10), Phaser.ArrayUtils.numberArray(11, 20), Phaser.ArrayUtils.numberArray(21, 30)];
Phaser.ArrayUtils.shuffle(testArray);

Will return something like

[[11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [21, 22, 23, 24, 25, 26, 27, 28, 29, 30]]

Where inner arrays aren’t shuffled.

PICKING RANDOM ITEMS FROM ARRAYS

When we need to pick random items from an array, Phaser gives us two opportunities: we can simply pick a random item or we can pick a random item and remove it from the array.

getRandomItem method will return a random item in the array

testArray = Phaser.ArrayUtils.numberArray(1, 10);
var item = Phaser.ArrayUtils.getRandomItem(testArray);

this code once execute will store into item variable a random testArray item.

We can also specify another argument which is the start index

testArray = Phaser.ArrayUtils.numberArray(1, 10);
var item = Phaser.ArrayUtils.getRandomItem(testArray, 9);

now item will be null if the random item is one of the first 8 items in the array (numbers from 1 to 9), or a random item from the 9th on, which in this case can only be 10.

The last argument we can specify is the number of values we want to randomly select.

testArray = Phaser.ArrayUtils.numberArray(1, 10);
var item = Phaser.ArrayUtils.getRandomItem(testArray, 2, 3);

in this case item will be the item with index greater or equal to 2 chosen among the three items with index 2, 3 and 4.

removeRandomItem works in the same way as getRandomItem but it also removes the item from the array

testArray = Phaser.ArrayUtils.numberArray(1, 10);
var item = Phaser.ArrayUtils.removeRandomItem(testArray);

if item is 4, then testArray will be [1, 2, 3, 5, 6, 7, 8, 9, 10]

removeRandomItem accepts the same extra arguments as getRandomItem working in the same way, and both getRandomItem and removeRandomItem do not work recursively on multi-dimensional arrays, so

testArray = [Phaser.ArrayUtils.numberArray(1, 10), Phaser.ArrayUtils.numberArray(11, 20)];
var item = Phaser.ArrayUtils.removeRandomItem(testArray);

will return for example item as an array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and testArray as the remaining array [[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]]

FINDING ITEMS

If you have a sorted array, you can find the closest item to a value with findClosest method.

testArray = Phaser.ArrayUtils.numberArray(1, 10);
var item = Phaser.ArrayUtils.findClosest(5, testArray);

Will return 5 while

testArray = Phaser.ArrayUtils.numberArray(1, 10);
var item = Phaser.ArrayUtils.findClosest(5.6, testArray);

will return 6

ROTATING ARRAYS

Arrays can also be rotated with rotateLeft and rotateRight methods.

testArray = Phaser.ArrayUtils.numberArray(1, 5);
var item = Phaser.ArrayUtils.rotateLeft(testArray);

At the end of the script, testArray from [1, 2, 3, 4, 5] will be [2, 3, 4, 5, 1] and item will be 1.

Following the same concept, with

testArray = Phaser.ArrayUtils.numberArray(1, 5);
var item = Phaser.ArrayUtils.rotateRight(testArray);

Will make the array be [5, 1, 2, 3, 4] and item to be 5

ROTATING TWO DIMENSIONAL ARRAYS

This is by far the most interesting feature of ArrayUtils class as it works on two-dimensional arrays. A two-dimensional array is also called a Matrix. With rotateMatrix method we can rotate a two-dimensional array of an angle of 90, 180 or 270 degrees.

testArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
testArray = Phaser.ArrayUtils.rotateMatrix(testArray, 90);

will change testArray from

[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

to

[
[3, 6, 9],
[2, 5, 8],
[1, 4, 7]
]

actually rotating it counter clockwise

testArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
testArray = Phaser.ArrayUtils.rotateMatrix(testArray, 180);

will change testArray from

[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

to

[
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]

flipping it horizontally and vertically and

testArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
testArray = Phaser.ArrayUtils.rotateMatrix(testArray, 270);

will change testArray from

[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

to

[
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]

actually rotating it clockwise.

Finally transposeMatrix method will transpose the two-dimensional array:

testArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
testArray = Phaser.ArrayUtils.transposeMatrix(testArray);

and testArray will change from

[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

to

[
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
]

Basically rows become columns and columns become row.

I hope you will find all these methods useful in your projects.

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