Skip to content
Luca Ubiali Web Developer

Real Time Games With Laravel - Calculating Victory

August 29th, 2024
Continuous Learning

Episode - https://laracasts.com/series/real-time-games-with-laravel/episodes/4


Victory can be calculated by using my dear friend reduce, always good to do practice with this one.

1<script>
2const fillSquare = (index) => {
3 //...
4 
5 const winningLine = lines.map((line) => line.reduce((carry, index) => carry + boardState.value[index], 0))
6 .filter((sum) => Math.abs(sum) === 3);
7 
8 //...
9}
10</script>

lines is an array of arrays. Each nested array represents a possible winning line: all rows (for example [0, 1, 2]), all columns (for example [0, 3, 6]) and the two crosses (for example [0, 4, 8]). Those are the ones we need to check to find the winner.