-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
119 lines (89 loc) · 2.89 KB
/
app.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
112
113
114
115
116
117
118
119
board = ['-', '-', '-', '-', '-', '-', '-', '-', '-']
def play():
game_is_still_on = True
current_player = 'X'
while game_is_still_on:
displayboard()
print(f"{current_player}'s turn")
getinput(current_player)
winner = check_winner()
if not winner:
current_player = switchplayer(current_player)
else:
displayboard()
if winner == 'Tie':
print("It's a tie!")
else:
print(f"{winner} won!")
continue_to_play = input("Do you want to start another game (y/n): ")
if continue_to_play.lower() == 'y':
global board
board = ['-', '-', '-', '-', '-', '-', '-', '-', '-']
play()
else:
game_is_still_on = False
def displayboard():
print(f"""
{board[0]} | {board[1]} | {board[2]}
{board[3]} | {board[4]} | {board[5]}
{board[6]} | {board[7]} | {board[8]}
""")
def getinput(current_player):
choice = input("Select a position from 1-9: ")
while True:
if choice:
if choice.isdigit():
if choice in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
if board[int(choice) - 1] == '-':
board[int(choice) - 1] = current_player
break
else:
print("That position is already occupied!")
else:
print("You can only select position between 1-9!")
else:
print("Your selection was invalid!")
choice = input("Select a position from 1-9: ")
else:
print("You did not select a position!")
choice = input("Select a position from 1-9: ")
def check_winner():
global game_is_still_on
winner = None
if not winner:
winner = check_row()
if not winner:
winner = check_column()
if not winner:
winner = check_diagonal()
if not winner:
winner = check_tie()
return winner
def check_row():
if board[0] == board[1] == board[2] != '-':
return board[0]
elif board[3] == board[4] == board[5] != '-':
return board[3]
elif board[6] == board[7] == board[8] != '-':
return board[6]
def check_column():
if board[0] == board[3] == board[6] != '-':
return board[0]
elif board[1] == board[4] == board[7] != '-':
return board[1]
elif board[2] == board[5] == board[8] != '-':
return board[2]
def check_diagonal():
if board[0] == board[4] == board[8] != '-':
return board[0]
elif board[2] == board[4] == board[6] != '-':
return board[2]
def check_tie():
if '-' not in board:
return 'Tie'
def switchplayer(current_player):
if current_player == 'X':
return 'O'
else:
return 'X'
play()