如何在游戏中点击值为1的方块时添加计分器以更新得分?

huangapple go评论82阅读模式
英文:

How can I add a score counter to update the score on a game when a square with a value of 1 clicked?

问题

我正在创建一个收集小行星的游戏。当值为1的方块被点击时,分数应该增加1。我希望方块在初始时被隐藏,然后在点击时显示出来(1=小行星图像,0=太空图像)。有人可以帮助我弄清楚如何正确添加计数器吗?我已经添加了一些注释“//for counter”来标记我添加的不起作用的代码行。

  1. // Maze dimensions
  2. const rows = 10;
  3. const columns = 10;
  4. // Number of asteroids to collect
  5. const totalAsteroids = 17;
  6. // Maze array generation
  7. const maze = Array.from({ length: rows }, () => Array(columns).fill(0));
  8. // Place the asteroids randomly
  9. let asteroidsPlaced = 0;
  10. while (asteroidsPlaced < totalAsteroids) {
  11. const randomRow = Math.floor(Math.random() * rows);
  12. const randomColumn = Math.floor(Math.random() * columns);
  13. if (maze[randomRow][randomColumn] === 0) {
  14. maze[randomRow][randomColumn] = 1;
  15. asteroidsPlaced++;
  16. }
  17. }
  18. // Initialize game state
  19. let asteroidsCollected = 0;
  20. let maxAsteroids = totalAsteroids;
  21. // Get elements from HTML
  22. const boardElement = document.getElementById('board');
  23. const messageElement = document.getElementById('message');
  24. const scoreBoard = document.getElementById('counter');
  25. messageElement.innerHTML = "Welcome! Start collecting asteroids!";
  26. scoreBoard.innerHTML = "Score: 0"; // for counter
  27. let score = 0;
  28. // Function to handle square clicks
  29. function squareClicked(row, column) {
  30. const squareValue = maze[row][column];
  31. if (squareValue === 1) {
  32. maze[row][column] = 0;
  33. asteroidsCollected++; //for the counter
  34. scoreBoard.innerHTML = "Score: " + asteroidsCollected; //for counter
  35. updateBoard();
  36. if (asteroidsCollected === totalAsteroids) {
  37. messageElement.textContent = "Congratulations! You found all the asteroids!";
  38. }
  39. }
  40. }
  41. // Function to update the board
  42. function updateBoard() {
  43. boardElement.innerHTML = '';
  44. for (let row = 0; row < rows; row++) {
  45. for (let column = 0; column < columns; column++) {
  46. const squareValue = maze[row][column];
  47. const square = document.createElement('div');
  48. square.className = 'maze-square';
  49. if (squareValue === 1) {
  50. square.style.backgroundImage = "url('https://i.stack.imgur.com/cfMRQ.png')";
  51. score++; //for counter
  52. } else {
  53. square.style.backgroundImage = "url('https://i.stack.imgur.com/Tu6uq.png')";
  54. }
  55. square.style.opacity = 0; // Hide the squares initially
  56. square.addEventListener('click', () => {
  57. square.style.opacity = 1;
  58. squareClicked(row, column); //for counter
  59. });
  60. boardElement.appendChild(square);
  61. }
  62. }
  63. }
  64. // Initial board update
  65. updateBoard();
  1. .maze-square {
  2. width: 50px;
  3. height: 50px;
  4. display: inline-block;
  5. background-size: contain;
  6. cursor: pointer;
  7. }
  8. #board{
  9. width: 500px;
  10. height: 540px;
  11. position: relative;
  12. margin: auto;
  13. border: 1px solid black;
  14. box-shadow: 0px 0px 10px black;
  15. background-image: url(space.svg);
  16. background-size: cover;
  17. background-color: aquamarine;
  18. }
  19. #message{
  20. width: 600px;
  21. height: 64px;
  22. line-height: 64px;
  23. text-align: center;
  24. font-size: 24px;
  25. font-weight: bold;
  26. color: aliceblue;
  27. text-shadow: 0px 0px 10px black;
  28. position:relative;
  29. background: rgba(0, 0, 0, 0.5);
  30. display: block;
  31. margin-left: 300px;
  32. }
  33. #counter{
  34. position:fixed;
  35. top: 20px;
  36. left: 20px;
  37. }
  1. <p id="message"></p>
  2. <div id="board"></div>
  3. <h1 id="counter"></h1>
  1. <details>
  2. <summary>英文:</summary>
  3. [asteroid image][1] [space-stars image][2].
  4. I&#39;m creating a game to collect asteroids. When the value of 1 is clicked, the score should get incremented by 1. I want the squares to be hidden initially and then revealed when the square is clicked (1=asteroid image, 0=space image) Can someone help with figuring out how to add the counter correctly? I&#39;ve added comments &quot;//for counter&quot; for the lines I added which are not working.
  5. I seem to have changed something right before posting this question(not sure what) so clicking the asteroid squares no longer clears the board, hence the edit.
  6. &lt;!-- begin snippet: js hide: false console: true babel: false --&gt;
  7. &lt;!-- language: lang-js --&gt;
  8. // Maze dimensions
  9. const rows = 10;
  10. const columns = 10;
  11. // Number of asteroids to collect
  12. const totalAsteroids = 17;
  13. // Maze array generation
  14. const maze = Array.from({ length: rows }, () =&gt; Array(columns).fill(0));
  15. // Place the asteroids randomly
  16. let asteroidsPlaced = 0;
  17. while (asteroidsPlaced &lt; totalAsteroids) {
  18. const randomRow = Math.floor(Math.random() * rows);
  19. const randomColumn = Math.floor(Math.random() * columns);
  20. if (maze[randomRow][randomColumn] === 0) {
  21. maze[randomRow][randomColumn] = 1;
  22. asteroidsPlaced++;
  23. }
  24. }
  25. // Initialize game state
  26. let asteroidsCollected = 0;
  27. let maxAsteroids = totalAsteroids;
  28. // Get elements from HTML
  29. const boardElement = document.getElementById(&#39;board&#39;);
  30. const messageElement = document.getElementById(&#39;message&#39;);
  31. const scoreBoard = document.getElementById(&#39;counter&#39;);
  32. messageElement.innerHTML = &quot;Welcome! Start collecting asteroids!&quot;;
  33. scoreBoard.innerHTML = &quot;Score: 0&quot;; // for counter
  34. let score = 0;
  35. // Function to handle square clicks
  36. function squareClicked(row, column) {
  37. const squareValue = maze[row][column];
  38. if (squareValue === 1) {
  39. maze[row][column] = 0;
  40. asteroidsCollected++; //for the counter
  41. scoreBoard.innerHTML = &quot;Score: &quot; + asteroidsCollected; //for counter
  42. updateBoard();
  43. if (asteroidsCollected === totalAsteroids) {
  44. messageElement.textContent = &quot;Congratulations! You found all the asteroids!&quot;;
  45. }
  46. }
  47. }
  48. // Function to update the board
  49. function updateBoard() {
  50. boardElement.innerHTML = &#39;&#39;;
  51. for (let row = 0; row &lt; rows; row++) {
  52. for (let column = 0; column &lt; columns; column++) {
  53. const squareValue = maze[row][column];
  54. const square = document.createElement(&#39;div&#39;);
  55. square.className = &#39;maze-square&#39;;
  56. if (squareValue === 1) {
  57. square.style.backgroundImage = &quot;url(&#39;https://i.stack.imgur.com/cfMRQ.png&#39;)&quot;;
  58. score++; //for counter
  59. } else {
  60. square.style.backgroundImage = &quot;url(&#39;https://i.stack.imgur.com/Tu6uq.png&#39;)&quot;;
  61. }
  62. square.style.opacity = 0; // Hide the squares initially
  63. square.addEventListener(&#39;click&#39;, () =&gt; {
  64. square.style.opacity = 1;
  65. squareClicked(row, column); //for counter
  66. });
  67. boardElement.appendChild(square);
  68. }
  69. }
  70. }
  71. // Initial board update
  72. updateBoard();
  73. &lt;!-- language: lang-css --&gt;
  74. .maze-square {
  75. width: 50px;
  76. height: 50px;
  77. display: inline-block;
  78. background-size: contain;
  79. cursor: pointer;
  80. }
  81. #board{
  82. width: 500px;
  83. height: 540px;
  84. position: relative;
  85. margin: auto;
  86. border: 1px solid black;
  87. box-shadow: 0px 0px 10px black;
  88. background-image: url(space.svg);
  89. background-size: cover;
  90. background-color: aquamarine;
  91. }
  92. #message{
  93. width: 600px;
  94. height: 64px;
  95. line-height: 64px;
  96. text-align: center;
  97. font-size: 24px;
  98. font-weight: bold;
  99. color: aliceblue;
  100. text-shadow: 0px 0px 10px black;
  101. position:relative;
  102. background: rgba(0, 0, 0, 0.5);
  103. display: block;
  104. margin-left: 300px;
  105. }
  106. #counter{
  107. position:fixed;
  108. top: 20px;
  109. left: 20px;
  110. }
  111. &lt;!-- language: lang-html --&gt;
  112. &lt;p id=&quot;message&quot;&gt;&lt;/p&gt;
  113. &lt;div id=&quot;board&quot;&gt;&lt;/div&gt;
  114. &lt;h1 id=&quot;counter&quot;&gt;&lt;/h1&gt;
  115. &lt;!-- end snippet --&gt;
  116. [1]: https://i.stack.imgur.com/cfMRQ.png
  117. [2]: https://i.stack.imgur.com/Tu6uq.png
  118. </details>
  119. # 答案1
  120. **得分**: 0
  121. 以下是您要翻译的内容:
  122. "So all I had to do was comment out the `updateBoard()` inside of the `squareClicked` function and that made it not clear the board out anymore.
  123. The problem is that when `updateBoard` is called, it creates all the `div` elements you can click on. If you recreate all the HTML inside the game every time you click on something, that will most certainly clear things out. Just removing this line fixes it.
  124. How did I find this out? I just commented stuff out to see what caused the bug. It happens when you click on something, so first I commented out the call to `squareClicked` inside the click function. This made the images stay on the board, which confirmed it has to do with the click. Everything inside the `squareClicked` function makes sense except for the callback to `updateBoard`."
  125. 以下是翻译好的部分:
  126. "所以,我所需要做的就是注释掉`squareClicked`函数内部的`updateBoard()`,这样就不再清空游戏板了。
  127. 问题在于当调用`updateBoard`时,它会创建所有可点击的`div`元素。如果每次点击某物体时都重新创建游戏内部的所有HTML,那肯定会清除掉一切。只需删除这行代码就可以修复它。
  128. 我是如何发现这个问题的?我只是注释掉了一些内容,看看是什么导致了这个错误。它发生在你点击某物体时,所以我首先注释掉了点击函数内`squareClicked`的调用。这使得图像保留在游戏板上,从而确认问题与点击有关。`squareClicked`函数内的一切都很合理,除了对`updateBoard`的回调。"
  129. <details>
  130. <summary>英文:</summary>
  131. So all I had to do was comment out the `updateBoard()` inside of the `squareClicked` function and that made it not clear the board out any more.
  132. The problem is that when `updateBoard` is called, it create all the `div` elements you can click on. If you re-create all the HTML inside of the game every time you click on something, that will most certainly clear things out. Just removint this line fixes it.
  133. How did I find this out? I just commented stuff out to see what caused the bug. It happens when you click on something, so first I commented out the call to `squareClicked` inside the click function. This made the images stay on the board, which confirmed it has to do with the click. Everything inside the `squareClicked` function makes sense except for the call back to `updateBoard`.
  134. &lt;!-- begin snippet: js hide: false console: true babel: false --&gt;
  135. &lt;!-- language: lang-js --&gt;
  136. // Maze dimensions
  137. const rows = 10;
  138. const columns = 10;
  139. // Number of asteroids to collect
  140. const totalAsteroids = 17;
  141. // Maze array generation
  142. const maze = Array.from({ length: rows }, () =&gt; Array(columns).fill(0));
  143. // Place the asteroids randomly
  144. let asteroidsPlaced = 0;
  145. while (asteroidsPlaced &lt; totalAsteroids) {
  146. const randomRow = Math.floor(Math.random() * rows);
  147. const randomColumn = Math.floor(Math.random() * columns);
  148. if (maze[randomRow][randomColumn] === 0) {
  149. maze[randomRow][randomColumn] = 1;
  150. asteroidsPlaced++;
  151. }
  152. }
  153. // Initialize game state
  154. let asteroidsCollected = 0;
  155. let maxAsteroids = totalAsteroids;
  156. // Get elements from HTML
  157. const boardElement = document.getElementById(&#39;board&#39;);
  158. const messageElement = document.getElementById(&#39;message&#39;);
  159. const scoreBoard = document.getElementById(&#39;counter&#39;);
  160. messageElement.innerHTML = &quot;Welcome! Start collecting asteroids!&quot;;
  161. scoreBoard.innerHTML = &quot;Score: 0&quot;; // for counter
  162. let score = 0;
  163. // Function to handle square clicks
  164. function squareClicked(row, column) {
  165. const squareValue = maze[row][column];
  166. if (squareValue === 1) {
  167. maze[row][column] = 0;
  168. asteroidsCollected++; //for the counter
  169. scoreBoard.innerHTML = &quot;Score: &quot; + asteroidsCollected; //for counter
  170. //updateBoard(); //&lt;--- I commented this out
  171. if (asteroidsCollected === totalAsteroids) {
  172. messageElement.textContent = &quot;Congratulations! You found all the asteroids!&quot;;
  173. }
  174. }
  175. }
  176. // Function to update the board
  177. function updateBoard() {
  178. boardElement.innerHTML = &#39;&#39;;
  179. for (let row = 0; row &lt; rows; row++) {
  180. for (let column = 0; column &lt; columns; column++) {
  181. const squareValue = maze[row][column];
  182. const square = document.createElement(&#39;div&#39;);
  183. square.className = &#39;maze-square&#39;;
  184. if (squareValue === 1) {
  185. square.style.backgroundImage = &quot;url(&#39;https://i.stack.imgur.com/cfMRQ.png&#39;)&quot;;
  186. score++; //for counter
  187. } else {
  188. square.style.backgroundImage = &quot;url(&#39;https://i.stack.imgur.com/Tu6uq.png&#39;)&quot;;
  189. }
  190. square.style.opacity = 0; // Hide the squares initially
  191. square.addEventListener(&#39;click&#39;, () =&gt; {
  192. square.style.opacity = 1;
  193. squareClicked(row, column); //for counter
  194. });
  195. boardElement.appendChild(square);
  196. }
  197. }
  198. }
  199. // Initial board update
  200. updateBoard();
  201. &lt;!-- language: lang-css --&gt;
  202. .maze-square {
  203. width: 50px;
  204. height: 50px;
  205. display: inline-block;
  206. background-size: contain;
  207. cursor: pointer;
  208. }
  209. #board{
  210. width: 500px;
  211. height: 540px;
  212. position: relative;
  213. margin: auto;
  214. border: 1px solid black;
  215. box-shadow: 0px 0px 10px black;
  216. background-image: url(space.svg);
  217. background-size: cover;
  218. background-color: aquamarine;
  219. }
  220. #message{
  221. width: 600px;
  222. height: 64px;
  223. line-height: 64px;
  224. text-align: center;
  225. font-size: 24px;
  226. font-weight: bold;
  227. color: aliceblue;
  228. text-shadow: 0px 0px 10px black;
  229. position:relative;
  230. background: rgba(0, 0, 0, 0.5);
  231. display: block;
  232. margin-left: 175px;
  233. }
  234. #counter{
  235. position:fixed;
  236. top: 20px;
  237. left: 20px;
  238. }
  239. &lt;!-- language: lang-html --&gt;
  240. &lt;p id=&quot;message&quot;&gt;&lt;/p&gt;
  241. &lt;div id=&quot;board&quot;&gt;&lt;/div&gt;
  242. &lt;h1 id=&quot;counter&quot;&gt;&lt;/h1&gt;
  243. &lt;!-- end snippet --&gt;
  244. </details>

huangapple
  • 本文由 发表于 2023年7月10日 12:43:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76650716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定