def test_kv_block(self): """ Tests key-value option in block """ kvb = Block() kvb.kv = KeyValueOption('value') self.assertEqual(kvb.render('kbv_name'), '\nkbv_name {\n kv value;\n}')
def draw(self, surf): """Draw to the surface given.""" cell_size = self.rect[3] curr_x = 0 for (i, block) in enumerate(self.inv_items): # draw cell background cell_rect = (curr_x, self.rect[1], cell_size, cell_size) pygame.draw.rect(surf, (0, 0, 0), cell_rect) curr_x += cell_size # draw highlight for cell if self.selected_cell == i: col = (255, 0, 0) else: col = (255, 255, 255) pygame.draw.rect(surf, col, cell_rect, 2) # draw block in center of cell_rect block_surf = Block(block).surf surf.blit(block_surf, (cell_rect[0] + cell_size/2 - block_surf.get_size()[0]/2, cell_rect[1] + cell_size/2 - block_surf.get_size()[1]/2)) # draw count count = self.inv_count[block] font_surf = self.font.render(str(count), True, (255, 255, 255)) surf.blit(font_surf, cell_rect)
def __init__(self, blocksize, orientation): Shape.__init__(self, blocksize) self.add(Block(blocksize, '1', (blocksize * 7, 0))) self.add(Block(blocksize, '1', (blocksize * 8, 0))) self.add(Block(blocksize, '1', (blocksize * 7, blocksize))) self.add(Block(blocksize, '1', (blocksize * 8, blocksize)))
def receive(obj): d = rlp.decode(obj) # Is transaction if len(d) == 8: tx = Transaction(obj) if mainblk.get_balance(tx.sender) < tx.value + tx.fee: return if mainblk.get_nonce(tx.sender) != tx.nonce: return txpool[bin_sha256(blk)] = blk broadcast(blk) # Is message elif len(d) == 2: if d[0] == 'getobj': try: return db.Get(d[1][0]) except: try: return mainblk.state.db.get(d[1][0]) except: return None elif d[0] == 'getbalance': try: return mainblk.state.get_balance(d[1][0]) except: return None elif d[0] == 'getcontractroot': try: return mainblk.state.get_contract(d[1][0]).root except: return None elif d[0] == 'getcontractsize': try: return mainblk.state.get_contract(d[1][0]).get_size() except: return None elif d[0] == 'getcontractstate': try: return mainblk.state.get_contract(d[1][0]).get(d[1][1]) except: return None # Is block elif len(d) == 3: blk = Block(obj) p = block.prevhash try: parent = Block(db.Get(p)) except: return uncles = block.uncles for s in uncles: try: sib = db.Get(s) except: return processblock.eval(parent, blk.transactions, blk.timestamp, blk.coinbase) if parent.state.root != blk.state.root: return if parent.difficulty != blk.difficulty: return if parent.number != blk.number: return db.Put(blk.hash(), blk.serialize())
def generate_new_block(self, x=0, y=0): #first test if a new block is valid test_block = Block.new_block(x, y, False) if detect_collisions(self.board, test_block): self.game_over() else: self.last_block = self.block self.block = Block.new_block(x, y)
def parse_variables(self): Block.parse_variables(self, constructor_variable=VariableJorek) # ... arguments for var in self._variables: # TODO must treate all cases if var.name in self._arguments: var.set_ctype(PREFIX_CONTEXT_TYPE_ARGUMENT) else: var.set_ctype(PREFIX_CONTEXT_TYPE_LOCAL)
def test(): g0 = Block(0) g1 = Block(1) g2 = Block(2) a = Block(1, g1) b = Block(1, g1) c = Block(1, b) d = Block(1, c) e = Block(1, c) f = Block(1, e) weighted_blocks = {g0: 1, b: 1, g2: 1, f: 1, d: 100} starting_blocks = {0: g0, 1: g1, 2: g2} blocks = [g0, g1, g2, a, b, c, d, e, f] result = sharded_fork_choice(starting_blocks, blocks, weighted_blocks) print("0", result[0]) print("1", result[1]) print("2", result[2]) print("height f", f.height) return result
def __init__(self, blocksize, orientation): Shape.__init__(self, blocksize) self.axis = Block(blocksize, '6', (blocksize * 7, blocksize)) self.add(Block(blocksize, '6', (blocksize * 6, blocksize))) self.add(self.axis) self.add(Block(blocksize, '6', (blocksize * 8, blocksize))) self.add(Block(blocksize, '6', (blocksize * 7, blocksize * 2))) while self.orientation != orientation: self._do_rotate(self)
def __init__(self, blocksize, orientation): Shape.__init__(self, blocksize) #Shape starts horizontal self.axis = Block(blocksize, '0', (blocksize * 7, blocksize)) self.add(Block(blocksize, '0', (blocksize * 6, blocksize))) self.add(self.axis) self.add(Block(blocksize, '0', (blocksize * 8, blocksize))) self.add(Block(blocksize, '0', (blocksize * 9, blocksize))) #If desired orientation is vertical, rotate if orientation % 2: self._do_rotate(self)
def __init__(self, blocksize, orientation): Shape.__init__(self, blocksize) self.orientation = 3 #Starts off in an 'L' orientation self.axis = Block(blocksize, '4', (blocksize * 7, blocksize)) self.add(Block(blocksize, '4', (blocksize * 7, 0))) self.add(self.axis) self.add(Block(blocksize, '4', (blocksize * 7, blocksize * 2))) self.add(Block(blocksize, '4', (blocksize * 8, blocksize * 2))) while self.orientation != orientation: self._do_rotate(self)
def parse(s, parent_block): config = copy.copy(s) pos, brackets_level, param_start = 0, 0, 0 while pos < len(config): if config[pos] == '#' and brackets_level == 0: re_sharp_comment = re.search( '(?P<offset>[\s\n]*)#(?P<comment>.*)$', config, re.M) sharp_comment = re_sharp_comment.groupdict() parent_block.add_comment( Comment(sharp_comment['offset'], sharp_comment['comment'])) config = config[re_sharp_comment.end():] pos, param_start = 0, 0 continue if config[pos] == ';' and brackets_level == 0: re_option = re.search( '\s*(?P<param_name>\w+)\s*(?P<param_options>.*?);', config[param_start:], re.S) if not re_option: raise Exception('Wrong option') option = re_option.groupdict() parent_block[option['param_name']] = KeyValueOption( re.sub('[ \n]+', ' ', option['param_options'])) config = config[re_option.end():] pos, param_start = 0, 0 continue if config[pos] == '{': brackets_level += 1 elif config[pos] == '}': brackets_level -= 1 if brackets_level == 0 and param_start is not None: re_block = re.search( '(?P<param_name>\w+)\s*(?P<param_options>.*)\s*{(\n){0,1}(?P<block>(.|\n)*)}', config[param_start:pos + 1], ) block = re_block.groupdict() if block['param_name'].lower() == 'location': new_block = Location(block['param_options']) parent_block.add_location(new_block) else: new_block = Block() parent_block[block['param_name']] = new_block if block['block']: parse(block['block'], new_block) config = config[re_block.end():] pos, param_start = 0, 0 continue pos += 1 if brackets_level != 0: raise Exception('Not closed bracket')
def get_best_move(self): if self.game_running: # print_matrix(self.board) #we test if this block is valid before using it test_block = Block.new_block(0, 0, False) moves = potential_moves(self.board, test_block) potential_boards = [potential_board for potential_board, _ in moves] potential_blocks = [potential_block for _, potential_block in moves] index = classifier.return_best_board(potential_boards, self.weights, rows + 1, cols) best_block = potential_blocks[index] best_block.y = 0 self.block = best_block if not self.headless: self.update_screen() if not fast_mode: while True: if self.drop(): if not self.headless: time.sleep(interval_between_drop) self.update_screen() else: break else: while True: if not self.drop(): if not self.headless: self.update_screen() break
def create_block(self): yield env.timeout(1) print("starting block formation") if len(self.txpool) != 0: for each_tx in self.txpool: self.current_gas += each_tx.gas self.current_size+= each_tx.size if self.current_gas<self.block_gas_limit: self.pendingpool.append(self.txpool.pop(0)) else: break global BLOCKID BLOCKID+=1 self.prev_block +=1 block = Block(self.current_size,self.prev_block,self.pendingpool,self.nodeID,self.prev_hash) self.prev_hash = block.hash print('%d, %d, Created, block, %d,%d'%(env.now,self.nodeID,block.id,block.size)) logger.debug('%d, %d, Created, block,%d,%d'%(env.now,self.nodeID,block.id,block.size)) print("hash of block is %s"%block.hash) self.block_list.insert(0,block) block_stability_logger.info("%s,%d,%d,created,%d"%(env.now,self.nodeID,block.id,block.size)) #print("No of blocks in node %d is %d"%(self.nodeID,len(self.block_list))) logger.info("No of blocks in node %d is %d"%(self.nodeID,len(self.block_list))) self.known_blocks.append(block.id) import ipdb; ipdb.set_trace() self.broadcaster(block,self.nodeID,1,0) self.current_gas=0 self.current_size=0 self.pendingpool=[]
def valid_placement(board, block, surface_coords): width, height = len(block.value[0]), len(block.value) results = [] #need to consider multiple positions to left for rotation_index in range(4): for offset_x in range(width)[::-1]: test_block = Block.copy_block(block) test_block.rotate_to(rotation_index) test_block.x = surface_coords[0] - offset_x test_block.y = surface_coords[1] - height #True if any of the blocks are above starting_row above_starting_row = any([y < 0 for x, y in test_block.get_coords()]) #sometimes blocks will be above while above_starting_row: test_block.y += 1 above_starting_row = any([y < 0 for x, y in test_block.get_coords()]) coords = valid_placement_helper(board, test_block) if coords: results.append(test_block) return results
def build(self): layout = load_image('assets/level1layout.png') level = Background((0, 0), 'assets/level1.png', 1, 1) background = Background((0, 0), 'assets/background1.png', 15, 15) #layout = load_image('henesyslayout.png') #level = Background((0,0), 'henesys.png', 1,1) #layout = load_image('citylevellayout.png') #level = Background((0,0), 'citylevel.png',1, 1) #layout = load_image('level3layout.png') #level = Background((0, 0), 'level3.png', 1, 1) #background = Background((0, 0), 'background3.png', 20, 20) self.backgrounds = [background, level] width, height = layout.get_size() self.blocks = [] from blocks import Block, Platform, Step for y in xrange(height): for x in xrange(width): pos = x * 8, y * 8 if layout.get_at((x, y)) == (0, 0, 0, 255): self.blocks.append(Block(pos)) elif layout.get_at((x, y)) == (0, 0, 255, 255): self.blocks.append(Platform(pos)) elif layout.get_at((x, y)) == (255, 0, 0, 255): self.blocks.append(Step(pos)) event = LevelBuildEvent(layout, self.backgrounds) self.evManager.Post(event)
def receive(obj): d = rlp.decode(obj) # Is transaction if len(d) == 8: tx = Transaction(obj) if mainblk.get_balance(tx.sender) < tx.value + tx.fee: return if mainblk.get_nonce(tx.sender) != tx.nonce: return txpool[bin_sha256(blk)] = blk broadcast(blk) # Is message elif len(d) == 2: if d[0] == 'getobj': try: return db.Get(d[1][0]) except: try: return mainblk.state.db.get(d[1][0]) except: return None elif d[0] == 'getbalance': try: return mainblk.state.get_balance(d[1][0]) except: return None elif d[0] == 'getcontractroot': try: return mainblk.state.get_contract(d[1][0]).root except: return None elif d[0] == 'getcontractsize': try: return mainblk.state.get_contract(d[1][0]).get_size() except: return None elif d[0] == 'getcontractstate': try: return mainblk.state.get_contract(d[1][0]).get(d[1][1]) except: return None # Is block elif len(d) == 3: blk = Block(obj) p = block.prevhash try: parent = Block(db.Get(p)) except: return uncles = block.uncles for s in uncles: try: sib = db.Get(s) except: return processblock.eval(parent,blk.transactions,blk.timestamp,blk.coinbase) if parent.state.root != blk.state.root: return if parent.difficulty != blk.difficulty: return if parent.number != blk.number: return db.Put(blk.hash(),blk.serialize())
def drop_helper(board, block): if block == None: return False #we first test to see if there will be a collision if block moves down test_block = Block.copy_block(block) test_block.y += 1 return not detect_collisions(board, test_block)
def rotate(self): if self.game_running: test_block = Block.copy_block(self.block) #try to rotate right test_block.rotate_right() #if there is no collision detected, rotate actual block if not detect_collisions(self.board, test_block): self.block.rotate_right()
def create_blocks(): global blocks_group colors = rand.get_random_color(5) values = rand.get_random_block_numbers(time) x = 0 y = -80 for i in range(0, 5): block = Block(colors[i], block_width, block_height, x, y, values[i]) x += block_x_increment y += block_y_increment blocks_group.add(block)
def __init__(self): # Call the parent's constructor pygame.sprite.Sprite.__init__(self) # get image self.image = pygame.image.load('pics/bro_jump3.gif').convert() self.rect = self.image.get_rect() self.image = pygame.transform.scale( self.image, (int(self.rect.width * constants.MARIO_MULTIPLIER), int(self.rect.height * constants.MARIO_MULTIPLIER))) self.rect = self.image.get_rect() self.rect.x = constants.PLAYER_START_POS self.rect.y = constants.SCREEN_HEIGHT # speed vector self.change_x = 0 self.change_y = 0 # state of player self.state = 's' # stop - right - left - jump self.pos_state = 's' # steady - jump - fall # prev coordinates self.prev_rect_x = 0 # viewport self.end_of_viewport = 1 # create blocks , remove after testing self.block_sprite_list = pygame.sprite.Group() self.block1 = Block(250, 490) self.block_sprite_list.add(self.block1) self.block2 = Block(800, 500) self.block_sprite_list.add(self.block2) self.block3 = Block(1300, constants.SCREEN_HEIGHT - 90) self.block_sprite_list.add(self.block3) # for screen stopping self.sstop = 0
def create_blocks(sets, screen, blocks, bird): """创建柱子群""" block = Block(sets, screen) block_width = block.rect.width for block_number in range(15): block_1 = Block(sets, screen) block_2 = Block(sets, screen) block_1.x = 4 * bird.rect.x + 2.5 * block_width * block_number block_2.x = 4 * bird.rect.x + 2.5 * block_width * block_number block_1.y = 200 #random.randint(150, 350) block_1.rect.x = block_1.x block_2.rect.x = block_2.x #block_1.rect.left block_1.rect.bottom = block_1.y block_2.rect.top = block_1.rect.bottom + 150 blocks.add(block_1) blocks.add(block_2)
def move(self, amt): if self.game_running: #we first test to see if there will be a collision if block moves down #by using a test_block test_block = Block.copy_block(self.block) test_block.x += amt #checks that ensure block does not go out of screen if test_block.x < test_block.buffer[0]: self.block.x = self.block.buffer[0] elif test_block.x > cols - test_block.length + test_block.buffer[1]: self.block.x = cols - self.block.length + self.block.buffer[1] #if there is a collision, then apply the movement to actual block if not detect_collisions(self.board, test_block): self.block.x += amt
def recv_blocks(self, block_lst): """ block_lst is rlp decoded data """ block_lst.reverse() # oldest block is sent first in list # FIXME validate received chain, compare with local chain for data in block_lst: logger.debug("processing block: %r" % rlp_hash_hex(data)) block = Block.deserialize(rlp.encode(data)) h = rlp_hash(data) try: self.blockchain.get(h) except KeyError: self.add_block(block) new_blocks_H.add(h)
def new_block(ledgerfilename): # ledger class instance for file name reference ledger = writer.Ledger(ledgerfilename) # parse the selected ledger writer.ledger_parse(ledger.filename) # data gets stored in lists in module chain.py l = bc_l() # blockchain length calc l -= 1 # generate the next block in the chain newblock = Block(chain.c_hash[l], chain.n_hash[l]) chain.blockchain.append(newblock) nblocklist = [ newblock.previous_hash, newblock.current_hash, newblock.next_hash ] #TODO: concensus check to eliminate duplicate blocks # add new block to the ledger writer.ledger_constructor(ledger.filename, nblocklist)
def get_tile_list(self, layer): '''given a map & specified layer, returns a Group of Block sprites on each tile in that layer ''' block_list = pygame.sprite.Group() #get block layer blocklayer = self.gamemap.get_layer_by_name(layer) #make a bunch of blocks, one for each collidable tile for x, y, gid in blocklayer: tile = self.gamemap.get_tile_image_by_gid(gid) if tile: blockx = x * self.gamemap.tilewidth blocky = y * self.gamemap.tileheight block = Block(tile, blockx, blocky) block_list.add(block) return block_list
def valid_placement(board, block, surface_coords): width, height = len(block.value[0]), len(block.value) results = [] #need to consider multiple positions to left for rotation_index in range(4): for offset_x in range(width)[::-1]: test_block = Block.copy_block(block) test_block.rotate_to(rotation_index) test_block.x = surface_coords[0] - offset_x test_block.y = surface_coords[1] - height coords = valid_placement_helper(board, test_block) if coords: results.append(test_block) return results
def reset(self): self.surface.fill(backgroundcolor) self.point = 0 self.level = 1 self.count = 0 self.time = 500 self.board_show = { i: [SingleBlock(self.surface, BLACK, WHITE) for j in range(NROWS)] for i in range(NCOLS) } self.board = { i: [0 for j in range(NROWS + 1)] for i in range(-1, NCOLS + 1) } self.board[-1] = [1 for j in range(NROWS + 1)] self.board[NCOLS] = [1 for j in range(NROWS + 1)] for i in range(-1, NCOLS + 1): self.board[i][NROWS] = 1 self.block = Block(self.board, self.board_show, random.choice(Blocks)) self.block_next = random.choice(Blocks) self.draw()
def drop(self): if self.game_running: if drop_helper(self.board, self.block): self.block.y += 1 return True #if collide, then add block to board and check if game over else: if detect_collisions(self.board, self.block): self.game_over() self.board = add_block_to_board(self.board, self.block) #if not game over, then create new block time.sleep(0.5) self.clear_rows() self.check_level() # target_coords = self.generate_best_move() # print(target_coords[0][0]) self.block = Block.new_block() # print(self.block.block_type) # print("______") return False
from validator import ConsensusMessage from validator import UnresolvedDeps from generate_transactions import gen_alice_and_bob_tx from config import * def add_switch_message(parent_shard, child_to_become_parent, child_to_move_down, position): global mempools mempools[parent_shard].insert(position, {'opcode': 'switch', 'child_to_become_parent': child_to_become_parent, 'child_to_move_down': child_to_move_down}) # Setup GENESIS_BLOCKS = {} GENESIS_MESSAGES = [] for ID in SHARD_IDS: GENESIS_BLOCKS[ID] = Block(ID, sources={}) # temporarily set sources to {}, since genesis blocks are not known yet GENESIS_MESSAGES.append(ConsensusMessage(GENESIS_BLOCKS[ID], 0, [])) # The watcher is the sender of the genesis blocks for ID in SHARD_IDS: GENESIS_BLOCKS[ID].sources = {ID : GENESIS_BLOCKS[ID] for ID in SHARD_IDS} GENESIS_BLOCKS[ID].parent_ID = None for _ in SHARD_IDS: if ID in INITIAL_TOPOLOGY[_]: GENESIS_BLOCKS[ID].parent_ID = _ GENESIS_BLOCKS[ID].child_IDs = INITIAL_TOPOLOGY[ID] for ID in SHARD_IDS: GENESIS_BLOCKS[ID].compute_routing_table() validators = {} for name in VALIDATOR_NAMES:
################################################### # this code implements a basic blockchain program # # creaton of chain # # author: and_bac 2019 # ################################################### from blocks import Block import datetime as date add_blocks = int(input("please enter the number of blocks to create the blockhain: ")) bac_chain = [Block.big_ben_block()] print("The genesis block or block 0 is created with the following Hash and timestamp: " % bac_chain[0].hash, bac_chain[0].timestamp) for i in range(1, add_blocks): bac_chain.append(Block(bac_chain[i-1].hash,"Block number %d" % i, date.datetime.now())) print("Block #%d created" % i) print("Hash: %s" % bac_chain[-1].hash) print("timestamp: %s" % bac_chain[-1].timestamp +"\n")
def make_obstacles(self): """Adds some arbitrarily placed obstacles to a sprite.Group.""" walls = [Block(pg.Color("chocolate"), (0, 980, 1000, 20)), Block(pg.Color("chocolate"), (0, 0, 20, 1000)), Block(pg.Color("chocolate"), (980, 0, 20, 1000))] static = [Block(pg.Color("darkgreen"), (250, 780, 200, 100)), Block(pg.Color("darkgreen"), (600, 880, 200, 100)), Block(pg.Color("darkgreen"), (20, 360, 880, 40)), Block(pg.Color("darkgreen"), (950, 400, 30, 20)), Block(pg.Color("darkgreen"), (20, 630, 50, 20)), Block(pg.Color("darkgreen"), (80, 530, 50, 20)), Block(pg.Color("darkgreen"), (130, 470, 200, 215)), Block(pg.Color("darkgreen"), (20, 760, 30, 20)), Block(pg.Color("darkgreen"), (400, 740, 30, 40))] moving = [MovingBlock(pg.Color("olivedrab"), (20, 740, 75, 20), 325, 0), MovingBlock(pg.Color("olivedrab"), (600, 500, 100, 20), 880, 0), MovingBlock(pg.Color("olivedrab"), (420, 430, 100, 20), 550, 1, speed=3, delay=200), MovingBlock(pg.Color("olivedrab"), (450, 700, 50, 20), 930, 1, start=930), MovingBlock(pg.Color("olivedrab"), (500, 700, 50, 20), 730, 0, start=730), MovingBlock(pg.Color("olivedrab"), (780, 700, 50, 20), 895, 0, speed=-1)] return pg.sprite.Group(walls, static, moving)
def sharded_fork_choice(starting_blocks, blocks, weighted_blocks, parent_shard_fork_choice: Block, child_IDs: List[int]): # TYPE GUARD for ID in starting_blocks.keys(): assert ID in SHARD_IDS, "expected shard IDs" assert isinstance(starting_blocks[ID], Block), "expected starting blocks to be blocks" assert starting_blocks[ ID] in blocks, "expected starting blocks to appear in blocks" assert starting_blocks[ID].is_valid(), "expected valid blocks" for b in blocks: assert isinstance(b, Block), "expected blocks" assert b.is_valid(), "expected valid blocks" assert isinstance(weighted_blocks, dict), "expected dictionary" for b in weighted_blocks.keys(): assert b in blocks, "expected weighted blocks to appear in blocks" assert isinstance(b, Block), "expected block" assert b.is_valid(), "expected valid blocks" assert weighted_blocks[b] > 0, "expected positive weights" # --------------------------------------------------------------------# parent_ID = parent_shard_fork_choice.shard_ID # THE CHILD SHARD HAS TO FILTER BLOCKS FROM ITS FORK CHOICE # AS A FUNCTION OF THE FORK CHOICE OF THE PARENT block_filter = [] for b in blocks: # blocks on the parent shard aren't filtered if b.shard_ID == parent_ID: continue # FILTER BLOCKS THAT DONT AGREE WITH MOST RECENT SOURCE if parent_shard_fork_choice.sources[b.shard_ID] is not None: if not parent_shard_fork_choice.sources[b.shard_ID].is_in_chain(b): if not b.is_in_chain( parent_shard_fork_choice.sources[b.shard_ID]): block_filter.append(b) continue # --------------------------------------------------------------------# # FILTER BLOCKS WITH ORPHANED SOURCES if b.sources[parent_ID] is not None: if not parent_shard_fork_choice.is_in_chain(b.sources[parent_ID]): block_filter.append(b) continue # --------------------------------------------------------------------# # FILTER BLOCKS WITH ORPHANED BASES filtered = False for m in b.newly_sent()[parent_ID]: if not parent_shard_fork_choice.is_in_chain(m.base): block_filter.append(b) filtered = True break if filtered: continue # --------------------------------------------------------------------# # FILTER BLOCKS THAT FAIL TO RECEIVE MESSAGES FROM PARENT ON TIME filtered = False for m in parent_shard_fork_choice.sent_log.log[ b.shard_ID]: # inefficient if m in b.received_log.log[parent_ID]: continue if b.height >= m.base.height + m.TTL: # EXPIRY CONDITION block_filter.append(b) filtered = True break if filtered: continue # --------------------------------------------------------------------# # FILTER BLOCKS THAT SEND MESSAGES THAT WERE NOT RECEIVED IN TIME filtered = False for m in b.sent_log.log[parent_ID]: # inefficient if m in parent_shard_fork_choice.received_log.log[b.shard_ID]: continue if parent_shard_fork_choice.height >= m.base.height + m.TTL: # EXPIRY CONDITION block_filter.append(b) filtered = True continue # --------------------------------------------------------------------# # CALCULATE CHILD FORK CHOICE (FILTERED GHOST) return { child_ID: fork_choice(starting_blocks[child_ID], blocks, weighted_blocks, block_filter) for child_ID in child_IDs }
insn_len = 4 reg_size = 4 r1 = Varnode('register', 0, reg_size) r2 = Varnode('register', reg_size, reg_size) r3 = Varnode('register', reg_size * 2, reg_size) u0 = Varnode('unique', 0, reg_size) insn1 = Instruction(insn_addr, insn_len, [PcodeOp(insn_addr, 'INT_ADD', [r1, r2], u0)]) insn2 = Instruction(insn_addr, insn_len, [PcodeOp(insn_addr, 'COPY', [u0], r3)]) insn3 = Instruction(insn_addr, insn_len, [PcodeOp(insn_addr, 'COPY', [u0], r1)]) # Simple test CFG s_block1 = Block([insn1.copy()], name='s_block_1') s_block2 = Block([insn1.copy()], predecessor=s_block1, name='s_block_2') s_block3 = Block([insn1.copy()], predecessor=s_block1, name='s_block_3') s_block4 = Block([insn1.copy()], predecessor=s_block3, name='s_block_4') simple_cfg_blocks = [s_block2, s_block3, s_block4, s_block1] # Complex test CFG 1 c1_block1 = Block([insn1.copy(), insn2], name='c1_block_1') c1_block2 = Block([insn1.copy()], predecessor=c1_block1, name='c1_block_2') c1_block3 = Block([insn1.copy()], predecessor=c1_block1, name='c1_block_3') c1_block4 = Block([insn1.copy()], predecessor=c1_block3, name='c1_block_4') c1_block4.add_predecessor(c1_block2) complex1_cfg_blocks = [c1_block2, c1_block3, c1_block4, c1_block1] # Complex test CFG 2 c2_block1 = Block([insn1.copy(), insn2], name='c2_block_1')
def main(): if len(sys.argv) == 1: print 'Available Functions:' print ' --setup' print print ' --account/verify_credentials(email, password)' print ' --account/settings (user_id)' print ' --account/update_settings (user_id, email, password, privacy, locale, timezone)' print ' --account/update_profile(user_id, username, name, bio, website, image)' print ' --account/create(email, password, username, name, privacy)' print print ' --blocks/exists (user_id, follower_id)' print ' --blocks/blocking/ids (user_id)' print ' --blocks/create (user_id, follower_id)' print ' --blocks/destroy (user_id, follower_id)' print print ' --users/show (user_id)' print ' --users/lookup (user_ids)' print ' --users/search (query)' print ' --users/flag (user_id)' print print ' --friends/ids (user_id)' print ' --followers/ids (user_id)' print print ' --friendships/create (user_id, following_id)' print ' --friendships/destroy (user_id, following_id)' print ' --friendships/exists (user_id, following_id)' print ' --friendships/show (user_id, following_id)' print ' --friendships/incoming (user_id)' print ' --friendships/outgoing (user_id)' print print ' --entities/show (entity_id)' print ' --entities/create (title, category)' print ' --entities/destroy (entity_id)' print ' --entities/update (entity_id, title, category)' print ' --entities/match (query)' print print ' --stamps/create (uid, entity_id, comment)' print ' --stamps/show (stamp_id)' print ' --stamps/destroy (stamp_id)' print ' --stamps/flag (stamp_id, [is_flagged])' print ' --stamps/read (stamp_id, [user_id], [is_read])' print print ' --conversation/show (comment_id)' print ' --conversation/create (user_id, stamp_id, comment)' print ' --conversation/destroy (comment_id)' print ' --conversation/flag (comment_id, [is_flagged])' print print ' --mentions/create (stamp_id, user_id)' print ' --mentions/destroy (stamp_id, user_id)' print ' --mentions/user (user_id)' print print ' --collections/inbox (user_id)' print ' --collections/user (user_id)' print ' --collections/add_stamp (stamp_id)' print print ' --favorites/show (user_id)' print ' --favorites/create (stamp_id, user_id)' print ' --favorites/destroy (stamp_id, user_id)' print sys.exit(1) option = sys.argv[1] # Setup: if option == '--setup': setup.setup() # Account: elif option == '--account/verify_credentials': account = Account() checkNumberOfArguments(2, len(sys.argv)) response = account.verify_credentials(sys.argv[2], sys.argv[3]) print 'Response: ', response elif option == '--account/settings': account = Account() checkNumberOfArguments(1, len(sys.argv)) response = account.settings(sys.argv[2]) print 'Response: ', response elif option == '--account/update_settings': account = Account() checkNumberOfArguments(6, len(sys.argv)) response = account.update_settings(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7]) print 'Response: ', response elif option == '--account/update_profile': account = Account() checkNumberOfArguments(6, len(sys.argv)) response = account.update_profile(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7]) print 'Response: ', response elif option == '--account/create': account = Account() checkNumberOfArguments(5, len(sys.argv)) response = account.create(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6]) print 'Response: ', response # Blocks: elif option == '--blocks/exists': block = Block() checkNumberOfArguments(2, len(sys.argv)) response = block.exists(sys.argv[2], sys.argv[3]) print 'Response: ', response elif option == '--blocks/blocking': block = Block() checkNumberOfArguments(1, len(sys.argv)) response = block.blocking(sys.argv[2]) print 'Response: ', response elif option == '--blocks/create': block = Block() checkNumberOfArguments(2, len(sys.argv)) response = block.create(sys.argv[2], sys.argv[3]) print 'Response: ', response elif option == '--blocks/destroy': block = Block() checkNumberOfArguments(2, len(sys.argv)) response = block.destroy(sys.argv[2], sys.argv[3]) print 'Response: ', response # Users: elif option == '--users/show': user = User() checkNumberOfArguments(1, len(sys.argv)) response = user.show(sys.argv[2]) print 'Response: ', response elif option == '--users/lookup': user = User() checkNumberOfArguments(1, len(sys.argv)) user_ids = [] for user_id in sys.argv[2:]: user_ids.append(user_id) response = user.lookup(user_ids) print 'Response: ', response elif option == '--users/search': user = User() checkNumberOfArguments(1, len(sys.argv)) response = user.search(sys.argv[2]) print 'Response: ', response elif option == '--users/flag': user = User() if len(sys.argv) == 4: response = user.flag(sys.argv[2], sys.argv[3]) elif len(sys.argv) == 3: response = user.flag(sys.argv[2]) else: print 'Missing parameters' sys.exit(1) print 'Response: ', response # Friends & Followers: elif option == '--friends/ids': friend = Friend() checkNumberOfArguments(1, len(sys.argv)) response = friend.ids(sys.argv[2]) print 'Response: ', response elif option == '--followers/ids': follower = Follower() checkNumberOfArguments(1, len(sys.argv)) response = follower.ids(sys.argv[2]) print 'Response: ', response # Friendships: elif option == '--friendships/create': friendship = Friendship() checkNumberOfArguments(2, len(sys.argv)) response = friendship.create(sys.argv[2], sys.argv[3]) print 'Response: ', response elif option == '--friendships/destroy': friendship = Friendship() checkNumberOfArguments(2, len(sys.argv)) response = friendship.destroy(sys.argv[2], sys.argv[3]) print 'Response: ', response elif option == '--friendships/exists': friendship = Friendship() checkNumberOfArguments(2, len(sys.argv)) response = friendship.exists(sys.argv[2], sys.argv[3]) print 'Response: ', response elif option == '--friendships/show': friendship = Friendship() checkNumberOfArguments(2, len(sys.argv)) response = friendship.show(sys.argv[2], sys.argv[3]) print 'Response: ', response elif option == '--friendships/incoming': friendship = Friendship() checkNumberOfArguments(1, len(sys.argv)) response = friendship.incoming(sys.argv[2]) print 'Response: ', response elif option == '--friendships/outgoing': friendship = Friendship() checkNumberOfArguments(1, len(sys.argv)) response = friendship.outgoing(sys.argv[2]) print 'Response: ', response # Entities: elif option == '--entities/show': entity = Entity() checkNumberOfArguments(1, len(sys.argv)) response = entity.show(sys.argv[2]) print 'Response: ', response elif option == '--entities/create': entity = Entity() checkNumberOfArguments(2, len(sys.argv)) response = entity.create(sys.argv[2], sys.argv[3]) print 'Response: ', response elif option == '--entities/destroy': entity = Entity() checkNumberOfArguments(1, len(sys.argv)) response = entity.destroy(sys.argv[2]) print 'Response: ', response elif option == '--entities/update': entity = Entity() checkNumberOfArguments(3, len(sys.argv)) response = entity.update(sys.argv[2], sys.argv[3], sys.argv[4]) print 'Response: ', response elif option == '--entities/match': entity = Entity() checkNumberOfArguments(1, len(sys.argv)) response = entity.match(sys.argv[2]) print 'Response: ', response # Stamps: elif option == '--stamps/create': stamp = Stamp() checkNumberOfArguments(3, len(sys.argv)) response = stamp.create(sys.argv[2], sys.argv[3], sys.argv[4]) print 'Response: ', response elif option == '--stamps/show': stamp = Stamp() checkNumberOfArguments(1, len(sys.argv)) response = stamp.show(sys.argv[2]) print 'Response: ', response elif option == '--stamps/destroy': stamp = Stamp() checkNumberOfArguments(1, len(sys.argv)) response = stamp.destroy(sys.argv[2]) print 'Response: ', response elif option == '--stamps/flag': stamp = Stamp() if len(sys.argv) == 4: response = stamp.flag(sys.argv[2], sys.argv[3]) elif len(sys.argv) == 3: response = stamp.flag(sys.argv[2]) else: print 'Missing parameters' sys.exit(1) print 'Response: ', response elif option == '--stamps/read': stamp = Stamp() if len(sys.argv) == 5: response = stamp.read(sys.argv[2], sys.argv[3], sys.argv[4]) elif len(sys.argv) == 4: response = stamp.read(sys.argv[2], sys.argv[3]) elif len(sys.argv) == 3: response = stamp.read(sys.argv[2]) else: print 'Missing parameters' sys.exit(1) print 'Response: ', response # Conversation: elif option == '--conversation/show': conversation = Conversation() checkNumberOfArguments(1, len(sys.argv)) response = conversation.show(sys.argv[2]) print 'Response: ', response elif option == '--conversation/create': conversation = Conversation() checkNumberOfArguments(3, len(sys.argv)) response = conversation.create(sys.argv[2], sys.argv[3], sys.argv[4]) print 'Response: ', response elif option == '--conversation/destroy': conversation = Conversation() checkNumberOfArguments(1, len(sys.argv)) response = conversation.destroy(sys.argv[2]) print 'Response: ', response elif option == '--conversation/flag': conversation = Conversation() if len(sys.argv) == 4: response = conversation.flag(sys.argv[2], sys.argv[3]) elif len(sys.argv) == 3: response = conversation.flag(sys.argv[2]) else: print 'Missing parameters' sys.exit(1) print 'Response: ', response # Mentions: elif option == '--mentions/create': mention = Mention() checkNumberOfArguments(2, len(sys.argv)) response = mention.create(sys.argv[2], sys.argv[3]) print 'Response: ', response elif option == '--mentions/destroy': mention = Mention() checkNumberOfArguments(2, len(sys.argv)) response = mention.destroy(sys.argv[2], sys.argv[3]) print 'Response: ', response elif option == '--mentions/user': mention = Mention() checkNumberOfArguments(1, len(sys.argv)) response = mention.user(sys.argv[2]) print 'Response: ', response # Collections: elif option == '--collections/inbox': collection = Collection() checkNumberOfArguments(1, len(sys.argv)) response = collection.inbox(sys.argv[2]) print 'Response: ', response elif option == '--collections/user': collection = Collection() checkNumberOfArguments(1, len(sys.argv)) response = collection.user(sys.argv[2]) print 'Response: ', response elif option == '--collections/add_stamp': collection = Collection() checkNumberOfArguments(1, len(sys.argv)) response = collection.add_stamp(sys.argv[2]) print 'Response: ', response # Favorites: elif option == '--favorites/show': favorite = Favorite() checkNumberOfArguments(1, len(sys.argv)) response = favorite.show(sys.argv[2]) print 'Response: ', response elif option == '--favorites/create': favorite = Favorite() checkNumberOfArguments(2, len(sys.argv)) response = favorite.create(sys.argv[2], sys.argv[3]) print 'Response: ', response elif option == '--favorites/destroy': favorite = Favorite() checkNumberOfArguments(2, len(sys.argv)) response = favorite.destroy(sys.argv[2], sys.argv[3]) print 'Response: ', response else: print 'unknown option: ' + option sys.exit(1)
pygame.display.update() blocks.empty() while nextlev < 600: nextlev += 1 gameover.fill((250,250,250)) tekst2 = font2.render(" LEVEL " + str(lev), True, (0,0,0) ) gameover.blit( tekst2, (180,150) ) screengl.blit(gameover, (0,0)) nl_sound.play() pygame.display.update() if lev == 2: for i in range(4): for column in range(32): if i % 2 == 1: if column % 2 == 1: block=Block((100,100+20*i,250-30*i),column*(25)+1,120+i*20) block.life = 2 blocks.add(block) else: if column % 2 == 0: block=Block((100,100+20*i,250-30*i),column*(25)+1,120+i*20) block.life = 2 blocks.add(block) if lev == 3: for i in range(5): for column in range(32): if column % 2 == 0: block=Block((40*i,250-50*i,60*i),column*(25)+1,120+i*23) block.life = 3 blocks.add(block) ball.y = 220
def __init__(self, *args, **kwargs): Block.__init__(self, *args, **kwargs)
def init_game(self): self.score = 0 self.level = 1 self.lines_cleared = 0 self.board = self.new_board() self.block = Block.new_block()