Пример #1
0
    def __init__(self):
        self.board = othello_board.OthelloBoard()

        print()
        self.board.draw()
        self.display_score()
        print()

        self.my_token = self.get_my_color()

        print()

        self.ai_token = B if self.my_token == W else W
        self.arti = ai.AI(self.ai_token, self.board)

        self.next_player = B

        while (self.board.has_move(W) or self.board.has_move(B)):
            if (not self.board.has_move(W) and self.next_player == W):
                print(
                    "Sorry, you could not make a move WHITE and your turn is skipped."
                )
                self.next_player = B
                continue
            elif (not self.board.has_move(B) and self.next_player == B):
                print(
                    "Sorry, you could not make a move BLACK and your turn is skipped."
                )
                self.next_player = W
                continue

            if self.next_player == self.my_token:
                self.do_human_turn()
            elif self.next_player == self.ai_token:
                self.do_ai_turn()
            else:
                print("Oh shoot, this isn't good")
                sys.exit(0)

            if self.next_player == B:
                self.next_player = W
            else:
                self.next_player = B

        print('Game end due to no more possibles moves')
Пример #2
0
    def __init__(self, player, network=None, game_mode='singleplayer',
                 game_type='blitz'):

        self.network = network
        self.game_mode = game_mode
        self.game_type = game_type

        if self.network is not None:
            self.get_game_state()
        else:
            self.game_state = engine.GameState(game_mode=self.game_mode,
                                               game_type=self.game_type)

        self.looking_for_ai_move = False
        self.move_made = False
        self.mouseup = None
        self.mousedown = None
        self.piece_selected = None
        self.piece_selected_square = ()
        self.piece_held = None
        self.piece_held_origin = ()

        #self.human_player_one = human_player_one
        #self.human_player_two = human_player_two
        #self.human_turn = self.human_player_one

        if self.game_mode == 'singleplayer':
            self.comp = ai.AI()
            self.moves_to_execute_ai = []
        else:
            self.comp = None
            self.moves_to_execute_ai = None

        self.player_one = True if player == 0 else False
        self.player_two = not self.player_one
        self.human_turn = self.player_one
        self.moves_to_execute = []
        #self.moves_to_execute_two = [] if game_mode == 'doubleplayer' else
        # None

        self.undo_moves = False  # True if self.game_type == 'standard' else
        # False

        self.prog_running = True
Пример #3
0
def salvis(self, trace_set_paths, model_type, vis_type, conf):
    """
    Visualize the salience of an AI.
    :param self:
    :param trace_set_paths: List of trace set paths to be used as possible examples for the saliency visualization.
    :param model_type: Type of model to load for this configuration.
    :param conf: Configuration of the model (required preprocessing actions, architecture, etc.).
    :return:
    """
    logger.info("Loading model")
    model = ai.AI(conf, model_type)
    model.load()

    logger.info("Resolving traces")
    resolve_paths(trace_set_paths)
    examples_iterator, _ = aiiterators.get_iterators_for_model(
        model_type,
        trace_set_paths, [],
        conf,
        hamming=conf.hamming,
        subtype=None,
        request_id=self.request.id)

    logger.info("Retrieving batch of examples")
    trace_set = examples_iterator.get_all_as_trace_set(
        limit=int(conf.saliency_num_traces / 256))
    examples_batch = AIInput(conf).get_trace_set_inputs(trace_set)
    examples_batch = examples_batch[0:conf.saliency_num_traces, :]
    if len(examples_batch.shape) != 2:
        raise ValueError(
            "Expected 2D examples batch for saliency visualization.")

    if conf.saliency_remove_bias:
        examples_batch = examples_batch[:, 1:]
    kerasvis = True if vis_type == 'kerasvis' else False

    return SalvisResult(examples_batch=examples_batch,
                        gradients=saliency.get_gradients(conf,
                                                         model,
                                                         examples_batch,
                                                         kerasvis=kerasvis))
Пример #4
0
    def __init__(self, pits: List[uipit.UiPit], title_text: Label) -> None:
        """
        init the class
        :param pits: the ui pits to change them from the
        :param title_text: the title of the game instructions
        """
        self.backup = None
        self.pit_to_index = {}
        self.pits = pits
        self.board_data = pit_board.PitBoard(pits)
        self.ai_logic = ai.AI(self)
        self.title = title_text
        self.board_mutex = Lock()

        self.ui_funcs = {
            UiMethodsIndexes.UPDATE_TEXT: self.update_pit,
            UiMethodsIndexes.ENABLE_PIT: self.enable_pit,
            UiMethodsIndexes.DISABLE_PIT: self.disable_pit,
            UiMethodsIndexes.CHANGE_TITLE: self.update_title,
            UiMethodsIndexes.TAKE_OPPONENT_STONES: self.steal_stones,
            UiMethodsIndexes.ANOTHER_TURN: self.another_turn
        }

        instructions = self.board_data.set_turn()
        # make move by reading data impact
        self.call_instructions(instructions)

        node = self.board_data.pits_link_list.start
        for index, pit in enumerate(pits):
            self.pit_to_index[pit] = index

            stones = defs.START_STONES_PER_PIT
            if index == 0 or index == len(pits) - 1:
                stones = defs.START_STONES_PER_JACKPOT

            pit.update_text(stones)
            node = node.right_node

        # if ai start
        if self.board_data.now_turn:
            self.play_ai()
Пример #5
0
    def __init__(self):
        self.robot = ai.AI()
        pygame.init()
        pygame.key.set_repeat(250, 25)
        self.width = cell_size * (cols + 6)
        self.height = cell_size * rows
        self.rlim = cell_size * cols
        self.bground_grid = [[
            8 if x % 2 == y % 2 else 0 for x in xrange(cols)
        ] for y in xrange(rows)]

        self.default_font = pygame.font.Font(pygame.font.get_default_font(),
                                             12)

        self.screen = pygame.display.set_mode((self.width, self.height))
        pygame.event.set_blocked(pygame.MOUSEMOTION)  # We do not need
        # mouse movement
        # events, so we
        # block them.
        self.next_stone = tetris_shapes[rand(len(tetris_shapes))]
        self.init_game()
Пример #6
0
 def __init__(self):
     self.running = True
     self.state = {}
     self.game = None
     self.last_mine_count = 0
     self.last_gold = 0
     self.last_life = 0
     self.hero_move = None
     self.hero_last_move = None
     self.action = None
     self.last_action = None
     self.path_to_goal = []
     self.decision = []
     self.nearest_enemy_pos = None
     self.nearest_mine_pos = None
     self.nearest_tavern_pos = None
     self.last_nearest_enemy_pos = None
     self.last_nearest_mine_pos = None
     self.last_nearest_tavern_pos = None
     self.last_pos = None
     # The A.I, Skynet's rising !
     self.ai = ai.AI()
Пример #7
0
    def __init__(self):

        # initialize players
        import ai, human
        self.player1 = ai.AI()
        self.player2 = human.Human()

        # randomize mystery stack
        nums = []
        for n in range(self.cardMin, self.cardMax + 1):
            nums.append(n)

        while len(nums) > 0:
            n = nums[random.randrange(0, len(nums))]
            self.mysteryStack.append(n)
            nums.remove(n)

        # deal cards to each rack
        for i in range(0, self.rackLength):
            self.p1Rack.append(self.mysteryStack.pop())
            self.p2Rack.append(self.mysteryStack.pop())

        # allow AI to perform initial setup
        self.player1.determineStaticValues(self.p1Rack)
Пример #8
0
def main():

    # DEBUG:

    rack = [45, 30, 46, 31, 47, 48, 12, 17, 50, 37]

    a = ai.AI()
    a.determineStaticValues(rack)
    print "Statics: ", a.getStatics()

    while True:
        print "\nRack: ", rack
        print "Statics: ", a.getStatics()

        choice = int(raw_input("Enter card: "))

        pos = a.findPosition(choice, rack)

        if pos == None:
            print "Card rejected"
        else:
            print "Inserting at position ", pos, " (exchange for ", rack[
                pos], ")"
            rack[pos] = choice
Пример #9
0
    def branch(self, x, y):
        '''
        Creates different game states which control what the turtle does.
        '''
        x = int(x)
        y = int(y)
        # self.state = 1
        if self.playon.no_input == False:
            if self.state == 0:
                self.playon.set_players(x, y)
                self.board.initialize_board()
                self.graphics.create_board()
                self.graphics.during_game()
                if self.playon.ai_play() == True:
                    self.graphics.end_game()
                    self.state = 2
                else:
                    self.state = 1
            elif self.state == 1:
                if self.playon.human_play(x, y) == True:
                    self.graphics.end_game()
                    self.state = 2
                else:
                    if self.playon.ai_play() == True:
                        self.graphics.end_game()
                        self.state = 2
            else:
                self.state = 0
                self.board = board.Board(self)
                self.graphics = graphics.Graphics(self)
                self.playon = playon.PlayOn(self)
                self.ai = ai.AI(self)

                self.graphics.initialize_game()
                self.board.initialize_board()
                print('\nGame initialized\n')
Пример #10
0
        # Command interpreter thread
        thread_command_interpreter = command_interpreter.CommandInterpreter(
            shared.q_command_interpreter)
        thread_command_interpreter.start()

        # Console input thread
        thread_console_input = console.ConsoleInput()
        thread_console_input.daemon = True
        thread_console_input.start()

        # Pong thread
        thread_pong = pong.Pong(shared.q_pong)
        thread_pong.start()

        # AI thread
        thread_ai = ai.AI(shared.q_ai)
        thread_ai.start()

        # Player thread
        thread_player = player.Player(shared.q_player)
        thread_player.start()

        # PROGRAM RUNS HERE TILL EXIT

        # wait for all threads to be stopped with their various exit signals
        # (except for threads which are daemonic and will be killed by sys.exit)
        thread_console_output.join()
        thread_command_interpreter.join()
        sys.exit()

    except Exception as e:
Пример #11
0
def runGame(USERDATA, useHintBox=False):
    theBag = bag.Bag()

    theBoard = board.Board()

    players = []

    h = heuristic.notEndGameHeuristic(heuristic.tileQuantileHeuristic(.5, 1.0))

    players.append(human.Human("Player", theBoard, theBag))
    players.append(ai.AI(theBoard, theBag, theHeuristic=h, theDifficulty=10.0))
    #players.append(ai.AI(theBoard, theBag))

    active = 0

    computerTurn = isinstance(players[active], ai.AI)
    firstTurn = True
    gameOver = False

    gameMenu = menu.GameMenu(useHintBox)

    redrawEverything(theBoard, players[active], players, gameOver, gameMenu)

    inHand = None
    stillPlaying = True
    AIstuck = False

    while stillPlaying:

        mouseClicked = False
        mouseMoved = False
        actionKeyHit = False
        shuffleKeyHit = False
        hintKeyHit = False

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEMOTION:
                mouseX, mouseY = event.pos
                mouseMoved = True
            elif event.type == MOUSEBUTTONUP:
                mouseX, mouseY = event.pos
                mouseClicked = True
            elif event.type == KEYUP:
                if event.key == K_SPACE or event.key == K_RETURN:
                    actionKeyHit = True
                if event.key == K_r:
                    shuffleKeyHit = True
                if event.key == K_h and useHintBox:
                    hintKeyHit = True

        #GAME MENU BUTTONS
        if mouseMoved:
            gameMenu.update(mouseX, mouseY)

        if mouseClicked:
            SELECTION = gameMenu.execute(mouseX, mouseY)

            if SELECTION == menu.GameMenu.PLAY_TURN:
                actionKeyHit = True
            elif SELECTION == menu.GameMenu.RESHUFFLE:
                shuffleKeyHit = True
            elif SELECTION == menu.GameMenu.HINT_TURN:
                hintKeyHit = True
            elif SELECTION == menu.GameMenu.MAIN_MENU:
                stillPlaying = False

        if (hintKeyHit or TRAINING_FLAG) and not computerTurn and not gameOver:
            tilesPulled = theBoard.removeTempTiles()
            if tilesPulled != None:
                #take the tiles back
                for t in tilesPulled:
                    players[active].take(t)
            players[active].executeTurn(firstTurn, DISPLAYSURF)
            TICTIC.play()

        if (actionKeyHit or TRAINING_FLAG or computerTurn) and not gameOver:
            #If it's the computer turn, we need to process its move first!
            if computerTurn:
                playedMove = players[active].executeTurn(
                    firstTurn, DISPLAYSURF)
            else:
                playedMove = True

            if playedMove:

                success = players[active].play(firstTurn)
                if success == "END":
                    gameOver = True
                    endGame(players, active, useHintBox, USERDATA)
                elif success:
                    DINGDING.play()
                    players[active].pulseScore()
                    firstTurn = False
                    active += 1
                    if active >= len(players):
                        active = 0
                    computerTurn = isinstance(players[active], ai.AI)
                    #If we were stuck before, we aren't anymore
                    if computerTurn:
                        AIstuck = False
                else:
                    if TRAINING_FLAG:
                        AIstuck = True
                    TICTIC.play()
                    if computerTurn:
                        print "AI thinks it has a good move, but it doesn't"
            else:
                players[active].shuffle()
                #Let the player know the AI shuffled
                players[active].lastScore = 0
                players[active].pulseScore()
                if theBag.isEmpty():
                    AIstuck = True

                active += 1
                if active >= len(players):
                    active = 0
                computerTurn = isinstance(players[active], ai.AI)

            redrawEverything(theBoard, players[active], players, gameOver,
                             gameMenu)

        if (shuffleKeyHit or
            (AIstuck and TRAINING_FLAG)) and not computerTurn and not gameOver:
            SCRIFFLE.play()
            players[active].shuffle()
            active += 1
            if active >= len(players):
                active = 0
            computerTurn = isinstance(players[active], ai.AI)
            #If we're stuck AND the AI is stuck, end the game without subtracting points
            if AIstuck:
                gameOver = True
                endGame(players, active, useHintBox, USERDATA, stuck=True)
            redrawEverything(theBoard, players[active], players, gameOver,
                             gameMenu)

        if mouseClicked and not computerTurn and not gameOver:
            inHand = tileGrab(mouseX, mouseY, inHand, theBoard,
                              players[active])
            redrawEverything(theBoard, players[active], players, gameOver,
                             gameMenu)

        if gameOver and TRAINING_FLAG:  #automatically start a new game for training purposes
            stillPlaying = False

        redrawNecessary(theBoard, players, gameOver)
        pygame.display.update()
Пример #12
0
 def __init__(self, channel, nickname, server, port=6667):
     irc.bot.SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
     self.channel = channel
     self.nick = nickname
     self.ai = ai.AI(nickname)
Пример #13
0
    def setupUi(self, MainWindow, test):
        MainWindow.setObjectName("PFD")
        MainWindow.resize(self.width, self.height)
        w = QWidget(MainWindow)
        w.setGeometry(0, 0, self.width, self.height)

        p = w.palette()
        if self.screenColor:
            p.setColor(w.backgroundRole(), QColor(self.screenColor))
            w.setPalette(p)
            w.setAutoFillBackground(True)
        instWidth = self.width - 160
        instHeight = self.height - 80
        self.a = ai.AI(w)
        self.a.resize(instWidth, instHeight)
        self.a.move(0, 20)

        self.alt_tape = altimeter.Altimeter_Tape(w)
        self.alt_tape.resize(70, instHeight)
        self.alt_tape.move(instWidth - 70, 20)

        self.alt_Box = altimeter.Altimeter_Digit(w)
        self.alt_Box.resize(60, 25)
        self.alt_Box.move(instWidth - 69, (instHeight / 2) + 7.5)

        self.alt_Trend = vsi.Alt_Trend_Tape(w)
        self.alt_Trend.resize(10, instHeight)
        self.alt_Trend.move(instWidth - 80, 20)

        self.alt_setting = altimeter.Altimeter_Setting(w)
        self.alt_setting.resize(90, 20)
        self.alt_setting.move(instWidth - 80, 0)

        self.as_tape = airspeed.Airspeed_Tape(w)
        self.as_tape.resize(70, instHeight)
        self.as_tape.move(0, 20)

        self.as_Trend = vsi.AS_Trend_Tape(w)
        self.as_Trend.resize(10, instHeight)
        self.as_Trend.move(70, 20)

        self.asd_Box = airspeed.Airspeed_Mode(w)
        self.asd_Box.resize(90, 20)
        self.asd_Box.move(0, 0)

        self.asdi_Box = airspeed.Airspeed_Digit(w)
        self.asdi_Box.resize(45, 25)
        self.asdi_Box.move(25, (instHeight / 2) + 7.5)

        self.head_tape = hsi.DG_Tape(w)
        self.head_tape.resize(instWidth, 60)
        self.head_tape.move(0, instHeight + 20)

        self.tC_Tape = tc.TurnCoordinator_Tape(w)
        self.tC_Tape.resize(instWidth / 4, 18)
        self.tC_Tape.move((instWidth - (instWidth / 4)) / 2, 1)

        if test == 'rasp':

            self.ias_warning = pa.Panel_Annunciator(w)
            self.ias_warning.setWARNING_Name("IAS")
            self.ias_warning.resize(70, 20)
            self.ias_warning.move(w.width() - 155, 310)

            self.gyro_warning = pa.Panel_Annunciator(w)
            self.gyro_warning.setWARNING_Name("Gyro")
            self.gyro_warning.resize(70, 20)
            self.gyro_warning.move(w.width() - 75, 310)

            self.mag_warning = pa.Panel_Annunciator(w)
            self.mag_warning.setWARNING_Name("Mag")
            self.mag_warning.resize(70, 20)
            self.mag_warning.move(w.width() - 155, 340)

            self.alt_warning = pa.Panel_Annunciator(w)
            self.alt_warning.setWARNING_Name("Alt")
            self.alt_warning.resize(70, 20)
            self.alt_warning.move(w.width() - 75, 340)

            self.cat_warning = pa.Panel_Annunciator(w)
            self.cat_warning.setWARNING_Name("CAT")
            self.cat_warning.resize(70, 20)
            self.cat_warning.move(w.width() - 155, 370)

            self.oat_warning = pa.Panel_Annunciator(w)
            self.oat_warning.setWARNING_Name("OAT")
            self.oat_warning.resize(70, 20)
            self.oat_warning.move(w.width() - 75, 370)

            self.co = gauges.HorizontalBar(w)
            self.co.name = "Carbon Monoxide"
            self.co.units = "ppm"
            self.co.decimalPlaces = 0
            self.co.lowRange = 0.0
            self.co.highRange = 75.0
            self.co.highWarn = 25.0
            self.co.highAlarm = 50.0
            self.co.lowWarn = 0.0
            self.co.lowAlarm = 0.0
            self.co.resize(150, 70)
            self.co.move(w.width() - 155, 20)
            self.co.value = 0

            self.volt = gauges.HorizontalBar(w)
            self.volt.name = "Volt"
            self.volt.units = "V"
            self.volt.decimalPlaces = 1
            self.volt.lowRange = 9.0
            self.volt.highRange = 16.0
            self.volt.highWarn = 12.9
            self.volt.highAlarm = 14.0
            self.volt.lowWarn = 10.0
            self.volt.lowAlarm = 9.6
            self.volt.resize(150, 70)
            self.volt.move(w.width() - 155, 90)
            self.volt.value = 12

            self.cat = gauges.HorizontalBar(w)
            self.cat.name = "Cockpit air temp"
            self.cat.units = "degC"
            self.cat.decimalPlaces = 1
            self.cat.lowRange = -40.0
            self.cat.highRange = 40.0
            self.cat.highWarn = 30.0
            self.cat.highAlarm = 35.0
            self.cat.lowWarn = -20
            self.cat.lowAlarm = -30
            self.cat.resize(150, 70)
            self.cat.move(w.width() - 155, 160)
            self.cat.value = 15

            self.oat = gauges.HorizontalBar(w)
            self.oat.name = "Outside air temp"
            self.oat.units = "degC"
            self.oat.decimalPlaces = 1
            self.oat.lowRange = -40.0
            self.oat.highRange = 40.0
            self.oat.highWarn = 30.0
            self.oat.highAlarm = 35.0
            self.oat.lowWarn = -20
            self.oat.lowAlarm = -30
            self.oat.resize(150, 70)
            self.oat.move(w.width() - 155, 230)
            self.oat.value = 15

        else:

            self.map_g = gauges.RoundGauge(w)
            self.map_g.name = "MAP"
            self.map_g.decimalPlaces = 1
            self.map_g.lowRange = 0.0
            self.map_g.highRange = 30.0
            self.map_g.highWarn = 28.0
            self.map_g.highAlarm = 29.0
            self.map_g.resize(155, 100)
            self.map_g.move(w.width() - 155, 100)

            self.rpm = gauges.RoundGauge(w)
            self.rpm.name = "RPM"
            self.rpm.decimalPlaces = 0
            self.rpm.lowRange = 0.0
            self.rpm.highRange = 2800.0
            self.rpm.highWarn = 2600.0
            self.rpm.highAlarm = 2760.0
            self.rpm.resize(155, 100)
            self.rpm.move(w.width() - 155, 0)

            self.op = gauges.HorizontalBar(w)
            self.op.name = "Oil Press"
            self.op.units = "psi"
            self.op.decimalPlaces = 1
            self.op.lowRange = 0.0
            self.op.highRange = 100.0
            self.op.highWarn = 90.0
            self.op.highAlarm = 95.0
            self.op.lowWarn = 45.0
            self.op.lowAlarm = 10.0
            self.op.resize(150, 75)
            self.op.move(w.width() - 155, 220)
            self.op.value = 45.2

            self.ot = gauges.HorizontalBar(w)
            self.ot.name = "Oil Temp"
            self.ot.units = "degF"
            self.ot.decimalPlaces = 1
            self.ot.lowRange = 160.0
            self.ot.highRange = 250.0
            self.ot.highWarn = 210.0
            self.ot.highAlarm = 230.0
            self.ot.lowWarn = None
            self.ot.lowAlarm = None
            self.ot.resize(150, 75)
            self.ot.move(w.width() - 155, 300)
            self.ot.value = 215.2

            self.fuel = gauges.HorizontalBar(w)
            self.fuel.name = "Fuel Qty"
            self.fuel.units = "gal"
            self.fuel.decimalPlaces = 1
            self.fuel.lowRange = 0.0
            self.fuel.highRange = 50.0
            self.fuel.lowWarn = 2.0
            self.fuel.resize(150, 75)
            self.fuel.move(w.width() - 155, 380)
            self.fuel.value = 15.2

            self.ff = gauges.HorizontalBar(w)
            self.ff.name = "Fuel Flow"
            self.ff.units = "gph"
            self.ff.decimalPlaces = 1
            self.ff.lowRange = 0.0
            self.ff.highRange = 20.0
            self.ff.highWarn = None
            self.ff.highAlarm = None
            self.ff.lowWarn = None
            self.ff.lowAlarm = None
            self.ff.resize(150, 75)
            self.ff.move(w.width() - 155, 460)
            self.ff.value = 5.2

            cht = gauges.HorizontalBar(w)
            cht.name = "Max CHT"
            cht.units = "degF"
            cht.decimalPlaces = 0
            cht.lowRange = 0.0
            cht.highRange = 500.0
            cht.highWarn = 380
            cht.highAlarm = 400
            cht.resize(150, 75)
            cht.move(w.width() - 155, 540)
            cht.value = 350

            self.egt = gauges.HorizontalBar(w)
            self.egt.name = "Avg EGT"
            self.egt.units = "degF"
            self.egt.decimalPlaces = 0
            self.egt.lowRange = 0.0
            self.egt.highRange = 1500.0
            self.egt.resize(150, 75)
            self.egt.move(w.width() - 155, 620)
            self.egt.value = 1350

        if test == 'normal':
            self.flightData.pitchChanged.connect(self.a.setPitchAngle)
            self.flightData.rollChanged.connect(self.a.setRollAngle)
            self.flightData.headingChanged.connect(self.head_tape.setHeading)
            self.flightData.altitudeChanged.connect(self.alt_tape.setAltimeter)
            self.flightData.altitudeChanged.connect(
                self.alt_Trend.setAlt_Trend)
            #self.flightData.vsiChanged.connect(self.alt_Trend.setAlt_Trend)
            self.flightData.airspeedChanged.connect(self.as_tape.setAirspeed)
            self.flightData.airspeedChanged.connect(self.as_Trend.setAS_Trend)
            self.flightData.airspeedChanged.connect(self.asd_Box.setIAS)
            self.flightData.RPMChanged.connect(self.rpm.setValue)
            self.flightData.MAPChanged.connect(self.map_g.setValue)
            self.flightData.OilPressChanged.connect(self.op.setValue)
            self.flightData.OilTempChanged.connect(self.ot.setValue)
            self.flightData.FuelFlowChanged.connect(self.ff.setValue)
            self.flightData.FuelQtyChanged.connect(self.fuel.setValue)

        elif test == 'fgfs':
            self.timer = QTimer()
            #Timer Signal to run guiUpdate
            QObject.connect(self.timer, SIGNAL("timeout()"), self.guiUpdate)
            # Start the timer 1 msec update
            self.timer.start(6)

            self.thread1 = fgfs.UDP_Process(self.queue)
            self.thread1.start()

        elif test == 'rasp':
            self.timer = QTimer()
            #Timer Signal to run guiUpdate
            QObject.connect(self.timer, SIGNAL("timeout()"), self.guiUpdate)
            # Start the timer 1 msec update
            self.timer.start(6)

            self.thread1 = rasp.GPIO_Process(self.queue)
            self.thread1.start()

            self.thread2 = rasp.VW(self.queue2)
            self.thread2.start()
Пример #14
0
import telepot.telepot as tp
import ai
import state
from os import environ

TOKEN = environ['TOKEN']
bot = tp.Bot(TOKEN)

if not state.local:
    import os
    from flask import Flask, request
    from telepot.telepot.loop import OrderedWebhook

    PORT = os.environ['PORT']
    AI = ai.AI()

    def handle(msg):
        content_type, chat_type, chat_id = tp.glance(msg)
        if content_type == 'text':
            answer = AI.answer(msg['text'], str(chat_id), bot.sendMessage)
            # bot.sendMessage(chat_id, answer)

    app = Flask(__name__)

    webhook = OrderedWebhook(bot, {'chat': handle})

    @app.route('/bot' + TOKEN, methods=['GET', 'POST'])
    def pass_update():
        webhook.feed(request.data)
        return 'OK'
Пример #15
0
import tileController

import grapher

import ai

import viewController

timeController = timeController.TimeController(1)
scoreController = scoreController.ScoreController()
gridController = gridController.GridController(scoreController)
tileController = tileController.TileController(gridController)

grapher = grapher.Grapher(scoreController)

ai = ai.AI(gridController, scoreController, grapher)

viewController = viewController.ViewController(gridController, timeController,
                                               scoreController, ai, grapher)

cTile = tileController.getRandomTile()
nTile = tileController.getRandomTile()
viewController.setTile(cTile, nTile)

while not viewController.abort:
    if timeController.timeEvent():
        if viewController.aiState:
            move, rotate, rating = ai.makeMove(cTile)
        if not cTile.incY():
            cTile.apply()
            if not gridController.checkForGameOver():
Пример #16
0
    def setupUi(self, MainWindow, test):
        MainWindow.setObjectName("PFD")
        MainWindow.resize(config.screenSize[0], config.screenSize[1])

        w = QWidget(MainWindow)
        w.setGeometry(0, 0, config.screenSize[0], config.screenSize[1])

        p = w.palette()
        if config.screenColor:
            p.setColor(w.backgroundRole(), QColor(config.screenColor))
            w.setPalette(p)
            w.setAutoFillBackground(True)
        instWidth = config.screenSize[0] - 410
        instHeight = config.screenSize[1] - 200
        a = ai.AI(w)
        a.resize(instWidth, instHeight)
        a.move(100, 100)

        alt_tape = altimeter.Altimeter_Tape(w)
        alt_tape.resize(100, instHeight)
        alt_tape.move(instWidth + 100, 100)

        as_tape = airspeed.Airspeed_Tape(w)
        as_tape.resize(100, instHeight)
        as_tape.move(0, 100)

        head_tape = hsi.DG_Tape(w)
        head_tape.resize(instWidth, 100)
        head_tape.move(100, instHeight + 100)

        map = gauges.RoundGauge(w)
        map.name = "MAP"
        map.decimalPlaces = 1
        map.lowRange = 0.0
        map.highRange = 30.0
        map.highWarn = 28.0
        map.highAlarm = 29.0
        map.resize(200, 100)
        map.move(w.width() - 200, 100)

        rpm = gauges.RoundGauge(w)
        rpm.name = "RPM"
        rpm.decimalPlaces = 0
        rpm.lowRange = 0.0
        rpm.highRange = 2800.0
        rpm.highWarn = 2600.0
        rpm.highAlarm = 2760.0
        rpm.resize(200, 100)
        rpm.move(w.width() - 200, 0)
        op = gauges.HorizontalBar(w)
        op.name = "Oil Press"
        op.units = "psi"
        op.decimalPlaces = 1
        op.lowRange = 0.0
        op.highRange = 100.0
        op.highWarn = 90.0
        op.highAlarm = 95.0
        op.lowWarn = 45.0
        op.lowAlarm = 10.0
        op.resize(190, 75)
        op.move(w.width() - 200, 220)
        op.value = 45.2

        ot = gauges.HorizontalBar(w)
        ot.name = "Oil Temp"
        ot.units = "degF"
        ot.decimalPlaces = 1
        ot.lowRange = 160.0
        ot.highRange = 250.0
        ot.highWarn = 210.0
        ot.highAlarm = 230.0
        ot.lowWarn = None
        ot.lowAlarm = None
        ot.resize(190, 75)
        ot.move(w.width() - 200, 300)
        ot.value = 215.2

        fuel = gauges.HorizontalBar(w)
        fuel.name = "Fuel Qty"
        fuel.units = "gal"
        fuel.decimalPlaces = 1
        fuel.lowRange = 0.0
        fuel.highRange = 20.0
        fuel.lowWarn = 2.0
        fuel.resize(190, 75)
        fuel.move(w.width() - 200, 380)
        fuel.value = 15.2

        ff = gauges.HorizontalBar(w)
        ff.name = "Fuel Flow"
        ff.units = "gph"
        ff.decimalPlaces = 1
        ff.lowRange = 0.0
        ff.highRange = 20.0
        ff.highWarn = None
        ff.highAlarm = None
        ff.lowWarn = None
        ff.lowAlarm = None
        ff.resize(190, 75)
        ff.move(w.width() - 200, 460)
        ff.value = 5.2

        cht = gauges.HorizontalBar(w)
        cht.name = "Max CHT"
        cht.units = "degF"
        cht.decimalPlaces = 0
        cht.lowRange = 0.0
        cht.highRange = 500.0
        cht.highWarn = 380
        cht.highAlarm = 400
        cht.resize(190, 75)
        cht.move(w.width() - 200, 540)
        cht.value = 350

        egt = gauges.HorizontalBar(w)
        egt.name = "Avg EGT"
        egt.units = "degF"
        egt.decimalPlaces = 0
        egt.lowRange = 800.0
        egt.highRange = 1500.0
        egt.resize(190, 75)
        egt.move(w.width() - 200, 620)
        egt.value = 1350

        if not test:
            self.flightData.pitchChanged.connect(a.setPitchAngle)
            self.flightData.rollChanged.connect(a.setRollAngle)
            self.flightData.headingChanged.connect(head_tape.setHeading)
        else:
            roll = QSlider(Qt.Horizontal, w)
            roll.setMinimum(-180)
            roll.setMaximum(180)
            roll.setValue(0)
            roll.resize(200, 20)
            roll.move(440, 100)

            pitch = QSlider(Qt.Vertical, w)
            pitch.setMinimum(-90)
            pitch.setMaximum(90)
            pitch.setValue(0)
            pitch.resize(20, 200)
            pitch.move(360, 180)

            smap = QSlider(Qt.Horizontal, w)
            smap.setMinimum(0)
            smap.setMaximum(30)
            smap.setValue(0)
            smap.resize(200, 20)
            smap.move(w.width() - 200, 200)

            srpm = QSlider(Qt.Horizontal, w)
            srpm.setMinimum(0)
            srpm.setMaximum(3000)
            srpm.setValue(0)
            srpm.resize(200, 20)
            srpm.move(w.width() - 200, 100)

            heading = QSpinBox(w)
            heading.move(0, instHeight + 100)
            heading.setRange(0, 360)
            heading.setValue(1)
            heading.valueChanged.connect(head_tape.setHeading)

            #headingBug = QSpinBox(w)
            #headingBug.move(650, 680)
            #headingBug.setRange(0, 360)
            #headingBug.setValue(1)
            #headingBug.valueChanged.connect(h.setHeadingBug)

            alt_gauge = QSpinBox(w)
            alt_gauge.setMinimum(0)
            alt_gauge.setMaximum(10000)
            alt_gauge.setValue(0)
            alt_gauge.setSingleStep(10)
            alt_gauge.move(1100, 100)
            alt_gauge.valueChanged.connect(alt_tape.setAltimeter)

            as_gauge = QSpinBox(w)
            as_gauge.setMinimum(0)
            as_gauge.setMaximum(140)
            as_gauge.setValue(0)
            as_gauge.move(10, 100)
            as_gauge.valueChanged.connect(as_tape.setAirspeed)

            pitch.valueChanged.connect(a.setPitchAngle)
            roll.valueChanged.connect(a.setRollAngle)
            smap.valueChanged.connect(map.setValue)
            srpm.valueChanged.connect(rpm.setValue)
Пример #17
0
import ai
logic = ai.AI()
logic.loop()
Пример #18
0
    def setUp(self):
        boardlibrary.init_boards()
        self.Pristine = boardlibrary.boards["Pristine"]
        # initial board
        self.SingleHopsRed = boardlibrary.boards["SingleHopsRed"]
        # Set up for two red single hops
        #           0  1  2  3  4  5  6  7
        #        0  .  b  .  b  .  b  .  b
        #        1  b  .  b  .  b  .  b  .
        #        2  .  b  .  .  .  .  .  b
        #        3  .  .  .  .  .  .  b  .
        #        4  .  .  .  b  .  .  .  r
        #        5  r  .  r  .  r  .  .  .
        #        6  .  r  .  r  .  r  .  r
        #        7  r  .  r  .  r  .  r  .
        self.SingleHopsBlack = boardlibrary.boards["SingleHopsBlack"]
        # Set up for black single hops
        #     0  1  2  3  4  5  6  7
        #  0  .  b  .  b  .  b  .  b
        #  1  b  .  b  .  b  .  b  .
        #  2  .  b  .  .  .  .  .  b
        #  3  .  .  .  .  .  .  r  .
        #  4  .  .  .  b  .  .  .  r
        #  5  r  .  r  .  r  .  .  .
        #  6  .  .  .  r  .  r  .  r
        #  7  r  .  r  .  r  .  r  .
        self.multihop = boardlibrary.boards["multihop"]
        # multihop
        #     0  1  2  3  4  5  6  7
        #  0  .  b  .  b  .  b  .  b
        #  1  b  .  r  .  b  .  .  .
        #  2  .  r  .  .  .  b  .  b
        #  3  .  .  .  .  .  .  .  .
        #  4  .  .  .  r  .  b  .  .
        #  5  .  .  .  .  .  .  r  .
        #  6  .  r  .  r  .  r  .  r
        #  7  r  .  .  .  r  .  .  .
        self.KingBlack = boardlibrary.boards["KingBlack"]
        # KingBlack
        # Black can move to become a King but should
        # not be able to move after being kinged
        #    0  1  2  3  4  5  6  7
        #    0  .  .  .  .  .  .  .  .
        #    1  .  .  .  .  .  .  .  .
        #    2  .  .  .  .  .  .  .  .
        #    3  .  .  .  .  b  .  .  .
        #    4  .  .  .  r  .  r  .  .
        #    5  .  .  .  .  .  .  .  .
        #    6  .  .  .  r  .  r  .  .
        #    7  .  .  .  .  .  .  .  .
        self.BlackKingTour = boardlibrary.boards["BlackKingTour"]
        # BlackKingTour
        #    0  1  2  3  4  5  6  7
        #    0  .  .  .  .  .  .  .  .
        #    1  .  .  .  .  .  .  .  .
        #    2  .  .  .  .  .  .  .  .
        #    3  .  .  .  .  B  .  .  .
        #    4  .  .  .  r  .  r  .  .
        #    5  .  .  .  .  .  .  .  .
        #    6  .  .  .  r  .  r  .  .
        #    7  .  .  .  .  .  .  .  .
        self.RedKingTour = boardlibrary.boards["RedKingTour"]
        # RedKingTour
        # Probably don't need to test this one as rules similar, but...
        #    0  1  2  3  4  5  6  7
        #    0  .  .  .  .  .  .  .  .
        #    1  .  .  .  .  .  .  .  .
        #    2  .  .  .  .  .  .  .  .
        #    3  .  .  .  .  R  .  .  .
        #    4  .  .  .  b  .  b  .  .
        #    5  .  .  .  .  .  .  .  .
        #    6  .  .  .  b  .  b  .  .
        #    7  .  .  .  .  .  .  .  .
        self.StrategyTest1 = boardlibrary.boards["StrategyTest1"]
        # ???
        self.EndGame1 = boardlibrary.boards["EndGame1"]
        # EndGame 1 - Red can easily win
        #       0  1  2  3  4  5  6  7
        #    0     .     .     R     b
        #    1  .     .     .     .
        #    2     .     .     .     .
        #    3  .     .     .     .
        #    4     .     .     .     .
        #    5  .     .     .     .
        #    6     .     .     .     R
        #    7  .     .     .     .
        self.boards = [self.Pristine, self.SingleHopsRed, self.SingleHopsBlack, self.multihop,
                       self.KingBlack, self.BlackKingTour, self.RedKingTour, self.EndGame1]
        self.my_checkerboard = checkerboard.CheckerBoard()
        self.my_ai_red = ai.AI('r', checkerboard.CheckerBoard, 10)
        self.my_ai_black = ai.AI('b', checkerboard.CheckerBoard, 10)

        self.minimax_red = ai.Minimax('r', 'b', 10, self.my_ai_red)
        self.minimax_black = ai.Minimax('b', 'r', 10, self.my_ai_red)
Пример #19
0
 def __init__(self, motigoma):
     gamePlayer.__init__(self, "cpu", motigoma, 4)
     self.ai = syougi_ai.AI(self)
Пример #20
0
    def reset(self):
        self.game.newRound()
        self.makeBoardDisplay()
        self.resetButton.configure(state="disabled")
        self.gameUpdate()

    def setCommand(self, command):
        for r in range(3):
            for c in range(3):
                if not self.game.isValid(r, c):
                    continue

                def helper(r, c):
                    self.buttons[r][c].configure(text={
                        Moves.X: "X",
                        Moves.O: "O"
                    }[self.game.turn])
                    for button in [but for row in self.buttons for but in row]:
                        button.configure(command=lambda: None)
                    command(r, c)

                self.buttons[r][c].configure(command=ft.partial(helper, r, c))


if __name__ == "__main__":
    game = GameApp()
    game.title("Game is Solved")
    game.registerPlayers(players.BasicHuman("Alex", game.game, game),
                         ai.AI("Jak", game.game))
    game.mainloop()
Пример #21
0
from PIL import Image
from PIL import ImageGrab
import match as matchApp
import card as cardApp
import winapi as winApp
import ai as aiApp
import experience as exApp
from posdef import *
import time
import copy
import traceback

timecount = 0

model0 = aiApp.AI('model/L0/best618', [1517, 1000, 200], False, 50)
model1 = aiApp.AI('model/F1/best457', [1517, 1000, 200], False, 50)
model2 = aiApp.AI('model/F2/best443', [1517, 1000, 200], False, 50)

AI = [model0, model1, model2]

handCardImg = [0] * 15
playCardImg = [0] * 15
remainCardImg = [0] * 15

gameinfo = {}
gameinfo['turn'] = 0  # 当前轮到谁出牌(地主为0)
gameinfo['last'] = 0  # 上一个出牌的人
gameinfo['handCard'] = [None, None, None]  # 每个人的手牌(自己的手牌全纪录,另外两家的手牌都记录可能的牌总数)
gameinfo['handRemain'] = [0, 0, 0]  # 每个人的剩余牌数
gameinfo['lastCard'] = [0] * 15  # 上一个出牌人出的牌
gameinfo['remainCard'] = [0] * 15  # 三张底牌
Пример #22
0
        self.screen = pygame.display.set_mode(self.size)
        self.paddleA = Paddle(self.WHITE, 10, 100)
        self.paddleA.rect.x = 30
        self.paddleA.rect.y = 300
        self.paddleB = Paddle(self.WHITE, 10, 100)
        self.paddleB.rect.x = 470
        self.paddleB.rect.y = 300
        self.ball = Ball(self.WHITE, 20, 20)
        self.ball.rect.x = 250
        self.ball.rect.y = 300
        self.all_sprites_list = pygame.sprite.Group()
        self.all_sprites_list.add(self.paddleA)
        self.all_sprites_list.add(self.paddleB)
        self.all_sprites_list.add(self.ball)
        self.winner = "No one yet"

        self.done = False
        self.scoreA = 0
        self.scoreB = 0

        rgbarray = pygame.surfarray.array3d(pygame.display.get_surface())
        info = [
            rgbarray, self.paddleA.rect, self.paddleB.rect, self.ball.rect, 0,
            self.done
        ]


player_one = ai.AI("weights_one.txt", "weights_two.txt")
game = Game(player_one, None, True)
game.runComp()
Пример #23
0
 def start_ai(self):
     '''
     Initializes the AI
     '''
     num = random.randint(0, 1)
     self.engine = ai.AI(num, 5)
Пример #24
0
 def __init__(self, *args, **kwargs):
     Person.__init__(self, *args, **kwargs)
     self.ai = ai.AI(self)
Пример #25
0
    def setupUi(self, MainWindow, test):
        MainWindow.setObjectName("PFD")
        MainWindow.resize(self.width, self.height)
        w = QWidget(MainWindow)
        w.setGeometry(0, 0, self.width, self.height)

        p = w.palette()
        if self.screenColor:
            p.setColor(w.backgroundRole(), QColor(self.screenColor))
            w.setPalette(p)
            w.setAutoFillBackground(True)
        instWidth = self.width - 410
        instHeight = self.height - 200
        self.a = ai.AI(w)
        self.a.resize(instWidth, instHeight)
        self.a.move(100, 100)

        self.alt_tape = altimeter.Altimeter_Tape(w)
        self.alt_tape.resize(90, instHeight)
        self.alt_tape.move(instWidth + 110, 100)

        self.alt_Trend = vsi.Alt_Trend_Tape(w)
        self.alt_Trend.resize(10, instHeight)
        self.alt_Trend.move(instWidth + 100, 100)

        self.alt_setting = altimeter.Altimeter_Setting(w)
        self.alt_setting.resize(90, 100)
        self.alt_setting.move(instWidth + 110, instHeight + 100)

        self.as_tape = airspeed.Airspeed_Tape(w)
        self.as_tape.resize(90, instHeight)
        self.as_tape.move(0, 100)

        self.as_Trend = vsi.AS_Trend_Tape(w)
        self.as_Trend.resize(10, instHeight)
        self.as_Trend.move(90, 100)

        self.asd_Box = airspeed.Airspeed_Mode(w)
        self.asd_Box.resize(90, 100)
        self.asd_Box.move(0, instHeight + 100)

        self.head_tape = hsi.DG_Tape(w)
        self.head_tape.resize(instWidth, 100)
        self.head_tape.move(100, instHeight + 100)

        self.map_g = gauges.RoundGauge(w)
        self.map_g.name = "MAP"
        self.map_g.decimalPlaces = 1
        self.map_g.lowRange = 0.0
        self.map_g.highRange = 30.0
        self.map_g.highWarn = 28.0
        self.map_g.highAlarm = 29.0
        self.map_g.resize(200, 100)
        self.map_g.move(w.width() - 200, 100)

        self.rpm = gauges.RoundGauge(w)
        self.rpm.name = "RPM"
        self.rpm.decimalPlaces = 0
        self.rpm.lowRange = 0.0
        self.rpm.highRange = 2800.0
        self.rpm.highWarn = 2600.0
        self.rpm.highAlarm = 2760.0
        self.rpm.resize(200, 100)
        self.rpm.move(w.width() - 200, 0)

        self.op = gauges.HorizontalBar(w)
        self.op.name = "Oil Press"
        self.op.units = "psi"
        self.op.decimalPlaces = 1
        self.op.lowRange = 0.0
        self.op.highRange = 100.0
        self.op.highWarn = 90.0
        self.op.highAlarm = 95.0
        self.op.lowWarn = 45.0
        self.op.lowAlarm = 10.0
        self.op.resize(190, 75)
        self.op.move(w.width() - 200, 220)
        self.op.value = 45.2

        self.ot = gauges.HorizontalBar(w)
        self.ot.name = "Oil Temp"
        self.ot.units = "degF"
        self.ot.decimalPlaces = 1
        self.ot.lowRange = 160.0
        self.ot.highRange = 250.0
        self.ot.highWarn = 210.0
        self.ot.highAlarm = 230.0
        self.ot.lowWarn = None
        self.ot.lowAlarm = None
        self.ot.resize(190, 75)
        self.ot.move(w.width() - 200, 300)
        self.ot.value = 215.2

        self.fuel = gauges.HorizontalBar(w)
        self.fuel.name = "Fuel Qty"
        self.fuel.units = "gal"
        self.fuel.decimalPlaces = 1
        self.fuel.lowRange = 0.0
        self.fuel.highRange = 50.0
        self.fuel.lowWarn = 2.0
        self.fuel.resize(190, 75)
        self.fuel.move(w.width() - 200, 380)
        self.fuel.value = 15.2

        self.ff = gauges.HorizontalBar(w)
        self.ff.name = "Fuel Flow"
        self.ff.units = "gph"
        self.ff.decimalPlaces = 1
        self.ff.lowRange = 0.0
        self.ff.highRange = 20.0
        self.ff.highWarn = None
        self.ff.highAlarm = None
        self.ff.lowWarn = None
        self.ff.lowAlarm = None
        self.ff.resize(190, 75)
        self.ff.move(w.width() - 200, 460)
        self.ff.value = 5.2

        cht = gauges.HorizontalBar(w)
        cht.name = "Max CHT"
        cht.units = "degF"
        cht.decimalPlaces = 0
        cht.lowRange = 0.0
        cht.highRange = 500.0
        cht.highWarn = 380
        cht.highAlarm = 400
        cht.resize(190, 75)
        cht.move(w.width() - 200, 540)
        cht.value = 350

        self.egt = gauges.HorizontalBar(w)
        self.egt.name = "Avg EGT"
        self.egt.units = "degF"
        self.egt.decimalPlaces = 0
        self.egt.lowRange = 0.0
        self.egt.highRange = 1500.0
        self.egt.resize(190, 75)
        self.egt.move(w.width() - 200, 620)
        self.egt.value = 1350

        if test == 'normal':
            self.flightData.pitchChanged.connect(self.a.setPitchAngle)
            self.flightData.rollChanged.connect(self.a.setRollAngle)
            self.flightData.headingChanged.connect(self.head_tape.setHeading)
            self.flightData.altitudeChanged.connect(self.alt_tape.setAltimeter)
            self.flightData.altitudeChanged.connect(
                self.alt_Trend.setAlt_Trend)
            #self.flightData.vsiChanged.connect(self.alt_Trend.setAlt_Trend)
            self.flightData.airspeedChanged.connect(self.as_tape.setAirspeed)
            self.flightData.airspeedChanged.connect(self.as_Trend.setAS_Trend)
            self.flightData.airspeedChanged.connect(self.asd_Box.setIAS)
            self.flightData.RPMChanged.connect(self.rpm.setValue)
            self.flightData.MAPChanged.connect(self.map_g.setValue)
            self.flightData.OilPressChanged.connect(self.op.setValue)
            self.flightData.OilTempChanged.connect(self.ot.setValue)
            self.flightData.FuelFlowChanged.connect(self.ff.setValue)
            self.flightData.FuelQtyChanged.connect(self.fuel.setValue)

        elif test == 'fgfs':
            self.timer = QTimer()
            #Timer Signal to run guiUpdate
            QObject.connect(self.timer, SIGNAL("timeout()"), self.guiUpdate)
            # Start the timer 1 msec update
            self.timer.start(6)

            self.thread1 = fgfs.UDP_Process(self.queue)
            self.thread1.start()
Пример #26
0
import evaluationB as evaluation
import ai

aiInst = ai.AI(strategy=1, saveFileName="tetroNetBackupB")
aiInst.train(saves=2500,
             steps=100,
             gamma=.99,
             tryhard=0.01,
             epochs=10,
             freq=1,
             evaluation=evaluation)
Пример #27
0
import evaluationMore as evaluation
import ai

aiInst = ai.AI(strategy=0, saveFileName="tetroNetBackupDN")
aiInst.train(saves=200,
             steps=50,
             gamma=.88,
             tryhard=.0001,
             evaluation=evaluation)
Пример #28
0
def main():
    #Initialize Everything
    sound_controler = Sound()

    db = database.Database('localhost', 27017)

    pygame.init()
    if sys.version_info[0] < 3:
        pygame.display.set_caption((u'武将大乱斗').encode('utf-8'))
    else:
        pygame.display.set_caption(u'武将大乱斗')

    hero.initiate_hero_pool(db)

    current_map = Map(name='map-1',team_count=3)
    sprite.Sprite.current_map = current_map
    screen = pygame.display.set_mode((current_map.map_width + 256, current_map.map_height))
    current_map.init_terrain_mask()
    skill.load_skill_images()

    gui_controller = gui.Gui(current_map, screen)

    current_mission = mission.test_mission

    #yun = pawn.Pawn((9,6) ,pawn.DIRECTION_RIGHT , pawn.ARM_MELEE , pawn.MOBILE_MOUNT, hero.hero_pool[0] , 0 , True , False)
    #lvbu = pawn.Pawn((6,5) , pawn.DIRECTION_LEFT ,  pawn.ARM_MELEE , pawn.MOBILE_MOUNT, hero.hero_pool[1] , 1 , False , True)
    #zhouyu = pawn.Pawn((6,6) , pawn.DIRECTION_LEFT ,  pawn.ARM_MELEE , pawn.MOBILE_WALK, hero.hero_pool[2] , 1 , False , True)
    #guanyu = pawn.Pawn((8,9) , pawn.DIRECTION_LEFT ,  pawn.ARM_MELEE , pawn.MOBILE_MOUNT, hero.hero_pool[3] , 0 , True , False)
    #weiwen = pawn.Pawn((10,9) , pawn.DIRECTION_LEFT ,  pawn.ARM_MELEE , pawn.MOBILE_WALK, hero.hero_pool[4] , 0 , True , False)

    #yun.action_turn = 0
    #lvbu.action_turn = 1
    #zhouyu.action_turn = 1
    #guanyu.action_turn = 0
    #
    #pawn_list = [yun , lvbu , zhouyu  , guanyu , weiwen]
    pawn_list = []
    for roster in current_mission.player_roster:
        p = pawn.Pawn(roster[1], roster[2], roster[3], roster[4], hero.hero_pool[roster[0]], roster[5], 0, roster[6],
                      roster[7])
        pawn_list.append(p)
    for roster in current_mission.friend_roster:
        h = copy.copy(hero.hero_pool[roster[0]])
        p = pawn.Pawn(roster[1], roster[2], roster[3], roster[4], h, roster[5], 1, roster[6], roster[7])
        p.ai_group = roster[9][0]
        p.is_leader = roster[9][1]
        p.ai_strategy = roster[10]
        pawn_list.append(p)
    for roster in current_mission.enemy_roster:
        h = copy.copy(hero.hero_pool[roster[0]])
        p = pawn.Pawn(roster[1], roster[2], roster[3], roster[4], h, roster[5], 2, roster[6], roster[7])
        p.persuade = roster[8]
        p.ai_group = roster[9][0]
        p.is_leader = roster[9][1]
        p.ai_strategy = roster[10]
        pawn_list.append(p)

    selected_pawn = None
    control = Control(current_map)
    gui_controller.side_menu(selected_pawn)
    logic_controller = logic.Logic(current_map, pawn_list)
    fight_logic_controller = fight_logic.FightLogic(current_map, pawn_list)
    skill.fight_logic_controller = fight_logic_controller

    logic_controller.process_action_queue()
    logic_controller.turn_team = 0
    logic.control = control
    logic.fight_logic_controller = fight_logic_controller

    ai.logic_controller = logic_controller
    gui.logic_controller = logic_controller
    info_before_move = (None, None, None)

    ai_controller = ai.AI(pawn_list)

    logic_controller.new_turn()

    current_round = 1
    last_turn_team = 0

    while True:

        config.clock = pygame.time.Clock().tick(config.FPS)

        current_map.render()

        logic_controller.update_terrain_mask()
        skill.fight_logic_controller.trigger_passive_skills_realtime()
        logic_controller.update_pawn_status()

        for p in logic_controller.pawn_list:
            if p.hero.alive:
                p.render()
            else:
                pawn_list.remove(p)


        #FOR ENEMY AI
        if logic_controller.turn_team != 0:
            for event in pygame.event.get():
                if event.type == QUIT:
                    return

            flag = False
            for p in ai_controller.pawn_list:
                if p.turn_team != logic_controller.turn_team:
                    continue
                if not p.turn_finished and p.has_ai:
                    if control.status == control.CONTROL_STATUS_IDlE:
                        ai_controller.take_action(p)
                        if p and p.next_move:
                            top = p.next_move[0]
                            action_type = top[0]
                            action_target = top[1]
                            if action_type == ai.AI_ACTION_MOVE:
                                logic_controller.process_player_action(p, action_target)
                                control.status = control.CONTROL_STATUS_PROCESSING_PLAYER_ACTION
                            elif action_type == ai.AI_ACTION_ATTACK:
                                logic_controller.process_player_action(p, action_target , MENU_ORDER_ATTACK)
                                control.status = control.CONTROL_STATUS_PROCESSING_PLAYER_ACTION
                            #print p.hero.name.encode('utf-8'), ' not finished', p.next_move, 'control status: ', control.status , logic_controller.turn_team , p.turn_team
                        flag = True
                        break
                    elif control.status == control.CONTROL_STATUS_PAWN_MOVED:
                        control.status = control.CONTROL_STATUS_PROCESSING_PLAYER_ACTION
                    flag = True
            if not flag:
                control.status = control.CONTROL_STATUS_TURN_FINISHING

            if control.status == control.CONTROL_STATUS_PROCESSING_PLAYER_ACTION:
                if not logic_controller.process_action_queue():
                    control.status = control.CONTROL_STATUS_IDlE
        else:
            for event in pygame.event.get():
                if event.type == QUIT:
                    return
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_p:
                        if debug and selected_pawn:
                            logger(  selected_pawn.status_info() )

                if control.status == control.CONTROL_STATUS_MENU_ATTACK_CHOOSE:
                    target = gui_controller.get_grid_on_mouse()
                    target_type = logic_controller.is_valid_target(selected_pawn, target, pawn.ACTION_ATTACK, )
                elif control.status == control.CONTROL_STATUS_MENU_OPENED:
                    target_type = gui_controller.is_mouse_on_menu()
                else:
                    target = gui_controller.get_grid_on_mouse()
                    target_type = logic_controller.get_target_type(0, target)
                if event.type == KEYDOWN or event.type == MOUSEBUTTONDOWN or event.type == MOUSEBUTTONUP:
                    control.event_queue.append((event, target_type))

            if control.status == control.CONTROL_STATUS_MENU_OPENED:

                #当鼠标在地图上右键, 打开菜单

                if gui_controller.menu is None:
                    gui_controller.build_menu(None)
                gui_controller.menu.display()
            elif control.status == control.CONTROL_STATUS_MENU_ITEM_SELECTING:
                gui_controller.menu.display(1)

            elif control.status == control.CONTROL_STATUS_PAWN_MOVED or control.status == control.CONTROL_STATUS_MENU_ATTACK_CHOOSE_CANCELED:
                gui_controller.build_menu(selected_pawn)
                control.status = control.CONTROL_STATUS_MENU_OPENED

            elif control.status == control.CONTROL_STATUS_MENU_CANCEL:

                #战斗菜单被取消后, 单位回到操作前的状态(包括位置,方向)

                gui_controller.menu = None
                if selected_pawn:
                    logic_controller.current_map.map_collision_info[selected_pawn.position[0]][
                        selected_pawn.position[1]] = battle_map.COLLISION_INFO_EMPTY

                    selected_pawn.position = info_before_move[0]
                    selected_pawn.direction = info_before_move[1]
                    selected_pawn.move_count = info_before_move[2]
                    selected_pawn.render_position = selected_pawn.get_render_position(selected_pawn.position)
                    logic_controller.current_map.map_collision_info[selected_pawn.position[0]][
                        selected_pawn.position[1]] = battle_map.COLLISION_INFO_OCCUPIED

                control.status = control.CONTROL_STATUS_IDlE


            elif control.status == control.CONTROL_STATUS_MENU_ITEM_SELECTED:
                control.status = control.get_control_status_by_menu_order(gui_controller.selected_menu_item)
                logic_controller.process_menu_order(selected_pawn, gui_controller.selected_menu_item)

            elif control.status == Control.CONTROL_STATUS_PROCESS_PLAYER_ACTION:

                if target and selected_pawn:
                    order = None
                    if gui_controller.selected_menu_item:
                        order = gui_controller.selected_menu_item.order
                    logic_controller.process_player_action(selected_pawn, target , order)
                    control.status = Control.CONTROL_STATUS_PROCESSING_PLAYER_ACTION

            elif control.status == control.CONTROL_STATUS_PAWN_SELECTED:

                if selected_pawn:
                    info_before_move = (selected_pawn.position, selected_pawn.direction , selected_pawn.move_count)
                    valid_move = logic_controller.get_valid_move(selected_pawn)

                    gui_controller.highlight_valid_move(valid_move, selected_pawn.controllable)
                    attack_range = logic_controller.get_attack_range_grids(selected_pawn)
                    gui_controller.draw_attack_frame_on_target(attack_range)


            elif control.status == control.CONTROL_STATUS_PROCESSING_PLAYER_ACTION:
                if not logic_controller.process_action_queue():
                    control.status = control.CONTROL_STATUS_IDlE
            elif control.status == control.CONTROL_STATUS_MENU_ATTACK_CHOOSE:
                valid_target = logic_controller.get_valid_target(selected_pawn)
                gui_controller.highlight_valid_target(valid_target)

                attack_range = logic_controller.get_attack_range_grids(selected_pawn)
                gui_controller.draw_attack_frame_on_target(attack_range)
                if selected_pawn.taunted_to:
                    gui_controller.highlight_taunting_target(valid_target)
            elif control.status == control.CONTROL_STATUS_MENU_PERSUADE_CHOOSE:
                valid_target = logic_controller.get_persuade_target(selected_pawn)
                gui_controller.highlight_valid_target(valid_target)
            else:
                selected_pawn = gui_controller.get_selected_pawn(pawn_list)

        if control.status == control.CONTROL_STATUS_TURN_FINISHING:
            if (gui_controller.switch_turn(logic_controller.turn_team)):
                logic_controller.end_turn()
                control.status = control.CONTROL_STATUS_IDlE
        else:
            control.process_event()

        if control.status not in (
            control.CONTROL_STATUS_MENU_OPENED,
            control.CONTROL_STATUS_MENU_BUILD,
            control.CONTROL_STATUS_MENU_ITEM_SELECTING
        ):
            gui_controller.menu = None
            gui_controller.draw_selection_frame()
            gui_controller.side_menu(selected_pawn)

        render_queue.sort(key=lambda surface:surface[0])

        while render_queue:
            top = render_queue.pop()
            if top[1] and top[2]:
                screen.blit(top[1], top[2])

        gui_controller.draw_border()

        pygame.display.update()
                    self.cleanup(hand, deck, 0)
                else:
                    self.turn = True
                    self.cleanup(hand, deck, 1)
        else:
            print("You can't do that yet")


if __name__ == "__main__":
    """This is the main function that will call everything."""
    pygame.init()

    deck = deck_def.Deck(36)
    hand = hand_def.Hand(game_constants.starting_hand_size, deck)
    game_rules = GameRules(True, deck)
    bot = ai.AI()

    pygame.display.set_caption('DURAK')
    clock = pygame.time.Clock()
    screen = pygame.display.set_mode(
        (game_constants.window_width, game_constants.window_height))

    views = [DeckView(deck), ButtonView(game_rules)]
    controllers = [MoveController([deck]), MoveController([game_rules])]
    models = [deck, game_rules]

    for c in hand.cards_in_hand:
        views.append(CardView(c))
        controllers.append(MoveController([c]))
        models.append(c)
Пример #30
0
def aitrain(self, training_trace_set_paths, validation_trace_set_paths, conf):
    resolve_paths(
        training_trace_set_paths)  # Get absolute paths for training set
    resolve_paths(
        validation_trace_set_paths)  # Get absolute paths for validation set

    # Hardcoded stuff
    subtype = 'custom'

    # Determine type of model to train
    model_type = get_conf_model_type(
        conf
    )  # TODO: Refactor 'name' to 'model_type' everywhere and let user specify modeltype in [] params of "train" activity

    # Select training iterator (gathers data, performs augmentation and preprocessing)
    training_iterator, validation_iterator = aiiterators.get_iterators_for_model(
        model_type,
        training_trace_set_paths,
        validation_trace_set_paths,
        conf,
        hamming=conf.hamming,
        subtype=subtype,
        request_id=self.request.id)

    print("Getting shape of data...")
    x, _ = training_iterator.next()
    input_shape = x.shape[1:]  # Shape excluding batch
    print("Shape of data to train: %s" % str(input_shape))

    # Select model
    model = None
    if conf.update or conf.testrank:  # Load existing model to update or test
        model = ai.AI(conf, model_type)
        model.load()
    else:  # Create new model
        if model_type == 'aicorrnet':
            model = ai.AICorrNet(conf, input_dim=input_shape[0])
        elif model_type == 'aishacpu':
            model = ai.AISHACPU(conf, input_shape=input_shape, subtype=subtype)
        elif model_type == 'aishacc':
            model = ai.AISHACC(conf, input_shape=input_shape)
        elif model_type == 'aiascad':
            model = ai.AIASCAD(conf, input_shape=input_shape)
        elif model_type == 'autoenc':
            model = ai.AutoEncoder(conf, input_dim=input_shape[0])
        else:
            raise EMMAException("Unknown model type %s" % model_type)
    logger.info(model.info())

    if conf.tfold:  # Train t times and generate tfold rank summary
        model.train_t_fold(training_iterator,
                           batch_size=conf.batch_size,
                           epochs=conf.epochs,
                           num_train_traces=45000,
                           t=10,
                           rank_trace_step=10,
                           conf=conf)
    elif conf.testrank:  # TODO this should not be in aitrain; refactor
        model.test_fold(validation_iterator,
                        rank_trace_step=10,
                        conf=conf,
                        max_traces=5000)
    else:  # Train once
        model.train_generator(training_iterator,
                              validation_iterator,
                              epochs=conf.epochs,
                              workers=1)