Node.js_網(wǎng)頁(yè)版"剪刀,石頭,布"-實(shí)現(xiàn)基本前后端交互

效果圖

snappy-2021-07-27-11H18M28S.jpg

實(shí)現(xiàn)

  • node.js
  • HTML + CSS + JS
  • VS Code

結(jié)構(gòu)

snappy-2021-07-27-11H24M18S.jpg

代碼

  • index.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>Game</title>
    <style>
      .btn {
        color: #fff;
        background-color: #409eff;
        border-color: #409eff;
        line-height: 1;
        white-space: nowrap;
        cursor: pointer;
        border: 1px solid #dcdfe6;
        font-weight: 500;
        padding: 12px 20px;
        font-size: 14px;
        border-radius: 4px;
        width: 100px;
        margin: 20px 20px 0;
      }
      .output {
        background-color: #e6effb;
        height: 400px;
        width: 400px;
        margin: 20px;
        padding: 10px;
        /* overflow: scroll;   */
        overflow-y: scroll;
      }
    </style>
  </head>
  <body>
    <button class="btn" id="stone">石頭</button>
    <button class="btn" id="cloth">布</button>
    <button class="btn" id="scissor">剪刀</button>
    <div class="output" id="output"></div>
    <button class="btn" id="reset">清除結(jié)果</button>
  </body>
  <script>
    const btnReset = document.getElementById("reset");
    const $button = {
      stone: document.getElementById("stone"),
      scissor: document.getElementById("scissor"),
      cloth: document.getElementById("cloth"),
    };
    const $output = document.getElementById("output");
    // 綁定事件
    Object.keys($button).forEach((key) => {
      $button[key].addEventListener("click", () => {
        fetch(`http://${location.host}/game?action=${key}`)
          .then((res) => {
            return res.text();
          })
          .then((text) => {
            $output.innerHTML += text + "<br/>";
          });
      });
    });
    // 綁定清除游戲結(jié)果內(nèi)容按鈕事件
    btnReset.onclick = () => {
      $output.innerHTML = "";
    };
  </script>
</html>
  • gameV3.js
const arr = ["stone", "cloth", "scissor"];

module.exports = function game(playerCard) {
  // 輸入數(shù)據(jù)驗(yàn)證
  if (arr.indexOf(playerCard) + 1) {
    if (playerCard === "stone") {
      playerCard = "石頭";
    } else if (playerCard === "cloth") {
      playerCard = "布";
    } else {
      playerCard = "剪刀";
    }
    console.log(`玩家出了: ${playerCard}`);
  } else {
    console.log("只能選擇輸入 stone, cloth, scissor 中的一個(gè),請(qǐng)重新輸入...");
    return -1;
  }

  const randomValue = Math.random() * 3;
  // console.log(randomValue);

  if (randomValue < 1) {
    console.log("電腦出了: 石頭");
    computerCard = "石頭";
  } else if (randomValue > 2) {
    console.log("電腦出了: 剪刀");
    computerCard = "剪刀";
  } else {
    console.log("電腦出了: 布");
    computerCard = "布";
  }

  if (computerCard === playerCard) {
    console.log("平局");
    return `你出了${playerCard}
            電腦出了${computerCard}
            平局`;
  } else if (
    (computerCard == "石頭" && playerCard == "剪刀") ||
    (computerCard == "剪刀" && playerCard == "布") ||
    (computerCard == "布" && playerCard == "石頭")
  ) {
    console.log("你輸了");
    return `你出了${playerCard}
    電腦出了${computerCard}
    你輸了`;
  } else {
    console.log("你贏了");
    return `你出了${playerCard}
            電腦出了${computerCard}
            你贏了`;
  }
};
  • app.js
var path = require("path");
// approach 1 : 需要import
// const fs = require("fs");
const game = require("./gameV3");
const url = require("url");
const querystring = require("querystring");
const express = require("express");
const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")));

// approach 1 :
// 測(cè)試結(jié)果: 通過(guò)
// app.get("/", (req, res) => {
//   res.writeHead(200, { "Content-Type": "text/html" });
//   fs.readFile("./html/index.html", "utf-8", function (err, data) {
//     if (err) {
//       throw err;
//     }
//     res.send(data);
//   });
// });

// approach 2: 直接渲染html文件
// 測(cè)試結(jié)果: 通過(guò)
app.get("/", (req, res) => {
  res.render("./public/index.html");
});

app.get("/game", async (req, res) => {
  // Express 中對(duì) request 做了一些處理,可以直接拿到 query 參數(shù)
  // const parsedUrl = url.parse(req.url);
  // let query = querystring.parse(parsedUrl.query);
  const query = req.query;
  let playerCard = query.action;
  const result = game(playerCard);
  res.send(result);
});

// start Server and listening
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`APP is listening on port ${port}`);
  console.log("Visit site by http://localhost:3000/");
});

本文參考了下列鏈接: https://juejin.cn/post/6971456438732816414
感謝起風(fēng)了Q, 提供思路, 讓我走出了前后端交互的實(shí)踐的第一步.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末忆畅,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子藕赞,更是在濱河造成了極大的恐慌断楷,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,539評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異香到,居然都是意外死亡图柏,警方通過(guò)查閱死者的電腦和手機(jī)序六,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評(píng)論 3 396
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)蚤吹,“玉大人难咕,你說(shuō)我怎么就攤上這事【嗔荆” “怎么了余佃?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,871評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)跨算。 經(jīng)常有香客問(wèn)我爆土,道長(zhǎng),這世上最難降的妖魔是什么诸蚕? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,963評(píng)論 1 295
  • 正文 為了忘掉前任步势,我火速辦了婚禮,結(jié)果婚禮上背犯,老公的妹妹穿的比我還像新娘坏瘩。我一直安慰自己,他們只是感情好漠魏,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,984評(píng)論 6 393
  • 文/花漫 我一把揭開(kāi)白布倔矾。 她就那樣靜靜地躺著,像睡著了一般柱锹。 火紅的嫁衣襯著肌膚如雪哪自。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,763評(píng)論 1 307
  • 那天禁熏,我揣著相機(jī)與錄音壤巷,去河邊找鬼。 笑死瞧毙,一個(gè)胖子當(dāng)著我的面吹牛胧华,可吹牛的內(nèi)容都是我干的寄症。 我是一名探鬼主播,決...
    沈念sama閱讀 40,468評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼矩动,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼有巧!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起铅忿,我...
    開(kāi)封第一講書(shū)人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤剪决,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后檀训,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體柑潦,經(jīng)...
    沈念sama閱讀 45,850評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,002評(píng)論 3 338
  • 正文 我和宋清朗相戀三年峻凫,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了渗鬼。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,144評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡荧琼,死狀恐怖譬胎,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情命锄,我是刑警寧澤堰乔,帶...
    沈念sama閱讀 35,823評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站脐恩,受9級(jí)特大地震影響镐侯,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜驶冒,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,483評(píng)論 3 331
  • 文/蒙蒙 一苟翻、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧骗污,春花似錦崇猫、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,026評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至贴谎,卻和暖如春汞扎,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背擅这。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,150評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留景鼠,地道東北人仲翎。 一個(gè)月前我還...
    沈念sama閱讀 48,415評(píng)論 3 373
  • 正文 我出身青樓痹扇,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親溯香。 傳聞我的和親對(duì)象是個(gè)殘疾皇子鲫构,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,092評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容