简介
本文将会基于React 实现五子棋小游戏,游戏规则为先让5颗棋子连成1线的一方获胜。
实现效果
技术实现
页面布局
<div>
<table style={
{border: '1px solid #000', borderCollapse: 'collapse', backgroundColor: 'lightgray'}}>
<tbody>
{
squares.map((row, rowIndex) => {
return <tr key={rowIndex}>
{
row.map((col, colIndex) => {
return <td key={colIndex}
style={
{border: '1px solid #000', width: '30px', height: '30px'}}
onClick={(event) => {
const clickedElement = event.target as HTMLTableCellElement;
const rect = clickedElement.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
const width = clickedElement.getBoundingClientRect().width;
const height = clickedElement.getBoundingClientRect().height;
const left = x / width;
const top = y / height;
if (left < 0.5 && top < 0.5){ // 左上
if (rowIndex > 0){
rowIndex--;
}
if (colIndex > 0){
colIndex--;
}
}
if (left < 0.5 && top > 0.5){ // 左下
if (colIndex > 0){
colIndex--;
}
}
if (left > 0.5 && top < 0.5){ // 右上
if (rowIndex > 0){
rowIndex--;
}
}
let item = squares[rowIndex][colIndex];
if (item !== '') {
return;
}
if (times % 2 === 0) {
item = 'black';
} else {
item = 'white';
}
const newSquares = [...squares];
newSquares[rowIndex][colIndex] = item;
setTimes(times + 1);
setSquares(newSquares);
}
}
>
{col === 'white' ?
<div
style={
{
width: '100%',
height: '100%',
backgroundColor: 'white',
borderRadius: '50%',
position: "relative",
right: "-50%",
bottom: "-50%"
}}></div>
: (col === 'black' ?
<div
style={
{
width: '100%',
height: '100%',
backgroundColor: 'black',
borderRadius: '50%',
position: "relative",
right: "-50%",
bottom: "-50%"
}}&g