function Game(options) { var frameRate = 1000 / 24; var gameLoopInterval = undefined; var score = 0; var ctx = $('canvas').get(0).getContext('2d'); var ball = new Ball({x: 10, y: 200, size: 10, dx: -1, dy: -1, sx: 6, sy: 4}); var paddle = new Paddle({x: ctx.canvas.width / 2, y: ctx.canvas.height - 20, size: 250, dx: 0, sx: 20}); function showMainMenu() { // Clear the screen. ctx.fillStyle = '#ffffff'; ctx.strokeStyle = '#ffffff'; ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // Show the buttons. $('.main-menu').show(); // Add button listners. $('body').on('click', '.main-menu button', (evt) => { switch ($(evt.currentTarget).attr('id')) { case 'beginner': { ball = new Ball({x: 10, y: 200, size: 10, dx: -1, dy: -1, sx: 6, sy: 4}); break; } case 'intermediate': { ball = new Ball({x: 10, y: 200, size: 10, dx: -1, dy: -1, sx: 12, sy: 8}); break; } case 'advanced': { ball = new Ball({x: 10, y: 200, size: 10, dx: -1, dy: -1, sx: 30, sy: 15}); break; } } startGame(); }); } function startGame() { // Hide the main menu. $('.main-menu').hide(); if (gameLoopInterval == undefined) { $(window).on('keydown', function(evt) { getInput(evt); }); gameLoopInterval = setInterval(function() { // Clear the screen. ctx.fillStyle = '#ffffff'; ctx.strokeStyle = '#ffffff'; ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // Update the ball and paddle. paddle.update(ctx); ball.update(ctx, paddle); // Draw the ball and paddle. paddle.draw (ctx); ball.draw(ctx); // Draw the score. ctx.fillStyle = '#000000'; ctx.font = '30px Tahoma'; ctx.fillText('Score: ' + score, 20, 60); }, frameRate); } } function endGame() { if (gameLoopInterval !== undefined) { clearInterval(gameLoopInterval); gameLoopInterval = undefined; // Draw Game Over. ctx.fillStyle = '#000000'; ctx.font = '120px Tahoma'; ctx.fillText('GAME OVER!', (ctx.canvas.width / 2) - (ctx.measureText('GAME OVER!').width / 2), ctx.canvas.height / 2); } } function getInput(evt) { // Left Arrow Key if (evt.keyCode == 37) { paddle.movePaddle(-1); } // Right Arrow Key else if (evt.keyCode == 39) { paddle.movePaddle(1); } } function add1ToScore() { score++; } return { 'showMainMenu': showMainMenu, 'startGame': startGame, 'endGame': endGame, 'add1ToScore': add1ToScore } }