为什么我不能更改我的可变数量并在 js 中设置它?

亚利安线

我正在制作乒乓球游戏,并且正在尝试为其添加分数。无论我做什么,它都不会增加分数。控制台中没有任何内容。我在谷歌上找不到任何东西。由于源代码很长,我就直接贴链接了。这是 Html & Js:

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>Pong</title><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jcanvas/21.0.1/min/jcanvas.min.js"></script>
  </head>

  <body>
    <div class="center">
      <h1>Pong</h1>
      <span class="playeronescore"> Player 1 - <p id="playeronescore">0</p></span>
      <canvas id="gameScreen" width="1000px" height="600px"></canvas>
      <br><br><span class="playertwoscore"> Player 2 - <p id="playertwoscore">0</p></span>
    </div>
  </body>

  <script>
    var playeronescore = document.getElementById("playeronescore");
    var playertwoscore = document.getElementById("playertwoscore");
    scoreone = 0;
    scoretwo = 0;
    var PIXEL_RATIO = (function() {
      var ctx = document.createElement("canvas").getContext("2d"),
        dpr = window.devicePixelRatio || 1,
        bsr =
          ctx.webkitBackingStorePixelRatio ||
          ctx.mozBackingStorePixelRatio ||
          ctx.msBackingStorePixelRatio ||
          ctx.oBackingStorePixelRatio ||
          ctx.backingStorePixelRatio ||
          1;

      return dpr / bsr;
    })();

    changeCanvasRatio = function() {
      const ratio = PIXEL_RATIO;
      const can = document.getElementsByTagName("canvas")[0];
      can.style.width = can.width + "px";
      can.style.height = can.height + "px";
      can.width = can.width * ratio;
      can.height = can.height * ratio;
      can.getContext("2d").setTransform(ratio, 0, 0, ratio, 0, 0);
      return can;
    };

    //Create canvas with the device resolution.
    changeCanvasRatio();
    
let canvas = $("#gameScreen");
const canvasBounds = { bottom: 600, top: 0, left: 0, right: 1000 };
let paddle1 = { height: 150, width: 22, x: 15, y: 225, vy: 0 };
let _paddle1 = Object.assign({}, paddle1);
let paddle2 = { height: 150, width: 22, x: 963, y: 225, vy: 0 };
let _paddle2 = Object.assign({}, paddle2);
let ball = { height: 15, width: 15, x: 492.5, y: 292.5, vx: 0, vy: 0 };
let _ball = Object.assign({}, ball);
let timer = 0;

let keys = { w: false, s: false, up: false, down: false };
const paddleSpeed = 6;
const initialBallSpeed = 5;
const ballSpeedIncrement = 1.6;
const startTimer = 100;

function resetGame() {
  timer = startTimer;

  paddle1 = Object.assign({}, _paddle1);
  paddle2 = Object.assign({}, _paddle2);
  ball = Object.assign({}, _ball);

  let ballDirection = Math.random() * 360;
  while (
    !(
      ballDirection < 60 ||
      (ballDirection > 120 && ballDirection < 240) ||
      ballDirection > 300
    )
  ) {
    ballDirection = Math.random() * 360;
  }

  ball.vx = convertToRect(initialBallSpeed, ballDirection).x;
  ball.vy = convertToRect(initialBallSpeed, ballDirection).y;
}

function convertToPolar(x, y) {
  let distance = Math.sqrt(x * x + y * y);
  let radians = Math.atan2(y, x);
  if (radians < 0) radians = (2 * Math.PI + radians) % (2 * Math.PI); // converts to positive
  let degrees = radians * (180 / Math.PI);
  return { distance: distance, degrees: degrees };
}

function convertToRect(distance, degrees) {
  let radians = degrees * (Math.PI / 180);
  let x = Math.cos(radians) * distance;
  let y = Math.sin(radians) * distance;
  return { x: x, y: y };
}

function checkCollision(paddle, object) {
  return (
    paddle.x < object.x + object.width &&
    paddle.x + paddle.width > object.x &&
    paddle.y < object.y + object.height &&
    paddle.y + paddle.height > object.y
  );
}

$("body").keydown(function(event) {
  switch (event.key) {
    case "w":
      keys.w = true;
      break;
    case "s":
      keys.s = true;
      break;
    case "ArrowUp":
      keys.up = true;
      break;
    case "ArrowDown":
      keys.down = true;
      break;
  }
});

$("body").keyup(function(event) {
  switch (event.key) {
    case "w":
      keys.w = false;
      break;
    case "s":
      keys.s = false;
      break;
    case "ArrowUp":
      keys.up = false;
      break;
    case "ArrowDown":
      keys.down = false;
      break;
  }
});

$("canvas").blur(function() {
  keys.w = false;
  keys.s = false;
  keys.up = false;
  keys.down = false;
});

function render(progress) {
  const p = progress / (1000 / 60);
  canvas.clearCanvas();

  canvas.drawRect({
    fillStyle: "#000000",
    x: 0,
    y: 0,
    width: canvasBounds.right,
    height: canvasBounds.bottom,
    fromCenter: false
  });

  canvas.drawRect({
    fillStyle: "#FFFFFF",
    x: paddle1.x,
    y: paddle1.y,
    width: paddle1.width,
    height: paddle1.height,
    fromCenter: false
  });

  canvas.drawRect({
    fillStyle: "#FFFFFF",
    x: paddle2.x,
    y: paddle2.y,
    width: paddle2.width,
    height: paddle2.height,
    fromCenter: false
  });
  canvas.drawRect({
    fillStyle: "#FFFFFF",
    x: ball.x,
    y: ball.y,
    width: ball.width,
    height: ball.height,
    fromCenter: false
  });

  if (timer > 0) {
    timer--;
    return;
  }

  if ((keys.w && keys.s) || !(keys.w || keys.s)) {
    paddle1.vy = 0;
  } else if (keys.w) {
    paddle1.vy = -1 * paddleSpeed;
  } else if (keys.s) {
    paddle1.vy = paddleSpeed;
  }

  if ((keys.up && keys.down) || !(keys.up || keys.down)) {
    paddle2.vy = 0;
  } else if (keys.up) {
    paddle2.vy = -1 * paddleSpeed;
  } else if (keys.down) {
    paddle2.vy = paddleSpeed;
  }

  paddle1.y += paddle1.vy * p;
  paddle2.y += paddle2.vy * p;

  ball.x += ball.vx * p;
  ball.y += ball.vy * p;

  if (paddle1.y > canvasBounds.bottom - paddle1.height) {
    paddle1.y = canvasBounds.bottom - paddle1.height;
    paddle1.vy = 0;
  }
  if (paddle1.y < canvasBounds.top) {
    paddle1.y = canvasBounds.top;
    paddle1.vy = 0;
  }

  if (paddle2.y > canvasBounds.bottom - paddle2.height) {
    paddle2.y = canvasBounds.bottom - paddle2.height;
    paddle2.vy = 0;
  }
  if (paddle2.y < canvasBounds.top) {
    paddle2.y = canvasBounds.top;
    paddle2.vy = 0;
  }

  if (ball.y > canvasBounds.bottom - ball.height) {
    ball.y = canvasBounds.bottom - ball.height;
    ball.vy *= -1;
  }
  if (ball.y < canvasBounds.top) {
    ball.y = canvasBounds.top;
    ball.vy *= -1;
  }
  if (ball.x < canvasBounds.left || ball.x + ball.width > canvasBounds.right)
    resetGame();
  
  if (ball.x <= canvasBounds.left) {  
    scoreone += 1;
    playeronescore = scoreone;
  }
  if (ball.x + ball.width >= canvasBounds.right) {
    scoretwo += 1;
    playertwoscore = scoretwo;
  } 
  
  if (checkCollision(paddle1, ball)) {
    ball.x = paddle1.x + paddle1.width + 0.01;
    ball.vx *= -1;
    const polar = convertToPolar(ball.vx, ball.vy);

    let ballDirection = polar.degrees;
    let ballSpeed = polar.distance;

    ballSpeed += ballSpeedIncrement;

    ballDirection += 90;
    if (ballDirection > 360) ballDirection -= 360;

    const ballDistance =
      ball.y - (paddle1.y + paddle1.height / 2 - ball.height);
    const percentChange =
      (50 / (paddle1.height / 2)) * Math.abs(ballDistance) * 0.01;
    1;
    if (ballDistance < 0) {
      ballDirection *= 1 - percentChange;
    } else {
      ballDirection = 180 - ballDirection;
      ballDirection *= 1 - percentChange;
      ballDirection = 180 - ballDirection;
    }

    if (ballDirection < 90) ballDirection += 360;

    ballDirection -= 90;

    const _temp = convertToRect(ballSpeed, ballDirection);
    ball.vx = _temp.x;
    ball.vy = _temp.y;
  }

  if (checkCollision(paddle2, ball)) {
    ball.x = paddle2.x - ball.width - 0.01;
    ball.vx *= -1;
    const polar = convertToPolar(ball.vx, ball.vy);

    let ballDirection = polar.degrees;
    let ballSpeed = polar.distance;

    ballSpeed += ballSpeedIncrement;

    ballDirection -= 90;

    const ballDistance =
      ball.y - (paddle2.y + paddle2.height / 2 - ball.height);
    const percentChange =
      (50 / (paddle2.height / 2)) * Math.abs(ballDistance) * 0.01;

    if (ballDistance > 0) {
      ballDirection *= 1 - percentChange;
    } else {
      ballDirection = 180 - ballDirection;
      ballDirection *= 1 - percentChange;
      ballDirection = 180 - ballDirection;
    }

    ballDirection += 90;

    const _temp = convertToRect(ballSpeed, ballDirection);
    ball.vx = _temp.x;
    ball.vy = _temp.y;
  }
}
    
resetGame();

let lastRender;
function loop(timestamp) {
  const progress = timestamp - lastRender;

  render(progress);

  lastRender = timestamp;
  window.requestAnimationFrame(loop);
}

lastRender = 0;
window.requestAnimationFrame(loop);   
    
  </script>
</html>
<script type="application/javascript" src="/share.js"></script>

查看源:https : //aaryank.codewizardshq.com/Pong1/pong.html

用户120242

在检查谁获胜之前,您正在重置游戏。并且您必须使用innerHTML 来写入DOM 元素的内容。您正在做的只是将变量分配给playertwoscorescoretwo 的值。设置错误代码在这里:

 if (ball.x <= canvasBounds.left) {  
    scoretwo += 1;
    document.getElementById('playertwoscore').innerHTML = scoretwo;
  }
  if (ball.x + ball.width >= canvasBounds.right) {
    scoreone += 1;
    document.getElementById('playeronescore').innerHTML = scoreone;
  } 
  if (ball.x < canvasBounds.left || ball.x + ball.width > canvasBounds.right)
    resetGame();

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jcanvas/21.0.1/jcanvas.js" integrity="sha256-ZqFgz7QUEDRCvHiosY/FIao3Zg5Pmg2J4rlLTEWu4BI=" crossorigin="anonymous"></script>

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>Pong</title><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jcanvas/21.0.1/min/jcanvas.min.js"></script>
  </head>

  <body>
    <div class="center">
      <h1>Pong</h1>
      <span class="playeronescore"> Player 1 - <p id="playeronescore">0</p></span>
      <canvas id="gameScreen" width="1000px" height="600px"></canvas>
      <br><br><span class="playertwoscore"> Player 2 - <p id="playertwoscore">0</p></span>
    </div>
  </body>

  <script>
    var playeronescore = document.getElementById("playeronescore");
    var playertwoscore = document.getElementById("playertwoscore");
    scoreone = 0;
    scoretwo = 0;
    var PIXEL_RATIO = (function() {
      var ctx = document.createElement("canvas").getContext("2d"),
        dpr = window.devicePixelRatio || 1,
        bsr =
          ctx.webkitBackingStorePixelRatio ||
          ctx.mozBackingStorePixelRatio ||
          ctx.msBackingStorePixelRatio ||
          ctx.oBackingStorePixelRatio ||
          ctx.backingStorePixelRatio ||
          1;

      return dpr / bsr;
    })();

    changeCanvasRatio = function() {
      const ratio = PIXEL_RATIO;
      const can = document.getElementsByTagName("canvas")[0];
      can.style.width = can.width + "px";
      can.style.height = can.height + "px";
      can.width = can.width * ratio;
      can.height = can.height * ratio;
      can.getContext("2d").setTransform(ratio, 0, 0, ratio, 0, 0);
      return can;
    };

    //Create canvas with the device resolution.
    changeCanvasRatio();
    
let canvas = $("#gameScreen");
const canvasBounds = { bottom: 600, top: 0, left: 0, right: 1000 };
let paddle1 = { height: 150, width: 22, x: 15, y: 225, vy: 0 };
let _paddle1 = Object.assign({}, paddle1);
let paddle2 = { height: 150, width: 22, x: 963, y: 225, vy: 0 };
let _paddle2 = Object.assign({}, paddle2);
let ball = { height: 15, width: 15, x: 492.5, y: 292.5, vx: 0, vy: 0 };
let _ball = Object.assign({}, ball);
let timer = 0;

let keys = { w: false, s: false, up: false, down: false };
const paddleSpeed = 6;
const initialBallSpeed = 5;
const ballSpeedIncrement = 1.6;
const startTimer = 100;

function resetGame() {
  timer = startTimer;

  paddle1 = Object.assign({}, _paddle1);
  paddle2 = Object.assign({}, _paddle2);
  ball = Object.assign({}, _ball);

  let ballDirection = Math.random() * 360;
  while (
    !(
      ballDirection < 60 ||
      (ballDirection > 120 && ballDirection < 240) ||
      ballDirection > 300
    )
  ) {
    ballDirection = Math.random() * 360;
  }

  ball.vx = convertToRect(initialBallSpeed, ballDirection).x;
  ball.vy = convertToRect(initialBallSpeed, ballDirection).y;
}

function convertToPolar(x, y) {
  let distance = Math.sqrt(x * x + y * y);
  let radians = Math.atan2(y, x);
  if (radians < 0) radians = (2 * Math.PI + radians) % (2 * Math.PI); // converts to positive
  let degrees = radians * (180 / Math.PI);
  return { distance: distance, degrees: degrees };
}

function convertToRect(distance, degrees) {
  let radians = degrees * (Math.PI / 180);
  let x = Math.cos(radians) * distance;
  let y = Math.sin(radians) * distance;
  return { x: x, y: y };
}

function checkCollision(paddle, object) {
  return (
    paddle.x < object.x + object.width &&
    paddle.x + paddle.width > object.x &&
    paddle.y < object.y + object.height &&
    paddle.y + paddle.height > object.y
  );
}

$("body").keydown(function(event) {
  switch (event.key) {
    case "w":
      keys.w = true;
      break;
    case "s":
      keys.s = true;
      break;
    case "ArrowUp":
      keys.up = true;
      break;
    case "ArrowDown":
      keys.down = true;
      break;
  }
});

$("body").keyup(function(event) {
  switch (event.key) {
    case "w":
      keys.w = false;
      break;
    case "s":
      keys.s = false;
      break;
    case "ArrowUp":
      keys.up = false;
      break;
    case "ArrowDown":
      keys.down = false;
      break;
  }
});

$("canvas").blur(function() {
  keys.w = false;
  keys.s = false;
  keys.up = false;
  keys.down = false;
});

function render(progress) {
  const p = progress / (1000 / 60);
  canvas.clearCanvas();

  canvas.drawRect({
    fillStyle: "#000000",
    x: 0,
    y: 0,
    width: canvasBounds.right,
    height: canvasBounds.bottom,
    fromCenter: false
  });

  canvas.drawRect({
    fillStyle: "#FFFFFF",
    x: paddle1.x,
    y: paddle1.y,
    width: paddle1.width,
    height: paddle1.height,
    fromCenter: false
  });

  canvas.drawRect({
    fillStyle: "#FFFFFF",
    x: paddle2.x,
    y: paddle2.y,
    width: paddle2.width,
    height: paddle2.height,
    fromCenter: false
  });
  canvas.drawRect({
    fillStyle: "#FFFFFF",
    x: ball.x,
    y: ball.y,
    width: ball.width,
    height: ball.height,
    fromCenter: false
  });

  if (timer > 0) {
    timer--;
    return;
  }

  if ((keys.w && keys.s) || !(keys.w || keys.s)) {
    paddle1.vy = 0;
  } else if (keys.w) {
    paddle1.vy = -1 * paddleSpeed;
  } else if (keys.s) {
    paddle1.vy = paddleSpeed;
  }

  if ((keys.up && keys.down) || !(keys.up || keys.down)) {
    paddle2.vy = 0;
  } else if (keys.up) {
    paddle2.vy = -1 * paddleSpeed;
  } else if (keys.down) {
    paddle2.vy = paddleSpeed;
  }

  paddle1.y += paddle1.vy * p;
  paddle2.y += paddle2.vy * p;

  ball.x += ball.vx * p;
  ball.y += ball.vy * p;

  if (paddle1.y > canvasBounds.bottom - paddle1.height) {
    paddle1.y = canvasBounds.bottom - paddle1.height;
    paddle1.vy = 0;
  }
  if (paddle1.y < canvasBounds.top) {
    paddle1.y = canvasBounds.top;
    paddle1.vy = 0;
  }

  if (paddle2.y > canvasBounds.bottom - paddle2.height) {
    paddle2.y = canvasBounds.bottom - paddle2.height;
    paddle2.vy = 0;
  }
  if (paddle2.y < canvasBounds.top) {
    paddle2.y = canvasBounds.top;
    paddle2.vy = 0;
  }

  if (ball.y > canvasBounds.bottom - ball.height) {
    ball.y = canvasBounds.bottom - ball.height;
    ball.vy *= -1;
  }
  if (ball.y < canvasBounds.top) {
    ball.y = canvasBounds.top;
    ball.vy *= -1;
  }
  
  if (ball.x <= canvasBounds.left) {  
    scoretwo += 1;
    playertwoscore.innerHTML = scoretwo;
  }
  if (ball.x + ball.width >= canvasBounds.right) {
    scoreone += 1;
    playeronescore.innerHTML = scoreone;
  } 
  if (ball.x < canvasBounds.left || ball.x + ball.width > canvasBounds.right)
    resetGame();
  
  if (checkCollision(paddle1, ball)) {
    ball.x = paddle1.x + paddle1.width + 0.01;
    ball.vx *= -1;
    const polar = convertToPolar(ball.vx, ball.vy);

    let ballDirection = polar.degrees;
    let ballSpeed = polar.distance;

    ballSpeed += ballSpeedIncrement;

    ballDirection += 90;
    if (ballDirection > 360) ballDirection -= 360;

    const ballDistance =
      ball.y - (paddle1.y + paddle1.height / 2 - ball.height);
    const percentChange =
      (50 / (paddle1.height / 2)) * Math.abs(ballDistance) * 0.01;
    1;
    if (ballDistance < 0) {
      ballDirection *= 1 - percentChange;
    } else {
      ballDirection = 180 - ballDirection;
      ballDirection *= 1 - percentChange;
      ballDirection = 180 - ballDirection;
    }

    if (ballDirection < 90) ballDirection += 360;

    ballDirection -= 90;

    const _temp = convertToRect(ballSpeed, ballDirection);
    ball.vx = _temp.x;
    ball.vy = _temp.y;
  }

  if (checkCollision(paddle2, ball)) {
    ball.x = paddle2.x - ball.width - 0.01;
    ball.vx *= -1;
    const polar = convertToPolar(ball.vx, ball.vy);

    let ballDirection = polar.degrees;
    let ballSpeed = polar.distance;

    ballSpeed += ballSpeedIncrement;

    ballDirection -= 90;

    const ballDistance =
      ball.y - (paddle2.y + paddle2.height / 2 - ball.height);
    const percentChange =
      (50 / (paddle2.height / 2)) * Math.abs(ballDistance) * 0.01;

    if (ballDistance > 0) {
      ballDirection *= 1 - percentChange;
    } else {
      ballDirection = 180 - ballDirection;
      ballDirection *= 1 - percentChange;
      ballDirection = 180 - ballDirection;
    }

    ballDirection += 90;

    const _temp = convertToRect(ballSpeed, ballDirection);
    ball.vx = _temp.x;
    ball.vy = _temp.y;
  }
}
    
resetGame();

let lastRender;
function loop(timestamp) {
  const progress = timestamp - lastRender;

  render(progress);

  lastRender = timestamp;
  window.requestAnimationFrame(loop);
}

lastRender = 0;
window.requestAnimationFrame(loop);   
    
  </script>
</html>
<script type="application/javascript" src="/share.js"></script>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

无法在draft.js中设置editorState(它看起来是不可变的,但没有错误)

为什么我不能设置Jquery的属性并在Electron中得到未定义的答案

试图在React Native中更改我的不可变数组

为什么我不能使用Redux从React.js中的数组中删除元素

为什么我不能运行数据库中的JS?

为什么我不能在Three.js中投射或接收阴影

为什么我不能在apache中阻止单个node.js文件?

为什么我不能评估.load以在node.js中启动交互式脚本?

为什么我不能在react.js的状态数组中推送值?

为什么我们不能在Express.js中执行多个response.send?

为什么我不能在Node.js Shell中需要模块?

为什么我不能在React中从D3js加载外部数据?

为什么我的JS计算中不能放一个以上的点

为什么我不能在 JS 中删除全局变量?

为什么我不能在状态中存储对象数组:React JS

为什么我的蓝牙耳机从“声音设置”中消失了,我该如何找回它?

在我的可变参数模板中获取UB,将可变数量的向量逐元素求和

在 Python 中,为什么当我将列表传递给函数时,我不能直接更改它?

为什么我不能在JS中复制此2d数组?我该如何复印?

为什么我不能通过 Vue.js 访问我的对象中动态插入的属性?

为什么我不能在我的password.js本地策略回调中创建和执行函数?

为什么我不能在Python中更改类的属性

为什么我不能更改反向列表中的元素?

为什么我不能在Notepad ++中更改文本背景

为什么我不能在React中更改输入值?

为什么我不能在SQLite中更改值?

为什么我不能更改RichTextBox中重复单词的颜色?

为什么我不能更改 QMap 中的 Qvariant 值?

为什么我不能通过 JS 函数更改我的内部 HTML?