Review simple game code

Hi, I’m pretty new to JS and I’m trying to create tetris game just for practice. And here is what my game loop looks like:

let game = {
    x: 30,
    canvas: document.getElementById('screen'),
    ctx: document.getElementById('screen').getContext('2d')
}
game.init = function(){
    console.log('init')
    game.update();
};
game.update = function(){
    game.x += 1;
    game.draw();
    requestAnimationFrame(game.update);
}
game.draw = function(){
    game.ctx.clearRect(0, 0, game.canvas.width, game.canvas.height);
    game.ctx.fillStyle = 'orange';
    game.ctx.fillRect(0, 0, game.canvas.width, game.canvas.height);
    game.ctx.fillStyle = 'black';
    game.ctx.fillRect(game.x, 20, 20, 20,);
}
document.addEventListener('load', game.init());

I feel that something isn’t right here :)) for example, I think I’m using all these ‘game.blahblah…’ wrong and here might be a ‘this’ word. Could you review this code and give any suggestions how to simplify it a little or just change something?
May be it could be better to create all the methods inside the game object, or assign something to the prototype etc.

I think if you made them all methods it should work…

not 100% sure and can’t test your code …so test it yourself before you take my advice :stuck_out_tongue_winking_eye:

let targetScreen = document.getElementById('screen')
let game = {
    x: 30,
    canvas: targetScreen,
    ctx: targetScreen.getContext('2d'),
    init: function(){
     console.log('init')
     this.update()
    },
    update: function(){
     this.x += 1;
     this.draw();
     requestAnimationFrame(this.update);
    },
    draw: function(){
     let targetScreenCtx = this.ctx
     targetScreenCtx.clearRect(0, 0, this.canvas.width, this.canvas.height);
     targetScreenCtx.fillStyle = 'orange';
     targetScreenCtx.fillRect(0, 0, this.canvas.width, this.canvas.height);
     targetScreenCtx.fillStyle = 'black';
     targetScreenCtx.fillRect(this.x, 20, 20, 20,);
    },
};
document.addEventListener('load', game.init());
1 Like