Tic Tac Toe game used to be one of my favourite paper games in primary school. It was known as ‘X’ and ‘O’, I don’t quite remember how often I won, but I definitely enjoyed playing it. Recently, my friend @eteimz challenged me to build this game with Vue. He built the react version. You can check it out here reactoe.
For this tutorial, I will be using the Vue Composition API Style. In the github repository linked below, you can find the code for both Composition and Options API.
We start by initializing the states of our game:
- winner to store the winner’s value,
- isTie: this stores a boolean value, false in the beginning and if no winner, is set to true,
- gameover: this holds a boolean value, false at the beginning and is set to true when a winner emerges or isTie is true,
- currentplayer stores the value of the current player
- a 3*3 array, also known as a matrix.
<script setup lang="ts">
import { ref, reactive } from 'vue';
const winner = ref<string | null>(null);
const isTie = ref(false);
const gameover = ref(false);
const currentPlayer = ref('X');
let board = reactive([
['', '', ''],
['', '', ''],
['', '', '']
]);
</script>
Next step is our template
- Inside the board div, the first div with a class of rows represents the rows which include an inner div that represents the cells in each row. A click event is attached to the cell.
<template>
<div>
<h1 class="">TicTac Game</h1>
<p class=""> Current Player: <span class=""> {{ currentPlayer }} </span> p>
<div class="row" v-for="(row, rowIndex) of board" :key="rowIndex">
<div class="cell" v-for="(cell, cellIndex) of row" :key="cellIndex"
:class="{ 'cell-x': cell === 'X', 'cell-o': cell === 'O' }" :disabled="cell !== null"
@click="playMove(rowIndex, cellIndex)">
{{ cell }}
</div>
</div>
<div class="">
<p v-if="winner">{{ winner }} wins!</p>
<p v-else-if="isTie">It's a tie!