资讯专栏INFORMATION COLUMN

前端每日实战:164# 视频演示如何用原生 JS 创作一个数独训练小游戏(内含 4 个视频)

OBKoro1 / 1135人阅读

摘要:第部分第部分第部分第部分源代码下载每日前端实战系列的全部源代码请从下载代码解读解数独的一项基本功是能迅速判断一行一列或一个九宫格中缺少哪几个数字,本项目就是一个训练判断九宫格中缺少哪个数字的小游戏。

效果预览

按下右侧的“点击预览”按钮可以在当前页面预览,点击链接可以全屏预览。

https://codepen.io/comehope/pen/mQYobz

可交互视频

此视频是可以交互的,你可以随时暂停视频,编辑视频中的代码。

请用 chrome, safari, edge 打开观看。

第 1 部分:
https://scrimba.com/p/pEgDAM/c7Q86ug

第 2 部分:
https://scrimba.com/p/pEgDAM/ckgBNAD

第 3 部分:
https://scrimba.com/p/pEgDAM/cG7bWc8

第 4 部分:
https://scrimba.com/p/pEgDAM/cez34fp

源代码下载

每日前端实战系列的全部源代码请从 github 下载:

https://github.com/comehope/front-end-daily-challenges

代码解读

解数独的一项基本功是能迅速判断一行、一列或一个九宫格中缺少哪几个数字,本项目就是一个训练判断九宫格中缺少哪个数字的小游戏。游戏的流程是:先选择游戏难度,有 Easy、Normal、Hard 三档,分别对应着九宫格中缺少 1 个、2 个、3 个数字。开始游戏后,用键盘输入九宫格中缺少的数字,如果全答出来了,就会进入下一局,一共 5 局,5 局结束之后这一次游戏就结束了。在游戏过程中,九宫格的左上角会计时,右上角会计分。

整个游戏分成 4 个步骤开发:静态页面布局、程序逻辑、计分计时和动画效果。

一、页面布局

定义 dom 结构,.app 是整个应用的容器,h1 是游戏标题,.game 是游戏的主界面。.game 中的子元素包括 .message.digits.message 用来提示游戏时间 .time、游戏的局数 .round、得分 .score.digits 里是 9 个数字:

</>复制代码

  1. Sudoku Training

  2. Time:
  3. 00:00
  4. 1/5

  5. Score:
  6. 100
  7. 1
  8. 2
  9. 3
  10. 4
  11. 5
  12. 6
  13. 7
  14. 8
  15. 9

居中显示:

</>复制代码

  1. body {
  2. margin: 0;
  3. height: 100vh;
  4. display: flex;
  5. align-items: center;
  6. justify-content: center;
  7. background: silver;
  8. overflow: hidden;
  9. }

定义应用的宽度,子元素纵向布局:

</>复制代码

  1. .app {
  2. width: 300px;
  3. display: flex;
  4. flex-direction: column;
  5. align-items: center;
  6. justify-content: space-between;
  7. user-select: none;
  8. }

标题为棕色字:

</>复制代码

  1. h1 {
  2. margin: 0;
  3. color: sienna;
  4. }

提示信息是横向布局,重点内容加粗:

</>复制代码

  1. .game .message {
  2. width: inherit;
  3. display: flex;
  4. justify-content: space-between;
  5. font-size: 1.2em;
  6. font-family: sans-serif;
  7. }
  8. .game .message span {
  9. font-weight: bold;
  10. }

九宫格用 grid 布局,外框棕色,格子用杏白色背景:

</>复制代码

  1. .game .digits {
  2. box-sizing: border-box;
  3. width: 300px;
  4. height: 300px;
  5. padding: 10px;
  6. border: 10px solid sienna;
  7. display: grid;
  8. grid-template-columns: repeat(3, 1fr);
  9. grid-gap: 10px;
  10. }
  11. .game .digits span {
  12. width: 80px;
  13. height: 80px;
  14. background-color: blanchedalmond;
  15. font-size: 30px;
  16. font-family: sans-serif;
  17. text-align: center;
  18. line-height: 2.5em;
  19. color: sienna;
  20. position: relative;
  21. }

至此,游戏区域布局完成,接下来布局选择游戏难度的界面。
在 html 文件中增加 .select-level dom 结构,它包含一个难度列表 levels 和一个开始游戏的按钮 .play,游戏难度分为 .easy.normal.hard 三个级别:

</>复制代码

  1. Sudoku Training

  2. Play

为选择游戏难度容器画一个圆形的外框,子元素纵向布局:

</>复制代码

  1. .select-level {
  2. z-index: 2;
  3. box-sizing: border-box;
  4. width: 240px;
  5. height: 240px;
  6. border: 10px solid rgba(160, 82, 45, 0.8);
  7. border-radius: 50%;
  8. box-shadow:
  9. 0 0 0 0.3em rgba(255, 235, 205, 0.8),
  10. 0 0 1em 0.5em rgba(160, 82, 45, 0.8);
  11. display: flex;
  12. flex-direction: column;
  13. align-items: center;
  14. font-family: sans-serif;
  15. }

布局 3 个难度选项,横向排列:

</>复制代码

  1. .select-level .levels {
  2. margin-top: 60px;
  3. width: 190px;
  4. display: flex;
  5. justify-content: space-between;
  6. }

input 控件隐藏起来,只显示它们对应的 label

</>复制代码

  1. .select-level .levels {
  2. position: relative;
  3. }
  4. .select-level input[type=radio] {
  5. visibility: hidden;
  6. position: absolute;
  7. left: 0;
  8. }

设置 label 的样式,为圆形按钮:

</>复制代码

  1. .select-level label {
  2. width: 56px;
  3. height: 56px;
  4. background-color: rgba(160, 82, 45, 0.8);
  5. border-radius: 50%;
  6. text-align: center;
  7. line-height: 56px;
  8. color: blanchedalmond;
  9. cursor: pointer;
  10. }

当某个 label 对应的 input 被选中时,令 label 背景色加深,以示区别:

</>复制代码

  1. .select-level input[type=radio]:checked + label {
  2. background-color: sienna;
  3. }

设置开始游戏按钮 .play 的样式,以及交互效果:

</>复制代码

  1. .select-level .play {
  2. width: 120px;
  3. height: 30px;
  4. background-color: sienna;
  5. color: blanchedalmond;
  6. text-align: center;
  7. line-height: 30px;
  8. border-radius: 30px;
  9. text-transform: uppercase;
  10. cursor: pointer;
  11. margin-top: 30px;
  12. font-size: 20px;
  13. letter-spacing: 2px;
  14. }
  15. .select-level .play:hover {
  16. background-color: saddlebrown;
  17. }
  18. .select-level .play:active {
  19. transform: translate(2px, 2px);
  20. }

至此,选择游戏难度的界面布局完成,接下来布局游戏结束界面。
游戏结束区 .game-over 包含一个 h2 标题,二行显示最终结果的段落 p 和一个再玩一次的按钮 .again。最终结果包括最终耗时 .final-time 和最终得分 .final-score

</>复制代码

  1. Sudoku Training

  2. Game Over

  3. Time:
  4. 00:00
  5. Score:
  6. 3000
  7. Play Again

因为游戏结束界面和选择游戏难度界面的布局相似,所以借用 .select-level 的代码:

</>复制代码

  1. .select-level,
  2. .game-over {
  3. z-index: 2;
  4. box-sizing: border-box;
  5. width: 240px;
  6. height: 240px;
  7. border: 10px solid rgba(160, 82, 45, 0.8);
  8. border-radius: 50%;
  9. box-shadow:
  10. 0 0 0 0.3em rgba(255, 235, 205, 0.8),
  11. 0 0 1em 0.5em rgba(160, 82, 45, 0.8);
  12. display: flex;
  13. flex-direction: column;
  14. align-items: center;
  15. font-family: sans-serif;
  16. }

标题和最终结果都用棕色字:

</>复制代码

  1. .game-over h2 {
  2. margin-top: 40px;
  3. color: sienna;
  4. }
  5. .game-over p {
  6. margin: 3px;
  7. font-size: 20px;
  8. color: sienna;
  9. }

“再玩一次”按钮 .again 的样式与开始游戏 .play 的样式相似,所以也借用 .play 的代码:

</>复制代码

  1. .select-level .play,
  2. .game-over .again {
  3. width: 120px;
  4. height: 30px;
  5. background-color: sienna;
  6. color: blanchedalmond;
  7. text-align: center;
  8. line-height: 30px;
  9. border-radius: 30px;
  10. text-transform: uppercase;
  11. cursor: pointer;
  12. }
  13. .select-level .play {
  14. margin-top: 30px;
  15. font-size: 20px;
  16. letter-spacing: 2px;
  17. }
  18. .select-level .play:hover,
  19. .game-over .again:hover {
  20. background-color: saddlebrown;
  21. }
  22. .select-level .play:active,
  23. .game-over .again:active {
  24. transform: translate(2px, 2px);
  25. }
  26. .game-over .again {
  27. margin-top: 10px;
  28. }

把选择游戏难度界面 .select-level 和游戏结束界面 .game-over 定位到游戏容器的中间位置:

</>复制代码

  1. .app {
  2. position: relative;
  3. }
  4. .select-level,
  5. .game-over {
  6. position: absolute;
  7. bottom: 40px;
  8. }

至此,游戏界面 .game、选择游戏难度界面 .select-level 和游戏结束界面 .game-over 均已布局完成。接下来为动态程序做些准备工作。
把选择游戏难度界面 .select-level 和游戏结束界面 .game-over 隐藏起来,当需要它们呈现时,会在脚本中设置它们的 visibility 属性:

</>复制代码

  1. .select-level,
  2. .game-over {
  3. visibility: hidden;
  4. }

游戏中,当选择游戏难度界面 .select-level 和游戏结束界面 .game-over 出现时,应该令游戏界面 .game 变模糊,并且加一个缓动时间,.game.stop 会在脚本中调用:

</>复制代码

  1. .game {
  2. transition: 0.3s;
  3. }
  4. .game.stop {
  5. filter: blur(10px);
  6. }

游戏中,当填错了数字时,要把错误的数字描一个红边;当填对了数字时,把数字的背景色改为巧克力色。.game .digits span.wrong.game .digits span.correct 会在脚本中调用:

</>复制代码

  1. .game .digits span.wrong {
  2. border: 2px solid crimson;
  3. }
  4. .game .digits span.correct {
  5. background-color: chocolate;
  6. color: gold;
  7. }

至此,完成全部布局和样式设计。

二、程序逻辑

引入 lodash 工具库,后面会用到 lodash 提供的一些数组函数:

</>复制代码

在写程序逻辑之前,先定义几个存储业务数据的常量。ALL_DIGITS 存储了全部备选的数字,也就是从 1 到 9;ANSWER_COUNT 存储的是不同难度要回答的数字个数,easy 难度要回答 1 个数字,normal 难度要回答 2 个数字,hard 难度要回答 3 个数字;ROUND_COUNT 存储的是每次游戏的局数,默认是 5 局;SCORE_RULE 存储的是答对和答错时分数的变化,答对加 100 分,答错扣 10 分。定义这些常量的好处是避免在程序中出现魔法数字,提高程序可读性:

</>复制代码

  1. const ALL_DIGITS = ["1","2","3","4","5","6","7","8","9"]
  2. const ANSWER_COUNT = {EASY: 1, NORMAL: 2, HARD: 3}
  3. const ROUND_COUNT = 5
  4. const SCORE_RULE = {CORRECT: 100, WRONG: -10}

再定义一个 dom 对象,用于引用 dom 元素,它的每个属性是一个 dom 元素,key 值与 class 类名保持一致。其中大部分 dom 元素是一个 element 对象,只有 dom.digitsdom.levels 是包含多个 element 对象的数组;另外 dom.level 用于获取被选中的难度,因为它的值随用户选择而变化,所以用函数来返回实时结果:

</>复制代码

  1. const $ = (selector) => document.querySelectorAll(selector)
  2. const dom = {
  3. game: $(".game")[0],
  4. digits: Array.from($(".game .digits span")),
  5. time: $(".game .time")[0],
  6. round: $(".game .round")[0],
  7. score: $(".game .score")[0],
  8. selectLevel: $(".select-level")[0],
  9. level: () => {return $("input[type=radio]:checked")[0]},
  10. play: $(".select-level .play")[0],
  11. gameOver: $(".game-over")[0],
  12. again: $(".game-over .again")[0],
  13. finalTime: $(".game-over .final-time")[0],
  14. finalScore: $(".game-over .final-score")[0],
  15. }

在游戏过程中需要根据游戏进展随时修改 dom 元素的内容,这些修改过程我们也把它们先定义在 render 对象中,这样程序主逻辑就不用关心具体的 dom 操作了。render 对象的每个属性是一个 dom 操作,结构如下:

</>复制代码

  1. const render = {
  2. initDigits: () => {},
  3. updateDigitStatus: () => {},
  4. updateTime: () => {},
  5. updateScore: () => {},
  6. updateRound: () => {},
  7. updateFinal: () => {},
  8. }

下面我们把这些 dom 操作逐个写下来。
render.initDigits 用来初始化九宫格。它接收一个文本数组,根据不同的难度级别,数组的长度可能是 8 个(easy 难度)、7 个(normal 难度)或 6 个(hard 难度),先把它补全为长度为 9 个数组,数量不足的元素补空字符,然后把它们随机分配到九宫格中:

</>复制代码

  1. const render = {
  2. initDigits: (texts) => {
  3. allTexts = texts.concat(_.fill(Array(ALL_DIGITS.length - texts.length), ""))
  4. _.shuffle(dom.digits).forEach((digit, i) => {
  5. digit.innerText = allTexts[i]
  6. digit.className = ""
  7. })
  8. },
  9. //...
  10. }

render.updateDigitStatus 用来更新九宫格中单个格子的状态。它接收 2 个参数,text
是格子里的数字,isAnswer 指明这个数字是不是答案。格子的默认样式是浅色背景深色文字,如果传入的数字不是答案,也就是答错了,会为格子加上 wrong 样式,格子被描红边;如果传入的数字是答案,也就是答对了,会在一个空格子里展示这个数字,并为格子加上 correct 样式,格子的样式会改为深色背景浅色文字:

</>复制代码

  1. const render = {
  2. //...
  3. updateDigitStatus: (text, isAnswer) => {
  4. if (isAnswer) {
  5. let digit = _.find(dom.digits, x => (x.innerText == ""))
  6. digit.innerText = text
  7. digit.className = "correct"
  8. }
  9. else {
  10. _.find(dom.digits, x => (x.innerText == text)).className = "wrong"
  11. }
  12. },
  13. //...
  14. }

render.updateTime 用来更新时间,render.updateScore 用来更新得分:

</>复制代码

  1. const render = {
  2. //...
  3. updateTime: (value) => {
  4. dom.time.innerText = value.toString()
  5. },
  6. updateScore: (value) => {
  7. dom.score.innerText = value.toString()
  8. },
  9. //...
  10. }

render.updateRound 用来更新当前局数,显示为 “n/m” 的格式:

</>复制代码

  1. const render = {
  2. //...
  3. updateRound: (currentRound) => {
  4. dom.round.innerText = [
  5. currentRound.toString(),
  6. "/",
  7. ROUND_COUNT.toString(),
  8. ].join("")
  9. },
  10. //...
  11. }

render.updateFinal 用来更新游戏结束界面里的最终成绩:

</>复制代码

  1. const render = {
  2. //...
  3. updateFinal: () => {
  4. dom.finalTime.innerText = dom.time.innerText
  5. dom.finalScore.innerText = dom.score.innerText
  6. },
  7. }

接下来定义程序整体的逻辑结构。当页面加载完成之后执行 init() 函数,init() 函数会对整个游戏做些初始化的工作 ———— 令开始游戏按钮 dom.play 被点击时调用 startGame() 函数,令再玩一次按钮 dom.again 被点击时调用 playAgain() 函数,令按下键盘时触发事件处理程序 pressKey() ———— 最后调用 newGame() 函数开始新游戏:

</>复制代码

  1. window.onload = init
  2. function init() {
  3. dom.play.addEventListener("click", startGame)
  4. dom.again.addEventListener("click", playAgain)
  5. window.addEventListener("keyup", pressKey)
  6. newGame()
  7. }
  8. function newGame() {
  9. //...
  10. }
  11. function startGame() {
  12. //...
  13. }
  14. function playAgain() {
  15. //...
  16. }
  17. function pressKey() {
  18. //...
  19. }

当游戏开始时,令游戏界面变模糊,呼出选择游戏难度的界面:

</>复制代码

  1. function newGame() {
  2. dom.game.classList.add("stop")
  3. dom.selectLevel.style.visibility = "visible"
  4. }

当选择了游戏难度,点击开始游戏按钮 dom.play 时,隐藏掉选择游戏难度的界面,游戏界面恢复正常,然后把根据用户选择的游戏难度计算出的答案数字个数存储到全局变量 answerCount 中,调用 newRound() 开始一局游戏:

</>复制代码

  1. let answerCount
  2. function startGame() {
  3. dom.game.classList.remove("stop")
  4. dom.selectLevel.style.visibility = "hidden"
  5. answerCount = ANSWER_COUNT[dom.level().value.toUpperCase()]
  6. newRound()
  7. }

当一局游戏开始时,打乱所有候选数字,生成一个全局数组变量 digitsdigits 的每个元素包含 3 个属性,text 属性表示数字文本,isAnswer 属性表示该数字是否为答案,isPressed 表示该数字是否被按下过,isPressed 的初始值均为 false,紧接着把 digits 渲染到九宫格中:

</>复制代码

  1. let digits
  2. function newRound() {
  3. digits = _.shuffle(ALL_DIGITS).map((x, i) => {
  4. return {
  5. text: x,
  6. isAnwser: (i < answerCount),
  7. isPressed: false
  8. }
  9. })
  10. render.initDigits(_.filter(digits, x => !x.isAnwser).map(x => x.text))
  11. }

当用户按下键盘时,若按的键不是候选文本,就忽略这次按键事件。通过按键的文本在 digits 数组中找到对应的元素 digit,判断该键是否被按过,若被按过,也退出事件处理。接下来,就是针对没按过的键,在对应的 digit 对象上标明该键已按过,并且更新这个键的显示状态,如果用户按下的不是答案数字,就把该数字所在的格子描红,如果用户按下的是答案数字,就突出显示这个数字:

</>复制代码

  1. function pressKey(e) {
  2. if (!ALL_DIGITS.includes(e.key)) return;
  3. let digit = _.find(digits, x => (x.text == e.key))
  4. if (digit.isPressed) return;
  5. digit.isPressed = true
  6. render.updateDigitStatus(digit.text, digit.isAnwser)
  7. }

当用户已经按下了所有的答案数字,这一局就结束了,开始新一局:

</>复制代码

  1. function pressKey(e) {
  2. if (!ALL_DIGITS.includes(e.key)) return;
  3. let digit = _.find(digits, x => (x.text == e.key))
  4. if (digit.isPressed) return;
  5. digit.isPressed = true
  6. render.updateDigitStatus(digit.text, digit.isAnwser)
  7. //判断用户是否已经按下所有的答案数字
  8. let hasPressedAllAnswerDigits = (_.filter(digits, (x) => (x.isAnwser && x.isPressed)).length == answerCount)
  9. if (!hasPressedAllAnswerDigits) return;
  10. newRound()
  11. }

增加一个记录当前局数的全局变量 round,在游戏开始时它的初始值为 0,每局游戏开始时,它的值就加1,并更新游戏界面中的局数 dom.round

</>复制代码

  1. let round
  2. function newGame() {
  3. round = 0 //初始化局数
  4. dom.game.classList.add("stop")
  5. dom.selectLevel.style.visibility = "visible"
  6. }
  7. function startGame() {
  8. render.updateRound(1) //初始化页面中的局数
  9. dom.game.classList.remove("stop")
  10. dom.selectLevel.style.visibility = "hidden"
  11. answerCount = ANSWER_COUNT[dom.level().value.toUpperCase()]
  12. newRound()
  13. }
  14. function newRound() {
  15. digits = _.shuffle(ALL_DIGITS).map((x, i) => {
  16. return {
  17. text: x,
  18. isAnwser: (i < answerCount),
  19. isPressed: false
  20. }
  21. })
  22. render.initDigits(_.filter(digits, x => !x.isAnwser).map(x => x.text))
  23. //每局开始时为局数加 1
  24. round++
  25. render.updateRound(round)
  26. }

当前局数 round 增加到常量 ROUND_COUNT 定义的游戏总局数,本次游戏结束,调用 gameOver() 函数,否则调用 newRound() 函数开始新一局:

</>复制代码

  1. function pressKey(e) {
  2. if (!ALL_DIGITS.includes(e.key)) return;
  3. let digit = _.find(digits, x => (x.text == e.key))
  4. if (digit.isPressed) return;
  5. digit.isPressed = true
  6. render.updateDigitStatus(digit.text, digit.isAnwser)
  7. let hasPressedAllAnswerDigits = (_.filter(digits, (x) => (x.isAnwser && x.isPressed)).length == answerCount)
  8. if (!hasPressedAllAnswerDigits) return;
  9. //判断是否玩够了总局数
  10. let hasPlayedAllRounds = (round == ROUND_COUNT)
  11. if (hasPlayedAllRounds) {
  12. gameOver()
  13. } else {
  14. newRound()
  15. }
  16. }

游戏结束时,令游戏界面变模糊,调出游戏结束界面,显示最终成绩:

</>复制代码

  1. function gameOver() {
  2. render.updateFinal()
  3. dom.game.classList.add("stop")
  4. dom.gameOver.style.visibility = "visible"
  5. }

在游戏结束界面,用户可以点击再玩一次按钮 dom.again,若点击了此按钮,就把游戏结束界面隐藏起来,开始一局新游戏,这就回到 newGame() 的流程了:

</>复制代码

  1. function playAgain() {
  2. dom.game.classList.remove("stop")
  3. dom.gameOver.style.visibility = "hidden"
  4. newGame()
  5. }

至此,整个游戏的流程已经跑通了,此时的脚本如下:

</>复制代码

  1. const ALL_DIGITS = ["1","2","3","4","5","6","7","8","9"]
  2. const ANSWER_COUNT = {EASY: 1, NORMAL: 2, HARD: 3}
  3. const ROUND_COUNT = 3
  4. const SCORE_RULE = {CORRECT: 100, WRONG: -10}
  5. const $ = (selector) => document.querySelectorAll(selector)
  6. const dom = {
  7. game: $(".game")[0],
  8. digits: Array.from($(".game .digits span")),
  9. time: $(".game .time")[0],
  10. round: $(".game .round")[0],
  11. score: $(".game .score")[0],
  12. selectLevel: $(".select-level")[0],
  13. level: () => {return $("input[type=radio]:checked")[0]},
  14. play: $(".select-level .play")[0],
  15. gameOver: $(".game-over")[0],
  16. again: $(".game-over .again")[0],
  17. finalTime: $(".game-over .final-time")[0],
  18. finalScore: $(".game-over .final-score")[0],
  19. }
  20. const render = {
  21. initDigits: (texts) => {
  22. allTexts = texts.concat(_.fill(Array(ALL_DIGITS.length - texts.length), ""))
  23. _.shuffle(dom.digits).forEach((digit, i) => {
  24. digit.innerText = allTexts[i]
  25. digit.className = ""
  26. })
  27. },
  28. updateDigitStatus: (text, isAnswer) => {
  29. if (isAnswer) {
  30. let digit = _.find(dom.digits, x => (x.innerText == ""))
  31. digit.innerText = text
  32. digit.className = "correct"
  33. }
  34. else {
  35. _.find(dom.digits, x => (x.innerText == text)).className = "wrong"
  36. }
  37. },
  38. updateTime: (value) => {
  39. dom.time.innerText = value.toString()
  40. },
  41. updateScore: (value) => {
  42. dom.score.innerText = value.toString()
  43. },
  44. updateRound: (currentRound) => {
  45. dom.round.innerText = [
  46. currentRound.toString(),
  47. "/",
  48. ROUND_COUNT.toString(),
  49. ].join("")
  50. },
  51. updateFinal: () => {
  52. dom.finalTime.innerText = dom.time.innerText
  53. dom.finalScore.innerText = dom.score.innerText
  54. },
  55. }
  56. let answerCount, digits, round
  57. window.onload = init
  58. function init() {
  59. dom.play.addEventListener("click", startGame)
  60. dom.again.addEventListener("click", playAgain)
  61. window.addEventListener("keyup", pressKey)
  62. newGame()
  63. }
  64. function newGame() {
  65. round = 0
  66. dom.game.classList.add("stop")
  67. dom.selectLevel.style.visibility = "visible"
  68. }
  69. function startGame() {
  70. render.updateRound(1)
  71. dom.game.classList.remove("stop")
  72. dom.selectLevel.style.visibility = "hidden"
  73. answerCount = ANSWER_COUNT[dom.level().value.toUpperCase()]
  74. newRound()
  75. }
  76. function newRound() {
  77. digits = _.shuffle(ALL_DIGITS).map((x, i) => {
  78. return {
  79. text: x,
  80. isAnwser: (i < answerCount),
  81. isPressed: false
  82. }
  83. })
  84. render.initDigits(_.filter(digits, x => !x.isAnwser).map(x => x.text))
  85. round++
  86. render.updateRound(round)
  87. }
  88. function gameOver() {
  89. render.updateFinal()
  90. dom.game.classList.add("stop")
  91. dom.gameOver.style.visibility = "visible"
  92. }
  93. function playAgain() {
  94. dom.game.classList.remove("stop")
  95. dom.gameOver.style.visibility = "hidden"
  96. newGame()
  97. }
  98. function pressKey(e) {
  99. if (!ALL_DIGITS.includes(e.key)) return;
  100. let digit = _.find(digits, x => (x.text == e.key))
  101. if (digit.isPressed) return;
  102. digit.isPressed = true
  103. render.updateDigitStatus(digit.text, digit.isAnwser)
  104. let hasPressedAllAnswerDigits = (_.filter(digits, (x) => (x.isAnwser && x.isPressed)).length == answerCount)
  105. if (!hasPressedAllAnswerDigits) return;
  106. let hasPlayedAllRounds = (round == ROUND_COUNT)
  107. if (hasPlayedAllRounds) {
  108. gameOver()
  109. } else {
  110. newRound()
  111. }
  112. }
三、计分和计时

接下来处理得分和时间,先处理得分。
首先声明一个用于存储得分的全局变量 score,在新游戏开始之前设置它的初始值为 0,在游戏开始时初始化页面中的得分:

</>复制代码

  1. let score
  2. function newGame() {
  3. round = 0
  4. score = 0 //初始化得分
  5. dom.game.classList.add("stop")
  6. dom.selectLevel.style.visibility = "visible"
  7. }
  8. function startGame() {
  9. render.updateRound(1)
  10. render.updateScore(0) //初始化页面中的得分
  11. dom.game.classList.remove("stop")
  12. dom.selectLevel.style.visibility = "hidden"
  13. answerCount = ANSWER_COUNT[dom.level().value.toUpperCase()]
  14. newRound()
  15. }

在用户按键事件中根据按下的键是否为答案记录不同的分值:

</>复制代码

  1. function pressKey(e) {
  2. if (!ALL_DIGITS.includes(e.key)) return;
  3. let digit = _.find(digits, x => (x.text == e.key))
  4. if (digit.isPressed) return;
  5. digit.isPressed = true
  6. render.updateDigitStatus(digit.text, digit.isAnwser)
  7. //累积得分
  8. score += digit.isAnwser ? SCORE_RULE.CORRECT : SCORE_RULE.WRONG
  9. render.updateScore(score)
  10. let hasPressedAllAnswerDigits = (_.filter(digits, (x) => (x.isAnwser && x.isPressed)).length == answerCount)
  11. if (!hasPressedAllAnswerDigits) return;
  12. let hasPlayedAllRounds = (round == ROUND_COUNT)
  13. if (hasPlayedAllRounds) {
  14. gameOver()
  15. } else {
  16. newRound()
  17. }
  18. }

接下来处理时间。先创建一个计时器类 Timer,它的参数是一个用于把时间渲染到页面上的函数,另外 Timerstart()stop() 2 个方法用于开启和停止计时器,计时器每秒会执行一次 tickTock() 函数:

</>复制代码

  1. function Timer(render) {
  2. this.render = render
  3. this.t = {},
  4. this.start = () => {
  5. this.t = setInterval(this.tickTock, 1000);
  6. }
  7. this.stop = () => {
  8. clearInterval(this.t)
  9. }
  10. }

定义一个记录时间的变量 time,它的初始值为 00 秒,在 tickTock() 函数中把秒数加1,并调用渲染函数把当前时间写到页面中:

</>复制代码

  1. function Timer(render) {
  2. this.render = render
  3. this.t = {}
  4. this.time = {
  5. minute: 0,
  6. second: 0,
  7. }
  8. this.tickTock = () => {
  9. this.time.second ++;
  10. if (this.time.second == 60) {
  11. this.time.minute ++
  12. this.time.second = 0
  13. }
  14. render([
  15. this.time.minute.toString().padStart(2, "0"),
  16. ":",
  17. this.time.second.toString().padStart(2, "0"),
  18. ].join(""))
  19. }
  20. this.start = () => {
  21. this.t = setInterval(this.tickTock, 1000)
  22. }
  23. this.stop = () => {
  24. clearInterval(this.t)
  25. }
  26. }

在开始游戏时初始化页面中的时间:

</>复制代码

  1. function startGame() {
  2. render.updateRound(1)
  3. render.updateScore(0)
  4. render.updateTime("00:00") //初始化页面中的时间
  5. dom.game.classList.remove("stop")
  6. dom.selectLevel.style.visibility = "hidden"
  7. answerCount = ANSWER_COUNT[dom.level().value.toUpperCase()]
  8. newRound()
  9. }

定义一个存储定时器的全局变量 timer,在创建游戏时初始化定时器,在游戏开始时启动计时器,在游戏结束时停止计时器:

</>复制代码

  1. let timer
  2. function newGame() {
  3. round = 0
  4. score = 0
  5. timer = new Timer(render.updateTime) //创建定时器
  6. dom.game.classList.add("stop")
  7. dom.selectLevel.style.visibility = "visible"
  8. }
  9. function startGame() {
  10. render.updateRound(1)
  11. render.updateScore(0)
  12. render.updateTime("00:00")
  13. dom.game.classList.remove("stop")
  14. dom.selectLevel.style.visibility = "hidden"
  15. answerCount = ANSWER_COUNT[dom.level().value.toUpperCase()]
  16. newRound()
  17. timer.start() //开始计时
  18. }
  19. function gameOver() {
  20. timer.stop() //停止计时
  21. render.updateFinal()
  22. dom.game.classList.add("stop")
  23. dom.gameOver.style.visibility = "visible"
  24. }

至此,时钟已经可以运行了,在游戏开始时从 0 分 0 秒开始计时,在游戏结束时停止计时。
最后一个环节,当游戏结束之后,不应再响应用户的按键事件。为此,我们定义一个标明是否可按键的变量 canPress,在创建新游戏时它的状态是不可按,游戏开始之后变为可按,游戏结束之后再变为不可按:

</>复制代码

  1. let canPress
  2. function newGame() {
  3. round = 0
  4. score = 0
  5. time = {
  6. minute: 0,
  7. second: 0
  8. }
  9. timer = new Timer()
  10. canPress = false //初始化是否可按键的标志
  11. dom.game.classList.add("stop")
  12. dom.selectLevel.style.visibility = "visible"
  13. }
  14. function startGame() {
  15. render.updateRound(1)
  16. render.updateScore(0)
  17. render.updateTime(0, 0)
  18. dom.game.classList.remove("stop")
  19. dom.selectLevel.style.visibility = "hidden"
  20. answerCount = ANSWER_COUNT[dom.level().value.toUpperCase()]
  21. newRound()
  22. timer.start(tickTock)
  23. canPress = true //游戏开始后,可以按键
  24. }
  25. function gameOver() {
  26. canPress = false //游戏结束后,不可以再按键
  27. timer.stop()
  28. render.updateFinal()
  29. dom.game.classList.add("stop")
  30. dom.gameOver.style.visibility = "visible"
  31. }

在按键事件处理程序中,首先判断是否允许按键,若不允许,就退出事件处理程序:

</>复制代码

  1. function pressKey(e) {
  2. if (!canPress) return; //判断是否允许按键
  3. if (!ALL_DIGITS.includes(e.key)) return;
  4. let digit = _.find(digits, x => (x.text == e.key))
  5. if (digit.isPressed) return;
  6. digit.isPressed = true
  7. render.updateDigitStatus(digit.text, digit.isAnwser)
  8. score += digit.isAnwser ? SCORE_RULE.CORRECT : SCORE_RULE.WRONG
  9. render.updateScore(score)
  10. let hasPressedAllAnswerDigits = (_.filter(digits, (x) => (x.isAnwser && x.isPressed)).length == answerCount)
  11. if (hasPressedAllAnswerDigits) {
  12. newRound()
  13. }
  14. }

至此,计分计时设计完毕,此时的脚本如下:

</>复制代码

  1. const ALL_DIGITS = ["1","2","3","4","5","6","7","8","9"]
  2. const ANSWER_COUNT = {EASY: 1, NORMAL: 2, HARD: 3}
  3. const ROUND_COUNT = 3
  4. const SCORE_RULE = {CORRECT: 100, WRONG: -10}
  5. const $ = (selector) => document.querySelectorAll(selector)
  6. const dom = {
  7. //略,与此前代码相同
  8. }
  9. const render = {
  10. //略,与此前代码相同
  11. }
  12. let answerCount, digits, round, score, timer, canPress
  13. window.onload = init
  14. function init() {
  15. //略,与此前代码相同
  16. }
  17. function newGame() {
  18. round = 0
  19. score = 0
  20. timer = new Timer(render.updateTime)
  21. canPress = false
  22. dom.game.classList.add("stop")
  23. dom.selectLevel.style.visibility = "visible"
  24. }
  25. function startGame() {
  26. render.updateRound(1)
  27. render.updateScore(0)
  28. render.updateTime(0, 0)
  29. dom.game.classList.remove("stop")
  30. dom.selectLevel.style.visibility = "hidden"
  31. answerCount = ANSWER_COUNT[dom.level().value.toUpperCase()]
  32. newRound()
  33. timer.start()
  34. canPress = true
  35. }
  36. function newRound() {
  37. //略,与此前代码相同
  38. }
  39. function gameOver() {
  40. canPress = false
  41. timer.stop()
  42. render.updateFinal()
  43. dom.game.classList.add("stop")
  44. dom.gameOver.style.visibility = "visible"
  45. }
  46. function playAgain() {
  47. //略,与此前代码相同
  48. }
  49. function pressKey(e) {
  50. if (!canPress) return;
  51. if (!ALL_DIGITS.includes(e.key)) return;
  52. let digit = _.find(digits, x => (x.text == e.key))
  53. if (digit.isPressed) return;
  54. digit.isPressed = true
  55. render.updateDigitStatus(digit.text, digit.isAnwser)
  56. score += digit.isAnwser ? SCORE_RULE.CORRECT : SCORE_RULE.WRONG
  57. render.updateScore(score)
  58. let hasPressedAllAnswerDigits = (_.filter(digits, (x) => (x.isAnwser && x.isPressed)).length == answerCount)
  59. if (!hasPressedAllAnswerDigits) return;
  60. let hasPlayedAllRounds = (round == ROUND_COUNT)
  61. if (hasPlayedAllRounds) {
  62. gameOver()
  63. } else {
  64. newRound()
  65. }
  66. }
四、动画效果

引入 gsap 动画库:

</>复制代码

游戏中一共有 6 个动画效果,分别是九宫格的出场与入场、选择游戏难度界面的显示与隐藏、游戏结束界面的显示与隐藏。为了集中管理动画效果,我们定义一个全局常量 animation,它的每个属性是一个函数,实现一个动画效果,结构如下,注意因为选择游戏难度界面和游戏结束界面的样式相似,所以它们共享了相同的动画效果,在调用函数时要传入一个参数 element 指定动画的 dom 对象:

</>复制代码

  1. const animation = {
  2. digitsFrameOut: () => {
  3. //九宫格出场
  4. },
  5. digitsFrameIn: () => {
  6. //九宫格入场
  7. },
  8. showUI: (element) => {
  9. //显示选择游戏难度界面和游戏结束界面
  10. },
  11. frameOut: (element) => {
  12. //隐藏选择游戏难度界面和游戏结束界面
  13. },
  14. }

确定下这几个动画的时机:

</>复制代码

  1. function newGame() {
  2. round = 0
  3. score = 0
  4. timer = new Timer(render.updateTime)
  5. canPress = false
  6. //选择游戏难度界面 - 显示
  7. dom.game.classList.add("stop")
  8. dom.selectLevel.style.visibility = "visible"
  9. }
  10. function startGame() {
  11. render.updateRound(1)
  12. render.updateScore(0)
  13. render.updateTime("00:00")
  14. //选择游戏难度界面 - 隐藏
  15. dom.game.classList.remove("stop")
  16. dom.selectLevel.style.visibility = "hidden"
  17. answerCount = ANSWER_COUNT[dom.level().value.toUpperCase()]
  18. newRound()
  19. timer.start()
  20. canPress = true
  21. }
  22. function newRound() {
  23. //九宫格 - 出场
  24. digits = _.shuffle(ALL_DIGITS).map((x, i) => {
  25. return {
  26. text: x,
  27. isAnwser: (i < answerCount),
  28. isPressed: false
  29. }
  30. })
  31. render.initDigits(_.filter(digits, x => !x.isAnwser).map(x => x.text))
  32. //九宫格 - 入场
  33. round++
  34. render.updateRound(round)
  35. }
  36. function gameOver() {
  37. canPress = false
  38. timer.stop()
  39. render.updateFinal()
  40. //游戏结束界面 - 显示
  41. dom.game.classList.add("stop")
  42. dom.gameOver.style.visibility = "visible"
  43. }
  44. function playAgain() {
  45. //游戏结束界面 - 隐藏
  46. dom.game.classList.remove("stop")
  47. dom.gameOver.style.visibility = "hidden"
  48. newGame()
  49. }

把目前动画时机所在位置的代码移到 animation 对象中,九宫格出场和入场的动画目前是空的:

</>复制代码

  1. const animation = {
  2. digitsFrameOut: () => {
  3. //九宫格出场
  4. },
  5. digitsFrameIn: () => {
  6. //九宫格入场
  7. },
  8. showUI: (element) => {
  9. //显示选择游戏难度界面和游戏结束界面
  10. dom.game.classList.add("stop")
  11. element.style.visibility = "visible"
  12. },
  13. hideUI: (element) => {
  14. //隐藏选择游戏难度界面和游戏结束界面
  15. dom.game.classList.remove("stop")
  16. element.style.visibility = "hidden"
  17. },
  18. }

在动画时机的位置调用 animation 对应的动画函数,因为动画是有执行时长的,下一个动画要等到上一个动画结束之后再开始,所以我们采用了 async/await 的语法,让相邻的动画顺序执行:

</>复制代码

  1. async function newGame() {
  2. round = 0
  3. score = 0
  4. timer = new Timer(render.updateTime)
  5. canPress = false
  6. // 选择游戏难度界面 - 显示
  7. await animation.showUI(dom.selectLevel)
  8. }
  9. async function startGame() {
  10. render.updateRound(1)
  11. render.updateScore(0)
  12. render.updateTime("00:00")
  13. // 选择游戏难度界面 - 隐藏
  14. await animation.hideUI(dom.selectLevel)
  15. answerCount = ANSWER_COUNT[dom.level().value.toUpperCase()]
  16. newRound()
  17. timer.start()
  18. canPress = true
  19. }
  20. async function newRound() {
  21. //九宫格 - 出场
  22. await animation.digitsFrameOut()
  23. digits = _.shuffle(ALL_DIGITS).map((x, i) => {
  24. return {
  25. text: x,
  26. isAnwser: (i < answerCount),
  27. isPressed: false
  28. }
  29. })
  30. render.initDigits(_.filter(digits, x => !x.isAnwser).map(x => x.text))
  31. //九宫格 - 入场
  32. await animation.digitsFrameIn()
  33. round++
  34. render.updateRound(round)
  35. }
  36. async function gameOver() {
  37. canPress = false
  38. timer.stop()
  39. render.updateFinal()
  40. // 游戏结束界面 - 显示
  41. await animation.showUI(dom.gameOver)
  42. }
  43. async function playAgain() {
  44. // 游戏结束界面 - 隐藏
  45. await animation.hideUI(dom.gameOver)
  46. newGame()
  47. }

接下来就开始设计动画效果。
animation.digitsFrameOut 是九宫格的出场动画,各格子分别旋转着消失。注意,为了与 async/await 语法配合,我们让函数返回了一个 Promise 对象:

</>复制代码

  1. const animation = {
  2. digitsFrameOut: () => {
  3. return new Promise(resolve => {
  4. new TimelineMax()
  5. .staggerTo(dom.digits, 0, {rotation: 0})
  6. .staggerTo(dom.digits, 1, {rotation: 360, scale: 0, delay: 0.5})
  7. .timeScale(2)
  8. .eventCallback("onComplete", resolve)
  9. })
  10. },
  11. //...
  12. }

animation.digitsFrameIn 是九宫格的入场动画,它的动画效果是各格子旋转着出现,而且各格子的出现时间稍有延迟:

</>复制代码

  1. const animation = {
  2. //...
  3. digitsFrameIn: () => {
  4. return new Promise(resolve => {
  5. new TimelineMax()
  6. .staggerTo(dom.digits, 0, {rotation: 0})
  7. .staggerTo(dom.digits, 1, {rotation: 360, scale: 1}, 0.1)
  8. .timeScale(2)
  9. .eventCallback("onComplete", resolve)
  10. })
  11. },
  12. //...
  13. }

animation.showUI 是显示择游戏难度界面和游戏结束界面的动画,它的效果是从高处落下,并在底部小幅反弹,模拟物体跌落的效果:

</>复制代码

  1. const animation = {
  2. //...
  3. showUI: (element) => {
  4. dom.game.classList.add("stop")
  5. return new Promise(resolve => {
  6. new TimelineMax()
  7. .to(element, 0, {visibility: "visible", x: 0})
  8. .from(element, 1, {y: "-300px", ease: Elastic.easeOut.config(1, 0.3)})
  9. .timeScale(1)
  10. .eventCallback("onComplete", resolve)
  11. })
  12. },
  13. //...
  14. }

animation.hideUI 是隐藏选择游戏难度界面和游戏结束界面的动画,它从正常位置向右移出画面:

</>复制代码

  1. const animation = {
  2. //...
  3. hideUI: (element) => {
  4. dom.game.classList.remove("stop")
  5. return new Promise(resolve => {
  6. new TimelineMax()
  7. .to(element, 1, {x: "300px", ease: Power4.easeIn})
  8. .to(element, 0, {visibility: "hidden"})
  9. .timeScale(2)
  10. .eventCallback("onComplete", resolve)
  11. })
  12. },
  13. }

至此,整个游戏的动画效果就完成了,全部代码如下:

</>复制代码

  1. const ALL_DIGITS = ["1","2","3","4","5","6","7","8","9"]
  2. const ANSWER_COUNT = {EASY: 1, NORMAL: 2, HARD: 3}
  3. const ROUND_COUNT = 3
  4. const SCORE_RULE = {CORRECT: 100, WRONG: -10}
  5. const $ = (selector) => document.querySelectorAll(selector)
  6. const dom = {
  7. //略,与增加动画前相同
  8. }
  9. const render = {
  10. //略,与增加动画前相同
  11. }
  12. const animation = {
  13. digitsFrameOut: () => {
  14. return new Promise(resolve => {
  15. new TimelineMax()
  16. .staggerTo(dom.digits, 0, {rotation: 0})
  17. .staggerTo(dom.digits, 1, {rotation: 360, scale: 0, delay: 0.5})
  18. .timeScale(2)
  19. .eventCallback("onComplete", resolve)
  20. })
  21. },
  22. digitsFrameIn: () => {
  23. return new Promise(resolve => {
  24. new TimelineMax()
  25. .staggerTo(dom.digits, 0, {rotation: 0})
  26. .staggerTo(dom.digits, 1, {rotation: 360, scale: 1}, 0.1)
  27. .timeScale(2)
  28. .eventCallback("onComplete", resolve)
  29. })
  30. },
  31. showUI: (element) => {
  32. dom.game.classList.add("stop")
  33. return new Promise(resolve => {
  34. new TimelineMax()
  35. .to(element, 0, {visibility: "visible", x: 0})
  36. .from(element, 1, {y: "-300px", ease: Elastic.easeOut.config(1, 0.3)})
  37. .timeScale(1)
  38. .eventCallback("onComplete", resolve)
  39. })
  40. },
  41. hideUI: (element) => {
  42. dom.game.classList.remove("stop")
  43. return new Promise(resolve => {
  44. new TimelineMax()
  45. .to(element, 1, {x: "300px", ease: Power4.easeIn})
  46. .to(element, 0, {visibility: "hidden"})
  47. .timeScale(2)
  48. .eventCallback("onComplete", resolve)
  49. })
  50. },
  51. }
  52. let answerCount, digits, round, score, timer, canPress
  53. window.onload = init
  54. function init() {
  55. //略,与增加动画前相同
  56. }
  57. async function newGame() {
  58. round = 0
  59. score = 0
  60. timer = new Timer(render.updateTime)
  61. canPress = false
  62. await animation.showUI(dom.selectLevel)
  63. }
  64. async function startGame() {
  65. render.updateRound(1)
  66. render.updateScore(0)
  67. render.updateTime("00:00")
  68. await animation.hideUI(dom.selectLevel)
  69. answerCount = ANSWER_COUNT[dom.level().value.toUpperCase()]
  70. newRound()
  71. timer.start()
  72. canPress = true
  73. }
  74. async function newRound() {
  75. await animation.digitsFrameOut()
  76. digits = _.shuffle(ALL_DIGITS).map((x, i) => {
  77. return {
  78. text: x,
  79. isAnwser: (i < answerCount),
  80. isPressed: false
  81. }
  82. })
  83. render.initDigits(_.filter(digits, x => !x.isAnwser).map(x => x.text))
  84. await animation.digitsFrameIn()
  85. round++
  86. render.updateRound(round)
  87. }
  88. async function gameOver() {
  89. canPress = false
  90. timer.stop()
  91. render.updateFinal()
  92. await animation.showUI(dom.gameOver)
  93. }
  94. async function playAgain() {
  95. await animation.hideUI(dom.gameOver)
  96. newGame()
  97. }
  98. function pressKey(e) {
  99. //略,与增加动画前相同
  100. }
  101. function tickTock() {
  102. //略,与增加动画前相同
  103. }

大功告成!

最后,附上交互流程图,方便大家理解。其中蓝色条带表示动画,粉色椭圆表示用户操作,绿色矩形和菱形表示主要的程序逻辑:

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/117030.html

相关文章

  • 前端每日实战 2018年10月至2019年6月项目汇总(共 20 项目)

    摘要:过往项目年月份项目汇总共个项目年月份项目汇总共个项目年月份项目汇总共个项目年月份项目汇总共个项目年月份项目汇总共个项目年月份项目汇总共个项目年月至年月发布的项目前端每日实战专栏每天分解一个前端项目,用视频记录编码过程,再配合详细的代码解读, 过往项目 2018 年 9 月份项目汇总(共 26 个项目) 2018 年 8 月份项目汇总(共 29 个项目) 2018 年 7 月份项目汇总(...

    muddyway 评论0 收藏0
  • 前端每日实战164# 视频演示何用原生 JS 创作训练游戏内含 4 视频

    摘要:第部分第部分第部分第部分源代码下载每日前端实战系列的全部源代码请从下载代码解读解数独的一项基本功是能迅速判断一行一列或一个九宫格中缺少哪几个数字,本项目就是一个训练判断九宫格中缺少哪个数字的小游戏。 showImg(https://segmentfault.com/img/bVbkNGa?w=400&h=300); 效果预览 按下右侧的点击预览按钮可以在当前页面预览,点击链接可以全屏预...

    Heier 评论0 收藏0
  • 前端每日实战:163# 视频演示何用原生 JS 创作多选场景的交互游戏内含 3 视频

    摘要:本项目将设计一个多选一的交互场景,用进行页面布局用制作动画效果用原生编写程序逻辑。中包含个展示头像的和个标明当前被选中头像的。 showImg(https://segmentfault.com/img/bVbknOW?w=400&h=302); 效果预览 按下右侧的点击预览按钮可以在当前页面预览,点击链接可以全屏预览。 https://codepen.io/comehope/pen/L...

    pakolagij 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<