Skip to content

Instantly share code, notes, and snippets.

@julzhk
Created April 17, 2019 14:14
Show Gist options
  • Save julzhk/0120577bd0dac51de099e27a207c3127 to your computer and use it in GitHub Desktop.
Save julzhk/0120577bd0dac51de099e27a207c3127 to your computer and use it in GitHub Desktop.
import pandas as pd
pieces_position_list = ['A_Red', 'B_Yellow', 'A_Red', 'B_Yellow', 'A_Red', 'B_Yellow', 'G_Red', 'B_Yellow']
def check_winner(df, colours = ['Red', 'Yellow']):
for col in df.columns:
series = df[col]
prev, count = '?', 1
for i in series:
if prev == i and i in colours:
count += 1
if count >= 4:
print('winner ', prev, ' row ', series.name)
return prev
else:
prev = i
count = 1
def make_arena(pieces_position_list):
arena = {}
COLUMNS = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
for c in COLUMNS:
arena[c] = []
colours = set()
for move in pieces_position_list:
column, colour = move.split('_')
arena[column].append(colour)
colours.add(colour)
return arena, colours
def make_dataframe(arena):
df = pd.DataFrame.from_dict(arena, orient='index',format='int').T
print('-'*8)
print(df)
return df
def transform_and_check_winners(df, colours):
for df in [df.T, df]:
# print(df)
winner = check_winner(df, colours)
if winner:
return winner
def skew_diagonal(arena, upwards = True):
arena = arena.copy()
no_cols = len(arena)
for i, key in enumerate(arena):
if upwards:
each_column = range(no_cols - i)
else:
each_column = range(i)
for col in each_column:
try:
arena[key] = [0] + arena[key]
except IndexError:
pass
return arena
def who_is_winner(pieces_position_list):
print(pieces_position_list)
print('-'*8)
for upto in range(4,1+len(pieces_position_list)):
print('-'*8)
arena, colours = make_arena(pieces_position_list[:upto])
df = make_dataframe(arena)
winner = transform_and_check_winners(df, colours)
if winner:
return winner
for upwards in [True, False]:
skew_arena = skew_diagonal(arena, upwards)
df = make_dataframe(skew_arena)
winner = transform_and_check_winners(df, colours)
if winner:
return winner
return 'Draw'
r = who_is_winner(pieces_position_list)
print(r)
@julzhk
Copy link
Author

julzhk commented Apr 17, 2019

given a record of moves in a game of connect 4, calculate who won - ie: first to have 4 in a row orthogonally, or diagonally.
The record of moves is (for instance): ['A_Red', 'B_Yellow', 'A_Red', ...

  • where the first character is the column (A-G) followed by the colour (only ever Red or Yellow)

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