-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgomoku.py
198 lines (169 loc) · 7.87 KB
/
gomoku.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
import random
import os
import sys
import pickle
import time
from gameState import *
from agents import *
from util import *
class Game:
def __init__(self):
self.agents = []
self.moveHistory = []
# Runs a full game until completion
# Returns a map of statistics, where the keys are:
# numMoves (int) - the number of moves played by all players
# avgMoveTime (float) - average time in seconds per move for each player
def runGames(self, gridSize, nInARow, numComputerAgents, numHumanAgents, verboseFlag):
#Collect statistics on the game
stats = {}
numberOfMoves = 0
self.state = GameState(nInARow, gridSize, numComputerAgents + numHumanAgents)
if verboseFlag:
print self.state
agentIndex = 0
agentTimeTaken = {}
while not self.state.gameEnded():
# Set agent time taken to 0 if this is the first move
if not agentIndex in agentTimeTaken:
agentTimeTaken[agentIndex] = 0
turnStartTime = time.clock()
agent = self.agents[agentIndex]
action = agent.getAction(self.state)
self.moveHistory.append((agentIndex, action))
numberOfMoves += 1
turnEndTime = time.clock()
print self.state.positionToFeatures
print "-----------------"
successorState = self.state.generateSuccessor(agentIndex, action)
oldState = self.state
self.state = successorState
print successorState.positionToFeatures
print "-----------------"
print oldState.positionToFeatures
print "======================"
if verboseFlag:
print self.state
agentTimeTaken[agentIndex] += turnEndTime - turnStartTime
agentIndex = (agentIndex + 1) % len(self.agents)
print "Game has ended!"
if self.state.getWinner() == -1:
print "The game was a tie."
else:
print "Player " + str(self.state.getWinner()) + " won the game!"
numberOfMovesPerPlayer = numberOfMoves / len(self.agents) #Integer truncation
lastPlayer = numberOfMoves % len(self.agents)
def oneMoreMove(agentIndex, lastPlayer): #Add the last move if the player did move. Needed for average time
if agentIndex <= lastPlayer:
return 1
return 0
stats["winner"] = self.state.getWinner()
stats["numMoves"] = numberOfMoves
stats["avgMoveTime"] = dict((agent, agentTimeTaken[agent]/(numberOfMovesPerPlayer + oneMoreMove(agent, lastPlayer))) for agent in agentTimeTaken)
# stats["moveHistory"] = self.moveHistory
return stats
# Repl is a read, evaluate, print loop
# Parses the args entered in the command line to set up the game
# Ex: python gomoku.py 5 3 1 1
# ============================================
# Arguments (in order):
# ============================================
# gridSize - Int representing the NxX dimension of the board (default: 5)
# nInARow - Int representing the number of pieces in a row to win (default: 5)
# numComputerAgents - Number of AI agents the user will play against (default: 1)
# numHumanAgents - Number of human players in this game (default: 1)
# numGames - Number of games to play
# verboseFlag - Print boards for each turn and other turn data. "verbose" will turn this on (default: False)
# agentTypes - a string of structure 'mrmm', where each letter defines the AI agent type. m - Minimax. r - random
def repl(self, args):
#Defaults
numArgs = 7
gridSize = 19
nInARow = 5
numComputerAgents = 1
numHumanAgents = 1
numberOfGames = 1
verbose = False
argumentsString = '''
============================================
Arguments (in order):
============================================
gridSize - Int representing the NxX dimension of the board (default: 5)
nInARow - Int representing the number of pieces in a row to win (default: 5)
numComputerAgents - Number of AI agents the user will play against (default: 1)
numHumanAgents - Number of human players in this game (default: 1)
numGames - Number of games to play
verboseFlag - Print boards for each turn and other turn data. "verbose" will turn this on (default: False)
agentTypes - a string of structure 'mrmm', where each letter defines the AI agent type. m - Minimax. r - random
'''
#Parse arguments
if len(args) > numArgs:
print "\nDid not enter valid arguments!"
print argumentsString
return
if len(args) > 5:
if args[5] == "verbose" or args[5] == "v" or args[5] == "Verbose":
verbose = True
if len(args) > 4 and isInt(args[4]):
numberOfGames = int(args[4])
if len(args) > 3 and isInt(args[3]):
numHumanAgents = int(args[3])
if len(args) > 2 and isInt(args[2]):
numComputerAgents = int(args[2])
if len(args) > 1 and isInt(args[1]):
nInARow = int(args[1])
if len(args) >= 1 and isInt(args[0]):
gridSize = int(args[0])
#Setup Human agents
for i in range(numHumanAgents):
human = HumanAgent(len(self.agents))
self.agents.append(human)
if len(args) > 6: #Parse what kind of computer agents
print "Agent args:", args[6], len(args[6])
if numComputerAgents != len(args[6]):
print "\nDid not enter valid arguments!"
print argumentsString
return
for i in range(numComputerAgents):
queryString = args[6]
agentType = None
if queryString[i] == "m":
agentType = MinimaxAgent(len(self.agents), verbose)
elif queryString[i] == "r":
agentType = RandomAgent(len(self.agents), verbose)
elif queryString[i] == "h":
agentType = MinimaxAgent(len(self.agents), verbose, depth = 3, hardCodedWeights = True)
else:
print "\nDid not enter valid arguments! Invalid agent types"
print argumentsString
return
self.agents.append(agentType)
else: #Setup computer agents (default)
for j in range(numComputerAgents):
computer = MinimaxAgent(len(self.agents), verbose)
print computer.index
self.agents.append(computer)
print('Welcome to our Gomoku game for CS221')
print "Grid Size: " + str(gridSize)
print "N in a row: " + str(nInARow)
print "Computers: " + str(numComputerAgents)
print "Humans: " + str(numHumanAgents) + "\n"
wins = {agent: 0 for agent in range(numComputerAgents + numHumanAgents)}
wins[-1] = 0 #Keep track of ties
wins = {i:0 for i in range(numHumanAgents + numComputerAgents)}
for i in range(numberOfGames):
print 'Game ' + str(i + 1)
stats = self.runGames(gridSize, nInARow, numComputerAgents, numHumanAgents, verbose)
wins[stats['winner']] += 1
resultMessage = ''
for index in wins:
resultMessage += str(index) + ': ' + str(wins[index]) + ', '
# Final Statistics
print "================= Final statistics ==================="
print "Number of games: " + str(numberOfGames)
print "Wins For Each Player: " + resultMessage
print "Win percentage (player 0): " + str(float(wins[0]) / numberOfGames * 100) + '%'
if __name__ == '__main__':
args = sys.argv[1:] # Get game components based on input
game = Game()
game.repl(args)