Отредактировано, чтобы добавить: *********** @melomene не понравились мои массивы вызовов и rollP.Однако они были объявлены как массивы.Ниже я добавил полный файл javascript.
У меня есть 2 маленьких массива: roll [] и rollP [].У них есть только 2 предмета каждый.Когда функция 'checkDouble6 ()' запущена, содержимое roll сохраняется в rollP, как показано ниже.
rollP = roll;
Это единственное место в коде, в котором значения roll назначаются для rollP.
Каким-то образом это иногда происходит ДО вызова функции checkDouble6 (), даже если этот оператор ВНУТРИ функции checkDouble6 ().
Я сошел с ума от попытки console.logsвыяснить это.Anyhoo ..
Вот кодовые блоки для того, что происходит, когда игрок щелкает (что приводит к броску виртуальных кубиков), функция checkDouble6 () и функция для удержания.Удержание - это когда игрок решает сохранить текущий счет и позволяет следующему игроку взять свой ход.
По какой-то причине приоритетное назначение переменных НЕ происходит при первом переключении игрока.Я думаю, это потому, что функция switchPlayer () переназначает rollP на [0,0].Но после этого, каждый раз, когда игрок бросает, переменный массив rollP получает значения roll до вызова функции checkDouble6 ().
document.querySelector('.btn-roll').addEventListener('click', function(){
if (isGamePlaying){
//1.Random number is generated
roll[0] = Math.floor(Math.random()*6) + 1;
roll[1] = Math.floor(Math.random()*6) + 1;
//2.Display the result
document.querySelectorAll('.dice').forEach(diceClass=>diceClass.style.display = 'block');
document.getElementById('dice1').src = 'dice-'+roll[0]+'.png';
document.getElementById('dice2').src = 'dice-'+roll[1]+'.png';
console.log('roll before checkDouble6: '+roll);
console.log('rollP before checkDouble6: '+rollP);
checkDouble6();
console.log('roll after checkDouble6: '+roll);
console.log('rollP after checkDouble6: '+rollP);
//3.Update the round score IF the rolled number is not a 1
if( roll[0]!== 1 && roll[1]!==1){
//Add score
roundScore += roll[0]+roll[1];
document.getElementById('current-'+activePlayer).textContent = roundScore;
}else{
//Next player's turn.
roundScore = 0;
switchPlayer();
}
}
});
function checkDouble6(){
if (roll[0]===6 &&(roll[1]===6 || rollP[0]===6 || rollP[1]===6)){
//lose whole global score. Next player's turn.
scores[activePlayer]=0;
console.log('roll during checkDouble6: '+roll);
console.log('roll during checkDouble6: '+rollP);
switchPlayer();
} else if (roll[1]===6 &&(rollP[0]===6 || rollP[1]===6)){
//lose whole global score. Next player's turn.
scores[activePlayer]=0;
console.log('roll: '+roll);
console.log('rollP: '+rollP);
switchPlayer();
} else{
//everything is fine
}
rollP = roll;
console.log('roll at end of checkDouble6 function: '+roll);
console.log('rollP at end of checkDouble6 function: '+rollP);
};
Есть так много console.logs, потому что я пытался вычислитькак это происходило.А ниже находится функция «удерживать».Опять же, это происходит не сразу после переключения ходов игрока, вероятно, из-за установки переката на [0,0].
document.querySelector('.btn-hold').addEventListener('click', function(){
if (isGamePlaying){
//Add current score to global score
scores[activePlayer] += roundScore;
//Update UI
document.getElementById('score-'+activePlayer).textContent = scores[activePlayer];
//Check if player won the game
if (scores[activePlayer]>=100){
//they won
document.getElementById('name-'+activePlayer).textContent = 'WINNER!';
document.querySelector('.dice').style.display = 'none';
document.querySelector('.player-'+activePlayer+'-panel').classList.remove('active');
document.querySelector('.player-'+activePlayer+'-panel').classList.add('winner');
isGamePlaying = false;
}else{
//they didn't win. Next player's turn.
switchPlayer();
}
}
});
Вот и весь шебанг:
var scores, roundScore, activePlayer, isGamePlaying;
var roll = new Array(2);
var rollP = new Array(2);
initializeGame();
//document.querySelector('#current-0').textContent = dice;
//document.querySelector('#current-'+activePlayer).innerHTML = '<em>'+dice+'</em>';
document.querySelector('.btn-roll').addEventListener('click', function(){
// This would be an anonymous function
if (isGamePlaying){
//1.Random number is generated
roll[0] = Math.floor(Math.random()*6) + 1;
roll[1] = Math.floor(Math.random()*6) + 1;
//2.Display the result
document.querySelectorAll('.dice').forEach(diceClass=>diceClass.style.display = 'block');
document.getElementById('dice1').src = 'dice-'+roll[0]+'.png';
document.getElementById('dice2').src = 'dice-'+roll[1]+'.png';
console.log('roll before checkDouble6: '+roll);
console.log('rollP before checkDouble6: '+rollP);
checkDouble6();
console.log('roll after checkDouble6: '+roll);
console.log('rollP after checkDouble6: '+rollP);
//3.Update the round score IF the rolled number is not a 1
if( roll[0]!== 1 && roll[1]!==1){
//Add score
roundScore += roll[0]+roll[1];
document.getElementById('current-'+activePlayer).textContent = roundScore;
}else{
//Next player's turn.
roundScore = 0;
switchPlayer();
}
}
});
document.querySelector('.btn-hold').addEventListener('click', function(){
if (isGamePlaying){
//Add current score to global score
scores[activePlayer] += roundScore;
//Update UI
document.getElementById('score-'+activePlayer).textContent = scores[activePlayer];
//Check if player won the game
if (scores[activePlayer]>=100){
//they won
document.getElementById('name-'+activePlayer).textContent = 'WINNER!';
document.querySelector('.dice').style.display = 'none';
document.querySelector('.player-'+activePlayer+'-panel').classList.remove('active');
document.querySelector('.player-'+activePlayer+'-panel').classList.add('winner');
isGamePlaying = false;
}else{
//they didn't win. Next player's turn.
switchPlayer();
}
}
});
function switchPlayer(){
// Set round scores to 0
roundScore = 0;
roll = [0,0];
rollP = [0,0];
document.getElementById('current-0').textContent = 0;
document.getElementById('current-1').textContent = 0;
// Toggle the visuals
document.querySelector('.player-0-panel').classList.toggle('active');
document.querySelector('.player-1-panel').classList.toggle('active');
//change active player from one to the other
console.log('Switch from player-'+activePlayer);
activePlayer === 1 ? activePlayer = 0 : activePlayer = 1;
console.log('to player-'+activePlayer);
};
document.querySelector('.btn-new').addEventListener('click', initializeGame);
function initializeGame(){
roll = [0,0];
rollP = [0,0];
roundScore = 0;
scores = [0,0];
activePlayer = 0;
document.querySelectorAll('.dice').forEach(diceClass => diceClass.style.display = 'none');
document.getElementById('score-0').textContent = '0';
document.getElementById('score-1').textContent = '0';
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.getElementById('name-0').textContent = 'Player 1';
document.getElementById('name-1').textContent = 'Player 2';
document.querySelector('.player-0-panel').classList.remove('winner');
document.querySelector('.player-1-panel').classList.remove('winner');
document.querySelector('.player-0-panel').classList.remove('active');
document.querySelector('.player-1-panel').classList.remove('active');
document.querySelector('.player-0-panel').classList.add('active');
isGamePlaying = true;
};
function checkDouble6(){
if (roll[0]===6 &&(roll[1]===6 || rollP[0]===6 || rollP[1]===6)){
//lose whole global score. Next player's turn.
scores[activePlayer]=0;
console.log('roll during checkDouble6: '+roll);
console.log('roll during checkDouble6: '+rollP);
switchPlayer();
} else if (roll[1]===6 &&(rollP[0]===6 || rollP[1]===6)){
//lose whole global score. Next player's turn.
scores[activePlayer]=0;
console.log('roll: '+roll);
console.log('rollP: '+rollP);
switchPlayer();
} else{
//everything is fine
}
rollP = roll;
console.log('roll at end of checkDouble6 function: '+roll);
console.log('rollP at end of checkDouble6 function: '+rollP);
};