How to add a time counter in Game

2

I got this game in HTML + JavaScript + CSS a while ago, I'd like to implement a time in the upper corner of the screen (either side) bugging every game!

Here is the function of Start in the game, I think of implementing the difficulty after being able to add this time on the screen:

function newGame() {
    block = 0
    angle = 2
    tempX = 0
    tempY = 0
    square = 0
    squareTop = 0
    squareLeft = 0
    squareMotion = 1
    nextScore = 0
    score = 0
    count = 0
    collisionOne = 0
    collisionTwo = 0
    collisionThree = 0

    clearTimeout(timeoutOne)
    clearInterval(intervalOne)
    clearInterval(intervalTwo)
    document.getElementById("square0").style.left = "0px"
    document.getElementById("square0").style.top = "0px"
    document.getElementById("square0").style.display = "block"
    document.getElementById("square1").style.left = "0px"
    document.getElementById("square1").style.top = "0px"
    document.getElementById("square1").style.display = "block"
    document.getElementById("pad").style.top = (gameHeight - 40) + "px"
    document.getElementById("pad").innerHTML = ""
    document.getElementById("notepad").innerHTML = ""

    intervalOne = setInterval("playGame()", speed)
  }

Follow the game running:

JsFiddle

The initial idea is to implement a time that starts when you click Play! Still have a few bugs ... little experience yet rsrsrs!

    
asked by anonymous 06.02.2016 / 01:56

1 answer

2

Here's a simple example of implementation.

div to display the time:

  <div style="z-index:1; 
              background:rgb(50, 50, 255); 
              opacity: 0.7; 
              width:70px; 
              height:20px;">
  <p id="display_tempo" style="font-color:black; text-align:center;"></p>
  </div>

Variables:

// início do jogo
var tempo = 0;

// referência ao timer
var tempo_controle = 0;

// está parado (=1) ou não (=0)
var parado = 1;

A function to update div of time:

function atualiza_tempo()
{
    if (parado)
        return;
    var tempo_segundos = Math.floor((+new Date() - tempo) / 1000);
    var display = tempo_segundos.toString() + " seg";
    document.getElementById("display_tempo").innerHTML = display;
    return;
}

At the end of the newGame() (start of game) function, start timing:

...
tempo = +new Date(); 
parado = 0;
atualiza_tempo();
tempo_controle = window.setInterval(atualiza_tempo, 600);   
...

In the last block of the checkCollision() function (when the collision occurs), stop the timer:

window.clearInterval(tempo_controle);
parado = 1;


Note: There are other ways (more accurate or more compatible) to implement this timer.

See working in jsfiddle

    
06.02.2016 / 04:42