【问题标题】:How do I add a Countdown Timer to my page如何将倒数计时器添加到我的页面
【发布时间】:2014-10-15 20:31:45
【问题描述】:

我目前正在使用 jquery 和 javascript 开发西蒙说类型游戏。

我已经在 github 上链接了游戏的完整副本

Github 下载并解压以完整查看游戏 https://github.com/Jamiex304/Simon_Says_Game_Demo(现已禁用)

我遇到了一个问题,我想添加一个玩家可以看到的计时器?

目前关卡会一直持续到用户点击序列中的错误按钮。

游戏的一些基本信息 用户将看到一个随机序列每个级别添加一个新序列和一个额外的移动 每次用户输入正确的序列时,他们都会进入下一个级别 所有信息都可以在附带的带有 cmets 的 JavaScript 中找到

我想补充什么

我只想添加一个计时器,当用户单击开始按钮时,它会在 10 秒后开始 每次输入正确的序列时,计时器都会重新启动 当他们到达 5 个正确的序列时,计时器会增加 5 秒,所以

我已经附上了处理游戏事件的 JavaScript 并且有一个完整网站的链接

任何帮助都会很棒

JavaScript

var game={ //game object
    level: 1, //current level
    turn: 0, //current turn
    difficulty: 1, // user difficulty
    score: 0, //current score
    active: false, //whether a turn is active or not
    handler: false, // whether the click and sound handlers are active
    shape: '.shape', // cached string for the pad class
    genSequence: [], //array containing the generated/randomized pads
    plaSequence: [], //array containing the users pad selections

    init: function(){                   //initialises the game
        if(this.handler === false){     //checks to see if handlers are already active
            this.initPadHandler();      //if not activate them
        }
        this.newGame();             //reset the game defaults

    },

    initPadHandler: function(){

        that=this;

        $('.pad').on('mouseup',function(){

            if(that.active===true){

                var pad=parseInt($(this).data('pad'),10);

                that.flash($(this),1,300, pad);

                that.logPlayerSequence(pad);

            }
        });

        this.handler=true;

    },

    newGame: function(){            //resets the game and generates a starts a new level

        this.level=1;
        this.score=0;
        this.newLevel();
        this.displayLevel();
        this.displayScore();

    },

    newLevel: function(){

        this.genSequence.length=0;
        this.plaSequence.length=0;
        this.pos=0;
        this.turn=0;
        this.active=true;

        this.randomizePad(this.level); //randomize pad with the correct amount of numbers for this level
        this.displaySequence(); //show the user the sequence

    },

    flash: function(element, times, speed, pad){ //function to make the pads appear to flash

        var that = this;                        //cache this

        if(times > 0){                          //make sure we are supposed to flash
            that.playSound(pad);                //play the corresponding pad sound
            element.stop().animate({opacity: '1'}, {        //animate the element to appear to flash
                duration: 50,
                complete: function(){
                element.stop().animate({opacity: '0.6'}, 200);
                }
            });                                             //end animation

        }

        if (times > 0) {                                    //call the flash function again until done the correct amount of times 
            setTimeout(function () {
                that.flash(element, times, speed, pad);
            }, speed);
            times -= 1;                     //times - 1 for each time it's called
        }
    },

    playSound: function(clip){              //plays the sound that corresponds to the pad chosen


        var sound= $('.sound'+clip)[0];
        console.log(sound);
        console.log($('.sound'+clip));
        sound.currentTime=0;                //resets audio position to the start of the clip
        sound.play();                       //play the sound


    },

    randomizePad: function(passes){         //generate random numbers and push them to the generated number array iterations determined by current level

        for(i=0;i<passes;i++){

            this.genSequence.push(Math.floor(Math.random() * 4) + 1);
        }
    },

    logPlayerSequence: function(pad){       //log the player selected pad to user array and call the checker function

        this.plaSequence.push(pad);
        this.checkSequence(pad);


    },

    checkSequence: function(pad){           //checker function to test if the pad the user pressed was next in the sequence

        that=this;

        if(pad !== this.genSequence[this.turn]){    //if not correct 

                this.incorrectSequence();

            }else{                                  //if correct
                this.keepScore();                   //update the score
                this.turn++;                        //incrememnt the turn

            }

        if(this.turn === this.genSequence.length){  //if completed the whole sequence

            this.level++;                           //increment level, display it, disable the pads wait 1 second and then reset the game
            this.displayLevel();
            this.active=false;
            setTimeout(function(){
                that.newLevel();
            },1000);
        }
    },

    displaySequence: function(){                    //display the generated sequence to the user

        var that=this;

        $.each(this.genSequence, function(index, val) {     //iterate over each value in the generated array

            setTimeout(function(){

                that.flash($(that.shape+val),1,300,val);

            },500*index*that.difficulty);               // multiply timeout by how many items in the array so that they play sequentially and multiply by the difficulty modifier
        });
    },

    displayLevel: function(){                           //just display the current level on screen

        $('.level h2').text('Level: '+this.level);

    },

    displayScore: function(){                           //display current score on screen
        $('.score h2').text('Score: '+this.score);
    },

    keepScore: function(){                              //keep the score

        var multiplier=0;

        switch(this.difficulty)                         //choose points modifier based on difficulty
        {
            case '2':
                multiplier=1;
                break;

            case '1':
                multiplier=2;
                break;

            case '0.5':
                multiplier = 3;
                break;

            case '0.25':
                multiplier = 4;
                break;
        }

        this.score += (1 * multiplier);                 //work out the score

        this.displayScore();                            //display score on screen
    },

    incorrectSequence: function(){                      //if user makes a mistake

        var corPad = this.genSequence[this.turn],       //cache the pad number that should have been pressed

            that = this;
            this.active=false;
            this.displayLevel();
            this.displayScore();

        setTimeout(function(){                          //flash the pad 4 times that should have been pressed
            that.flash($(that.shape+corPad),4,300,corPad);
        },500);

        $('.start').show();                             //enable the start button again and allow difficulty selection again
        $('.difficulty').show();

    }

};
$(document).ready(function(){                           //document ready

    $('.start').on('mouseup', function(){               //initialise a game when the start button is clicked
        $(this).hide();
        game.difficulty = $('input[name=difficulty]:checked').val();
        $('.difficulty').hide();
        game.init();


    });


});

【问题讨论】:

  • 你是说你想增加每个级别的计时器......所以我可以知道我在你的游戏中升级了吗..?或者换句话说,我如何在你的小提琴中玩游戏..?
  • @TJ 抱歉,目前小提琴不会玩游戏,但它是如何工作的,当你点击开始时,如果你按正确的顺序点击它们,2 个圆圈会一个接一个地亮起你通过1 级,然后游戏会向您显示一个新的序列,此时 3 个圆圈会亮起,依此类推,每次您输入正确的序列时,您会升一级并显示在下方
  • 如果代码行不通,你怎么期望有人相应地编写代码..?!!
  • @TJ 我明白这就是为什么我把它放在我的 github 上并添加了问题的链接,因为我无法让它在小提琴中运行,对不起,我在这里尝试一切
  • 糟糕,Nvm,我没有注意到 github 的链接...

标签: javascript jquery html css javascript-events


【解决方案1】:

好的,我想我已经按照你想要的方式做到了,这里是完整的 js:

(我已经评论了我添加的部分)

var game={ //game object
    level: 1, //current level
    turn: 0, //current turn
    difficulty: 1, // user difficulty
    score: 0, //current score
    active: false, //whether a turn is active or not
    handler: false, // whether the click and sound handlers are active
    shape: '.shape', // cached string for the pad class
    genSequence: [], //array containing the generated/randomized pads
    plaSequence: [], //array containing the users pad selections

    init: function(){                   //initialises the game
        if(this.handler === false){     //checks to see if handlers are already active
            this.initPadHandler();      //if not activate them
        }
        this.newGame();             //reset the game defaults

    },

    initPadHandler: function(){

        that=this;

        $('.pad').on('mouseup',function(){

            if(that.active===true){

                var pad=parseInt($(this).data('pad'),10);

                that.flash($(this),1,300, pad);

                that.logPlayerSequence(pad);

            }
        });

        this.handler=true;

    },

    newGame: function(){            //resets the game and generates a starts a new level

        this.level=1;
        this.score=0;
        this.newLevel();
        this.displayLevel();
        this.displayScore();

        //initialize timer to 10 seconds
        this.timer = 10;  

    },

    newLevel: function(){

        this.genSequence.length=0;
        this.plaSequence.length=0;
        this.pos=0;
        this.turn=0;
        this.active=true;

        this.randomizePad(this.level); //randomize pad with the correct amount of numbers for this level
        this.displaySequence(); //show the user the sequence
    },

    flash: function(element, times, speed, pad){ //function to make the pads appear to flash

        var that = this;                        //cache this

        if(times > 0){                          //make sure we are supposed to flash
            that.playSound(pad);                //play the corresponding pad sound
            element.stop().animate({opacity: '1'}, {        //animate the element to appear to flash
                duration: 50,
                complete: function(){
                element.stop().animate({opacity: '0.6'}, 200);
                }
            });                                             //end animation

        }

        if (times > 0) {                                    //call the flash function again until done the correct amount of times 
            setTimeout(function () {
                that.flash(element, times, speed, pad);
            }, speed);
            times -= 1;                     //times - 1 for each time it's called
        }
    },

    playSound: function(clip){              //plays the sound that corresponds to the pad chosen


        var sound= $('.sound'+clip)[0];
        console.log(sound);
        console.log($('.sound'+clip));
        sound.currentTime=0;                //resets audio position to the start of the clip
        sound.play();                       //play the sound


    },

    randomizePad: function(passes){         //generate random numbers and push them to the generated number array iterations determined by current level

        for(i=0;i<passes;i++){

            this.genSequence.push(Math.floor(Math.random() * 4) + 1);
        }
    },

    logPlayerSequence: function(pad){       //log the player selected pad to user array and call the checker function

        this.plaSequence.push(pad);
        this.checkSequence(pad);


    },

    checkSequence: function(pad){           //checker function to test if the pad the user pressed was next in the sequence

        that=this;

        if(pad !== this.genSequence[this.turn]){    //if not correct 

                this.incorrectSequence();

            }else{                                  //if correct
                this.keepScore();                   //update the score
                this.turn++;                        //incrememnt the turn

            }

        if(this.turn === this.genSequence.length){  //if completed the whole sequence

            this.level++;                           //increment level, display it, disable the pads wait 1 second and then reset the game
            this.displayLevel();
            this.active=false;

            // Stop counting when sequence is correct to avoid time running out before starting next level
            clearInterval(this.timerInterval);

            //Add 5 seconds each 5th level
            this.timer = 10 + 5 * Math.floor(this.level / 5);

            //Update timerdisplay to show fulltime while displaying next level sequence
            $(".Timer p").html(this.timer);

            setTimeout(function(){
                that.newLevel();
            },1000);
        }
    },

    // Countdown and update timer, call incorrectsequence when time's up
    countDown: function(){ 
        this.timer -= 0.1;
        $(".Timer p").html(this.timer.toFixed(1));   // Display 9.0 instad of 9
        if(this.timer < 0.1){
            this.incorrectSequence();
        }
    },

    displaySequence: function(){                    //display the generated sequence to the user

        var that=this;

        var timerCount = 0;

        $.each(this.genSequence, function(index, val) {     //iterate over each value in the generated array
            timerCount = index;
            setTimeout(function(){

                that.flash($(that.shape+val),1,300,val);

            },500*index*that.difficulty);               // multiply timeout by how many items in the array so that they play sequentially and multiply by the difficulty modifier
        });

        // Wait to start timer until full sequence is displayed
        setTimeout(function(){ that.timerInterval = setInterval(function(){that.countDown()}, 100)}, 500*timerCount*that.difficulty);
    },

    displayLevel: function(){                           //just display the current level on screen

        $('.level h2').text('Level: '+this.level);

    },

    displayScore: function(){                           //display current score on screen
        $('.score h2').text('Score: '+this.score);
    },

    keepScore: function(){                              //keep the score

        var multiplier=0;

        switch(this.difficulty)                         //choose points modifier based on difficulty
        {
            case '2':
                multiplier=1;
                break;

            case '1':
                multiplier=2;
                break;

            case '0.5':
                multiplier = 3;
                break;

            case '0.25':
                multiplier = 4;
                break;
        }

        this.score += (1 * multiplier);                 //work out the score

        this.displayScore();                            //display score on screen
    },

    incorrectSequence: function(){                      //if user makes a mistake

        //Stop counting down timer and display start message
        clearInterval(this.timerInterval);
        $(".Timer p").html("Get Ready your time starts when you click start");

        var corPad = this.genSequence[this.turn],       //cache the pad number that should have been pressed

            that = this;
            this.active=false;
            this.displayLevel();
            this.displayScore();

        setTimeout(function(){                          //flash the pad 4 times that should have been pressed
            that.flash($(that.shape+corPad),4,300,corPad);
        },500);

        $('.start').show();                             //enable the start button again and allow difficulty selection again
        $('.difficulty').show();

    }

};
$(document).ready(function(){                           //document ready

    $('.start').on('mouseup', function(){               //initialise a game when the start button is clicked
        $(this).hide();
        game.difficulty = $('input[name=difficulty]:checked').val();
        $('.difficulty').hide();
        game.init();


    });


});

您可以在这里查看:JSFiddle(小提琴中的声音已禁用)

【讨论】:

    【解决方案2】:

    除了计时器之外,您并没有真正具体说明您想要什么,但是根据您的标记,您正在寻找类似这样的东西吗?

    Here is your updated fiddle

    var $timer = $('.Timer'),
        $timerTitle = $('.TimerTitle'),
        $start = $('.start'),
        $increment = $('.increment'),
        maxDuration = 10,
        defaultDuration = 10,
        count = 0,
        $gameCount = $('#gameCount');
        
    
    $timerTitle.text("Get ready! You have " + maxDuration + " seconds!");
    
    $start.on('click', function()
    {
        getDuration();
        return false;
    });
    
    function getDuration()
    {
        $start.prop('disabled', true);
        setTimeout(function()
        {
            var duration = $timer.data('duration');
            if(duration === undefined || duration < 0)
                duration = maxDuration;
            
            $timer.text(duration);
            $timer.data('duration', --duration);
            
            if(duration > -1)
            {
                if(duration < 5)
                {
                    if(duration % 2 == 0)
                    {
                        $timer.css({'background-color':'blue', 'color':'white'});
                    }
                    else
                    {
                        $timer.css({'background-color':'transparent', 'color':'black'});
                    }
                }
                getDuration();
            }
            else
            {
                count++;
                $gameCount.text("Current game count: " + count);
                if(count % 5 == 0)
                    defaultDuration += 5;
                
                maxDuration = defaultDuration;
                $timer.css({'background-color':'transparent', 'color':'black'});
                $timer.text('');
                $timerTitle.text("Get ready! You have " + maxDuration + " seconds!");
                $start.prop('disabled', false);
            }
        }, 1000);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <div align='center'>
    <div class="TimerTitle"></div>
    <div class="Timer"></div>
    <br />
    <button class="start">start</button>
    <div id='gameCount'>Current game count: 0</div>
    </div>

    【讨论】:

    • 再一次,这是一些有用的东西,但我不知道我在寻求帮助时如何不明确。我有一个游戏,我想添加一个计时器,当用户点击开始时,它会倒计时,每次他们完成一个级别时,它会在 10 级重新开始,并且在 5 级后上升 5 秒,你可以提供的任何帮助都是再次非常感谢
    • @Jamiex304 查看更新的小提琴,它会在 5 级后自动增加计时器
    • 再次,这与我想要的很接近,但正如我上面所说,我需要将游戏中的每个新关卡重置为 10,目前你的示例只是一直倒计时到 0,我已经更新了问题与所有信息。但感谢您抽出宝贵时间提供帮助
    • 我想你对如何让它停止倒计时到 0 而不是在游戏中的每个 lvl 之后刷新有任何其他想法?
    • 再次抱歉,但我需要帮助将其与上面的 javascript 代码联系起来,这样每次玩家升级时时间都会停止
    【解决方案3】:

    有点不合常规(不是倒数,而是倒数),但这是怎么回事:

    http://jsfiddle.net/rudiedirkx/nrp3e269/

    魔法是tick(),触发 60/s:

    var tickStart = 0;
    function tick() {
        var tickSpent = (Date.now() - tickStart) / 1000,
            timeLeft = startTimeLeft - tickSpent;
        tl.textContent = Math.round(timeLeft * 10) / 10;
        if ( timeLeft > 0 ) {
            requestAnimationFrame(tick);
        }
        else {
            document.body.classList.add('gameover');
        }
    }
    

    开始按钮开始计数:

    tickStart = Date.now();
    tick();
    

    移动按钮为计数增加时间:

    if ( ++moves % 5 == 0 ) {
        startTimeLeft += 5;
    }
    else {
        startTimeLeft += 1;
    }
    

    这只是一个概念证明。你将不得不做大部分。首先是让它成为一个不错的 CountDown 对象,其中包含方法和本地属性,而不是全局属性。

    CountDown.startTimeLeft
    CountDown.tickStart
    CountDown.tick()
    CountDown.start()
    CountDown.finish()
    CountDown.addTime()
    

    将您的应用逻辑与股票代码分开。

    【讨论】:

    • 对不起,但这让我完全失去了我遇到的问题是将计时器与游戏联系起来,所以每次用户完成一个关卡我都需要它重新开始你可以看到游戏如何从 github 链接运行,但无论如何感谢
    • 就像我说的:你需要做大部分。我们可以帮助您处理计时器逻辑,但您必须编写游戏。
    • 这就是我在这里的原因,我发现了各种形式的计时器的多个示例,我遇到的问题是让计时器与我的游戏交互,这就是问题所在,但再次感谢
    • 没有尝试任何东西...您的具体问题是什么,我们可以帮助您解决问题,以便您将其应用到游戏中?
    • 我很难相信你制作了这个游戏(相当高级的东西),但不知道如何添加一个简单的计时器......
    【解决方案4】:

    这样的方法可能有用吗?

    var n = 100;
    setTimeout(countDown,1000);
    
    function countDown(){
       n--;
       if(n > 0){
          setTimeout(countDown,1000);
       }
       $(".timer").html(n);
    }
    

    http://jsfiddle.net/gfdq8krd/

    【讨论】:

    • 这与我想要的很接近,但我不希望计时器启动直到用户开始游戏,第二个如果它达到零我希望游戏结束
    【解决方案5】:

    如果我理解你只是想倒计时?从10秒等等? 我认为这个脚本会帮助你

    <script>
    
    <!-- 
    //change below target URL to your own OTHERWISE DELETE
    // this link will redirect you to the main page or the page you want
    var targetURL="example.com" 
    //change the second to start counting down from 
    var countdownfrom=10
    
    var currentsecond=document.redirect.redirect2.value=countdownfrom+1 
    function countredirect(){ 
    if (currentsecond!=1){ 
    currentsecond-=1 
    document.redirect.redirect2.value=currentsecond 
    } 
    else{ 
    window.location=targetURL 
    return 
    } 
    setTimeout("countredirect()",1000) 
    }
    
    countredirect() 
    //--> 
    </script>
    

    【讨论】:

    • 我可以看到您要向我展示的内容,但是,它没有为用户显示倒计时,我已经尝试过但没有重置,而且我一直收到错误,未捕获的 TypeError:不能读取未定义的属性“redirect2”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    相关资源
    最近更新 更多