Exemple #1
0
class RandomPlayer:
    def __init__(self, color, oponent_color, columns, rows, c, p):
        self.color = color
        self.oponent_color = oponent_color
        self.logicalBoard = LogicalBoard(columns, rows, c, p)

        if not os.path.isdir('log'):
            os.mkdir('log')
        self.log_file = open('log/random_player_' + self.color + '.log', 'a')

    def move(self, last_move=None):
        if last_move is not None:
            self.log("He moved: " + str(last_move))
            self.logicalBoard.makeMove(self.oponent_color, last_move)

        while True:
            move = randint(0, self.logicalBoard.columns - 1)
            if self.logicalBoard.isValidMove(move):
                break
        self.log("I moved: " + str(move))
        self.logicalBoard.makeMove(self.color, move)
        return move

    def log(self, msg):
        self.log_file.write(str(msg) + "\n")
        self.log_file.flush()
Exemple #2
0
    def __init__(self, color, oponent_color, columns, rows, c, p):
        self.color = color
        self.oponent_color = oponent_color
        self.logicalBoard = LogicalBoard(columns, rows, c, p)

        if not os.path.isdir('log'):
            os.mkdir('log')
        self.log_file = open('log/random_player_' + self.color + '.log', 'a')
Exemple #3
0
 def __init__(self,player1,player2,max_turns,show):
    self.player1 = player1
    self.player2 = player2
    self.logical_board = LogicalBoard()
    self.history_board = []
    self.graphical_board = GraphicalBoard(self.logical_board,self.history_board)
    self.max_turns = max_turns
    self.show = show
Exemple #4
0
    def __init__(self, columns, rows, c, p, player1, player2, show_ui=False):

        self.player1 = player1
        self.player2 = player2

        self.logicalBoard = LogicalBoard(columns, rows, c, p)

        if show_ui:
            self.graphicalBoard = GraphicalBoard(self.logicalBoard)
        else:
            self.graphicalBoard = None

        assert self.graphicalBoard is not None or (not player1.human
                                                   and not player2.human)
Exemple #5
0
    def __init__(self,player1, player2, boardHeight, boardWidth, timeLimit):
        self.timeLimit = timeLimit
        self.logicalBoard = LogicalBoard(boardHeight,boardWidth) 
        self.playerScores = [0,0,0]
        self.draws = 0
        self.graphicalBoard = GraphicalBoard(self.logicalBoard, self.playerScores)

        if player1 is None:
            player1Controller = HumanPlayer(PLAYER1, self.graphicalBoard)
        else:
            player1Controller = BotPlayer(player1,PLAYER1,timeLimit)

        if player2 is None:
            player2Controller = HumanPlayer(PLAYER2, self.graphicalBoard)
        else:
            player2Controller = BotPlayer(player2,PLAYER2,timeLimit)

        self.players = [player1Controller,player2Controller]
Exemple #6
0
    def __init__(self,
                 columns,
                 rows,
                 steps,
                 team_A,
                 team_B,
                 quites_A,
                 quites_B,
                 show_ui=True):

        self.team_A = team_A
        self.team_A.players = zip(range(len(quites_A)), quites_A)
        self.team_B = team_B
        self.team_B.players = zip(range(len(quites_B)), quites_B)

        self.steps = steps

        self.logicalBoard = LogicalBoard(columns, rows, self.team_A.players,
                                         self.team_B.players)

        if show_ui:
            self.graphicalBoard = GraphicalBoard(self.logicalBoard)
        else:
            self.graphicalBoard = None
Exemple #7
0
class RandomPlayer_test:
    def __init__(self, color, oponent_color, columns, rows, c, p, probability):
        self.color = color
        self.oponent_color = oponent_color
        self.logicalBoard = LogicalBoard(columns, rows, c, p)
        self.probability = probability

        if not os.path.isdir('log'):
            os.mkdir('log')
        self.log_file = open('log/random_player_' + self.color + '.log', 'a')

    def move(self, last_move=None):
        if last_move is not None:
            self.log("He moved: " + str(last_move))
            self.logicalBoard.makeMove(self.oponent_color, last_move)

        move = None
        inteligente = False
        if random() < self.probability:
            inteligente = True

        if inteligente:
            move = self.get_win_move(self.color)
            if move is None:
                move = self.get_win_move(self.oponent_color)

        if move is None:
            aux = []
            while True:
                move = randint(0, self.logicalBoard.columns - 1)
                if (move in aux and len(aux) < self.logicalBoard.columns):
                    continue

                aux.append(move)

                if self.logicalBoard.isValidMove(move):

                    self.logicalBoard.makeMove(self.color, move)
                    puedeganar = self.get_win_move(self.oponent_color)
                    self.logicalBoard.undoMove(move)

                    if puedeganar is None:
                        break

                    if len(aux) >= self.logicalBoard.columns:
                        break

                    if not inteligente:
                        break

        self.log("I moved: " + str(move))
        self.logicalBoard.makeMove(self.color, move)
        return move

    def log(self, msg):
        self.log_file.write(str(msg) + "\n")
        self.log_file.flush()

    def get_win_move(self, player_color):

        for i in range(self.logicalBoard.columns):
            if self.logicalBoard.isValidMove(i):
                self.logicalBoard.makeMove(player_color, i)
                if self.logicalBoard.isWinner(player_color):
                    self.logicalBoard.undoMove(i)
                    return i
                self.logicalBoard.undoMove(i)
        return None
Exemple #8
0
class Referee:
    def __init__(self,
                 columns,
                 rows,
                 steps,
                 team_A,
                 team_B,
                 quites_A,
                 quites_B,
                 show_ui=True):

        self.team_A = team_A
        self.team_A.players = zip(range(len(quites_A)), quites_A)
        self.team_B = team_B
        self.team_B.players = zip(range(len(quites_B)), quites_B)

        self.steps = steps

        self.logicalBoard = LogicalBoard(columns, rows, self.team_A.players,
                                         self.team_B.players)

        if show_ui:
            self.graphicalBoard = GraphicalBoard(self.logicalBoard)
        else:
            self.graphicalBoard = None

    def runPlay(self,
                starting_team,
                seconds_between_steps=SECONDS_BETWEEN_STEPS,
                last_graphical_delay=LAST_GRAPHICAL_DELAY):
        self.team_A.starting_positions = self.team_A.startGame(
            self.logicalBoard.columns, self.logicalBoard.rows, self.steps,
            SIDE[A], self.team_A.players, self.team_B.players)
        self.team_B.starting_positions = self.team_B.startGame(
            self.logicalBoard.columns, self.logicalBoard.rows, self.steps,
            SIDE[B], self.team_B.players, self.team_A.players)

        self.logicalBoard.reset(self.team_A.starting_positions,
                                self.team_B.starting_positions, starting_team)
        self.update_canvas()

        for step in range(self.steps):
            print "Step: ", step
            board_state_A = self.logicalBoard.getState()
            board_state_B = self.logicalBoard.getState()
            moves_A = self.team_A.move(board_state_A)
            moves_B = self.team_B.move(board_state_B)

            starter = self.logicalBoard.makeMove(moves_A, moves_B)

            self.update_canvas()

            if starter is not None:
                sleep(seconds_between_steps)
                self.logicalBoard.startingPositions(
                    self.team_A.starting_positions,
                    self.team_B.starting_positions, starter)
                self.update_canvas()

            sleep(seconds_between_steps)

        winner = self.logicalBoard.winner()
        self.team_A.finished(winner)
        self.team_B.finished(winner)

        if self.graphicalBoard is not None:
            self.graphicalBoard.finished(winner)

        sleep(last_graphical_delay)
        return winner

    def update_canvas(self):
        if self.graphicalBoard is not None:
            self.graphicalBoard.draw()

    def exit(self):
        self.team_A.done()
        self.team_B.done()
        sys.exit()
class Referee:
    def __init__(self, columns, rows, c, p, player1, player2, show_ui=False):

        self.player1 = player1
        self.player2 = player2

        self.logicalBoard = LogicalBoard(columns, rows, c, p)

        if show_ui:
            from GraphicalBoard import *
            self.graphicalBoard = GraphicalBoard(self.logicalBoard)
        else:
            self.graphicalBoard = None

        assert self.graphicalBoard is not None or (not player1.human
                                                   and not player2.human)

    def runPlay(self, first_player):

        self.logicalBoard.reset()
        if self.graphicalBoard is not None:
            self.graphicalBoard.draw()

        self.last_move = None
        self.turn = first_player.color

        self.player1.startGame(self.logicalBoard.columns,
                               self.logicalBoard.rows, self.logicalBoard.c,
                               self.logicalBoard.p,
                               self.turn == self.player1.color)
        self.player2.startGame(self.logicalBoard.columns,
                               self.logicalBoard.rows, self.logicalBoard.c,
                               self.logicalBoard.p,
                               self.turn == self.player2.color)

        while True:  # main game loop

            # Checks if the human wants to exit
            if self.graphicalBoard is not None:
                self.check_exit(self.graphicalBoard.check_user_exits())

            # Select correct player to move
            if self.turn == self.player1.color:
                player = self.player1
                oponent = self.player2
            else:
                player = self.player2
                oponent = self.player1

            # make the player move
            if player.human:  # if human playing graphical board exists, previously checked by the __init__ assert
                self.last_move = self.graphicalBoard.getHumanMove(player.color)
                self.check_exit(self.last_move)
            else:
                column = player.move(self.last_move)
                if self.graphicalBoard is not None:
                    self.graphicalBoard.animateComputerMove(
                        column, player.color)
                else:
                    self.logicalBoard.makeMove(player.color, column)
                self.last_move = column

            # check if the game has reached the end
            if self.logicalBoard.isWinner(player.color):
                winner = player.color
                player.finished(WIN)
                oponent.finished(LOSE)
                break
            elif self.logicalBoard.isWinner(oponent.color):
                winner = oponent.color
                player.finished(LOSE)
                oponent.finished(WIN)
                break
            elif self.logicalBoard.isBoardFull(
            ) or not self.logicalBoard.availableMoves():
                winner = None
                player.finished(TIE)
                oponent.finished(TIE)
                break

            # switch to other player's turn
            self.turn = oponent.color

        if self.graphicalBoard is not None:
            status = self.graphicalBoard.finished(winner)
            self.check_exit(status)

    def check_exit(self, status):
        if status == EXIT:
            self.exit()

    def exit(self):
        self.player1.done()
        self.player2.done()
        sys.exit()
Exemple #10
0
class Referee:
    def __init__(self,player1,player2,max_turns,show):
       self.player1 = player1
       self.player2 = player2
       self.logical_board = LogicalBoard()
       self.history_board = []
       self.graphical_board = GraphicalBoard(self.logical_board,self.history_board)
       self.max_turns = max_turns
       self.show = show

    def get_bot_move(self,player_bot,player_turn):
        info = self.logical_board.get_info()
        player_bot.send(str(len(info))) 
        for t in info:
            player_bot.send(str(t))
            #print(str(t))
        move = player_bot.receive(str).split()

        #print("------ " + str(player_turn) + " " + str(move[0]) + " " + str(move[1]) + " " + str(move[2]) + " " + str(move[3]) + " " + str(move[4]) + " ------")
        
        if len(move) == 0:
            return True

        self.graphical_board.do_bot_move(player_turn,Point(int(move[0]),int(move[1])),Point(int(move[2]),int(move[3])),int(move[4]),self.show)
     
        return False

    def play_game(self,first_player):

        self.history_board.clear()

        self.logical_board.reset()
     
        player_turn = first_player
        
        if self.show == 1:
            self.graphical_board.draw(first_player)
         
        invalid_action = False

        turns = 0

        while not self.graphical_board.terminated and not invalid_action and not self.logical_board.game_finished() and turns < self.max_turns:
            
            invalid_action = False
            
            self.history_board.append(copy.deepcopy(self.logical_board))

            if player_turn == Player.PLAYER0:
                if self.player1.human == True:
                    self.graphical_board.get_human_move(Player.PLAYER0)
                else:
                    invalid_action = self.get_bot_move(self.player1,Player.PLAYER0)

                player_turn = Player.PLAYER1
            else:
                if self.player2.human == True:
                    self.graphical_board.get_human_move(Player.PLAYER1)
                else:
                    invalid_action = self.get_bot_move(self.player2,Player.PLAYER1)

                player_turn = Player.PLAYER0

            if invalid_action == True:
                player_turn = Player.PLAYER0 if player_turn == Player.PLAYER1 else Player.PLAYER1
            
            turns = len(self.history_board)

        if not self.player1.human:
            self.player1.send("-1")
        if not self.player2.human:
            self.player2.send("-1")

        if turns == self.max_turns:
            return (DRAW,invalid_action)

        return (WIN_GOLD,invalid_action) if player_turn == Player.PLAYER1 else (WIN_WHITE,invalid_action)

    def play_games(self,games,first_turn_str):
         
        first_turn = Player.PLAYER0 if first_turn_str == GOLD else Player.PLAYER1

        if not self.player1.human:
            self.player1.send("0 " + str(games))

        if not self.player2.human:
            self.player2.send("1 " + str(games))

        last_winner = -1

        wins_player1 = 0
        wins_player2 = 0
        draws = 0

        while games > 0 and self.graphical_board.terminated == False:

            if not self.player1.human:
                self.player1.send(str(last_winner))
            if not self.player2.human:
                self.player2.send(str(last_winner))

            (last_winner,invalid_action) = self.play_game(first_turn)

            first_turn = (first_turn+1)%2

            games-=1

            if last_winner == DRAW:
                draws+=1
                print("Max amount of turns reached, it is a draw!")
            elif last_winner == WIN_GOLD:
                wins_player1+=1
                print(self.player1.id + " player won!")
            elif last_winner == WIN_WHITE:
                wins_player2+=1
                print(self.player2.id + " player won!")
        
            print("Wins for " + GOLD + " player: " + str(wins_player1))
            print("Wins for " + WHITE + " player: " + str(wins_player2))

            if invalid_action == True:
                if last_winner == DRAW:
                    print("Max amount of turns reached, it is a draw!")
                elif last_winner == WIN_GOLD:
                    wins_player1 += games
                    print(WHITE + " player timeouted!")
                elif last_winner == WIN_WHITE:
                    wins_player2 += games
                    print(GOLD + " player timeouted!")
        
                self.player1.finish()
                self.player2.finish()
                games = 0
            
            if self.graphical_board.terminated == True:
                self.player1.finish()
                self.player2.finish()


                
        print("Final results:")
        print("Wins for " + GOLD + " player: " + str(wins_player1))
        print("Wins for " + WHITE + " player: " + str(wins_player2))
        print("Draws: " + str(draws))
        if wins_player1 > wins_player2:        
            print(self.player1.id + " player wins the match!")
        elif wins_player1 < wins_player2:        
            print(self.player2.id + " player wins the match!")
        else:
            print("None won the match,it is a draw!")

    def state_info(self,info : list) -> str:
        state_str = ""
        for t in info:
            state_str += str(t) + " "
        state_str = state_str[:-1]
        return state_str
Exemple #11
0
class Referee:
    def __init__(self,player1, player2, boardHeight, boardWidth, timeLimit):
        self.timeLimit = timeLimit
        self.logicalBoard = LogicalBoard(boardHeight,boardWidth) 
        self.playerScores = [0,0,0]
        self.draws = 0
        self.graphicalBoard = GraphicalBoard(self.logicalBoard, self.playerScores)

        if player1 is None:
            player1Controller = HumanPlayer(PLAYER1, self.graphicalBoard)
        else:
            player1Controller = BotPlayer(player1,PLAYER1,timeLimit)

        if player2 is None:
            player2Controller = HumanPlayer(PLAYER2, self.graphicalBoard)
        else:
            player2Controller = BotPlayer(player2,PLAYER2,timeLimit)

        self.players = [player1Controller,player2Controller]

    def playGame(self,games, first):
        
        for player in self.players:
            player.send(2*games)
            player.send(player.id)
            player.send(self.logicalBoard.height)
            player.send(self.logicalBoard.width)
            player.send(self.timeLimit)
        
        for round in range(games):
            self.logicalBoard.startNewGame(first)
            #print(self.logicalBoard.boardToString())
            matchScores = [0,0]
            for match in range(2):
                #print("match:",match)
                self.logicalBoard.resetGame(first)
                winner = self.playRound(round,first)

                if self.graphicalBoard.terminated == True:
                    break

                matchScores[winner]+=1
                first = self.nextRoundPlayer(first)

            if matchScores[0]>matchScores[1]:
                self.playerScores[0]+=1
            elif matchScores[1]>matchScores[0]:
                self.playerScores[1]+=1
            else:
                self.playerScores[2]+=1

        print("Final score:")
        print("Player 0: ",self.playerScores[0])
        print("Player 1: ",self.playerScores[1])
        print("Draws: ", self.playerScores[2])

    def playRound(self,round,first):
        
        self.graphicalBoard.draw()

        winner = -1
        while not self.logicalBoard.isGameDone():
            playerTurn = self.logicalBoard.playerTurn
            #print("Player turn",playerTurn)
            currentPlayer = self.players[playerTurn]
            currentPlayer.send(-1)

            stringBoard = self.logicalBoard.boardToString()
            currentPlayer.send(stringBoard)
            
            #for player in self.players:
            #    currentPlayer.send(self.logicalBoard.playerToString(player.id))

            response = currentPlayer.receive(self.formatAction)
            
            if self.graphicalBoard.terminated == True:
                self.players[0].finish()
                self.players[1].finish()
                break

            if not self.logicalBoard.isValidAction(response):
                print(f"Invalid action for player {playerTurn}")
                winner = self.nextRoundPlayer(playerTurn)
                break
            
            self.graphicalBoard.animateAction(response)
            self.logicalBoard.doAction(response)
      
        if self.logicalBoard.isGameDone():
            winner = self.logicalBoard.getWinner()

        playerTurn = self.logicalBoard.playerTurn

        self.players[playerTurn].send(winner)
        self.players[self.nextRoundPlayer(playerTurn)].send(winner)

        return winner

    def nextRoundPlayer(self,first):
        if first == PLAYER1:
            return PLAYER2
        else:
            return PLAYER1

    
    def formatAction(self,action):
        data = action.split(' ')

        if len(data) != 4:
            return Action(Point(-1,-1),Point(-1,-1))
        
        toX = int(data[0])
        toY = int(data[1])
        removeX = int(data[2])
        removeY = int(data[3])

        return Action(Point(toX, toY), Point(removeX, removeY))