当前位置: 首页>>代码示例>>Python>>正文


Python ai.AI类代码示例

本文整理汇总了Python中ai.AI的典型用法代码示例。如果您正苦于以下问题:Python AI类的具体用法?Python AI怎么用?Python AI使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了AI类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: start_game

def start_game(game_type):
    game = Game()
    ai = AI()
    
    while (game.game_finished is False):
        
        #clear board so output is not too messy
        os.system('cls' if os.name == "nt" else 'clear')
        
        #print the current board state for the players
        print_board_state(game.board)
        
        #if the game has an AI player get AI to move if it's their turn
        if (game_type == AI_PLAYS_BLUE or game_type == AI_PLAYS_RED):
            
            #if it's the AI's turn call the AI to make a move, else player is prompted for a move
            if (game.current_player_turn == RED_PLAYER and game_type == AI_PLAYS_RED):
                game.player_move(ai.get_move(game))
            elif (game.current_player_turn == BLUE_PLAYER and game_type == AI_PLAYS_BLUE):
                game.player_move(ai.get_move(game))
            else:
                game.player_move(get_user_column_input())
        
        #get player move if no AI player or it's still player turn
        else:
            game.player_move(get_user_column_input())
            
        #if the game is finished print the board state and let the player know who has won
        if (game.game_finished):
            os.system('cls' if os.name == "nt" else 'clear')
            print_board_state(game.board)
            print
            print str(game.winner) + " has won the game!"
开发者ID:zbendef,项目名称:connect_four,代码行数:33,代码来源:run.py

示例2: test_ai

def test_ai():
	grid = Grid()
	grid.gprint()
	ct = CountTime()
	totalCT = 0
	while grid.won==False:
		# input()
		print("*******************************************")
		ai = AI(grid)
		ct.start()
		d = ai.nextMove()
		ct.stop()
		moved = grid.move(d["move"])
		if moved==True:
			grid.gprint()
			moveCount = d["moveCount"]
			cutoffs = d["cutoffs"]
			print("moveCount:%d\tcutoffs:%d"%(moveCount,cutoffs))
			nct = ct.milliseconds()
			totalCT += nct
			print("time consume:%d "%(nct))
			print("total time consume:%d "%(totalCT))
			if grid.won==False:
				grid.computerMove()
			else:
				grid.gprint()
		else:
			print("You fail")
			return
开发者ID:LiWeiJie,项目名称:2048_AI,代码行数:29,代码来源:manualtest.py

示例3: test_opponent_next_move_is_winning

    def test_opponent_next_move_is_winning(self):
        ai = AI(['x', ' ', 'o',
                 ' ', ' ', ' ',
                 ' ', ' ', 'x'])

        self.assertEqual(ai.opponent_winning(), 4)
        self.assertEqual(ai.play(4), Game.X_WINS)
开发者ID:alexnad,项目名称:HackBulgaria-Programming-101-2,代码行数:7,代码来源:ai_tests.py

示例4: test_ai_winning

    def test_ai_winning(self):
        ai = AI(['o', ' ', 'x',
                 ' ', ' ', ' ',
                 ' ', ' ', 'o'])

        self.assertEqual(ai.winning(), 4)
        self.assertEqual(ai.play(1), Game.O_WINS)
开发者ID:alexnad,项目名称:HackBulgaria-Programming-101-2,代码行数:7,代码来源:ai_tests.py

示例5: BrainConnection

class BrainConnection():
    def __init__(self):
        self.ai = AI(realtimeMode=True)
        random.seed(self.ai.getRandomness())
        self.lastValue = self.ai.getNeuralResult()
        self.directionValue = 50

        #while True:
        #    print self.getDirection()

    #we get a directional vector between 0 and 100 which is influenced by the 
    #returned values from the brain interface
    def getDirection(self):
        currentValue = self.ai.getNeuralResult()
        if currentValue == self.lastValue:
            return self.directionValue

        if self.lastValue > currentValue:
            if self.directionValue != 100:
                self.directionValue += 10
        else:
            if self.directionValue != 0:
                self.directionValue -= 10
        self.lastValue = currentValue
        return self.directionValue


    #returns entropy data depending on the analogue converted data from the brain interface
    def getRandomness(self,randrange):
        return random.randrange(randrange)
开发者ID:barde,项目名称:efhagame,代码行数:30,代码来源:glue.py

示例6: __init__

class Game:
    def __init__(self):
        self.browser = Browser()
        self.app = QApplication(sys.argv)
        self.timer = QTimer()
        self.timer.timeout.connect(self.updateEvent)

        self.ai = AI()
        self.last_score = 1

    def run(self, delay):
        self.timer.start(delay)
        self.browser.run()
        return self.app.exec_()

    def updateEvent(self):
        self.timer.stop()

        (score, board) = self.browser.extractData()

        if self.last_score > score:
            self.ai.restart_game()
        self.last_score = score

        self.browser.sendMove(self.ai.get_move(score, board))

        self.timer.start() # restart the event loop
开发者ID:JINGHSU,项目名称:reinforcement-2048,代码行数:27,代码来源:2048.py

示例7: sp

def sp(choix_ai_adversaire, num_tirages_MC = 3, num_descentes_dans_arbre = 7, facteur_uct = 0.0):
    '''Une partie opposant un joueur humain à une intelligence artificielle'''
    grid = Grille()
    ai = AI('O')
    if choix_ai_adversaire == 2:
        ai = MC('O', num_tirages_MC)
    elif choix_ai_adversaire == 3:
        ai = UCT('O', num_tirages_MC, num_descentes_dans_arbre, facteur_uct)
    le_joueur1_gagne = False
    mes_coups_possibles = grid.lookForAllowedSteps()
    input = []
    player = 'X'
    while(input != 'q' and grid.checkVictory() is False and len(mes_coups_possibles)>0):
        grid.showGrid()
        input = raw_input("Number 1 through 7  = drop disc, q = quit. \nYour move:")
        if (input in ['1','2','3','4','5','6','7']):
            MonCoup = int(input)
            if grid.drop(player, MonCoup):
                le_joueur1_gagne = True
                mes_coups_possibles = grid.lookForAllowedSteps()
                if(grid.checkVictory() is False and len(mes_coups_possibles)>0):
                    VotreCoup = ai.ai(grid)
                    grid.drop(ai.player, VotreCoup)
                    le_joueur1_gagne = False
                    mes_coups_possibles = grid.lookForAllowedSteps()
    il_y_a_un_vainqueur = grid.checkVictory()
    print "The game ended in the following state:"
    grid.showGrid()
    print("Y a-t-il un gagnant ?"),
    print(il_y_a_un_vainqueur)
    print("Si oui, est-ce le joueur n 1 (X) ?"),
    print(le_joueur1_gagne)
开发者ID:,项目名称:,代码行数:32,代码来源:

示例8: __init__

class Ship:
    def __init__(self, screen):
        self.hp = 100
        self.ai = 1
        self.ai_object = AI(screen, self)
        self.x = 0
        self.y = 0
        self.xvel = 0
        self.yvel = 0
        self.pic = 0
        self.screen = screen

        self.fire_rate = 0

        screen.add_ship(self)

    def set_pic(self, number):
        self.pic = number

    def set_player(self):
        self.ai = 0

    def render(self):
        self.screen.fast_display(self.x, self.y, self.pic)

    def update(self):
        self.x += self.xvel
        self.y += self.yvel

        if self.ai >= 0:
            self.ai_object.move(self.ai)

        if self.y > self.screen.max_y:
            self.screen.explosion(self.x, self.y)

    def damage(self, value):
        self.hp -= value
        if self.hp < 0:
            self.screen.remove_ship(self)
            self.screen.explosion(self.x, self.y)

    def fire(self, rate, target=None):
        if self.fire_rate > 0:
            self.fire_rate -= 1
            return
        self.fire_rate = rate

        shot = Shot(self.screen, self.x, self.y + 40, self, target)

        player = self.screen.player

        dx = player.x - self.x
        dy = player.y - self.y - 15

        total = sqrt(dx ** 2 + dy ** 2)
        shot.xvel = dx / total * 15
        shot.yvel = dy / total * 15

        shot.range = 100
开发者ID:mls-m5,项目名称:test5-python,代码行数:59,代码来源:ship.py

示例9: update

 def update(self, **kwargs):
     """ (**kwargs) -> None
     Updates the aggressive AI.
     Remember, the ball_x, ball_y, ball_vx (x speed), ball_vy
     (y speed), paddle_x, and paddle_y, MUST be supplied
     on every game iteration.
     """
     AI.update(self, **kwargs)
开发者ID:BrianMao04,项目名称:PlayMatrix,代码行数:8,代码来源:aggressiveAI.py

示例10: TestAI

class TestAI(unittest.TestCase):
    def setUp(self):
        self.ai = AI(Board(), 0)
    
    def test_get_difficulty(self):
        self.assertEqual(self.ai.get_difficulty(), 0)
        
    def test_set_difficulty(self):
        self.assertEqual(self.ai.set_difficulty(1), True)
开发者ID:cprimera,项目名称:projects,代码行数:9,代码来源:tests.py

示例11: process_text

 def process_text(self):
     bot = AI(self.msg)
     print self.msg
     result = bot.respond(self.msg.content)
     if options.debug:
         logging.info('bot response %s',result)
     if isinstance(result, list):
         return ObjectDict(msg_type=MSG_TYPE_NEWS,response=result)
     else:
         return ObjectDict(msg_type=MSG_TYPE_TEXT,response=sender.decode(result))
开发者ID:jamiesun,项目名称:talkincode_mp,代码行数:10,代码来源:handlers.py

示例12: __init__

class CLI:
    def __init__(self):
        self._game = AI()

    def play(self):
        outcome = Game.IN_PROGRESS
        while outcome == Game.IN_PROGRESS:
            self._draw_board()
            move = None
            while move is None:
                move = self._get_move()

            outcome = self._game.play(move)
            self._clear()
        self._announce_outcome(outcome)

    def _announce_outcome(self, outcome):
        if outcome == Game.X_WINS:
            print('Congratulations! You won!')
        if outcome == Game.O_WINS:
            print('Sorry, you loose. Better luck next time')
        else:
            print('It\'a a tie')

    def _get_move(self):
        try:
            position = int(input('Enter your move>'))
            if self._game.valid_move(position):
                return position
            print("Wrong input!")
        except ValueError:
            print("Wrong input!")
            return None

    def _clear(self):
        os.system('clear')

    def _draw_board(self):
        state = self._game.current_state()
        symbols = {str(place): symbol for place, symbol in enumerate(state)}
        print(self._fill_board(symbols))

    def _fill_board(self, symbols):
        new_board = []
        for character in BOARD:
            if character in symbols and symbols[character] != Game.EMPTY:
                new_board.append(symbols[character])
            else:
                new_board.append(character)

        return "".join(new_board)
开发者ID:alexnad,项目名称:HackBulgaria-Programming-101-2,代码行数:51,代码来源:cli.py

示例13: AITest

class AITest(unittest.TestCase):

    def setUp(self):
        self.game = Game()
        self.AI = AI(self.game.UI.BOARD, self.game.winning_routes)

    def test_init(self):
        self.assertEqual(self.AI.BOARD, self.game.UI.BOARD)
        self.assertEqual(self.AI.winning_routes, self.game.winning_routes)

    def test_get_correct_position_when_two_places_marked_vertical(self):
        BOARD = [['X', ' ', ' '],
                 ['X', ' ', ' '],
                 [' ', ' ', ' ']]

        self.AI.BOARD = BOARD
        self.assertEqual((2, 0), self.AI.get_best_position())

    def test_get_correct_position_when_two_places_marked_horizontal(self):
        BOARD = [[' ', ' ', ' '],
                 ['X', ' ', 'X'],
                 [' ', ' ', ' ']]

        self.AI.BOARD = BOARD
        self.assertEqual((1, 1), self.AI.get_best_position())

    def test_get_correct_position_when_two_places_marked_diagonal(self):
        BOARD = [[' ', ' ', 'X'],
                 [' ', 'X', ' '],
                 [' ', ' ', ' ']]

        self.AI.BOARD = BOARD
        self.assertEqual((2, 0), self.AI.get_best_position())

    def test_when_only_one_place_is_marked(self):
        BOARD = [[' ', 'X', ' '],
                 [' ', ' ', ' '],
                 [' ', ' ', ' ']]

        self.AI.BOARD = BOARD
        self.AI.attack()

        for line in self.AI.BOARD:
            for place in line:
                if place == 'O':
                    self.assertTrue(True)
                    return

        self.assertFalse(True)
开发者ID:betrakiss,项目名称:HackBulgaria,代码行数:49,代码来源:ai_test.py

示例14: simulerMonteCarlo

 def simulerMonteCarlo(self, grille, symbole_dont_c_est_le_tour):
     '''Evaluer une grille par des simulations Monte-Carlo de la fin de la partie'''
     ai = AI(symbole_dont_c_est_le_tour)
     num_parties_avec_vainqueur = 0
     num_victoires_du_joueur1 = 0
     for i in range(self.num_tirages_MC):
         grille_simulee = Grille(grille)
         (il_y_a_un_vainqueur, le_joueur1_gagne) = ai.autoComplete(grille_simulee)
         num_parties_avec_vainqueur += int(il_y_a_un_vainqueur)
         num_victoires_du_joueur1 += int(le_joueur1_gagne)
     try:
         score  = (2.0*num_victoires_du_joueur1 - num_parties_avec_vainqueur)/num_parties_avec_vainqueur
     except ZeroDivisionError:
         score = 0.5
     return score
开发者ID:,项目名称:,代码行数:15,代码来源:

示例15: __init__

    def __init__(self, controller, settings):
        super(Game, self).__init__()

        # check to make sure that the controller
        # can handle all of the registered spells
        # so it does not pop randomly in the middle
        # of game ;)
        for spell in AttrReader.items_from_klass(Spell):
            controller.get_spell_handler(spell)

        controller.set_game(self)
        self.controller = controller
        self.settings = settings
        self.ai = AI(self.controller._send_msg)
        self.levels = None
        self.player = None

        for event in self.controller.events.values():
            self.events[event.name] = event

        self._turn_num = None
        self._level_count = None
        self._current_level = None

        self._level_generator = LevelGenerator()
        self._object_generator = ObjectGenerator()
        self._species_generator = SpeciesGenerator()
开发者ID:nate1001,项目名称:vecter_hack,代码行数:27,代码来源:game.py


注:本文中的ai.AI类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。