所以我制作了一个游戏,我在HTML5 Canvas上点击它们打开盒子,然后尝试匹配盒子里的数字(长话短说,得到一个匹配=一个胜利,即第一个盒子可能是一个5,如果第二个盒子也是5,我赢了)。
单击一个框时,会在某个范围之间生成一个随机数。我需要的是一种方法来比较生成的数字,以检查玩家是否赢了或者是否需要继续打开盒子。
这些框的工作原理如下:
var rect = {
x: 30,
y: 150,
width: 100,
height: 100
};
function getMousePos(canvas, event) {
var rect = canvas.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
}
我曾考虑过存储随机生成的数字,如下所示:
var firstChoice = Math.floor(Math.random() * (10 - 5 + 1) + 10);
var secondChoice = Math.floor(Math.random() * (10 - 5 + 1) + 10);
但我不知道如何让程序识别出secondChoice,thirdChoice,4thChoice等需要在下一个方框而不是firstChoice中运行。
任何提示?
答案 0 :(得分:0)
如果您正在寻找的是一种存储和比较数据的方法......我会使用sessionStorage存储第一个单击的数据,然后将其比较,直到找到匹配为止:
// Player clicks box and generates number before the following function is called
function checkNumber(randomNumberGeneratedByRandomNumberGenerator) {
// Checks to see if there is a number already stored
if (sessionStorage.getItem("firstNumberClicked")) {
// Retrieve the stored number to use for comparison
const firstNumberClicked = sessionStorage.getItem("firstNumberClicked");
// Compare numbers, if they are exactly equal, hooray for user...if not, boo for user.
if (firstNumberClicked == randomNumberGeneratedByRandomNumberGenerator) {
alert("hooray, you won user!!!!");
sessionStorage.removeItem("firstNumberClicked");
} else {
alert("sorry user, better luck next time :(");
}
} else {
// There is not a number that already exists in storage, store the number passed to the function
sessionStorage.setItem("firstNumberClicked", randomNumberGeneratedByRandomNumberGenerator);
}
}
生成随机数后立即调用此函数