Skip to content
Luca Ubiali Web Developer

Real Time Games With Laravel - Board Basics

August 28th, 2024
Continuous Learning

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


This episode is about laying down the tic-tac-toe grid. The interesting part is how it’s modeled and updated through user interaction.

1<script>
2 //...
3 
4 const boardState = ref([0, 0, 0, 0, 0, 0, 0, 0, 0]);
5 
6 const xTurn = computed(() => boardState.value.reduce((carry, value) => carry + value, 0) === 0);
7 
8 const fillSquare = (index) => {
9 boardState.value[index] = xTurn.value ? -1 : 1;
10 }
11</script>

The board is represented by an array of nine numbers. Each number is set to zero if the square is empty, -1 for a cross and 1 for a nought.

On the UI each empty square has a button that triggers fillSquare when clicked. I like how through the xTurn computed property it’s possible to determine which player turn it is.

By summing up all the elements in the array we can see that it’s X’’s turn if the sum is less than zero, Os otherwise. No need for additional support variable.