Talking about Perfect Square! game, Game development, HTML5, Javascript, Phaser and TypeScript.
Finally, after a long tutorial series about the migration from JavaScript to TypeScript, we are ready to start building games again.
If you want more information about the migration from JavaScript to TypeScript, check steps 1, 2, 3 and 4.
The first game we port from JavaScript to TypeScript is Perfect Square!, which has been already built with Phaser 2 and 3.
This is the game we are going to build:
Tap and hold to make the square grow, release to drop it. Don’t make it fall down the hole or hit the ground. There are also in-game instructions.
To ensure a maximum code reusability, the source code is split in 10 TypeScript files and one HTML file. Let’s analyse them one by one:
index.html
It’s the webpage which hosts the game, it only has a little CSS code, a div
element where the game will run, then main.ts
is called.
<!DOCTYPE html>
<html>
<head>
<style type = "text/css">
body {
background: #000000;
padding: 0px;
margin: 0px;
}
</style>
</head>
<body>
<div id = "thegame"></div>
<script src = "scripts/main.ts"></script>
</body>
</html>
main.ts
It’s the main TypeScript file, built to be reused as it only initializes the game.
import Phaser from 'phaser';
import { ScaleObject } from './scaleObject';
import { PreloadAssets } from './preloadAssets';
import { PlayGame} from './playGame';
const configObject: Phaser.Types.Core.GameConfig = {
type: Phaser.AUTO,
scale: ScaleObject,
scene: [PreloadAssets, PlayGame]
}
new Phaser.Game(configObject);
scaleObject.ts
Another file which can be reused, it just contains the scale manager configuration
export const ScaleObject : Phaser.Types.Core.ScaleConfig = {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
parent: 'thegame',
width: 640,
height: 960
}
preloadAssets.ts
This is the scene which preloads all assets. Can be reused too.
export class PreloadAssets extends Phaser.Scene {
constructor() {
super({
key: 'PreloadAssets'
});
}
preload() {
this.load.image('base', 'assets/base.png');
this.load.image('square', 'assets/square.png');
this.load.image('top', 'assets/top.png');
this.load.bitmapFont('font', 'assets/font.png', 'assets/font.fnt');
}
create() {
this.scene.start('PlayGame');
}
}
playGame.ts
The game itlself. Check for Perfect Square! built with modern JavaScript to see the differences between JavaScript and TypeScript.
import { GameOptions } from './gameOptions';
import { GameModes } from './gameModes';
import { GameTexts } from './gameTexts';
import GameWall from './gameWall';
import SquareText from './squareText';
import PlayerSquare from './playerSquare';
export class PlayGame extends Phaser.Scene {
saveData: any;
leftSquare: GameWall;
rightSquare: GameWall;
leftWall: GameWall;
rightWall: GameWall;
square: PlayerSquare;
squareText: SquareText;
infoGroup: Phaser.GameObjects.Group;
levelText: Phaser.GameObjects.BitmapText;
squareTweenTargets:any[];
currentGameMode: number = GameModes.IDLE;
gameWidth: number;
gameHeight: number;
growTween: Phaser.Tweens.Tween;
rotateTween: Phaser.Tweens.Tween;
constructor() {
super({
key: 'PlayGame'
});
}
create(): void {
this.gameWidth = this.game.config.width as number;
this.gameHeight = this.game.config.height as number;
this.saveData = localStorage.getItem(GameOptions.localStorageName) == null ? { level: 1} : JSON.parse(localStorage.getItem(GameOptions.localStorageName) as string);
let tintColor = Phaser.Utils.Array.GetRandom(GameOptions.bgColors);
this.cameras.main.setBackgroundColor(tintColor);
this.placeWalls();
this.square = new PlayerSquare(this, this.gameWidth / 2, -400, 'square');
this.add.existing(this.square);
this.squareText = new SquareText(this, this.square.x, this.square.y, 'font', this.saveData.level, 120, tintColor);
this.add.existing(this.squareText);
this.squareTweenTargets = [this.square, this.squareText];
this.levelText = this.add.bitmapText(this.gameWidth / 2, 0, 'font', 'level ' + this.saveData.level, 60);
this.levelText.setOrigin(0.5, 0);
this.updateLevel();
this.input.on('pointerdown', this.grow, this);
this.input.on('pointerup', this.stop, this);
}
placeWalls(): void {
this.leftSquare = new GameWall(this, 0, this.gameHeight, 'base', new Phaser.Math.Vector2(1, 1));
this.add.existing(this.leftSquare);
this.rightSquare = new GameWall(this, this.gameWidth, this.gameHeight, 'base', new Phaser.Math.Vector2(0, 1));
this.add.existing(this.rightSquare);
this.leftWall = new GameWall(this, 0, this.gameHeight - this.leftSquare.height, 'top', new Phaser.Math.Vector2(1, 1));
this.add.existing(this.leftWall);
this.rightWall = new GameWall(this, this.gameWidth, this.gameHeight - this.leftSquare.height, 'top', new Phaser.Math.Vector2(0, 1));
this.add.existing(this.rightWall);
}
updateLevel(): void {
let holeWidth = Phaser.Math.Between(GameOptions.holeWidthRange[0], GameOptions.holeWidthRange[1]);
let wallWidth = Phaser.Math.Between(GameOptions.wallRange[0], GameOptions.wallRange[1]);
this.leftSquare.tweenTo((this.gameWidth - holeWidth) / 2);
this.rightSquare.tweenTo((this.gameWidth + holeWidth) / 2);
this.leftWall.tweenTo((this.gameWidth - holeWidth) / 2 - wallWidth);
this.rightWall.tweenTo((this.gameWidth + holeWidth) / 2 + wallWidth);
this.tweens.add({
targets: this.squareTweenTargets,
y: 150,
scaleX: 0.2,
scaleY: 0.2,
angle: 50,
duration: 500,
ease: 'Cubic.easeOut',
callbackScope: this,
onComplete: function() {
this.rotateTween = this.tweens.add({
targets: this.squareTweenTargets,
angle: 40,
duration: 300,
yoyo: true,
repeat: -1
});
if (this.square.successful == 0) {
this.addInfo(holeWidth, wallWidth);
}
this.currentGameMode = GameModes.WAITING;
}
})
}
grow(): void {
if (this.currentGameMode == GameModes.WAITING) {
this.currentGameMode = GameModes.GROWING;
if (this.square.successful == 0) {
this.infoGroup.toggleVisible();
}
this.growTween = this.tweens.add({
targets: this.squareTweenTargets,
scaleX: 1,
scaleY: 1,
duration: GameOptions.growTime
});
}
}
stop(): void {
if (this.currentGameMode == GameModes.GROWING) {
this.currentGameMode = GameModes.IDLE;
this.growTween.stop();
this.rotateTween.stop();
this.rotateTween = this.tweens.add({
targets: this.squareTweenTargets,
angle: 0,
duration:300,
ease: 'Cubic.easeOut',
callbackScope: this,
onComplete: function(){
if (this.square.displayWidth <= this.rightSquare.x - this.leftSquare.x) {
this.tweens.add({
targets: this.squareTweenTargets,
y: this.gameHeight + this.square.displayWidth,
duration:600,
ease: 'Cubic.easeIn',
callbackScope: this,
onComplete: function(){
this.levelText.text = 'Oh no!!!';
this.gameOver();
}
})
}
else{
if (this.square.displayWidth <= this.rightWall.x - this.leftWall.x) {
this.fallAndBounce(true);
}
else{
this.fallAndBounce(false);
}
}
}
})
}
}
fallAndBounce(success: Boolean): void {
let destY = this.gameHeight - this.leftSquare.displayHeight - this.square.displayHeight / 2;
let message = success ? GameTexts.success : GameTexts.failure;
if (success) {
this.square.successful ++;
}
else {
destY = this.gameHeight - this.leftSquare.displayHeight - this.leftWall.displayHeight - this.square.displayHeight / 2;
}
this.tweens.add({
targets: this.squareTweenTargets,
y: destY,
duration:600,
ease: 'Bounce.easeOut',
callbackScope: this,
onComplete: function() {
this.levelText.text = message;
if (!success) {
this.gameOver();
}
else{
this.time.addEvent({
delay: 1000,
callback: function() {
if (this.square.successful == this.saveData.level) {
this.saveData.level ++;
localStorage.setItem(GameOptions.localStorageName, JSON.stringify({
level: this.saveData.level
}));
this.scene.start('PlayGame');
}
else {
this.squareText.updateText(this.saveData.level - this.square.successful);
this.levelText.text = 'level ' + this.saveData.level;
this.updateLevel();
}
},
callbackScope: this
});
}
}
})
}
addInfo(holeWidth: number, wallWidth: number): void {
this.infoGroup = this.add.group();
let targetSquare = this.add.sprite(this.gameWidth / 2, this.gameHeight - this.leftSquare.displayHeight, 'square');
targetSquare.displayWidth = holeWidth + wallWidth;
targetSquare.displayHeight = holeWidth + wallWidth;
targetSquare.alpha = 0.3;
targetSquare.setOrigin(0.5, 1);
this.infoGroup.add(targetSquare);
let targetText = this.add.bitmapText(this.gameWidth / 2, targetSquare.y - targetSquare.displayHeight - 20, 'font', GameTexts.landHere, 48);
targetText.setOrigin(0.5, 1);
this.infoGroup.add(targetText);
let holdText = this.add.bitmapText(this.gameWidth / 2, 250, 'font', GameTexts.infoLines[0], 40);
holdText.setOrigin(0.5, 0);
this.infoGroup.add(holdText);
let releaseText = this.add.bitmapText(this.gameWidth / 2, 300, 'font', GameTexts.infoLines[1], 40);
releaseText.setOrigin(0.5, 0);
this.infoGroup.add(releaseText);
}
gameOver(): void {
this.time.addEvent({
delay: 1000,
callback: function() {
this.scene.start('PlayGame');
},
callbackScope: this
});
}
}
gameOptions.ts
Game options which can be changed to tune the gameplay are stored in a separate module, ready to be reused.
export const GameOptions = {
bgColors: [0x62bd18, 0xff5300, 0xd21034, 0xff475c, 0x8f16b2, 0x588c7e, 0x8c4646],
holeWidthRange: [80, 260],
wallRange: [10, 50],
growTime: 1500,
localStorageName: 'squaregamephaser3'
}
gameModes.ts
Game modes too are stored in a separate module.
export const GameModes = {
IDLE: 0,
WAITING: 1,
GROWING: 2
}
gameTexts.ts
In-game dynamic text messages have been stored in a separate module, ready to be reused.
export const GameTexts = {
level: 'level',
infoLines: ['tap and hold to grow', 'release to drop'],
landHere: 'land here',
success: 'Yeah!!!',
failure: 'On no!!'
}
gameWall.ts
This is the class which handles game walls. Game walls only tween to become bigger or smaller.
export default class GameWall extends Phaser.GameObjects.Sprite {
constructor(scene: Phaser.Scene, x: number, y: number, key: string, origin: Phaser.Math.Vector2) {
super(scene, x, y, key);
this.setOrigin(origin.x, origin.y);
}
tweenTo(x: number): void {
this.scene.tweens.add({
targets: this,
x: x,
duration: 500,
ease: 'Cubic.easeOut'
});
}
}
squareText.ts
It’s the dynamic text inside the square telling us how many drops we need to finish the level.
export default class SquareText extends Phaser.GameObjects.BitmapText {
constructor(scene: Phaser.Scene, x: number, y: number, font: string, text: string, size: number, tintColor: number) {
super(scene, x, y, font, text, size);
this.setOrigin(0.5);
this.setScale(0.4);
this.setTint(tintColor);
}
updateText(text: string) {
this.setText(text);
}
}
playerSquare.ts
The square we control
export default class PlayerSquare extends Phaser.GameObjects.Sprite {
successful: number;
constructor(scene: Phaser.Scene, x: number, y: number, key: string) {
super(scene, x, y, key);
this.successful = 0;
this.setScale(0.2);
}
}
I did not comment the scripts because they are basically the porting from this JavaScript prototype, it’s just an example to show you how easy is to code with TypeScript and how keeping modules separate allows us to reuse some of the code.
Download the source code of the entire project.
Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.