TIc Tac Toe AI Not Working

Hi everyone, I got my Tic Tac Toe project mostly done, but I wanted to use the MinMax AI, so I followed along with a youtube tutorial :https://www.youtube.com/watch?v=x_Je9i3aKNk

Somehow, it doesn’t seem to work for me, and I’m still learning how to debug. Could anyone please help me out? Or at least point me in the right direction? My code is here:
The error I get is “Uncaught TypeError: Cannot read property ‘cost’ of undefined”.

Thank you!

The console shows you that the else block of code is the problem:

           return max.cost;

A few lines above this code, you will see:

        var max = _.maxBy(values, (v) => {
          return v.cost;

When I click to put my first “X” on the board, max is assigned the result of the call to _.maxBy. The variable values is passed in along with an anonymous function to _.maxBy.

If you were to put console.log(values); on the line before the declaration and assignment of max, you will see that values is an empty array, so max returns undefined.

Finally, we get the line (at the top of this post) which attempts to return max.cost; You are getting the ““Uncaught TypeError: Cannot read property ‘cost’ of undefined”” error because undefined is not an object, so it has no property called “cost”.

You need to make use of console.log to understand what the values are for specific variables while trying to debug your code. You have more debugging to do in order to figure out why values is empty.

Just keep working at it and you will eventually figure out. :smiley:

1 Like

Thank you Randell for the thorough explanation. It took me a while but I finally got it working :slight_smile: