如何在我的复选框中添加功能?

时间:2014-10-30 12:09:25

标签: javascript jquery html css onclick

我目前正在为游戏添加功能,我有2个用户选项

他们可以禁用flash和文本

我目前有两个复选框,用户必须在开始游戏前检查他们想要的功能

我想添加一个onclick函数,如果用户在运行它时选择了该功能将在游戏中的复选按钮,并且如果它们没有它将不会

例如,如果用户想要闪光灯,则选中复选框等

为了更好地理解小提琴,看看我的意思

Heres是一个小提琴完整游戏的链接(声音已被禁用,因为它没有被小提琴支持)还要确保你扩展它以查看所有游戏和侧栏

http://jsfiddle.net/uusL7hch/17/

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
    colors: ['green', 'red', 'purple', 'blue'],
    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 (10.0)
        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
        return; //not supported in jsfiddle
////////////////////////////////////////////////////////////////////////////////////////////////////////////
        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.0 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);
                $(".TextBox").children(":first").html('<b>'+that.colors[val-1]+'</b>');
            }, 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)
        setTimeout(function(){$(".TextBox").children(":first").html('');}, 500);
        }, 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);
        
        $(".TextBox").children(":first").html("<b>the good answer was "+that.colors[corPad-1]+"</b>");
        
        $('.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();
    });
});
body {
    background-color: #333;
    color: #fff;
}

ul {
    list-style: none;
    margin: 0 0 20px 0;
    padding: 0;
    text-align: center;
}

li {
    display: inline-block;
    padding: 3px;
}

.wrapper2 {
    position: relative;
    float:left;
    width: 650px;
    height: 700px;
    margin-left:25%;
    -moz-border-radius: 15px;border-radius: 15px;border: 5px groove #8E2B2B; padding-left: 0.5em;
}

.wrapper3{
    position: relative;
    float:right;
    width: 300px;
    height: 700px;
    margin-right:1%;
    -moz-border-radius: 15px;border-radius: 15px;border: 5px groove #8E2B2B; padding: 0.5em;
}

.Timer{
    width:300px;
    height:200px;
    margin-top:235px;
    margin-left:177px;
    border:5px solid white;
    border-radius: 50%;
    background-color:black;
    text-align:center;
}

.TextBox{
    width:300px;
    height:50px;
    margin-top:30px;
    margin-left:177px;
    border:5px solid white;
    background-color:black;
    text-align:center;
}

.pad {
    z-index: 1;
    margin: 10px;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=60)";
    filter: alpha(opacity=60);
    opacity: 0.6;
}

.shape1 {
    position: absolute;
    left: 50%;
    margin-left: -50px;
    width: 125px;
    height: 125px;
    background-color: green;
    border-radius: 50%;
}

.shape2 {
    position: absolute;
    left: 50%;
    bottom: 2.5px;
    margin-left: -50px;
    width: 125px;
    height: 125px;
    background-color: red;
    border-radius: 50%;
}

.shape3 {
    position: absolute;
    left: 78%;
    right: 50%;
    bottom: 50%;
    margin-bottom: -50px;
    margin-right: -50px;
    width: 125px;
    height: 125px;
    background-color: purple;
    border-radius: 50%;
}

.shape4 {
    position: absolute;
    left: 0;
    bottom: 50%;
    margin-bottom: -50px;
    width: 125px;
    height: 125px;
    background-color: blue;
    border-radius: 50%;
}

.level, .score {
    width: 50%;
    float: left;
    text-align: center;
}

.sButton {
    width: 30%;
    margin: 0 auto;
    color: black;
    border: 3pt ridge Black;
    font-weight: bold;
}

.start {
    width: 100%;
    height: 30px;
    text-align: center;
}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="wrapper2">
        <div class="pad shape1" data-pad="1">
            <audio preload="auto" class="sound1">
                <source src="Media/mp3/sounds_01.mp3" type="audio/mpeg"/>
                <source src="Media/ogg/sounds_01.ogg" type="audio/ogg"/>
            </audio>
        </div>
        <div class="pad shape2" data-pad="2">
            <audio preload="auto" class="sound2">
                <source src="Media/mp3/sounds_02.mp3"  type="audio/mpeg"/>
                <source src="Media/ogg/sounds_02.ogg" type="audio/ogg"/>
            </audio>
        </div>
        <div class="Timer">
            <br />
            <br />
            <br />
            <br />
            <p><b>Get Ready your time starts when you click start</b></P>
        </div>            
        <div class="TextBox">
            <p><b>Get Ready and click the buttons who's name appear here</b></P>
        </div>
        <div class="pad shape3" data-pad="3">
            <audio preload="auto" class="sound3">
                <source src="Media/mp3/sounds_03.mp3" type="audio/mpeg"/>
                <source src="Media/ogg/sounds_03.ogg" type="audio/ogg"/>
            </audio>
        </div>
        <div class="pad shape4" data-pad="4">
            <audio preload="auto" class="sound4">
                <source src="Media/mp3/sounds_04.mp3" type="audio/mpeg"/>
                <source src="Media/ogg/sounds_04.ogg" type="audio/ogg"/>
            </audio>
        </div>
    </div>

    <div class="wrapper3">
        <div class="level">
            <h2>Level: 1</h2>
        </div>
        <div class="score">
            <h2>Score: 0</h2>
        </div>
        
        <ul class="difficulty">
            <li>
                <input type="radio" class="difOpt" name="difficulty" value="2">Easy
            </li>
            <li>
                <input type="radio" class="difOpt" name="difficulty" value="1" checked>Normal
            </li>
            <li>
                <input type="radio" class="difOpt" name="difficulty" value="0.5">Hard
            </li>
            <li>
                <input type="radio" class="difOpt" name="difficulty" value="0.25">Insane
            </li>
        </ul>
        <p>Do You want Flashes ? </p>
        <input type="checkbox"value="No"style="color: Black;">Yes

        <p>Do You want Text ? </p>
        <input type="checkbox"value="No"style="color: Black;">Yes
        <br />
        <div class="sButton">
            <button class="start">START</button>
        </div>
    </div>  
</body>

任何帮助都会很棒

1 个答案:

答案 0 :(得分:1)

您需要通过添加ID来更改声音复选框,以便更轻松地使用jQuery

进行选择
<input type="checkbox"value="No"style="color: Black;" id="sound">

您需要更改playSound功能以检查是否应该播放声音,方法是查看是否选中了声音复选框

...
playSound: function (clip) { //plays the sound that corresponds to the pad chosen
    if($("#sound").is(":checked")) {
        var sound = $('.sound' + clip)[0];
        console.log(sound);
        console.log($('.sound' + clip));
        if(sound.duration) {
            sound.currentTime = 0; //resets audio position to the start of the clip
            sound.play(); //play the sound
        }
    }
}
...

这是由此产生的小提琴http://jsfiddle.net/uusL7hch/16/