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


Python Board.won方法代码示例

本文整理汇总了Python中board.Board.won方法的典型用法代码示例。如果您正苦于以下问题:Python Board.won方法的具体用法?Python Board.won怎么用?Python Board.won使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在board.Board的用法示例。


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

示例1: run

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import won [as 别名]
def run(ai_function, times=1,  **kws):
    results = []
    states_encountered = {}
    prev_states = 0
    while(times > 0):
        score = 0
        moves = 0
        board = Board(**kws)
        while True:
            if board.won() or not board.canMove():
                break

            move = ai_function(board,score)
            score += board.move(move)
            moves += 1

        results.append((moves, largest_tile(board), score))
        times -= 1
    return results
开发者ID:tuahk,项目名称:term2048,代码行数:21,代码来源:ai.py

示例2: Game

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import won [as 别名]

#.........这里部分代码省略.........
            while True:
                self.clear_screen()
                print(self.__str__(margins=margins, change=change))
                if not can_move:
                    if self.__ai is not None:
                        self.__ai.action_callback(self.board.cells, None)
                    break

                if self.__ai is not None:
                    m = self.__ai.action_callback(self.board.cells,
                                                  self.board.possible_moves())
                else:
                    m = None
                    while m is None:
                        m = self.read_move()


                num_empty_old = 0
                for i in range(4):
                    for j in range(4):
                        if self.board.cells[i][j] == 0:
                            num_empty_old = num_empty_old + 1


                score_inc = self.board.move(m)
                self.increment_score(score_inc)
                change = (score_inc, move_str.get(m))


                num_empty_new = 0
                for i in range(4):
                    for j in range(4):
                        if self.board.cells[i][j] == 0:
                            num_empty_new = num_empty_new + 1

                can_move = self.board.can_move()
                if not can_move:
                    score_inc -= 10000

                if self.__ai is not None:
                    self.__ai.reward_callback((num_empty_new - num_empty_old + 1) * (np.log(score_inc + 1.0)))

                    print ((num_empty_new - num_empty_old + 1) * (np.log(score_inc + 1.0)))

        except KeyboardInterrupt:
            self.save_best_score()
            return None

        self.save_best_score()
        print('You won!' if self.board.won() else 'Game Over')

        print (self.score)

        return self.score

    def get_cell_str(self, x, y):
        """
        return a string representation of the cell located at x,y.
        """
        c = self.board.get_cell(x, y)

        if c == 0:
            return '.' if self.__azmode else '  .'

        elif self.__azmode:
            if c not in self.__az:
                s = '?'
            else:
                s = self.__az[c]
        elif c >= 1024:
            s = '%2dk' % (c / 1024)
        else:
            s = '%3d' % c

        return self.__colors.get(c, Fore.RESET) + s + Style.RESET_ALL

    def board_to_str(self, margins={}):
        """
        return a string representation of the current board.
        """
        b = self.board
        rg = range(b.size())
        left = ' ' * margins.get('left', 0)
        s = '\n'.join(
            [left + ' '.join([self.get_cell_str(x, y) for x in rg]) for y in rg])
        return s

    def __str__(self, margins={}, change=None):
        top = '\n' * margins.get('top', 0)
        bottom = '\n' * margins.get('bottom', 0)
        left = ' ' * margins.get('left', 0)
        board = self.board_to_str(margins=margins)
        scores = left + 'Score: %7d  Best: %7d\n' % (self.score, self.best_score)
        changes = '\n' if change is None else left + '+%13d  %s\n' % change
        output = top + board + '\n\n' + scores + changes + bottom

        if self.__ai is None:
            return output
        else:
            return ('Epoch: %d\n' % self.__ai.epoch) + output
开发者ID:frw,项目名称:2048-DRL,代码行数:104,代码来源:game.py

示例3: Game

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import won [as 别名]

#.........这里部分代码省略.........

    def hideCursor(self):
        """
        Hide the cursor. Don't forget to call ``showCursor`` to restore
        the normal shell behavior. This is a no-op if ``clear_screen`` is
        falsy.
        """
        if not self.clear_screen:
            return
        if not self.__is_windows:
            sys.stdout.write('\033[?25l')

    def showCursor(self):
        """Show the cursor."""
        if not self.__is_windows:
            sys.stdout.write('\033[?25h')

    #### HERE STARTS THE AI STUFF ####

    def ai_loop(self, ai_function):
        """
        Loop to use with AI.
        Input function (ai_function) need to return value from [Board.UP, Board.DOWN..]
        as input ai_function recives current board object and current score.
        """
        margins = {'left': 4, 'top': 4, 'bottom': 4}

        atexit.register(self.showCursor)

        self.hideCursor()
        while True:
            self.clearScreen()
            print(self.__str__(margins=margins))
            if self.board.won() or not self.board.canMove():
                break

            m = ai_function(self.board, self.score)
            self.incScore(self.board.move(m))

        print('You won!' if self.board.won() else 'Game Over')
        return self.score

    ### HERE ENDS AI STUFF #####################

    def loop(self):
        """
        main game loop. returns the final score.
        """
        pause_key = self.board.PAUSE
        margins = {'left': 4, 'top': 4, 'bottom': 4}

        atexit.register(self.showCursor)

        moves = 0

        try:
            self.hideCursor()
            while True:
                self.clearScreen()
                print(self.__str__(margins=margins))
                if self.board.won() or not self.board.canMove():
                    break
                m = self.readMove()

                if (m == pause_key):
                    self.saveBestScore()
开发者ID:tuahk,项目名称:term2048,代码行数:70,代码来源:game.py

示例4: __init__

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import won [as 别名]
class Game:
    """
    A 2048 game
    """

    __dirs = {
        keypress.UP:    Board.UP,
        keypress.DOWN:  Board.DOWN,
        keypress.LEFT:  Board.LEFT,
        keypress.RIGHT: Board.RIGHT,
    }

    __clear = 'cls' if os.name == 'nt' else 'clear'

    __colors = {
           2: Fore.GREEN,
           4: Fore.BLUE,
           8: Fore.CYAN,
          16: Fore.RED,
          32: Fore.MAGENTA,
          64: Fore.CYAN,
         128: Fore.BLUE,
         256: Fore.MAGENTA,
         512: Fore.GREEN,
        1024: Fore.RED,
        2048: Fore.YELLOW,
    }

    SCORES_FILE = '%s/.term2048.scores' % os.path.expanduser('~')

    def __init__(self, scores_file=SCORES_FILE, **kws):
        self.board = Board(**kws)
        self.score = 0
        self.scores_file = scores_file
        self.loadBestScore()

    def loadBestScore(self):
        """
        load local best score from the default file
        """
        if self.scores_file is None or not os.path.exists(self.scores_file):
            self.best_score = 0
            return
        try:
            f = open(self.scores_file, 'r')
            self.best_score = int(f.readline(), 10)
            f.close()
        except:
            pass # fail silently

    def saveBestScore(self):
        """
        save current best score in the default file
        """
        if self.score > self.best_score:
            self.best_score = self.score
        try:
            f = open(self.scores_file, 'w')
            f.write(str(self.best_score))
            f.close()
        except:
            pass # fail silently

    def end(self):
        """
        return True if the game is finished
        """
        return not (self.board.won() or self.board.canMove())

    def readMove(self):
        """
        read and return a move to pass to a board
        """
        k = keypress.getArrowKey()
        return Game.__dirs.get(k)

    def loop(self):
        """
        main game loop
        """
        while True:
            os.system(Game.__clear)
            print self.__str__(margins={'left':4, 'top':4, 'bottom':4})
            if self.board.won() or not self.board.canMove():
                break
            try:
                m = self.readMove()
            except KeyboardInterrupt:
                self.saveBestScore()
                return
            self.score += self.board.move(m)
            if self.score > self.best_score:
                self.best_score = self.score

        self.saveBestScore()
        print 'You won!' if self.board.won() else 'Game Over'

    def getCellStr(self, x, y):
        """
        return a string representation of the cell located at x,y.
#.........这里部分代码省略.........
开发者ID:cychoi,项目名称:term2048,代码行数:103,代码来源:game.py

示例5: Game

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import won [as 别名]

#.........这里部分代码省略.........
        if self.modified and not self.ui.confirmLeaveAction():
            return
        path = self.ui.getOpenPath()
        board = None
        try:
            with open(path, 'r') as f:
                board = pickle.load(f)
        except Error:
            self.ui.statusBar().showMessage(
                "Unable to load game :(", 3000
            )
        if board:
            self.modified = False
            self.board = board
            self.boardView = BoardScene(self, Board.ROW_LENGTH,
                                        self.ui.centralWidget())
            self.ui.centralWidget().setScene(self.boardView)

    def exit(self):
        return not self.modified or self.ui.confirmLeaveAction()

    def showInfo(self):
        self.ui.showMessage(
            "This game was written with Python and the PyQt4 library.\n" +
            "View the source code at the author's github page:\n" + 
            "\n\thttps://github.com/dsuedholt\n\n" + 
            "The game itself was not invented by me, but was shown\n" + 
            "to me by a malicious fellow student aiming to waste my time.",
            "About this game"
        )

    def showHelp(self):
        self.ui.showMessage(
            "The rules for this game are simple. Your goal is to\n" +
            "cross out all the numbers. You can cross out any two\n" +
            "numbers that are equal to another or add up to ten,\n" +
            "as long as they're directly next to or above each other.\n" +
            "If only crossed numbers lie between two other numbers,\n" +
            "they count as adjacent! Crossing over line breaks is also\n" +
            "allowed. When you can't make any more moves, the game\n" + 
            "will expand the board by adding every number you didn't\n" +
            "cross yet to the bottom of the board. Clicking any tile\n" +
            "will show you the tiles you can cross with the selected one." +
            "\n\nStart a new game by going to the \"Game\" menu or\n" +
            "by pressing Ctrl+N.",
            "How to play"
        )

    def handleClick(self, tileR, tileC):
        if not (0 <= tileR < self.board.rows()
                and 0 <= tileC < Board.ROW_LENGTH):
            return

        if self.board.isCrossed(tileR, tileC):
            self.ui.statusBar().showMessage(
                "You already crossed this one!", 3000
            )
            return
        if self.selectedTile:
            if (tileR, tileC) == self.selectedTile:
                for (r, c) in self.board.iterator2D():
                    if not self.board.isCrossed(r, c):
                        self.boardView.setTileStatus(r, c, TileItem.NORMAL)
                self.selectedTile = None

            elif self.board.crossable(self.selectedTile, (tileR, tileC)):
                self.board.cross(self.selectedTile, (tileR, tileC))
                self.boardView.setTileStatus(tileR, tileC, TileItem.CROSSED)
                self.boardView.setTileStatus(*self.selectedTile,
                                             status=TileItem.CROSSED)
                for (r, c) in self.board.iterator2D():
                    if not self.board.isCrossed(r, c):
                        self.boardView.setTileStatus(r, c, TileItem.NORMAL)
                self.selectedTile = None
                self.modified = True
                while self.board.deadlock():
                    self.ui.statusBar().showMessage(
                        "No more moves! Expanding Board", 3000
                    )
                    self.board.expand()
                    self.boardView.expand()
            else:
                self.ui.statusBar().showMessage(
                    "These two tiles can't be crossed!", 3000
                )

        else:
            self.boardView.setTileStatus(tileR, tileC, TileItem.SELECTED)
            self.selectedTile = (tileR, tileC)
            for (r, c) in self.board.iterator2D():
                if self.board.crossable(self.selectedTile, (r, c)):
                    self.boardView.setTileStatus(r, c, TileItem.AVAILABLE)
                elif (not self.board.isCrossed(r, c)
                      and (r, c) != self.selectedTile):
                    self.boardView.setTileStatus(r, c, TileItem.UNAVAILABLE)

        if self.board.won():
            self.ui.statusBar().showMessage(
                "You crossed all the tiles! You win!", 3000
            )
开发者ID:dsuedholt,项目名称:numbergame,代码行数:104,代码来源:game.py

示例6: __init__

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import won [as 别名]

#.........这里部分代码省略.........
        avoid yellow, to give a few examples.
        """
        rp = Game.__color_modes.get(mode, {})
        for k, color in self.__colors.items():
            self.__colors[k] = rp.get(color, color)

    def loadBestScore(self):
        """
        load local best score from the default file
        """
        if self.scores_file is None or not os.path.exists(self.scores_file):
            self.best_score = 0
            return
        try:
            f = open(self.scores_file, 'r')
            self.best_score = int(f.readline(), 10)
            f.close()
        except:
            pass # fail silently

    def saveBestScore(self):
        """
        save current best score in the default file
        """
        if self.score > self.best_score:
            self.best_score = self.score
        try:
            f = open(self.scores_file, 'w')
            f.write(str(self.best_score))
            f.close()
        except:
            pass # fail silently

    def end(self):
        """
        return True if the game is finished
        """
        return not (self.board.won() or self.board.canMove())

    def readMove(self):
        """
        read and return a move to pass to a board
        """
        k = keypress.getArrowKey()
        return Game.__dirs.get(k)

    def loop(self):
        """
        main game loop
        """
        while True:
            os.system(Game.__clear)
            print self.__str__(margins={'left':4, 'top':4, 'bottom':4})
            if self.board.won() or not self.board.canMove():
                break
            try:
                m = self.readMove()
            except KeyboardInterrupt:
                self.saveBestScore()
                return
            self.score += self.board.move(m)
            if self.score > self.best_score:
                self.best_score = self.score

        self.saveBestScore()
        print 'You won!' if self.board.won() else 'Game Over'

    def getCellStr(self, x, y):
        """
        return a string representation of the cell located at x,y.
        """
        c = self.board.getCell(x, y)
        if c == 0:
            return '  .'

        if c == 1024:
            s = ' 1k'
        elif c == 2048:
            s = ' 2k'
        else:
            s = '%3d' % c
        return self.__colors.get(c, Fore.RESET) + s + Fore.RESET

    def boardToString(self, margins={}):
        """
        return a string representation of the current board.
        """
        b = self.board
        rg = xrange(b.size())
        left = ' '*margins.get('left', 0)
        s = '\n'.join(
            [left + ' '.join([self.getCellStr(x, y) for x in rg]) for y in rg])
        return s

    def __str__(self, margins={}):
        b = self.boardToString(margins=margins)
        top = '\n'*margins.get('top', 0)
        bottom = '\n'*margins.get('bottom', 0)
        scores = ' \tScore: %5d  Best: %5d\n' % (self.score, self.best_score)
        return top + b.replace('\n', scores, 1) + bottom
开发者ID:idosch,项目名称:term2048,代码行数:104,代码来源:game.py


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