game.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. function Game(options) {
  2. var frameRate = 1000 / 24;
  3. var gameLoopInterval = undefined;
  4. var score = 0;
  5. var ctx = $('canvas').get(0).getContext('2d');
  6. var ball = new Ball({x: 10, y: 200, size: 10, dx: -1, dy: -1, sx: 6, sy: 4});
  7. var paddle = new Paddle({x: ctx.canvas.width / 2, y: ctx.canvas.height - 20, size: 250, dx: 0, sx: 20});
  8. function showMainMenu() {
  9. // Clear the screen.
  10. ctx.fillStyle = '#ffffff';
  11. ctx.strokeStyle = '#ffffff';
  12. ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  13. // Show the buttons.
  14. $('.main-menu').show();
  15. // Add button listners.
  16. $('body').on('click', '.main-menu button', (evt) => {
  17. switch ($(evt.currentTarget).attr('id')) {
  18. case 'beginner': {
  19. ball = new Ball({x: 10, y: 200, size: 10, dx: -1, dy: -1, sx: 6, sy: 4});
  20. break;
  21. }
  22. case 'intermediate': {
  23. ball = new Ball({x: 10, y: 200, size: 10, dx: -1, dy: -1, sx: 12, sy: 8});
  24. break;
  25. }
  26. case 'advanced': {
  27. ball = new Ball({x: 10, y: 200, size: 10, dx: -1, dy: -1, sx: 30, sy: 15});
  28. break;
  29. }
  30. }
  31. startGame();
  32. });
  33. }
  34. function startGame() {
  35. // Hide the main menu.
  36. $('.main-menu').hide();
  37. if (gameLoopInterval == undefined) {
  38. $(window).on('keydown', function(evt) {
  39. getInput(evt);
  40. });
  41. gameLoopInterval = setInterval(function() {
  42. // Clear the screen.
  43. ctx.fillStyle = '#ffffff';
  44. ctx.strokeStyle = '#ffffff';
  45. ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  46. // Update the ball and paddle.
  47. paddle.update(ctx);
  48. ball.update(ctx, paddle);
  49. // Draw the ball and paddle.
  50. paddle.draw (ctx);
  51. ball.draw(ctx);
  52. // Draw the score.
  53. ctx.fillStyle = '#000000';
  54. ctx.font = '30px Tahoma';
  55. ctx.fillText('Score: ' + score, 20, 60);
  56. }, frameRate);
  57. }
  58. }
  59. function endGame() {
  60. if (gameLoopInterval !== undefined) {
  61. clearInterval(gameLoopInterval);
  62. gameLoopInterval = undefined;
  63. // Draw Game Over.
  64. ctx.fillStyle = '#000000';
  65. ctx.font = '120px Tahoma';
  66. ctx.fillText('GAME OVER!', (ctx.canvas.width / 2) - (ctx.measureText('GAME OVER!').width / 2), ctx.canvas.height / 2);
  67. }
  68. }
  69. function getInput(evt) {
  70. // Left Arrow Key
  71. if (evt.keyCode == 37) {
  72. paddle.movePaddle(-1);
  73. }
  74. // Right Arrow Key
  75. else if (evt.keyCode == 39) {
  76. paddle.movePaddle(1);
  77. }
  78. }
  79. function add1ToScore() {
  80. score++;
  81. }
  82. return {
  83. 'showMainMenu': showMainMenu,
  84. 'startGame': startGame,
  85. 'endGame': endGame,
  86. 'add1ToScore': add1ToScore
  87. }
  88. }