def interactiveGame(currentGame, depth):
    # Fill me in
    #sys.exit('Interactive mode is currently not implemented')
    while currentGame.pieceCount != 42:
        if currentGame.currentTurn == 1:
            move = input('enter some number in the range of 1-7::')
            if move > 7 or move < 1:
                print 'Invalid move'
                continue
            if not currentGame.playPiece(move - 1):
                print 'No space left in this column..'
                continue
            try:
                currentGame.gameFile = open('human.txt', 'w')
            except:
                sys.exit('file not found')
            postmoveupdate(currentGame, move - 1)
        elif currentGame.pieceCount != 42:
            search = Minimax(currentGame, depth)
            move = search.decision()
            result = currentGame.playPiece(move)
            try:
                currentGame.gameFile = open("computer.txt", 'w')
            except:
                sys.exit('file not found')
            postmoveupdate(currentGame, move)

    currentGame.gameFile.close()
    if currentGame.player1Score == currentGame.player2Score:
        print 'It is a draw'
    elif currentGame.player2Score < currentGame.player1Score:
        print 'Human wins'
    else:
        print 'AI rampage'
def interactiveGame(currentGame, depth):
    while currentGame.pieceCount != 42:
        if currentGame.currentTurn == 1:
            nextMove = input(
                "Enter the column between [1-7] where you want to insert your next coin : "
            )
            if not currentGame.playPiece(nextMove - 1):
                print "This column is full!"
                continue
            if nextMove < 1 or nextMove > 7:
                print "Enter a column between [1-7]!"
            currentGame.gameFile = open("Human.txt", 'w')
            gameState(currentGame, nextMove - 1)
        elif currentGame.pieceCount != 42:
            minimaxTree = Minimax(currentGame, depth)
            move = minimaxTree.Decision()
            result = currentGame.playPiece(move)
            currentGame.gameFile = open("Computer.txt", 'w')
            gameState(currentGame, move)
    currentGame.gameFile.close()
    if currentGame.player1Score > currentGame.player2Score:
        print "User won"
    elif currentGame.player2Score > currentGame.player1Score:
        print "Computer won"
    else:
        print "Game Drawn"
示例#3
0
def aiPlay(currentGame, init_next, depth):
    print('---------------COMPUTER TURN---------------')
    #Minimax object
    miniobj = Minimax(currentGame, init_next, depth)

    #Result of next move(column) using minimax algorithm
    dec_col = miniobj.final_decision()

    #Play with result column
    currentGame.playPiece(dec_col)
    print('move %d: Player %d, column %d' %
          (currentGame.pieceCount, currentGame.currentTurn, dec_col + 1))

    # Print GameBoard
    print 'Game state after move:'
    currentGame.printGameBoard()

    # Print Score
    currentGame.countScore()
    print('Score: Player 1 = %d, Player 2 = %d' %
          (currentGame.player1Score, currentGame.player2Score))

    try:
        # open computer.txt with write mode
        currentGame.gameFile = open("computer.txt", 'w')
    except:
        sys.exit('Error opening output file, computer.txt')

    # write currentGameBoard to computer.txt
    currentGame.printGameBoardToFile()

    # human.txt computer.txt close
    currentGame.gameFile.close()
def oneMoveGame(currentGame, depth):
    if currentGame.pieceCount == 42:  # Is the board full already?
        print 'BOARD FULL\n\nGame Over!\n'
        sys.exit(0)
    tree = Minimax(currentGame, depth)
    move = tree.Decision()
    result = currentGame.playPiece(move)
    gameState(currentGame, move)
    currentGame.gameFile.close()
def oneMoveGame(currentGame,depth):
    if currentGame.pieceCount == 42:    # Is the board full already?
        print 'BOARD FULL\n\nGame Over!\n'
        sys.exit(0)

    #currentGame.aiPlay() # Make a move (only random is implemented)
    searchTree = Minimax(currentGame,depth)
    move = searchTree.makeDecision()
    result = currentGame.playPiece(move)
    afterMoveOperations(currentGame,move)
    currentGame.gameFile.close()
示例#6
0
def oneMoveGame(currentGame, depth):
    if currentGame.pieceCount == 42:  # Is the board full already?
        print 'BOARD FULL\n\nGame Over!\n'
        sys.exit(0)

    #currentGame.aiPlay() # Make a move (only random is implemented)
    possible_moves = Minimax(currentGame, depth)
    move = possible_moves.makeDecision()
    currentGame.playPiece(move)
    nextMove(currentGame, move)
    currentGame.gameFile.close()
示例#7
0
def computerClick():
    global step
    if Minimax.checkWin(playerSymbol, gameBoard):
        tkinter.messagebox.showinfo("Tic-Tac-Toe", "You win!")
        return
    if step == 9:
        tkinter.messagebox.showinfo("Tic-Tac-Toe", "Draw")
        return
    move = Minimax.findMove(gameBoard)
    gameBoard[move] = computerSymbol
    dict_b[move]["text"] = "O"
    step += 1
示例#8
0
def netplay(window,images,board,player,coupE,date,damier,scoreboard,score_noir,score_blanc):
    if (date == 0) and (player == 2):
        coupE = attentePremierCoup()
        return netplay(window,images,board,player,coupE,1,damier,scoreboard,score_noir,score_blanc) #OnlinePlay(player,dam,coupE,1)
    elif (date == 0) and (player == 1):
        coupE = jouer(65)
        print ('moi: 65')
        Poser(6,5,1,damier)
        boardupdate(window,board,images,damier,player)
        return netplay(window,images,board,player,coupE,1,damier,scoreboard,score_noir,score_blanc)
        
    if (coupE != -1):
        xe = int(coupE//10) 
        ye = int(coupE%10)
        print ('lui: ',coupE)
        Poser(xe,ye,3-player,damier)
    else:
        print("the enemy pass")
    boardupdate(window,board,images,damier,player)
    noplay =np (damier,player)
    if noplay[0] == 4:
        return fin(-1)
    coup = Minimax (damier,player)
    print ('moi: ',coup)
    x = int(coup//10)
    y = int(coup%10)
    Poser(x,y,player,damier)
    noplay = np(damier,player)
    if noplay[0] == 4:
        return fin(coup)
    boardupdate(window,board,images,damier,player)
    scoreboard.itemconfigure(score_noir,text ="Joueur 1 : %d" %(noplay[1]))
    scoreboard.itemconfigure(score_blanc,text ="Joueur 2 : %d" %(noplay[2]))
    return netplay(window,images,board,player,jouer(coup),1,damier,scoreboard,score_noir,score_blanc)
示例#9
0
    def multiBot(self):
        """ Permainan Mode 3: Bot Minimax vs Bot Minimax Local Search"""
        terminalState = False
        while not (terminalState):
            # Masukkan mau pion ID berapa yang mau dijalankan
            self.printInfo()
            if (self.currentPlayer.noPlayer == 1):
                print("PLAYER " + str(self.currentPlayer.noPlayer) +
                      " MINIMAX TURN!")
                self.currentPlayer.printAllPion()
                # Minimax Process
                currentState = GameState.GameState(self.board,
                                                   self.currentPlayer,
                                                   self.oppositePlayer)
                beforeProcess = time.time()
                minimaxState, _eval = Minimax.minimax(
                    currentState, 3,
                    time.time() + self.tlimit, -math.inf, math.inf,
                    self.currentPlayer.noPlayer)
                self.assignState(minimaxState)
                deltaTime = time.time() - beforeProcess
                print(f"Execution time = {deltaTime} seconds")

            else:
                print("PLAYER " + str(self.currentPlayer.noPlayer) +
                      " MINIMAX LOCAL SEARCH TURN!")
                self.currentPlayer.printAllPion()
                # Minimax with Local Search
                currentState = GameState.GameState(self.board,
                                                   self.currentPlayer,
                                                   self.oppositePlayer)
                beforeProcess = time.time()
                minimaxState, _eval = Minimax.minimaxLocalSearch(
                    currentState, 3,
                    time.time() + self.tlimit, -math.inf, math.inf,
                    self.currentPlayer.noPlayer)
                self.assignState(minimaxState)
                deltaTime = time.time() - beforeProcess
                print(f"Execution time = {deltaTime} seconds")

            if (self.board.checkTerminalState(self.currentPlayer.noPlayer)):
                terminalState = True
            else:
                self.nextTurn()
        self.printInfo()
        print("Player " + str(self.currentPlayer.noPlayer) + " win the game!")
示例#10
0
 def minimaxDecision(self):
     nextBoards = self.board.nextBoardsExcludingCar(self.otherCar)
     minValues = []
     for nextBoard in nextBoards:
         s = Minimax.minimax(nextBoard, self.carCh, 3, False)
         minValues.append(s)
     i = minValues.index(max(minValues))
     return nextBoards[i]
示例#11
0
    def playerVsMinMax(self):
        """ Permainan Mode 1: Player vs BOT Minimax """
        terminalState = False
        while not (terminalState):
            self.printInfo()

            # Giliran Player BOT Minimax
            if (self.currentPlayer.noPlayer != self.hplayer):
                print("PLAYER " + str(self.currentPlayer.noPlayer) +
                      " MINIMAX TURN!")
                input("Begin minimax? ")
                self.currentPlayer.printAllPion()

                # Minimax process for the BOT
                currentState = GameState.GameState(self.board,
                                                   self.currentPlayer,
                                                   self.oppositePlayer)
                beforeProcess = time.time()
                minimaxState, _eval = Minimax.minimax(
                    currentState, 2,
                    time.time() + self.tlimit, -math.inf, math.inf,
                    self.currentPlayer.noPlayer)
                self.assignState(minimaxState)
                deltaTime = time.time() - beforeProcess
                print(f"Execution time = {deltaTime} seconds")
                print("PLAYER " + str(self.currentPlayer.noPlayer) + " FANO")
                print("PLAYER " + str(self.hplayer) + " Hello")
                input("Boleh next sekarang!")

            # Giliran Player Manusia
            else:
                print("PLAYER " + str(self.currentPlayer.noPlayer) + " TURN!")
                self.currentPlayer.printAllPion()
                chosenID = int(
                    input("Pilih Pion ID mana yang ingin dimainkan :  "))
                if (chosenID == 999):
                    self.saveGame()
                possible_moves = self.currentPlayer.listAllPossibleMove(
                    chosenID, self.board)
                for i in range(len(possible_moves)):
                    print(str(i + 1) + ". ", end="")
                    possible_moves[i].printPosisi()
                chosenMove = int(
                    input(
                        "Pilih move yang diinginkan dengan memasukkan nomor :  "
                    ))
                self.currentPlayer.movePion(chosenID,
                                            possible_moves[chosenMove - 1],
                                            self.board)

            # Cek apakah sekarang merupakan kondisi terminal
            if (self.board.checkTerminalState(self.currentPlayer.noPlayer)):
                terminalState = True
            else:
                self.nextTurn()

        self.printInfo()
        print("Player " + str(self.currentPlayer.noPlayer) + " win the game!")
示例#12
0
 def play(self, game):
     if self.color is None:
         raise RuntimeError("A player cannot play without an assigned color.")
     if self.color != game.currentColor:
         raise RuntimeError("This player ({}) can't"
                            "play this turn ({}).".format(self.color,
                                                          game.currentColor))
     value, move, strokes = Minimax.minimax(game, self, debug=False)
     return game.play(move)
示例#13
0
 def minimaxDecisionABPruning(self):
     nextBoards = self.board.nextBoardsExcludingCar(self.otherCar)
     minValues = []
     alpha = -float("inf")
     beta = float("inf")
     for nextBoard in nextBoards:
         s = Minimax.minimax_pruning(nextBoard, self.carCh, 3, False, alpha, beta)
         minValues.append(s)
     i = minValues.index(max(minValues))
     return nextBoards[i]
示例#14
0
 def play(self, game):
     if self.color is None:
         raise RuntimeError(
             "A player cannot play without an assigned color.")
     if self.color != game.currentColor:
         raise RuntimeError("This player ({}) can't"
                            "play this turn ({}).".format(
                                self.color, game.currentColor))
     value, move, strokes = Minimax.minimax(game, self, debug=False)
     return game.play(move)
示例#15
0
def Play(player, dam, player1, player2, gamemode):
    affiche(player, dam)
    if (win(dam, player, player1, player2, gamemode) == 0):
        print('')
    else:
        return
    if gamemode == 1:
        if (player == 1):
            coup = int(input(player1))
        else:
            coup = int(input(player2))
    if gamemode == 4:
        coup = Minimax(dam, player)
    if gamemode == 5:
        if player == 1:
            coup = Minimax(dam, player)
        else:
            plyy = []
            for i in range(10):
                for j in range(10):
                    if estValide(i, j, player, dam) and dam[i][j] == 0:
                        plyy.append(10 * i + j)
            if plyy != []:
                coup = plyy[random.randint(0, len(plyy) - 1)]
    if gamemode == 2:
        if player == 1:
            coup = int(input(player1))
        else:
            coup = Minimax(dam, player)
    x = int(coup // 10)  #Oui, la magie existe!
    y = int(coup % 10)
    if coup == -1:
        print('aha')
    else:
        if coup not in range(0, 100, 1):
            print("Impossible")
            return Play(player, dam, player1, player2, gamemode)
        if not estValide(x, y, player, dam):
            print("Impossible")
            return Play(player, dam, player1, player2, gamemode)
    Poser(x, y, player, dam)
    return Play(3 - player, dam, player1, player2, gamemode)
示例#16
0
 def play(self):
     self.display()
     s = in2048()
     m = mm.miniMax(s)
     while not self.gameover:
         #op = raw_input('operator: ')
         #print ("AI")
         op = m.find_best_move(s, 3)
         #commands = ['w','d','s','a']
         #op = commands.index(op)
         self.operation(op)
         self.display()
示例#17
0
def btnClick(x):
    global step
    if Minimax.checkWin(computerSymbol, gameBoard):
        tkinter.messagebox.showinfo("Tic-Tac-Toe", "Computer wins!")
        return
    if dict_b[x]["text"] == " ":
        dict_b[x]["text"] = playerSymbol
        gameBoard[x] = 'X'
        step += 1
        computerClick()
    else:
        tkinter.messagebox.showinfo("Tic-Tac-Toe", "Button already Clicked!")
示例#18
0
def interactiveGame(currentGame, depth):
    # Fill me in
    # sys.exit('Interactive mode is currently not implemented')

    while not currentGame.pieceCount == 42:
        if currentGame.currentTurn == 1:
            userMove = input(
                "Enter the column number [1-7] where you would like to play : "
            )
            if not 0 < userMove < 8:
                print "Invalid column number!"
                continue
            if not currentGame.playPiece(userMove - 1):
                print "This column is full!"
                continue
            try:
                currentGame.gameFile = open("human.txt", 'w')
            except:
                sys.exit('Error opening output file.')
            nextMove(currentGame, userMove - 1)

        elif not currentGame.pieceCount == 42:
            possible_moves = Minimax(currentGame, depth)
            move = possible_moves.makeDecision()
            currentGame.playPiece(move)
            try:
                currentGame.gameFile = open("comupter.txt", 'w')
            except:
                sys.exit('Error opening output file.')
            nextMove(currentGame, move)

    currentGame.gameFile.close()

    if currentGame.player1Score > currentGame.player2Score:
        print "Player 1 wins"
    elif currentGame.player2Score > currentGame.player1Score:
        print "Computer wins"
    else:
        print "It's a draw"
    print "Thank you for playing MaxConnect4Game"
示例#19
0
 def minimaxDecision(self):
     start = time.time()
     nextBoards = self.board.next(self.label)
     minValues = []
     for nextBoard in nextBoards:
         s = Minimax.minimax(nextBoard, self.label, 4, False)
         minValues.append(s)
     i = minValues.index(max(minValues))
     end = time.time()
     print(
         "Time it took to make this decision with minimax without alpha-beta pruning: "
         + str(end - start))
     return nextBoards[i]
def interactiveGame(currentGame,depth):
    # Fill me in
    # sys.exit('Interactive mode is currently not implemented')

    while not currentGame.pieceCount == 42:
        if currentGame.currentTurn == 1:
            userMove = input("Enter the column number [1-7] where you would like to play : ")
            if not 0 < userMove < 8:
                print "Invalid column number!"
                continue
            if not currentGame.playPiece(userMove-1):
                print "This column is full!"
                continue
            try:
                currentGame.gameFile = open("human.txt", 'w')
            except:
                sys.exit('Error opening output file.')
            afterMoveOperations(currentGame,userMove-1)

        elif not currentGame.pieceCount == 42:
            searchTree = Minimax(currentGame,depth)
            move = searchTree.makeDecision()
            result = currentGame.playPiece(move)
            try:
                currentGame.gameFile = open("comupter.txt", 'w')
            except:
                sys.exit('Error opening output file.')
            afterMoveOperations(currentGame,move)

    currentGame.gameFile.close()

    if currentGame.player1Score > currentGame.player2Score:
        print "Player 1 wins"
    elif currentGame.player2Score > currentGame.player1Score:
        print "Computer wins"
    else:
        print "It's a draw"
    print "Thank you for playing MaxConnect4Game"
示例#21
0
 def minimaxDecisionABPruning(self):
     start = time.time()
     nextBoards = self.board.next(self.label)
     minValues = []
     alpha = -float("inf")
     beta = float("inf")
     for nextBoard in nextBoards:
         s = Minimax.minimax_pruning(nextBoard, self.label, 4, False, alpha,
                                     beta)
         minValues.append(s)
     i = minValues.index(max(minValues))
     end = time.time()
     print(
         "Time it took to make this decision with minimax with alpha-beta pruning: "
         + str(end - start))
     return nextBoards[i]
示例#22
0
 def choose_move(self, game):
     try:
         if self.type == Player.PlayerTypes.MINIMAX:
             return Minimax.alpha_beta(game, Player.DEPTH, self, True,
                                       self.get_disk())
         elif self.type == Player.PlayerTypes.HUMAN:
             return self.human_move(game)
         elif self.type == Player.PlayerTypes.NBOARD:
             pass  # todo add choose move for Nboard player
         elif self.type == Player.PlayerTypes.RANDOM:
             return self.random_move(game)
         elif self.type == Player.PlayerTypes.FOUR_BY_FOUR:
             return self.four_by_four_move(game)
         elif self.type == Player.PlayerTypes.TABLE:
             raise ValueError("not supposed to do a move")
     except Exception as e:
         print("do again")
         print(str(e))
         return self.choose_move(game)
示例#23
0
 def minimaxMove(self):
     """ Menjalankan bot Minimax pada giliran bot tersebut """
     print("PLAYER " + str(self.currentPlayer.noPlayer) + " MINIMAX TURN!")
     # Minimax Process
     beforeProcess = time.time()
     currentState = GameState.GameState(self.board, self.currentPlayer,
                                        self.oppositePlayer)
     minimaxState, _eval = Minimax.minimax(currentState, 3,
                                           time.time() + self.tlimit,
                                           -math.inf, math.inf,
                                           self.currentPlayer.noPlayer)
     deltaTime = time.time() - beforeProcess
     self.totalTime += deltaTime
     print(f"Execution time = {deltaTime} seconds")
     self.assignState(minimaxState)
     terminalState = False
     if (self.board.checkTerminalState(self.currentPlayer.noPlayer)):
         terminalState = True
     return terminalState
示例#24
0
def Play(window,board,images,damier,X,Y,scoreboard,score_noir,score_blanc):
    w , h = window.winfo_screenwidth(), window.winfo_screenheight()
    global player
    noplay = np(damier,player)
    x = Y//70
    y = X//70
    if estValide(x,y,player,damier):
        Poser(x,y,player,damier)
        player = 2
        noplay = np(damier,player)
        boardupdate(window,board,images,damier,1)
        while (noplay[0] == 0) and (player == 2):
            coup = Minimax(damier,player)
            print("ai played: " , coup)
            x = int(coup//10) 
            y = int(coup%10)
            Poser(x,y,player,damier)
            boardupdate(window,board,images,damier,1)
            player = 1
            noplay = np(damier,player)
            if noplay[0] == 4:
                break
            elif noplay[0] == 1:
                print( "skipped turn player")
                player = 2
                noplay = np(damier,player)
        scoreboard.itemconfigure(score_noir,text ="Joueur : %d" %(noplay[1]))
        scoreboard.itemconfigure(score_blanc,text ="IA : %d" %(noplay[2]))
    player = 1
    if noplay[0] == 4:
        print("game ended")
        if noplay[1] == noplay[2]:
            Button(window, text = 'Egalite' , command = lambda:window.destroy()).place(x=w/2-50, y = h/2-25, width=100, height=30)
        elif noplay[1] > noplay[2]:
            Button(window, text = 'Victoire Joueur' , command = lambda:window.destroy()).place(x=w/2-50, y = h/2-25, width=100, height=30)
        else:
            Button(window, text = 'Victoire IA' , command = lambda:window.destroy()).place(x=w/2-50, y = h/2-25, width=100, height=30)
示例#25
0
 def move(self, state):
     m = Minimax.Minimax(state)
     best_move, value = m.bestMove(self.difficulty, state, self.color)
     return best_move
示例#26
0
def get_grid_tile(px_x, px_y):
    return Vector2(px_x // 125, px_y // 125)

curr_player = GL.BLACK
is_running = True
pending_move = PendingMove(board, curr_player)

# debugging
show_mouse_moves = False

while is_running:

    if curr_player == GL.RED:
        start_s = time.time()
        move = ALG.minimax(board, DEPTH, float('-inf'), float('inf'), True)[0]
        end_s = time.time()
        print('move found in ' + str(round(end_s-start_s,4)) + ' seconds')
        GL.execute_move(board, move)
        pending_move.switch_player()
        curr_player *= -1
        gm = GL.game_over(board, curr_player)
        if gm:
            print([None, 'Red', 'Black'][gm] + ' Won!')
            is_running = False

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            is_running = False
            break
示例#27
0
				if self.board[i]==self.board[i+2]==self.board[i+4] and self.board[i]!=".":
					return True
		return False
		
num_players= int(input('Enter the number of AI players: '))
x = Game_Board()
x.display_board
state=Minimax.State(x.board, 'X')
if num_players==1:
	while True:
		if x.is_empty():
			player = 1
		if player==1:
			place = int(input("What spot would you like to mark: "))
		elif player==2:
			result=Minimax.minimax(state, 2, 'O')
			place=result
			print place
		if x.mark_board(place, player)==False:
			print "Invalid move, Choose again"
		
		else:
			print "Player %d has marked %d: " % (player, place)
			if player==1:
				state=Minimax.State(x.board, 'X')
			else:
				state=Minimax.State(x.board,'O')
			if x.check_win():
				if player==1:
					x.display_board()
					print "Player 1 wins!"
示例#28
0
import Minimax
import GameState as game

best_moves = set([(0, 0), (2, 0), (0, 1)])
rootNode = game.GameState()
minimax_move = Minimax.minimax_decision(rootNode)

print("Best move choices: {}".format(list(best_moves)))
print("Your code chose: {}".format(minimax_move))

if minimax_move in best_moves:
    print(
        "That's one of the best move choices. Looks like your minimax-decision function worked!"
    )
else:
    print("Uh oh...looks like there may be a problem.")
示例#29
0
features.append(TDLearning.getScoreFeature())

# whiteWin, blackWin = TDLearning.getWinFeatures()
# features.append(whiteWin)
# features.append(blackWin)

# features.append(TDLearning.getProtectedFeature(abgame, 1))
# features.append(TDLearning.getProtectedFeature(abgame, -1))

# features.append(TDLearning.getPushFeature(abgame, 1))
# features.append(TDLearning.getPushFeature(abgame, -1))

#features.append(TDLearning.getTurnFeature(1))
#features.append(TDLearning.getTurnFeature(-1))

minimax = Minimax.Minimax(explore=float(args["explore"]))
tdlearning = TDLearning.TDLearning(features,
                                   step=float(args["step"]),
                                   discount=float(args["discount"]))

TRAINING_DEPTH = 2
GAME_DEPTH = 3

print abgame

if args['weights'] != None:
    tdlearning.applyWeights(
        util.getPreloadedWeights("weights/" + args['weights'] + ".txt"))
    tdlearning.printWeights()
if numGames > 0:
    print "Training algorithm..."
示例#30
0
    if len(sys.argv) < 2:
        print "Please enter the input position filename:"
        input = sys.stdin.readlines()
    # Take in from command line arguments
    else:
        input = sys.argv[1]  # sys.argv[0] is this file's name (Driver.py)

    # Does this input exists and is input a file (not a directory).
    if os.path.exists(input) or os.path.isfile(input):
        file = open(input, 'r')  # open file for reading
        parser = Parser.Parser(file)  # construct new parser object.
        (count, color, steps, board) = parser.parse()  # Parse the file.
        file.close()

        if count == "1":
            print MoveGenerator.MoveGenerator.randSetup(color)
        else:
            hash = Hash.Hash()  # Construct a new hash
            hash.calculateHashkey(
                board)  # Calculate the hash key for this given board.

            mini = Minimax.Minimax(board, color)
            res = mini.minimax(2, board, color, "", count, hash)
            move = res[1].split('|')
            print move[1].strip()

    else:
        print "File not found"

    sys.exit()
示例#31
0
文件: Game.py 项目: mbaez/pydamas
	def __init__(self):
		evaluacion=Tablero()
		algoritmo=Minimax()
		self.tablero=Tablero(evaluacion.evaluar_suma_peso)
		self.tablero.cargar_fichas()
		self.minimax=Minimax(algoritmo.minimax);
示例#32
0
文件: Game.py 项目: mbaez/pydamas
class Game:
	def __init__(self):
		evaluacion=Tablero()
		algoritmo=Minimax()
		self.tablero=Tablero(evaluacion.evaluar_suma_peso)
		self.tablero.cargar_fichas()
		self.minimax=Minimax(algoritmo.minimax);
	def quien_gano(self):
		value=self.tablero.evaluar_suma(1)
		if(value < 0):
			return "Perdiste!!!"
		return "Ganaste!!!"
	
	def juega_computadora(self):
		old_move_computadora,new_move_computadora=self.minimax.start(self.tablero)
		print "score : ", new_move_computadora
		lista, comer_move=self.tablero.comer_fichas(old_move_computadora)
		if(len(lista)-1==0):
			self.tablero.mover_ficha(old_move_computadora,new_move_computadora)
			lista.append(old_move_computadora)
			lista.append(new_move_computadora)
			comer_move=[]
		if(self.tablero.es_dama(new_move_computadora,Ficha.COMPUTADORA)):
			self.tablero.crear_dama(new_move_computadora, Ficha.COMPUTADORA)
		return lista,comer_move
		'''

		'''
	def traducir_a_index(self, move):
		return move.i*8+move.j%8
		
	def juega_usuario(self,x,y):
		
		'''
		debe verificar si:
		se comio una ficha y actualizar el tablero
		'''
	def realizar_movimiento(self, old_move, new_move):
		if(self.tablero.es_valido_move(old_move,new_move)):
			if(self.es_dama_usuario(old_move)):
				#prueba una posicion
				self.tablero.mover_ficha(old_move, new_move)
				comer_move=self.tablero.get_pos_ficha_anterior(old_move,new_move)
				if(not self.tablero.es_duenho(comer_move, Ficha.COMPUTADORA)):
					comer_move=None
			else:
				comer_move=self.tablero.comer_ficha(old_move, new_move)
				self.tablero.mover_ficha(old_move, new_move)
				if(self.es_dama_usuario(new_move)):
					self.tablero.crear_dama(new_move)
			if not (comer_move==None):
				print self.tablero
				self.tablero.eliminar_ficha(comer_move)
				return comer_move.i*Tablero.MAX_DIM+comer_move.j%Tablero.MAX_DIM
			return True
		return False
		
	def route_valido(self, old_move, new_move):
		copia=self.tablero.get_copia()
		if(copia.es_valido_move(old_move,new_move)):
			return True
		return False
	
	def esta_bloqueada(self, move):
		if(self.tablero.casillas[move.i][move.j].duenho==Ficha.BLOQUEADA):
			return True;
		return False
	'''
	verifica si una casilla esta ocupada por el duenho
	'''
	def ocupe_casilla(self, move, duenho=Ficha.USUARIO):
		if(self.tablero.es_vacio(move.i, move.j) or not self.tablero.casillas[move.i][move.j].duenho==duenho):
			return False
		return True
	
	def eliminar_ficha(self, move):
		self.tablero.casillas[move.i][move.j]=Ficha()
	
	def es_dama_usuario(self,move):
		return self.tablero.es_dama(move, Ficha.USUARIO)
	def es_dama_computadora(self, move):
		return self.tablero.es_dama(move, Ficha.COMPUTADORA)
	def es_ficha_usuario(self,move):
		return self.tablero.casillas[move.i][move.j].duenho==Ficha.USUARIO
	def es_ficha_computadora(self, move):
		return self.tablero.casillas[move.i][move.j].duenho==Ficha.COMPUTADORA
示例#33
0
    def start(self):

        while True:

            #Evaluacion para no terminar con todos los items
            #if self.interfaz.manzanas==[] or abs(len(self.user_items)-len(self.pc_items))>len(self.interfaz.manzanas):
            #Evalua si el juego Termino
            if self.interfaz.manzanas == []:

                self.pintar_ganador()

            #Eventos de tablero
            #turno tablero
            elif self.turno == True:
                pos = self.next(self.interfaz.pos_cn)
                self.crear_botones_player(pos)
            #turno pc
            elif self.turno == False:
                minimax = Minimax(self.interfaz.pos_cn, self.interfaz.pos_cb,
                                  self.user_items, self.pc_items,
                                  self.interfaz.manzanas)
                #mover caballo blanco
                self.moves(minimax.pos_cb, False)

                #cambia turno
                self.turno = True

                #aleatorio
                #pos=self.next(self.interfaz.pos_cb)
                #self.move_pc(pos)

            for evento in pygame.event.get():

                if evento.type == QUIT:
                    pygame.quit()
                    sys.exit()

                if evento.type == pygame.MOUSEBUTTONDOWN:

                    mouse_pos = evento.pos  # gets mouse position
                    #Cuando un usuario selecciona una opcion envia la coordenada que selecciono el jugador
                    if self.b1.collidepoint(mouse_pos):
                        self.moves([int(self.b1.x / 60),
                                    int(self.b1.y / 60)], 1)
                    if self.b2.collidepoint(mouse_pos):
                        self.moves([int(self.b2.x / 60),
                                    int(self.b2.y / 60)], 1)
                    if self.b3.collidepoint(mouse_pos):
                        self.moves([int(self.b3.x / 60),
                                    int(self.b3.y / 60)], 1)
                    if self.b4.collidepoint(mouse_pos):
                        self.moves([int(self.b4.x / 60),
                                    int(self.b4.y / 60)], 1)
                    if self.b5.collidepoint(mouse_pos):
                        self.moves([int(self.b5.x / 60),
                                    int(self.b5.y / 60)], 1)
                    if self.b6.collidepoint(mouse_pos):
                        self.moves([int(self.b6.x / 60),
                                    int(self.b6.y / 60)], 1)
                    if self.b7.collidepoint(mouse_pos):
                        self.moves([int(self.b7.x / 60),
                                    int(self.b7.y / 60)], 1)
                    if self.b8.collidepoint(mouse_pos):
                        self.moves([int(self.b8.x / 60),
                                    int(self.b8.y / 60)], 1)
                    if self.b_reset.collidepoint(mouse_pos):
                        pygame.quit()
示例#34
0
 def take_turn(self, state):
     decider = Minimax.Minimax(state, self.depth)
     move = decider.get_best_move()
     state.perform_action(move)
     return move
示例#35
0
文件: main.py 项目: IDSRosler/FIA
import Minimax
import Node

estado_inicial = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
cont = 0

minimax = Minimax.Minimax()
root = Node.Node(estado_inicial, 9)
minimax.completar_arvore(root, 9)
resultado_minimax = minimax.minimax(root, 9, True)
print("O resultado minimax da raiz do jogo da velha é: {}".format(
    resultado_minimax))
cont = minimax.cont_estados(root, 9)
print("Quantidade de estados existentes: {}".format(cont))