简体   繁体   English

使用html和JavaScript为游戏添加分数计数器

[英]Add a score counter to a game using html and JavaScript

I'm extremely new to JavaScript and programming, but I was wondering if anyone could help me with trying to add a score counter to my maths game. 我对JavaScript和编程非常陌生,但我想知道是否有人可以帮助我尝试在我的数学游戏中添加分数计数器。 The site randomly generates a multiplication question, which is checked and then a message appears saying whether they got the question right or not. 该网站随机生成一个乘法问题,然后检查该问题,然后会显示一条消息,说明他们是否正确提问。 I've added a timer and I've tried to add a score counter but failed. 我添加了一个计时器,我试图添加一个计分器,但失败了。 Here is my html: 这是我的HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <script type="text/javascript" src="assets/stylesheets/script.js"></script>
    <link rel="stylesheet" href="assets/stylesheets/main.css">
    <link href="https://fonts.googleapis.com/css?family=Indie+Flower" rel="stylesheet">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Learning to multiply</title>
</head>

<body onload="genQuestion();">
<h1>Learning to multiply</h1>
<form name="myForm" id="myForm" action="#">
<label>What is...</label>
<input id="question" name="question" type="text" />
<br>
<label>My answer is...</label>
<input name="answer" id="answer" type="text" />
<br>
<input class="button" name="Check my answer..." type="button" value="Check my answer..." onclick="buttonPressed()" />
</form>
    <div class="score-board">
  <div class="player">
      <h4>Your score</h4>
      <div class="score-box">
         0 
      </div>
  </div>
        </div>
</body>
</html>

and this is my js file: 这是我的js文件:

var x, y;



        function aNumber() {
        return 1 + Math.round(Math.random() * 11);
        }

        function genQuestion(){
            x = aNumber();
            y = aNumber();
            dout = document.getElementById("question");
            dout.value = x + " times " + y;
         }

        function buttonPressed() {
        var mult = document.getElementById("answer").value;



         var posStatements = [
            "Very Good", 
            "Excellent", 
            "Correct - Nice Work!", 
            "Correct - Keep up the good work"];

        var negStatements = [
            "No. Please try again", 
            "Wrong. Try once more", 
            "Incorrect - Don't give up", 
            "No - keep trying"];

         if (mult == x*y) 
            {
                window.alert(posStatements[Math.round(Math.random() * 3)]);
        }
        else 
        {
                window.alert(negStatements[Math.round(Math.random() * 3)]);
        }

        location.reload();
        }

var score=0 
var score = document.getElementById("score-box").value;
function scoreboard() {
    if (mult == x*y)
        {score= score +1}
}

window.onload = function timer() {
var secs = 0;
    var id = setInterval(function timer(){ 
        secs++; console.log(secs);
      if(secs> 9){
        clearInterval(id);
        alert("Time's up!");
       }
    }, 1000);
}    

I'm aware it doesn't work but I have no idea how to go about this... Thank you! 我知道它不起作用,但我不知道如何去做...谢谢!

The problem that you are running into here is an important one in web development, namely that web applications are by default stateless . 您遇到的问题是Web开发中的一个重要问题,即Web应用程序默认是无状态的 That simply means that each time that a web page is loaded, it loads with a completely fresh and new set of controls and variables. 这仅仅意味着每次加载网页时,它都会加载一组全新的控件和变量。

So, when your buttonPressed() function calls location.reload(), the page and all its contents, including script variables, are loaded afresh as if they had never existed before. 因此,当你的buttonPressed()函数调用location.reload()时,页面及其所有内容(包括脚本变量)将重新加载,就像之前从未存在过一样。

In order for your idea of adding score keeping to your game to work, you will need to create state in your application, in other words, you will need to keep track of what the conditions (eg the score) were in the game before the current latest page load. 为了让你想要在你的游戏中添加得分,你需要在你的应用程序中创建状态,换句话说,你需要跟踪游戏中的条件(例如得分)。当前最新页面加载。

Now there are many, many ways of doing that, and modern web applications will probably not reload the page in its entirety between rounds, but just update the bits on the same page that need to be updated. 现在有许多方法可以做到这一点,而现代Web应用程序可能不会在轮次之间完全重新加载页面,而只是更新需要更新的同一页面上的位。 That is certainly one way of doing it. 这当然是一种做法。

Another way, which suits the way that you have laid out your application, with calling genQuestion() on page load, would be to pass the score from the previous round on to the next next page load. 另一种方式,适合您布置应用程序的方式,在页面加载时调用genQuestion(),将分数从上一轮传递到下一个下一页加载。 This can be done in a number of ways as well, the simplest of which is arguably to pass a query string to the next page load, ie a URL that won't just be 这可以通过多种方式完成,其中最简单的方法是将查询字符串传递给下一页加载,即不仅仅是一个URL

http://...game.html

but rather 反而

http://...game.html?score=3

That is just the starting point, though. 不过,这只是一个起点。 Once you have what the current score is (and remember on the first page load it will simply be 0), then you need to update it in the correct place, if the user gets an answer right. 一旦你得到了当前得分(并记住第一页加载它将只是0),那么你需要在正确的位置更新它,如果用户得到正确答案。 As your code stands now, you will need to do that in the if statement that checks whether the user's answer was correct. 正如您的代码现在所示,您需要在if语句中执行此操作,以检查用户的答案是否正确。

I won't give you a working solution, but to get you on your way, here are some pointers: 我不会给你一个有效的解决方案,但为了让你继续前进,这里有一些指示:

To pass the current score on to the next page load, don't just do a location.reload(), but do a window.location.assign(url), where the url is the same url with the score added at the end as "?score=xx". 要将当前分数传递给下一页加载,不要只执行location.reload(),而是执行window.location.assign(url),其中url是相同的url,最后添加了分数为“?score = xx”。 Refer to this w3schools article . 请参阅这篇w3schools文章

To the read the score on the next page load from the url, use location.search(). 要从URL中读取下一页加载的分数,请使用location.search()。 Refer to this w3schools article . 请参阅这篇w3schools文章

There are many other ways of solving this problem, but I'm sure you will learn a lot from doing it this way as a starting point. 还有很多其他方法可以解决这个问题,但我相信你会从这种方式中学到很多东西作为起点。 Good luck! 祝好运!

1 - add a label for showing Score and set id to "lblScore" 1 - 添加标签以显示分数并将ID设置为“lblScore”

<label id="lblScore">0</label>

2 - declare global variable in js file (out of functions body) 2 - 在js文件中声明全局变量(在函数体外)

    var Score=0;

3 - add 1 or sub 1 to score depend on answer 3 - 根据答案将1或1加1得分

if (mult == x*y) 
        {
            Score=Score+1;
    }
    else 
    {
            Score=Score-1;
    }

4 - you should set Score to label in js file (after part 2) like below 4 - 您应该将分数设置为js文件中的标签(在第2部分之后),如下所示

var lblScore = Document.getElementbyId('lblScore');
lblScore.innerHTML=Score;

instead use: 改为使用:

if (mult == x*y) 
{
    Score+=1;
}
else 
{
    Score-=1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM