0

I am making a tic-tac-toe game for fun and I am trying to do something a little different.

I am currently trying to check winning combinations by iterating through an array of stored tds that were grabbed with Jquery.

WIN_COMBINATIONS = [$("#square_0, #square_1, #square_2"), 
$("#square_6, #square_7, #square_8"),
$("#square_0, #square_3, #square_6"), 
$("#square_3, #square_4, #square_5"), 
$("#square_1, #square_4, #square_7"),
$("#square_2, #square_5, #square_8"), 
$("#square_0, #square_4, #square_8"), $("#square_6, #square_4, #square_2")]

So, basically, WIN_COMBINATIONS[0] is a winning combo. What is the best way to iterate through, and actually check the .html of the Jquery object?

Basically, I would like to do something like this

if (WIN_COMBINATIONS[0].html = "X", "X", "X") {
        //do something here
}

Thanks for your help!

3
  • The X might belong to different players Commented Jun 27, 2018 at 20:16
  • Well, there are only two players, and if all the spots are filled with an "X", the game will stop and declare a winner. That is what I am after. Just a simple game of tic tac toe :D Commented Jun 27, 2018 at 20:19
  • you will need to do a "Deep Equals" of each item in the array... Looking now Commented Jun 27, 2018 at 20:22

2 Answers 2

2
WIN_COMBINATIONS.forEach(function(combination){
    if(combination.map(function(){return $(this).text()}).toArray().join("") == "XXX") { 
        console.log("winning combination")   
    } 
})   
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant Answer! This is exactly what I was looking for! Thanks Juvian
0

if ES6 (ES2015) is OK than you can try reduce to find match

!!array.reduce(function(a, b){ return (a === b) ? a : NaN; });

Results:

var array = ["a", "a", "a"] => result: "true"
var array = ["a", "b", "a"] => result: "false"
var array = ["false", ""] => result: "false"
var array = ["false", false] => result: "false"
var array = ["false", "false"] => result: "true"
var array = [NaN, NaN] => result: "false" 

Warning: var array = [] => result: TypeError thrown

All credit to: Lightness Races in Orbit

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.