# Connect4 - Checking for wins.

Page 1 of 1

## 2 Replies - 1541 Views - Last Post: 04 March 2012 - 08:08 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=269354&amp;s=e1bb1ab31d25e2453d68715fa3aac72f&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 KyleRose26

Reputation: 1
• Posts: 28
• Joined: 02-March 12

# Connect4 - Checking for wins.

Posted 04 March 2012 - 06:57 AM

Hey, at the moment I've made a basic connect4 game which works in the sense you can play it and winner can be found.

Basically my game is part of a school project and I was wondering if the way I'm doing is long-winded and theres an esier way which I'm missing or if the way i've done it is ok.

The board acts as a (7,9) array and I at the moment I've basically worked it out in steps, so vertically, horizontally, diagonally. The way i've gone about doing it is by for example horizontally

---
Check (y+1) and (y-1) for same colour piece, if both true check
if either (y+2) or (y-2) are same colour
else check (y+1) only, if colour check (y+2)(y+3)
else check (y-1) only, if colour check (y-2)(y-3)

'Basically when coding this, I get three If statemetns which I then apply a corresponding x or y boundary.
---

The coding for the first part is below, I don't want to post all my coding but just to show you what I'm doing.
```Function checkwin(ByVal x As Integer, ByVal y As Integer) As Boolean

Dim Player As String
If marker = True Then
Player = "Player"
Else
Player = "CPU"
End If

'Horizontal check for win
'THIS IS ONLY THE FIRST LINE of the Pseudo code above.
If (3 <= y And y <= 7) Then
If board(x, (y + 1)).Image.Tag = Player And board(x, (y - 1)).Image.Tag = Player Then
If board(x, (y + 2)).Image.Tag = Player Or board(x, (y - 2)).Image.Tag = Player Then
Return True
End If
End If
End If

```

So basically is the way I'm doing it now effective? I end up with 12 If statements to check all possible wins or is it long winded??
I don't know if there is an algorithm out there which can be used, but basically I wanted to make it as much of my own code as possible, so I'm trying to refrain from looking at other peoples coding for connect4.

Is This A Good Question/Topic? 0

## Replies To: Connect4 - Checking for wins.

### #2 demausdauth

Reputation: 190
• Posts: 692
• Joined: 03-February 10

## Re: Connect4 - Checking for wins.

Posted 04 March 2012 - 04:30 PM

That sounds like you are on the right track.

• MrCupOfT

Reputation: 2294
• Posts: 9,531
• Joined: 29-May 08

## Re: Connect4 - Checking for wins.

Posted 04 March 2012 - 08:08 PM

If you are repesting a lot for similar code.
To me it would suggest breaking that code out it a separate function, and a some form of loop.