Cookie Consent by Free Privacy Policy Generator 📌 Implementing Tic Tac Toe in Vue

🏠 Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeiträge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden Überblick über die wichtigsten Aspekte der IT-Sicherheit in einer sich ständig verändernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch übersetzen, erst Englisch auswählen dann wieder Deutsch!

Google Android Playstore Download Button für Team IT Security



📚 Implementing Tic Tac Toe in Vue


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

Tictac-toeTictac 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 initialising the states of our game:

  • winner to store the winner value,
  • isTie: this stores a boolean value, false in the begining and if no winner, is sets to true,
  • gameover: this holds a boolean value, false at the begining and is sets to true when a winner emerges or isTie is true,
  • currentplayer stores the value of the current player
  • a 3*3 array, also know as 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 row represents the the rows which includes an inner div that represents the cells in each rows. 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!</p>
      <button @click="reset">Reset Game</button>
    </div>
  </div>
</template>

Next step is creating the functions for our game, we start with the checkTie. This function checks if the current game is in a tie state.

The checkTie function uses a nested loop to iterate over each cell on the 3x3 game board. It starts by initializing two variables i and j to zero and increments them until they reach three. The i and j variables represent the row and column index of each cell on the board.

With each iteration of the loop, the function checks if the cell at the current i and j position is empty, if empty, the function returns false.

If the loop completes without finding any empty cell, the function returns true resulting in a tie state between the players.

const checkTie = () => {
  for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
      if (!board[i][j]) {
        return false;
      }
    }
  }
  return true;
}

Our next step is the checkWin function. This function checks all the possible ways a player can win, and returns true if the current player has won and false otherwise.

Inside the function, the for loop checks each row and column of the board to see if all the cells in the row or column match the current player's value. This is done by using the every() method on each row and column to if every cell in that row or column is equal to the current value.

If a row or column is found where every cell matches the current player's value, the function returns true to indicate that the current player has won the game.

If no winning row or column is found, the function checks the two diagonals of the board to see if they are all equal to the current player's value. If a diagonal is found where all cells are equal to the current value, the function returns true to indicate that the current player has won the game.

If no winning row, column, or diagonal is found, the function returns false to indicate that the game is not yet won by the current player.

const checkWin = () => {
  const a = currentPlayer.value;

  for (let i = 0; i < 3; i++) {
    if (board[i].every(cell => cell === a)) return true;
    if (board.every(row => row[i] === a)) return true;
  }

  // Check diagonals
  if (board[0][0] === a && board[1][1] === a && board[2][2] === a) return true;
  if (board[0][2] === a && board[1][1] === a && board[2][0] === a) return true;

  return false;
};

Our next function is the playMove function. This function updates the board when a player makes a move, it takes in two arguments, row and col, which represents the coordinates of the cell that the player clicks.

The function first checks if the cell is empty (!board[row][col]) and if there is no winner yet (!winner.value). If both of these conditions are true, then it proceeds to update the game board with the current player's value.

The checkWin function is then called to check if the current player has won the game. If the current player has won, the winner variable is updated with the current player's value. If not, the checkTie function is called to check if the game is tied. If the game is tied, the isTie varaible is set to true.

If the game is not won or tied, the currentPlayer variable is updated to the other player's title. This is done using a ternary operator that checks if the current player is 'X'. If so, it switches to 'O', and vice versa.

const playMove = (row: number, col: number) => {
  if (!board[row][col] && !winner.value) {
    board[row][col] = currentPlayer.value;
    if (checkWin()) {
      winner.value = currentPlayer.value;
    } else if (checkTie()) {
      isTie.value = true;
    } else {
      currentPlayer.value = currentPlayer.value === 'X' ? 'O' : 'X';
    }
  }
}

Finally, we have the reset function, to reset the state of our game to its default state.

const reset = () => {
  board = [
    ['', '', ''],
    ['', '', ''],
    ['', '', '']
  ];
  currentPlayer.value = 'X';
  gameover.value = false;
  winner.value = null;
}

Here's the css used for this game

body {
  margin: 0;
  display: flex;
  min-width: 320px;
  min-height: 100vh;
}


#app {
  max-width: 1280px;
  margin: 0 auto;
  padding: 2rem;
  text-align: center;
}

.tic-tac-toe {
  text-align: center;
}

.board {
  display: inline-block;
  margin-top: 20px;
}

.row {
  clear: both;
}

.cell {
  width: 50px;
  height: 50px;
  float: left;
  margin-right: -1px;
  margin-bottom: -1px;
  line-height: 50px;
  text-align: center;
  border: 1px solid #bbb;
  cursor: pointer;
  font-size: 40px;
}

.cell-x {
  color: #f00;
}

.cell-o {
  color: #00f;
}

button {
  margin-top: 20px;
  font-size: 16px;
  padding: 10px;
  border-radius: 5px;
  background-color: #ccc;
  border: none;
  cursor: pointer;
}

Link to the the github repo tictac game repo

...



📌 Implementing Tic Tac Toe in Vue


📈 92.66 Punkte

📌 You Can Now Play Solitaire and Tic-Tac-Toe in Google's Search Results


📈 66.13 Punkte

📌 Solitaire & Tic Tac Toe: Neue Eastereggs in Google Suche


📈 66.13 Punkte

📌 You Can Now Play Solitaire and Tic-Tac-Toe in Google's Search Results


📈 66.13 Punkte

📌 Solitaire & Tic Tac Toe: Neue Eastereggs in Google Suche


📈 66.13 Punkte

📌 Printf Oriented Programming (tic-tac-toe implementation)


📈 66.13 Punkte

📌 Tic Tac Toe: Zickenkrieg statt Street-Credibility


📈 66.13 Punkte

📌 Build a Tic Tac Toe Game using HTML, CSS, JavaScript, Tailwind CSS and Canvas Confetti


📈 66.13 Punkte

📌 myTicTacToe 3.3 - Tic-Tac-Toe game.


📈 66.13 Punkte

📌 Caltech Scientists Use DNA Tiles To Play Tic-Tac-Toe at the Nanoscale


📈 66.13 Punkte

📌 Lessons Learned: Adding ChatGPT to a Tic-Tac-Toe Game in Next.js


📈 66.13 Punkte

📌 Advent of Typescript 2023 Day 21 : TIC TAC TOE


📈 66.13 Punkte

📌 Building a Tic Tac Toe App with React.js: A Step-by-Step Guide 2024


📈 66.13 Punkte

📌 Creating a Tic-Tac-Toe Game in C++


📈 66.13 Punkte

📌 Browser-based Multiplayer Tic Tac Toe Game in React


📈 66.13 Punkte

📌 Tic-Tac-Toe JavaScript game for beginners


📈 66.13 Punkte

📌 Llama-2 vs. Llama-3: a Tic-Tac-Toe Battle Between Models


📈 66.13 Punkte

📌 Use smart chips in #GoogleDocs to play tic tac toe with you teammates ❌ ⭕️ #Shorts


📈 66.13 Punkte

📌 Tic Tac Toe Terminal Game


📈 66.13 Punkte

📌 Need help with the Odin Project 'Tic Tac Toe'


📈 66.13 Punkte

📌 Tic-Tac-Toe Hard Mode


📈 66.13 Punkte

📌 Building a Tic-Tac-Toe Game in Python: A Step-by-Step Guide


📈 66.13 Punkte

📌 Strip Tac Toe 1.0 Englisch


📈 44.22 Punkte

📌 Results are in: Qualcomm’s Snapdragon X Elite goes toe-to-toe with Apple’s new M3 Pro processor


📈 43.81 Punkte

📌 Apple's rumored M1 successor could go toe-to-toe with high-end Intel chips


📈 43.81 Punkte

📌 Qualcomm's Going Toe-To-Toe With Apple's Satellite Messaging Feature


📈 43.81 Punkte

📌 Moving From Vue 1 To Vue 2 To Vue 3: A Case Study Of Migrating A Headless CMS System


📈 40.82 Punkte

📌 NativeScript-Vue 2.0 erschienen: Native Mobile-Apps mit Vue


📈 27.21 Punkte

📌 Easy Vue internationalization - guide to the Vue I18n plugin


📈 27.21 Punkte

📌 Vue i18n – So erstellst Du mehrsprachige Vue.js Anwendungen!


📈 27.21 Punkte

📌 500+ Vue.js Tailwind CSS UI Components - TailGrids Vue


📈 27.21 Punkte

📌 Vue Designer 1.4 - Desktop editor to visually design Vue applications.


📈 27.21 Punkte

📌 HTML & Vue.js, a secrete you may not know about Vue


📈 27.21 Punkte

📌 Enhance the drag and drop of your Vue 3 application with Vue Fluid DnD


📈 27.21 Punkte

📌 Implementing Debouncing in Vue


📈 26.53 Punkte











matomo