A Quick BreakOut Game in JavaScript

by Michael

Every third friday, the company that I work at lets us do whatever we want, as long as it is programming related and helps us become better developers. It had been a while that I wrote anything in pure JavaScript and was feeling the need to get back into it. I decided to take the opportunity to write BreakOut using the HTML canvas element. The goal was to have something up and running by the end of the day.

The idea was to make a BreakOut game that has support for multiple balls and multiple players as well as bricks of differing ‘hardness’.

I ended up writing this. Here’s the code for the startGame method:

function startGame() {

    Game.ctx = getContext();
    Game.screen = getScreen();

    var screen = Game.screen;

    Events.init();

    var p = new Player();
    p.x = Game.screen.hmiddle - p.w / 2;
    p.y = Game.screen.height - p.h - 5;
    Game.players.push(p);

    for (var i = 10; i < screen.vmiddle; i += 30)
        for (var j = 10; j < screen.width - 60; j += 60)
            Game.bricks.push(new Brick(j, i, randInt(3)));

    Game.balls.push(new Ball(10, Game.screen.vmiddle, 0.3, 0.3));

    // extra ball - weeeeee!  😀
    setTimeout(function () {
        Game.balls.push(new Ball(10, Game.screen.vmiddle, 0.3, 0.3));
    }, 5000);

    step(new Clock());
}

And here’s a quick screenshot of the game running in js fiddle. I discovered js fiddle just after I finished writing the game. It looks like a great online development tool. Look forward to using it more in the future.

Advertisements