Build a Tic Tac Toe Game Using Vue 3 and JavaScript
Written on
Creating a New Project
To get started with building a Tic Tac Toe game using Vue 3, we first need to set up our Vue project. This can be accomplished using the Vue CLI.
To install the Vue CLI, use the following commands:
npm install -g @vue/cli
or for Yarn users:
yarn global add @vue/cli
After installation, create your project by running:
vue create tic-tac-toe
Simply choose the default options to initialize your project.
Developing the Tic Tac Toe Game
In order to create the game, we will set up the template and script as follows:
<template>
<div v-if="xWins || oWins">
<div v-if="xWins">X wins</div>
<div v-if="oWins">O wins</div>
<button @click="restart">Restart</button>
</div>
<form v-else>
<div v-for="i in 3" :key="i">
<span v-for="j in 3" :key="j">
<input v-model.trim="board[i - 1][j - 1]" style="width: 20px" /></span>
</div>
</form>
</template>
<script>
const board = [[], [], []];
export default {
name: "App",
data() {
return {
board,};
},
computed: {
xWins() {
return this.checkWinner("x");},
oWins() {
return this.checkWinner("o");},
},
methods: {
restart() {
this.board = [[], [], []];},
checkWinner(player) {
const { board } = this;
return (
(board[0][0] === player && board[0][1] === player && board[0][2] === player) ||
(board[1][0] === player && board[1][1] === player && board[1][2] === player) ||
(board[2][0] === player && board[2][1] === player && board[2][2] === player) ||
(board[0][0] === player && board[1][0] === player && board[2][0] === player) ||
(board[0][1] === player && board[1][1] === player && board[2][1] === player) ||
(board[0][2] === player && board[1][2] === player && board[2][2] === player) ||
(board[0][0] === player && board[1][1] === player && board[2][2] === player) ||
(board[0][2] === player && board[1][1] === player && board[2][0] === player)
);
},
},
};
</script>
In this template, a conditional div shows the result of the game if there is a winner. If either player X or O wins, it displays the respective winner along with a restart button. If the game is still ongoing, the 3x3 input grid allows players to enter their moves.
The v-for directive is used to create the grid inputs, and we bind the values entered by players to a nested array that represents the game board using v-model. The trim modifier is applied to eliminate any unnecessary whitespace from the input.
The script section initializes the board and defines computed properties to check if a player has won. The checkWinner method verifies whether the specified player has achieved a winning configuration by checking all possible winning combinations—horizontally, vertically, or diagonally.
Conclusion
Creating a Tic Tac Toe game with Vue 3 and JavaScript is straightforward and offers a great way to practice your skills. For more insightful content, visit plainenglish.io.