0
我正在構建像西蒙一樣的記憶遊戲。我的問題是,在第一輪之後,即使在閱讀正確之後,它也會讀取其他所有內容。它也在控制檯中重複多次。我無法弄清楚爲什麼會發生這種情況。我相信問題在於player_turn和check_move函數的某處。JavaScript遊戲無法正常工作
我的所有的JavaScript代碼如下:
var sqrArray =['one', 'two', 'three', 'four'];
var game = {
count: 0,
sequence: [],
is_strict: false
}
// get random array element
function random_sqr() {
return sqrArray[Math.floor(Math.random() * 4)];
}
// adds and remove green background
function makelight(n) {
$('#' + n).addClass('light');
setTimeout(function() {
$('#' + n).removeClass('light');
}, 300);
}
// assignes makelight() in order of array elements
function play() {
var i = 0;
var sequenceInter = setInterval(function() {
makelight(game.sequence[i]);
i++;
if(i>=game.sequence.length) {
clearInterval(sequenceInter);
}
}, 600);
}
// adds random sqr to game
function addToSequence() {
game.sequence.push(random_sqr());
}
function play_game() {
game.count++
game.sequence.push(random_sqr());
play();
}
var checkCount = 0;
//player picks sqr
function player_pick() {
play_game();
player_turn();
}
function player_turn() {
if(checkCount < game.sequence.length) {
check_move();
} else {
checkCount = 0;
player_pick();
console.log('The end!');
console.log('check: ' + checkCount);
}
}
// Checks player choice
function check_move() {
$('.sqr').click(function() {
if(this.id === game.sequence[checkCount]) {
console.log('Correct!');
checkCount++;
console.log('after increment ' + checkCount);
player_turn();
} else if(this.id !== game.sequence[checkCount]) {
console.log('incorrect');
console.log('Array ' + game.sequence[checkCount]);
}
})
}
player_pick();
下面是HTML:
<div class="sqr" id="one" ></div>
<div class="sqr" id="two"></div>
<div class="sqr" id="three"></div>
<div class="sqr" id="four"></div>