Esempio n. 1
0
def test(args):
    c, n = args
    # settings
    RED, BLUE = 1, 2
    ai_algorithms = ['random', 'mc', 'mc_ucb1', 'uct', 'uct_wm']
    player1_type, player2_type, board_size = sys.argv[1:4]

    # init red player
    if player1_type in ai_algorithms:
        player1 = AI(RED, player1_type)
    else:
        raise TypeError("Wrong player 1 type ")

    # init blue player
    if player2_type in ai_algorithms:
        player2 = AI(BLUE, player2_type)
    else:
        raise Exception("Wrong player 2 type")

    if c != None:
        player2.explorationConstant = c

    board = Board(board_size)
    game = Game(board, player1, player2)
    winner = game.runNoDisplay()

    return winner
Esempio n. 2
0
    def create_players(self, player_type1: str, player_type2: str):
        """
        Instantiates the player objects and assigns them to the appropriate
        instance attributes.

        :param player_type1: Type of player1 - user, easy, medium
        :param player_type2: Type of player2
        """
        difficulties = ['easy', 'medium', 'hard']

        if player_type1 == 'user':
            self.player1 = Human('X')
        elif player_type1 in difficulties:
            self.player1 = AI('X', player_type1)
        else:
            raise InvalidPlayerTypeError(player_type1)

        if player_type2 == 'user':
            self.player2 = Human('O')
        elif player_type2 in difficulties:
            self.player2 = AI('O', player_type2)
        else:
            raise InvalidPlayerTypeError(player_type2)

        self.players = (self.player1, self.player2)
Esempio n. 3
0
File: TTTS.py Progetto: suen/ttts
 def new_game_init(self):
     print "New Game initializing"
     self.game = TicTacToe()
     #self.player1 = AI("artificial agent", "X", self)
     self.player2 = AI("AI agent", "O", self)
     self.game.setPlayer1(self.player1)
     self.game.setPlayer2(self.player2)
     self.game.setFirstMover(self.player1)
     self.startGame = True
     self.playerHasMoved = False
     self.playerMove = None
     print "New Game started"
Esempio n. 4
0
    def do_computer_move(self, player: AI):
        """
        Performs a move for an AI player.

        :param player: (AI) The AI player making the move
        """
        print(f'Making move level "{player.difficulty}"')

        move = player.calculate_move(self.board)
        if not self.is_open_cell(move):
            print(move)
            raise Exception()

        self.board.update_cell(move, player.token)
Esempio n. 5
0
 def prepare_game(self, ai_player_count):
     self.presentation.Hide()
     try:
         if ai_player_count == 0:
             p1 = Human(self.presentation.get_player_name("Player #1"))
             p2 = Human(self.presentation.get_player_name("Player #2"))
             hotseat = True
         elif ai_player_count == 1:
             p1 = Human(self.presentation.get_player_name("Player #1"))
             p2 = AI(self.presentation.get_ai_file("Player #2"))
             hotseat = False
         else:  # ai_player_count == 2:
             p1 = AI(self.presentation.get_ai_file("Player #1"))
             p2 = AI(self.presentation.get_ai_file("Player #2"))
             hotseat = False
     except UserCancelError:
         return
     self.presentation.stop_sonar()
     return_msg = self.run_game([p1, p2], hotseat)
     self.presentation.play_game_over_sound()
     self.presentation.give_message("Game Over", return_msg['msg'])
     self.presentation.Show()
     self.presentation.start_sonar()
Esempio n. 6
0
 def run_headless_tournament_generator(self):
     TARGET_GAME_COUNT = 100
     players = []
     victors_dict = {}
     try:
         paths = self.presentation.get_ai_files()
     except UserCancelError:
         return
     for path in paths:
         try:
             player = AI(path)
         except Exception, data:
             continue
         players.append(path)
         victors_dict[player.name] = 0
Esempio n. 7
0
import numpy as np
from Board import GameBoard, BoardStates
from Player import AI
from Game import Game
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from matplotlib import colors
from tkinter import *
from GameDisplay import GameDisplay


if __name__ == "__main__":
    player_one = AI()
    player_two = AI()
    game = Game(player_one, player_two)

    root = Tk()
    game_display = GameDisplay(game, root)
    root.mainloop()
Esempio n. 8
0
            except Exception, data:
                continue
            players.append(path)
            victors_dict[player.name] = 0
        if not len(players) >= 2:
            msg = 'Must have more than one AI player for tournament mode'
            raise MultipleAiNeededError(msg)
        combinations_len = len(list(combinations(players, 2)))
        iteration_count = TARGET_GAME_COUNT / combinations_len
        yield iteration_count * combinations_len
        counter = 0
        for p1, p2 in combinations(players, 2):
            for i in xrange(iteration_count):
                counter += 1
                yield counter
                result = self.run_game([AI(p1), AI(p2)], hotseat=False)
                winner_name = result['winner'].name
                loser_name = result['loser'].name
                msg = '%s beat %s in round %d' % (winner_name, loser_name,
                                                  counter)
                yield (counter, msg)
                victors_dict[winner_name] += 1
        victors_sorted = sorted(victors_dict, key=lambda k: victors_dict[k])
        victors_sorted.reverse()
        self.presentation.stop_sonar()
        self.presentation.play_game_over_sound()
        self.presentation.show_tournament_results(victors_sorted, victors_dict,
                                                  iteration_count)
        self.presentation.start_sonar()

    def run_game(self, player_config, hotseat):
Esempio n. 9
0
####### Init Game, Players and Board instances #######

#init boardgame
board_size = sys.argv[3]
board = Board(board_size)

#init players
RED, BLUE = 1, 2
player1_type = sys.argv[1]
player2_type = sys.argv[2]
ai_algorithms = ['random', 'mc', 'mc_ucb1', 'uct', 'uct_wm']

if player1_type == 'h':  # h for human
    player1 = Human(RED)
elif player1_type in ai_algorithms:
    player1 = AI(RED, player1_type)
else:
    print('Wrong player type.')
    print(f'Available options: {["h"] + ai_algorithms}.')
    exit()

if player2_type == 'h':
    player2 = Human(BLUE)
elif player2_type in ai_algorithms:
    player2 = AI(BLUE, player2_type)
else:
    print(f'Wrong player type.')
    print(f'Available options: {["h"] + ai_algorithms}.')
    exit()

#####################################################
Esempio n. 10
0
def main():
    """
    The main function from which everything else is run
    """

    global FPS, WINDOW_DIMENSIONS, BACKGROUND_COLOUR

    pygame.init()
    screen = pygame.display.set_mode(WINDOW_DIMENSIONS)
    pygame.display.set_caption('pyConnect4')

    background = pygame.Surface(WINDOW_DIMENSIONS)
    background = background.convert()
    background.fill(BACKGROUND_COLOUR)

    FPSCLOCK = pygame.time.Clock()

    screen.blit(background, (0, 0))

    # Change the following two lines to add a Human() or an AI()
    # The parameter is a string for the name of the player.
    player1 = AI("CPU 1")
    player2 = AI("CPU 2")
    gameBoard = board.Board(player1, player2)

    count = 0  # count for time elapsed
    isDone = False

    while not isDone:
        # draw header and footer
        board.draw_header(gameBoard.PLAYERS, gameBoard.COUNT1,
                          gameBoard.COUNT2, screen)
        board.draw_footer(gameBoard.TURN, gameBoard.PLAYERS, count, screen)
        gameBoard.draw(screen)  # draw the main game board
        pygame.display.flip()  # update the screen
        count += FPSCLOCK.tick(FPS)

        if gameBoard.isAITurn():
            isDone = gameBoard.play()
            pygame.event.clear()  # ignore clicks while the CPU was "thinking"

        for event in pygame.event.get():  # event handling loop
            if event.type == QUIT or \
               (event.type == KEYUP and event.key == K_ESCAPE):
                quit()
            elif event.type == MOUSEBUTTONUP and event.button == 1 and\
                    not gameBoard.isAITurn():
                mousepos = pygame.mouse.get_pos()
                isDone = gameBoard.play(mousepos)
                print("CLICK AT:", mousepos)

    gameBoard.draw(screen)

    message_font = pygame.font.Font(None, 100)
    message_pos = screen.get_rect().centerx

    if isDone == 1:
        message_text = str(gameBoard.PLAYERS[gameBoard.TURN]) + " Wins!"
    else:
        message_text = "Draw!"

    message = message_font.render(message_text, True, (160, 160, 169))
    message_pos = message.get_rect()
    message_pos.centerx = screen.get_rect().centerx
    message_pos.centery = screen.get_rect().centery
    screen.blit(message, message_pos)

    pygame.display.flip()  # update the screen
Esempio n. 11
0
File: TTTS.py Progetto: suen/ttts
class Main:
    def __init__(self):
        config = ConfigParser.RawConfigParser()
        config.read("config.ini")
           
        self.username = config.get('user', 'username');
        self.broadcastAddress = config.get('network', 'broadcastAddress')
        self.UDPPort = int(config.get('network', 'UDPPort'))
        self.TCPPort = int(config.get('network', 'TCPPort'))
        self.WebSocketPort = int(config.get('network', 'WebSocketPort'))

        try:
            self.privateKeyPath = config.get('user', 'privateKey')
            if os.path.isfile(self.privateKeyPath):
                self.rsaKey = RSA.importKey((open(self.privateKeyPath, "r")).read())
                if self.rsaKey is not None :
                    print "RSA Key loaded successfully"
            else:
                self.rsaKey = None
                print "no private found, generate one for distributed score system"
        except ConfigParser.NoOptionError:
            pass
        self.config = config
        
        self.breceiver = BroadcastListener(self)
        
        self.net = Network.Instance()
        self.net.setBroadcastAddress(self.broadcastAddress)
        self.net.setUDPPort(self.UDPPort)
        self.net.setTCPPort(self.TCPPort)
        self.net.setWebSocketPort(self.WebSocketPort)
        self.net.setMain(self)

        self.webClient = None;
        self.startGame = False
        self.board_sent_to_player = False
        self.user = AsyncUser(self)

        self.broadcastReceived = []
        self.lastBroadcastedMsg = ""
            
        signal.signal(signal.SIGINT, self.signal_handler)

        self.die = False
        #self.gameLoopThread = Thread(target=self.run)
        #self.gameLoopThread.start()
        
        Thread(target=self.startWebclient).start()
        
        self.startNetwork()

    def new_game_init(self):
        print "New Game initializing"
        self.game = TicTacToe()
        #self.player1 = AI("artificial agent", "X", self)
        self.player2 = AI("AI agent", "O", self)
        self.game.setPlayer1(self.player1)
        self.game.setPlayer2(self.player2)
        self.game.setFirstMover(self.player1)
        self.startGame = True
        self.playerHasMoved = False
        self.playerMove = None
        print "New Game started"

    def startNetwork(self):
        self.net.startNetwork()
        self.die = True
    
    def startWebclient(self):
        os.system("/usr/bin/google-chrome ../web/index.html")
        return
    
    def connectPeer(self, address, port):
        self.net.connectPeer(address, port);

    def setWebClient(self, client):
        print "new webclient"
        self.user = AsyncUser(self)
        self.user.setWebClient(client);
#        self.player1 = AsyncPlayer("Web Player", "X", self)
#        self.player1.setWebSocket(self.webClient)

    def getPeerList(self):
        return self.net.getPeers()
  
    def getPeerById(self, peerId):
        return self.net.getPeerById(peerId)
    
    def getPeerByIP(self, peerIp):
        return self.net.getPeerByIP(peerIp)
    
    def onPeerListChange(self):
        print "calling self.user for peer change"
        self.user.onPeerListChange()
    
    def sendMessage(self, peerId, message):
        for (id, p, ip) in self.getPeerList():
            if id == peerId:
                p.sendLine(message)
    
    
    def onPeerMsgReceived(self, peerIdentity, msg):
        self.user.onPeerMsgReceived(peerIdentity, msg)
    
    def onBroadcastReceived(self, msgTuple):
        datagram,peerIdentity = msgTuple;
        
        broadcastingPeer = self.net.getPeerByIP(peerIdentity[0])
        
        if broadcastingPeer is None:
            self.connectPeer(peerIdentity[0], peerIdentity[1]);
            return
        
        if msgTuple not in self.broadcastReceived:
            #self.broadcastReceived.append(msgTuple)
            self.user.onNewBroadcastReceived((broadcastingPeer.peerName, datagram))              
            
    def setOpponentPlayer(self, opponent):
        self.player2 = opponent
        
    def playerNextMove(self, player, move):
        self.playerMove = move
        self.playerHasMoved = True
        return;
    
    def createNewRoom(self, roomName):
        self.gameRoom = GameRoom(roomName)
        print "Creating a new room " + self.gameRoom.getName()


    def reannounceRoom(self):
        print "Multicasting created room " + self.gameRoom.getName()
        self.net.sendMulticast("NEW_ROOM " + self.gameRoom.getName())
    
    def getGameRoom(self):
        return self.gameRoom

    def sendMulticast(self, msg):
        self.net.sendMulticast(msg)
        
    def broadcast(self):
        self.net.broadcast();

    def getUsername(self):
        return self.username
 
    def generateKey(self):
        self.rsaKey = RSA.generate(2048, os.urandom);
    
        fw = open("private.key", "w")
        fw.write(self.rsaKey.exportKey());
        fw.close()
    
        self.config.set("user", "privateKey", "private.key")
        with open("config.ini", "w") as configfile:
            self.config.write(configfile)
        print "RSA Key generated and written to key and included to config.ini"

    def getPublicKey(self):
        return self.rsaKey.publickey()

    def getPublicKeyString(self):
        return self.rsaKey.publickey().exportKey()
 
    def run(self):

        while (self.net is None or 
                self.webClient is None or 
                not self.startGame ):
            print "No game, GameLoopThread sleeping"
            if self.die:
                return
            time.sleep(10)
        
        #self.net.sendDataWebPeers("GAME BOARDSTATE " + str(self.game.board.board))    
        
        if self.game.gameover():
            winner = self.game.getWinner();
            if winner == "":
                #self.net.sendDataWebPeers("GAME GAME_OVER NO_WINNER")
                win_code1 = 0;
                win_code2 = 0;
            else:
                win_code1 = 1 if winner == self.player1.symbol else 2
                win_code2 = 1 if winner == self.player2.symbol else 2

            self.player1.gameover(self.game.board.board, win_code1)
            self.player2.gameover(self.game.board.board, win_code2)

            self.startGame = False
        
        if not self.playerHasMoved:
            if not self.board_sent_to_player: 
                self.game.next_player.makeMove(self.game.board.makeCopy())
                print "Asking for player input"
                self.board_sent_to_player = True
        else:
            coord = self.playerMove
            self.game.makeMove(self.game.next_player, coord)
            self.playerHasMoved = False
            self.playerMove = None
            self.board_sent_to_player = False
        
        time.sleep(1)
        self.run()

    def signal_handler(self, signal, frame):
        print 'KeyBoard Interrupt',signal
        print 'Graceful Exit'
        self.die = True
        reactor.callFromThread(reactor.stop)