簡體   English   中英

我如何為游戲創建雲變量(高分)

[英]How do would I create a cloud varible (High score) for a game

<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>


我看過各種網站,但似乎沒有一個能回答我的問題。 我有 javascript 的中級基礎知識。 中高級 HTML 和 CSS 中的中級知識以及 PHP 的基礎知識。

我對此的解決方案需要您對 Node.js 有一點熟悉。 只是一些基礎知識

我們要做的是創建一些后端邏輯來存儲我們的分數。 當您談論“雲”時,它實際上只是一台可以從任何地方訪問的計算機。 我們將使用 Node 和 Express(一種常見的組合)創建一個小型 API 來讀取和寫入包含玩家姓名及其分數的本地 JSON 文件

首先讓我們回顧一下后端結構

const express = require("express");
var fs = require("fs")
const cors = require('cors')
var bodyParser = require('body-parser')
  • Express:這使得 API 和端點的創建變得超級快速和簡單
  • FS:這讓我們可以讀寫本地文件
  • body-parser:這讓我們可以從 HTML 頁面讀取傳入的數據
const app = express();
app.use(express.json())
app.use(cors())
app.use(bodyParser.urlencoded({extended: false}));

以上是設置 express 以使用我們想要的所有中間件

現在讓我們看一下我們的小型 API 的端點,我們將有 2 個端點。 一種是更新分數,另一種是獲取當前的高分。 要更新分數,我們將使用POST端點

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")
    })
})

在此POST端點中,我們以 json 對象的形式獲取一些值。 該對象包含玩家姓名和他們的分數。 然后我們將結果分數和名稱寫入 json 文件。 此文件保存在服務器本地存儲中,以便可以讀取

接下來是GET端點

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)
    })
})

GET端點讀取服務器上的 json 文件的內容,然后發回相關信息(在本例中為分數和姓名)

最后我們將在端口 3000 上啟動服務器

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

這就是我們在后端需要的所有信息。 現在我們可以處理將顯示給您的用戶的前端頁面。

我們在前端需要 2 個函數,第一個函數將檢索存儲在服務器上的當前分數。 第二個將更新存儲在服務器上的分數。 我已經完成了它們如下

    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)
      })
    }

上面的函數向我們之前設置的端點發出GET請求。 然后它從這個端點獲取響應並相應地更新我們的 HTML

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()
      })
    }

上面的函數之前向我們的端點表單發出了POST請求。 這次它向服務器提供相關信息以相應地更新存儲的分數。 重要的是要注意,在我們更新服務器上的高分之后,我們也想顯示這個分數,你會注意到我們在承諾的最后調用了getHighScore()函數來這樣做。

最后一步是將它們全部放在 HTML 文檔中。 完整文檔如下所示

<!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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM