玩家赢得乒乓球比赛后无法更新和显示正确的最终比分

Unable to update and display the correct final scores after a player has won a Ping Pong match

我已经使用 JavaScript 构建了一个 Ping Pong 游戏,并试图在每场比赛后在 'scoreboard' 上更新分数。目前,记分牌上两位选手的得分处于某种循环中,不会停止。我想在每场比赛后为获胜球员的统计数据增加 1 场胜利。我怎样才能在记分牌上为每个玩家反映正确的总获胜次数。非常感谢您的帮助!

Link to Fiddle

<body>
  <h1>Ping Pong</h1>
  <canvas id="gameCanvas" width="800" height="600"></canvas>
  <div id="sb">
    <h1>SCOREBOARD</h1>
    <ul>
      <li>Player 1: <span id="player_1">0</span></li>
      <li> Player 2: <span id="player_2">0</span></li>
    </ul>
  </div>



  <script>
var count1_final = 0;
var count2_final = 0;

var canvas;
var canvasContext;
var ballX = 50;
var ballY = 50;
var ballSpeedX = 10;
var ballSpeedY = 4;

var player1Score = 0;
var player2Score = 0;
const WINNING_SCORE = 2;

var showingWinScreen = false;

var paddle1Y = 250;
var paddle2Y = 250;
const PADDLE_THICKNESS = 10;
const PADDLE_HEIGHT = 100;

function calculateMousePos(evt) {
  var rect = canvas.getBoundingClientRect();
  var root = document.documentElement;
  var mouseX = evt.clientX - rect.left - root.scrollLeft;
  var mouseY = evt.clientY - rect.top - root.scrollTop;
  return {
    x:mouseX,
    y:mouseY
  };
}

function handleMouseClick(evt) {
  if(showingWinScreen) {
    player1Score = 0;
    player2Score = 0;
    showingWinScreen = false;
  }
}

window.onload = function() {
  canvas = document.getElementById('gameCanvas');
  canvasContext = canvas.getContext('2d');

  var framesPerSecond = 30;
  setInterval(function() {
      moveEverything();
      drawEverything();
    }, 1000/framesPerSecond);

  canvas.addEventListener('mousedown', handleMouseClick);

  canvas.addEventListener('mousemove',
    function(evt) {
      var mousePos = calculateMousePos(evt);
      paddle1Y = mousePos.y - (PADDLE_HEIGHT/2);
    });
}

function ballReset() {
  var count1_final = 0;
  var count2_final = 0;
  if(player1Score >= WINNING_SCORE ||
    player2Score >= WINNING_SCORE) {

    showingWinScreen = true;

  }

  ballSpeedX = -ballSpeedX;
  ballX = canvas.width/2;
  ballY = canvas.height/2;
}

function computerMovement() {
  var paddle2YCenter = paddle2Y + (PADDLE_HEIGHT/2);
  if(paddle2YCenter < ballY - 35) {
    paddle2Y = paddle2Y + 6;
  } else if(paddle2YCenter > ballY + 35) {
    paddle2Y = paddle2Y - 6;
  }
}

function moveEverything() {
  if(showingWinScreen) {
    return;
  }

  computerMovement();

  ballX = ballX + ballSpeedX;
  ballY = ballY + ballSpeedY;

  if(ballX < 0) {
    if(ballY > paddle1Y &&
      ballY < paddle1Y+PADDLE_HEIGHT) {
      ballSpeedX = -ballSpeedX;

      var deltaY = ballY
          -(paddle1Y+PADDLE_HEIGHT/2);
      ballSpeedY = deltaY * 0.35;
    } else {
      player2Score++; // must be BEFORE ballReset()
      ballReset();
    }
  }
  if(ballX > canvas.width) {
    if(ballY > paddle2Y &&
      ballY < paddle2Y+PADDLE_HEIGHT) {
      ballSpeedX = -ballSpeedX;

      var deltaY = ballY
          -(paddle2Y+PADDLE_HEIGHT/2);
      ballSpeedY = deltaY * 0.35;
    } else {
      player1Score++; // must be BEFORE ballReset()
      ballReset();
    }
  }
  if(ballY < 0) {
    ballSpeedY = -ballSpeedY;
  }
  if(ballY > canvas.height) {
    ballSpeedY = -ballSpeedY;
  }
}

function drawNet() {
  for(var i=0;i<canvas.height;i+=40) {
    colorRect(canvas.width/2-1,i,2,20,'white');
  }
}


function drawEverything() {
  // next line blanks out the screen with black
  colorRect(0,0,canvas.width,canvas.height,'black');

  if(showingWinScreen) {
    canvasContext.fillStyle = 'white';

    if(player1Score >= WINNING_SCORE) {
      canvasContext.fillText("Player 1 Won", 350, 200);
      // var count1 = 0;
      // var count1_final = count1 + 1;
      // player1final_score++;
      count1_final++;
      document.getElementById("player_1").innerHTML = count1_final;
      console.log(count1_final)

    } else if(player2Score >= WINNING_SCORE) {
      canvasContext.fillText("Player 2 Won", 350, 200);
      // var count2 = 0;
      // var count2_final = count2 + 1;
      // player2final_score++;
      count2_final++;
      // console.log(player2final_score)
      document.getElementById("player_2").innerHTML = count2_final;
      console.log(count2_final)

    }

    canvasContext.fillText("Play Again", 350, 500);
    return;
  }

  drawNet();

  // this is left player paddle
  colorRect(0,paddle1Y,PADDLE_THICKNESS,PADDLE_HEIGHT,'white');

  // this is right computer paddle
  colorRect(canvas.width-PADDLE_THICKNESS,paddle2Y,PADDLE_THICKNESS,PADDLE_HEIGHT,'white');

  // next line draws the ball
  colorCircle(ballX, ballY, 10, 'white');

  canvasContext.fillText(player1Score, 100, 100);
  canvasContext.fillText(player2Score, canvas.width-100, 100);
}

function colorCircle(centerX, centerY, radius, drawColor) {
  canvasContext.fillStyle = drawColor;
  canvasContext.beginPath();
  canvasContext.arc(centerX, centerY, radius, 0,Math.PI*2,true);
  canvasContext.fill();
}

function colorRect(leftX,topY, width,height, drawColor) {
  canvasContext.fillStyle = drawColor;
  canvasContext.fillRect(leftX,topY, width,height);
}
</script>
</head>
</body>

body {
  background: #283048;  /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #859398, #283048);  /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #859398, #283048); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */

}

h1 {
  color: white;
  text-align: center;
}

#gc {
  float: left;
}

#sb {
  float: right;
  margin-right: 50px;
  border: 2px solid;
  padding: 20px;
}

相关代码:

if(player1Score >= WINNING_SCORE) {
      canvasContext.fillText("Player 1 Won", 350, 200);
      var count1 = 0;
      var count1_final = count1 + 1;
      // player1final_score++;
      console.log(player1final_score)
      document.getElementById("player_1").innerHTML = count1_final;

    } else if(player2Score >= WINNING_SCORE) {
      canvasContext.fillText("Player 2 Won", 350, 200);
      var count2 = 0;
      var count2_final = count2 + 1;
      console.log(player2final_score)
      document.getElementById("player_2").innerHTML = count2_final;

    }

违规文字在这里:

var count1 = 0;
var count1_final = count1 + 1;

您是说将计数设置回零,然后将其递增 1,这就是分数不超过 1 的原因。

作为一个解决方案,这些代表玩家获胜次数的变量应该全局定义,然后只在 "win" 函数中递增它们——在递增之前不要将它们设置为零。

编辑: 您现在已经更改了您的代码,您的问题也变成了一个完全不同的问题,但我会再次向您展示错误的根源。它与程序的逻辑流程有关。你有:

var framesPerSecond = 30;
  setInterval(function() {
      moveEverything();
      drawEverything();
    }, 1000/framesPerSecond);

在您的程序中不断触发。但是,即使玩家获胜,您仍然会不断调用 drawEverything(),并且在您的 drawEverything() 函数中是您的获胜计数器:

function drawEverything() {
  // next line blanks out the screen with black
  colorRect(0,0,canvas.width,canvas.height,'black');

  if(showingWinScreen) {
    canvasContext.fillStyle = 'white';

    if(player1Score >= WINNING_SCORE) {
      canvasContext.fillText("Player 1 Won", 350, 200);
      count1_final++; // <-- here
      document.getElementById("player_1").innerHTML = count1_final;
      console.log(count1_final) <-- evidence here, count goes up constantly in the console

    }
... 
}

换句话说,您需要重新考虑程序的流程。你怎么能让玩家只 "wins" 一次?

这两行总是将count1设置为零,然后将count1_final设置为0 + 1 == 1,下面几行count2_final也是如此。

if(player1Score >= WINNING_SCORE) {
    canvasContext.fillText("Player 1 Won", 350, 200);
    var count1 = 0;                    // <---------
    var count1_final = count1 + 1;     // <---------
    // player1final_score++;
    console.log(player1final_score)
    document.getElementById("player_1").innerHTML = count1_final;
}

您需要检索 count1_final并向那个加一,这意味着您需要存储count1_final 和 count2_final 函数 drawEverything 之外的某处。用 var 在其中声明它们会使它们成为该函数的局部变量,并且每次调用该函数时它们都会重新初始化为零。

您可能会在 ballReset 中这样做——在检查分数时 >= WINNING_SCORE 您还可以检查谁赢了并将他们的赢计数加一:count1_final++

function ballReset() {
    if (player1Score >= WINNING_SCORE ||
        player2Score >= WINNING_SCORE)
    {
        showingWinScreen = true;
        if (player1Score > player2Score) {
            count1_final++;
        }
        else {
            count2_final++;
        }
    }
}

我能够找出问题所在。我添加了一个新函数 addFinalScore 并在 ballReset 函数中调用该函数。现在记分牌正在正确更新分数。

JSFiddle

<body>
  <h1>Ping Pong</h1>
  <canvas id="gameCanvas" width="800" height="600"></canvas>
  <div id="sb">
    <h1>SCOREBOARD</h1>
    <ul>
      <li>Player 1: <span id="player_1">0</span></li>
      <li> Player 2: <span id="player_2">0</span></li>
    </ul>
  </div>



  <script>
var count1_final = 0;
var count2_final = 0;

var canvas;
var canvasContext;
var ballX = 50;
var ballY = 50;
var ballSpeedX = 10;
var ballSpeedY = 4;

var player1Score = 0;
var player2Score = 0;
const WINNING_SCORE = 2;

var showingWinScreen = false;

var paddle1Y = 250;
var paddle2Y = 250;
const PADDLE_THICKNESS = 10;
const PADDLE_HEIGHT = 100;

function calculateMousePos(evt) {
  var rect = canvas.getBoundingClientRect();
  var root = document.documentElement;
  var mouseX = evt.clientX - rect.left - root.scrollLeft;
  var mouseY = evt.clientY - rect.top - root.scrollTop;
  return {
    x:mouseX,
    y:mouseY
  };
}

function handleMouseClick(evt) {
  if(showingWinScreen) {
    player1Score = 0;
    player2Score = 0;
    showingWinScreen = false;
  }
}

window.onload = function() {
  canvas = document.getElementById('gameCanvas');
  canvasContext = canvas.getContext('2d');

  var framesPerSecond = 30;
  setInterval(function() {
      moveEverything();
      drawEverything();
    }, 1000/framesPerSecond);

  canvas.addEventListener('mousedown', handleMouseClick);

  canvas.addEventListener('mousemove',
    function(evt) {
      var mousePos = calculateMousePos(evt);
      paddle1Y = mousePos.y - (PADDLE_HEIGHT/2);
    });
}

function ballReset() {
  if(player1Score >= WINNING_SCORE ||
    player2Score >= WINNING_SCORE) {

    showingWinScreen = true;
    addFinalScore()
  }


  ballSpeedX = -ballSpeedX;
  ballX = canvas.width/2;
  ballY = canvas.height/2;
}

function computerMovement() {
  var paddle2YCenter = paddle2Y + (PADDLE_HEIGHT/2);
  if(paddle2YCenter < ballY - 35) {
    paddle2Y = paddle2Y + 6;
  } else if(paddle2YCenter > ballY + 35) {
    paddle2Y = paddle2Y - 6;
  }
}

function moveEverything() {
  if(showingWinScreen) {
    return;
  }

  computerMovement();

  ballX = ballX + ballSpeedX;
  ballY = ballY + ballSpeedY;

  if(ballX < 0) {
    if(ballY > paddle1Y &&
      ballY < paddle1Y+PADDLE_HEIGHT) {
      ballSpeedX = -ballSpeedX;

      var deltaY = ballY
          -(paddle1Y+PADDLE_HEIGHT/2);
      ballSpeedY = deltaY * 0.35;
    } else {
      player2Score++; // must be BEFORE ballReset()
      ballReset();
    }
  }
  if(ballX > canvas.width) {
    if(ballY > paddle2Y &&
      ballY < paddle2Y+PADDLE_HEIGHT) {
      ballSpeedX = -ballSpeedX;

      var deltaY = ballY
          -(paddle2Y+PADDLE_HEIGHT/2);
      ballSpeedY = deltaY * 0.35;
    } else {
      player1Score++; // must be BEFORE ballReset()
      ballReset();
    }
  }
  if(ballY < 0) {
    ballSpeedY = -ballSpeedY;
  }
  if(ballY > canvas.height) {
    ballSpeedY = -ballSpeedY;
  }
}

function drawNet() {
  for(var i=0;i<canvas.height;i+=40) {
    colorRect(canvas.width/2-1,i,2,20,'white');
  }
}


function addFinalScore() {
  if(player1Score >= WINNING_SCORE) {
    count1_final++;
    document.getElementById("player_1").innerHTML = count1_final;

  } else {
    count2_final++;
    document.getElementById("player_2").innerHTML = count2_final;
  }
}

function drawEverything() {
  // next line blanks out the screen with black
  colorRect(0,0,canvas.width,canvas.height,'black');

  if(showingWinScreen) {
    canvasContext.fillStyle = 'white';

    if(player1Score >= WINNING_SCORE) {
      canvasContext.fillText("Player 1 Won", 350, 200);
      // count1_final++;
      // document.getElementById("player_1").innerHTML = count1_final;
      console.log(count1_final)

    } else if(player2Score >= WINNING_SCORE) {
      canvasContext.fillText("Player 2 Won", 350, 200);
      // count2_final++;
      // console.log(player2final_score)
      // document.getElementById("player_2").innerHTML = count2_final;
      console.log(count2_final)

    }

    canvasContext.fillText("Play Again", 350, 500);
    return;
  }

  drawNet();

  // this is left player paddle
  colorRect(0,paddle1Y,PADDLE_THICKNESS,PADDLE_HEIGHT,'white');

  // this is right computer paddle
  colorRect(canvas.width-PADDLE_THICKNESS,paddle2Y,PADDLE_THICKNESS,PADDLE_HEIGHT,'white');

  // next line draws the ball
  colorCircle(ballX, ballY, 10, 'white');

  canvasContext.fillText(player1Score, 100, 100);
  canvasContext.fillText(player2Score, canvas.width-100, 100);
}

function colorCircle(centerX, centerY, radius, drawColor) {
  canvasContext.fillStyle = drawColor;
  canvasContext.beginPath();
  canvasContext.arc(centerX, centerY, radius, 0,Math.PI*2,true);
  canvasContext.fill();
}

function colorRect(leftX,topY, width,height, drawColor) {
  canvasContext.fillStyle = drawColor;
  canvasContext.fillRect(leftX,topY, width,height);
}
</script>
</head>
</body>

body {
  background: #283048;  /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #859398, #283048);  /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #859398, #283048); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */

}

h1 {
  color: white;
  text-align: center;
}

#gc {
  float: left;
}

#sb {
  float: right;
  margin-right: 50px;
  border: 2px solid;
  padding: 20px;
}