Node.js_网页版"剪刀,石头,布"-实现基本前后端交互

效果图

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

实现

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

结构

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">清除结果</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/>";
          });
      });
    });
    // 绑定清除游戏结果内容按钮事件
    btnReset.onclick = () => {
      $output.innerHTML = "";
    };
  </script>
</html>
  • gameV3.js
const arr = ["stone", "cloth", "scissor"];

module.exports = function game(playerCard) {
  // 输入数据验证
  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 中的一个,请重新输入...");
    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 :
// 测试结果: 通过
// 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文件
// 测试结果: 通过
app.get("/", (req, res) => {
  res.render("./public/index.html");
});

app.get("/game", async (req, res) => {
  // Express 中对 request 做了一些处理,可以直接拿到 query 参数
  // 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
感谢起风了Q, 提供思路, 让我走出了前后端交互的实践的第一步.

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容