Tic Tac Toe: Problem switching players between user and computer

Tic Tac Toe: Problem switching players between user and computer
0.0 0


Project Link - https://codepen.io/zapbampow/pen/NwbOpO

I’ve run into an issue I haven’t been able to get around. If you go to my project and click through the options One Player -> Second Player -> Easy, the computer will take a turn. All the variables will change in order for the user to play, but then the user cannot play. If you choose First Player -> Easy the user can play continuously and the computer never takes a turn. I am 90% sure the issue is in the following function.

function easyOnePlayerGame() {
  console.log("easyOnePlayerGame called.");
  if (currentPlayerName === 'Computer') {
  else {

If I change the if…else to a while-loop, the computer takes a turn, then the user can play continuously without the computer being able to take another turn.

In psuedocode what I want to happen is this

if currentPlayerName is "Computer"
   Computer takes a turn;
   the user takes a turn;

I guess I’m just missing something for prompting the code to run the if-statement again. If I try to make the function recursive, it gets stuck in and infinite loop.

Any suggestions? I’m sure I’m missing something obvious.


You need to call the function. It only fires once, and it will always be Computers turn.
As I understand, you want it to be a sort of check in the background to see who currentPlayer is and then enable or disable the move.
I got it working like it should, when I just make the check after every second. Game works great.

setInterval(() => {
}, 1000)

But this is kind hacky, I think. Better would be to make a switch at some point. For example:

else if (liveBoard.includes(null) == true) {
    console.log("No winner yet! Keep playing");

And again, the game works.



Thanks. I also eventually hacked a semi-solution that kind of worked. But both of your suggests are better, I think. I appreciate the help.