forked from erikackermann/Connect-Four
/
connect4.py
357 lines (296 loc) · 11.8 KB
/
connect4.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# Python Final Project
# Connect Four
#
# Erik Ackermann
# Charlene Wang
#
# Connect 4 Module
# February 27, 2012
import random
import os
import time
from minimax import Minimax
class Game(object):
""" Game object that holds state of Connect 4 board and game values
"""
board = None
round = None
finished = None
winner = None
turn = None
players = [None, None]
game_name = u"Connecter Quatre\u2122" # U+2122 is "tm" this is a joke
colors = ["x", "o"]
def __init__(self):
self.round = 1
self.finished = False
self.winner = None
# do cross-platform clear screen
os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )
print(u"Welcome to {0}!".format(self.game_name))
print("Should Player 1 be a Human or a Computer?")
while self.players[0] == None:
choice = str(raw_input("Type 'H' or 'C': "))
if choice == "Human" or choice.lower() == "h":
name = str(raw_input("What is Player 1's name? "))
self.players[0] = Player(name, self.colors[0])
elif choice == "Computer" or choice.lower() == "c":
name = str(raw_input("What is Player 1's name? "))
diff = int(raw_input("Enter difficulty for this AI (1 - 4) "))
self.players[0] = AIPlayer(name, self.colors[0], diff+1)
else:
print("Invalid choice, please try again")
print("{0} will be {1}".format(self.players[0].name, self.colors[0]))
print("Should Player 2 be a Human or a Computer?")
while self.players[1] == None:
choice = str(raw_input("Type 'H' or 'C': "))
if choice == "Human" or choice.lower() == "h":
name = str(raw_input("What is Player 2's name? "))
self.players[1] = Player(name, self.colors[1])
elif choice == "Computer" or choice.lower() == "c":
name = str(raw_input("What is Player 2's name? "))
diff = int(raw_input("Enter difficulty for this AI (1 - 4) "))
self.players[1] = AIPlayer(name, self.colors[1], diff+1)
else:
print("Invalid choice, please try again")
print("{0} will be {1}".format(self.players[1].name, self.colors[1]))
# x always goes first (arbitrary choice on my part)
self.turn = self.players[0]
self.board = []
for i in xrange(6):
self.board.append([])
for j in xrange(7):
self.board[i].append(' ')
def newGame(self):
""" Function to reset the game, but not the names or colors
"""
self.round = 1
self.finished = False
self.winner = None
# x always goes first (arbitrary choice on my part)
self.turn = self.players[0]
self.board = []
for i in xrange(6):
self.board.append([])
for j in xrange(7):
self.board[i].append(' ')
def switchTurn(self):
if self.turn == self.players[0]:
self.turn = self.players[1]
else:
self.turn = self.players[0]
# increment the round
self.round += 1
def nextMove(self):
player = self.turn
# there are only 42 legal places for pieces on the board
# exactly one piece is added to the board each turn
if self.round > 42:
self.finished = True
# this would be a stalemate :(
return
# move is the column that player want's to play
move = player.move(self.board)
for i in xrange(6):
if self.board[i][move] == ' ':
self.board[i][move] = player.color
self.switchTurn()
self.checkForFours()
self.printState()
return
# if we get here, then the column is full
print("Invalid move (column is full)")
return
def checkForFours(self):
# for each piece in the board...
for i in xrange(6):
for j in xrange(7):
if self.board[i][j] != ' ':
# check if a vertical four-in-a-row starts at (i, j)
if self.verticalCheck(i, j):
self.finished = True
return
# check if a horizontal four-in-a-row starts at (i, j)
if self.horizontalCheck(i, j):
self.finished = True
return
# check if a diagonal (either way) four-in-a-row starts at (i, j)
# also, get the slope of the four if there is one
diag_fours, slope = self.diagonalCheck(i, j)
if diag_fours:
print(slope)
self.finished = True
return
def verticalCheck(self, row, col):
#print("checking vert")
fourInARow = False
consecutiveCount = 0
for i in xrange(row, 6):
if self.board[i][col].lower() == self.board[row][col].lower():
consecutiveCount += 1
else:
break
if consecutiveCount >= 4:
fourInARow = True
if self.players[0].color.lower() == self.board[row][col].lower():
self.winner = self.players[0]
else:
self.winner = self.players[1]
return fourInARow
def horizontalCheck(self, row, col):
fourInARow = False
consecutiveCount = 0
for j in xrange(col, 7):
if self.board[row][j].lower() == self.board[row][col].lower():
consecutiveCount += 1
else:
break
if consecutiveCount >= 4:
fourInARow = True
if self.players[0].color.lower() == self.board[row][col].lower():
self.winner = self.players[0]
else:
self.winner = self.players[1]
return fourInARow
def diagonalCheck(self, row, col):
fourInARow = False
count = 0
slope = None
# check for diagonals with positive slope
consecutiveCount = 0
j = col
for i in xrange(row, 6):
if j > 6:
break
elif self.board[i][j].lower() == self.board[row][col].lower():
consecutiveCount += 1
else:
break
j += 1 # increment column when row is incremented
if consecutiveCount >= 4:
count += 1
slope = 'positive'
if self.players[0].color.lower() == self.board[row][col].lower():
self.winner = self.players[0]
else:
self.winner = self.players[1]
# check for diagonals with negative slope
consecutiveCount = 0
j = col
for i in xrange(row, -1, -1):
if j > 6:
break
elif self.board[i][j].lower() == self.board[row][col].lower():
consecutiveCount += 1
else:
break
j += 1 # increment column when row is decremented
if consecutiveCount >= 4:
count += 1
slope = 'negative'
if self.players[0].color.lower() == self.board[row][col].lower():
self.winner = self.players[0]
else:
self.winner = self.players[1]
if count > 0:
fourInARow = True
if count == 2:
slope = 'both'
return fourInARow, slope
def findFours(self):
""" Finds start i,j of four-in-a-row
Calls highlightFours
"""
for i in xrange(6):
for j in xrange(7):
if self.board[i][j] != ' ':
# check if a vertical four-in-a-row starts at (i, j)
if self.verticalCheck(i, j):
self.highlightFour(i, j, 'vertical')
# check if a horizontal four-in-a-row starts at (i, j)
if self.horizontalCheck(i, j):
self.highlightFour(i, j, 'horizontal')
# check if a diagonal (either way) four-in-a-row starts at (i, j)
# also, get the slope of the four if there is one
diag_fours, slope = self.diagonalCheck(i, j)
if diag_fours:
self.highlightFour(i, j, 'diagonal', slope)
def highlightFour(self, row, col, direction, slope=None):
""" This function enunciates four-in-a-rows by capitalizing
the character for those pieces on the board
"""
if direction == 'vertical':
for i in xrange(4):
self.board[row+i][col] = self.board[row+i][col].upper()
elif direction == 'horizontal':
for i in xrange(4):
self.board[row][col+i] = self.board[row][col+i].upper()
elif direction == 'diagonal':
if slope == 'positive' or slope == 'both':
for i in xrange(4):
self.board[row+i][col+i] = self.board[row+i][col+i].upper()
elif slope == 'negative' or slope == 'both':
for i in xrange(4):
self.board[row-i][col+i] = self.board[row-i][col+i].upper()
else:
print("Error - Cannot enunciate four-of-a-kind")
def printState(self):
# cross-platform clear screen
os.system( [ 'clear', 'cls' ][ os.name == 'nt' ] )
print(u"{0}!".format(self.game_name))
print("Round: " + str(self.round))
for i in xrange(5, -1, -1):
print("\t"),
for j in xrange(7):
print("| " + str(self.board[i][j])),
print("|")
print("\t _ _ _ _ _ _ _ ")
print("\t 1 2 3 4 5 6 7 ")
if self.finished:
print("Game Over!")
if self.winner != None:
print(str(self.winner.name) + " is the winner")
else:
print("Game was a draw")
class Player(object):
""" Player object. This class is for human players.
"""
type = None # possible types are "Human" and "AI"
name = None
color = None
def __init__(self, name, color):
self.type = "Human"
self.name = name
self.color = color
def move(self, state):
print("{0}'s turn. {0} is {1}".format(self.name, self.color))
column = None
while column == None:
try:
choice = int(raw_input("Enter a move (by column number): ")) - 1
except ValueError:
choice = None
if 0 <= choice <= 6:
column = choice
else:
print("Invalid choice, try again")
return column
class AIPlayer(Player):
""" AIPlayer object that extends Player
The AI algorithm is minimax, the difficulty parameter is the depth to which
the search tree is expanded.
"""
difficulty = None
def __init__(self, name, color, difficulty=5):
self.type = "AI"
self.name = name
self.color = color
self.difficulty = difficulty
def move(self, state):
print("{0}'s turn. {0} is {1}".format(self.name, self.color))
# sleeping for about 1 second makes it looks like he's thinking
#time.sleep(random.randrange(8, 17, 1)/10.0)
#return random.randint(0, 6)
m = Minimax(state)
best_move, value = m.bestMove(self.difficulty, state, self.color)
return best_move