Source

scripts / python / connect4.py

The default branch has multiple heads

Full commit
#!/usr/bin/env python

from __future__ import print_function
import sys

def char_check(row, col, char, prev_row=0, prev_col=0, count=0, direction=0):
    direction_dict = {1: None,
                      2: None,
                      3: None,
                      4: lambda: char_check(row, col - 1, char, row, col, count + 1, 4),
                      5: None,
                      6: lambda: char_check(row, col + 1, char, row, col, count + 1, 6),
                      7: lambda: char_check(row + 1, col - 1, char, row, col, count + 1, 7),
                      8: lambda: char_check(row + 1, col, char, row, col, count + 1, 8),
                      9: lambda: char_check(row + 1, col + 1, char, row, col, count + 1, 9)}

    if count == 3:
        print("Winner: %s" % char)
        sys.exit(0)

    direction_list = []
    direction_list_append = direction_list.append

    try:
        if (four_list[row][col - 1] == char and 
            (row != prev_row or (col - 1) != prev_col) and 
            direction in (0,4)): 
            direction_list_append(4)
        elif (four_list[row][col + 1] == char and 
              (row != prev_row or (col + 1) != prev_col) and
              direction in (0,6)):
              direction_list_append(6)
        elif (four_list[row + 1][col - 1] == char and 
              ((row + 1) != prev_row or (col - 1) != prev_col) and
              direction in (0,7)):
              direction_list_append(7)
        elif (four_list[row + 1][col] == char and
              ((row + 1) != prev_row or col != prev_col) and
              direction in (0,8)):
              direction_list_append(8)
        elif (four_list[row + 1][col + 1] == char and
              ((row + 1) != prev_row or (col + 1) != prev_col) and
              direction in (0,9)):
              direction_list_append(9)

        for d in direction_list:
            direction_dict[d]()

    except IndexError:
        pass

if __name__ == "__main__":
    try:
        four_list = eval(sys.stdin.read())
    except SyntaxError:
        print("Error getting list from the web, using preprogrammed backup.")
        four_list = [
                        [".", ".", ".", ".", ".", ".", "."],
                        [".", ".", ".", ".", ".", ".", "."],
                        [".", ".", "O", ".", ".", ".", "."],
                        [".", ".", "X", "O", "X", "X", "."],
                        [".", ".", "X", "X", "O", "O", "X"],
                        [".", ".", "O", "X", "X", "O", "X"]
                    ]
    finally:
        for r,_ in enumerate(four_list):
            [char_check(r, c, four_list[r][c]) for c,_ in enumerate(four_list[r]) if four_list[r][c] != "."]

        print("No Winner")