| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- 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
- }
- }
|