Add game ticks

master
Talon 2021-11-04 23:55:56 +01:00
parent b257784553
commit 90d7fe9a81
5 changed files with 37 additions and 2 deletions

File diff suppressed because one or more lines are too long

View File

@ -40,6 +40,11 @@ export default class ItemBuilder {
return this; return this;
} }
withTickCallback(callback) {
this.item.addTickCallback(callback);
return this;
}
create() { create() {
return this.item; return this.item;
} }

View File

@ -5,6 +5,7 @@ import Output from './output';
import Input from './input'; import Input from './input';
import Commands from './commands'; import Commands from './commands';
export default class Game { export default class Game {
constructor() { constructor() {
this.player = new Player(); this.player = new Player();
@ -15,6 +16,7 @@ export default class Game {
this.commandHandler = new Commands(this); this.commandHandler = new Commands(this);
this.input = new Input(this.commandHandler, this.output); this.input = new Input(this.commandHandler, this.output);
this.visitedRooms = new Map(); this.visitedRooms = new Map();
this.interval = null;
} }
print(string) { print(string) {
@ -36,6 +38,21 @@ export default class Game {
this.player = new Player(); this.player = new Player();
this.player.context = this; this.player.context = this;
this.move(this.player.currentRoom); this.move(this.player.currentRoom);
this.start();
}
advanceTick() {
this.items.forEach((item) => item.onTick());
this.rooms.forEach((room) => room.onTick());
}
start() {
this.interval = setInterval(() => this.advanceTick(), 1000);
}
stop() {
clearInterval(this.interval);
this.interval = null;
} }
examineRoom() { examineRoom() {

View File

@ -8,6 +8,7 @@ export default class Item {
this.useCallback = null; this.useCallback = null;
this.takeCallback = null; this.takeCallback = null;
this.dropCallback = null; this.dropCallback = null;
this.tickCallback = null;
this.context = null; this.context = null;
} }
@ -19,6 +20,10 @@ export default class Item {
if (this.takeCallback) return this.takeCallback(); if (this.takeCallback) return this.takeCallback();
} }
async onTick() {
if (this.tickCallback) return this.tickCallback(this.context);
}
addUseCallback(callback) { addUseCallback(callback) {
this.useCallback = callback.bind(this); this.useCallback = callback.bind(this);
} }
@ -30,4 +35,8 @@ export default class Item {
addDropCallback(callback) { addDropCallback(callback) {
this.dropCallback = callback.bind(this); this.dropCallback = callback.bind(this);
} }
addTickCallback(callback) {
this.tickCallback = callback.bind(this);
}
} }

View File

@ -76,4 +76,8 @@ export default class Room {
getItems() { getItems() {
return this.objects.map((item) => this.context.getItem(item)); return this.objects.map((item) => this.context.getItem(item));
} }
async onTick() {
if (this.tickCallback) return this.tickCallback(this.context);
}
} }