-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathNewTicTacToe
More file actions
126 lines (96 loc) · 3.02 KB
/
NewTicTacToe
File metadata and controls
126 lines (96 loc) · 3.02 KB
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
'''
Tic Tac Toe
-------------------------------------------------------------
'''
import random
class TicTacToe:
def __init__(self):
self.board = []
def create_board(self):
for i in range(3):
row = []
for j in range(3):
row.append('-')
self.board.append(row)
def get_random_first_player(self):
return random.randint(0, 1)
def fix_spot(self, row, col, player):
self.board[row][col] = player
def has_player_won(self, player):
n = len(self.board)
board_values = set()
# check rows
for i in range(n):
for j in range(n):
board_values.add(self.board[i][j])
if board_values == {player}:
return True
else:
board_values.clear()
# check cols
for i in range(n):
for j in range(n):
board_values.add(self.board[j][i])
if board_values == {player}:
return True
else:
board_values.clear()
# check diagonals
for i in range(n):
board_values.add(self.board[i][i])
if board_values == {player}:
return True
else:
board_values.clear()
board_values.add(self.board[0][2])
board_values.add(self.board[1][1])
board_values.add(self.board[2][0])
if board_values == {player}:
return True
else:
return False
def is_board_filled(self):
for row in self.board:
for item in row:
if item == '-':
return False
return True
def swap_player_turn(self, player):
return 'X' if player == 'O' else 'O'
def show_board(self):
for row in self.board:
for item in row:
print(item, end=' ')
print()
def start(self):
self.create_board()
player = 'X' if self.get_random_first_player() == 1 else 'O'
game_over = False
while not game_over:
try:
self.show_board()
print(f'\nPlayer {player} turn')
row, col = list(
map(int, input(
'Enter row & column numbers to fix spot: ').split()))
print()
if col is None:
raise ValueError(
'not enough values to unpack (expected 2, got 1)')
self.fix_spot(row - 1, col - 1, player)
game_over = self.has_player_won(player)
if game_over:
print(f'Player {player} wins the game!')
continue
game_over = self.is_board_filled()
if game_over:
print('Match Draw!')
continue
player = self.swap_player_turn(player)
except ValueError as err:
print(err)
print()
self.show_board()
if __name__ == '__main__':
tic_tac_toe = TicTacToe()
tic_tac_toe.start()