def nacin_igre(self, nacin): '''nastavi igralce''' nacini_igre = [ (clovek.Clovek(self), clovek.Clovek(self)), (clovek.Clovek(self), racunalnik.Racunalnik(self, minimax.Minimax(minimax.globina))), (racunalnik.Racunalnik(self, minimax.Minimax(minimax.globina)), clovek.Clovek(self)), (racunalnik.Racunalnik(self, minimax.Minimax(minimax.globina)), racunalnik.Racunalnik(self, minimax.Minimax(minimax.globina))) ] (igralec_1, igralec_2) = nacini_igre[nacin] self.zacni_igro(igralec_1, igralec_2)
def test_move_chosen(self): ruleset1 = StandardRules() really_new_game = game.Game('p1', 'p2') test_minimax = minimax.Minimax(really_new_game) assert test_minimax.minimaxRoot(1, test_minimax.game.board, True) == [[6, 0], [4, 0]]
def test_simple(self): # Simple hardcoded game for debugging game = minimax_domino.Game([ [(0, 0), (1, 2)], [(0, 1), (2, 2)], [(1, 1), (0, 0)], [(0, 2), (0, 1)], ]) mm = minimax.Minimax(game) state = game.first_state() value = mm.find(state) self.assertEqual(value, 1)
def generate_episode(): e = Episode() b = game.Board() move_count = 0 while True: if (move_count > 42): print('error move count') game_status, p1_action = q.play_best(b, 1) sah = state_action.get_hash_from_board(b, p1_action) e.state_action_hashes.append(sah) move_count += 1 if (game_status == 'Win' or game_status == 'Tie' or game_status == 'Loss'): e.result = game_status e.final_board = b.board return e if PLAY_RANDOM: p2_action = pick_random_action() game_status = b.move(p2_action, 2) if game_status == 'Illegal': while game_status == 'Illegal': p2_action = pick_random_action() game_status = b.move(p2_action, 2) else: # play with minimax converted_board = b.convert_board() m = minimax.Minimax(converted_board) p2_action = m.bestMove(MINIMAX_DEPTH, converted_board, 'o') game_status = b.move(p2_action[0], 2) if game_status == 'Illegal': print('Minimax ERROR') while game_status == 'Illegal': p2_action = pick_random_action() game_status = b.move(p2_action, 2) move_count += 1 e.board_history.append(copy.deepcopy(b.board)) if (game_status == 'Win' or game_status == 'Tie' or game_status == 'Loss'): e.result = game_status e.final_board = b.board return e return None
def makeMinimaxedMove(self, board): # Calculate game tree of boarde gameTree = self.calculateGameTree(board, ply=3) # minimax tree minmax_gameTree = mnm.Minimax().minimax(gameTree) # search for matching nodes from children # level 1 = root, level 2 = children. (may be multiple nodes) best_move_nodes = at.search.findall_by_attr(minmax_gameTree, minmax_gameTree.value, name="value", maxlevel=2) # select random move from equally best scoring ones randindex = np.random.randint( 1, len(best_move_nodes)) # 0th item is always root move = best_move_nodes[randindex].move time.sleep(self.delay) return b.move(board, move)
def test_second_win(self): # Second team wins game = generate_game(2, 2, 12) mm = minimax.Minimax(game) cur_state = game.first_state() first_value = mm.find(cur_state) # print(game.pieces) # print(first_value) # print(cur_state) while not game.is_over(cur_state): moves = mm.get_moves(cur_state) move = moves[0] cur_state = game.apply(cur_state, move) # print(moves) # print(">>", move) # print(cur_state) value = mm.find(cur_state) self.assertEqual(value, first_value)
def test_large(self): # Game with max_value up to 6 game = domino_ux.generate_game(seed=7) mm = minimax.Minimax(game) cur_state = game.first_state() first_value = mm.find(cur_state) # print(game.pieces) # print(first_value) # print(cur_state) while not game.is_over(cur_state): moves = mm.get_moves(cur_state) move = moves[0] cur_state = game.apply(cur_state, move) # print(moves) # print(">>", move) # print(cur_state) value = mm.find(cur_state) self.assertEqual(value, first_value)
# THIS FILE EXISTS ONLY FOR QUICK TESTING PURPOSE # DO NOT USE THIS FILE IN PRODUCTION ENVIRONMENT # USE THE X-RUDDER.PY INSTEAD # --------------------------------------------------- from anytree import RenderTree, LevelOrderIter import minimax import board from config import CROSS, CIRCLE, DEPTH b = board.Board() ai = minimax.Minimax() temp = board.Board() def run_test(b): b.setTile(CROSS, "H3") b.setTile(CROSS, "G2") b.setTile(CROSS, "G4") b.setTile(CROSS, "I4") b.setTile(CROSS, "I2") b.setTile(CIRCLE, "I3") b.displayBoard() b = ai.aiAction(b, CIRCLE, b.moveCounter, b.addCounter, DEPTH, True) for pre, fill, node in RenderTree(b): print("%s%s" % (pre, node.score), file=open("output.txt", "a")) b.displayBoard()
def AImove(self): AI_move = minimax.Minimax(self.game).minimaxRoot(3, self.game.board, False) # print(AI_move) self.game.execute_turn(AI_move[0][0],AI_move[0][1],AI_move[1][0],AI_move[1][1])
import board import player import minimax from config import CROSS, CIRCLE, DEPTH board_game = board.Board() player1 = player.Player() player2 = minimax.Minimax() human_turn = True player1.symbol = CROSS player2.symbol = CIRCLE # This is the game logic. def run(board_game, human_turn, strong_heuristic): help_enable = True # This is the game loop # message() while not board_game.winner_found: print( "===============================================================") board_game.displayBoard() if help_enable is True: help() help_enable = False print("CROSS token left: {}\nCIRCLE token left: {}".format( player1.tokenleft, player2.tokenleft)) #print("the current used tiles in the game") #board_game.printUsedTiles() #print(board_game.used_tiles)
def run_before_tests(): ruleset = StandardRules() new_game = game.Game('p1', 'p2', ruleset) test_minimax = minimax.Minimax(new_game) return test_minimax
def __init__(self, color): self.color = color self.solver = minimax.Minimax(self.color)
import tkinter as tk import gamestate import minimax import board import sys #improvement: transpositions #improvement: having more stones on the board gives a score advantage #not fair if you sometimes play deeper (or if the depth differs in parity) args = sys.argv #size, depth, player size = int(args[1]) depth = int(args[2]) if (int(args[3]) == 1): aiNum = -1 if (int(args[3]) == 2): aiNum = 1 top = tk.Tk() gamestate = gamestate.GameState(size, size, 5) #AI = montecarlo.MCGameTree(gamestate, 100) AI = minimax.Minimax(gamestate, aiNum, depth) if aiNum == -1: gameboard = board.Board(top, gamestate, "human", AI) if aiNum == 1: gameboard = board.Board(top, gamestate, AI, "human") top.mainloop()
def __init__(self, master, globina): self.logika = None # Tu bo spravljena logika igre, ko se bo igra dejansko začela. self.igralec1 = None self.igralec2 = None # Narišemo igralno okno. self.okno = tkinter.Canvas(master) self.okno.grid(row=1, column=1) # Ustvarimo label z opozorili. self.opozorila = tkinter.Label(master, text="", font=("Comic Sans", 16)) self.opozorila.grid(row=0, column=1, pady=0, padx=0) # Ustvarimo okvir, v katerem bodo gumbi. gumbi = tkinter.Frame(master) gumbi.grid(row=3, column=1) # Narišemo gumbe. self.seznam_gumbov = [] for i in range(len(Gui.SEZNAM_BARV)): gumb_v_nastajanju = tkinter.Button( gumbi, width=5 * Gui.VELIKOST_POLJA, height=2 * Gui.VELIKOST_POLJA, text=" ", highlightbackground=Gui.SEZNAM_BARV[i], background=Gui.SEZNAM_BARV[i], command=lambda i=i: self.barva_klik(i)) gumb_v_nastajanju.pack(side=tkinter.LEFT, padx=10, pady=5) self.seznam_gumbov.append(gumb_v_nastajanju) # Levo in desno od igralne plosce postavimo label-a z vmesnim rezultatom. levi_okvir = tkinter.Frame( master ) # Okvir v katerem sta ime Igralca 1 in njegov rezultat leva_vrednost. levi_okvir.grid(row=1, column=0, padx=20, sticky="S") self.leva_vrednost = tkinter.Label(levi_okvir, text="0", font=("Comic Sans", 16), borderwidth=20) self.leva_vrednost.pack(side=tkinter.BOTTOM) desni_okvir = tkinter.Frame( master ) # Okvir v katerem sta ime Igralca 2 in njegov rezultat desna_vrednost. desni_okvir.grid(row=1, column=2, padx=20, sticky="S") self.desna_vrednost = tkinter.Label(desni_okvir, text="0", font=("Comic Sans", 16), borderwidth=20) self.desna_vrednost.pack(side=tkinter.BOTTOM) def omejitev_stevila_znakov(event): """Dopušča vnos v Entry do dolžine 14, daljše nize skrajša na to dolžino.""" if len(self.ime_igralca1.get()) > 14: skrajsano_ime = self.ime_igralca1.get()[:14] self.ime_igralca1.delete(0, len(self.ime_igralca1.get())) self.ime_igralca1.insert(0, skrajsano_ime) elif len(self.ime_igralca2.get()) > 14: skrajsano_ime = self.ime_igralca2.get()[:14] self.ime_igralca2.delete(0, len(self.ime_igralca2.get())) self.ime_igralca2.insert(0, skrajsano_ime) # Pod vmesnim rezultatom ustvarimo polje za vnos imen igralcev. self.ime_igralca1 = tkinter.Entry(master, justify="center") self.ime_igralca1.insert(0, "Igralec 1") self.ime_igralca1.grid(row=2, column=0, padx=20, sticky="N") self.ime_igralca1.bind(sequence='<KeyRelease>', func=omejitev_stevila_znakov) self.ime_igralca2 = tkinter.Entry(master, justify="center") self.ime_igralca2.insert(0, "Igralec 2") self.ime_igralca2.grid(row=2, column=2, padx=20, sticky="N") self.ime_igralca2.bind(sequence='<KeyRelease>', func=omejitev_stevila_znakov) # Nastavimo minimalno širino prvega in zadnjega stolpca. root.grid_columnconfigure(0, minsize=150) root.grid_columnconfigure(2, minsize=150) # Okvir za igralno polje: self.plosca = tkinter.Frame(master) self.plosca.grid(row=1, column=1, rowspan=2) # Naredimo glavni menu: menu = tkinter.Menu(master) master.config(menu=menu) # in podmenu z izbiro vrste igre: menu_igra = tkinter.Menu(menu, tearoff=0) menu.add_cascade(label="Nova igra", menu=menu_igra) menu_igra.add_command( label="Človek proti računalniku", command=lambda: self.narisi_polje( clovek.Clovek(self), racunalnik.Racunalnik( self, minimax.Minimax(globina, VELIKOST_IGRALNE_PLOSCE)))) menu_igra.add_command(label="Človek proti človeku", command=lambda: self.narisi_polje( clovek.Clovek(self), clovek.Clovek(self))) menu_igra.add_command( label="Računalnik proti računalniku", command=lambda: self.narisi_polje( racunalnik.Racunalnik( self, minimax.Minimax(globina, VELIKOST_IGRALNE_PLOSCE)), racunalnik.Racunalnik( self, minimax.Minimax(globina, VELIKOST_IGRALNE_PLOSCE)))) # Naredimo podmenu z gumbom razveljavi: self.moznosti = tkinter.Menu(menu, tearoff=0) menu.add_cascade(label="Možnosti", menu=self.moznosti) self.moznosti.add_command(label="Razveljavi eno potezo", command=lambda: self.razveljavi_eno_potezo()) self.moznosti.add_command(label="Razveljavi dve potezi", command=lambda: self.razveljavi_dve_potezi()) # Nariše igralno polje in nastavi oba igralca. # Privzeto: zagnana igra je igra človek proti računalniku. self.narisi_polje( clovek.Clovek(self), racunalnik.Racunalnik( self, minimax.Minimax(globina, VELIKOST_IGRALNE_PLOSCE)))
def __AI_move(self): AI_move = minimax.Minimax(self.game).minimaxRoot( 2, self.game.board, True) print(AI_move) self.game.execute_turn(AI_move[0][0], AI_move[0][1], AI_move[1][0], AI_move[1][1])
# Nick Weisberg from game import Game import Players import minimax as Searcher # create the game, and the initial state game = Game(n=5, depthlimit=5) #game2 = Game(n=5, depthlimit=depth) state = game.initial_state() # set up the players current_player = Players.VerboseComputer(game, Searcher.Minimax(game)) #current_player = Players.HumanMenu(game) #other_player = Players.VerboseComputer(game2, Searcher.Minimax(game2)) other_player = Players.HumanMenu(game) # play the game while not game.is_terminal(state): state.display() # ask the current player for a move choice = current_player.ask_move(state) # check the move assert choice in game.actions( state), "The action <{}> is not legal in this state".format(choice)