# Thread: Need help w/2d array game function

1. ## Need help w/2d array game function

Hello,

I am writing a Connect-4 computer game based on the classic "board game." It is written in C++ as a Console Mode program. For those that don't know, you have a 7x6 "board" filled with empty slots.

000000
000000
000000
000000
000000
000000
000000

It is a 2 player game where each player (let's use symbols 1 and 2 respectively) tries to connect 4 of their markers in a variety of ways. For example:

EXAMPLE 1 EXAMPLE 2 EXAMPLE 3
000000 000000 000000
000000 020000 010020
111100 002000 020020
000000 000200 000020
000000 000020 000020
000000 000000 000000
000000 000000 000000

Get the picture? Pretty simple? My question is: what routine would I write to check if player 1 or 2 is the winner and how would I implement it? I used a "brute force" routine for Tic-Tac-Toe (only 3x3; just took awhile to code), but I don't want this to take quite so much work. Any suggestions?

cpp4ever

2. using a brute force might not be so difficult... but here's an alternative...

scan the board for checkers... if one is encountered, check the adjacency aligned on each of the 8 possible directions... if it goes 'out of bounds' it is not a possible solution... you will get all results, and you will not have to do as many checks...

3. Just remember to check for out of bounds situations. If you are the top of the board (or the first row in the array for 2d array) you would not want to try to check the square above you. This would result in a negative array value. If you tried to check this w/o clamping the value, you would probably crash your computer.

Doubleanti's way is certainly better than hard-coding all the cell combinations. Since the board is so small, checking in a for-next loop would be pretty fast. If you are checking for 1's (black) then if you encounter a 2, you know that you can check the next direction and vice versa. The slowest check time would be when you had a black or red piece surrounded by 3 pieces (in a row) of the other color. This would incur 3 checks on 8 directions (up,up-right,right,down-right,down,down-left,left,up left). But even it would not take long.

4. Also, one trick you can do is to only scan for winning combinations that use the last piece played. In a game like this, the winning combination must include the last piece played (or else you would have won before).

Total, considering that the solution must contain the final piece played, you need to check 16 combinations, less if you're close to an edge. You might be able to use recursion to make it very simple to code.

5. ooh, an even more efficient algo... good job v! right on!!! logik++...