DEV Community

Pure and Simple - Tic Tac Toe with Javascript

Borna Šepić on January 08, 2020

Have you wanted to build something fun and simple to practice your Front End skills but the thought of building another TODO application makes you ...
Collapse
 
cnorman19 profile image
Cameron Norman

Hello Sir, modifying this solution to make it work for a 4x4 tic tac toe game but I am having some trouble getting it to work and I'm not quite understanding why. Any help would be highly appreciated. I will list the steps I have taken in order to accomplish that and maybe you can tell me where I went wrong.

  1. Adding more cells to our board by modifying both the HTML and CSS.
  2. Modifying the win conditions in order to accommodate for the change in board size
for (let i = 0; i <= 15; i++) {
        const winCondition = winningConditions[i];
        let a = gameState[winCondition[0]];
        let b = gameState[winCondition[1]];
        let c = gameState[winCondition[2]];
        let d = gameState[winCondition[3]];

        if (a === '' || b === '' || c === '' || d === '') {
            continue;
        }
        if (a === b && b === c && c === d) {
            roundWon = true;
            break; 
        }
    }
Enter fullscreen mode Exit fullscreen mode
  1. Lastly I modified the gamestate to reflect the additional cells.

Like I said any help would be greatly appreciated! If you would like to look at the full code let me know! Thank you for your time!

Collapse
 
cnorman19 profile image
Cameron Norman

Sorry, realized immediately after posting this that my for-loop should look like this. Got a little confused on what exactly was taking place.

for (let i = 0; i <= 9; i++)

Everything works perfect now. Thank you.

Collapse
 
bornasepic profile image
Borna Šepić

Ah the rubber duck debugging at it's finest :)

Glad you sorted it out!

Collapse
 
jeffmx profile image
jeff-mx

Great code, I'am just starting with JS so I find it very usefull. I add the next lines in order to set a color to every player.

function handleCellPlayed(clickedCell, clickedCellIndex) {
/*
We update our internal game state to reflect the played move,
as well as update the user interface to reflect the played move
*/
gameState[clickedCellIndex] = currentPlayer;
clickedCell.innerHTML = currentPlayer;

    if ( currentPlayer == "X" ) { 
        document.querySelectorAll('.cell')[clickedCellIndex].style.color = "blue";
    }else{
        document.querySelectorAll('.cell')[clickedCellIndex].style.color = "red";
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bornasepic profile image
Borna Šepić

Hey Jeff, that's a great idea!
Always happy to see someone taking the tutorial a step further :)

Collapse
 
pcamellon profile image
Pcamellon

I think it might be better use ===.

Collapse
 
starrysamurai profile image
StarrySamurai

I keep recieving this error- Uncaught TypeError: Cannot set property 'innerHTML' of null. Anyone know how to fix this?

Collapse
 
linehammer profile image
linehammer

In JavaScript almost everything is an object, null and undefined are exception. if a variable has been declared, but has not been assigned a value, is automatically assigned the value undefined . Therefore, if you try to access the value of such variable, it will throw Uncaught TypeError cannot set property ‘0’ of undefined/null .

JavaScript null and undefined is one of the main reasons to produce a runtime errors . This happens because you don’t check the value of unknown return variables before using it. If you are not sure a variable that will always have some value, the best practice is to check the value of variables for null or undefined before using them. The standard way to catch null and undefined simultaneously is this:

if (variable == null) {
// your code here.
}

Because null == undefined is true, the above code will catch both null and undefined.

Also you can write equivalent to more explicit but less concise:

if (variable === undefined variable === null) {
// your code here.
}

This should work for any variable that is either undeclared or declared and explicitly set to null or undefined.

Collapse
 
bornasepic profile image
Borna Šepić

Hey, sorry to hear your having trouble with this tutorial. Could you post your code on codesandbox.io/ or some other similar platform? I'd be more than happy to take a look and help you out

Collapse
 
justkundai profile image
Just-Kundai

Actually having the same error message. Did you guys resolve this?

Thread Thread
 
truepiotrek profile image
truepiotrek

Can you post your repo/code?

Collapse
 
pcamellon profile image
Pcamellon

I think you’re trying to access an undeclared variable. Look for typos!

Collapse
 
truepiotrek profile image
truepiotrek • Edited

And one thing from my side :) When you display winning/draw message you use:

statusDisplay.innerHTML = someMessage();

I think it should be used as:

statusDisplay.innerHTML = someMessage;

If I do it your way IDE tells me it's not of function type which is true since it's a const with a string inside. Apart from that it's great (:

EDIT: I've just noticed that you have functions there... This explains a lot :D

Collapse
 
cukekwe profile image
CUkekwe

For some reason the grid is appearing as a 1x9 column instead of 3x3. I think that it has something to do with the "grid-template-columns" part of the CSS but I'm not entirely sure. I made sure there were no typos in my CSS so I know it isn't that.

Collapse
 
httpsolly profile image
HttpsOlly

I have my styling set to:
display: grid;
width: 90vw;
grid-template-columns: 30vw 30vw 30vw;
grid-template-rows: 30vw 30vw 30vw;
margin: 0 5vw 0 5vw;

This ensures all cells are square. By listing 3 values for both columns and rows, it ensures the grid is 3x3.

If you want the grid to be as wide as the viewport, set the "width" to 100vw and the columns to "auto auto auto" to create 3 columns - the width of the columns will be 1/3 of the viewport. Though you would have to resize the rows also :)

Collapse
 
pcamellon profile image
Pcamellon

In my opinion this could break your design. You can use instead grid-template-columns: 1fr 1fr 1fr

Collapse
 
ledsilva2004 profile image
ledsilva2004

Hello, first of all, thanks for a great tutorial. I wonder if anyone here could help. I am very new to js, and bee trying to resolve the below errors:

Cannot redeclare block-scoped variable 'winningConditions'.ts(2451)

I seem to be getting the error in the below block of code. I dont understand what it entirely means:

const winningConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
function handleResultValidation() {
let roundWon = false;
for (let i = 0; i <= 7; i++) {
const winCondition = winningConditions[i];
let a = gameState[winCondition[0]];
let b = gameState[winCondition[1]];
let c = gameState[winCondition[2]];
if (a === '' || b === '' || c === '') {
continue;
}
if (a === b && b === c) {
roundWon = true;
break
}
}
if (roundWon) {
statusDisplay.innerHTML = winningMessage();
gameActive = false;
return;
}
}

Any feedback would be much appreciated. Thanks

Collapse
 
alikk360 profile image
alikk360

const winningConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];
function handleResultValidation() {
let roundWon = false;
for (let i = 0; i <= 7; i++) {
const winCondition = winningConditions[i];
let a = gameState[winCondition[0]];
let b = gameState[winCondition[1]];
let c = gameState[winCondition[2]];
if (a === '' || b === '' || c === '') {
continue;
}

  if (a === b && b === c) {
            roundWon = true;
            break
Enter fullscreen mode Exit fullscreen mode
    }
}
Enter fullscreen mode Exit fullscreen mode

i don't understand what you do in these steps specially this :

for (let i = 0; i <= 7; i++) {
const winCondition = winningConditions[i];
let a = gameState[winCondition[0]];
let b = gameState[winCondition[1]];
let c = gameState[winCondition[2]];

and this:

if (a === b && b === c) {
roundWon = true;
break

Collapse
 
cforsyth68 profile image
Charles Forsyth • Edited

Wouldn't this be better? (event delegation, so there is only only event listener)

document
  .querySelector(".game--container")
  .addEventListener("click", handleCellClick);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pcamellon profile image
Pcamellon

How would I know the clicked cell?

Collapse
 
baziotabeans profile image
fabioBaziota

amazing, simple, practical and super clean tutorial...

Collapse
 
dhruv21dk profile image
dhruv21dk

const handleCellClick = (elementListener) => {
console.log(elementListener);
const cellClicked = elementListener.target;

   const clickedCellIndex = cellClicked.getAttribute("data-cell-index")
   const idx = parseInt(clickedCellIndex);
   console.log(idx);
   if(gameState[clickedCellIndex]!=''||!gameActive){
     return;
   }
   handleCellPlayed(cellClicked,clickedCellIndex);
   handleResultValidation();
Enter fullscreen mode Exit fullscreen mode

}

//what's wrong in this shitty piece of code

Collapse
 
elav252 profile image
ElAv252

Wow you so helped me with a problem I had.
thanks.

Collapse
 
giftedgeek profile image
Rajesh

What is data-cell-index btw?

Collapse
 
bornasepic profile image
Borna Šepić

The data-cell-index is a custom attribute on an HTML element, you can read more about them here: developer.mozilla.org/en-US/docs/L...

We are using it to more cleanly track the position of the cell that has been clicked and to update the game state array at its position.

Collapse
 
jrubino22 profile image
jrubino22

Hello Borna,
I am about a month into learning JS, so there is a lot of this code I do not understand.
Can you please explain what the purpose of this in the handleResultValidation() function is:

if (a === b && b === c)

Collapse
 
truepiotrek profile image
truepiotrek

Hey there, I hope I can help :)

First you take the winConditions which is the table with smaller tables marking all possible.. well, win conditions :D And with the code you are asking about you are checking if any of them is created using the same symbol (X or O). If those two conditions are met, the game ends with a win.

Collapse
 
kokohranghlu profile image
Koko Hranghlu • Edited

In the handleResultValidation, the a, b and c variables don't change. We could use const instead to declare those variables, so that we don't have to worry when or how the values will change

Collapse
 
yash06112002 profile image
Yash Kansara • Edited

From where handleCellClick function's parameter clickedCellEvent will get value ?

Collapse
 
nivasreddy2400 profile image
HomeLander • Edited

same doubt ,am i missing something here?
edit: its just the e that generally passed to eventhandlers

Collapse
 
adamirenee profile image
Taylor Renee Adami

Hey, I'm having issues getting the code to switch between users. I am able to get the current player to be X, but it won't switch to O

Collapse
 
dantedenzel profile image
Dante Burnett • Edited

Thank you for this blog. I am getting an error statusDisplay is null. Anyone else have that problem?

Edit: I figured it out, had a breakdown in my HTML.