"Tic Tac Toe using html, javascript and css" Code Answer's

You're definitely familiar with the best coding language Javascript that developers use to develop their projects and they get all their queries like "Tic Tac Toe using html, javascript and css" answered properly. Developers are finding an appropriate answer about Tic Tac Toe using html, javascript and css related to the Javascript coding language. By visiting this online portal developers get answers concerning Javascript codes question like Tic Tac Toe using html, javascript and css. Enter your desired code related query in the search bar and get every piece of information about Javascript code related question on Tic Tac Toe using html, javascript and css. 

Tic Tac Toe using html, javascript and css

By Dull DonkeyDull Donkey on Apr 28, 2021
const player = "O";
const computer = "X";

let board_full = false;
let play_board = ["", "", "", "", "", "", "", "", ""];

const board_container = document.querySelector(".play-area");

const winner_statement = document.getElementById("winner");

check_board_complete = () => {
  let flag = true;
  play_board.forEach(element => {
    if (element != player && element != computer) {
      flag = false;
    }
  });
  board_full = flag;
};

const check_line = (a, b, c) => {
  return (
    play_board[a] == play_board[b] &&
    play_board[b] == play_board[c] &&
    (play_board[a] == player || play_board[a] == computer)
  );
};

const check_match = () => {
  for (i = 0; i < 9; i += 3) {
    if (check_line(i, i + 1, i + 2)) {
      return play_board[i];
    }
  }
  for (i = 0; i < 3; i++) {
    if (check_line(i, i + 3, i + 6)) {
      return play_board[i];
    }
  }
  if (check_line(0, 4, 8)) {
    return play_board[0];
  }
  if (check_line(2, 4, 6)) {
    return play_board[2];
  }
  return "";
};

const check_for_winner = () => {
  let res = check_match()
  if (res == player) {
    winner.innerText = "Winner is player!!";
    winner.classList.add("playerWin");
    board_full = true
  } else if (res == computer) {
    winner.innerText = "Winner is computer";
    winner.classList.add("computerWin");
    board_full = true
  } else if (board_full) {
    winner.innerText = "Draw!";
    winner.classList.add("draw");
  }
};

const render_board = () => {
  board_container.innerHTML = ""
  play_board.forEach((e, i) => {
    board_container.innerHTML += `<div id="block_${i}" class="block" onclick="addPlayerMove(${i})">${play_board[i]}</div>`
    if (e == player || e == computer) {
      document.querySelector(`#block_${i}`).classList.add("occupied");
    }
  });
};

const game_loop = () => {
  render_board();
  check_board_complete();
  check_for_winner();
}

const addPlayerMove = e => {
  if (!board_full && play_board[e] == "") {
    play_board[e] = player;
    game_loop();
    addComputerMove();
  }
};

const addComputerMove = () => {
  if (!board_full) {
    do {
      selected = Math.floor(Math.random() * 9);
    } while (play_board[selected] != "");
    play_board[selected] = computer;
    game_loop();
  }
};

const reset_board = () => {
  play_board = ["", "", "", "", "", "", "", "", ""];
  board_full = false;
  winner.classList.remove("playerWin");
  winner.classList.remove("computerWin");
  winner.classList.remove("draw");
  winner.innerText = "";
  render_board();
};

//initial render
render_board();

Source: dev.to

Add Comment

0

All those coders who are working on the Javascript based application and are stuck on Tic Tac Toe using html, javascript and css can get a collection of related answers to their query. Programmers need to enter their query on Tic Tac Toe using html, javascript and css related to Javascript code and they'll get their ambiguities clear immediately. On our webpage, there are tutorials about Tic Tac Toe using html, javascript and css for the programmers working on Javascript code while coding their module. Coders are also allowed to rectify already present answers of Tic Tac Toe using html, javascript and css while working on the Javascript language code. Developers can add up suggestions if they deem fit any other answer relating to "Tic Tac Toe using html, javascript and css". Visit this developer's friendly online web community, CodeProZone, and get your queries like Tic Tac Toe using html, javascript and css resolved professionally and stay updated to the latest Javascript updates. 

Javascript answers related to "Tic Tac Toe using html, javascript and css"

View All Javascript queries

Javascript queries related to "Tic Tac Toe using html, javascript and css"

Tic Tac Toe using html, javascript and css create tic tac toe game in react using jsx files how to show input value in html using javascript using slice and reduce together in javascript image image using next and previous button in javascript how to write to and read from text files line by line using javascript javascript generate css for html page html string to html Adding and Deleting html Elements vue js error mixed spaces and tabs no-mixed-spaces-and-tabs how to change image source using javascript how to convert an array into an object using javascript add object in array javascript to index using lodash how to reverse a string in javascript without using reverse method using apis in javascript area selection on image using javascript javascript add css file add css in javascript html to pdf javascript reactjs javascript is mobile and desktop convert milliseconds to minutes and seconds javascript javascript and operator javascript get array min and max and operator in javascript hide automatically show and hide javascript how to make a file and write code in it javascript how to make and add to an array in javascript different types ways of export and import in javascript range dual slider with minimum and maximum javascript how do i remove all vowels from a string in javascript and return the result How you can take and use input in Javascript Javascript random number between 0 and 5 display non using Jquery expo has stopped if login using facebook error after login react native expo login using facebook error after login react native how to authenticate token in react using axios how to call api on load using hooks in react how to change style class by using onclick function with multiple buttons in react js how to get property names from object using map method react how to install react fullpage using npm how to load a drop down list in reactjs using json data how to make a github api using react Programmatically navigate using react router react enzyme async using hooks react eznyme fetch api using hooks react must be in scope when using jsx reactjs upload zip using fetch upload image file in react native using rest api to website using firebase with react key value using react-fontawesome using shortid in react lists read file in nodejs using fs how to display data from json api using flutter expansiontile how to send a message using discord.js send a message using discord.js how to change background color using js using dot notation in jsx Queue Events don't trigger with BullMQ using Heroku Redis write confirm dialog box if yes then run function using php using laravel variable inside alpine js line chart using chart.js combining two arrays using spread syntax finding in mongoose using a name angular navigate using component remove one element using splice change nav background color on scroll css without bootstrap how to add css based on route react how to get css property of div after rendering in react js how to import background image in inline css in react vue import css css permit tabs on textarea react how to change an element in a different elements code css normalize css cdn react render html variable read html file node js render html in node js mouse scroll event html how to toggle password visibility in html get element by id html button click move to next page in html dataset html data attribute html change inner html in jquery vs code emmet for html in react convert a string to html element in js https://mongoosejs.com/docs/deprecations.html#findandmodify html bind js file how to make a preloader dissapear in html html get form elements axios response return html not json data heroku get requests return html code in production pdfjs customizing viewer.html js event handler simple search filter for table html how to display current date in html textbox jquery select input value empty and hasclass create react app and tailwind find 401 error and logout axios in react how to identify debug and release build in react native how to import react dom and react how to validate password and confirm password on react form hook props and state react react yup password with number string and uppercase ReactElement Function lacks ending return statement and return type does not include 'undefined'. reactjs and webpack tutorial watchman watch-del-all, and react-native start --reset-cache vue electron name and icon rest api with mongodb and nodejs flutter regular expression for arabic and english characters mongoose find by and delete how to add up all the numbers in between 0 and that number shift and unshift js js eventlistener to add and remove stylings Line 7:13: Expected an assignment or function call and instead saw an expression no-unused-expressions Line 6:3: Expected an assignment or function call and instead saw an expression no-unused-expressions associative array add new key and value js javaScipt diference != and !== JSDOM - getting source location of a node with `nodeLocation(node)` // `parse5` lib helps to serialize and/or parse swal.fire on click back and forth forward tinymce image and links inputs disabled regular expression arabic and persion number between 0 and 5 with decimals regex comparing mongoose ids and strings Resource and asset merger: Duplicate resources When rendering a list what is a key and what is it's purpose? es6 get first and last element of array MongoParseError: URI does not have hostname, domain name and tld hide and show in angular 8 To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. git config username and password passing argument to function handler functional compoent javascript react use javascript library in react node js send javascript javascript queryselectorall math.random javascript javascript onclick href location javascript get last element of array remove attribute javascript Javascript stop setInterval javascript round 2 decimals javascript to integer parse integer javascript javascript convert string to number Javascript write to text file afficher un div qui etait cache en javascript javascript in viewport javascript remove first character from string document ready javascript vanilla how to convert minutes into seconds in javascript how to get all elements with same class in javascript application/x-www-form-urlencoded javascript fetch add 10 seconds to date javascript javascript get random floating number how to remove duplicate array object in javascript Array unique values javascript remove element from array javascript to pascal case javascript javascript multiline string window onload javascript how to check if object is empty javascript document ready javascript math floor javascript null read file javascript javascript check if string is number javascript urlencode json How to get current timestamp in javascript javascript object to json javascript startswith javascript reverse array regex space javascript javascript object entries timestamp to date javascript array length javascript javascript classlist add javascript object destructuring javascript first letter uppercase datetime to date javascript create element javascript foreach object javascript javascript redirection how to use javascript to get full file path default in javascript javascript get stack trace javascript show stack trace javascript style an element javascript convert array to object javascript object to array javascript merge objects Javascript merge two objects javascript replace spaces with nbsp window.open javascript auto close javascript sort array of date string.find javascript math.max in javascript javascript iterate through for loop javascript prototype explained javascript background color check online status javascript how to get nth fibonacci javascript

Browse Other Code Languages

CodeProZone