Beispiel #1
0
	def new_game(self, event):      # --- teiknar mynd af nyju bordi yfir gamla, gamla sést ef stærd breytist.
		print "Stofna nýjan leik!"
		afbrigdi = self.afbrigdi.GetValue()
		staerd = self.boardSize()
		assert(staerd != False)
 		print self.Against()
		ntowin = self.ntowin()
		assert(ntowin > 0)
		print "ntowin=" + str(ntowin)
		if self.Against() == 'Mennskur':        # --- ekki alveg klár á hvort þetta sé besta leiðin | ses: jamm, þetta er ekki fallegt en sleppur :-)
                        self.board = game.board(self.size.GetValue(), ntowin) 
                        self.gboard = wxgame.GraphicalBoard(self, self.board, 2) # XXX: hardcoding 2 players !
                        self.panel = self.gboard
                        self.IN_GAME = True
                if self.Against() == u'Tölva': # XXX: Erfiðleikastig?
			difficulty = self.Difficulty()
			assert(difficulty > 0)
			self.HAS_COMPUTER = True
                        self.board = game.board(self.size.GetValue(), ntowin) 
                        self.gboard = wxgame.GraphicalBoard(self, self.board, 2) # XXX: hardcoding 2 players !
			self.gboard.computer = True
			self.gboard.computer_cb = self.Computer
			self.computer = game.computer(self.board, difficulty) # XXX: hardcoded difficulty = 3 (same as in constructor of game.computer)
                        self.IN_GAME = True

		self.update_nextplayer(1) # spilari 1 á að gera í upphafi !
		self.gboard.game_mode = self.afbrigdi_to_gm(afbrigdi)
Beispiel #2
0
    def __init__(self, init_model=None):
        self.board = board()
        self.game = game(self.board)
        # Training parameter
        self.learn_rate = 2e-3
        self.lr_multiplier = 1.0
        self.temp = 1.0
        self.n_playout = 400
        self.c_puct = 5
        self.buffer_size = 10000
        self.batch_size = 512
        self.data_buffer = deque(maxlen=self.buffer_size)
        self.play_batch_size = 1
        self.epochs = 5
        self.kl_targ = 0.02
        self.check_freq = 50
        self.game_batch_num = 1500
        self.best_win_ratio = 0.0

        # num of simulations used for pure mcts
        self.pure_mcts_playout_num = 1000
        if init_model:
            # start from an existing policy value net
            self.policy_value_net = PolicyValueNet(model_file=init_model)
        else:
            self.policy_value_net = PolicyValueNet()
Beispiel #3
0
def run():
    try:
        b = board()
        g = game(b)
        p = player()
        g.start_play(p, is_shown=1)
    except KeyboardInterrupt:
        print('\n\rquit')
    def miniMaxSearch(self):
        if depth == maxdepth:
            return self.evaluateBoard(
            ), 0  ## Move shouldn't matter at max depth
        myturn = True if self.myplayernum == self.playerturn else False

        ## Special case the last move, since this can produce draws, and we need to search for the valid move
        if self.board.numpieces >= 41:
            for i in xrange(7):
                locboard = board(orig=self.board)
                done, winner = locboard.play(self.playerturn, i)
                if (myturn and winner == self.playerturn): return 1.0, i
                if (not myturn and winner == self.playerturn): return -1.0, i
                if winner == 0: return 0.0, i
            return 0.0, 0  ## Shouldn't get here

        locboards = [0] * 7
        done = [0] * 7
        winner = [0] * 7
        for i in xrange(7):
            locboard[i] = board(orig=self.board)
            done[i], winner[i] = locboard[i].play(self.playerturn, i)
            if (myturn and done[i] and winner == self.playerturn):
                return 1.0, i
            if (not myturn and done[i] and winner == self.playerturn):
                return -1.0, i  ## Move shouldn't matter here

        ## Now we iterate through remaining plays that aren't done and return the max/min of the results depending on minimax of node
        newplayer = 2 if self.playerturn == 1 else 2
        maxval, minval = -1.0, 1.0
        maxidx = 0
        for i in xrange(7):
            if not done[i]:
                childnode = node(locboard[i], self.depth + 1, self.maxdepth,
                                 myplayernum, newplayer)
                val = childnode.miniMaxSearch()
                if (myturn and val == 1.0): return 1.0
                if (not myturn and val == -1.0): return -1.0
                if val > maxval: maxval = val
                if val < minval: minval = val
        return maxval if myturn else minval
Beispiel #5
0
def main():
    from game import board
    print("Would you like to go first? 'y' for yes and 'n' for no")
    firstTurn = None
    while True:
        firstTurn = input()
        if firstTurn == "y" or firstTurn == "n":
            break
        print("Invalid input, please enter 'y' or 'n' (without the ')")

    gameBoard = board()
    if firstTurn == "y":
        humanPiece = 'r'
        aiPiece = 'b'
        gameBoard.print()
        print("Select a number associated with the column you want to choose")
        while True:
            column = input()
            if gameBoard.isValidColumn(column):
                gameBoard.addPiece(humanPiece, column)
                break
        blockPrint()
        computerAction = maxAI(gameBoard, aiPiece, 6)[1]
        gameBoard.addPiece(aiPiece, computerAction)
        enablePrint()
    else:
        humanPiece = 'b'
        aiPiece = 'r'
        gameBoard.addPiece(aiPiece, 3)
    while gameBoard.winner is None and not gameBoard.isFull():
        gameBoard.print()
        print("Select a number associated with the column you want to choose")
        while True:
            column = input()
            if gameBoard.isValidColumn(column):
                if gameBoard.addPiece(humanPiece, column)[0]:
                    print("You win!")
                break
        if gameBoard.winner is not None or gameBoard.isFull():
            break
        blockPrint()
        computerAction = maxAI(gameBoard, aiPiece, 7)[1]
        if gameBoard.addPiece(aiPiece, computerAction):
            print("You lose!")
        enablePrint()
    gameBoard.print()
    if gameBoard.isFull():
        print("Draw!")
Beispiel #6
0
			size = '6x6' # default !
		(w,h) = size.split('x')
		print "Boarding will be " + str(int(w)) + "x" + str(int(h))
		has_size = 1
	except:
		print "Invalid size!"

print "And how many discs in a row does it take to win? It's your decision... (default: 4)"
has_discs = 0
while (not has_discs):
	discs = raw_input(prompt)
	try:
		if discs == '':
			discs = '4' # default !
		discs = int(discs)
		gameboard = game.board(size, discs) # useless, but makes "sure" that the input doesn't generate some exception..
		has_discs = 1
	except ValueError:
		print "Please enter a number?!"
	except Exception as e:
		print e

player_str = "Alright "
for i in range(0, len(players)):
	if i == len(players)-1:
		player_str += " and "
	else:
		if i != 0:
			player_str += ", "
	player_str += players[i]
		
Beispiel #7
0
from mcts import MCTSPlayer
from game import board

gameBoard = board(cout=False)
while not gameBoard.gameEnded:
    print(gameBoard)
    move = int(input('Your move: '))
    while not gameBoard.validMove(move)[0]:
        move = int(input('Your move: '))
    gameBoard.placeMove(move)
    # mctsPlayer = MCTSPlayer(gameBoard)
    # move = mctsPlayer.returnMove()
    print(gameBoard)
    mctsPlayer2 = MCTSPlayer(gameBoard)
    move = mctsPlayer2.returnMove()
    gameBoard.placeMove(move)
print(gameBoard)
Beispiel #8
0
from game import board

gameBoard = board(cOut=True)
gameBoard.slots = [['x', 'o', 'o', 'o', 'x', 'o'],
                   ['o', 'o', 'x', 'x', 'x', 'o'],
                   ['o', 'x', 'o', 'o', 'x', 'x'],
                   ['o', 'x', 'x', 'x', 'o', 'x'],
                   ['x', 'x', 'o', 'o', 'x', 'o'],
                   ['o', 'o', 'x', 'o', 'x', 'x'],
                   ['-', 'o', 'x', 'o', 'x', 'o']]
gameBoard.placeMove(6)
print(gameBoard.gameEnded)
Beispiel #9
0
symbols = ['X','O']

def symbol_to_n(symbol):
	n = 0
	for symbol in symbols:
		if symbol == symbols[n]:
			return n
		n += 1

	return -1

(height, width) = [int(val) for val in size.split("x")]

for r in range(0,rounds):
	game_over = 0
	board = game.board(size, 3) # 3-in-a-row !
	computer = game.computer(board,difficulty)
	if (r % 10 == 0):
		print "Round %d/%d"%(r+1,rounds)
	computer_player = random.randrange(2) # which player is the computer?
	while (not game_over):
		#board.draw()
		#print "Computer should play: " + str(symbols[computer_player])
		# we are the random dude?
		for player in [0, 1]:
			if (board.fourinarow is not None or board.freespaces == 0):
				#print "Player %s is playing, but the game is over, or no free spaces"%player
				break
			if player == computer_player:
				computer.play(symbols[player])
			else:
Beispiel #10
0
import game

print "Performing tests:"
b = game.board('6x6',3)
r = b.play('X',0)
tests = 0
successful = 0

# Testing phase 1 is to verify that a) the fourinarow variable is set only when a player wins
# and b) that after it has been set, any attempts to play will fail
tests += 1
if (not r or b.fourinarow):
	print "1: TEST FAILED"
else:
	successful += 1
	print "1: TEST SUCCESSFUL"

tests += 1
r = b.play('X',1)
if (not r or b.fourinarow):
	print "2: TEST FAILED"
else:
	successful += 1
	print "2: TEST SUCCESSFUL"

tests += 1
r = b.play('X',2)
if (not r or b.fourinarow != 'X'):
	print "3: TEST FAILED"
else:
	successful += 1