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


Python Board.getCell方法代码示例

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


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

示例1: Game

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

#.........这里部分代码省略.........
        if self.score > self.best_score:
            self.best_score = self.score
        try:
            with open(self.scores_file, 'w') as f:
                f.write(str(self.best_score))
        except:
            return False
        return True

    def incScore(self, pts):
        """
        update the current score by adding it the specified number of points
        """
        self.score += pts
        if self.score > self.best_score:
            self.best_score = self.score

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

    def store(self):
        """
        save the current game session's score and data for further use
        """
        size = self.board.SIZE
        cells = []

        for i in range(size):
            for j in range(size):
                cells.append(str(self.board.getCell(j, i)))

        score_str = "%s\n%d" % (' '.join(cells), self.score)

        try:
            with open(self.store_file, 'w') as f:
                f.write(score_str)
        except:
            return False
        return True

    def restore(self):
        """
        restore the saved game score and data
        """

        size = self.board.SIZE

        try:
            with open(self.store_file, 'r') as f:
                lines = f.readlines()
                score_str = lines[0]
                self.score = int(lines[1])
        except:
            return False

        score_str_list = score_str.split(' ')
        count = 0

        for i in range(size):
            for j in range(size):
                value = score_str_list[count]
                self.board.setCell(j, i, int(value))
开发者ID:tuahk,项目名称:term2048,代码行数:70,代码来源:game.py

示例2: Game

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import getCell [as 别名]
class Game(object):

    def __init__(self, colors={},
	 mode=None, azmode=False, **kws):
	"""
Create a new game.
scores_file: file to use for the best score (default
is ~/.term2048.scores)
colors: dictionnary with colors to use for each tile
mode: color mode. This adjust a few colors and can be 'dark' or
'light'. See the adjustColors functions for more info.
other options are passed to the underlying Board object.
"""
	self.board = Board(**kws)
	self.score = 0

	self.__colors = colors
	self.__azmode = azmode


    def boardToString(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.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\n' % (self.score)
	return top + b.replace('\n', scores, 1) + bottom


    def incScore(self, pts):
	"""
update the current score by adding it the specified number of points
"""
	self.score += pts

    def getCellStr(self, x, y):  # TODO: refactor regarding issue #11
	"""
	return a string representation of the cell located at x,y.
	"""
	c = self.board.getCell(x, y)
	az = {}
	tempclass = Supy2048(callbacks.Plugin)
	colors = tempclass.getColors()
	for i in range(1, int(math.log(self.board.goal(), 2))):
	    az[2 ** i] = chr(i + 96)

	if c == 0 and self.__azmode:
	    return '.'
	elif c == 0:
	    return '  .'

	elif self.__azmode:
	    if c not in az:
		return '?'
	    s = az[c]
	elif c == 1024:
	    s = ' 1k'
	elif c == 2048:
	    s = ' 2k'
	else:
	    s = '%3d' % c
#	print str(colors[int(math.log(c, 2) % len(colors))])
	return "\x03"+ str(colors[int(math.log(c, 2) % len(colors))])+s+"\x03"
开发者ID:Transfusion,项目名称:2048-IRC,代码行数:75,代码来源:plugin.py

示例3: __init__

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import getCell [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

示例4: __init__

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import getCell [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 getCell [as 别名]
class Game(object):
    #Asignacion de teclas de direccion
    __dirs = {
        keypress.UP:      Board.UP,
        keypress.DOWN:    Board.DOWN,
        keypress.LEFT:    Board.LEFT,
        keypress.RIGHT:   Board.RIGHT,
    }
    #Diccionario con los colores:
    COLORS = {
        2:    Fore.GREEN,
        4:    Fore.BLUE + Style.BRIGHT,
        8:    Fore.CYAN,
        16:   Fore.RED,
        32:   Fore.MAGENTA,
        64:   Fore.CYAN,
        128:  Fore.BLUE + Style.BRIGHT,
        256:  Fore.MAGENTA,
        512:  Fore.GREEN,
        1024: Fore.RED,
        2048: Fore.YELLOW,
        4096: Fore.RED,
        8192: Fore.CYAN,
    }

    def __init__(self, colors=COLORS, clear_screen=True, azmode=False):
        #Inicializa el juego
        self.board = Board()
        self.score = 0
        self.clear_screen = clear_screen
        self.__colors = colors
        self.__azmode = azmode

    def updateScore(self, pts):
        self.score += pts


    def readMove(self):
        #Lee un movimiento y lo pasa al tablero
        k = keypress.getKey()
        return Game.__dirs.get(k)

    def clearScreen(self):
        #Limpia la pantalla:
        if self.clear_screen:
            os.system('clear')
        else:
            print('\n')

    def loop(self):
        #Inicializa el juego:
        margins = {'left': 3, 'top': 3, 'bottom': 3}
        try:
            while True:
                self.clearScreen()
                print(self.__str__(margins=margins))
                if self.board.win() or not self.board.canMove():
                    break
                direction = self.readMove()
                self.updateScore(self.board.move(direction))

        except KeyboardInterrupt:
            return

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

    def getCellStr(self, x, y):  # TODO: refactor regarding issue #11
        """
        return a string representation of the cell located at x,y.
        """
        c = self.board.getCell(x, y)

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

        elif self.__azmode:
            az = {}
            for i in range(1, int(math.log(self.board.goal(), 2))):
                az[2 ** i] = chr(i + 96)

            if c not in az:
                return '?'
            s = az[c]
        elif c == 1024:
            s = ' 1k'
        elif c == 2048:
            s = ' 2k'
        else:
            s = '%3d' % c

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

    def boardToString(self, margins={}):
        """
        return a string representation of the current board.
        """
        b = self.board
        rg = range(b.size())
        left = ' '*margins.get('left', 0)
#.........这里部分代码省略.........
开发者ID:juanfra684,项目名称:old-projects,代码行数:103,代码来源:game.py


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