Esempio n. 1
0
def dfs(depth, teban, board):

    kyokumen = copy.deepcopy(board)
    if depth < 0:
        return False, []
    elif depth == 1:
        return check1(teban, kyokumen)
    else:
        # 王手になる指し手を生成
        # print(depth , 'te check')
        ote_list = ote(kyokumen, teban)
        for ote_hand in ote_list:
            # kyokumen = copy.deepcopy(board)
            ote_board = b.move(kyokumen, ote_hand, teban)
            oshu_list = avoid(ote_board, (teban % 2) + 1)
            if len(oshu_list) == 0 and 'FUut' not in ote_hand:
                return True, ote_hand

            tumi_flg = True
            for oshu in oshu_list:
                # ote_board_tmp = copy.deepcopy(ote_board)
                # print(ote_hand, oshu)
                b.disp(ote_board)
                flg = dfs(depth - 2, teban,
                          b.move(ote_board, oshu, (teban % 2) + 1))
                if flg == False:
                    tumi_flg = False
            if tumi_flg == True:
                return True
        return False
 def get_moves(self, board):
     moves = []
     for row in [0, 1, 2]:
         for col in [0, 1, 2]:
             if board.board[row][col] == 0:
                 new_board = board.move(row, col)
                 new_score = new_board.eval()
                 moves.append([[row, col], new_board, new_score])
     return moves
Esempio n. 3
0
 def get_next_play(self, board: board):
     #play is a class within the rule_checker
     play = strategy.next_move(board)
     worker = play.worker
     move_direction = play.move_direction
     build_direction = play.move_direction
     board = board.move(worker, move_direction)
     if build_direction:
         board = board.build(worker, build_direction)
     return board
Esempio n. 4
0
def check3(board: tuple, teban: int) -> list:
    tumute = []
    # loopは頭使う
    #for i in range(tesu):
    #手番側の王手と王手した後の盤面を生成
    koho_hand = ote(board, teban)
    koho_board = [copy.deepcopy(board) for _ in range(len(koho_hand))]
    for i, hand in enumerate(koho_hand):
        koho_board[i] = b.move(koho_board[i], hand, teban)

    # 王手着手後の局面から逃げる手を求める
    for i, ote_board in enumerate(koho_board):
        avoid_hand = avoid(ote_board, (teban + 1) % 2)
        koho_hand[i] = [koho_hand[i], avoid_hand]

    # 一手詰みがあるか確認
    for hand in koho_hand:
        # print(hand)
        if len(hand[1]) == 0 and 'FUut' not in hand[0]:
            # print('一手詰み', hand)
            tumute.append(hand[0])

    if len(tumute) > 0:
        return tumute

    #一手詰めがなければさらに探索
    for i, ote_board in enumerate(koho_board):
        # ex) hand [王手,[応手1,応手2,...]]
        avoid_board = [
            copy.deepcopy(ote_board) for _ in range(len(koho_hand[i][1]))
        ]
        tumute_temp = []
        for j, oshu in enumerate(koho_hand[i][1]):
            avoid_board[j] = b.move(avoid_board[j], oshu, (teban + 1) % 2)
            ittedume = check1(avoid_board[j], teban)
            if len(ittedume) == 0:
                tumute_temp = []
                break
            else:
                tumute_temp.append([koho_hand[i][0], oshu, ittedume])
                if j == len(koho_hand[i][1]) - 1:
                    tumute.append(tumute_temp)
    return tumute
Esempio n. 5
0
    def move(self, bb, x, y):
        boards = bb.open_boards()
        oboards = [(a,b) for a,b in boards if bb[a][a][1][1] == BLANK]
        if x == None:
            x,y = oboards.pop()

        if bb[x][y][1][1] == BLANK:
            print 'center board(%d,%d) pos:(%d,%d)' % (x,y,1,1)
            return move(1, 1, x, y)
        else:
            return random_bot().move(bb, x, y)
Esempio n. 6
0
 def __init__(self, p1, p2):
     self.board = big_board()
     self.mini = board()
     self.turn = 1
     self.current_player = None
     self.p1 = p1
     self.p1.set_mark(marks[0])
     self.p2 = p2
     self.p2.set_mark(marks[1])
     self.marks = {self.p1: marks[0], self.p2: marks[1]}
     self.gameover = False
     self.last_move = move()
Esempio n. 7
0
def ai_battle():
    #tests the different heuristics by having ai play each other
    P1 = 0
    P2 = 1
    # multiprocess computaion
    parallel = True
    lookahead = 8  # AI lookahead depth, set to negative to search entire game
    board = Board()
    ai = AI(P1, lookahead, relative_score=False)
    #ai_horder = AI(P2, lookahead, horde=True) # hordes pieces on its side
    ai_relative = AI(P2,
                     lookahead,
                     relative_score=True,
                     horde=True,
                     relative_horde=True)  #horde relative is better then not
    next = random.randint(0, 1)

    starting_ai = next
    ai_cur = None  # ai with current turn

    while not board.game_over():

        if not board.has_move(next):
            next = (next + 1) % 2
        if next == ai.player:
            ai_cur = ai
        else:
            ai_cur = ai_relative
        move = ai_cur.move(board, parallel)
        print board
        ## get the move for the ai player
        #if ai.player == ai_basic.player:
        #   print 'Basic picked ', move+1
        #else:
        #   print 'Horder picked ', move+1
        next = board.move(ai_cur.player, move)

    print '         FINAL'
    print board
    p1_score = board.get_score(P1)
    p2_score = board.get_score(P2)

    if next == ai:
        print 'P1 Started'
    else:
        print 'P2  Started'
    if p1_score > p2_score:
        print 'P1 Wins!'
    elif p1_score < p2_score:
        print 'P2 Wins!'
    else:
        print 'It\'s a tie !'
Esempio n. 8
0
def move_board(convert):
    global state
    if state == GAME_OVER:
        return

    moved, score_inc = board.move(convert)
    if moved:
        generate_block()

    score.score += score_inc

    if board.is_full() and not board.can_reduce():
        end_game()
Esempio n. 9
0
def check1(teban, board) -> bool:
    kyokumen = copy.deepcopy(board)
    print("kyokumen:", id(kyokumen))
    print("board:", id(board))
    #手番側の王手と王手した後の盤面を生成
    ote_list = ote(kyokumen, teban)
    # koho_board = [copy.deepcopy(board) for _ in range(len(koho_hand))]
    for hand in ote_list:
        ote_board = b.move(kyokumen, hand, teban)
        # 王手着手後の局面から逃げる手を求める
        avoid_hand = avoid(ote_board, (teban + 1) % 2)
        if len(avoid_hand) == 0 and 'FUut' not in hand[0]:
            return True
    return False
Esempio n. 10
0
 def genNextMoves(self):
     if self.depth % 2 == 0:
         for i in range(7, 13):
             if self.state[i] == 0:
                 continue
             else:
                 # need to add optional state pass to board
                 tempState = self.state[:]
                 board.move(tempState, 1, str(i))
                 tempNode = Node(tempState, self.depth + 1, self.depthLim,
                                 i)
                 self.nextMoves.append(tempNode)
     else:
         for i in range(0, 6):
             if self.state[i] == 0:
                 continue
             else:
                 # need to add optional state pass to board
                 tempState = self.state[:]
                 board.move(tempState, 0, str(i))
                 tempNode = Node(tempState, self.depth + 1, self.depthLim,
                                 i)
                 self.nextMoves.append(tempNode)
Esempio n. 11
0
def playerMove(spaces, player):
    success = False
    available = ""

    if (player == board.SOUTH):
        available = board.SOUTH_SPACES
    else:
        available = board.NORTH_SPACES

    while not success:
        select = input("\tMake your move (" + available + "): ")
        success, errorMessage = board.move(spaces, player, select)

        if not success:
            print(errorMessage)
Esempio n. 12
0
    def move(self, bb, x,y):
        self.bb = bb
        boards = self.bb.open_boards()
        random.shuffle(boards)
        if x == None:
            x,y = boards.pop()

        while self.bb[x][y].check_win() != BLANK:
            x,y = boards.pop()

        ps = self.bb[x][y].open_pos()
        random.shuffle(ps)
        px,py = ps.pop()
        print 'board(%d,%d) pos:(%d,%d)' % (x,y,px,py)
        return move(px, py, boardx=x, boardy=y)
Esempio n. 13
0
 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)
Esempio n. 14
0
def avoid(board: dict, teban: int) -> list:
    """局面の候補手の中から自玉が王手にならないものをリストで返す"""
    koho_hand = candidate.candidate_all(board, teban)
    # 盤面を候補手分生成
    koho_board = [copy.deepcopy(board) for _ in range(len(koho_hand))]
    # 候補手に従って盤面を動かす
    for i, hand in enumerate(koho_hand):
        #print(i, koho_board[i], hand, teban)
        koho_board[i] = b.move(koho_board[i], hand, teban)
        if control.check_ote(koho_board[i])[teban] != False:
            koho_hand[i] = '@'
    # 王手でない候補手は削除する
    for i in range(len(koho_hand))[::-1]:
        if koho_hand[i] == '@':
            koho_hand.pop(i)
            koho_board.pop(i)  # 不要
    return koho_hand
Esempio n. 15
0
    def makeHumanMove(self, board):
        print("The available moves for this turn are:")
        availableMoves = b.f.posMovesToReadMoves(board.getAvailableMoves())
        for item in availableMoves:
            print(item[0], " to ", item[1])
        validMove = False
        while validMove is False:
            moveStr = input(
                "Please select a move by entering a pair of numbers 'xx yy', representing the move from square xx to yy: "
            )
            move = np.array([[0, 0]])
            try:
                if moveStr == "exit":
                    raise SystemExit("Requested 'exit'. Ending program...")
                if len(moveStr) < 3:
                    raise ValueError('Insufficient length')
                move0 = search(r'^([0-9]|[0-9][0-9])\b', moveStr).group(1)
                move1 = search(r'\b([0-9]|[0-9][0-9])$', moveStr).group(1)
                move[0][0] = int(move0)
                move[0][1] = int(move1)

                if move[0].tolist() not in availableMoves.tolist():
                    raise ValueError('Illegal move')

                print("Move Accepted")
                move = b.f.readMovesToPosMoves(move)
                print(move)
                validMove = True

            except AttributeError:
                print(
                    "Sorry, the move was not valid. Please check for typos and try again..."
                )
            except ValueError as ValErr:
                arg = ValErr.args
                if arg[0] == 'Insufficient length':
                    print(
                        "Sorry, the move entered was not valid. Please enter a pair of numbers."
                    )
                if arg[0] == 'Illegal move':
                    print(
                        "Sorry but that move is not legal. Please choose from the list of available moves this turn:"
                    )
                    for item in availableMoves:
                        print(item[0], " to ", item[1])
        return b.move(board, move[0])
Esempio n. 16
0
def main():
    spaces = board.getStartBoard()
    turn = getWhoMovesFirst()
    depthLim = getDepthLim()
    gameEnd = False

    while not gameEnd:
        print("-------------------------------------")
        board.printBoard(spaces)

        if turn == board.SOUTH:
            print("South's turn")
            print("-------------------------------------")
            playerMove(spaces, turn)
            turn = board.NORTH
        elif turn == board.NORTH:
            print("North's turn")
            print("-------------------------------------")
            tempNode = Node.Node(spaces[:], 0, depthLim)
            value, state = Node.ABPruning(tempNode, -1000000, 1000000)
            success, errorMessage = board.move(spaces, board.NORTH,
                                               str(state.cupMove))
            print("\tMoving Cup:", state.cupMove, "\n\tTranslated to Cup:",
                  state.cupMove - 7)
            turn = board.SOUTH
        else:
            print("Error: Turn set to invalid player.")
            break
        gameEnd = board.checkEndState(spaces)
        if gameEnd:
            board.printBoard(spaces)
            print("-------------------------------------")
            input("Game has ended. Hit enter to see results")
            print("\n----- RESULTS -----")
            print("South Points:", board.getScore(spaces, board.SOUTH))
            print("North Points:", board.getScore(spaces, board.NORTH))

            if board.getScore(spaces, board.SOUTH) > board.getScore(
                    spaces, board.NORTH):
                print("South wins!")
            elif board.getScore(spaces, board.SOUTH) < board.getScore(
                    spaces, board.NORTH):
                print("North wins!")
            else:
                print("It's a tie.")
Esempio n. 17
0
 def calculateGameTree(self, board, ply=3, parent=None):
     if parent is None:
         gameTree = at.Node("root", value=-inf)
     for move in board.getAvailableMoves():
         if parent is None:
             node = at.Node(str(move),
                            parent=gameTree,
                            move=move,
                            value=-inf)
         else:
             node = at.Node(str(move), parent=parent, move=move, value=-inf)
         next_board = b.move(board, move, show=False)
         if ply != 1:
             self.calculateGameTree(next_board, ply=ply - 1, parent=node)
         else:
             score = next_board.feature_score(self.coeff)
             node.value = score
             #node.scores = b.CBBFunc.showFeatureScore(next_board,self.coeff)
     if parent is None:
         return gameTree
Esempio n. 18
0
 def count_average_points(self, board, first_move, depth):
     board = move(board, first_move)[1]
     if depth == 0:
         return sum(3**v for c in board for v in c)
     else:
         possible_spawns = [((x, y), v) for x in range(len(board))
                            for y in range(len(board[0])) for v in (1, 2)
                            if board[x][y] == 0]
         s = 0
         c = 0
         for (x, y), v in possible_spawns:
             new_board = board.copy()
             new_board[x][y] = v
             for m in possible_moves(new_board):
                 s += self.count_average_points(new_board, m, depth - 1)
                 c += 1
         if c != 0:
             return s / c
         else:
             return 0
Esempio n. 19
0
def check1(board: tuple, teban: int) -> list:

    tumute = []
    #手番側の王手と王手した後の盤面を生成
    koho_hand = ote(board, teban)
    koho_board = [copy.deepcopy(board) for _ in range(len(koho_hand))]
    for i, hand in enumerate(koho_hand):
        koho_board[i] = b.move(koho_board[i], hand, teban)

    # 王手着手後の局面から逃げる手を求める
    for i, ote_board in enumerate(koho_board):
        avoid_hand = avoid(ote_board, (teban + 1) % 2)
        koho_hand[i] = [koho_hand[i], avoid_hand]

    # check
    for hand in koho_hand:
        # 王手を回避する有効な応手がない場合詰み手順としてtumuteに加える
        # ただし打ち歩詰めはのぞく
        if len(hand[1]) == 0 and 'FUut' not in hand[0]:
            # print('詰み', hand)
            tumute.append(hand[0])
    return tumute
Esempio n. 20
0
 def makeAlphaBetaMove(self, board):
     # start tracking passed time
     t = time.time()
     # Construct the tree of moves to consider
     movetree = self.constructAlphaBetaPrunedCheckersTree(board)
     # extract best move
     # level 1 = root, level 2 = children. (may be multiple nodes)
     best_move_nodes = at.search.findall_by_attr(movetree,
                                                 movetree.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
     # print move choice for human player to read
     #printMove = b.f.posMovesToReadMoves(move)
     #print("%s makes move: %d to %d" % (b.turn_to_string(board.turn),printMove[0],printMove[1]))
     # slow down turn
     sleepTime = self.delay - (time.time() - t)
     if sleepTime > 0:
         time.sleep(sleepTime)
     return b.move(board, move)
Esempio n. 21
0
def ote(board: tuple, teban: int) -> list:
    """局面の候補手で王手を返す"""
    # koho_temp = candidate.candidate_all(board, teban)
    # koho_hand = [ [hand] for hand in koho_temp]
    koho_hand = candidate.candidate_all(board, teban)
    # 盤面を候補手分生成
    koho_board = [copy.deepcopy(board) for _ in range(len(koho_hand))]
    # 候補手に従って盤面を動かす
    for i, hand in enumerate(koho_hand):
        #print(i, koho_board[i], hand, teban)
        koho_board[i] = b.move(koho_board[i], hand, teban)
        #if teban == 1 and control.check_ote(koho_board[i]) != (False, True):
        #    koho_hand[i] = '@'
        #elif teban == 0 and control.check_ote(koho_board[i]) != (True, False):
        #    koho_hand[i] = '@'
        ote_state = control.check_ote(koho_board[i])
        if ote_state[teban] != False or ote_state[(teban + 1) % 2] != True:
            koho_hand[i] = '@'
    # 王手でない候補手は削除する
    for i in range(len(koho_hand))[::-1]:
        if koho_hand[i] == '@':
            koho_hand.pop(i)
            koho_board.pop(i)  # 不要
    return koho_hand
Esempio n. 22
0
    def rcv(self, msg):
        global color  # 退出时把棋子颜色重新修改为-1
        # 如果是服务器转发的对方消息
        if msg[0] == '-':
            s = msg.split('-')
            oppo = s[1]  # 对手id
            op = s[2]
            # 接收服务器发来的对方走棋,("-id-m-x-y")
            if op == 'm':
                x = int(s[3])
                y = int(s[4])
                if color == 1:
                    c = 0
                else:
                    c = 1
                board.move(x, y, c)
                self.draw(x, y, c)  # 在棋盘上画子
                self.myturn = True  # 解锁己方棋盘,可以下棋
                print('oppo move', s)
            # 接收服务器发来的对方悔棋,("-id-w-x-y")
            if op == 'w':
                x = int(s[3])
                y = int(s[4])
                if board.last_draw == color:  # 如果自己已经下了棋,先退回自己的上一步
                    board.undo()
                    self.pieces[board.number()].clear()
                    self.drawed_piece -= 1
                board.withdraw(x, y)
                self.pieces[board.number()].clear()
                self.drawed_piece -= 1
                self.myturn = False  # 锁棋盘,重新等待对方下棋
            # 接收服务器发来的对方已经退出,("-id-l")
            elif op == 'l':
                r = QMessageBox.question(
                    self, 'Oops',
                    "Your opponent has dropped. Clear the board?",
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
                if r == QMessageBox.Yes:
                    self.clear_game()
                    board.clear()
                self.myturn = False  # 锁棋盘
                color = -1
                print("oppo quit")
            # 接收服务器发来的对方要求重开,("-id-r")
            elif op == 'r':
                # r = input("对手要求重新开始游戏,是否同意?y/n")  # 需要GUI进一步处理
                r = QMessageBox.question(
                    self, 'Oops',
                    "Your opponent asked to restart the game. Agree?",
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
                self.myturn = False  # 锁棋盘,必须先处理消息
                # 同意/不同意
                if r == QMessageBox.Yes:
                    rply = '-y-' + oppo
                    board.clear()
                    self.clear_game()
                else:
                    rply = '-n-' + oppo
                send(rply)

        # 服务器主动发来的消息,需要解析
        elif msg[0] == '~':
            m = msg.split('~')
            op = m[1]
            ex = "CANNOT CONTINUE:\n"
            # 只需要打印消息的处理
            if op == 'm' or op == 'p':
                if op == 'm':
                    ex = m[2]
                # 收到游戏开始消息(只有白棋会收到这个消息),提示但不必开始键盘
                elif op == 'p':
                    ex = 'GAME START! WAIT YOUR OPPONENT PLAY..'
                r = QMessageBox.information(self, 'Recieved', ex,
                                            QMessageBox.Ok)
                if r == QMessageBox.Ok:
                    print(ex)
            # 需要用户决定是否清空棋盘
            else:
                color = -1
                if op == 'c':
                    ex += "THE GAME IS CLOSED."
                elif op == 'k':
                    ex += "YOU HAVE BEEN KICKED OUT."
                elif op == 'o':
                    ex += "YOUR OPPONENT HAS BEEN KICKED OUT."
                elif op == 'l':
                    ex += 'YOU LOOOOOOSE!!'
                    self.myturn = False
                r = QMessageBox.question(
                    self, 'Game Canceled',
                    ex + "\nDo you want to clear the board?",
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
                if r == QMessageBox.Yes:
                    self.clear_game()
Esempio n. 23
0
def move(x, y):
    msg = '-m-' + str(x) + '-' + str(y)
    i = send(msg)
    if i == 'y':
        board.move(x, y, color)  # 更新自己棋盘
    return i
Esempio n. 24
0
def main():
    P1 = 0
    P2 = 1
    # multiprocess computaion
    parallel = True
    lookahead = 6  # AI lookahead depth, set to negative to search entire game
    board = Board()
    # ai Player
    ai = AI(P2, lookahead)
    # starting player is random
    current_player = random.randint(0, 1)
    next = (current_player + 1) % 2
    move = 0
    while not board.game_over() and move != 'quit':
        print board
        print '\nP' + str(current_player + 1) + '\'s Turn'
        # if the current player has a move, else switch
        if board.has_move(current_player):
            # not ai turn, user turn
            if current_player != ai.player:
                move = ''
                next = current_player
                while current_player == next and board.has_move(
                        current_player) and move != 'quit':
                    move = get_user_move(board, current_player)
                    if not board.check_move(current_player, move):
                        print 'No pieces', move
                    if move != 'quit':
                        next = board.move(current_player, move)
                        print board
                        print 'Play again!'
                        print '\nP' + str(current_player + 1)

            else:
                # AI turn
                move = ai.move(board, parallel)
                # get the move for the ai player
                print '\tAI picked ', move + 1
                next = board.move(ai.player, move)
                # while AI has another move
                while ai.player == next and board.has_move(
                        ai.player) and move != 'quit':
                    print board
                    print '\tAI Playing Again...'
                    move = ai.move(board, parallel)
                    print '\tAI picked ', move + 1
                    next = board.move(ai.player, move)
            # set player to the next
            current_player = next
        else:
            print '\n P' + str(current_player + 1) + ' has no moves!'
            current_player = (current_player + 1) % 2

    # If game is over and user did not quit
    if move != 'quit':
        print '         FINAL'
        print board
        p1_score = board.get_score(P1)
        p2_score = board.get_score(P2)
        if p1_score > p2_score:
            print 'Player 1 Wins!'
        elif p1_score < p2_score:
            print 'Player 2 Wins!'
        else:
            print 'It\'s a tie !'
    print 'Goodbye!'
Esempio n. 25
0
    def makeMove(self):
        if board.isFull():
            return 0
        bestMoves = set([])
        nextBest = set([])
        okay = set([])
        leastBest = set([])
        for x in range(0, 3):
            for y in range(0, 3):
                if (board.isOpen((x, y)) == False):
                    #print(x,y,"is not open")
                    for adjacent in board.getPerimiter((x, y)):
                        if board.getValue((x, y)) == board.getValue(adjacent):
                            #print("Allan: Found two next to each other:",(x,y),adjacent)
                            bestSpace = self.getRemainingSpace((x, y),
                                                               adjacent)
                            #print("Remian space:",bestSpace)
                            if board.isValidMove(bestSpace):
                                bestMoves.add(bestSpace)
                    for gap in board.getGaps((x, y)):
                        if board.getValue((x, y)) == board.getValue(gap):
                            #print("Allan: Found gap:", (x,y), gap)
                            bestSpace = self.getRemainingSpace((x, y), gap)
                            if board.isValidMove(bestSpace):
                                bestMoves.add(bestSpace)
                if (board.isOpen((x, y)) == False) and (board.getValue(
                    (x, y)) == self.value):
                    for adjacent in board.getPerimiter((x, y)):
                        if board.getValue(adjacent) == 0 and board.getValue(
                                self.getRemainingSpace((x, y), adjacent)) == 0:
                            nextBest.add(adjacent)
                        elif board.getValue(adjacent) == 0:
                            okay.add(adjacent)
                if board.isOpen((x, y)):
                    leastBest.add((x, y))

        # print("Allan: best:",bestMoves)
        # print("Allan: next best:",nextBest)
        # print("Allan: okay:",okay)
        # print("Allan: least best:",leastBest)
        # print()
        bestMoves = list(bestMoves)
        nextBest = list(nextBest)
        okay = list(okay)
        leastBest = list(leastBest)

        if board.getValue((1, 1)) == 0:
            board.move((1, 1), self.value)
        elif len(bestMoves) == 0 and len(nextBest) == 0 and len(okay) == 0:
            reccomended = [i for i in leastBest if board.isCorner(i)]
            if len(reccomended) > 0:
                board.move(random.choice(reccomended), self.value)
            else:
                board.move(random.choice(leastBest), self.value)
        elif len(bestMoves) == 0 and len(nextBest) == 0:
            reccomended = [i for i in okay if board.isCorner(i)]
            if len(reccomended) > 0:
                board.move(random.choice(reccomended), self.value)
            else:
                board.move(random.choice(okay), self.value)
        elif len(bestMoves) == 0:
            reccomended = [i for i in nextBest if board.isCorner(i)]
            if len(reccomended) > 0:
                board.move(random.choice(reccomended), self.value)
            else:
                board.move(random.choice(nextBest), self.value)
        elif len(bestMoves) > 0:
            board.move(random.choice(bestMoves), self.value)
        else:
            print("Boards full!")
Esempio n. 26
0
 def __init__(self, value):
     self.value = value
     if board.isEmpty():
         board.move((1, 1), self.value)
Esempio n. 27
0
def main():
	global board, settings

	pygame.init()
	pygame.font.init()
	screen = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
	pygame.display.set_caption("2048 by 74Genesis")
	font = pygame.font.Font("font/ClearSans-Bold.ttf", 18)
	fontScore = pygame.font.Font("font/ClearSans-Bold.ttf", 13)

	#Основной "холст"
	mainSur = pygame.Surface((WIN_WIDTH, WIN_HEIGHT))
	mainSur.fill(pygame.Color("#faf8ef"))

	# Кнопка Новая игра
	restartBut = pygame.Surface((100, 50))
	restartBut.fill(pygame.Color("#8f7a66"))
	#текст New game
	nGame = font.render("New Game", True, (249,246,242))	

	# Счет
	score = pygame.Surface((80, 50))
	score.fill(pygame.Color("#bbada0"))
	#score
	scoreText = font.render("Score", True, (249,246,242))
	#score число
	scoreNum = None

	# Лучший счет
	bestScore = pygame.Surface((80, 50))
	bestScore.fill(pygame.Color("#bbada0"))
	bestText = font.render("Best", True, (249,246,242))

	#фон доски
	boardBg = pygame.Surface((BOARD_SIZE, BOARD_SIZE))
	boardBg.fill(pygame.Color("#bbada0"))

	board = board.Board()
	# board.board = [[2, 256, 3, 7],
 #       		  	  [2, 128, 4, 8],
	#    		  	  [1024, 64, 5, 9],
	#    		  	  [1024, 32, 6, 34]]

	#Нарисовать заполненные клетки
	cellObjects, textObjects = board.drowFullCells(cellGroup, textGroup)

	pygame.key.set_repeat(1, 400)
	clock = pygame.time.Clock()
	scoreNumX = 0
	while 1:
		clock.tick(400)
		up=down=left=right=False
		#Закрыть окно
		for e in pygame.event.get():
			#Перед выходом сохранить в файл все настройки
			if e.type == pygame.QUIT:
				settings = settings.Settings()
				settings.changeOption("Score", board.getScore())
				settings.changeOption("Best", board.getBest())
				settings.changeOption("StartGame", False)
				settings.changeOption("Board", board.getBoard())
				raise SystemExit

			#Проверять нажатие клавиши только если не осуществляется движение доски
			if not board.startMove:
				if e.type == pygame.KEYDOWN:
					if e.key == pygame.K_UP:
						up = True
					elif e.key == pygame.K_DOWN:
						down = True
					elif e.key == pygame.K_LEFT:
						left = True
					elif e.key == pygame.K_RIGHT:
						right = True
			if e.type == pygame.MOUSEBUTTONDOWN:
				mousePos = pygame.mouse.get_pos()
				if mousePos[0] > ELEM_IND and \
				   mousePos[0] < ELEM_IND+100 and \
				   mousePos[1] > ELEM_IND and \
				   mousePos[1] < ELEM_IND+50:
					board.newGame()
					#Удалить старые спрайты клеток и текста
					for key in cellObjects:
						cellGroup.remove(cellObjects[key])
					for key in textObjects:
						textGroup.remove(textObjects[key])
					cellObjects, textObjects = board.drowFullCells(cellGroup, textGroup) 


		#Если нажата кнопка управления полем
		if up or down or left or right:
			board.setStartMove(True) #начинаем передвижение
			board.setBoardMove(False) #Пересчитана ли доска
			#запоминаем нажатую кнопку
			if up: board.setKeyDown("up")
			if down: board.setKeyDown("down")
			if left: board.setKeyDown("left")
			if right: board.setKeyDown("right")

		#Пока активировано передвижение, изменяем доску
		if board.getStartMove():
			if board.getKeyDown() == "up": up = True
			if board.getKeyDown() == "down": down = True
			if board.getKeyDown() == "left": left = True
			if board.getKeyDown() == "right": right = True
			
			if not board.getBoardMove():
				nBoard, moveMap, nScore = board.move(up, down, left, right)
				board.setNewBoard(nBoard)
				board.setMoveMap(moveMap)
				board.setNewScore(nScore)

				board.setBoardMove(True)

			updateRes = board.update(cellObjects, textObjects, board.moveMap) #двигает клетки

			if updateRes: #Все клетки передвинуты
				board.setBoardMove(False)
				if len(board.getMoveMap()) > 0: # если ячейки двигались
					boardNewNum = board.totalCell(board.getNewBoard()) #добавить ещё одну цифру
					board.setBoard(boardNewNum) #сохранить новую доску
				
				#Удалить старые спрайты клеток и текста
				for key in cellObjects:
					cellGroup.remove(cellObjects[key])
				for key in textObjects:
					textGroup.remove(textObjects[key])

				cellObjects, textObjects = board.drowFullCells(cellGroup, textGroup) #Создать новые
				board.setStartMove(False) #Индикатор движения выключить

				board.setScore(board.getNewScore()) #Обновить счет

				#Если лучший счет меньше основного, обновить его
				if board.getBest() < board.getScore():
					board.setBest(board.getScore())

				#Проверяем не проиграл ли пользователь
				# if board.isMove(board.getNewBoard()):
				# 	print("Конец игры")

				#Победил ли пользователь
				# if board.winner(board.getNewBoard()):
				# 	print("Победитель !")

		#Создание числа "Счет" и "Лучший счет"
		scoreNum = fontScore.render(str(board.getScore()), True, (249,246,242))
		bestNum = fontScore.render(str(board.getBest()), True, (249,246,242))

		#Рисование всех элементов
		#Главный "Холст"
		screen.blit(mainSur, (0,0)) 
		#Новая игра
		screen.blit(restartBut, (ELEM_IND,ELEM_IND)) 
		#New game
		screen.blit(nGame, (ELEM_IND+7, ELEM_IND+11)) 
		#cчет
		screen.blit(score, (115+ELEM_IND,ELEM_IND)) 
		screen.blit(scoreText, (147, ELEM_IND)) #Текст score
		scoreNumX = numAlignCenter(str(board.getScore()), 115+ELEM_IND, 80) #позиция числа
		screen.blit(scoreNum, (scoreNumX, ELEM_IND+25)) #Число score
		#Лучший счет
		screen.blit(bestScore, (115+80+ELEM_IND*2,ELEM_IND)) 
		screen.blit(bestText, (115+80+ELEM_IND*2 + 23, ELEM_IND)) #Текст best
		bestNumX = numAlignCenter(str(board.getBest()), 115+80+ELEM_IND*2, 80) #позиция числа
		screen.blit(bestNum, (bestNumX, ELEM_IND+25)) #Число best
		#фон доски
		screen.blit(boardBg, (ELEM_IND,ELEM_IND*2 + 50)) 

		board.drowCellBack(screen, GAME_BEGIN_X, GAME_BEGIN_Y) #пустые клетки
			
		cellGroup.draw(screen)
		textGroup.draw(screen)
		pygame.display.update()
Esempio n. 28
0
 def makeRandomMove(self, board):
     availableMoves = board.getAvailableMoves()
     time.sleep(self.delay)
     move_index = np.random.randint(0, len(availableMoves))
     #print("making random move")
     return b.move(board, availableMoves[move_index])
Esempio n. 29
0
 def handle(self, params):
     print "Comando: %s"  % params["text"]
     board.move(params["text"])
     board.draw()
Esempio n. 30
0
 def constructAlphaBetaPrunedCheckersTree(self,
                                          board,
                                          depth=3,
                                          alpha=-inf,
                                          beta=+inf,
                                          thisNode=None,
                                          maximising=True,
                                          showAlphaBeta=True):
     if thisNode == None:  # at root
         thisNode = at.Node("root")
     if depth == 0:
         thisNode.value = board.feature_score(self.coeff)
         #thisNode.scores = b.CBBFunc.showFeatureScore(board,self.coeff)
         return None
     if maximising:
         thisNode.value = -inf
         for move in board.getAvailableMoves():
             child = at.Node('b' + str(move))
             child.move = move
             child.parent = thisNode
             next_state = b.move(board, move, show=False)
             if next_state.turn != board.turn:  # minimise oponent
                 self.constructAlphaBetaPrunedCheckersTree(next_state,
                                                           depth=depth,
                                                           alpha=alpha,
                                                           beta=beta,
                                                           thisNode=child,
                                                           maximising=False)
             else:  # maximise self
                 self.constructAlphaBetaPrunedCheckersTree(next_state,
                                                           depth=depth,
                                                           alpha=alpha,
                                                           beta=beta,
                                                           thisNode=child,
                                                           maximising=True)
             thisNode.value = max(child.value, thisNode.value)
             alpha = max(child.value, alpha)
             if showAlphaBeta:
                 thisNode.ab = (alpha, beta)
             if alpha >= beta:
                 break
     else:  # minimising
         thisNode.value = +inf
         for move in board.getAvailableMoves():
             child = at.Node('r' + str(move))
             child.move = move
             child.parent = thisNode
             next_state = b.move(board, move, show=False)
             if next_state.turn != board.turn:  # maximise self
                 self.constructAlphaBetaPrunedCheckersTree(next_state,
                                                           depth=depth - 1,
                                                           alpha=alpha,
                                                           beta=beta,
                                                           thisNode=child,
                                                           maximising=True)
             else:  # minimise oponent
                 self.constructAlphaBetaPrunedCheckersTree(next_state,
                                                           depth=depth,
                                                           alpha=alpha,
                                                           beta=beta,
                                                           thisNode=child,
                                                           maximising=False)
             thisNode.value = min(child.value, thisNode.value)
             beta = min(child.value, beta)
             if showAlphaBeta:
                 thisNode.ab = (alpha, beta)
             if alpha >= beta:
                 break
     if thisNode == thisNode.root:
         return thisNode
     return None
Esempio n. 31
0
File: game.py Progetto: adhamaa/Lab
#x = Modulo('Xerxes')
#o = Modulo('Olle')

#x = FindWinner('Xerxes')
#o = FindWinner('Olle')

#x = MonteCarlo('Xerxes')
#o = MonteCarlo('MonteCarlo')
o = Player('MonteCarlo')

board = board.Board()
print(board.display())

while True:
    m = x.move(board)
    board.move(m)
    print(board.display())
    if board.calc():
        print(x.name + " vann!")
        break

    m = o.move(board)
    board.move(m)
    print(board.display())
    if board.calc():
        print(o.name + " vann!")
        break

    if len(board.moves) == 42:
        print('remi!')
        break