-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
277 lines (252 loc) · 7.47 KB
/
game.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import random
import time
game_state = True
draw = False
player_id = 1
opponent_type = ""
player_item_type = {1: "", 2: ""}
board = [
["_", "_", "_"],
["_", "_", "_"],
["_", "_", "_"],
]
winning_states = [
[(0, 0), (0, 1), (0, 2)],
[(1, 0), (1, 1), (1, 2)],
[(2, 0), (2, 1), (2, 2)],
[(0, 0), (1, 0), (2, 0)],
[(0, 1), (1, 1), (2, 1)],
[(0, 2), (1, 2), (2, 2)],
[(0, 0), (1, 1), (2, 2)],
[(0, 2), (1, 1), (2, 0)],
]
def otherPlayer():
if player_id == 1:
return 2
elif player_id == 2:
return 1
else:
return 0
def otherPlayerItem():
if player_item_type[player_id] == "X":
return "O"
elif player_item_type[player_id] == "O":
return "X"
else:
return 0
def printBoard():
for i in board:
for j in i:
print(j, end=" ")
print()
print()
#Returns an integer from -6 (worst case) to 5 (best case)
def getWinningStates(player_id):
count_item = 0
player_winning_states = []
for x in winning_states:
temp = 0
for y in x:
row, col = y
if board[row][col] == player_item_type[player_id]:
temp += 2
elif board[row][col] == "_":
temp += 1
elif board[row][col] == player_item_type[otherPlayer()]:
temp -= 2
if temp > count_item:
count_item = temp
player_winning_states.clear()
player_winning_states.append(x)
elif temp == count_item:
count_item = temp
player_winning_states.append(x)
return count_item, player_winning_states
def userItemSelect():
# Choosing X or O for PLAYER 1
choice = input("Select Item type for player " + str(player_id) + " (X/O): ")
if choice == "X" or choice == "x":
player_item_type[player_id] = "X"
player_item_type[otherPlayer()] = "O"
elif choice == "O" or choice == "o":
player_item_type[player_id] = "O"
player_item_type[otherPlayer()] = "X"
else:
print("Invalid choice! Game will end now.")
game_state = False
quit()
'''
playCountAI = 0
def aiPlayOld():
#First I tried to make the AI play in random slots of the board
#but it was not a good way for the AI to play, so I discarded this logic
#feel free to check it out though
freeSlots = []
for x in range(len(board)):
for y in range(len(board[x])):
if board[x][y] == "_":
freeSlots.append((x,y))
if playCountAI == 0:
row, col = random.choice(freeSlots)
board[row][col] = player_type[player_id]
playCountAI += 1
freeState = []
for x in winning_states:
playerItem = 0
for y in x:
row, col = y
if player_type[1] in board[row][col]:
playerItem += 1
if playerItem == 0:
freeState.append(x)
if len(freeState) != 0:
playStyle = random.choice(freeState)
row, col = random.choice(playStyle)
board[row][col] = player_type[player_id]
playCountAI += 1
'''
def aiPlay():
print("AI (" + player_item_type[player_id] + ") is thinking...")
player_count_item, player_winning_states = getWinningStates(otherPlayer())
ai_count_item, ai_winning_states = getWinningStates(player_id)
freeSlots = []
if ai_count_item >= 5:
# print("AI leading so trying to win")
for x in ai_winning_states:
for y in x:
a, b = y
if board[a][b] == "_":
freeSlots.append(y)
elif player_count_item >= 5:
# print("Player leading so trying to stop them from winning")
for x in player_winning_states:
for y in x:
a, b = y
if board[a][b] == "_":
freeSlots.append((a, b))
else:
for x in ai_winning_states:
for y in x:
a, b = y
if board[a][b] == "_":
freeSlots.append(y)
if len(freeSlots) == 0:
for x in range(len(board)):
for y in range(len(board[x])):
if board[x][y] == "_":
freeSlots.append((x, y))
row, col = random.choice(freeSlots)
board[row][col] = player_item_type[player_id]
time.sleep(1)
printBoard()
def userPlay():
pos = int(input(
"Pos to place " + player_item_type[player_id] + " for player " + str(player_id) + " [0-8]: "))
row, col = 0, 0
if 0 <= pos <= 2:
row = 0
col = pos
elif 3 <= pos <= 5:
row = 1
col = pos - 3
elif 6 <= pos <= 8:
row = 2
col = pos - 6
else:
print("Invalid input. Please try again!")
return 0
if board[row][col] == "_":
board[row][col] = player_item_type[player_id]
else:
print("Invalid position, please try again!")
return 0
printBoard()
#CONSOLE LOG STARTS FROM HERE
printBoard()
print("""1. Play against a player
2. Play against the computer
""")
opponent_choice = int(input("Enter your choice (1/2): "))
print()
if opponent_choice == 1:
opponent_type = "P"
elif opponent_choice == 2:
opponent_type = "C"
else:
print("Invalid choice, game ending now.")
game_state = False
quit()
if opponent_type == "P":
userItemSelect()
elif opponent_type == "C":
player_id = random.randint(1,2)
if player_id == 2:
player_item_type[player_id] = random.choice(["X", "O"])
player_item_type[otherPlayer()] = otherPlayerItem()
print("AI is starting first and has chosen " + player_item_type[player_id])
elif player_id == 1:
userItemSelect()
else:
print("Invalid player id")
game_state = False
quit()
else:
print("Invalid opponent_type")
game_state = False
quit()
# Main game logic
while game_state:
if player_id == 1:
status = userPlay()
if status == 0:
continue
elif player_id == 2:
if opponent_type == "P":
status = userPlay()
if status == 0:
continue
elif opponent_type == "C":
aiPlay()
else:
game_state = False
quit()
else:
print("Invalid player id")
game_state = False
quit()
# checking each time for game win logic
for x in winning_states:
count_x = 0
count_o = 0
for y in x:
a, b = y
if board[a][b] == "X":
count_x += 1
if board[a][b] == "O":
count_o += 1
if count_x == 3 or count_o == 3:
if opponent_type == "C" and player_id == 2:
print("AI", "(" + player_item_type[player_id] + ")", "HAS WON THE GAME!")
else:
print("PLAYER", player_id, "(" + player_item_type[player_id] + ")", "HAS WON THE GAME!")
game_state = False
break
# DRAW condition check game logic
for x in board:
if "_" in x:
draw = False
break
else:
draw = True
if draw:
print("GAME IS A DRAW!")
game_state = False
break
# Switching play chance to other player if the game is not over
if otherPlayer() != 0:
player_id = otherPlayer()
else:
print("Invalid player id")
game_state = False
quit()
print("TicTacToe by Hara <3")