Пример #1
0
    def __init__(self, over, under):
        Top.__init__(self, find_bounding_box(over + under))

        from block import Block

        self.over = Block(over)
        self.under = Block(under)
Пример #2
0
 def __init__(self, adjStats = string.ascii_letters + ' ', noisy = False):
   # Load it...
   if noisy: print 'Reading in ply2 corpus file...'
   data = read(os.path.join(os.path.dirname(__file__),'corpus.ply2'))
   
   # Convert contents into a list of blocks...
   self.blocks = []
   
   t_arr = data['element']['document']['text']
   a_arr = data['element']['document']['attribution']
   
   if noisy:
     print 'Creating blocks...'
   
   for i in xrange(t_arr.shape[0]):
     b = Block(t_arr[i], a_arr[i])
     self.blocks.append(b)
     
   # Construct all statistics - this gets complicated for reasons of efficiency...
   if noisy:
     print 'Collecting statistics...'
   
   self.counts = numpy.zeros(256, dtype=numpy.int32)
   self.adj = numpy.zeros((len(adjStats),len(adjStats)), dtype=numpy.int32)
   self.adj_index = adjStats
   
   for b in self.blocks:
     b.stats(self.counts, self.adj, self.adj_index)
Пример #3
0
 def _block_real_name(self):
     if type(self._block) is str:
         return Block.to_real_name(Block.from_full_name(self._block)[1])
     elif self._block is None:
         return None
     else:
         return self._block.real_name()
Пример #4
0
class Game:

	def __init__( self, scr, loop ):

		self.scr = scr

		from block import Block
		self.block = Block( scr )

		from message import Messages
		self.msg = Messages( self.scr )

		self.loop = loop

		self.FPS = 60

		self.block( self, self.loop )

	def update( self ):

		lasttime = time.time(  )

		self.block.update(  )

		self.FPS = 1.0 / ( time.time(  ) - lasttime )

	def draw( self ):

		scr = self.scr
		scr.fill( ( 35, 35, 35 ) )

		self.block.draw(  )
		self.msg.message( round( self.FPS, 1 ), ( 10, 10 ) )
Пример #5
0
def make_updated_block_for_site(transformation_matrix,
		                operators_to_add_to_block):
    """Make a new block for a list of operators.

    Takes a dictionary of operator names and matrices and makes a new
    block inserting in the `operators` block dictionary the result of
    transforming the matrices in the original dictionary accoring to the
    transformation matrix.

    You use this function everytime you want to create a new block by
    transforming the current operators to a truncated basis. 

    Parameters
    ----------
    transformation_matrix : a numpy array of ndim = 2.
        The transformation matrix coming from a (truncated) unitary
	transformation.
    operators_to_add_to_block : a dict of strings and numpy arrays of ndim = 2.
        The list of operators to transform.

    Returns
    -------
    result : a Block.
        A block with the new transformed operators.
    """
    cols_of_transformation_matrix = transformation_matrix.shape[1]
    result = Block(cols_of_transformation_matrix)
    for key in operators_to_add_to_block.keys():
	result.add_operator(key)
	result.operators[key] = transform_matrix(operators_to_add_to_block[key],
			                         transformation_matrix)
    return result
Пример #6
0
 def __init__(self, size):
     """Initialize board:
        argument: size
     """
     self.size = size
     self.side = BLACK
     self.goban = {} #actual board
     self.init_hash()
     #Create and initialize board as empty size*size
     for pos in self.iterate_goban():
         #can't use set_goban method here, because goban doesn't yet really exists
         self.goban[pos] = EMPTY
         self.current_hash = self.current_hash ^ self.board_hash_values[EMPTY, pos]
     self.blocks = {} #blocks dictionary
     #Create and initialize one whole board empty block
     new_block = Block(EMPTY)
     for pos in self.iterate_goban():
         new_block.add_stone(pos)
     self.block_dict = {}
     self.add_block(new_block)
     self.chains = {}
     self.stone_count = {}
     for color in EMPTY+BLACK+WHITE:
         self.stone_count[color] = 0
     self.ko_flag = PASS_MOVE
     BoardAnalysis.__init__(self)
Пример #7
0
    def compute_blocks(self):
        """
            Compute the set of blocks that C infer
            return: Topologically sorted blocks T_c
        """

        timer_start('Compute blocks')

        T_c = list()
        T_unions = set()

        # iterate the combination sizes in reverse
        a = range(len(self.C)+1)[::-1]
        for i in a:
            choose = i
            for comb in combinations(self.C, choose):
                union = itemsets.union_of_itemsets(comb)

                if not union in T_unions:
                    T_unions.add(union)
                    T = Block()
                    T.union_of_itemsets = union
                    T.singletons = itemsets.singletons_of_itemsets(comb)
                    T.itemsets = set(comb)

                    T_c.append(T)

        timer_stop('Compute blocks')
        return T_c
Пример #8
0
def parse(blockchain):
	print 'print Parsing Block Chain'
	counter = 0
	while True:
		print counter
		block = Block(blockchain)
		block.toString()
		counter+=1
Пример #9
0
 def __init__(self, image_path, position, center, collider=None):
     Block.__init__(self, image_path, position, collider)
     self.center = center
     self.this_center = pygame.math.Vector2(self.position.x
                                            + self.animation.current_frame().get_width() / 2,
                                            self.position.y
                                            + self.animation.current_frame().get_height() / 2)
     self.distance = self.this_center - self.center
     self.type = Entity.TYPE_OBJECT_DYNAMIC
Пример #10
0
def parse(file_name):
    '''function that takes a file name, and returns a list of blocks,
       instances of class Block.'''
    from block import Block
# open file, specified on command line
    block_file = open(file_name, 'r')
# compile the regular expressions to be used for performance reasons
    comment_pattern = re.compile(r'\s*#.*')
    block_start_pattern = re.compile(r'\s*begin\s+(\w+)')
    block_end_pattern = re.compile(r'\s*end\s+(\w+)')
# current_block holds an instance of Block for the block that is being
# parsed, its # value is None when outside a block, note that it doubles
# as state variable
    current_block = None
# list to hold the blocks
    blocks = []
    for line in block_file:
        # remove leading/triailing spaces, and comments (i.e., everything
        # following a '#'
        line = comment_pattern.sub('', line.strip())
# ignore blank lines
        if len(line) == 0:
            continue
# check for begin block
        match = block_start_pattern.match(line)
        if match is not None:
            # if current_block is not None, we are already in a block,
            # raise error
            if current_block is not None:
                raise ParseError(
                    'block {0} is not close when opening {1}'.format(
                        current_block.get_name(), match.group(1)))
# now in a block, so change state
            current_block = Block(match.group(1))
            continue
# check for end block
        match = block_end_pattern.match(line)
        if match is not None:
            # if the end block name is not the current block, raise error
            if match.group(1) != current_block.get_name():
                raise ParseError(
                    'block {0} is closed with {1}'.format(
                        match.group(1), current_block.get_name()))
# now out of a block, add current block to the list, and change state
            blocks.append(current_block)
            current_block = None
            continue
# if not in a block, ignore the line
        if current_block is None:
            continue
        else:
            # store block data
            current_block.add_data(line)
# close the file
    block_file.close()
    return blocks
Пример #11
0
 def split_marked_group(self, block, mark):
     """move all stones with given mark to new block
        Return splitted group.
     """
     new_block = Block(block.color)
     for stone, value in block.stones.items():
         if value==mark:
             block.remove_stone(stone)
             new_block.add_stone(stone)
     return new_block
Пример #12
0
def new_next_block():
    global next_block
    global next_block_pos
    new_type = random.choice(block_types)
    next_block = Block(new_type[0], new_type[1], [0, 0], board_width, board_height)
    width, height = next_block.get_size()
    width *= block_size
    height *= block_size
    x = next_block_surface[0] + next_block_surface[2] / 2 - width / 2
    y = next_block_surface[1] + next_block_surface[3] / 2 - height / 2
    next_block_pos = [x, y]
Пример #13
0
 def __init_blocks(self):
     self.blocks = list()
     row_mid = len(self.piece[0])/2
     row_offset = self.__first_non_empty_row()
     for row in range(0, len(self.piece)):
         for col in range(0, len(self.piece[row])):
             block_symbol = self.piece[row][col]
             if block_symbol != '.':
                 block = Block(block_symbol)
                 block.move_to((col - row_mid, row - row_offset))
                 self.blocks.append(block)
Пример #14
0
    def spawn_block(self):
        """
        Creates a new block with random starting position/random orientation.
        """
        block = Block()
        #block.position = (random.randint(0,GRID_WIDTH-1),block.position[1]) #uncomment here and comment below for randomly positioned blocks
        block.position = (GRID_WIDTH/2,block.position[1]) #spawn in middle of field
        for i in range(random.randint(0,3)): #random orientation
            block.rotate(True)

        self.block_count += 1
        return block
Пример #15
0
 def __merge(self,ns_list):
     block_li = []                 # 文本块列表
     block = Block()               # 文本块
     for i in range(len(ns_list)):
         if ns_list[i]['offset'] >= 1:#thr:                
             # 大于或等于阈值,保存上一个块,划给新块
             if not block.is_empty():
                 block_li.append( block )
                 block = Block()               # 新增文本块
         if ns_list[i]['node'] and ns_list[i]['node'].string.strip():
             block.append( ns_list[i]['node'] )
     return block_li
Пример #16
0
def polarArray(geom,numberOfCopies,totalAngle=2*pi,center=Point(0,0)):
    '''
    array geometric entity in a polar pattern
    '''
    b = Block()
    theta_step = totalAngle / numberOfCopies
    theta = 0.0
    for i in range(numberOfCopies):
        g = rotateAboutPoint(geom,center,theta)
        b.append(g)
        theta += theta_step
    return b
Пример #17
0
    def test_add_blocks(self):
        self.test_init_field()

        for i, b_data in enumerate(self.raw_data):
            b = Block(b_data["type"], b_data["conns"], b_data["name"], b_data["groups"])

            b.rotate(b_data["rot"])
            b.mirror(set_to=b_data["mir"])

            self.field.add_block(b, b_data["pos"])

        self.assertEqual(len(self.field), len(self.raw_data))
Пример #18
0
def rectArray(geom,xNum,xStep,yNum=1,yStep=None):
    '''
    array geometric entity in a rectangular pattern
    '''
    b = Block()
    y = 0.0
    for j in range(yNum):
        x = 0.0
        for i in range(xNum):
            t = AffineMatrix().translation(Vector(x,y,0.0))
            b.append(t * geom)
            x += xStep
        y += yStep
    return b
Пример #19
0
def parse(blockchain): 
        print 'Parsing Block Chain' 
        
        '''
        block = Block(blockchain) 
        return block
        '''
        
        counter = 0 
        while True: 
                print counter 
                block = Block(blockchain) 
                block.toString() 
                print "\n"*10
                counter+=1 
Пример #20
0
 def _block_name(self):
     if type(self._block) is str:
         return Block.from_full_name(self._block)[1]
     elif self._block is None:
         return None
     else:
         return self._block.name
Пример #21
0
 def _dataset_name(self):
     if type(self._block) is str:
         return Block.from_full_name(self._block)[0]
     elif self._block is None:
         return None
     else:
         return self._block.dataset.name
Пример #22
0
    def __init__(self):

        #self.TICKS_PER_SEC = TICKS_PER_SEC

        # A Batch is a collection of vertex lists for batched rendering.
        self.batch = pyglet.graphics.Batch()

        # A TextureGroup manages an OpenGL texture.
        self.group = Textures._texture_group

        # Block useful methods
        self.block = Block()

        # A mapping from position to the texture of the block at that position.
        # This defines all the blocks that are currently in the world.
        self.world = dict()

        # Same mapping as `world` but only contains blocks that are shown.
        self.shown = dict()

        # Mapping from position to a pyglet `VertextList` for all shown blocks.
        self._shown = dict()

        # Mapping from sector to a list of positions inside that sector.
        self.sectors = dict()

        # Simple function queue implementation. The queue is populated with
        # _show_block() and _hide_block() calls
        self.queue = deque()

        self._initialize()
Пример #23
0
 def init(self):
     self.Repeat = 0
     super(ColorDiffGame, self).init()
     self.block = Block(color = ColorDiffGame.GREEN,level=self.level,score = self.score)
     self.startgame = False
     self.block.constant()
     self.render_score()
Пример #24
0
def parse(blockchain):
	print 'print Parsing Block Chain'
	continueParsing = True
	counter = 0
	blockchain.seek(0, 2)
	fSize = blockchain.tell() - 80 #Minus last Block header size for partial file
	blockchain.seek(0, 0)
	while continueParsing:	
		block = Block(blockchain)
		continueParsing = block.continueParsing
		if continueParsing:
			block.toString()
		counter+=1

	print ''
	print 'Reached End of Field'
	print 'Parsed %s blocks', counter
Пример #25
0
def parse(blockchain, block_counter_start=0, datfilenum=0, debug=False):
	if debug: print 'print Parsing Block Chain'
	continueParsing = True
	counter = block_counter_start
	blockchain.seek(0, 2)
	fSize = blockchain.tell() - 80 #Minus last Block header size for partial file
	blockchain.seek(0, 0)
	while continueParsing:	
		block = Block(blockchain, counter, datfilenum, debug)
		continueParsing = block.continueParsing
		if continueParsing:
			if debug: block.toString()
			block.toCSV()
		counter+=1

	if debug: print ''
	if debug: print 'Reached End of Field'
	if debug: print 'Parsed %s blocks', counter
    def next_block(self):
        """Get the next block for fitting. Returns None when the end 
        of the data is reached.
        """
        if self.debug:
            print("\nSearching for next block...")
            print("    Starting index:", self.idx)

        # Call the C function that will do the actual search. 
        return_inds = np.zeros(2, dtype=np.int64)
        b = blockident_median_c.next_block(
            max(self.idx - self.filt_len, 0), 
            self.filt_len, 
            self.pad_post,
            self.max_len,
            self.th,
            self.r,
            return_inds)
        i0, i1 = return_inds

        # Are we at the end of the data? 
        if i0 == self.r.size:
            return None

        # Construct new block.
        block = Block(self.r, self.p,
                      max(i0 - self.pad_pre, 0),
                      min(i1 + self.pad_post, self.r.size - 1),
                      b)

        block.exclude_pre = self.exclude_pre
        block.exclude_post = self.exclude_post
        
        # Update current index, always making some progress. 
        # This helps us avoid a problem that occurs when we reach the
        # end of the data. 
        self.set_position(max(self.idx + 1, block.i1 - self.exclude_post))
        
        if self.debug:
            print("    Found block   :", block.i0)
            print("    Length        :", block.i1 - block.i0)
        
        return block
Пример #27
0
    def newBlock(self):
        #新方塊
        self.block = Block(0, self.col_size//2)

        for row, col in self.block.tellAllPos():
            if self.board[row][col] > 0:
                self.mergeBlock()
                self.draw()
                print("遊戲結束")
                sys.exit()
Пример #28
0
def CalculateBlocks(video_image):
	start = time.time()
        orig_image = video_image
	# orig_image = cv2.imread("block_test.jpg")
	# orig_image = cv2.imread("Picture 11.jpg") # Picture 6-11
	# cv2.imshow("Original", orig_image)
	image = cv2.resize(orig_image, (0,0), fx=0.25, fy=0.25) # half x and y axes
	height, width, channels = image.shape
	# BGR
	# for y in range(0, width):
	# 	for x in range(0, height):
	# 		red = image.item(x,y,2) 
	# 		green = image.item(x,y,1)
	# 		blue = image.item(x,y,0)
	# 		if red > 1.3 * green and red > 1.3 * blue:
	# 			image.itemset((x,y,2),0)
	# 			image.itemset((x,y,1),0)
	# 			image.itemset((x,y,0),0)

	blocks = []
	for x in xrange(10,width-10,10):
		for y in xrange(10,height-10,10):
			block = Block(x,y);

			# print("x,y:", x,",",y)
			FloodFill(x,y,image,block)

			# print("numPixels: ", block.getNumPixelsInBlock())
			if block.getNumPixelsInBlock() > 500:
                                block.meanX = block.accumulatedX / block.getNumPixelsInBlock()
				blocks.append(block)
                                # x, y = block.getBlockBottomPixel()
				# print(x,y)
                                # print (block.meanX == x)
                                # image.itemset((y, x, 0),0)
                                # image.itemset((y, x, 1),255)
                                # image.itemset((y, x, 2),0)

	# print("Blocks: ", len(blocks))
	end = time.time()
	# print("Time: ", (end - start))
	return blocks
Пример #29
0
def parse(blockchain, blkNo):
	print 'Parsing Block Chain block head, transaction etc.'
	continueParsing = True
	counter = 0
	blockchain.seek(0, 2)
	fSize = blockchain.tell() - 80 #Minus last Block header size for partial file
	blockchain.seek(0, 0)
	while continueParsing:	
		block = Block(blockchain)
		continueParsing = block.continueParsing
		if continueParsing:
			block.toString()
		counter+=1
		print "#"*20+"Block counter No. %s"%counter +"#"*20
		if counter >= blkNo and blkNo != 0xFF:
			continueParsing = False

	print ''
	print 'Reached End of Field'
	print "Parsed %d blocks" % counter
Пример #30
0
def get_block_list(world):
	blocks = {}
	for obj in world.objects.values():
		if obj.type.name != "BLOCK":
			continue
		block = None
		if world.atom_true(worldsim.Atom(world.predicates["table"], [obj])):
			block = Block(Block.TABLE, obj.name)
		elif world.atom_true(worldsim.Atom(world.predicates["triangle"], [obj])):
			block = Block(Block.TRIANGLE, obj.name)
		elif world.atom_true(worldsim.Atom(world.predicates["block"], [obj])):
			block = Block(Block.SQUARE, obj.name)
		if not block:
			continue
		block.clear = False
		block.on = None
		block.onfire = False
		if block.type == block.TABLE:
			table = block
		blocks[obj.name] = block
	for atom in world.atoms:
		if atom.predicate == world.predicates["on"]:
			blocks[atom.args[0].name].on = blocks[atom.args[1].name]
		elif atom.predicate == world.predicates["on-table"]:
			blocks[atom.args[0].name].on = table
		elif atom.predicate == world.predicates["clear"]:
			blocks[atom.args[0].name].clear = True
		elif atom.predicate == world.predicates["onfire"]:
			blocks[atom.args[0].name].onfire = True
	return sorted(blocks.values(), key = lambda x: x.id)
Пример #31
0
 def __init__(self):
     self.chain = [Block.genesis()]
     self.blockindex = 1
     self.reward = 10
def run_model(x, start_bottom_y,start_top_y, step, multipliers, x_interval,  save_name):

    """ Main Program """
    stop = start_top_y
    count = 1
    while stop > 0:

        stop -= step
        print_data = True

        save_folder_path = save_name + str(count)


        test_levels = build_blueprint_range(x=x, start_bottom_y=start_bottom_y, start_top_y=start_top_y, width=100,
                                            stop=stop, multipliers=multipliers, y_interval=1, x_interval=x_interval)


        #level1
        levels = Block.generate(SCREEN_WIDTH, SCREEN_HEIGHT, 100, True, test_levels)

        screen, clock, current_level, current_level_no = init(SCREEN_WIDTH, SCREEN_HEIGHT, levels)


        done = False
        while not done:

            # --- Event Processing ---

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True


            # --- Drawing ---
            screen.fill(WHITE)

            for block in current_level:
                block.draw(screen)


            capture(surface=screen, mode='capture', remove_blank_frames=True,
                    level_number=current_level_no,
                    save_folder_path=save_folder_path, preview=False)

            if current_level_no < len(levels) - 1:
                current_level_no += 1
                current_level = levels[current_level_no]
            else:
                done = True


            pygame.display.flip()

            clock.tick(60)



        if print_data:
            print('Simulation Terminated')
        pygame.quit()
        count += 1
Пример #33
0
from blockchain import BlockChain
from block import Block
from hashlib import sha256
from json import dumps

genesis_prev_hash = sha256((b'\x00' * 32))

genesis_data = 'Hello there!'.encode('utf-8')
data1 = '1!'.encode('utf-8')
data2 = '2!'.encode('utf-8')
data3 = '3!'.encode('utf-8')
data4 = '4!'.encode('utf-8')

genesis_block = Block(genesis_data, genesis_prev_hash.digest())
block1 = Block(data1, genesis_block.hash())
block2 = Block(data2, block1.hash())
block3 = Block(data3, block2.hash())
block4 = Block(data4, block1.hash())

blockchain = BlockChain(genesis_block)

one = blockchain.append(block1)
two = blockchain.append(block2)
three = blockchain.append(block3)
four = blockchain.append(block4)

test_dict = {
    "data": "MyE=",
    "previous":
    "3b9448477c4dc133872b1029ab8d3e5ca151ad872cf5de636c2e8595dbf67855"
}
Пример #34
0
 def build_block(self, transactions, tree):
     prevhash = len(self.blocks) > 0 and self.blocks[-1].roothash or ''
     return Block(transactions, tree.root, tree.tree, prevhash)
Пример #35
0
    def make_move(self, board: Block) -> int:
        """Choose a move to make on the given board, and apply it, mutating
        the Board as appropriate.

        Return 0 upon successful completion of a move, and 1 upon a QUIT event.
        """

        scores = {}
        iterations = {0: 5, 1: 10, 2: 25, 3: 50, 4: 100, 5: 150}
        moves = iterations[self.diff]

        # Get all the available blocks
        list_ = board.get_all_blocks()

        # Try all the moves, record, and undo them.
        for _ in range(moves):
            block = random.randint(0, len(list_) - 1)
            curr = list_[block]

            move_index = random.randint(1, 4)

            if move_index == 1:
                curr.rotate(1)
                dict_helper(scores, self.goal.score(board), curr, 1)
                curr.rotate(3)

            elif move_index == 2:
                curr.rotate(3)
                dict_helper(scores, self.goal.score(board), curr, 2)
                curr.rotate(1)

            elif move_index == 3:
                curr.swap(0)
                dict_helper(scores, self.goal.score(board), curr, 3)
                curr.swap(0)

            elif move_index == 4:
                curr.swap(1)
                dict_helper(scores, self.goal.score(board), curr, 4)
                curr.swap(1)
        # Find the move with the highest score and execute that move.
        # find the max score
        score = max(scores, key=int)
        self._selected_block = scores[score][0][0]
        move = scores[score][0][1]
        self._selected_block.highlighted = True

        # draw the board, call time delay
        self.renderer.draw(board, self.id)
        pygame.time.wait(TIME_DELAY)

        # do the move
        if move == 1:
            self._selected_block.rotate(1)
        elif move == 2:
            self._selected_block.rotate(3)
        elif move == 3:
            self._selected_block.swap(0)
        elif move == 4:
            self._selected_block.swap(1)

        self._selected_block.highlighted = False
        self.renderer.draw(board, self.id)

        return 0
Пример #36
0
    def process_event(self, board: Block,
                      event: pygame.event.Event) -> Optional[int]:
        """Process the given pygame <event>.

        Identify the selected block and mark it as highlighted.  Then identify
        what it is that <event> indicates needs to happen to <board>
        and do it.

        Return
           - None if <event> was not a board-changing move (that is, if was
             a change in cursor position, or a change in _level made via
            the arrow keys),
           - 1 if <event> was a successful move, and
           - 0 if <event> was an unsuccessful move (for example in the case of
             trying to smash in an invalid location or when the player is not
             allowed further smashes).
        """
        # Get the new "selected" block from the position of the cursor
        block = board.get_selected_block(pygame.mouse.get_pos(), self._level)

        # Remove the highlighting from the old "_selected_block"
        # before highlighting the new one
        if self._selected_block is not None:
            self._selected_block.highlighted = False
        self._selected_block = block
        self._selected_block.highlighted = True

        # Since get_selected_block may have not returned the block at
        # the requested level (due to the level being too low in the tree),
        # set the _level attribute to reflect the level of the block which
        # was actually returned.
        self._level = block.level

        if event.type == pygame.MOUSEBUTTONDOWN:
            block.rotate(event.button)
            return 1
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                if block.parent is not None:
                    self._level -= 1
                return None

            elif event.key == pygame.K_DOWN:
                if len(block.children) != 0:
                    self._level += 1
                return None

            elif event.key == pygame.K_h:
                block.swap(0)
                return 1

            elif event.key == pygame.K_v:
                block.swap(1)
                return 1

            elif event.key == pygame.K_s:
                if self.num_smashes >= self.MAX_SMASHES:
                    print('Can\'t smash again!')
                    return 0
                if block.smash():
                    self.num_smashes += 1
                    return 1
                else:
                    print('Tried to smash at an invalid depth!')
                    return 0
Пример #37
0
 def genesis_block(self):
     return Block('Genesis')
Пример #38
0
def test_rotate() -> None:
    block = Block((0, 0), 16, (1, 128, 181), 0, 2)
    b1 = Block((8, 0), 8, (1, 128, 181), 1, 2)
    b2 = Block((0, 0), 8, (199, 44, 58), 1, 2)
    b3 = Block((0, 8), 8, (1, 128, 181), 1, 2)
    b4 = Block((8, 8), 8, (255, 211, 92), 1, 2)
    block.children = [b1, b2, b3, b4]
    b31 = Block((4, 8), 4, (1, 128, 181), 2, 2)
    b32 = Block((0, 8), 4, (199, 44, 58), 2, 2)
    b33 = Block((0, 12), 4, (255, 211, 92), 2, 2)
    b34 = Block((4, 12), 4, (199, 44, 58), 2, 2)
    b3.children = [b31, b32, b33, b34]
    assert b31.rotate(1) is False
    assert b4.rotate(3) is False
    assert b3.rotate(1)
    assert b32.position == (4, 8)
    assert block.rotate(3)
    assert b32.position == (8, 8)
Пример #39
0
def test_paint() -> None:
    block = Block((0, 0), 16, (1, 128, 181), 0, 2)
    b1 = Block((8, 0), 8, (1, 128, 181), 1, 2)
    b2 = Block((0, 0), 8, (199, 44, 58), 1, 2)
    b3 = Block((0, 8), 8, (1, 128, 181), 1, 2)
    b4 = Block((8, 8), 8, (255, 211, 92), 1, 2)
    block.children = [b1, b2, b3, b4]
    b31 = Block((4, 8), 4, (1, 128, 181), 2, 2)
    b32 = Block((0, 8), 4, (199, 44, 58), 2, 2)
    b33 = Block((0, 12), 4, (255, 211, 92), 2, 2)
    b34 = Block((4, 12), 4, (199, 44, 58), 2, 2)
    b3.children = [b31, b32, b33, b34]
    color = (255, 211, 92)
    assert block.paint(color) is False
    assert b2.paint(color) is False
    assert b33.paint(color) is False
    assert b31.paint(color) is True
    assert b31.colour == color
Пример #40
0
def text_line_segmentation_NN(image,
                              scale,
                              use_binary=True,
                              debug_image=None,
                              offset=(0, 0),
                              debug_mode=False):

    h, w = image.shape[:2]

    if debug_image is None:
        debug_image = image
        if len(debug_image.shape) < 3:
            debug_image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)

    if len(image.shape) > 2:
        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    if use_binary:
        image = (thresh_sauvola(image, k=0.2) * 255).astype('uint8')

    labels, _ = label(image == 0)
    objects = find_objects(labels)

    height_map = [
        sl.height(o) for o in objects if sl.height(o) > 6
        and sl.height(o) < 100 and sl.aspect_normalized(o) < 8
    ]
    avg_h = max(np.nan_to_num(np.mean(height_map)), scale * 0.6)

    # remove underline (optional)
    image = remove_underline(image, avg_h)

    block = Block(image, avg_h)
    words = block.getWordBoundingBoxes()

    words = filter_and_merge_overlap_boxes(words,
                                           max(avg_h, scale * 0.8) * 0.3,
                                           (h, w))
    words = filter_and_merge_overlap_boxes(words,
                                           max(avg_h, scale * 1.0) * 0.3,
                                           (h, w),
                                           use_merge_same_line_only=True,
                                           same_line_multiplier=5)

    offset_x, offset_y = offset

    # filter line by size
    lines = [
        (l, m) for l, m in words if l[3] - l[1] > avg_h * 0.5 and l[3] -
        l[1] < min(avg_h, scale * 1.5) * 3.5 and l[2] - l[0] > avg_h *
        0.25 and 1.0 * (l[2] - l[0]) /
        (l[3] - l[1]) > 0.2 and max(l[3] - l[1], l[2] - l[0]) > avg_h * 0.8
    ]
    masks = [m for _, m in lines]

    lines = [sl.pad_box(l, 0, (h, w)) for l, _ in lines]
    lines = [[
        l[0] + offset_x, l[1] + offset_y, l[2] + offset_x, l[3] + offset_y
    ] for l in lines]

    if debug_mode:
        debug_image = block.paint(None)
    else:
        pre_image = debug_image.copy()
        for i, m in enumerate(masks):
            x0, y0 = lines[i][0], lines[i][1]
            x1, y1 = lines[i][2], lines[i][3]
            mh, mw = m.shape

            cv2.rectangle(pre_image, (x0, y0), (x1, y1), (0, 0, 255), 1)
            cv2.rectangle(debug_image, (x0, y0), (x1, y1), (0, 0, 255), 1)
            region = debug_image[y0:y0 + mh, x0:x0 + mw]
            region[m[:region.shape[0], :region.shape[1]] > 0] = [0, 0, 255]

        alpha = 0.75
        debug_image = cv2.addWeighted(pre_image, alpha, debug_image, 1 - alpha,
                                      0)

    return lines, debug_image
Пример #41
0
def test_block_to_squares() -> None:
    block1 = Block((0, 0), 16, None, 0, 2)
    c1 = Block((8, 0), 8, (1, 128, 181), 1, 2)
    c2 = Block((0, 0), 8, (199, 44, 58), 1, 2)
    c3 = Block((0, 8), 8, None, 1, 2)
    c4 = Block((8, 8), 8, None, 1, 2)
    block1.children = [c1, c2, c3, c4]
    b31 = Block((4, 8), 4, (1, 128, 181), 2, 2)
    b32 = Block((0, 8), 4, (199, 44, 58), 2, 2)
    b33 = Block((0, 12), 4, (255, 211, 92), 2, 2)
    b34 = Block((4, 12), 4, (199, 44, 58), 2, 2)
    c3.children = [b31, b32, b33, b34]
    b41 = Block((12, 8), 4, (255, 211, 92), 2, 2)
    b42 = Block((8, 8), 4, (199, 44, 58), 2, 2)
    b43 = Block((8, 12), 4, (255, 211, 92), 2, 2)
    b44 = Block((12, 12), 4, (199, 44, 58), 2, 2)
    c4.children = [b41, b42, b43, b44]
    lst = _block_to_squares(block1)
    assert ((1, 128, 181), (4, 8), 4) in lst
 def insert_block(self, data):
     new_block = Block(self.len + 1, data, self.previous_hash, self.hash,
                       self.difficulty)
     self.len += 1
     self.blockchain.append(new_block.get_block())
     return True
Пример #43
0
def add_block(last_block, data):
    this_index = last_block.index + 1
    this_timestamp = date.datetime.now()
    this_data = data
    this_hash = last_block.hash
    return Block(this_index, this_timestamp, this_data, this_hash)
Пример #44
0
from block import Block
import datetime

num_blocks_to_add = 10

block_chain = [Block.create_genesis_block()]

print("The genesis block has been created.")
print("Hash: %s" % block_chain[0].hash)

for i in range(1, num_blocks_to_add + 1):
    block_chain.append(
        Block(block_chain[i - 1].hash, "Block number %d" % i,
              datetime.datetime.now()))
    print("Block #%d created." % i)
    print("Hash: %s" % block_chain[-1].hash)
Пример #45
0
import time
from transaction import Transaction
from block import Block
from key import BitcoinAccount

wallet = BitcoinAccount()

difficulty = 4

first_block = Block(0, "")

tx = Transaction("mohamed", "justine", 50, time.time())

first_block.add_transaction(tx)
first_block.mine(difficulty)

print("First block is: ")

print(first_block)

last_hash = first_block.hashval

second_block = Block(1, last_hash)

second_block.mine(difficulty)

print("Second block is: ")

print(second_block)
Пример #46
0
def test_combine() -> None:
    block = Block((0, 0), 16, (1, 128, 181), 0, 2)
    b1 = Block((8, 0), 8, (1, 128, 181), 1, 2)
    b2 = Block((0, 0), 8, (199, 44, 58), 1, 2)
    b3 = Block((0, 8), 8, (1, 128, 181), 1, 2)
    b4 = Block((8, 8), 8, (255, 211, 92), 1, 2)
    block.children = [b1, b2, b3, b4]
    b31 = Block((4, 8), 4, (1, 128, 181), 2, 2)
    b32 = Block((0, 8), 4, (199, 44, 58), 2, 2)
    b33 = Block((0, 12), 4, (255, 211, 92), 2, 2)
    b34 = Block((4, 12), 4, (199, 44, 58), 2, 2)
    b3.children = [b31, b32, b33, b34]
    b41 = Block((12, 8), 4, (255, 211, 92), 2, 2)
    b42 = Block((8, 8), 4, (199, 44, 58), 2, 2)
    b43 = Block((8, 12), 4, (255, 211, 92), 2, 2)
    b44 = Block((12, 12), 4, (199, 44, 58), 2, 2)
    b4.children = [b41, b42, b43, b44]
    assert b34.combine() is False
    assert block.combine() is False
    assert b3.combine()
    assert b4.combine() is False
    assert block.combine
    assert block.combine() is False
Пример #47
0
    def make_move(self, board: Block):
        """Produce random moves (moves_to_check) times and make those moves
         on the <board> to calculate their score and then undo them. Then store
         the identities that lead us to the maximum score among other moves that
         we have produced. And do that move to gain the biggest possible score
         among the other moves that we have generated.

         Each random move will be produced by calling the _move method on the
         random block that will be generated by producing random location and
         random level( <= board.max_depth ) on the given <board>.

         Return 0 upon successful completion of a move. And since random player
         can't Quit therefore it won't return 1 in any case.

         """

        max_score = 0
        # minimum score is 0.

        best_move = 0
        # it will save the number( that later in _move function determine the
        # action) of the best move ( to generate on the block )

        best_block: Block
        # the identity that will help us to store the block on the board which
        # will lead us through our goal

        for _ in range(self.moves_to_check):

            x = random.randint(0, BOARD_WIDTH)
            y = random.randint(0, BOARD_WIDTH)
            # producing random location (x, y)
            # which is inside the area of the board

            random_level = random.randint(0, board.max_depth)
            # producing random level ( <= board.max_depth )

            block = board.get_selected_block((x, y), random_level)
            # choose a block on the board base on the identities that we
            # randomly generated

            decider = random.randint(0, 3)
            # it is the number between 0 and 3 which base on it's value, our
            # _move function will do the action on the block. it doesn't contain
            # 4 because base on the implementiation of the function random_move
            # 4 will do the smash however Smartplayer can't smash any block

            random_move(decider, block)
            # to the generated action on the generated block
            if max_score < self.goal.score(board):
                # check if the score that has been generated from the move that
                # that we made is greater than the existing max_score, then
                # save the identities of the move.
                best_move = decider
                best_block = block
                max_score = self.goal.score(board)

            undo_move(block, decider)
            # undo the move that we have (done and calculated its score)

        block = best_block
        # chooose the stored block as the best_block to lead us to the highest
        # possible score among the other moves that we haved check

        block.highlighted = True
        # select the block

        self.renderer.draw(board, self.id)
        # to draw the frame around the selected block with HIGHLIGHT_COLOUR

        pygame.time.wait(TIME_DELAY)
        # to introduce a delay so that the user can see what is happening.

        random_move(best_move, block)
        # move the selected block with the best action to gain more score

        block.highlighted = False
        # unselect the block

        self.renderer.draw(board, self.id)
        # to draw the change that happens because of our random_move

        return 0
Пример #48
0
def test_create_copy() -> None:
    block = Block((0, 0), 16, None, 0, 5)
    b1 = Block((8, 0), 8, (1, 128, 181), 1, 5)
    b2 = Block((0, 0), 8, (199, 44, 58), 1, 5)
    b3 = Block((0, 8), 8, None, 1, 5)
    b4 = Block((8, 8), 8, (255, 211, 92), 1, 5)
    block.children = [b1, b2, b3, b4]
    b31 = Block((4, 8), 4, (1, 128, 181), 2, 5)
    b32 = Block((0, 8), 4, (199, 44, 58), 2, 5)
    b33 = Block((0, 12), 4, (255, 211, 92), 2, 5)
    b34 = Block((4, 12), 4, (199, 44, 58), 2, 5)
    b3.children = [b31, b32, b33, b34]
    b = block.create_copy()
    assert id(b) != id(block)
    assert b.position == block.position
    assert b.size == block.size
    assert b.max_depth == block.max_depth
    assert b.level == block.level
    assert b.colour == block.colour
    assert b.children == block.children
    assert id(b.children[1]) != id(b2)
    assert b.children[1].position == b2.position
    assert b.children[1].size == b2.size
    assert b.children[1].max_depth == b2.max_depth
    assert b.children[1].level == b2.level
    assert b.children[1].colour == b2.colour
    assert id(b.children[2].children[0]) != id(b31)
    assert b.children[2].children[0].position == b31.position
    assert b.children[2].children[0].size == b31.size
    assert b.children[2].children[0].max_depth == b31.max_depth
    assert b.children[2].children[0].level == b31.level
    assert b.children[2].children[0].colour == b31.colour
Пример #49
0
 def generate(self):
     for i in range(self.height):
         #if i > 10:
         for j in range(self.width):
             self.world.append(Block(self.get_id(i), j, i))
Пример #50
0
def test_flatten() -> None:
    blocky = Block((0, 0), 16, (1, 128, 181), 0, 0)
    assert _flatten(blocky) == [[(1, 128, 181)]]
    block = Block((0, 0), 16, None, 0, 1)
    b1 = Block((8, 0), 8, (1, 128, 181), 1, 1)
    b2 = Block((0, 0), 8, (199, 44, 58), 1, 1)
    b3 = Block((0, 8), 8, (1, 128, 181), 1, 1)
    b4 = Block((8, 8), 8, (255, 211, 92), 1, 1)
    block.children = [b1, b2, b3, b4]
    assert _flatten(block) == [[(199, 44, 58), (1, 128, 181)],
                               [(1, 128, 181), (255, 211, 92)]]
    block1 = Block((0, 0), 16, None, 0, 2)
    c1 = Block((8, 0), 8, (1, 128, 181), 1, 2)
    c2 = Block((0, 0), 8, (199, 44, 58), 1, 2)
    c3 = Block((0, 8), 8, None, 1, 2)
    c4 = Block((8, 8), 8, None, 1, 2)
    block1.children = [c1, c2, c3, c4]
    b31 = Block((4, 8), 4, (1, 128, 181), 2, 2)
    b32 = Block((0, 8), 4, (199, 44, 58), 2, 2)
    b33 = Block((0, 12), 4, (255, 211, 92), 2, 2)
    b34 = Block((4, 12), 4, (199, 44, 58), 2, 2)
    c3.children = [b31, b32, b33, b34]
    b41 = Block((12, 8), 4, (255, 211, 92), 2, 2)
    b42 = Block((8, 8), 4, (199, 44, 58), 2, 2)
    b43 = Block((8, 12), 4, (255, 211, 92), 2, 2)
    b44 = Block((12, 12), 4, (199, 44, 58), 2, 2)
    c4.children = [b41, b42, b43, b44]
    block2 = Block((0, 0), 16, None, 0, 2)
    c1 = Block((8, 0), 8, (1, 128, 181), 1, 2)
    c2 = Block((0, 0), 8, (199, 44, 58), 1, 2)
    c3 = Block((0, 8), 8, (255, 211, 92), 1, 2)
    c4 = Block((8, 8), 8, (1, 128, 181), 1, 2)
    block2.children = [c1, c2, c3, c4]
    assert len(_flatten(block1)) == len(_flatten(block2))
    assert _flatten(block1) == [[(199, 44, 58), (199, 44, 58), (199, 44, 58),
                                 (255, 211, 92)],
                                [(199, 44, 58), (199, 44, 58), (1, 128, 181),
                                 (199, 44, 58)],
                                [(1, 128, 181), (1, 128, 181), (199, 44, 58),
                                 (255, 211, 92)],
                                [(1, 128, 181), (1, 128, 181), (255, 211, 92),
                                 (199, 44, 58)]]
    assert _flatten(block2) == [[(199, 44, 58), (199, 44, 58), (255, 211, 92),
                                 (255, 211, 92)],
                                [(199, 44, 58), (199, 44, 58), (255, 211, 92),
                                 (255, 211, 92)],
                                [(1, 128, 181), (1, 128, 181), (1, 128, 181),
                                 (1, 128, 181)],
                                [(1, 128, 181), (1, 128, 181), (1, 128, 181),
                                 (1, 128, 181)]]
Пример #51
0
from block import Block
'''
{
  "blockchain": [
    {
      "authorizations": {}, 
      "hash_root": "", 
      "nonce": 52811, 
      "now_hash": "0000208efadb6caff4e351c6fd1bf059677bb3f64fb63e0e1aec9a7ffffca265", 
      "prev_hash": 0, 
      "timestamp": 1516156465.836211
    }
  ], 
  "difficulty": "0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 
  "height": 1
}
'''
genesis_block = Block(
    0, [], "5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9",
    1516156465.836211,
    "00002758d1b4dd20111165f398e0cdf649af643176d5f77c5ab9cd1b39141ef9", 126745)
#print(genesis_block.to_json())
Пример #52
0
def test_score_blob_goal() -> None:
    block1 = Block((0, 0), 16, None, 0, 2)
    c1 = Block((8, 0), 8, (1, 128, 181), 1, 2)
    c2 = Block((0, 0), 8, (199, 44, 58), 1, 2)
    c3 = Block((0, 8), 8, None, 1, 2)
    c4 = Block((8, 8), 8, None, 1, 2)
    block1.children = [c1, c2, c3, c4]
    b31 = Block((4, 8), 4, (1, 128, 181), 2, 2)
    b32 = Block((0, 8), 4, (199, 44, 58), 2, 2)
    b33 = Block((0, 12), 4, (255, 211, 92), 2, 2)
    b34 = Block((4, 12), 4, (199, 44, 58), 2, 2)
    c3.children = [b31, b32, b33, b34]
    b41 = Block((12, 8), 4, (255, 211, 92), 2, 2)
    b42 = Block((8, 8), 4, (199, 44, 58), 2, 2)
    b43 = Block((8, 12), 4, (255, 211, 92), 2, 2)
    b44 = Block((12, 12), 4, (199, 44, 58), 2, 2)
    c4.children = [b41, b42, b43, b44]
    block2 = Block((0, 0), 16, None, 0, 2)
    c1 = Block((8, 0), 8, (1, 128, 181), 1, 2)
    c2 = Block((0, 0), 8, (199, 44, 58), 1, 2)
    c3 = Block((0, 8), 8, (255, 211, 92), 1, 2)
    c4 = Block((8, 8), 8, (1, 128, 181), 1, 2)
    block2.children = [c1, c2, c3, c4]
    block3 = Block((0, 0), 16, None, 0, 2)
    c1 = Block((8, 0), 8, (1, 128, 181), 1, 2)
    c2 = Block((0, 0), 8, (199, 44, 58), 1, 2)
    c3 = Block((0, 8), 8, None, 1, 2)
    c4 = Block((8, 8), 8, (199, 44, 58), 1, 2)
    block3.children = [c1, c2, c3, c4]
    b31 = Block((4, 8), 4, (1, 128, 181), 2, 2)
    b32 = Block((0, 8), 4, (199, 44, 58), 2, 2)
    b33 = Block((0, 12), 4, (255, 211, 92), 2, 2)
    b34 = Block((4, 12), 4, (0, 0, 0), 2, 2)
    c3.children = [b31, b32, b33, b34]
    b41 = Block((12, 8), 4, (255, 211, 92), 2, 2)
    b42 = Block((8, 8), 4, (199, 44, 58), 2, 2)
    b43 = Block((8, 12), 4, (0, 0, 0), 2, 2)
    b44 = Block((12, 12), 4, (199, 44, 58), 2, 2)
    c4.children = [b41, b42, b43, b44]
    goal1 = BlobGoal((199, 44, 58))
    goal2 = BlobGoal((255, 211, 92))
    goal3 = BlobGoal((0, 0, 0))
    block4 = Block((0, 0), 16, None, 0, 2)
    c1 = Block((8, 0), 8, (1, 128, 181), 1, 2)
    c2 = Block((0, 0), 8, (199, 44, 58), 1, 2)
    c3 = Block((0, 8), 8, None, 1, 2)
    c4 = Block((8, 8), 8, None, 1, 2)
    block4.children = [c1, c2, c3, c4]
    b31 = Block((4, 8), 4, (1, 128, 181), 2, 2)
    b32 = Block((0, 8), 4, (199, 44, 58), 2, 2)
    b33 = Block((0, 12), 4, (199, 44, 58), 2, 2)
    b34 = Block((4, 12), 4, (199, 44, 58), 2, 2)
    c3.children = [b31, b32, b33, b34]
    b41 = Block((12, 8), 4, (255, 211, 92), 2, 2)
    b42 = Block((8, 8), 4, (199, 44, 58), 2, 2)
    b43 = Block((8, 12), 4, (199, 44, 58), 2, 2)
    b44 = Block((12, 12), 4, (199, 44, 58), 2, 2)
    c4.children = [b41, b42, b43, b44]
    assert goal1.score(block1) == 5
    assert goal1.score(block4) == 10
    assert goal2.score(block1) == 1
    assert goal2.score(block2) == 4
    assert goal3.score(block3) == 2
    assert goal3.score(block1) == 0
Пример #53
0
 def build_element(self, elements_list, element_name):
     new_hero = Block(element_name, self.get_random_position())
     while not (self.validate_position(elements_list, new_hero)):
         new_hero = Block(element_name, self.get_random_position())
     return new_hero
Пример #54
0
def test_get_block() -> None:
    block = Block((0, 0), 16, None, 0, 5)
    b1 = Block((8, 0), 8, (1, 128, 181), 1, 5)
    b2 = Block((0, 0), 8, (199, 44, 58), 1, 5)
    b3 = Block((0, 8), 8, None, 1, 5)
    b4 = Block((8, 8), 8, (255, 211, 92), 1, 5)
    block.children = [b1, b2, b3, b4]
    b31 = Block((4, 8), 4, (1, 128, 181), 2, 5)
    b32 = Block((0, 8), 4, (199, 44, 58), 2, 5)
    b33 = Block((0, 12), 4, (255, 211, 92), 2, 5)
    b34 = Block((4, 12), 4, (199, 44, 58), 2, 5)
    b3.children = [b31, b32, b33, b34]
    x = _get_block(block, (3, 7), 2)
    y = _get_block(block, (7, 10), 2)
    a = _get_block(block, (8, 8), 1)
    b = _get_block(block, (16, 8), 1)
    z = _get_block(block, (15, 13), 5)
    assert b is None
    assert a.position == (8, 8)
    assert y.position == (4, 8)
    assert x.position == (0, 0)
    assert z.position == (8, 8)
Пример #55
0
class ColorDiffGame(gamelib.SimpleGame):
    BLACK = pygame.Color('black')
    WHITE = pygame.Color('white')
    GREEN = pygame.Color('green')

    def __init__(self):
        super(ColorDiffGame, self).__init__('ColorDiff', ColorDiffGame.WHITE)
        self.level = 2
        self.score = 0
        self.start_time = 60
        self.frame_count = 0
        self.frame_rate = 60
        self.total_seconds = 60

    def init(self):
        self.Repeat = 0
        super(ColorDiffGame, self).init()
        self.block = Block(color=ColorDiffGame.GREEN,
                           level=self.level,
                           score=self.score)
        self.startgame = False
        self.block.constant()
        self.render_score()

    def update(self):
        self.render_time()
        if pygame.mouse.get_pressed() == (1, 0, 0):  # detect left click
            self.Repeat += 1
            if self.Repeat == 1:
                self.mouse_position = [self.posX, self.posY]
                self.block.is_clicked(self.mouse_position, self.level)

        else:
            self.Repeat = 0

            if self.block.is_pass() == True:
                self.score += 1
                print(self.score)
                if (self.score > 25): self.level = 10
                elif (self.score > 22): self.level = 9
                elif (self.score > 18): self.level = 8
                elif (self.score > 14): self.level = 7
                elif (self.score > 10): self.level = 6
                elif (self.score > 7): self.level = 5
                elif (self.score > 4): self.level = 4
                elif (self.score > 1): self.level = 3

                self.init()

        self.frame_count += 1
        self.total_seconds = self.start_time - (self.frame_count //
                                                self.frame_rate)

        if self.total_seconds < 0:
            self.done = True
            self.total_seconds = 0

    def render_score(self):
        self.score_image = self.font.render("Score = %d" % self.score, 0,
                                            ColorDiffGame.GREEN)

    def render_time(self):
        self.time_image = self.font.render(
            "Time left: {0} ".format(self.total_seconds), 0,
            ColorDiffGame.GREEN)

    def render(self, surface):
        self.block.render(surface, self.level, self.score)
        surface.blit(self.score_image, (100, 640))
        surface.blit(self.time_image, (250, 640))
 def add_block(self, data):
     self.chain.append(Block(data))
Пример #57
0
# intersect function used for collision determination
def intersect(rect1, rect2):
    if (rect1.x <
            rect2.x + rect2.width) and (rect1.x + rect1.width > rect2.x) and (
                rect1.y < rect2.y + rect2.height) and (rect1.height + rect1.y >
                                                       rect2.y):
        return True
    return False


# Instantiate all objects and append into object lists drawables and blocks
drawables = []
blocks = []

newBall = Ball(10, 350, (255, 0, 0))
newBlock1 = Block(300, 320, (0, 0, 255))
newBlock2 = Block(300, 330, (0, 0, 255))
newBlock3 = Block(300, 340, (0, 0, 255))
newBlock4 = Block(310, 320, (0, 0, 255))
newBlock5 = Block(310, 330, (0, 0, 255))
newBlock6 = Block(310, 340, (0, 0, 255))
newBlock7 = Block(320, 320, (0, 0, 255))
newBlock8 = Block(320, 330, (0, 0, 255))
newBlock9 = Block(320, 340, (0, 0, 255))
newText = Text('Score: 0', 0, 0, (0, 0, 0))
resetText = Text('Press r to reset ball', 250, 0, (0, 0, 0))
quitText = Text('Press q to quit game', 250, 10, (0, 0, 0))

drawables.append(newBall)
drawables.append(newBlock1)
drawables.append(newBlock2)
Пример #58
0
    def generate_move(self, board: Block) -> \
            Optional[Tuple[str, Optional[int], Block]]:
        """Return a valid move by assessing multiple valid moves and choosing
        the move that results in the highest score for this player's goal (i.e.,
        disregarding penalties).

        A valid move is a move other than PASS that can be successfully
        performed on the <board>. If no move can be found that is better than
        the current score, this player will pass.

        This function does not mutate <board>.
        """
        if not self._proceed:
            return None
        self._proceed = False
        curr_score = self.goal.score(board)
        moves = [ROTATE_CLOCKWISE, ROTATE_COUNTER_CLOCKWISE, SWAP_HORIZONTAL,
                 SWAP_VERTICAL, SMASH, COMBINE, PAINT]
        results = []
        # random position
        while len(results) < self._difficulty:
            depth = random.randint(0, board.max_depth)
            random_location = (random.randint(0, board.size-1),
                               random.randint(0, board.size-1))
            # make moves on copies
            copy = board.create_copy()  # to get score
            random_block = _get_block(copy, random_location, depth)  # move
            block_copy = random_block.create_copy()  # try move
            # random move
            random_move = random.choice(moves)
            successful = False
            if random_move[0] == 'rotate' and block_copy.rotate(1):
                if random_move[1] == 1:
                    random_block.rotate(1)
                if random_move[1] == 3:
                    random_block.rotate(3)
                successful = True
            elif random_move[0] == 'swap' and block_copy.swap(1):
                if random_move[1] == 1:
                    random_block.swap(1)
                if random_move[1] == 0:
                    random_block.swap(0)
                successful = True
            elif random_move[0] == 'paint':
                if block_copy.paint(self.goal.colour):
                    random_block.paint(self.goal.colour)
                    successful = True
            elif random_move[0] == 'smash':
                if block_copy.smash():
                    random_block.smash()
                    successful = True
            elif random_move[0] == 'combine':
                if block_copy.combine():
                    random_block.combine()
                    successful = True
            if successful:
                score = self.goal.score(copy)
                results.append((score, _create_move(random_move, _get_block(
                    board, random_location, depth))))
        scores = {}
        for result in results:
            if result[0] in scores:
                scores[result[0]].append(result[1])
            else:
                scores[result[0]] = [result[1]]
        if max(list(scores.keys())) <= curr_score:
            return _create_move(PASS, board)
        else:
            return random.choice(scores[max(list(scores.keys()))])
Пример #59
0
 def __init__(self, index, timestamp, data, prev_hash):
     self.__block_chain = list()
     self.__block_chain.append(Block(index, timestamp, data, timestamp))
Пример #60
0
    def cache_constructor(self):
        block0 = Block()
        block0.set_number(0)
        block0.set_state("I")
        block0.set_memory_address(0)
        block0.set_data(0)
        block0.set_tag(0)

        block1 = Block()
        block1.set_number(1)
        block1.set_state("I")
        block1.set_memory_address(0)
        block1.set_data(0)
        block1.set_tag(0)

        block2 = Block()
        block2.set_number(2)
        block2.set_state("I")
        block2.set_memory_address(0)
        block2.set_data(0)
        block2.set_tag(0)

        block3 = Block()
        block3.set_number(3)
        block3.set_state("I")
        block3.set_memory_address(0)
        block3.set_data(0)
        block3.set_tag(0)

        set0 = [block0, block1]
        set1 = [block2, block3]

        self.set_sets([set0, set1])
        self.set_blocks([block0, block1, block2, block3])