|
| 1 | + |
| 2 | +const canvas = document.getElementById('game'); |
| 3 | +const ctx = canvas.getContext('2d'); |
| 4 | + |
| 5 | +let maxX = canvas.width; |
| 6 | +let maxY = canvas.height; |
| 7 | + |
| 8 | +let paddleWidth = 10; |
| 9 | +let paddleHeight = 35; |
| 10 | +let maxPaddleSpeed = .75; |
| 11 | +// All paddles need to store is y position |
| 12 | +let paddle1 = Math.floor(maxY / 2); |
| 13 | +let paddle2 = paddle1; |
| 14 | +let points1 = 0; |
| 15 | +let points2 = 0; |
| 16 | +let ballX = Math.floor(maxX / 2); |
| 17 | +let ballY = Math.floor(maxY / 2); |
| 18 | +let ballVx = 1; |
| 19 | +let ballVy = 1; |
| 20 | + |
| 21 | +function render() { |
| 22 | + ctx.fillStyle = "#444444"; |
| 23 | + ctx.fillRect(0, 0, canvas.width, canvas.height); |
| 24 | + |
| 25 | + ctx.fillStyle = "#cccccc"; |
| 26 | + ctx.fillRect(ballX-5, ballY-5, 10, 10); |
| 27 | + |
| 28 | + ctx.fillRect(10, paddle1 - paddleHeight/2, 10, paddleHeight); |
| 29 | + ctx.fillRect(280, paddle2 - paddleHeight/2, 10, paddleHeight); |
| 30 | + |
| 31 | + ctx.fillText(points1, 5, 10); |
| 32 | + ctx.fillText(points2, 285, 10); |
| 33 | +} |
| 34 | + |
| 35 | +function reset(full) { |
| 36 | + paddle2 = Math.floor(maxY / 2); |
| 37 | + ballX = Math.floor(maxX / 2); |
| 38 | + ballY = Math.floor(maxY / 2); |
| 39 | + ballVx = Math.random() > .5 ? 1 : -1; |
| 40 | + ballVy = 1; |
| 41 | + if (full) { |
| 42 | + points1 = 0; |
| 43 | + points2 = 0; |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +function clamp(val, min, max) { |
| 48 | + return Math.min(Math.max(val, min), max); |
| 49 | +} |
| 50 | + |
| 51 | +function handleMouseMove(e) { |
| 52 | + let targetY = (e.pageY - canvas.offsetTop) * canvas.height / canvas.offsetHeight; |
| 53 | + paddle1 = targetY; |
| 54 | +} |
| 55 | + |
| 56 | +function main() { |
| 57 | + paddle2 += clamp(ballY - paddle2, -maxPaddleSpeed, maxPaddleSpeed); |
| 58 | + |
| 59 | + let nextX = ballX + ballVx; |
| 60 | + let nextY = ballY + ballVy; |
| 61 | + if (nextX < 0) { |
| 62 | + points2++; |
| 63 | + reset(); |
| 64 | + } else if (nextX > maxX) { |
| 65 | + points1++; |
| 66 | + reset(); |
| 67 | + } else if (nextY < 0 || nextY > maxY) { |
| 68 | + ballVy = -ballVy; |
| 69 | + } |
| 70 | + if (ballX < 20 && ballX > 10 && Math.abs(ballY - paddle1) < paddleHeight / 2) { |
| 71 | + ballVx = -ballVx * 1.1; |
| 72 | + ballVy += (Math.random()-0.5) * .1; |
| 73 | + } |
| 74 | + if (ballX < 290 && ballX > 280 && Math.abs(ballY - paddle2) < paddleHeight / 2) { |
| 75 | + ballVx = -ballVx * 1.1; |
| 76 | + ballVy += (Math.random()-0.5) * .1; |
| 77 | + } |
| 78 | + |
| 79 | + ballX += ballVx; |
| 80 | + ballY += ballVy; |
| 81 | + |
| 82 | + render(); |
| 83 | + |
| 84 | + |
| 85 | + requestAnimationFrame(main); |
| 86 | +} |
| 87 | + |
| 88 | +document.onmousemove = handleMouseMove; |
| 89 | +reset(true); |
| 90 | +main(); |
0 commit comments