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


Python Board.update方法代码示例

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


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

示例1: mainLoop

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import update [as 别名]
def mainLoop():
    # get grid
    board = Board(BIRD_IP, MAX_X, MAX_Y)
    robots = [Robot(x, board) for x in robotId]
    
    if PLAN:
        board.update()
    # get robot pos
    if RUN_ROBOTS:
        print 'Connecting to robots ', robotId
        for r in robots:
            r.connect()
            r.testConnection()
            while r.pos == None:
                r.update()
            print 'Robot {} starting at {}'.format(r.id, r.pos)
    
    # plan
    if PLAN:
        # write problem
        pddl = makePDDL(board.positions, board.robots, board.blocked, board.box, board.goal)
        f = open('problem.pddl', 'w')
        f.write(pddl)
        f.close()
        call(['/usr/local/bin/python3', './src/pyperplan.py', './domain.pddl', './problem.pddl'])
    
    # Select parts for this robot
    plan = getPlan('./src/simple.pddl.soln')
    print plan
    

    # while has steps not completed
    while not stop.is_set():
        for r in robots:
            r.update()
            if r.actionComplete:
                if len(plan[r.id]) > 0:
                    curr = plan[r.id][0]
                    print 'current move ', curr
                    if r.completed(curr):
                        print 'Moving ', curr, ' competed'
                        plan[r.id].remove(curr)
                        curr = plan[r.id][0]
                    # Identify preconditions for this robots steps
                    if 'move' == curr[0]:
                        r.move(curr[1], curr[2], curr[3])
                    elif 'push' == curr[0]:
                        r.push(curr[1], curr[2], curr[3], curr[4])
        time.sleep(1)
    #   check precondition of step
    #   start timeout
    #   if timeout replan
    #   if precondition run step
    for r in robots:
        r.close()
开发者ID:babsher,项目名称:flockbot-sokoban,代码行数:57,代码来源:run.py

示例2: play

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import update [as 别名]
    def play(self, bot, url, params):
        state = self.next(url, params, self.START_TIMEOUT)
        heroes = HeroManager(state['hero']['id'], state['game']['heroes'])
        board = Board(state['game']['board']['size'])
        print('ELO: {}'.format(state['hero']['elo']), state['viewUrl'])
        while not state['game']['finished']:
            board.update(state['game']['board']['tiles'])
            heroes.update(board, state['game']['heroes'])
            direction = bot.move(board, heroes)
            try:
                state = self.next(state['playUrl'], {'dir': direction}, self.MOVE_TIMEOUT)
            except requests.RequestException as e:
                print e
                state['game']['finished'] = True

        self.session.close()
开发者ID:allevo,项目名称:vindinium-z4r-bot,代码行数:18,代码来源:game.py

示例3: main

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import update [as 别名]
def main():
	random_seed = int( time.time() * 1000 )
	print "seeding random with", random_seed
	random.seed( random_seed )

	player_one = Player( PlayerNumber.one, sys.argv[ 1 ] )
	player_two = Player( PlayerNumber.two, sys.argv[ 2 ] )

	board = Board( player_one, player_two )

	board_state = board.get_state()
	while board_state != BoardState.game_finished:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				return

		pygame.display.update()
		board.update()
		board_state = board.get_state()

		display_surface.fill( ( 10, 10, 10 ) )
		board.render( display_surface )

		time.sleep( 0.01 )

	winning_player = board.get_winner()
	if winning_player is None:
		print "Game is a tie"
	else:
		print winning_player, "has won"


	while True:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				return

		pygame.display.update()
		display_surface.fill( ( 10, 10, 10 ) )
		board.render( display_surface )

		time.sleep( 0.1 )
开发者ID:tomcraven,项目名称:hive,代码行数:46,代码来源:hive.py

示例4: main

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import update [as 别名]
def main():
    pygame.init()
    screen_size = w, h = (1024, 768)

    screen = pygame.display.set_mode(screen_size)
    pygame.display.set_caption("WBRD")

    # Initialize clock
    clock = pygame.time.Clock()

    # Set up our game objects
    p1 = Player('1', Color('red'))
    p2 = Player('2', Color('blue'))
    p1.set_input_map(K_a, K_d, K_w, K_s)
    p2.set_input_map(K_j, K_l, K_i, K_k)
    # Make a new board with our two players on it
    board = Board('test_board.brd', [p1, p2])
    pixel_x = w / board.width
    pixel_y = h / board.height
    pixel_size = min(pixel_x, pixel_y)
    print("pixel size: %s" % pixel_size)

    done = False
    while not done:
        clock.tick(60) # don't run faster than 60FPS
        pygame.event.pump() # refresh the event queue
        pressed_keys = pygame.key.get_pressed()
        # Process input
        board.process_input(pressed_keys)
        # Update
        board.update()
        # Render
        screen.fill(Color('black'))
        board.render(screen, pixel_size)
        pygame.display.flip()

    pygame.quit()
开发者ID:p-buse,项目名称:wbrd,代码行数:39,代码来源:main.py

示例5: Engine

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

    draw = None
    board = None

    def __init__(self):
        self.draw = Draw()
        self.board = Board()
        self.draw.set_board(self.board)

    def run(self):

        info = self.draw.get_board_info()

        self.board.set_cols(info['cols'])
        self.board.set_lines(info['lines'])

        self.draw.draw_board()

        while True:
            self.board.update()
            self.draw.draw_board()

            time.sleep(0.1)
开发者ID:zoltax,项目名称:tanks,代码行数:26,代码来源:engine.py

示例6: Play

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

    def __init__(self):
        self.quit = False
        self.done = False
        self.next = 'game-over'
        self.board = None

    def update(self, keys):
        if not self.board:
            self.board = Board()
        if keys[K_q]:
            self.quit = True
        self.done = self.board.update(keys)

    def cleanup(self):
        self.board.left_paddle.cleanup()
        self.board.right_paddle.cleanup()
        self.board = None
        self.done = False
开发者ID:ewilson,项目名称:pong,代码行数:22,代码来源:states.py

示例7: Exception

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import update [as 别名]
      sys.exit()
      
  # Blank screen
  screen.fill(black)
  
  # Draw board area walls
  game_board.draw_walls(screen)

  # Draw menu
  if game_state == "menu":
    menu_obj.draw_menu(screen)
  elif game_state == "play":
    # If the game is not over
    if not game_board.state == "game_over":
      # Advance game
      game_board.update()
    # If the game is over, return to menu
    else:
      game_state = "menu"
  else:
    raise Exception("Unknown game state")
  
  # Draw falling and stacked bricks
  game_board.draw_bricks(screen)
  # Draw score
  game_board.draw_score(screen)
  
  # Refresh display
  pygame.display.update()    
  # Ensure 60 FPS
  fps_clock.tick(60)
开发者ID:dlowashere,项目名称:Something-Something-Bricks,代码行数:33,代码来源:ssb.py

示例8: __init__

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

#.........这里部分代码省略.........
        return False
    
    def isRotatable(self):
        if (time.clock() - self.time['rotated']) > self.interval['rotate']:
            return True
        if (time.clock() - self.time['stopped_rotating'])< PtModel.INTERVAL['rotate']:
            return True
        return False
    
    def movePiece(self, direction):
        if direction == 'up':
            self.p.drop()
        else:
            self.p.move(direction)
        self.time['moved'] = time.clock()
        if self.interval['move'] > 0.1:
            self.interval['move'] *= 0.9
#        self.flag['moving'] = True

    def rotatePiece(self, radius):
        self.p.rotate(radius)
        self.time['rotated'] = time.clock()
        if(self.interval['rotate']>0.1):
            self.interval['rotate'] *= 0.9
#        self.flag['rotating'] = True

    def fallPiece(self):
        if time.clock() - self.time['fell'] > self.interval['gravity']:
            self.time['fell'] = time.clock()
            self.p.move('down')
            self.time['moved'] = time.clock()
    
    def isAlive(self):
        for i in self.board.getShape()[3]:
            if i!=0 and i!=8: return False
        return True
    
    def updateBoard(self):
        p_shape = self.p.getShape()
        p_type = self.p.getType()
        self.board.update(p_shape, p_type, self.p.getX(), self.p.getY())

    def updatePiece(self):
        self.p = copy.deepcopy(self.p_next)
        self.p.setBoard(self.board)
        self.p_next = Piece(self.board)
        self.view.renderNext(self.p_next.getShape(), self.p_next.getType())

    def update(self):
        if self.isWaiting():
            return False
        self.updateBoard()
        self.erase()
        self.updatePiece()
        return True
            
    def erase(self):
        self.score += PtModel.SCORE[self.board.erase()]

    def isWaiting(self):
        if self.p.isGround():
            if time.clock() - self.time['moved'] < self.interval['gravity']:
                return True
            if time.clock() - self.time['rotated'] < self.interval['gravity']:
                return True
            return False
        return True
    
    def gameOver(self):
        pass
    
    def tick(self):
        pygame.time.Clock().tick(15)

    # boardとpieceを統合して現在の画面の状態を得る
    def getCurrentBoard(self):
        b_shape = copy.deepcopy(self.board.getShape())
        p_shape = self.p.getShape()
        p_type = self.p.getType()
        offset_x = self.p.getX()
        offset_y = self.p.getY()
        for i in range(len(p_shape)):
            for j in range(len(p_shape[i])):
                if p_shape[i][j]:
                    b_shape[i + offset_y][j + offset_x] = p_type
        return b_shape

    def draw(self):
        self.view.renderBoard(self.getCurrentBoard())
        self.view.renderScore(self.score)
        pygame.display.update()
    
    def loop(self):
        self.tick()
        self.update()
        if self.isAlive() == False:
            self.gameOver()
        self.getKey()
        self.fallPiece()
        self.draw()
开发者ID:fand,项目名称:pytetris,代码行数:104,代码来源:model.py

示例9: Board

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import update [as 别名]
last_updated = time.time()
status = "menu"

board = Board()
menus = []
board.draw_menu(games)
while(True):
    key = board.screen.getch()
    if key == ord('q'):
        break
    if key == ord('m'):
        status = "menu"
        games = api.getGames()
        board.draw_menu(games)
    elif status == 'menu':
        for idx in range(1,len(games)+1):
            if key == ord(str(idx)):
                status = 'live'
                msgs = api.getMessage(games[idx-1]['pb_url'])
                board.init_match(games[idx-1])
                board.update(msgs)
                last_updated = time.time()
                break
    elif status == 'live':
        t = time.time()
        if t - last_updated > fresh_time or key == ord("f"):
            msgs = api.getMessage(games[idx-1]['pb_url'])
            board.init_match(games[idx-1])
            board.update(msgs)
            last_updated = time.time()
开发者ID:chenminhua,项目名称:nbacli,代码行数:32,代码来源:test.py

示例10: AStar

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import update [as 别名]
        return [GridState(child, self) for child in self.value.neighbors if child.PASSABLE or child == self.goal]


class AStar(object):
    def __init__(self, start_state):
        self.closedset = set()
        self.openset = PriorityQueue()
        self.openset.put((0, start_state))

    def solve(self):
        while self.openset.qsize():
            priority, closest = self.openset.get(False)
            self.closedset.add(closest)
            for child in closest.get_children():
                if child not in self.closedset:
                    distance = child.estimate()
                    if not distance:
                        return child.path
                    #print child.value, distance
                    self.openset.put((distance, child))
                    #print 'Q', [(p, s.value) for p, s in sorted(self.openset.queue)]
                    #print 'S', [s.value for s in self.closedset]

if __name__ == '__main__':
    from board import Board

    board = Board(4)
    board.update('  ####    ####      ##          ')

    print AStar(GridState(board[0][0], goal=board[0][3])).solve()
开发者ID:z4r,项目名称:vindinium-z4r-bot,代码行数:32,代码来源:astar.py

示例11: __init__

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

#.........这里部分代码省略.........
            self.board = Board(int(args[0]),self.log)
            return ''
    
    def clear_board(self,args):
        """
        Clears the board
        """
        self.board.clear()
        self.bPlayer = Player('b',self.board,self.log)
        self.wPlayer = Player('w',self.board,self.log) 
        return ''
    
    def komi(self,args):
        """
        Sets the new komi to the float value specified as argument
        """
        try:
            komi = float(args[0])
        except Exception:
            raise SyntaxError('komi is not a float')
        else:
            self.score = float(args[0])
            return ''
    
    def play(self,args):
        """
        Updates the board according to the move specified as argument
        """
        color = self.__decodeColor__(args[0])
        posLetter,posNumber = self.__decodePosition__(args[1])
    
        m = Move(color=color,posLetter=posLetter,posNumber=posNumber)
        
        self.board.update(m)

        self.bPlayer.updateListLegal(m.getListFormat(),self.board.getKilled())
        self.wPlayer.updateListLegal(m.getListFormat(),self.board.getKilled())
        
        self.log.logDebug(self.board.showBoard())
                
        return ''
    
    def genmove(self,args):
        """
        Generate a new move for the player specified as argument
        """
        
        
        move = MonteCarlo(self.log,self.board, self.__decodeColor__(args[0]), self.bPlayer, self.wPlayer)
        
        self.board.update(move)     
        
        self.bPlayer.updateListLegal(move.getListFormat(),self.board.getKilled())
        self.wPlayer.updateListLegal(move.getListFormat(),self.board.getKilled())
        
        self.log.logDebug(self.board.showBoard())

        return move.encode()
    
    
    def execute(self):
        """
        Main method: reads a command from stdin and writes the output to stdout
        
        """
        
开发者ID:tizyweb,项目名称:rego,代码行数:69,代码来源:rego.py

示例12: __init__

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import update [as 别名]
class Game:
    '''
    A runner class to run one full full game.
    
    The Game class is customizable in the following ways:
    * maximumRounds - The absolute maximum number of rounds to be played in the game before a tie is declared, defaults to 250. A value of 0 means that there is no maximum number of rounds.
    * minimumRounds - The minimum number of rounds to be run when doing decay ending, defaults to 0.
    * decay - The probability of any given round taking place, defaults to 1.
    
    @note: A decay of .01 give an expected length of ~100 rounds. Decay calculations do not begin until after minimumRounds rounds have passed.
    '''

    maximumRounds = 0
    ''' The maximum number of rounds in the game. A value of 0 means there is no maximum number of rounds. '''
    
    decay = 1
    '''
    The decay rate of the game, i.e. the probability that the next round will take place.
    
    @note: A decay of .99 gives an expected length of ~100 rounds, which is a reasonable default value for a game.
    Decay calculations do not begin until after minimumRounds rounds have passed.
    '''
    
    minimumRounds = 0
    '''
    The minimum number of rounds in the game.
    
    @note: This is the number of rounds that are run before the decay logic is applied to determine the end of the game.
    '''
    
    numRounds = 0
    ''' The number of rounds so far. '''
    
    graphics = None
    '''
    The Graphics object used for displaying the game.
    
    If the value is None, then no graphics are displayed.
    '''
    
    synchronizeGraphics = False
    ''' Flag used to indicate whether the game update loop should synchronize with the graphics or not. '''
    
    board = None
    ''' The Board object for the game. '''
    
    gameOver = False
    ''' Flag indicating whether the game is done or not. '''
    
    scripts = None
    ''' Stash of scripts used for re-running the game. '''

    def __init__(self, scripts, useGraphics = False, synchronizeGraphics = False, maximumRounds = DEFAULT_MAXIMUM_ROUNDS, decay = 1, minimumRounds = 0):
        '''
        Constructor for Game class.
        
        @param scripts: A dict of robotBehavior objects keyed to the script's name.
        @param useGraphics: The Graphics object being used to render the graphics object. If graphics is None, no graphical display will be done.
        @param synchronizeGraphics: If graphics are being used, making this True will cause the game loop to update at the same rate as the graphics loop,
        rather than running as fast as it can. This is available for debugging purposes.
        @param maximumRounds: The maximum number of rounds in the game.
        @param decay: The decay rate of the game, i.e. the probability that the next round will take place.
        @param minimumRounds: The minimum number of rounds in the game.
        '''
        
        # ====================
        # INITIALIZE VARIABLES
        # ====================
        
        # initialize passed in variables
        self.maximumRounds = maximumRounds
        self.decay = decay
        self.minimumRounds = minimumRounds
        self.scripts = scripts
        
        # if graphics are being used, initialize graphics
        if useGraphics: 
            self.graphics = Graphics()
            self.synchronizeGraphics = synchronizeGraphics
        
    def run(self):
        '''
        Runs the game simulation and returns the winner.
        
        @return: A list containing the names of all the robots that survived the round.
        '''
        
        # reset important variables
        self.numRounds = 0
        self.gameOver = False
        self.board = Board(self.scripts)
        
        # ==============
        # START GRAPHICS
        # ==============
        
        # if graphics not None, start graphics runner
        if not (self.graphics is None):
            
            # give graphics object initial board state
#.........这里部分代码省略.........
开发者ID:CSSDePaul,项目名称:Computerized-Robot-Arena-Program,代码行数:103,代码来源:game.py

示例13:

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import update [as 别名]
   screen.fill(pygame.Color('#918da8'))

   for event in [pygame.event.poll()]:
      if event.type == pygame.QUIT:
         sys.exit()
      elif event.type == pygame.KEYDOWN and event.key == pygame.K_q:
         sys.exit()
      elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
         if direction != 'left':
            direction = 'right'
      elif event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
         if direction != 'right':
            direction = 'left'
      elif event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
         if direction != 'down':
            direction = 'up'
      elif event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
         if direction != 'up':
            direction = 'down'
      elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
         if gameBoard.stillPlaying:
            gameBoard.paused = not gameBoard.paused
         else:
            gameBoard.__init__(screen)
            direction = 'right'

   gameBoard.update(direction)

   pygame.display.update()
   clock.tick(10)
开发者ID:Sepiac,项目名称:Snake,代码行数:32,代码来源:snake.py

示例14: tavern_function

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import update [as 别名]
            if self.heroes.player.life <= hero.life:
                return 0
            if not hero.mines:
                return 0
            return self.heroes.player.life / (len(path) - 1)

        def tavern_function():
            return (100 - self.heroes.player.life) / (len(path) - 1)

        def mine_function():
            return self.heroes.player.life / (len(path) - 1)

        score_functions = defaultdict(lambda: lambda: 0)
        score_functions[MineTile] = mine_function
        score_functions[HeroTile] = hero_function
        score_functions[TavernTile] = tavern_function
        return score_functions[type(path[-1])]()

if __name__ == '__main__':
    from json import load
    from board import Board
    from hero import HeroManager

    with open('../fakestate.json') as fp:
        state = load(fp)
        h = HeroManager(state['hero']['id'], state['game']['heroes'])
        b = Board(state['game']['board']['size'])
        b.update(state['game']['board']['tiles'])
        h.update(b, state['game']['heroes'])
        print ZARBot().move(b, h)
开发者ID:allevo,项目名称:vindinium-z4r-bot,代码行数:32,代码来源:bot.py

示例15: len

# 需要导入模块: from board import Board [as 别名]
# 或者: from board.Board import update [as 别名]
    if len(sys.argv) < 2:
        print "You need to specify initial configuration."
        sys.exit(1)

    input_data = None

    with open(sys.argv[1], 'r') as input_data_fd:
        input_data = json.load(input_data_fd)

    gameboard = Board(input_data['width'],
                      input_data['height'],
                      input_data['colony_pos'],
                      input_data['food'])

    if len(sys.argv) > 2:
        file_fd = open(sys.argv[2], 'r')
        sys.stdin = file_fd

    while True:
        data = sys.stdin.readline().rstrip()
        try:
            data_in = json.loads(data)
            if 'exit' in data_in:
                gameboard.exit()
                sys.stdin.close()
                sys.exit(0)
            gameboard.update(data_in)
        except ValueError:
            pass

开发者ID:VasilSokolov,项目名称:ants_visualization,代码行数:31,代码来源:antvis.py


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