Question

In: Computer Science

Use JavaScript/HTML to create a Tic Tac Toe game displaying X's O's. Score the result. Each...

Use JavaScript/HTML to create a Tic Tac Toe game displaying X's O's. Score the result. Each player takes a turn putting their mark until done or tied.

Solutions

Expert Solution

CODE:

index.html

<!DOCTYPE html>

<html>

<head>

    <title>tic tac toe</title>

    <link rel="stylesheet" type="text/css" href="styles.css">

    

</head>

<body>

    <h1 class="title">tic tac toe</h1>

    <table class="table">

        <tr class="t1">

            <td class="cell" id="0"></td>

            <td class="cell" id="1"></td>

            <td class="cell" id="2"></td>

        </tr>

        <tr class="t1">

            <td class="cell" id="3"></td>

            <td class="cell" id="4"></td>

            <td class="cell" id="5"></td>

        </tr>

        <tr class="t1">

            <td class="cell" id="6"></td>

            <td class="cell" id="7"></td>

            <td class="cell" id="8"></td>

        </tr>

    </table>

    <div class="endgame">

        <div class="text"></div>

    </div>

    <button class="replay" onclick="startGame()">Replay</button>

<script src="app.js" type="text/javascript" ></script>

</body>

</html>

styles.css

body{

    padding: 0px;

    margin: 0px;

    box-sizing: border-box;

    background-color: #24272E

}

.title{

    position: absolute;

    left: 50%;

    transform: translate(-50%,-50%);

    color: #2d716b;

    text-transform: uppercase;

    font-family: "Comic Sans MS",cursive;

    font-size: 100px;

    display: block;

}

td{

    border:2px solid #333;

    height: 100px;

    width: 100px;

    text-align: center;

    vertical-align: middle;

    font-size: 70px;

    cursor: pointer;

    font-family: "Comic Sans MS",cursive;

    border-color: #fff;

    color: #fff;

}

table{

    border-collapse: collapse;

    position: absolute;

    top: 50%;

    left: 50%;

    transform: translate(-50%,-50%);

}

table tr:first-child td{

    border-top: 0;

}

table tr:last-child td{

    border-bottom: 0;

}

table tr td:first-child{

    border-left: 0;

}

table tr td:last-child{

    border-right: 0;

}

.endgame{

    display: none;

    position: absolute;

    width: 200px;

    top: 45%;

    left: 50%;

    transform: translate(-50%,-50%);

    background-color: rgba(205,133,63, 0.8);

    padding-top: 50px;

    padding-bottom: 50px;

    text-align: center;

    color: white;

    border-right: 5px;

    font-size: 2em;

}

.replay{

    position: absolute;

    left: 50%;

    top: 80%;

    transform: translate(-50%,-50%);

    font-size: 30px;

    font-family: "Comic Sans MS",cursive;

}

app.js

var origBoard;

const first_player = "O";

const second_player = "X";

const winCombos = [

  [0, 1, 2],

  [3, 4, 5],

  [6, 7, 8],

  [0, 3, 6],

  [1, 4, 7],

  [2, 5, 8],

  [0, 4, 8],

  [6, 4, 2]

];

// get all the table data cells dom elements

const cells = document.querySelectorAll(".cell");

startGame();

function startGame() {

  document.querySelector(".endgame").style.display = "none";

  origBoard = Array.from(Array(9).keys());

  

  for (var i = 0; i < cells.length; i++) {

    cells[i].innerText = "";

    cells[i].style.removeProperty("background-color");

    cells[i].addEventListener("click", turnClick, false);

  }

}

var whoseTurn=1;

function turnClick(square) {

  // check if that index is empty or not

  // when not empty it will store a string "X" or "O"

  if (typeof origBoard[square.target.id] == "number") {

    console.log(checkTie())

    if(whoseTurn%2!=0){

      if (!checkWin(origBoard, first_player) && !checkTie())

        turn(square.target.id, first_player);

    }

    

    else{

      if (!checkWin(origBoard, first_player) && !checkTie()){

        turn(square.target.id, second_player);

        

      }

        

    }

    

      console.log(origBoard);

    whoseTurn++;

  }

}

// register a turn

function turn(squareId, player) {

  // store X or O at that index

  origBoard[squareId] = player;

  // update the frontend with O or X

  document.getElementById(squareId).innerText = player;

  // check if the move can be a winning more or not

  let gameWon = checkWin(origBoard, player);

  if (gameWon) gameOver(gameWon);

}

function checkWin(board, player) {

  let plays = board.reduce((a, e, i) => (e === player ? a.concat(i) : a), []);

  let gameWon = null;

  for (let [index, win] of winCombos.entries()) {

    if (win.every(elem => plays.indexOf(elem) > -1)) {

      gameWon = { index: index, player: player };

      break;

    }

  }

  return gameWon;

}

function gameOver(gameWon) {

  for (let index of winCombos[gameWon.index]) {

    document.getElementById(index).style.backgroundColor =

      gameWon.player == first_player ? "blue" : "red";

  }

  for (var i = 0; i < cells.length; i++) {

    cells[i].removeEventListener("click", turnClick, false);

  }

  declareWinner(gameWon.player == first_player ? "Player 1 Won!" : "Player 2 Won");

}

function declareWinner(who) {

  document.querySelector(".endgame").style.display = "block";

  document.querySelector(".endgame .text").innerText = who;

}

// returns the number of cells with no inputs

function emptySquares() {

  return origBoard.filter(s => typeof s == "number");

}



function checkTie() {

  if (emptySquares().length == 1) {

    for (var i = 0; i < cells.length; i++) {

      cells[i].style.backgroundColor = "green";

      cells[i].removeEventListener("click", turnClick, false);

    }

    declareWinner("Tie Game!");

    return true;

  }

  return false;

}


OUTPUT:

Please upvote if you like my answer and comment below if you have any queries or need any further explanation.


Related Solutions

How to make tic tac toe game in javascript with vue.js
How to make tic tac toe game in javascript with vue.js
For this assignment, you will write a tic-tac-toe application in HTML and JavaScript, using an HTML...
For this assignment, you will write a tic-tac-toe application in HTML and JavaScript, using an HTML <canvas> tag. The game will be played "hot seat" where players take turns using the same device. Requirements: The canvas should be 600px tall and wide, with the gameplay area occupying most of the canvas. The X's and O's may be drawn using polygons or large-font text The grid should be drawn using polygons, specifically long, thin rectangles Before & between games, the canvas...
Write a program that plays tic-tac-toe. The tic-tac-toe game is played on a 3 × 3...
Write a program that plays tic-tac-toe. The tic-tac-toe game is played on a 3 × 3 grid as shown below: The game is played by two players, who take turns. The first player marks moves with a circle, the second with a cross. The player who has formed a horizontal, vertical, or diagonal sequence of three marks wins. Your program should draw the game board, ask the user for the coordinates of the next mark (their move), change the players...
- Make a 2-D array to represent a Tic-Tac-Toe game/grid. Place a couple of 'X's and...
- Make a 2-D array to represent a Tic-Tac-Toe game/grid. Place a couple of 'X's and 'O's in the grid and display it. Do some extra printing to make it look like a Tic-Tac-Toe board we are suppose to use rows and columns so just make it simple thanks!
PYTHON (Game: Tic-tac-toe): Write a program that plays the tic-tac-toe game. Two players take turns clicking...
PYTHON (Game: Tic-tac-toe): Write a program that plays the tic-tac-toe game. Two players take turns clicking an available cell in a 3 x 3 grid with their respective tokens (either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won. A draw (no winner) occurs when all the cells in the grid have been filled with tokens and neither player has...
please create a tic tac toe game with python using only graphics.py library
please create a tic tac toe game with python using only graphics.py library
Tic-Tac-Toe, also called X's and O's, Noughts and Crosses, and X and 0 is a simple...
Tic-Tac-Toe, also called X's and O's, Noughts and Crosses, and X and 0 is a simple game played on a 3x3 grid, referred to as the board. Lines may be horizontal, vertical, or diagonal. You will implement a Board class to represent the 3x3 grid. This class will have functions to determine which symbol, if any, is in a cell, to place a symbol in a cell, to determine the winner, if any so far, and to print the board...
make a 4x4 tic tac toe in javascript (X is the user) (O is the computer)
make a 4x4 tic tac toe in javascript (X is the user) (O is the computer)
Program Description, Interfaces, and Functionality To create a Python tic-tac-toe game, use Python's randint function from...
Program Description, Interfaces, and Functionality To create a Python tic-tac-toe game, use Python's randint function from the random module to control the computer's moves. To determine if the game has been won or is a tie/draw, write at least the func- tions: def move(), def check_cols(), def check_diag1(), def check_diag2(), def check_rows(), and def print_board(). Four of the functions will check if a winning state exist. To win tic-tac-toe, a user needs to have three of the same game pieces,...
The objective of this assignment is to implement the tic-tac-toe game with a C program. The...
The objective of this assignment is to implement the tic-tac-toe game with a C program. The game is played by two players on a board defined as a 5x5 grid (array). Each board position can contain one of two possible markers, either ‘X’ or ‘O’. The first player plays with ‘X’ while the second player plays with ‘O’. Players place their markers in an empty position of the board in turns. The objective is to place 5 consecutive markers of...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT