本文整理汇总了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!"
示例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
示例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)
示例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)
示例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)
示例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
示例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)
示例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
示例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)
示例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)
示例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))
示例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)
示例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)
示例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
示例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()