Exemplo n.º 1
0
 def __init__(self, race, name, body_template, stats=None, ai=None):
     for i in Creature.__reg:
         if i.name == name:
             raise ValueError()
     self.name = name
     if stats == None:
         stats = race.stats
     if ai == None:
         self.AI = race.ai_class(self)
     elif isinstance(ai, type):
         self.AI = ai(self)
     else:
         self.AI = ai
     assert(isinstance(race, Race))
     assert(type(name) == str)
     self.needs = set()
     self.body = body_template.clone()
     for p in self.body.parts:
         for f in p.functions:
             self.needs.add(f)
     self.race = race
     self.alive = True
     Creature.__max_id += 1
     self.id = Creature.__max_id
     Creature.__reg.append(self)
     self.stats = stats
     self.vision = self.stats.dic['VSN']
     self.controlled_by_player = False
     self.light = 0
     self.effects = set()
     self.check_health()
     log('init called')
Exemplo n.º 2
0
def main(ai_classes=[]):
    w = world.World()
    wt = worldtalker.WorldTalker(w)
    global World
    World = w

    for ai in ai_classes:
        AI.append(ai(wt))

    for ai in AI:
        ai._init()

    ai_cycler = itertools.cycle(AI)
    if settings.SAVE_IMAGES:
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 200, 200)
        cairo_context = cairo.Context(surface)

    for ai in AI:
        b = mapobject.Building(wt)
        w.buildings[b] = next(ai_cycler)
        w.map.placeObject(b, w.map.getRandomSquare())

    for turn in xrange(LIFESPAN):
        for ai in AI:
            ai._spin()
    #            try:
    #                ai.spin()
    #            except Exception, e:
    #                log.info("AI raised exception %s, skipping this turn for it" % (e))

        w.Turn()
        if settings.SAVE_IMAGES:
            worldmap.draw_map(cairo_context, 200, 200, AI, w)
    log.info("Finished simulating the world")
Exemplo n.º 3
0
def sim(ai):
    board = Board()
    cnt = 0
    while not board.finished():
        cnt += 1
        board.move(ai(board).move())
    return cnt
Exemplo n.º 4
0
def main(ai_classes=[]):
  w = world.World()
  wt = worldtalker.WorldTalker(w)
  global World
  World = w

  for ai in ai_classes:
    AI.append(ai(wt))

  for ai in AI:
    ai._init()

  ai_cycler = itertools.cycle(AI)
  if settings.SAVE_IMAGES:
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 200, 200)
    cairo_context = cairo.Context(surface)

  for ai in AI:
    b = mapobject.Building(wt)
    w.buildings[b] = next(ai_cycler)
    w.map.placeObject(b,
      w.map.getRandomSquare())

  for turn in xrange(LIFESPAN):
      for ai in AI:
          ai._spin()
  #            try:
  #                ai.spin()
  #            except Exception, e:
  #                log.info("AI raised exception %s, skipping this turn for it" % (e))

      w.Turn()
      if settings.SAVE_IMAGES:
        worldmap.draw_map(cairo_context, 200, 200, AI, w)
  log.info("Finished simulating the world")
Exemplo n.º 5
0
def interactive_play(ai, board, start_player=0):
    st = 0
    rd = 1
    print_board(board)
    player = start_player
    if player == 1:
        i, j = ai(board, player)
        board[i][j] = -1
        print('computer move')
        print_board(board)
        if get_status(board) == -1:
            print('You Lose!')
            return
        elif get_status(board) == 2:
            print('Tie!')
            return
    while True:
        print('****rount {}:'.format(rd))
        ij = input('input i,j:\n')
        ij = ij.strip()
        ij = ij.split(',')
        i, j = int(ij[0]), int(ij[1])
        if board[i][j] != 0:
            print('illgegal!')
            continue
        board[i][j] = 1
        print('your move:')
        print_board(board)
        if get_status(board) == 1:
            print('You Win!')
            break
        elif get_status(board) == 2:
            print('Tie!')
            break
        i, j = ai(board, 1 - player)
        board[i][j] = -1
        print('computer move')
        print_board(board)
        if get_status(board) == -1:
            print('You Lose!')
            break
        elif get_status(board) == 2:
            print('Tie!')
            break
        rd += 1
    print('now exit')
Exemplo n.º 6
0
 def __init__(self, id, white=False, max_dep=2000, max_t=20):# user plays white if true
     self.index = id
     self.id = gen_id()
     self.board = Board()
     self.play_white = white # true if user plays white
     self.user = white # true if it is users turn
     self.book_move = True
     self.start_time = time.time()
     self.ai = ai(not white, max_t, max_dep)
Exemplo n.º 7
0
 def newwave(self):
     max = 3
     if Bonus.points > 10:
         max = 4
     self.tank = self.wave[self.waveindx]
     for num in range(1, max):
         tank = pirate(self.tank)
         self.pirates.append(tank)
         self.sprites.add(tank)
     self.ai = ai(self.player, self.pirates, self.canisters)
     self.waveindx += 1
Exemplo n.º 8
0
 def test_ai(self):
     for ai in (EasyAI, NormalAI, AdvancedAI):
         board = Board()
         board.move(pair := ai(board).move())
         self.assertTrue(pair[0] in range(board.height))
         self.assertTrue(pair[1] in range(board.width))
     all_cells = Board().remaining_cells
     width = Board().width
     height = Board().height
     for ai in (EasyAI, NormalAI, AdvancedAI):
         s = score(ai)
         self.assertFalse(s < all_cells or s > width * height)
Exemplo n.º 9
0
def play_turn(game_state: GameState, ai) -> None:
    """
    Play a single turn in a game using the ai to select moves to take.
    :param game_state: GameState at the start of the turn
    :param ai: Function to choose the next action, based on the current GameState
    :return: None
    """
    current_player = game_state.player_turn

    while game_state.player_turn == current_player:
        game_state.assert_valid_game_state()
        chosen_action = ai(game_state, game_state.get_next_actions())
        game_state.resolve_action(chosen_action)
Exemplo n.º 10
0
def move(data, vector):
    if not (data.is_won or data.is_lost):
        if data.is_ai:
            data.board, result, _ = move_sim(
                data.board, data.grid, ai(data.board, data.grid, data.target),
                data.target)
        elif vector in ["Left", "Right", "Up", "Down"]:
            data.board, result, _ = move_sim(data.board, data.grid, vector,
                                             data.target)

        if result not in [True, False]:
            pass
        else:
            data.is_won, data.is_lost = (True, False) if result else (False,
                                                                      True)
            data.timerDelay = 1000
Exemplo n.º 11
0
 def add_ai(self, ai):
     a = ai(self.wt)
     self.AI.append(a)
     a._init()
Exemplo n.º 12
0

def redy(inp):
    inp = list(inp)
    while True:
        try:
            inp.remove(".")
        except:
            try:
                inp.remove(",")
            except:
                try:
                    inp.remove("!")
                except:
                    try:
                        inp.remove("?")
                    except:
                        i = ""
                        for k in inp:
                            i += k
                        return i.lower()


ai = ai()
while True:
    inp = input("user: ")
    inp = redy(inp)
    try:
        ai.run(inp)
    except Exception as e:
        print(e)
Exemplo n.º 13
0
if __name__ == '__main__':

    times = []
    wins = 0
    losses = 0
    draws = 0
    fens = [
        '8/8/5p2/1P1K1k2/8/2r5/8/7R w - - 0 0',
        '3k4/5ppp/2q5/3p2r1/8/1Q3P2/P4P1P/3R3K w - - 0 1',
        '4R3/1k6/1p2P1p1/p7/4r3/1P1r4/1K6/2R5 w - - 0 0',
        '5k2/R7/3K4/4p3/5P2/8/8/5r2 w - - 0 0',
        '5k2/1R6/4p1p1/1pr3Pp/7P/1K6/8/8 w - - 0 0'
    ]
    for i in range(5):
        board = Board(fen=fens[i])
        solver = ai(True, max_depth=6, max_time=5000)

        book_move = True
        reader = chess.polyglot.open_reader("ProDeo.bin")

        while True:
            if book_move:
                entries = reader.find_all(board.board, minimum_weight=200)
                if sum(1 for entry in entries) == 0:
                    book_move = False
            if book_move:
                move = reader.find(board.board).move
                board.push(move)
                print(move, end=" ")
            else:
                start = time.time()
Exemplo n.º 14
0
		print '                6 => Player13 vs. Player 13'
		print '                7 => Player14 vs. Player 56'
		print '                8 => Player90 vs. Random Player'
		print '                9 => Player13 vs. Player90'

		#sys.exit(1)
 
	obj1 = ''
	obj2 = ''
	option = sys.argv[1]	
	if option == '1':
		obj1 = Player13()
		obj2 = Player1()
	elif option == '2':
		obj1 = Player13()
		obj2 = ai()
	elif option == '3':
		obj1 = Player13()
		obj2 = Player14()
	elif option == '4':
		obj1 = Player13()
		obj2 = team56.Player56()
	elif option == '5':
		obj1 = Player13()
		obj2 = team79.Player79()
	elif option == '6':
		obj1 = Player13()
		obj2 = Player13()
	elif option == '7':
		obj1 = Player14()
		obj2 = team79.Player79()
        print '                6 => Player13 vs. Player 13'
        print '                7 => Player14 vs. Player 56'
        print '                8 => Player90 vs. Random Player'
        print '                9 => Player13 vs. Player90'

        #sys.exit(1)

    obj1 = ''
    obj2 = ''
    option = sys.argv[1]
    if option == '1':
        obj1 = Player13()
        obj2 = Player1()
    elif option == '2':
        obj1 = Player13()
        obj2 = ai()
    elif option == '3':
        obj1 = Player13()
        obj2 = Player14()
    elif option == '4':
        obj1 = Player13()
        obj2 = team56.Player56()
    elif option == '5':
        obj1 = Player13()
        obj2 = team79.Player79()
    elif option == '6':
        obj1 = Player13()
        obj2 = Player13()
    elif option == '7':
        obj1 = Player14()
        obj2 = team79.Player79()
Exemplo n.º 16
0
        for i in range(len(players[player])):
            health += players[player][i].getHealth()

        return health
        
    def humanAttack(self):
        game.drawScreen()


        while True:
            human_fire = self.verify_input(raw_input('Enter coordinates to fire eg. x, y: '), False)
            if human_fire != False:
                if game.c_map[human_fire[0]][human_fire[1]] not in (2, 3, 4):
                    self.computer_ships = game.battle(human_fire[0], human_fire[1], False, self.computer_ships)
                    break
    
#MAIN GAME LOOP:

while True:
    game = board()
    computer = ai()
    play = playgame(game, computer)
    play.computer_start()
    play.human_start()
    while play.calcHealth(True) > 0 and play.calcHealth(False) > 0:
        play.humanAttack()
        computer.attack(game, play)
        print "Human health: %d \nComputer health: %d" % (play.calcHealth(True), play.calcHealth(False))
        
Exemplo n.º 17
0
    game.is_selected = False
    game.is_check(brd.board,brd.moves_white,brd.moves_black)

    if game.check :
        brd.draw_check(game.tour)
    if game.is_checkmate(brd.board,brd.moves_white,brd.moves_black):
        winner = "Whites" if game.tour else "Black"
        button_end = Button(brd.root, text = '%s win by checkmate ! Try again ?'%winner, command = exit)
        button_end.pack()

    if game.is_draw(brd.board,brd.moves_white,brd.moves_black):
        button_draw = Button(brd.root, text = 'Draw : %s'%game.draw_message, command = exit)
        button_draw.pack()
    game.tour = not game.tour



if len(sys.argv) > 1 and sys.argv[1] == 'multi':
    func = locals()["motion"]
else:
    func = locals()["motion_ia"]

root = Tk()
root.title('chess')
brd = Board(size_windows, margin_left, margin_top, size_case, root)
game = ChessGame()
my_ai = ai(brd,"white",game)

root.bind('<Button-1>', func)

root.mainloop()
Exemplo n.º 18
0
from ai import *

if __name__ == "__main__":

    board = Board()
    solver = ai(True)
    if board.board.is_game_over():
        print(board.board.result())
        exit(0)

    print(board)

    book_move = True
    reader = chess.polyglot.open_reader("ProDeo.bin")

    while True:
        print("Thinking ...\n")
        if book_move:
            entries = reader.find_all(board.board, minimum_weight=200)
            if sum(1 for entry in entries) == 0:
                book_move = False
        if book_move:
            move = reader.find(board.board).move
            print(move)
            board.push(move)
        else:

            start = time.time()

            move = solver.get_move(board)
            print(move)