DEV Community

Cover image for Creating TicTacToe in Vue.js
Ezekiel Sulit Ayuno
Ezekiel Sulit Ayuno

Posted on • Edited on

Creating TicTacToe in Vue.js

Intoduction

Hello readers in this blog post I will be writing about how to build a Tic Tac Toe game with Vue.js with Vite and Tailwind CSS to style. For those who don't know what Tic Tac Toe is it is a simple game yet very entertaning to pass time, you will need two people to play this game. The goal of the game is to get three of your symbols in a row in a three by three box. For most people seeking to be a game developer creating a tic tac toe game is quite useful since it is a quick and challenging activity to gain skills in this field.

Prerequisites

  • Basic Knowledge of Vue JS

VueJS framework for building user interface and single-page applications. (Discussed on my previous blog post!)

  • Intro Level Knowledge of Tailwind CSS

Tailwind CSS is a utility-first CSS framework designed to enable users to style applications faster and easier.

Example: If you want to create a button that has a fixed height, horizontal padding, rounded corners, red background, and white colored font, heres the code you would implement:

<button @click="ResetGame" class="px-4 bg-red-500 rounded uppercase font-bold hover:bg-green">Reset</button>

px-4: This class sets the horizontal padding of the button to 4 units.

rounded: This sets the button to have rounded corners.

font-bold: This sets the font of the button to be bold.

bg-red: This class sets the background color of the button to red.

hover:bg-green: This sets the background color of the button to green if the mouse hovers on it.

Using TailwindCSS makes it easier by keeping your CSS files small, safer changes, and low-level coding.

  • Basic Knowledge of Vite

Also created by Evan You (Creator of Vue) Vite is a build tool for faster development because of (HMR) Hot Module Reload and fast cold start times. Were gonna be using Vite to get the project started.

Setting up The project

Installing Vite

To use "Vite" on a Vue.JS project in the terminal type:

npm create vite@latest

This command will create a basic template for us to use for our project. This command will also ask you questions on a project name, package name, which framework, and either JS or TS. Please choose as shown:

ViteInstallation

Installing VueJS

When the "npm create vite@latest" command is run we will be prompted to pick which framework we will use, please select Vue.JS

Installing Tailwind CSS

To install TailwindCSS in the terminal type:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

After running this command you will have to configure your "tailwind.config.js file" replace the contents of the file with this code:

module.exports = {
  content: [
    "./index.html",
    "./src/**/*.{vue,js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
Enter fullscreen mode Exit fullscreen mode

You will also have to create a new CSS file called main.css and paste this code inside:

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

In the main.js file add:

import './main.css'

Know that all the prerequisites have been installed we will get started on creating our TicTacToe project. You will have to create a new file called "App.vue" in the src folder. In this App.vue file is where we will create our TicTacToe game.

Creating Board Logic

To create the TicTacToe board in our App.vue file we will have to add this code in the script tag:

const player = ref ('X');
const board = ref ([
  ['', '', ''],
  ['', '', ''],
  ['', '', '']
])
Enter fullscreen mode Exit fullscreen mode

As you can see this board shows our TicTacToe board and also shows the player. There are 9 cells like in a regular TicTacToe game so imagine that each array in this array is a row and the items inside those arrays are going to be our marks.

Finding the Winner

Our next piece of code is showing how to calculate the winner, under the code above still in our App.vue file add this code in the script tag:

const 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;
}
Enter fullscreen mode Exit fullscreen mode

So for this code we have lines and these lines show us all the possible ways of winning a game if our marks are in the right place. 0-8 are assigned to the 9 cells in our square respectively and if we have any of the lines shown above true to ours then this will calculate the winner of the game.

We also have:

const winner = computed(() => calculateWinner(board.value.flat()))
Enter fullscreen mode Exit fullscreen mode

The line of code above will show who the winner is!

Whos move?

We will also have code that will determine which players move it is

const MakeMove = ( x, y ) => {
  if (winner.value) return

  if (board.value[x][y] !== '') return

  board.value[x][y] = player.value
  player.value = player.value === 'X' ? 'O' : 'X'
  }
Enter fullscreen mode Exit fullscreen mode

The code above turns our logical board and turns it into a grid with "x" being horizontal and "y" being vertical this determines which players move is finished when they click on an empty cell then switches players from player "X" to player "O".

Resetting the board

Our final piece of script code is to reset the board once a game is finished.

const ResetGame = () => {
    board.value = [
        ['', '', ''],
        ['', '', ''],
        ['', '', '']
    ]
    player.value = 'X'
  }
Enter fullscreen mode Exit fullscreen mode

Creating Board Physical

Know that the logic part for our TicTacToe game is done lets create our physical game board.

This code will physically create our board and calls the "board" method in the script section.

Styled by using TailwindCSS if we hover over a cell it will turn green and onced clicked it will display the mark of the current player.

<div class="flex flex-col items-center mb-8">
            <div 
                v-for="(row, x) in board" 
                :key="x"
                class="flex">
                <div 
                    v-for="(cell, y) in row" 
                    :key="y" 
                    @click="MakeMove(x, y)" 
                    :class="`border border-white w-24 h-24 hover:bg-blue-700 flex items-center justify-center material-icons-outlined text-4xl cursor-pointer ${cell === 'X' ? 'text-pink-500' : 'text-blue-400'}`">
                    {{ cell === 'X' ? 'close' : cell === 'O' ? 'circle' : '' }}
                </div>
            </div>
        </div>
Enter fullscreen mode Exit fullscreen mode

Player Move

This code will currently show which players turn it is by retrieving the player information from the player value.

<h3 class="text-xl mb-4">Player {{ player }}'s turn</h3>
Enter fullscreen mode Exit fullscreen mode

Displaying Winner

This code will call the "winner" method in our script section and display the winner of the game if there was a winner.

<h2 v-if="winner" class="text-6xl font-bold mb-8">Player '{{ winner }}' wins!</h2>

Enter fullscreen mode Exit fullscreen mode

Reset Button

This code will call the "reset" method in our script and once clicked will get rid of all marks made on the board and reset the game.

<button @click="ResetGame" class="px-4 py-2 bg-red-500 rounded uppercase font-bold hover:bg-red-600 duration-300">Reset</button>

Enter fullscreen mode Exit fullscreen mode

Final Product

Conclusion

As a result, creating a TicTacToe game with Vue JS, Tailwind CSS, and Vite is a rewarding and instructive project that may teach you more about contemporary web programming. You can make your own version of the game that is better suited to your liking by following the instructions provided in this blog article. Coding is...... fun.

Top comments (0)