Skip to content

Instantly share code, notes, and snippets.

@mlhaufe mlhaufe/Maze.ts
Created Jun 21, 2018

Embed
What would you like to do?
TypeScript Command Pattern example for CLJS: <https://groups.google.com/forum/#!topic/comp.lang.javascript/N8jA1Blh9LY>
abstract class Command {
abstract execute(): void
}
abstract class UndoableCommand extends Command {
abstract undo(): void
}
class Direction {
static readonly UP = 0
static readonly RIGHT = 90
static readonly DOWN = 180
static readonly LEFT = 270
constructor(readonly angle: number) { }
// ... other methods ellided for clarity
opposite(): Direction {
return new Direction((this.angle + 180) % 360)
}
}
/**
* A class representing a Maze game
* where your moves can be undone
*/
class Maze {
// A "stack" of commands for history tracking
protected _commands: Command[]
//... methods for defining maze parts and rendering ellided for clarity
move(direction: Direction): void {
// ellided for clarity
}
protected _doCommand(command: Command) {
if (command) {
this._commands.push(command)
command.execute()
}
}
protected _undoCommand() {
if (this._commands.length) {
let top = this._commands[this._commands.length - 1]
if (top instanceof UndoableCommand) {
this._commands.pop()
top.undo()
}
}
}
}
// Define an undoable command
class MazeMove extends UndoableCommand {
constructor(
readonly maze: Maze,
readonly direction: Direction
) { super() }
execute(): void {
this.maze.move(this.direction)
}
undo(): void {
this.maze.move(this.direction.opposite())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.