-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper_functions.py
111 lines (85 loc) · 2.9 KB
/
helper_functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
from colorama import Fore, Style
def create_initial_game_board():
game_size = int(input("How many rows/columns should the game board have? "))
game_board = []
for i in range(game_size):
row = []
for i in range(game_size):
row.append(0)
game_board.append(row)
return game_board
def show(game_board):
# separator between moves
print("---------------------------------")
# header indicating column numbers
header_row = " "
for i in range(len(game_board)):
header_row += " " + str(i)
print(header_row)
# row numbers and actual game board
for row_index, row in enumerate(game_board):
colored_row = ""
for item in row:
if item == 0:
colored_row += " "
elif item == "X":
colored_row += Fore.GREEN + " X " + Style.RESET_ALL
elif item == "O":
colored_row += Fore.MAGENTA + " O " + Style.RESET_ALL
print(row_index, colored_row)
# empty line for clarity
print("")
return
def make_move(game_board, player):
# game interaction
print(f"Player {player}:")
choice = input("Which position (row, column) do you want to play?: ")
row, column = choice.split(",")
row, column = int(row), int(column)
# making the actual move
if game_board[row][column] != 0:
raise Exception("This position is already taken!")
else:
game_board[row][column] = player
return game_board
def determine_game_status(game_board):
# helper function
def all_the_same(lst):
player = lst[0]
if (lst.count(player) == len(lst)) and player != 0:
return True
else:
return False
# horizontal winner
for row in game_board:
if all_the_same(row):
return "horizontal win"
# vertical winner
for index in range(len(game_board)):
column_elements = []
for row in game_board:
column_elements.append(row[index])
if all_the_same(column_elements):
return "vertical win"
# diagonal winner (\)
diagonal_elements = []
for index in range(len(game_board)):
diagonal_elements.append(game_board[index][index])
if all_the_same(diagonal_elements):
return "diagonal win"
# diagonal winner (/)
diagonal_elements = []
indices = range(len(game_board))
for row, column in zip(indices, reversed(indices)):
diagonal_elements.append(game_board[row][column])
if all_the_same(diagonal_elements):
return "diagonal win"
# draw
free_positions = []
for row in game_board:
for position in row:
if position == 0:
free_positions.append(position)
if len(free_positions) == 0:
return "draw"
return "ongoing"