def carregarArquivo(nome, nomeJogo):
    """Carrega o arquivo e retorna a arvore de jogo correspondente aos dados do arquivo"""
    arvoreDeJogo = GameTree(nomeJogo)
    # Caso o arquivo não exista, ele é criado
    try:
        grafo = open(nome, 'r')
    except Exception:
        grafo = open(nome, 'w')
        grafo.close()
        grafo = open(nome, 'r')
    # Adiciona os vértices e arestas do arquivo na árvore de jogo
    for l in grafo.readlines():
        linha = l.split(';')
        vertice = linha.pop(0)
        # Tirar o \n do ultimo elemento
        if len(linha) > 0:
            novoElemento = ''
            for caractere in linha[len(linha) - 1]:
                if caractere != '\n':
                    novoElemento += caractere
            linha[len(linha) - 1] = novoElemento
        else:
            # Caso o vértice seja o único elemento da linha, retira o \n dele mesmo
            novoElemento = ''
            for caractere in vertice:
                if caractere != '\n':
                    novoElemento += caractere
            vertice = novoElemento
        arvoreDeJogo.addAdjacents(vertice, linha, 0)
    return arvoreDeJogo
Пример #2
0
def test_random_tests():
    solvable = 0
    unsolvable = 0
    average_steps = 0
    how_many = 100
    for i in range(how_many):
        board = shuffle()
        if not CheckPuzzle(board).bool_check():
            unsolvable += 1
            print(i, 'un:', unsolvable)
            continue
        puzzle = Puzzle(board)
        game_tree = GameTree(puzzle)
        path = game_tree.solve()
        steps = -1
        for _ in path:
            steps += 1
        average_steps += steps
        solvable += 1
        print(i, 's:', solvable)
    output = 'In ' + str(how_many) + ' random boards:\n ' \
                                     'There is ' + str(unsolvable) + ' unsolvable:\n ' \
             + str(solvable) + ' solvable\n' \
                               'average_steps = ' + str(average_steps / solvable) + ' \n'
    print(output)
Пример #3
0
 def solve(self, event):
     """
     PRESS <SPACE> -> do a 'tip' move
     """
     game_tree = GameTree(self.puzzle)
     solution = game_tree.solve()
     list_solution = []
     for state in solution:
         list_solution.append(state.puzzle.board)
     to = self.tip(list_solution[1:])
     self._slide(to)
Пример #4
0
    def computerSetUp(self,rootTile):
        '''creates an instance of the game tree and calls to populate it,
         then runs the rollback analysis'''
        self.root = GNode(rootTile,1,0)
        self.tree=GameTree(self.root,rootTile)
        self.tree.populateTree(self.player1,self.player2)
        self.tree.setPayoffs()
##        self.tree.printTree() #UNCOMMENT LINE TO SEE TREE PRINT

        g1=self.grid.gridPoint(self.startX,self.startY)
        g2=self.grid.gridPoint(self.startX+1,self.startY)
        self.startX+=1
        self.startY-=1

        if self.root.isEmpty():
            winB=Button(self.win,Point(self.win.getWidth()/2,self.win.getHeight()/2),200,100,'white',"Player 1 wins!")
            self.over=True
            return False
        else:
            pays=[]
            for node in self.root.getOutgoing():
                pays.append(node.getPayoff())
            index=pays.index(min(pays))
            newNode=self.root.getOutgoing()[index]
            tile = newNode.getTile()
        if tile.getColor1() != self.root.getTile().getColor2():
            tile.switch()
        tile.placeTile(g1,g2)
        self.player2.updateLeft(tile)
        if newNode.isEmpty():
            self.over=True
            winB=Button(self.win,Point(self.win.getWidth()/2,self.win.getHeight()/4),200,100,'white',"Player 2 wins!")
        for button in self.buttons:
            button.activate()
        return newNode
Пример #5
0
def file_to_cli():
    """
    FILE-CLI interface
    """
    print("FILE->CLI")
    filename = input("Input filename: ")
    final_puzzle = work_with_file.read_puzzle(filename)
    print("Wait...\n")
    check_puzzle = CheckPuzzle(final_puzzle)
    check_puzzle.check()
    game = Puzzle(final_puzzle)
    tree_game = GameTree(game)
    solution = tree_game.solve()
    print('Solution:\n')
    step = -1
    for state in solution:
        print(state.pretty_print())
        step += 1
    print('steps:', step)
Пример #6
0
def cli_to_file():
    """
    CLI-FILE interface
    """
    print("CLI->FILE")
    final_puzzle = accept_from_user()
    print("Wait...\n")
    check_puzzle = CheckPuzzle(final_puzzle)
    check_puzzle.check()
    game = Puzzle(final_puzzle)
    tree_game = GameTree(game)
    solution = tree_game.solve()
    out_file = input("Input filename: ")
    str_solution = 'SOLUTION:\n'
    step = -1
    for state in solution:
        str_solution += state.pretty_print()
        str_solution += '\n'
        step += 1
    str_solution += 'steps:' + str(step)
    work_with_file.write_puzzle(out_file, str_solution)
Пример #7
0
def cli_to_cli():
    """
    CLI-CLI interface
    """
    print("CLI->CLI")
    final_puzzle = accept_from_user()
    print("Wait...\n")
    check_puzzle = CheckPuzzle(final_puzzle)
    check_puzzle.check()
    game = Puzzle(final_puzzle)
    tree_game = GameTree(game)
    tok = perf_counter()
    solution = tree_game.solve()
    tic = perf_counter()
    print('Solution:\n')
    step = -1
    for state in solution:
        print(state.pretty_print())
        step += 1
    print('steps:', step)
    print("time:", tic - tok)
Пример #8
0
    def __init__(self, board_fen=chess.STARTING_FEN, c=0.05, **kwargs): 
        '''
        We take the current game state which is parameterized by its FEN string. 
        self.cur_node = the StateNode that houses the root of the game tree which we wish to explore
        self.black = bool, True if the agent is playing black 
        self.c = float, a hyperparameter controlling the degree of exploration in the UCB1 bandit formula
        '''
        self.policy_net = MoveNet(**kwargs)
        self.policy_net.load_state_dict(torch.load('./trained_models/mc_net.pth', map_location=torch.device('cpu')))
        self.tree = GameTree(board_fen)

        # retain the board
        self.c = c
        self.tau = 1.0
Пример #9
0
def file_to_file():
    """
    FILE-FILE interface
    """
    print("FILE->FILE")
    filename = input("Input filename to read: ")
    final_puzzle = work_with_file.read_puzzle(filename)
    print("Wait...\n")
    check_puzzle = CheckPuzzle(final_puzzle)
    check_puzzle.check()
    game = Puzzle(final_puzzle)
    tree_game = GameTree(game)
    solution = tree_game.solve()
    out_file = input("Input filename to write: ")
    str_solution = 'SOLUTION:\n'
    step = -1
    for state in solution:
        str_solution += state.pretty_print()
        str_solution += '\n'
        step += 1
    str_solution += 'steps:' + str(step)
    work_with_file.write_puzzle(out_file, str_solution)
    print('\nSUCCESS\n')
Пример #10
0
def test_game_tree():
    the_most_hard_puzzle_1 = [[8, 6, 7],
                              [2, 5, 4],
                              [3, 0, 1]]
    puzzle = Puzzle(the_most_hard_puzzle_1)
    assert CheckPuzzle(the_most_hard_puzzle_1).bool_check() is True
    game_tree = GameTree(puzzle)
    path = game_tree.solve()
    steps = -1
    for _ in path:
        steps += 1
    assert steps == 31
    the_most_hard_puzzle_2 = [[6, 4, 7],
                              [8, 5, 0],
                              [3, 2, 1]]
    puzzle = Puzzle(the_most_hard_puzzle_2)
    assert CheckPuzzle(the_most_hard_puzzle_2).bool_check() is True
    game_tree = GameTree(puzzle)
    path = game_tree.solve()
    steps = -1
    for _ in path:
        steps += 1
    assert steps == 31
    print('pass')
Пример #11
0
def human_vs_cpu(game):
	game_tree = GameTree.GameTree(depth, game.board, game.turn)

	# return the move the cpu player will make
	return minimax_search.run_minimax(game_tree.root, -sys.maxint - 1, sys.maxint, Heuristics.maximize_threats)[1]
Пример #12
0
def cpu2(game):
	game_tree = GameTree.GameTree(depth, game.board, game.turn)

	# return the move the cpu player will make
	return minimax_search.run_minimax(game_tree.root, -sys.maxint - 1, sys.maxint, Heuristics.streaks_234)[1]
Пример #13
0
class GamePlay:
    def __init__(self,win,grid,player1,player2,quitB):
        '''constructs the instance for game play'''
        self.win=win
        self.grid=grid
        self.player1=player1
        self.player2=player2
        self.startX=0
        self.startY=8
        self.quitB=quitB
        self.buttons=player1.getButtonSet()
        self.tiles1=player1.getTileSet()
        self.switch,self.place=player1.getMoveSet()
        self.usedTiles=[]
        self.numClicked=0
        self.over=False

    def playGame(self):
        '''begins the game'''
        pt=self.win.getMouse()
        start=False
        while start == False or not self.quitB.isClicked(pt):
            if self.quitB.isClicked(pt):
                self.win.close()
                break
            else:
                start=self.startUp(pt)
            if start!=False:
                break
            pt=self.win.getMouse()

        move=self.humanMove(pt,start,start.getTile(),2)



    def startUp(self,pt):
        '''waits for the first tile to be picked by player1, then uses it to
         call to populate the tree'''
        for button in self.buttons:
            if button.isClicked(pt):
                self.buttons[self.numClicked].unchoose()
                button.choose()
                self.switch.activate()
                self.place.activate()
                self.numClicked=self.buttons.index(button)
        if self.switch.isClicked(pt):
            self.tiles1[self.numClicked].switch()
        elif self.place.isClicked(pt):
            self.switch.deactivate()
            self.buttons[self.numClicked].die()
            
            g1=self.grid.gridPoint(self.startX,self.startY)
            g2=self.grid.gridPoint(self.startX+1,self.startY)
            self.tiles1[self.numClicked].placeTile(g1,g2)
            self.place.deactivate()
            self.tiles1[self.numClicked].updateMark(2)
            self.player1.updateLeft(self.tiles1[self.numClicked])
            for button in self.buttons:
                button.deactivate()
            self.startX+=1
            self.startY-=1
            return self.computerSetUp(self.tiles1[self.numClicked])
            
        #returns false so that the while loop gets another click
        return False


    def computerSetUp(self,rootTile):
        '''creates an instance of the game tree and calls to populate it,
         then runs the rollback analysis'''
        self.root = GNode(rootTile,1,0)
        self.tree=GameTree(self.root,rootTile)
        self.tree.populateTree(self.player1,self.player2)
        self.tree.setPayoffs()
##        self.tree.printTree() #UNCOMMENT LINE TO SEE TREE PRINT

        g1=self.grid.gridPoint(self.startX,self.startY)
        g2=self.grid.gridPoint(self.startX+1,self.startY)
        self.startX+=1
        self.startY-=1

        if self.root.isEmpty():
            winB=Button(self.win,Point(self.win.getWidth()/2,self.win.getHeight()/2),200,100,'white',"Player 1 wins!")
            self.over=True
            return False
        else:
            pays=[]
            for node in self.root.getOutgoing():
                pays.append(node.getPayoff())
            index=pays.index(min(pays))
            newNode=self.root.getOutgoing()[index]
            tile = newNode.getTile()
        if tile.getColor1() != self.root.getTile().getColor2():
            tile.switch()
        tile.placeTile(g1,g2)
        self.player2.updateLeft(tile)
        if newNode.isEmpty():
            self.over=True
            winB=Button(self.win,Point(self.win.getWidth()/2,self.win.getHeight()/4),200,100,'white',"Player 2 wins!")
        for button in self.buttons:
            button.activate()
        return newNode

    def computerMove(self,node,tile,depth):
        '''chooses the computer's next move based on payoff, then places it'''
        g1=self.grid.gridPoint(self.startX,self.startY)
        g2=self.grid.gridPoint(self.startX+1,self.startY)
        self.startX+=1
        self.startY-=1
        
        if node.isEmpty():
            return False, False
        else:
            pays=[]
            for child in node.getOutgoing():
                pays.append(child.getPayoff())
            index=pays.index(min(pays))
            newNode=node.getOutgoing()[index]
            newTile= newNode.getTile()
            if newTile.getColor1() != tile.getColor2():
                newTile.switch()
            newTile.placeTile(g1,g2)
            self.player2.updateLeft(newTile)
            if node.getOutgoing()[index].isEmpty():
                return True,True
            for button in self.buttons:
                button.activate()
            return newTile, newNode
   
    def humanMove(self,pt,node,tile,depth):
        '''gets clicks until player places tile correctly'''
        while not self.quitB.isClicked(pt) or not self.over:
            if self.quitB.isClicked(pt):
                break
            for button in self.buttons:
                if button.isClicked(pt):
                    self.buttons[self.numClicked].unchoose()
                    button.choose()
                    self.switch.activate()
                    self.place.activate()
                    self.numClicked=self.buttons.index(button)
            if self.switch.isClicked(pt):
                self.tiles1[self.numClicked].switch()
            elif self.place.isClicked(pt):
                if tile.getColor2() != self.tiles1[self.numClicked].getColor1():
                    errorRect=Rectangle(Point(249,100),Point(748,350))
                    errorRect.setFill('white')
                    errorRect.draw(self.win)
                    errorMess=Text(Point(500,200),"That move is invalid.\nChoose a tile whose left color corresponds\nto the rightmost tile-color on the board.")
                    errorMess.draw(self.win)
                    errorMess.setSize(26)
                    self.win.getMouse()
                    errorRect.undraw()
                    errorMess.undraw()
                else:
                    self.switch.deactivate()
                    self.buttons[self.numClicked].die()
                    
                    g1=self.grid.gridPoint(self.startX,self.startY)
                    g2=self.grid.gridPoint(self.startX+1,self.startY)
                    self.tiles1[self.numClicked].placeTile(g1,g2)
                    self.place.deactivate()
                    self.tiles1[self.numClicked].updateMark(2)
                    self.player1.updateLeft(self.tiles1[self.numClicked])
                    for button in self.buttons:
                        button.deactivate()
                    self.startX+=1
                    self.startY-=1
                    if depth==8:
                        self.over=True
                        winB=Button(self.win,Point(self.win.getWidth()/2,self.win.getHeight()/4),200,100,'white',"Player 1 wins!")
                    else:
                        for iNode in node.getOutgoing():
                            if iNode.getTile() == self.tiles1[self.numClicked]:
                                newNode = iNode
                        tile, node= self.computerMove(newNode,self.tiles1[self.numClicked],depth)
                        depth+=2
                        if tile == False:
                            self.over=True
                            winB=Button(self.win,Point(self.win.getWidth()/2,self.win.getHeight()/4),200,100,'white',"Player 1 wins!")
                        elif tile == True:
                            self.over=True
                            winB=Button(self.win,Point(self.win.getWidth()/2,self.win.getHeight()/4),200,100,'white',"Player 2 wins!")
                            
            pt=self.win.getMouse()
        self.win.close()
Пример #14
0
import numpy as np
import Bitboard as bb
import GameTree as gt
import time
from random import randrange

import Bitboard as bb
#all = pow(2,34) + pow(2,6) + pow(2,2)
#bb.printBitBoard(all)
#m = bb.getRookMoveMask(all,2)
#bb.printBitBoard(m)

#all = pow(2,17) + pow(2,22) + pow(2,43) + pow(2,3) + pow(2,19)
s = gt.State(True)
s.createStartConfig()
g = gt.GameTree(True)
#s.printState()
print len(s.getChildren())
g.alphaBeta(s, 3, -200, 200, True)
print len(s.getChildren())
s2 = s.getBestMove()
s2.printState()
#print g.getCount()
'''
moves = g.generateAllMoves(s)
print "white starts"
for m in moves:
	pass
	#m.printMove()

new = g.makeMove(s,moves[1])