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

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...
How to make tic tac toe game in javascript with vue.js
How to make tic tac toe game in javascript with vue.js
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!
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
In a game of tic tac toe. How do you check if all the positions in...
In a game of tic tac toe. How do you check if all the positions in a double array are taken, the double arrays are used to store the x's and o's?
Write a program that allows two players to play a game of tic-tac-toe. Use a two-dimensional...
Write a program that allows two players to play a game of tic-tac-toe. Use a two-dimensional char array with three rows and three columns as the game board. Each element of the array should be initialized with an asterisk (*). The program should run a loop that does the following: Displays the contents of the board array. Allows player 1 to select a location on the board for an X. The program should ask the user to enter the row...
Game of Tic Tac Toe with the following conditions A point system where a  move that leads...
Game of Tic Tac Toe with the following conditions A point system where a  move that leads to a winning game is given 1 point, a move that leads to a tie is given 0 point, and a  lead to a losing game will get -1 point. Grid size of 5x5 A timer that can be set for how long a game can be played 5 symbols in a row to get a point Connected lines cannot be crossed (No diagonal lines)...
If you were to write a game of tic-tac-toe, you may store the representation of the...
If you were to write a game of tic-tac-toe, you may store the representation of the game board as a two dimensional list such as   [['X', '', 'X'], ['O', 'X', ''], ['', 'O', 'X']] where each sublist is a row in the board.   Empty strings ('') denote a space that does not yet have a value. Assuming this representation, write functions (contained in the same file) that do the following: a) Create a new empty tic-tac-toe board. This function should...
If anyone can please write a code for a 5x5 tic tac toe game in matlab...
If anyone can please write a code for a 5x5 tic tac toe game in matlab I would greatly appreciate it. Its extra credit. PLEASE HELP ME :(
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT