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

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

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”来标记我添加的不起作用的代码行。

// Maze dimensions
const rows = 10;
const columns = 10;

// Number of asteroids to collect
const totalAsteroids = 17;

// Maze array generation
const maze = Array.from({ length: rows }, () => Array(columns).fill(0));

// Place the asteroids randomly
let asteroidsPlaced = 0;
while (asteroidsPlaced < totalAsteroids) {
  const randomRow = Math.floor(Math.random() * rows);
  const randomColumn = Math.floor(Math.random() * columns);

  if (maze[randomRow][randomColumn] === 0) {
    maze[randomRow][randomColumn] = 1;
    asteroidsPlaced++;
  }
}

// Initialize game state
let asteroidsCollected = 0;
let maxAsteroids = totalAsteroids;

// Get elements from HTML
const boardElement = document.getElementById('board');
const messageElement = document.getElementById('message');
const scoreBoard = document.getElementById('counter');

messageElement.innerHTML = "Welcome! Start collecting asteroids!";
scoreBoard.innerHTML = "Score: 0"; // for counter

let score = 0;

// Function to handle square clicks
function squareClicked(row, column) {
  const squareValue = maze[row][column];

  if (squareValue === 1) {

    maze[row][column] = 0;
    asteroidsCollected++;  //for the counter
    scoreBoard.innerHTML = "Score: " + asteroidsCollected;  //for counter

    updateBoard();

    if (asteroidsCollected === totalAsteroids) {
      messageElement.textContent = "Congratulations! You found all the asteroids!";
    }
  }    
}

// Function to update the board
function updateBoard() {
  boardElement.innerHTML = '';

  for (let row = 0; row < rows; row++) {
    for (let column = 0; column < columns; column++) {
      const squareValue = maze[row][column];

      const square = document.createElement('div');
      square.className = 'maze-square';

      if (squareValue === 1) {
        square.style.backgroundImage = "url('https://i.stack.imgur.com/cfMRQ.png')";
        score++;        //for counter
      } else {
        square.style.backgroundImage = "url('https://i.stack.imgur.com/Tu6uq.png')";
      }

      square.style.opacity = 0; // Hide the squares initially
      square.addEventListener('click', () => {
        square.style.opacity = 1;
        squareClicked(row, column); //for counter
      });

      boardElement.appendChild(square);
    }
  }
}

// Initial board update
updateBoard();
.maze-square {
  width: 50px;
  height: 50px;
  display: inline-block;
  background-size: contain;
  cursor: pointer;
}
#board{
  width: 500px;
  height: 540px;
  position: relative;
  margin: auto;
  border: 1px solid black;
  box-shadow: 0px 0px 10px black;
  background-image: url(space.svg);
  background-size: cover;
  background-color: aquamarine;
}
#message{
  width: 600px;
  height: 64px;
  line-height: 64px;
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  color: aliceblue;
  text-shadow: 0px 0px 10px black;
  position:relative;
  background: rgba(0, 0, 0, 0.5);
  display: block;
  margin-left: 300px;
}
#counter{
  position:fixed;
  top: 20px;
  left: 20px;
}
<p id="message"></p>
<div id="board"></div>
<h1 id="counter"></h1>

<details>
<summary>英文:</summary>
[asteroid image][1] [space-stars image][2]. 
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. 
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.
&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;
&lt;!-- language: lang-js --&gt;
// Maze dimensions
const rows = 10;
const columns = 10;
// Number of asteroids to collect
const totalAsteroids = 17;
// Maze array generation
const maze = Array.from({ length: rows }, () =&gt; Array(columns).fill(0));
// Place the asteroids randomly
let asteroidsPlaced = 0;
while (asteroidsPlaced &lt; totalAsteroids) {
const randomRow = Math.floor(Math.random() * rows);
const randomColumn = Math.floor(Math.random() * columns);
if (maze[randomRow][randomColumn] === 0) {
maze[randomRow][randomColumn] = 1;
asteroidsPlaced++;
}
}
// Initialize game state
let asteroidsCollected = 0;
let maxAsteroids = totalAsteroids;
// Get elements from HTML
const boardElement = document.getElementById(&#39;board&#39;);
const messageElement = document.getElementById(&#39;message&#39;);
const scoreBoard = document.getElementById(&#39;counter&#39;);
messageElement.innerHTML = &quot;Welcome! Start collecting asteroids!&quot;;
scoreBoard.innerHTML = &quot;Score: 0&quot;; // for counter
let score = 0;
// Function to handle square clicks
function squareClicked(row, column) {
const squareValue = maze[row][column];
if (squareValue === 1) {
maze[row][column] = 0;
asteroidsCollected++;  //for the counter
scoreBoard.innerHTML = &quot;Score: &quot; + asteroidsCollected;  //for counter
updateBoard();
if (asteroidsCollected === totalAsteroids) {
messageElement.textContent = &quot;Congratulations! You found all the asteroids!&quot;;
}
}    
}
// Function to update the board
function updateBoard() {
boardElement.innerHTML = &#39;&#39;;
for (let row = 0; row &lt; rows; row++) {
for (let column = 0; column &lt; columns; column++) {
const squareValue = maze[row][column];
const square = document.createElement(&#39;div&#39;);
square.className = &#39;maze-square&#39;;
if (squareValue === 1) {
square.style.backgroundImage = &quot;url(&#39;https://i.stack.imgur.com/cfMRQ.png&#39;)&quot;;
score++;        //for counter
} else {
square.style.backgroundImage = &quot;url(&#39;https://i.stack.imgur.com/Tu6uq.png&#39;)&quot;;
}
square.style.opacity = 0; // Hide the squares initially
square.addEventListener(&#39;click&#39;, () =&gt; {
square.style.opacity = 1;
squareClicked(row, column); //for counter
});
boardElement.appendChild(square);
}
}
}
// Initial board update
updateBoard();
&lt;!-- language: lang-css --&gt;
.maze-square {
width: 50px;
height: 50px;
display: inline-block;
background-size: contain;
cursor: pointer;
}
#board{
width: 500px;
height: 540px;
position: relative;
margin: auto;
border: 1px solid black;
box-shadow: 0px 0px 10px black;
background-image: url(space.svg);
background-size: cover;
background-color: aquamarine;
}
#message{
width: 600px;
height: 64px;
line-height: 64px;
text-align: center;
font-size: 24px;
font-weight: bold;
color: aliceblue;
text-shadow: 0px 0px 10px black;
position:relative;
background: rgba(0, 0, 0, 0.5);
display: block;
margin-left: 300px;
}
#counter{
position:fixed;
top: 20px;
left: 20px;
}
&lt;!-- language: lang-html --&gt;
&lt;p id=&quot;message&quot;&gt;&lt;/p&gt;
&lt;div id=&quot;board&quot;&gt;&lt;/div&gt;
&lt;h1 id=&quot;counter&quot;&gt;&lt;/h1&gt;
&lt;!-- end snippet --&gt;
[1]: https://i.stack.imgur.com/cfMRQ.png
[2]: https://i.stack.imgur.com/Tu6uq.png
</details>
# 答案1
**得分**: 0
以下是您要翻译的内容:
"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.
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.
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`."
以下是翻译好的部分:
"所以,我所需要做的就是注释掉`squareClicked`函数内部的`updateBoard()`,这样就不再清空游戏板了。
问题在于当调用`updateBoard`时,它会创建所有可点击的`div`元素。如果每次点击某物体时都重新创建游戏内部的所有HTML,那肯定会清除掉一切。只需删除这行代码就可以修复它。
我是如何发现这个问题的?我只是注释掉了一些内容,看看是什么导致了这个错误。它发生在你点击某物体时,所以我首先注释掉了点击函数内`squareClicked`的调用。这使得图像保留在游戏板上,从而确认问题与点击有关。`squareClicked`函数内的一切都很合理,除了对`updateBoard`的回调。"
<details>
<summary>英文:</summary>
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.
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.
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`.
&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;
&lt;!-- language: lang-js --&gt;
// Maze dimensions
const rows = 10;
const columns = 10;
// Number of asteroids to collect
const totalAsteroids = 17;
// Maze array generation
const maze = Array.from({ length: rows }, () =&gt; Array(columns).fill(0));
// Place the asteroids randomly
let asteroidsPlaced = 0;
while (asteroidsPlaced &lt; totalAsteroids) {
const randomRow = Math.floor(Math.random() * rows);
const randomColumn = Math.floor(Math.random() * columns);
if (maze[randomRow][randomColumn] === 0) {
maze[randomRow][randomColumn] = 1;
asteroidsPlaced++;
}
}
// Initialize game state
let asteroidsCollected = 0;
let maxAsteroids = totalAsteroids;
// Get elements from HTML
const boardElement = document.getElementById(&#39;board&#39;);
const messageElement = document.getElementById(&#39;message&#39;);
const scoreBoard = document.getElementById(&#39;counter&#39;);
messageElement.innerHTML = &quot;Welcome! Start collecting asteroids!&quot;;
scoreBoard.innerHTML = &quot;Score: 0&quot;; // for counter
let score = 0;
// Function to handle square clicks
function squareClicked(row, column) {
const squareValue = maze[row][column];
if (squareValue === 1) {
maze[row][column] = 0;
asteroidsCollected++;  //for the counter
scoreBoard.innerHTML = &quot;Score: &quot; + asteroidsCollected;  //for counter
//updateBoard(); //&lt;--- I commented this out
if (asteroidsCollected === totalAsteroids) {
messageElement.textContent = &quot;Congratulations! You found all the asteroids!&quot;;
}
}    
}
// Function to update the board
function updateBoard() {
boardElement.innerHTML = &#39;&#39;;
for (let row = 0; row &lt; rows; row++) {
for (let column = 0; column &lt; columns; column++) {
const squareValue = maze[row][column];
const square = document.createElement(&#39;div&#39;);
square.className = &#39;maze-square&#39;;
if (squareValue === 1) {
square.style.backgroundImage = &quot;url(&#39;https://i.stack.imgur.com/cfMRQ.png&#39;)&quot;;
score++;        //for counter
} else {
square.style.backgroundImage = &quot;url(&#39;https://i.stack.imgur.com/Tu6uq.png&#39;)&quot;;
}
square.style.opacity = 0; // Hide the squares initially
square.addEventListener(&#39;click&#39;, () =&gt; {
square.style.opacity = 1;
squareClicked(row, column); //for counter
});
boardElement.appendChild(square);
}
}
}
// Initial board update
updateBoard();
&lt;!-- language: lang-css --&gt;
.maze-square {
width: 50px;
height: 50px;
display: inline-block;
background-size: contain;
cursor: pointer;
}
#board{
width: 500px;
height: 540px;
position: relative;
margin: auto;
border: 1px solid black;
box-shadow: 0px 0px 10px black;
background-image: url(space.svg);
background-size: cover;
background-color: aquamarine;
}
#message{
width: 600px;
height: 64px;
line-height: 64px;
text-align: center;
font-size: 24px;
font-weight: bold;
color: aliceblue;
text-shadow: 0px 0px 10px black;
position:relative;
background: rgba(0, 0, 0, 0.5);
display: block;
margin-left: 175px;
}
#counter{
position:fixed;
top: 20px;
left: 20px;
}
&lt;!-- language: lang-html --&gt;
&lt;p id=&quot;message&quot;&gt;&lt;/p&gt;
&lt;div id=&quot;board&quot;&gt;&lt;/div&gt;
&lt;h1 id=&quot;counter&quot;&gt;&lt;/h1&gt;
&lt;!-- end snippet --&gt;
</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:

确定