Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <html>
- <head>
- <title>Pong</title>
- </head>
- <body>
- <canvas id="game" width="800" height="600"></canvas>
- <script>
- var canvas, canvasContext;
- var width, height;
- var bx, by;
- var bvelx=5, bvely=4;
- var bsize=10;
- var paddlePosY;
- var paddlew=10; paddleh=200;
- var botPosY;
- var botw=10; both=paddleh;
- window.onload = function() {
- canvas = document.getElementById('game');
- canvasContext = canvas.getContext('2d');
- height=canvas.height; width=canvas.width;
- paddlePosY=height/2; botPosY=height/2;
- resetBall();
- updateAll();
- setInterval( updateAll, 1000/60 );
- canvas.addEventListener('mousemove',
- function(event){
- var mousePos = calculateMousePos(event);
- paddlePosY = mousePos.y-paddleh/2;
- } );
- }
- function resetBall() {
- bx=width/2, by=height/2;
- }
- function updateAll() {
- rect(0, 0, width, height, '#909090'); //tlo
- rect(bx, by, bsize, bsize, '#882233'); //ball
- rect(0, paddlePosY, paddlew, paddleh, 'black'); // gracz
- rect(0, paddlePosY, paddlew, paddleh, 'black'); // gracz
- bx+=bvelx;
- by+=bvely;
- if (bx >= width-bsize) { bvelx*=-1; }
- if (bx <= 0) {
- if (by>=paddlePosY && by<=paddlePosY+paddleh) {
- bvelx*=-1;
- } else {
- resetBall();
- }
- }
- if (by >= height-bsize) { bvely*=-1; }
- if (by <= 0) { bvely*=-1; }
- }
- function rect(posx, posy, width, height, color) {
- canvasContext.fillStyle = color;
- canvasContext.fillRect(posx, posy, width, height);
- }
- function calculateMousePos(event) {
- var rect = canvas.getBoundingClientRect();
- var root = document.documentElement;
- var mouseX = event.clientX - rect.left - root.scrollLeft;
- var mouseY = event.clientY - rect.top - root.scrollTop;
- return {
- x:mouseX,
- y:mouseY
- }
- }
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement