Trying to create a score with javascript

Asked

Viewed 899 times

0

Hello, I am a computer student and I made a game with html, css and javascript. Unfortunately when I created the scoreboard I ended up having a problem that I believe may be overlapping. The program displays the right score before clicking on the dummy, however, the part of the sum it always displays wrong. Thanks in advance, below the program:

Game_cordova1.html

   !DOCTYPE html>
<html>
    <head>
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/jogo_cordova.css">
        <title>Jogo - Cordova</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <script>
            $(document).ready(function(){
                $('.move').click(function(){
                    var g = 0;
                    var r = 400;
                    var i = 0;
                    var y = 0;
                    var t = 0;
                    var div = document.getElementById("bolt3");
                    div.innerHTML = '000' + i;
                    while (g <= 100){
                        r -= 3;
                        $('.in, .bolt2').animate({'top':'10%'}, 0, 'linear', function(){
                            $('.in, .bolt2').css('display', 'block');
                        });
                        var d = Math.floor(Math.random() * (74 + 1) + 26);
                        if(d < 28){
                            $('.in, .bolt2').animate({'left':'26%'}, 0, 'linear');
                        }
                        else if(d < 30){
                            $('.in, .bolt2').animate({'left':'30%'}, 0, 'linear');
                        }
                        else if(d < 35){
                            $('.in, .bolt2').animate({'left':'36%'}, 0, 'linear');
                        }
                        else if(d < 45){
                            $('.in, .bolt2').animate({'left':'40%'}, 0, 'linear');
                        }
                        else if(d < 50){
                            $('.in, .bolt2').animate({'left':'43%'}, 0, 'linear');
                        }
                        else if(d < 55){
                            $('.in, .bolt2').animate({'left':'48%'}, 0, 'linear');
                        }
                        else if(d <= 60){
                            $('.in, .bolt2').animate({'left':'52%'}, 0, 'linear');
                        }
                        else if(d < 65){
                            $('.in, .bolt2').animate({'left':'60%'}, 0, 'linear');
                        }
                        else {
                            $('.in, .bolt2').animate({'left':'68%'}, 0, 'linear');
                        }
                        $('.in, .bolt2').animate({'top':'75%'}, r, 'linear', $('.bolt2').click(function(){
                            i += 1;
                            if(i < 10){
                                div.innerHTML = '000' + i;
                            }
                            else if(i < 100){
                                div.innerHTML = '00' + i;
                            }
                            else if(i < 1000){
                                div.innerHTML = '0' + i;
                            }
                            else{
                                div.innerHTML = i;
                            }
                        }));
                        g += 1;
                    }
                });
                $('.move1').click(function(){
                    window.location.href = "Jogo_cordova.html";
                });
            });
        </script>
    </head>
    <body>
        <li class='move'><a>PLAY</a></li><br/><br/>
        <li class='move1'><a>MENU</a></li>
        <div class='bolt'></div>
        <div class='bolt1'></div>
        <div class='bolt2'></div>
        <div class='bolt3'><p id='bolt3' name='bolt3'></p></div>
        <img class='in' src='img/logo.png'></img>
    </body>
</html>

Game_cordova.css

body{
    top: 0px;
    left: 0px;
    right: 0px;
    background-color: #436EEE;
    z-index: 1;
}
div#menu{
    position: relative;
    left: 34%;
    margin-top: 18%;
    width: 30%;
    height: 20%;
    z-index: 2;
}
li{
    position: relative;
    font-size: 50pt;
    text-decoration: none;
    display: inline-block;
    text-align: center;
    background-color: #EEE9E9;
    width: 100%;
    border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 6px;
    cursor: pointer;
}
a{
    position: relative;
    color: black;
    text-decoration:none;
}
div#menu1{
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100%;
    height: 100%;
    background-color: #000000;
    opacity: .0;
    -moz-opacity: .0;
    filter: alpha(opacity=0);
    z-index: 1000;
    display: none;
}
div#menu2{
    position: fixed;
    top: 20%;
    left: 30%;
    width: 40%;
    height: 60%;
    background-color: #fff;
    z-index: 1001;
    display: none;
}
p#menu3{
    position: relative;
    left: 20%;
    top: 10%;
    width: 70%;
    height: 50%;
    background-color: white;
    font-size: 14pt;
}
h2#menu4{
    position: relative;
    left: 35%;
    top: 10%;
    width: 35%;
    background-color: white;
    font-size: 24pt;
}
.close{
    float: right;
    margin-right: 5%;
    cursor: pointer;
    font-size: 14pt;
}
.bolt{
    position: absolute;
    left: 20%;
    top: 10%;
    width: 60%;
    height: 80%;
    background-color: #fff;
}
.bolt1{
    position: absolute;
    left: 25.5%;
    top: 75%;
    width: 50%;
    height: 15%;
    background-color: #000;
    z-index: 1002;
}
.in{
    position: absolute;
    width: 7%;
    height: 15%;
    left: 25.5%;
    top: 10%;
    display: none;
}
.bolt2{
    position: absolute;
    width: 7%;
    height: 15%;
    left: 25.5%;
    top: 10%;
    z-index: 1001;
    background-color: #000;
    opacity: 0;
    cursor: pointer;
    display: none;
}
.move{
    position: absolute;
    font-size: 14pt;
    text-decoration: none;
    display: inline-block;
    text-align: center;
    background-color: #EEE9E9;
    width: 10%;
    border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 6px;
    cursor: pointer;
    top: 10%;
    left: 5%;
}
.move1{
    position: absolute;
    font-size: 14pt;
    text-decoration: none;
    display: inline-block;
    text-align: center;
    background-color: #EEE9E9;
    width: 10%;
    border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 6px;
    cursor: pointer;
    top: 15%;
    left: 5%;
}
.bolt3{
    position: absolute;
    width: 4.1%;
    height: 10%;
    left: 20%;
    top: 10%;
    z-index: 1001;
    background-color: #000;
    color: #fff;
    font-size: 20pt;
}
p#bolt3{
    position: relative;
    left: 5%;
}

Image/doll

inserir a descrição da imagem aqui

1 answer

1


The way you were doing the count was wrong. The function animate expects in the 4th parameter a function to be executed when completing the animation, but in this case you tried to associate the click in the ship there.

I created a pen in Codepen with your code and made some modifications, which you can see complete here (you can change the view to editor to read the modified fonts): https://codepen.io/dudaskank/full/jvMjoO/

I will comment on the changes I made to run the game:


Size of the score text

It was too big and couldn’t fit in the target area, so I just lowered the font in CSS:

p#bolt3 {
  position: relative;
  left: 5%;
  font-size: 1rem;
}

Variable for spacecraft and adjusted click function

The ship’s selector was used at various points, I simplified the thing and kept it in a variable, so it doesn’t waste time looking for it at other points.

The original click function was in a wrong place, I put it right at the beginning of javascript and, instead of counting and updating the scoreboard, arrow a flag in the element itself stating that clicked on it. Further ahead will be used.

  var nave = $(".in, .bolt2");
  nave.click(function() {
    console.log('acertou');
    $(this).data('acertou', true);
  });

New game - resetting current animation and changing numbers

If you click on play during a running game, originally you need to wait until the game is over and then start the other game. Calling the method finish he finishes the current animations immediately, getting ready for the next game at the same time.

I also changed the numbers to make it easier for me to play (easy mode?) and removed unused variables. I also simplified the settings for the left of the spacecraft, using a vector with the possible values, and directly modifying with the function css jQuery.

$(".move").click(function() {
  // para as aminações atuais e começa de novo
  nave.finish();
  // vetor com os percentuais do 'left'
  var vetLeft = [ '26%', '30%', '36%', '40%', '43%', '48%', '52%', '60%', '68%' ];
  var g = 1;
  var r = 2000;
  var i = 0;
  var div = document.getElementById("bolt3");
  // primeiro, concateno '000' com o valor de i, e em seguida pego apenas os 4 últimos caracteres da string resultante
  // bem mais simples do que o monte de if's
  div.innerHTML = ('000' + i).slice(-4);
  while (g <= 5) {
    r -= 100;
    nave.animate({'top':'10%'}, 0, 'linear', function(){
      nave.css('display', 'block');
      // troquei aquele monte de if/animate por estas duas linhas
      var leftPct = vetLeft[Math.floor(Math.random()*vetLeft.length)];
      nave.css("left", leftPct);
    });
    // continua...

Time to count the score

To finally count the score, I used the 2nd documented form of the function animate, where I pass the properties that will be animated and the options. Among the options, is the progress, calling a function in each animation frame. Here, I check the element flag nave, somo and already update the score. Remember to set to falsethe flag here, otherwise each step will add one point.

    // continuando...
    nave.animate(
      { top: "75%" },
      {
        duration: r,
        easing: "linear",
        progress: function () {
          // durante a animação, verifica se o flag da nave foi setado pelo evento de clique
          if (nave.data('acertou')) {
            i += 1;
            div.innerHTML = ('0000' + i).slice(-4);
            nave.data('acertou', false);
          }
        },
      }
    );
    g += 1;
  }
});

END

I hope you can understand what I’ve adjusted, and good luck in game development.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.