在Reaction中,我试图重现著名的游戏"扫雷舰",在我的旅程中,我想随机生成炸弹将在哪里产生,所以我得到了一个12*12矩阵和40个炸弹,我随机生成了代表坐标的x和y,但为了不公平,我只在第一个方块被选中后才生成炸弹,现在代码还没有完成,但我猜是因为在游戏的第一阶段(前面提到的)我通过按下提交按钮进行了重新渲染,变量炸弹永远不会减少到0,因为它总是被再次声明为40.我试图在函数外部声明它,我甚至try 为该值设置useState,但它不断递增并创建无限循环.如何声明不可更改的变量?
import { useState } from 'react'
import './App.css'
const square = {
bomb: 0,
viz: 0,
}
let nrbomb = 40
function App() {
const n = 12
let v = []
for (let i = 0; i < n; i++) {
let arr = []
for (let j = 0; j < n; j++) arr.push(square)
v.push(arr)
}
const [inc, change_inc] = useState(0)
const [mine_grid, change_mine_grid] = useState(v)
const [cx, change_cx] = useState(0)
const [cy, change_cy] = useState(0)
const [rendergame, change_render_game] = useState(0)
if (inc == 0) {
return (
<div className="all">
<div className="grid_container">
{mine_grid.map((arr) => {
return arr.map((e) => {
return (
<div
style={{
background: 'green',
width: '50px',
height: '50px',
margin: '5px',
}}
></div>
)
})
})}
</div>
<h6>for x:</h6>
<input
value={cx}
onChange={(e) => {
change_cx(e.target.value)
}}
></input>
<h6>for y:</h6>
<input
value={cy}
onChange={(e) => {
change_cy(e.target.value)
}}
></input>
<button
type="button"
onClick={() => {
let new_grid = mine_grid
new_grid[cx][cy].viz = 1
change_mine_grid(new_grid)
change_inc(1)
}}
>
Submit move
</button>
</div>
)
}
if (inc == 1 && rendergame == 0) {
while (nrbomb != 0) {
let x = Math.floor(Math.random() * n)
let y = Math.floor(Math.random() * n)
console.log(x, y, nrbomb)
if (mine_grid[x][y].bomb === 0 && mine_grid[x][y].viz == 0) {
nrbomb = nrbomb - 1
let new_grid = mine_grid
new_grid[x][y].bomb = 1
change_mine_grid(new_grid)
}
}
}
return <div className="grid_container"></div>
}
export default App