Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

problem converting a connect4 game diagonal upward win function to diagonal downward win function

Hello, I am creating a connect4 game and struggling to translate my diagonal win upward function into a diagonal win downward function. I know I have to subtract the variables instead of add them but I'm struggling on how exactly to write it. Thank you!

html reference:

<div class="column-1">
            <div class="circle-slot slot5 row6" ></div>
            <div class="circle-slot slot4 row5"></div>
            <div class="circle-slot slot3 row4"></div>
            <div class="circle-slot slot2 row3"></div>
            <div class="circle-slot slot1 row2"></div>
            <div class="circle-slot slot0 row1"></div>
   </div> (this is repeated for 6 columns)

<script>
function diagonalUpWinner() { 
    for(var j=1; j<=6; j++)  {
        for(var i = 1; i<= 4; i++) {
        if($('.column-' + i + '> .row' + j).html()
            && $('.column-' + i + '> .row' + j).html() === $('.column-' + (i + 1 )+ '> .row'+ (j + 1)).html()
            && $('.column-' + i + '> .row'+ j).html() === $('.column-' + (i + 2 )+ '> .row'+ (j + 2)).html()
            && $('.column-' + i + '> .row'+ j).html() === $('.column-' + (i + 3 )+ '> .row'+ (j + 3)).html()) { 
               alert('winner')    

           }    

       }             
   }

}
</script>

1 Answer

Steven Parker
Steven Parker
243,199 Points

For one thing, you're checking non-existing elements. Your loop only needs to go through 9 cycles (the first 3 in both directions):

function diagonalUpWinner() {
  for (var j = 1; j <= 3; j++) {
    for (var i = 1; i <= 3; i++) {

Then, to check the other diagonal, you simply loop through the top 3 rows instead of the bottom 3, and subtract the row offsets instead of adding them:

function diagonalDownWinner() {
  for (var j = 4; j <= 6; j++)
    for (var i = 1; i <= 3; i++)
      if ($(".column-" + i + "> .row" + j).html() &&
          $(".column-" + i + "> .row" + j).html() === $(".column-" + (i + 1) + "> .row" + (j - 1)).html() &&
          $(".column-" + i + "> .row" + j).html() === $(".column-" + (i + 2) + "> .row" + (j - 2)).html() &&
          $(".column-" + i + "> .row" + j).html() === $(".column-" + (i + 3) + "> .row" + (j - 3)).html()  ) {
        alert("winner");
      }
}