Skip to content
This repository was archived by the owner on May 25, 2022. It is now read-only.

Commit d69bf46

Browse files
authored
Create xo.py
1 parent 1df204b commit d69bf46

File tree

1 file changed

+103
-0
lines changed
  • projects/tic tac toe (xo)

1 file changed

+103
-0
lines changed

projects/tic tac toe (xo)/xo.py

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
def start():
2+
global board
3+
board = [
4+
['','',''],
5+
['','',''],
6+
['','','']
7+
]
8+
9+
def print_board():
10+
print(' ---------')
11+
for row in board:
12+
print(' ',row[0],'|',row[1],'|',row[2])
13+
print(' ---------')
14+
15+
def have_empty_room():
16+
for row in board:
17+
for room in row:
18+
if not room:
19+
return True
20+
return False
21+
22+
def set_room_state(roomxy,state):
23+
x = int(roomxy[0])-1
24+
y = int(roomxy[1])-1
25+
row = board[x]
26+
room = row[y]
27+
if not room:
28+
board[x][y] = state
29+
return True
30+
return False
31+
32+
def check_xy(xy):
33+
xy = str(xy)
34+
if len(xy) != 2:
35+
return False
36+
if int(xy[0]) > 3 or int(xy[0]) < 1 or int(xy[1]) > 3 or int(xy[1]) < 1:
37+
return False
38+
return True
39+
40+
def check_for_win():
41+
if board[0][0] == board[0][1] == board[0][2] != '':
42+
winner = board[0][0]
43+
print(f'{winner} won!')
44+
45+
elif board[1][0] == board[1][1] == board[1][2] != '':
46+
winner = board[1][0]
47+
print(f'{winner} won!')
48+
49+
elif board[2][0] == board[2][1] == board[2][2] != '':
50+
winner = board[2][0]
51+
print(f'{winner} won!')
52+
53+
elif board[0][0] == board[1][0] == board[2][0] != '':
54+
winner = board[0][0]
55+
print(f'{winner} won!')
56+
57+
elif board[0][1] == board[1][1] == board[2][1] != '':
58+
winner = board[0][1]
59+
print(f'{winner} won!')
60+
61+
elif board[0][2] == board[1][2] == board[2][2] != '':
62+
winner = board[0][0]
63+
print(f'{winner} won!')
64+
65+
elif board[0][0] == board[1][1] == board[2][2] != '':
66+
winner = board[0][0]
67+
print(f'{winner} won!')
68+
69+
elif board[0][2] == board[1][1] == board[2][0] != '':
70+
winner = board[0][2]
71+
print(f'{winner} won!')
72+
73+
else:
74+
return False
75+
76+
return True
77+
78+
79+
turn = 'o'
80+
start()
81+
82+
while have_empty_room():
83+
print_board()
84+
print('\n')
85+
if turn == 'o':
86+
turn = 'x'
87+
else:
88+
turn = 'o'
89+
print(f'{turn}\'s Turn!')
90+
while True:
91+
xy = int(input('enter x and y: '))
92+
if check_xy(xy):
93+
if set_room_state(str(xy),turn):
94+
break
95+
print('This room is full!')
96+
continue
97+
print('Error!')
98+
continue
99+
if check_for_win():
100+
break
101+
print_board()
102+
print('Game Over')
103+
input()

0 commit comments

Comments
 (0)