如何在满足要求时添加自动计数器

时间:2014-09-16 21:12:53

标签: jquery html

我正在努力打造一款游戏。我真的很想做一个事件,当你有一个或多个工人时,他们会自动点击'外星人和外星人到我的柜台。为了使它更清晰,我有一个外星人的形象,当我点击它时,我有一个计数器向上嘀嗒一声。然后,我有一个雇用工人的按钮,我希望自动柜台只在我有一个或多个工人时工作。我希望自动计数器每秒向我的外星人计数器添加1个外星人,每个工人都会增加。

1名工人=每秒1名外国人 2名工人=每秒2名外国人 等

这是我的代码:

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <title>Clicker!</title>
</head>

<body>
    <h3 id="head1"><span id="Aliens">0</span> aliens</h3>
    <h3 id="head2"><span id="Empires">0</span> empires</h3>
    <h3 id="head3"><span id="Spaceships">0</span> spaceships</h3>
    <h3 id="head4"><span id="Planets">0</span> planets</h3>
    <h3 id="head5"><span id="SolarSystems">0</span> solarsystems</h3>
    <h3 id="head6"><span id="Galaxies">0</span> galaxies</h3>
    <h3 id="head7"><span id="Workers">0</span> workers</h3>
    <!--<p>You need <span id="test">0</span> aliens to hire a worker!</p>--> <!--Need to make dynamic-->
    <img id="Alien" src="alien.png">
    <img id="whirl" src="galaxy.jpg" style="width:25em; height:25em;">
    <button id="Purchase">Hire Workers</button>
</body>
<script>    
$(function() {
$('#Alien').click(function() {
    incrementCounter();
});

function incrementCounter() {
    var previousCounter = parseInt($("#Aliens").text());
    previousCounter = isNaN(previousCounter) ? 0: ++previousCounter;

    $("#Aliens").text(previousCounter);

    if(previousCounter % 25 === 0) {
        $("#Empires").text(previousCounter/25);
    }

    if(previousCounter % 100 === 0) {
        $("#Spaceships").text(previousCounter/100);
    }

    if(previousCounter % 1000 === 0) {
        $("#Planets").text(previousCounter/1000);
    }

    if(previousCounter % 10000 === 0) {
        $("#SolarSystems").text(previousCounter/10000);
    }

    if(previousCounter % 100000 === 0) {
        $("#Galaxies").text(previousCounter/100000);
    }

}

function resetCounter() {
    $("#Aliens").text(0);
}
});

</script>   
<script id="s2">
$(function() {
$('#Purchase').click(function() {
    automaticCounter();
});

function automaticCounter() {
    var workers = parseInt($("#Workers").text());
    workers = isNaN(workers) ? 0: ++workers;

    $("#Workers").text(workers);

    var autoCounter = parseInt($("#Aliens").text());
    autoCounter = isNaN(autoCounter) ? 0: autoCounter - 10 * workers;

    $("#Aliens").text(autoCounter);
}
});
</script>
</html>

我研究了一些计时器,但它们是制作时钟的字面计时器。我希望我不要太困惑!

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

只需在窗口/全局范围内调用setInterval(function, interval)即可。请参阅文档here

答案 1 :(得分:0)

<强> jsFiddle Demo

基本上,您将要使用1000毫秒的间隔来检查工作人员的文本,然后通过调用#Alien的点击事件来迭代这么多次。

var workerCheck = setInterval(function(){
  var workers = parseInt($("#Workers").text());
    if( workers > 0 ){
     for(var i = 0; i < workers; i++){
      $("#Alien").click();       
     }
    }
},1000);