Javascript 如何将倒计时计时器添加到我的页面

Javascript 如何将倒计时计时器添加到我的页面,javascript,jquery,html,css,javascript-events,Javascript,Jquery,Html,Css,Javascript Events,我目前正在使用jquery和javascript开发一个Simon says类型的游戏 我已经在github上链接了游戏的完整副本 Github下载并解压缩,以全面查看游戏 (现在已禁用) 我遇到了一个问题,我想添加一个计时器,玩家可以看到吗 目前,该级别将一直持续到用户按错顺序的按钮为止 关于游戏的一些基本信息 用户将看到一个随机序列每一级一个新的序列添加了一个额外的移动 每次用户输入正确的顺序时,他们都会进入下一个级别 所有信息都可以在附加的JavaScript中找到,并附上注释 我需要帮助

我目前正在使用jquery和javascript开发一个Simon says类型的游戏

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

Github下载并解压缩,以全面查看游戏 (现在已禁用)

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

目前,该级别将一直持续到用户按错顺序的按钮为止

关于游戏的一些基本信息 用户将看到一个随机序列每一级一个新的序列添加了一个额外的移动 每次用户输入正确的顺序时,他们都会进入下一个级别 所有信息都可以在附加的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();


    });


});
var-game={//game对象
级别:1,//当前级别
回合:0,//当前回合
难度:1,//用户难度
分数:0,//当前分数
活动:false,//转弯是否活动
handler:false,//单击和声音处理程序是否处于活动状态
形状:'.shape',//pad类的缓存字符串
genSequence:[],//包含生成/随机化焊盘的数组
plaSequence:[],//包含用户键盘选择的数组
init:function(){//初始化游戏
if(this.handler==false){//检查处理程序是否已处于活动状态
this.initPadHandler();//如果不激活它们
}
this.newGame();//重置游戏默认值
},
initPadHandler:function(){
那=这个;
$('.pad')。on('mouseup',function(){
if(that.active==true){
var pad=parseInt($(this).data('pad'),10);
flash($(这个),1300,pad);
logPlayerSequence(pad);
}
});
this.handler=true;
},
newGame:function(){//重置游戏并生成一个新的级别
这个。级别=1;
这个分数=0;
这个.newLevel();
这个.displayLevel();
这个.displayScore();
},
newLevel:function(){
此.genSequence.length=0;
此.plaSequence.length=0;
这是pos=0;
这个。转身=0;
这个.active=true;
this.randomizePad(this.level);//使用此级别的正确数字随机填充
this.displaySequence();//向用户显示序列
},
闪光:功能(元素、时间、速度、焊盘){//使焊盘闪烁的功能
var that=this;//缓存此
如果(次>0){//请确保我们应该闪烁
that.playSound(pad);//播放相应的pad声音
element.stop().animate({opacity:'1'},{//为元素设置动画,使其显示为闪烁
持续时间:50,
完成:函数(){
element.stop().animate({opacity:'0.6'},200);
}
});//结束动画
}
如果(次数>0){//再次调用flash函数,直到完成正确的次数
setTimeout(函数(){
闪光(元素、次数、速度、焊盘);
},速度);
times-=1;//每次调用它的次数为-1
}
},
播放声音:功能(剪辑){//播放与所选键盘对应的声音
var-sound=$('.sound'+clip)[0];
控制台。日志(声音);
console.log($('.sound'+clip));
sound.currentTime=0;//将音频位置重置为剪辑的开头
sound.play();//播放声音
},
randomizePad:函数(通过){//生成随机数,并将它们推送到由当前级别确定的生成的数组迭代数

对于(i=0;i这样的东西可能有用吗

var n = 100;
setTimeout(countDown,1000);

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

如果我知道你只想倒计时?从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>

除了计时器之外,你并没有明确说出你想要什么,但基于你的标记,你在寻找什么

var$timer=$('.timer'),
$timerTitle=$('.timerTitle'),
$start=$('.start'),
$increment=$('.increment'),
最大持续时间=10,
defaultDuration=10,
计数=0,
$gameCount=$(“#gameCount”);
$timertite.text(“准备好!您有”+maxDuration+“秒!”);
$start.on('click',function()
{
getDuration();
返回false;
});
函数getDuration()
{
$start.prop('disabled',true);
setTimeout(函数()
{
var duration=$timer.data('duration');
如果(持续时间==未定义| |持续时间<0)
持续时间=最大持续时间;
$timer.text(持续时间);
$timer.data('duration',--duration);
如果(持续时间>-1)
{
如果(持续时间<5)
{
如果(持续时间%2==0)
{
$timer.css({'background-color':'blue','color':'white'});
}
其他的
{
$timer.css({'background-color':'transparent','color':'black'});
}
}
getDuration();
}
其他的
{
计数++;
$gameCount.text(“当前游戏计数:+count”);
如果(计数%5==0)
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.startTimeLeft
CountDown.tickStart
CountDown.tick()
CountDown.start()
CountDown.finish()
CountDown.addTime()
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();


    });


});