Advertisement
Guest User

Untitled

a guest
Feb 24th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. <html>
  2. <head>
  3. <title>Pong</title>
  4. </head>
  5.  
  6. <body>
  7.  
  8. <canvas id="game" width="800" height="600"></canvas>
  9.  
  10. <script>
  11. var canvas, canvasContext;
  12. var width, height;
  13. var bx, by;
  14. var bvelx=5, bvely=4;
  15. var bsize=10;
  16.  
  17. var paddlePosY;
  18. var paddlew=10; paddleh=200;
  19.  
  20. var botPosY;
  21. var botw=10; both=paddleh;
  22.  
  23. window.onload = function() {
  24. canvas = document.getElementById('game');
  25. canvasContext = canvas.getContext('2d');
  26.  
  27. height=canvas.height; width=canvas.width;
  28.  
  29. paddlePosY=height/2; botPosY=height/2;
  30.  
  31. resetBall();
  32.  
  33. updateAll();
  34. setInterval( updateAll, 1000/60 );
  35.  
  36. canvas.addEventListener('mousemove',
  37. function(event){
  38. var mousePos = calculateMousePos(event);
  39. paddlePosY = mousePos.y-paddleh/2;
  40. } );
  41. }
  42. function resetBall() {
  43. bx=width/2, by=height/2;
  44. }
  45.  
  46. function updateAll() {
  47. rect(0, 0, width, height, '#909090'); //tlo
  48.  
  49. rect(bx, by, bsize, bsize, '#882233'); //ball
  50.  
  51. rect(0, paddlePosY, paddlew, paddleh, 'black'); // gracz
  52. rect(0, paddlePosY, paddlew, paddleh, 'black'); // gracz
  53.  
  54. bx+=bvelx;
  55. by+=bvely;
  56.  
  57. if (bx >= width-bsize) { bvelx*=-1; }
  58. if (bx <= 0) {
  59. if (by>=paddlePosY && by<=paddlePosY+paddleh) {
  60. bvelx*=-1;
  61. } else {
  62. resetBall();
  63. }
  64. }
  65. if (by >= height-bsize) { bvely*=-1; }
  66. if (by <= 0) { bvely*=-1; }
  67. }
  68.  
  69. function rect(posx, posy, width, height, color) {
  70. canvasContext.fillStyle = color;
  71. canvasContext.fillRect(posx, posy, width, height);
  72. }
  73. function calculateMousePos(event) {
  74. var rect = canvas.getBoundingClientRect();
  75. var root = document.documentElement;
  76. var mouseX = event.clientX - rect.left - root.scrollLeft;
  77. var mouseY = event.clientY - rect.top - root.scrollTop;
  78. return {
  79. x:mouseX,
  80. y:mouseY
  81. }
  82. }
  83. </script>
  84.  
  85. </body>
  86. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement