Last active
April 30, 2024 07:22
-
-
Save MrZhouZh/540c5df34f4985e15aca6295ec051810 to your computer and use it in GitHub Desktop.
react tic-tac-toe 小游戏算法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 计算胜负 | |
* 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