Skip to content

Instantly share code, notes, and snippets.

@brendanberg
Created March 10, 2012 00:06
Show Gist options
  • Save brendanberg/2009408 to your computer and use it in GitHub Desktop.
Save brendanberg/2009408 to your computer and use it in GitHub Desktop.
Connect4 winner detection
import sys
import json
def search_line(row):
string = ''.join(row)
if string.find('OOOO') != -1:
return 'O'
if string.find('XXXX') != -1:
return 'X'
else:
return None
def detect(board):
for row in board:
winner = search_line(row)
if winner:
return winner
for col in zip(*board[::1]):
winner = search_line(col)
if winner:
return winner
for dia in diagonals(board):
winner = search_line(dia)
if winner:
return winner
return None
def diagonals(board):
"Return lists of diagonals."
height = len(board)
width = len(board[0])
# NW <-> SE diagonals
diags = []
for i, row in enumerate(board):
diags.append(row[i:])
# SW <-> NE diagonals
for i, row in enumerate(board):
diags.append(["."] * i + row)
return zip(*diags[::1])
if __name__ == '__main__':
board = json.load(sys.stdin)
winner = detect(board)
if winner:
print 'Winner: {0}'.format(winner)
else:
print 'No winner'
@brendanberg
Copy link
Author

[
  [".", ".", ".", ".", ".", ".", "."],
  [".", ".", ".", ".", ".", ".", "."],
  [".", ".", "O", ".", ".", ".", "."],
  [".", ".", "X", "O", "X", "X", "."],
  [".", ".", "X", "X", "O", "O", "X"],
  [".", ".", "O", "X", "X", "O", "X"]
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment