Home > OS >  How do would I create a cloud varible (High score) for a game
How do would I create a cloud varible (High score) for a game

Time:12-17

<script>
// I want to create a cloud variable (high score)
// But I don't know how. 
var click = 0;
document.getElementById("High_score").innerHTML = cloud_varible;
function btn(){
click   ;
document.getElementById("p").innerHTML = click;
}
if (clicks < cloud_varible){
clicks = cloud_varible
document.getElementById("High_score").innerHTML = cloud_varible;
}
</script>
<button id="btn" onclick="btn();">click</button>
<p id="p">clicks: </p>
<p id="High_score"></p>


I've looked at various wbsite but none seem to awnser my qestion. I have intermediate-basic knoledge in javascript. Intermediate-Advance HTML and intermediate Knoledge in CSS and basic knowledge in PHP.

CodePudding user response:

My take on a solution for this will need you to be a little familiar with Node. Just some basics

What we will be doing is creating a little bit of backend logic to store our score. When you talk about "The Cloud" what it really is is just a computer that is accessible from anywhere. We will use Node and Express (a common combo) to create a small API to read and write to a local JSON file that holds the players name as well as their score

First lets go over the back end structure

const express = require("express");
var fs = require("fs")
const cors = require('cors')
var bodyParser = require('body-parser')
  • Express: This makes the API and endpoint creation super quick and easy
  • FS: This lets us Read and Write to a local file
  • body-parser: This lets us read the incoming data from our HTML page
const app = express();
app.use(express.json())
app.use(cors())
app.use(bodyParser.urlencoded({extended: false}));

Above are setting up express to use all of the middleware that we want

now lets take a look at the endpoints of our small API, we will have 2 endpoints. One to update the score and one to get the current highscore. to update the score we will use a POST endpoint

app.post("/updateScore",(req,res) =>{
    console.log(req.body)
    obj = {
            highscore:req.body.highscore,
            playerName:req.body.playerName
    }
    fs.writeFile("score.json",JSON.stringify(obj),() =>{
        console.log("writing file")
    })
})

In this POST endpoint we take in the some values in the form of a json object. This object contains the players name and their score. we then write the resulting score and name to a json file. This file is saved on to the servers local storage so that it is accessible for reading

next up is the GET endpoint

app.get("/score", (req,res) => {
    console.log()
    fs.readFile("./score.json","utf-8",(err,data)=>{
        console.log("ReadingFile")
        parsedData = JSON.parse(data)
        console.log(parsedData)
        res.json(parsedData)
    })
})

The GET endpoint Reads the contents of the json file on the server and then sends back the relevant information (in this case the score and name)

finally we will start the server on port 3000

  app.listen("3000", () => {
    console.log(`Server listening on 3000`);
  });

That is all the information we need on the backend. Now we can work on the frontend page that will displayed to your users.

We need 2 functions on thet frontend side, the first will retreive the current score that is stored on the server. The second will update the score that is stored on the server. I have acomplished them as follows

    function getHighScore(){
      fetch("http://localhost:3000/score")
      .then((res)=>{
        return(res.json())
      })
      .then((res) => {
        console.log(res)
        document.getElementById("highScore").innerText = res.playerName   ": "   res.highscore
        return(res)
      })
    }

The function above makes a GET request to the endpoint we setup earlier. it then takes the response form this endpoint and updates our HTML accordingly

function setHighScore(name, score){
      fetch("http://localhost:3000/updateScore",{
        method: "POST",
        headers: {
          'Content-Type': 'application/json'
        },
        body:JSON.stringify({
          playerName: name,
          highscore: score
        })
      })
      .then(()=>{
        console.log("Here")
        getHighScore()
      })
    }

The function above makes a POST request to our endpoint form before. This time it supply's the server with relevant information to update the stored score accordingly. It is important to note that after we update the highscore on theserver we want to display this score as well, you will notice we call the getHighScore() function at the end of our promise as well to do so.

The last step is to put it all together in the HTML document. The full document looks as follows

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gift</title>
    <link rel="stylesheet" href="index.css">
</head>
<body>
  <div id="main">
    <div>
      High Score:
    </div>
    <div id="highScore">
      0
    </div>
    <div>
      <button onclick="setHighScore('Josh',5)">Set New Score</button>
    </div>
  </div>
  <script>
    function getHighScore(){
      fetch("http://localhost:3000/score")
      .then((res)=>{
        return(res.json())
      })
      .then((res) => {
        console.log(res)
        document.getElementById("highScore").innerText = res.playerName   ": "   res.highscore
        return(res)
      })
    }
    function setHighScore(name, score){
      fetch("http://localhost:3000/updateScore",{
        method: "POST",
        headers: {
          'Content-Type': 'application/json'
        },
        body:JSON.stringify({
          playerName: name,
          highscore: score
        })
      })
      .then(()=>{
        console.log("Here")
        getHighScore()
      })
    }
    getHighScore()
  </script>   
</body>

</html>
  • Related