RollerGirlatHeart
RollerGirlatHeart

Reputation: 31

Python Connect four Diagonal Checking

I'm having issue getting my code started. I have a Connect 4 project for my programming class and I'm having a really stupid issue. I don't understand the diagonal checking. He gave us an example but I honestly don't get it.

def CheckForWinner(board, playerName, playerChar):


diagonal = board[2][0] + board[3][1] + board[4][2] + board[5][3]
if playerChar * 4 in diagonal:
    return playerName

It is a 42 space board(7x6)

 1 2 3 4 5 6 7 
 _ _ _ _ _ _ _ 
|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|

I'm just having difficulties under standing what it is checking. I'm not asking for you to give me the code. Just an explanation please. :)

Upvotes: 1

Views: 2390

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 113998

1 2 3 4 5 6 7 
 _ _ _ _ _ _ _ 
|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|
|_|_|_|_|W|_|_|
|_|_|_|Z|_|_|_|
|_|_|Y|_|_|_|_|
|_|X|_|_|_|_|_|

x = 2,0
y = 3,1
z = 4,2
w = 5,3

it is probably using 1 for player 1 and 2 for player 2 so the board would look like this as an array (note that the array is probably (row) inverted from the displayed grid.)

player = 2
the_board = [[0,0,2,0,0,0,0],  
             [0,0,0,2,0,0,0],
             [0,0,0,0,2,0,0],
             [0,0,0,0,0,2,0],
             [0,0,0,0,0,0,0],
             [0,0,0,0,0,0,0]]
print the_board[2][0]  #2
diagonal = the_board[2][0] + the_board[3][1] + the_board[4][2] + the_board[5][3] # 2+2+2+2 = 8
player * 4  == diagonal # 2*4 =?= 2+2+2+2

Upvotes: 1

Ben
Ben

Reputation: 6767

It's building a string up of the characters stored in a diagonal. For example, if the board is:

 1 2 3 4 5 6 7 
 _ _ _ _ _ _ _ 
|_|A|_|_|_|_|_|
|_|_|B|_|_|_|_|
|_|_|_|C|_|_|_|
|_|_|_|_|D|_|_|
|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|

Then the following line:

diagonal = board[2][0] + board[3][1] + board[4][2] + board[5][3]

will assign the value ABCD to the variable diagonal, because it's concatenating the characters in board[2][0] (A), board[3][1] (B), etc... into one string: ABCD.

The if statement makes up a 4-character string of the player's character, and checks if it is in the diagonal string. If the player's character is X, for example, then the if evaluates to checking if XXXX is in ABCD. It will then return the player's name if this is True, which means they've won.

(Of course, the actual location of the A, B, C and D in my example depends on what way round the list of lists is representing the board)

Upvotes: 3

Related Questions