2Truth
2Truth

Reputation: 65

How can I add a button to display a timer when clicked

I have a simple memory game that is won by matching two letter. How can I add a button to start a timer that displays some where by the game, and when you win the timer stops but shows best times, furthermore, you can keep count to beat your best time. Also, how do I change my letter to substitute for images?

<title>Memory</title>
    </head>
    <body>
        <div id="container">
            <div id="header">
                Memory!
            </div>
            <div id="content">
                <table id="gameBoard">
                    <tbody>                 
                    </tbody>
                </table>
                <button id="playAgain">Play Again</button>
            </div>
        </div>

body {
    font-family:copperplate;
    font-size: 0.9em;
    background-color:#ccc;  
}

html, body {
    margin:0;
    padding:0;
    height:100%;
}

#container {
    width:950px;
    min-width:950px;
    background-color:#fff;
    margin:0 auto;
    min-height:100%;
}

#header {
    font-size:4em;
    line-height:95px;
    text-align:center;
    border-bottom:1px solid #000;
}

#content {
    clear:both;
    border-top:1px solid #000;
    padding-top:5px;
    padding:10px;
    text-align:center;
}

h1 {
    text-transform: capitalize;
}

#gameBoard {
    margin-left:auto;
    margin-right:auto;
    margin-bottom:25px;
}

.card {
    width:100px;
    height:100px;
    border:1px solid #000;
    cursor: pointer;
}

.down {
    background-color: #E8DD5B;  
}

.up {
    background-color: #ccc;
    line-height: 100px;
    text-align:center;
    font-size:5em;
}

button {
    font-size:2em;
    padding:5px;
    background-color:#E97A54;
}

$(function() {
                var cards = [
                    { id: 1, matchesId: 2, content: "A" },
                    { id: 2, matchesId: 1, content: "A" },
                    { id: 3, matchesId: 4, content: "B" },
                    { id: 4, matchesId: 3, content: "B" },
                    { id: 5, matchesId: 6, content: "C" },
                    { id: 6, matchesId: 5, content: "C" },
                    { id: 7, matchesId: 8, content: "D" },
                    { id: 8, matchesId: 7, content: "D" },
                    { id: 9, matchesId: 10, content: "E" },
                    { id: 10, matchesId: 9, content: "E" },
                    { id: 11, matchesId: 12, content: "F" },
                    { id: 12, matchesId: 11, content: "F" }
                ];
                var shuffledCards = [];
                var cardToMatchElement;

                setupGame();

                $("#playAgain").click(function() {
                    setupGame();
                });

                function setupGame() {
                    cardToMatchElement = null;
                    shuffleCards();
                    dealCards();
                }

                function shuffleCards() {
                    shuffledCards = [];
                    for(var i = 0; i < cards.length; i++) {
                        var randomCardIndex = getRandomCardIndex();
                        while($.inArray(randomCardIndex,shuffledCards) != -1) {
                            randomCardIndex = getRandomCardIndex();
                        }
                        shuffledCards.push(randomCardIndex);
                    }
                }

                function getRandomCardIndex() {
                    return Math.floor((Math.random() * cards.length));
                }

                function dealCards() {
                    setupGameBoard();
                    attachCardEvents();
                }

                function attachCardEvents() {
                    $(".card").click(function() {
                        var selectedCardElement = $(this);
                        var selectedCard = getCardFromElement(selectedCardElement);
                        flipCard(selectedCardElement, selectedCard);

                        if(cardToMatchElement) {
                            var cardToMatch = getCardFromElement(cardToMatchElement);
                            if(cardToMatch.matchesId == selectedCard.id) {
                                selectedCardElement.off();
                                cardToMatchElement.off();
                                cardToMatchElement = null;
                            }
                            else {
                                $.blockUI({ message: "", overlayCSS : { backgroundColor: '#fff', cursor:'normal', opacity:0.5 } });
                                setTimeout(function() {
                                    flipCard(selectedCardElement, selectedCard);
                                    flipCard(cardToMatchElement, cardToMatch);
                                    cardToMatchElement = null;
                                    $.unblockUI();
                                },1000);
                            }
                        }
                        else {
                            cardToMatchElement = selectedCardElement;
                        }
                    });             
                }


                function getCardFromElement(cardElement) {
                    return cards[cardElement.attr("data-cardindex")];
                }

                function flipCard(cardElement, card) {
                    if(cardElement.hasClass("down")) {
                        cardElement.removeClass("down").addClass("up");
                        cardElement.html(card.content); 
                    }
                    else {
                        cardElement.removeClass("up").addClass("down");
                        cardElement.html("");
                    }                                               
                }

                function setupGameBoard() {
                    var numberColumns = 4;
                    var tableBody = "";
                    var tableRow = "<tr>";
                    $.each(shuffledCards, function(index, card) {                       
                        tableRow += "<td><div class='card down' data-cardindex='" + shuffledCards[index] + "'>&nbsp</div></td>";
                        if(index > 0 && (index + 1) % numberColumns == 0) {
                            tableRow += "</tr>";
                            if(index < cards.length - 1) {
                                tableRow += "<tr>";
                            }
                        }

                        if(index == cards.length - 1 && (index + 1) % numberColumns != 0) {
                            tableRow += "</tr>";
                        }                       
                        tableBody += tableRow;
                        tableRow = "";
                    });

                    $("#gameBoard tbody").html(tableBody);
                }
            });

http://jsfiddle.net/Brannan2/VkKRa/1/

Upvotes: 0

Views: 158

Answers (1)

S4beR
S4beR

Reputation: 1847

To create a timer call below function on your button click (id is some global js variable)

function createTimer() {
    id = setInterval(function(){

        var secondEl = document.getElementById('second');
            if (secondEl.value == null || secondEl.value == "") {
                secondEl.value = 0;   
            }

            var seconds = parseInt(secondEl.value) + 1;
            if (seconds == 60) {
                seconds = 0;
                var minuteEl = document.getElementById('minute');
                if (minuteEl.value == null || minuteEl.value == "") {
                    minuteEl.value = 0;   
                }

                var minutes = parseInt(minuteEl.value) + 1;
                if (minutes == 60) {
                    minutes = 0;
                    var hourEl = document.getElementById('hour');
                    if (hourEl.value == null || hourEl.value == "") {
                        hourEl.value = 0;   
                    }

                    hourEl.value = parseInt(hourEl.value) + 1;
                }

                minuteEl.value = minutes;
            }

            secondEl.value = seconds;
    },1000);
}

For my sample I have created three input types in html with ids 'hour','minute' and 'second'. You can create any other based on UI need and update function accordingly.

To stop timer just remove the setInterval function as shown below

window.clearInterval(id);

Once you have stop the watch you can calculate total times easily by using below formula

var totalTime = (hours * 3600) + (minutes * 60) + seconds;

This will return the total time in seconds. Now to get best times, I think you have to use localStorage so that you can store best times in client browser and refer to it later whenever user returns again to play your game.

To substitute letter with images, there can be many ways. For e.g. you can add a css class to the element which will set the background image for you or you can directly use a img tag in your div with image location. Its totally up to you. I am not sure though why you want to show image with your current requirement.

Upvotes: 1

Related Questions