Skip to content

Instantly share code, notes, and snippets.

@MrZhouZh
Last active April 30, 2024 07:22
Show Gist options
  • Save MrZhouZh/540c5df34f4985e15aca6295ec051810 to your computer and use it in GitHub Desktop.
Save MrZhouZh/540c5df34f4985e15aca6295ec051810 to your computer and use it in GitHub Desktop.
react tic-tac-toe 小游戏算法
/**
* 计算胜负
* refs: https://react.dev/learn/tutorial-tic-tac-toe
* leetcode: https://leetcode.cn/problems/find-winner-on-a-tic-tac-toe-game
*/
export default function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment