我是新来的反应者,因此决定制作一款扫雷游戏,边做边学。如果它们不碰任何炸弹,以递归方式清除磁贴,就会遇到麻烦。
我决定处理组成square
的每个board
组件的click事件。此单击处理程序首先检查是否单击了炸弹,然后检查该正方形是否已被单击或标记,如果不是,则清除该正方形。如果广场没有碰到任何炸弹,它也应该清除其相邻的地砖。我想通过在其上调用element.click()来清除这些相邻的磁贴,但是据我所知,调用element.click()如此多次会减慢浏览器的速度并占用大量内存。
我在问:
Codepen链接:https://codepen.io/door-bell/pen/WKNJyy
class Square extends React.Component {
constructor(props) {
super(props);
this.handleRightClick = this.handleRightClick.bind(this);
this.state = {
status: 'unclicked',
touching: this.props.touching,
isBomb : this.props.bomb
};
}
handleClick(isBomb) {
if (isBomb) {
document.writeln('game over!');
return;
}
if (this.state.status !== 'clicked' && this.state.status !== 'flagged') {
this.setState({status: 'clicked'});
if (this.state.touching === 0) {
var adjacentSquares = getAdjacentSquares(this.props.row, this.props.col);
for (var i = 0; i < adjacentSquares.length; i++) {
var element = document.querySelector('[row="'+adjacentSquares[i].row+'"][col="'+adjacentSquares[i].col+'"]');
if (element && element.classList.contains('unclicked')) {
console.log('clicking...'+JSON.stringify(adjacentSquares[i]));
element.click();
console.log('clicked one');
}
}
}
}
}
handleRightClick(e) {
e.preventDefault();
switch (this.state.status) {
case 'unclicked':
this.setState({status: 'flagged'});
break;
case 'flagged':
this.setState({status: 'unclicked'});
break;
default:
break;
}
}
render() {
var states = {
'unclicked': ' ',
'clicked': this.state.touching,
'flagged': '*'
}
return (
<td
row={this.props.row}
col={this.props.col}
className={'tile ' + this.state.status}
onClick={() => this.handleClick(this.state.isBomb)}
onContextMenu={this.handleRightClick}>
{states[this.state.status]}
</td>
);
}
}
getAdjacentSquares方法,该方法返回对象数组{行:x,col:y}
function getAdjacentSquares(row,col) {
var adjacentSquares = [
{
row: row+1,
col: col+1
},
{
row: row,
col: col+1
},
{
row: row+1,
col: col
},
{
row: row-1,
col: col-1
},
{
row: row,
col: col-1
},
{
row: row-1,
col: col
},
{
row: row+1,
col: col-1
},
{
row: row-1,
col: col+1
}
];
return adjacentSquares;
}