我試圖做一個簡單的(或者我以爲)記憶遊戲。不幸的是,當用戶點擊它們時,它不會更新卡的狀態。我正在用盡想法,可能是因爲這是我的第一個JavaScript遊戲。我猜遊戲循環有問題。任何人都可以至少指出我的方向是否正確,並幫助我理解需要更改/重寫的內容?簡單記憶遊戲不會更新其狀態。糟糕的遊戲循環?
//HTML5 Memory Game implementation
//main variables
var cards = [1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8];
var exposed = [makeArray("false",16)];
var first_card = 0;
var second_card = 0;
var moves = 0;
var WIDTH = 800;
var HEIGHT = 100;
var state = 0;
var mouseX = 0;
var mouseY = 0;
//creating canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = WIDTH;
canvas.height = HEIGHT;
document.getElementById("game").appendChild(canvas);
//filling empty array with number,character,object
function makeArray(value, length) {
var newArray = [];
var i = 0;
while (i<length) {
newArray[i] = value;
i++;
}
return newArray;
}
//shuffling algorithm
function shuffle(array) {
var copy = [];
var n = array.length;
var i;
while (n) {
i = Math.floor(Math.random() * n--);
copy.push(array.splice(i, 1)[0]);
}
return copy;
}
//where user clicks
function getClickPosition(event) {
var X = event.pageX - canvas.offsetLeft;
var Y = event.pageY - canvas.offsetTop;
return mouse = [X, Y];
}
//read click position
function readPos(event) {
mousePos = getClickPosition(event);
mouseX = mousePos[0];
mouseY = mousePos[1];
}
//initializing
function init() {
state = 0;
moves = 0;
exposed = [makeArray("false",16)];
cards = shuffle(cards);
}
//drawing cards
function draw() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (var i in cards) {
if (exposed[i] === true) {
ctx.fillStyle = "rgb(250, 250, 250)";
ctx.font = "50px Courier New";
ctx.fillText(cards[i], (i*50+12), 65);
} else {
ctx.strokeStyle = "rgb(250, 0, 0)";
ctx.fillStyle = "rgb(0, 0, 250)";
ctx.fillRect(i*50, 0, 50, 100);
ctx.strokeRect(i*50, 0, 50, 100);
}
}
};
//update cards
function update() {
if (exposed[parseInt(mouseX/50)] === false) {
if (state == 0) {
state = 1;
first_card = parseInt(mouseX/50);
exposed[parseInt(mouseX/50)] = true;
} else if (state == 1) {
state = 2;
second_card = parseInt(mouseX/50);
exposed[parseInt(mouseX/50)] = true;
} else {
if (cards[first_card] != cards[second_card]) {
exposed[first_card] = false;
exposed[second_card] = false;
}
state = 1;
first_card = parseInt(mouseX/50);
exposed[parseInt(mouseX/50)] = true;
}
}
}
addEventListener('click', readPos, false);
setInterval(function() {
update();
draw();
}, 16);
您是否嘗試過使用調試器來逐步瀏覽代碼並查看單擊時會發生什麼?您必須首先執行該操作,並將問題範圍縮小到無法按預期工作的那部分代碼。無論如何,這個過程應該可能導致你的解決方案,因爲它可能是微不足道的。祝你好運! – Mataniko
檢查您的點擊事件是否真正被觸發(例如,在其中放置一個斷點或將一個console.log放入其中以及一些相關數據)。我懷疑有必要有16ms的間隔;這可能會造成積壓。如果你讓間隔更大(比如200毫秒),情況會有所改善嗎?你甚至可能想重新考慮一個循環,讓點擊卡片來更新界面。如果mouseX和mouseY被正確設置,檢查update()是否訪問同一個變量(例如它們是否具有相同的值?)。如果他們這樣做,它是否轉化爲正確的卡片(或卡片?)。 – Sumurai8