Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect Four: Help Using JQuery in a function

I am new to programming and am trying to make a simple, Html/CSS/Javascript/JQuery Connect Four game. Here is what i have so far.

Only problem is you can't stack tokens on top of each other! This Connect four game sucks ; )!

Inside the dropToken() function, I am trying to create a for loop with an if statement to find if the space I am trying to put the token on is white, or else, go up one tr by using the var i counter in the for loop.

function dropToken(obj, column)
{            
    for (var i == 6; i > 0; i--)
    {
        if ($('table tr:last-child td:nth-child(' + column + ')').css("background-color") == "white")
        {
            $('table tr:last-child td:nth-child(' + column + ')').css("background-color", playerTurn);
        }
    }
    if (playerTurn == "Red")
    {
        playerTurn = "Blue"
        obj.style.backgroundColor = "Blue";   
    }
    else
    {
        playerTurn = "Red"
        obj.style.backgroundColor = "Red"; 
    }
}

However, this code makes the program not work.

like image 739
JoshK Avatar asked Apr 22 '15 00:04

JoshK


1 Answers

Try this

http://jsfiddle.net/f7hpoyfj/1/

You need to use if (element.css("background-color") == "rgba(0, 0, 0, 0)") to compare colors. It may or may not be browser dependant .. not sure yet

Also, see how I created the loop - you did not use i in your previous function which I think is a mistake, as you effectively compared the same element over and over again.

for (var i = 7; i > 1; i--)
{
    var element = $('table tr:nth-child(' + i + ') td:nth-child(' + column + ')');
    if (element.css("background-color") == "rgba(0, 0, 0, 0)" || element.css("background-color") == "transparent" || element.css("background-color") == "white")
    {
        element.css("background-color", playerTurn);
        break;
    }
}
like image 59
philz Avatar answered Nov 09 '22 11:11

philz