Advertisement
Guest User

Untitled

a guest
May 27th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function pong() {
  2.   const canvas = document.getElementById('canvas');
  3.   const context = canvas.getContext('2d');
  4.  
  5.   canvas.height = 500;
  6.   canvas.width = 1000;
  7.  
  8.   const cw = canvas.width;
  9.   const ch = canvas.height;
  10.  
  11.   const ballSize = 20;
  12.   let ballX = cw/2 - ballSize/2;
  13.   let ballY = ch/2 - ballSize/2;
  14.  
  15.   const paddleWidth = 20;
  16.   const paddleHeight = 100;
  17.   const playerX = 70;
  18.   let playerY = 20;
  19.   const aiX = 910;
  20.   let aiY = 20;
  21.   const lineHeight = 16;
  22.   const lineWidth = 6;
  23.  
  24.   let ballSpeedX = 4;//tutaj okreslamy poczatkowa predkosc pilki
  25.   let ballSpeedY = 4;// o predkosciach pogadamy sobie nqastepnym razem, tak od strony fizycznej ;p
  26.  
  27.  
  28.  
  29.   function drawPlayer() {
  30.     context.fillStyle = "blue";
  31.     context.fillRect(playerX, playerY, paddleWidth, paddleHeight);
  32.   }
  33.  
  34.   function drawAi() {
  35.     context.fillStyle = "green";
  36.     context.fillRect(aiX, aiY, paddleWidth, paddleHeight);
  37.   }
  38.  
  39.   function drawBall() {
  40.     context.fillStyle = "orange";
  41.     context.fillRect(ballX, ballY, ballSize, ballSize);
  42.  
  43.     ballX += ballSpeedX; // z kazdym krokiem przesuwamy pilke
  44.     ballY += ballSpeedY; // tu to samo
  45.  
  46.     if (ballY <= 0 || ballY + ballSize >= ch) { // tutaj sprawdzamy czy pilka nie wychodzi poza krawedzie
  47.       ballSpeedY = -ballSpeedY;
  48.     }
  49.     if (ballX <= 0 || ballX + ballSize >= cw) {
  50.       ballSpeedX = -ballSpeedX;
  51.     }
  52.   }
  53.  
  54.   function drawTable() {
  55.     context.fillStyle = "black";
  56.     context.fillRect(0, 0, cw, ch);
  57.     for (let linePosition = 20; linePosition < ch; linePosition = linePosition + 30){
  58.       context.fillStyle = "grey";
  59.       context.fillRect(cw/2 - lineWidth/2, linePosition, lineWidth, lineHeight);
  60.     }
  61.   }
  62.   function game() {
  63.     drawTable();
  64.     drawBall();
  65.     drawPlayer();
  66.     drawAi();
  67.  
  68.   }
  69.  
  70.   setInterval(game, 1000/60);
  71.  
  72. }
  73.  
  74. window.onload = pong;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement