0

I'm making a simple tic-tac-toe game but for some reason when trying to create the rules for the game, I can't seem to get anything to work. I have a multidimensional array that has the rules in it but I can't even get one cell to react accordingly. What's wrong with the bottom if statement in my JavaScript pannel? http://jsfiddle.net/Cp4Lu/1/ (This is the if statement I'm referring to)

if (c9.text === 'X') {
alert("You win!");
}
user2449973
  • 123
  • 2
  • 7

2 Answers2

3

You have a couple problems

Uncaught ReferenceError: c9 is not defined 
  • You're using c9 outside of the scope in which it is defined
  • The if (c9... isn't inside any event listener, so it only happens the first time when the JavaScript runs initially
  • jQuery's text is a function, not a property
  • an id in HTML should begin with a letter
Community
  • 1
  • 1
Paul S.
  • 58,277
  • 8
  • 106
  • 120
  • Does that mean I'll have to define my winConditions either in or before my event listener where I define my table cell variables? – user2449973 Jun 08 '13 at 13:20
  • If you want to use the variables in your `document.ready` _function_, you need to have the code that uses them either in the same/child scope, or you need to `var` them differently. – Paul S. Jun 08 '13 at 13:23
  • How would I 'var' them differently? – user2449973 Jun 08 '13 at 13:25
  • write the `var` in a common ancestor scope, then set them in the `document.ready` _function_ without a second `var`. – Paul S. Jun 08 '13 at 13:26
  • If you make that change and start getting `TypeError: Cannot read property 'foobar' of undefined`, then the variable has been `var`d, but not set yet (i.e. you're trying to use it before it's ready) – Paul S. Jun 08 '13 at 13:30
0

Here you go: http://jsfiddle.net/Cp4Lu/4/

I basically put all your code in the $(document).ready and put your conditional within your click event. I believe it now does what you were looking for.

$('td').on('click', function () {
    turnCount += 1;
    setCurrentPlayer();
    $(this).text(currentPlayer);
    console.log(turnCount);
    if (c9.text() === 'X') {
        alert("You win!");
    }
});
Dallas
  • 17,186
  • 21
  • 64
  • 82