I'm new to TypeScript, coming from Java and having some knowledge of JavaScript. I'm learning TS by making a good old Snake game!
I have this class Gui that should draw the canvas. In my contructor I start with creating my Snake object. Later on I start the game loop in which the Snake should be moved...
But the loop function does not work, because of this error. "Uncaught Type Error: Cannot read property 'move' of undefined."
I suspect it has something to do with the setInterval function that works 'asyncronously' or something but I'm not sure... It seems as a kind of fundamental JavaScript problem.
Any help is highly appreciated!
module gui {
export class Gui {
snake:model.Snake;
loop:any;
constructor() {
// get snake
this.snake = new model.Snake();
// Attach key event
document.addEventListener("keydown", KeyListener.handleEvt);
// activate game loop
this.loop = setInterval(this.gameLoop, 50);
}
gameLoop() {
if (this.snake) {
console.log("loop");
this.snake.move();
this.drawSnake()
}
}
drawPart(part:model.Part) { ... }
drawSnake() { ... }
}
class KeyListener {
static handleEvt(e) {
if (e) {
switch (e.keyCode) {
case 37:
console.log("left");
break;
case 38:
console.log("up");
break;
case 39:
console.log("right");
break;
case 40:
console.log("down");
break;
}
}
}
}
}