如果满足两个条件,则获得加分

Get a plus score if two conditions are met?

本文关键字:条件 两个 满足 如果      更新时间:2023-09-26

我试图构建一个游戏,但遇到了一个问题。这个想法是,如果满足两个条件,就可以获得+1分。如果显示特定的随机图像并单击特定的按钮,如果满足这两个条件,我想获得+1分,分数应该增加一分。到目前为止,这是我的代码。

如果显示了特定的图片,代码确实有效,并将分数提高一分,但我也需要点击按钮才能正常工作。

var clicks = 0;  
var myPix = ["faces/angry.png", "faces/happy.png", "faces/normal.png","faces /pur.png","faces/sad.png"];
function choosePic() {
    var randomNum = Math.floor(Math.random() * myPix.length);
    document.getElementById("myPicture").src = myPix[randomNum];
    if ([randomNum]  == 1) {
        clicks++;updateClickCount();
    }
}
function startTimer() {
    setInterval(choosePic, 1000);
}

一些建议:

  1. 添加全局变量myPicture,该全局变量保持实际图像的索引。将函数choosePic中的变量randomNum更改为myPicture。删除函数中的条件。

  2. 添加一些带有事件onclick和适当功能的按钮来处理单击。

    <button onclick="clicked(0);">angry</button>
    
  3. 添加单击事件的函数。

    function clicked(index) {
        // this checks the actual picture index with the index of the button
        if (myPicture === index) {
            clicks++;
            updateClickCount();
        }
    }
    
  4. 添加显示点击次数的功能

    function updateClickCount() {
        document.getElementById('count').innerHTML = clicks;
    }
    
  5. 启动间隔

    startTimer();
    

这里的工作代码没有图像:

var clicks = 0,
    myPix = ["faces/angry.png", "faces/happy.png", "faces/normal.png", "faces /pur.png", "faces/sad.png"],
    myPicture;
function choosePic() {
    myPicture = Math.floor(Math.random() * myPix.length);
    document.getElementById("myPicture").src = myPix[myPicture];
    // only to the see the picture name
    document.getElementById("myPicture").alt = myPix[myPicture];
}
function startTimer() {
    setInterval(choosePic, 1000);
}
function clicked(index) {
    if (myPicture === index) {
        clicks++;
        updateClickCount();
    }
}
function updateClickCount() {
    document.getElementById('count').innerHTML = clicks;
}
startTimer();
<img id="myPicture" width="100" height="50"/><br />
<button onclick="clicked(0);">angry</button>
<button onclick="clicked(1);">happy</button>
<button onclick="clicked(2);">normal</button>
<button onclick="clicked(3);">pur</button>
<button onclick="clicked(4);">sad</button><br />
Count: <span id="count">0</span>