如何添加一个倒数计时器到我的页面 [英] How do I add a Countdown Timer to my page

查看:115
本文介绍了如何添加一个倒数计时器到我的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我已经在github上链接了完整的游戏副本
$ b Github下载和解压缩游戏完全是
https://github.com/Jamiex304/Simon_Says_Game_Demo
(现在禁用)



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



目前这个级别会持续下去,直到用户点击错误的按钮。

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



我想帮助添加什么



我只想添加一个计时器,当用户单击开始按钮
时,开始时间为10秒每次输入正确的顺序,计时器再次启动
当它们达到5个正确的序列时,计时器会增加5个额外的秒数,所以



我附加了处理游戏事件的JavaScript,并且链接到完整的网站



任何帮助都很棒

JavaScript

  var game = {//游戏对象
等级:1,//当前等级
转:0,//当前转
难度:1,//用户难度
得分:0,//当前得分
有效: false,//转弯是否有效
处理程序:false,//点击和声音处理程序是否处于活动状态
shape:'.shape',//缓冲区类的缓冲区字符串
genSequence:[],//包含生成的/随机化的pad的数组
plaSequence:[],//包含用户pad选项的数组
$ b $ init:function(){// initialises游戏
if(this.handler === false){//检查处理程序是否已经激活
this.initPadHandler(); //如果不激活它们

this.newGame(); //重置游戏默认值

},

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;
$ b $,

newGame:function(){//重置游戏并生成一个新的关卡

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); //用这个级别的正确数量的随机数pad
this.displaySequence(); //向用户显示顺序

},

flash:函数(元素,时间,速度,垫){//使垫子显示闪烁的功能

var that = this; //缓存这个

if(times> 0){//确定我们应该闪烁
that.playSound(pad); //播放相应的pad声音
element.stop()。animate({opacity:'1'},{//将元素动画显示为闪烁
持续时间:50,
完成:function(){
element.stop()。animate({opacity:'0.6',200);
}
}); //结束动画



if(times> 0){//再次调用flash函数直到完成正确的时间量
setTimeout(function (){
that.flash(element,times,speed,pad);
},speed);
次 - = 1; //时间 - 每次1时它被称为
}
},

playSound:function(clip){//播放与所选择的$ b $对应的声音b

var sound = $('。sound'+ clip)[0];
console.log(声音);
console.log($('。sound'+ clip));
sound.currentTime = 0; //将音频位置重置为剪辑的开始处
sound.play(); //播放声音


},

randomizePad:function(passes){//产生随机数并将它们推到生成的数组数组迭代中当前水平

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

logPlayerSequence:function(pad){//将玩家选择的垫记录到用户数组并调用检查器函数

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


},

checkSequence:function(pad){//检查函数用于测试用户按下的键盘是否在序列中的下一个

that = this;

if(pad!== this.genSequence [this.turn]){//如果不正确

this.incorrectSequence();

} else {//如果正确
this.keepScore(); //更新分数
this.turn ++; //增加轮次

}

if(this.turn === this.genSequence.length){//如果完成整个序列

this.level ++; //增量级别,显示它,禁用焊盘等待1秒,然后重置游戏
this.displayLevel();
this.active = false;
setTimeout(function(){
that.newLevel();
},1000);
}
},

displaySequence:function(){//将生成的序列显示给用户

var that = this;

$ .each(this.genSequence,function(index,val){//遍历生成数组中的每个值

setTimeout(function(){

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

},500 * index * that.difficulty); //将超时乘以多少项在数组中,以便它们按顺序播放并乘以难度修饰符
});
},

displayLevel:function(){//只显示屏幕上的当前等级

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


$ b displayScore:function(){//在屏幕上显示当前得分
$('。score h2')。text('Score:' + this.score);
},

keepScore:function(){//保留分数

var multiplier = 0;

switch(this.difficulty)//根据难度选择分数修饰符
{
case'2':
multiplier = 1;
休息;

案例'1':
乘数= 2;
休息;

案例'0.5':
乘数= 3;
休息;

案例'0.25':
乘数= 4;
休息;
}

this.score + =(1 * multiplier); //计算得分

this.displayScore(); //在屏幕上显示分数
},

incorrectSequence:function(){//如果用户犯了错误

var corPad = this.genSequence [this。转],//缓存应该被按下的垫号

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

setTimeout(function(){//闪动键盘4次应该被按下
that.flash($(that.shape + corPad),4,300,corPad);
},500);

$('。start')。show(); //再次启用启动按钮,并允许再次难以选择
$('。difficulty')。show();

}

}; $('。start')。on('mouseup',function(){//初始化一个游戏。
$(document).ready(function(){// document ready
$ b $当点击开始按钮
$(this).hide();
game.difficulty = $('input [name = difficulty]:checked')。val();
$ ('.difficulty')。hide();
game.init();


});


}) ;


解决方案

好吧,我想我已经设法做到了这是完整的js:



(我评论过我添加的部分)

  var game = {//游戏对象
等级:1,//当前等级
转:0,//当前转
难度:1 ,//用户难度
得分:0,//当前得分
active:false,//是否一个转动是否有效
处理程序:false,//点击和声音处理程序是活动的
形状:'.shape',//缓冲区类用于缓冲区类
genSequence:[],//包含生成/随机缓冲区的数组
plaSequence:[],//包含用户填充选择的数组

init:function(){//初始化游戏
if(this.handler === false){//检查处理程序是否已经处于活动状态
this.initPadHandler(); //如果不激活它们

this.newGame(); //重置游戏默认值

},

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;
$ b $,

newGame:function(){//重置游戏并生成一个新的关卡

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

//将计时器初始化为10秒
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); //用这个级别的正确数量的随机数pad
this.displaySequence(); //向用户显示序列
},

flash:function(element,times,speed,pad){//用于使焊盘显示为闪烁的功能

var that = this; //缓存这个

if(times> 0){//确定我们应该闪烁
that.playSound(pad); //播放相应的pad声音
element.stop()。animate({opacity:'1'},{//将元素动画显示为闪烁
持续时间:50,
完成:function(){
element.stop()。animate({opacity:'0.6',200);
}
}); //结束动画



if(times> 0){//再次调用flash函数直到完成正确的时间量
setTimeout(function (){
that.flash(element,times,speed,pad);
},speed);
次 - = 1; //时间 - 每次1时它被称为
}
},

playSound:function(clip){//播放与所选择的$ b $对应的声音b

var sound = $('。sound'+ clip)[0];
console.log(声音);
console.log($('。sound'+ clip));
sound.currentTime = 0; //将音频位置重置为剪辑的开始处
sound.play(); //播放声音


},

randomizePad:function(passes){//产生随机数并将它们推到生成的数组数组迭代中当前水平

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

logPlayerSequence:function(pad){//将玩家选择的垫记录到用户数组并调用检查器函数

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


},

checkSequence:function(pad){//检查函数用于测试用户按下的键盘是否在序列中的下一个

that = this;

if(pad!== this.genSequence [this.turn]){//如果不正确

this.incorrectSequence();

} else {//如果正确
this.keepScore(); //更新分数
this.turn ++; //增加轮次

}

if(this.turn === this.genSequence.length){//如果完成整个序列

this.level ++; //增量级别,显示它,禁用焊盘等待1秒,然后重置游戏
this.displayLevel();
this.active = false;

//当序列正确时停止计数,以避免在开始下一级之前耗尽时间
clearInterval(this.timerInterval);

//每5秒添加5秒
this.timer = 10 + 5 * Math.floor(this.level / 5);

//更新timerdisplay以在显示下一级序列时显示全部时间
$(。Timer p)。html(this.timer);
$ b setTimeout(function(){
that.newLevel();
},1000);



//倒计时和更新定时器,当时间到了时调用不正确的序列
countDown:function(){
this.timer - = 0.1;
$(。Timer p)。html(this.timer.toFixed(1)); //显示9.0
的9.0个实例if(this.timer< 0.1){
this.incorrectSequence();
}
},

displaySequence:function(){//将生成的序列显示给用户

var that = this;

var timerCount = 0;

$ .each(this.genSequence,function(index,val){//遍历生成数组中的每个值
timerCount = index;
setTimeout(function() {

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

},500 * index * that.difficulty); // multiply timeout数组中有多少物品,以便它们顺序地玩,并乘以难度修饰符
});

//等待启动计时器直到显示完整序列
setTimeout(function(){that.timerInterval = setInterval(function(){that.countDown()},100)}, 500 * * timerCount that.difficulty);
},

displayLevel:function(){//只显示屏幕上的当前等级

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


$ b displayScore:function(){//在屏幕上显示当前得分
$('。score h2')。text('Score:' + this.score);
},

keepScore:function(){//保留分数

var multiplier = 0;

switch(this.difficulty)//根据难度选择分数修饰符
{
case'2':
multiplier = 1;
休息;

案例'1':
乘数= 2;
休息;

案例'0.5':
乘数= 3;
休息;

案例'0.25':
乘数= 4;
休息;
}

this.score + =(1 * multiplier); //计算得分

this.displayScore(); //在屏幕上显示得分
},

incorrectSequence:function(){//如果用户犯了错误

//停止倒计时器并显示开始消息
clearInterval(this.timerInterval);
$(。Timer p)。html(当你点击开始时准备你的时间开始);

var corPad = this.genSequence [this.turn],//缓存应该按下的垫号

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

setTimeout(function(){//闪动键盘4次应该被按下
that.flash($(that.shape + corPad),4,300,corPad);
},500);

$('。start')。show(); //再次启用启动按钮,并允许再次难以选择
$('。difficulty')。show();

}

}; $('。start')。on('mouseup',function(){//初始化一个游戏。
$(document).ready(function(){// document ready
$ b $当点击开始按钮
$(this).hide();
game.difficulty = $('input [name = difficulty]:checked')。val();
$ ('.difficulty')。hide();
game.init();


});


}) ;

你可以在这里查看: JSFiddle (声音在小提琴中被禁用)


I am currently developing a Simon says type game using jquery and javascript.

I have linked a fully copy of the game on github

Github download and unzip to see the game fully https://github.com/Jamiex304/Simon_Says_Game_Demo(Disabled Now)

And I have reached a problem I want to add a timer that the player can see ?

currently the level will just go on til the user clicks the wrong button in the sequence.

Some Basic info on the game the user will see a random sequence each level a new sequence is added with one more extra move Each time the user enters the right sequence they go to the next level all info can be found in the attached JavaScript with comments

WHAT I WANT HELP ADDING

I just want to add a timer that starts at 10 seconds when the user clicks the start button Each time the enter the right sequence the timer starts again when they reach 5 right sequences the timer adds 5 extra seconds and so

I have attached the JavaScript that handles the game events and there is a link to the full site

Any help would be great

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();


    });


});

解决方案

Ok I think i've managed to do it the way you want it, here is full js:

(I've commented the parts i've added)

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();


    });


});

You can check it out here: JSFiddle (sounds disabled in fiddle)

这篇关于如何添加一个倒数计时器到我的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆