如何使用jQuery多次变量随机变量

时间:2013-08-22 17:58:54

标签: javascript jquery random

我正在尝试用jQuery制作一个卡片记忆游戏,但我遇到了一个小问题。我想要它,所以当你点击卡片时,每次启动程序时图像都是随机的。我也试图让它成为一张卡片所拥有的图像然后与另一张随机卡共享。现在我有卡,但是当随机选择图像时,它会应用于所有卡片。这是我到目前为止的JavaScript。如果有人能帮到我,那就太好了。

var score = 0;
var images = ["images are here"];
Image = images[Math.floor(Math.random() * images.length)];
$("#score").text("Number of turns: " + score);

$(".cards").mouseenter(function () {
    $(this).animate({
       height: "+=10px",
        width: "+=10px"
    });
});
$(".cards").mouseleave(function () {
    $(this).animate({
        height: "-=10px",
        width: "-=10px"
    });
});

$(".cards").click(function () {
    score++;
    $("#score").text("Number of turns: " + score);

    $(this).css({
        "background-image": 'url(' + Image + ')'
    });
});

编辑:这是html:

<body>
     <h5>card game</h5>

    <div id="card1" class="cards"></div>
    <div id="card2" class="cards"></div>
    <div id="card3" class="cards"></div>
    <div id="card4" class="cards"></div>
    <div id="card5" class="cards"></div>
    <div id="card6" class="cards"></div>
    <div id="score"></div>
</body>

2 个答案:

答案 0 :(得分:0)

在搞清楚之前,我盯着它看了很长时间。这是你的问题: 图像仅设置一次。每次用户点击时,您都需要重新分配Image。 以下是代码的外观:

var score = 0;
var images = ["images are here"];
$("#score").text("Number of turns: " + score);

$(".cards").mouseenter(function () {
    $(this).animate({
       height: "+=10px",
        width: "+=10px"
    });
});
$(".cards").mouseleave(function () {
    $(this).animate({
        height: "-=10px",
        width: "-=10px"
    });
});

$(".cards").click(function () {
    score++;
    $("#score").text("Number of turns: " + score);

    Image = images[Math.floor(Math.random() * images.length)];
    $(this).css({
        "background-image": 'url(' + Image + ')'
    });
});

注意:您用于随机化的方法并不能保证同一张卡不会弹出两次。

答案 1 :(得分:0)

如果我理解你的目标,你不想在点击卡片时随机选择卡片,否则你无法保证每张卡片只会出现两次,更不用说在游戏时更换了播放。相反,你想在一开始就洗牌一次。这是编码shuffle的一种方法:

var N = 10; // number of images
var indices = new Array(2*N);
for( var i=0 ; i<2*N ; ++i ) indices[i] = i>>1; // 0,0,1,1,2,2,...
// Do a Fisher-Yates shuffle
for( var i=2*N-1 ; 1<=i ; --i )
{
  var j = Math.floor( Math.random() * (i+1) ); // random 0 <= j <= i
  if( i == j ) continue;
  // Swap i and j
  indices[i] ^= indices[j];
  indices[j] ^= indices[i];
  indices[i] ^= indices[j];
}

将N更改为不同图像的数量。然后你牌组中的牌数是2 * N.

运行上面的代码后,访问您的混乱套牌图像[indices [0]],图像[indices [1]],图像[indices [2]],...,图像[indices [2 * N-] 1]]。每个图像将按照随机顺序在此序列中精确显示两次。

希望有所帮助。