Now we need to add our Winner logic. First add the Audio component and two of the freeby sounds: GameOver1.wav and OooScary1.wav.
Select the Left-Click-On-Tile event (#6), Add new Sub-event. We need to cycle through each of the elements in the Winners array. We actually get the length/height of the array from the array itself, and subtract one since our array starts counting at zero, not one.
Open full size image
Before we continue, we need three local variables, to make our logic a bit easier to deal with.
Right-click our new event and Add local variables for: CurrentA, CurrentB, CurrentC
Now we dig into our arrays, cross indexing Winners to CurrentPlay. All we are doing is getting those three indexes into the set that defines the three squares that define a winner. Remember, there are 8 sets of 3.
I’ll explain this:
We get the loopindex, which is 0 to 7, this is our Y index. We’re hard coding the X index to 0, 1, 2. So starting at y=0, we’re just getting:
Winners(0,0,0) which equals 0, & Winners(0,0,1) which equals 0.
These are now our indices into the CurrentPlay Array, that is CurrentPlay(0,0), which is either 0, for no player, 1 for X, 2 for O.
In other words, we are just extracting the three values specified by the Winners array so we can compare them to see if they are all the same (and not blank), which is what we’ll do next.
Add a new sub-event and add the System condition: Compare two values. Compare CurrentA to CurrentB. Add extra conditions to do the same for B & C, and make sure any of those are not zero (blank).
If all those conditions are met, then we have a winner!
Mark the game as done. Set the index of the WinnersMark animation frame to loopindex("y"). Make WinnersMarks visible. Play the GameOver1 sound.
If you run right now, you will see a win is marked, and the game stops working, until you press the Restart button.
Add a new sub-event to see if the winner is X, Else, winner is O.
We just have one more case to deal with – when nobody wins.
Add a new event after (12), check that we aren’t flagged as done yet. Loop through our CurrentPlay array to see if all elements are not blank. We use Add to a local variable to count the non-blank squares. If we count 9 non-zero elements then we’ve got a ‘cats-game’ and nobody wins. Turn on the ‘C’ animation frame, making it visible, and set GameDone=1. Play the GameOver1 and OoScary1 sounds. Set our state text to "No winner".
Open full size image
Download the sample file from the Tutorial Downloads section, to the left: TicTacToe-Part1-B.capx
Check out Part 2
Unlock your full gamedev potential
Upgrade to the Personal Edition of Construct 2, it has way more features and won't holding back from making money and using your full creativity like the free edition does. It's a one off payment and all Construct 2 editor updates are free for life!
Plus, it's got a lot of additional features that will help you save time and make more impressive games!