Reputation: 1
I am trying to build a tic tac toe game but it is not working, what I mean by that is when I click the gameboard, I want the game to start and have my functions accordingly. Now the problem is I want this game to be human vs machine and the machine part(function AI()) is not working properly.
Here's the link codepen
I have all my functions in the "game" function(game ()) which should run when a user clicks on the game-board which is at the end of the js file.
Just try to play the game and you'll understand what I am talking about--weird behaviour and I am scratching my eyes out and still I'm stuck.
I would really appreciate it if anyone could help me. Thanks.
function game(){
symbDisp();
winCheck();
turns += 1;
if (gameEnd == false && turns % 2 == 0) {
AI();
winCheck();
turns += 1;
}
}
Upvotes: 0
Views: 190
Reputation: 6562
First symbDisp is receiving window
as this
instead of the correct td
.
change line 10 to
$('.square').on('click', function() { game(this) } );
because of the change you have to pass this
to the subfunctions. So make the following changes:
124: function game(ths){
125:
126: symbDisp(ths);
and then change symbDisp to:
function symbDisp (ths) {
if($(ths).text()==='') {
$(ths).text(pTurn);
if(pTurn == player){
pTurn =comp;
}else{
pTurn=player;
}
}
}
There is another error: pTurn is undefined when it first reaches symbDisp function. So change userIcon to:
function userIcon() {
if($(this).attr("id")=="x"){
player = pTurn ="X";
comp ="O";
} else if($(this).attr("id")=="o"){
player = pTurn ="O";
comp ="X";
}
$('#user').fadeOut(1000);
}
see that I setted pTurn when player is setted.
That's it. It should work now. I forked a working version here:
http://codepen.io/anon/pen/oxPyej
Hope it helps
Upvotes: 0
Reputation: 3274
AI() function works (more or less). It's actually only the AI that's playing the game. Player moves don't work because you don't tell the symbDisp() function which square was clicked ('this' refers to the document, not the squares)
You could change the eventhandler to form
$('.square').on('click', function() {
game($(this));
});
Inside this anonymous function this refers to the square, as that's the element the event handler was bound to.
Now you also need to pass this square element around a bit by changing your game() and symbDisp() functions to take the element as their arguments and and using that inside symbDisp().
for example:
function game(elem){
symbDisp(elem);
//more stuff
function symbDisp(elem) {
if(elem.text()==='') {
//more stuff
There's also other bugs in your game but I'll leave those for you to tackle.
Upvotes: 1