Untitled

 avatar
unknown
plain_text
2 years ago
2.6 kB
6
Indexable
// Set up the canvas and context
const canvas = document.getElementById('pong');
const context = canvas.getContext('2d');

// Set up the game state
const ball = {
  x: canvas.width / 2,
  y: canvas.height / 2,
  radius: 10,
  velocityX: 5,
  velocityY: 5
};

const player1 = {
  x: 0,
  y: canvas.height / 2 - 50,
  width: 10,
  height: 100,
  score: 0
};

const player2 = {
  x: canvas.width - 10,
  y: canvas.height / 2 - 50,
  width: 10,
  height: 100,
  score: 0
};

// Draw the game elements
function draw() {
  // Clear the canvas
  context.clearRect(0, 0, canvas.width, canvas.height);

  // Draw the ball
  context.beginPath();
  context.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
  context.fillStyle = '#ffffff';
  context.fill();
  context.closePath();

  // Draw the players
  context.fillStyle = '#ffffff';
  context.fillRect(player1.x, player1.y, player1.width, player1.height);
  context.fillRect(player2.x, player2.y, player2.width, player2.height);

  // Draw the scores
  context.font = '32px Arial';
  context.fillText(player1.score, canvas.width / 4, 40);
  context.fillText(player2.score, canvas.width * 3 / 4, 40);
}

// Update the game state
function update() {
  // Move the ball
  ball.x += ball.velocityX;
  ball.y += ball.velocityY;

  // Bounce the ball off the walls
  if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
    ball.velocityY = -ball.velocityY;
  }

  // Check for a point scored by player 1
  if (ball.x - ball.radius < 0) {
    player2.score++;
    reset();
  }

  // Check for a point scored by player 2
  if (ball.x + ball.radius > canvas.width) {
    player1.score++;
    reset();
  }

  // Bounce the ball off player 1
  if (ball.x - ball.radius < player1.x + player1.width &&
      ball.y > player1.y &&
      ball.y < player1.y + player1.height) {
    ball.velocityX = -ball.velocityX;
  }

  // Bounce the ball off player 2
  if (ball.x + ball.radius > player2.x &&
      ball.y > player2.y &&
      ball.y < player2.y + player2.height) {
    ball.velocityX = -ball.velocityX;
  }
}

// Reset the ball to the center of the screen
function reset() {
  ball.x = canvas.width / 2;
  ball.y = canvas.height / 2;
  ball.velocityX = -ball.velocityX;
}

// Handle player input
function handleInput() {
  // Move player 1 up
  if (keys[87]) {
    player1.y -= 5;
  }

  // Move player 1 down
  if (keys[83]) {
    player1.y += 5;
  }

  // Move player 2 up
  if (keys[38]) {
    player2.y -= 5;
  }

  // Move player 



Editor is loading...