Example #1
0
 def addValidBlock(self, Block):
     # TODO: TEAM PLEASE THINK ABOUT ANY CONDITIONS THAT I MAY NOT HAVE THOUGHT ABOUT
     # Condition #1: Valid Chain and Empty Chain (This is verbose as an empty chain will always be valid)
     #              We must now check that the Block trying to be added has a previousHash value of 0
     #              if these conditions aren't met, Block will be denied entry into chain.
     # Condtion #2: Valid Chain which means all blocks have been properly verified and that their hashes align
     #              correctly. It is important to now verify that the Block being added has the proper hash value
     #              lastBlockInChain.getBlockHash() == potentialBlockToBeAdded.previousHash(). This condition may
     #              help solve and validate the Proof of Work Step if it needs to be implemented.
     # Condition #3: No Blocks will ever be accepted by a invalid Chain. Therefore, until the error is corrected this
     #               chain will allow no other activity to be completed
     if self.getChainValidity() == True and self.getBlockCount() == 0:
         if Block.getPreviousHash() == '0':
             self.__theChain.append(Block)
             print('Block Added to Valid Chain.')
         else:
             print(
                 'Genesis block must have Previous Hash of 0. Block Not added'
             )
     elif self.getChainValidity() == True and self.getBlockCount() > 0:
         if self.__theChain[self.getBlockCount() -
                            1].getBlockHash() == Block.getPreviousHash():
             self.__theChain.append(Block)
             print('Block Added to Valid Chain.')
         else:
             print(
                 'Invalid Block prohibited from being added to chain. Rework your PoW'
             )
     else:
         print('Block was not added. This BlockChain is corrupted.')
Example #2
0
def fill_bottom_row(board, max_block_length):
    """
        Fill the bottom row of the given board with new blocks whose length does
        not exceed the given maximum length.
        - Upon completion, there will be at least one free cell in the bottom row and
          it will not be possible to add an additional block of the given maximum
          length to the bottom row.
        ASSUMPTIONS
        - The given board is a proper board.
        - The bottom row of the given board is empty.
        - The given maximum length is at least 2 and does not exceed halve the number
          of columns in the given board.
        NOTE
        - This function is already provided (you do not have to work out this function yourself).
    """
    nb_filled_cells = 0
    block_to_add = Block.make_random_block(max_block_length)
    position_for_block = get_random_position_for(board, block_to_add)
    while (position_for_block is not None) and \
            (nb_filled_cells + Block.get_length(block_to_add) < \
             Dimension.get_nb_of_columns(get_dimension(board))):
        add_block_at(board, block_to_add, position_for_block)
        nb_filled_cells += Block.get_length(block_to_add)
        block_to_add = Block.make_random_block(max_block_length)
        position_for_block = get_random_position_for(board, block_to_add)
Example #3
0
 def fullyAssociativeRead(self, address):
     block = Block(self.blockWord, Address(address))
     line = self.cacheHit(block)
     if line != -1:
         if self.replacementPolicy == 2:
             self.queue.put(line)
         if self.replacementPolicy == 3:
             self.frequency[line] += 1
         return 'CACHE HIT linha ' + str(line) + '\n'
     else:
         emptyLine = self.cacheHit(Block(self.blockWord, Address(None)))
         if emptyLine != -1:
             if self.replacementPolicy == 2:
                 self.queue.put(emptyLine)
             if self.replacementPolicy == 3:
                 self.frequency[emptyLine] += 1
             oldBlock = self.lines[emptyLine].blockId
             self.lines[emptyLine] = block
             return 'CACHE MISS -> alocado na linha ' + str(
                 emptyLine) + ' -> bloco ' + str(
                     oldBlock) + ' substituido\n'
         if self.replacementPolicy == 1:
             line, oldBlock = self.randomReplacement(block)
             return 'CACHE MISS -> alocado na linha ' + str(
                 line) + ' -> bloco ' + str(oldBlock) + ' substituido\n'
         if self.replacementPolicy == 2:
             line, oldBlock = self.fifoReplacement(block)
             return 'CACHE MISS -> alocado na linha ' + str(
                 line) + ' -> bloco ' + str(oldBlock) + ' substituido\n'
         if self.replacementPolicy == 3:
             line, oldBlock = self.lfuReplacement(block)
             return 'CACHE MISS -> alocado na linha ' + str(
                 line) + ' -> bloco ' + str(oldBlock) + ' substituido\n'
Example #4
0
def test_Get_Top_Moves__Single_Row_Single_Solution(score, max_score):
    """Function get_top_moves: single row, single best solution."""
    max_score.value += 12
    try:
        the_board = Board.make_board((6, 10))
        block1_1 = Block.make_block(1, color=Color.RED)
        Board.add_block_at(the_board, block1_1, ("a", 3))
        block1_2 = Block.make_block(2, color=Color.RED)
        Board.add_block_at(the_board, block1_2, ("a", 8))
        block2_1 = Block.make_block(2, color=Color.BLUE)
        block2_2 = Block.make_block(3, color=Color.BLUE)
        block2_3 = Block.make_block(2, color=Color.BLUE)
        blocks_to_fill = [[(("a", 1), block2_1), (("a", 4), block2_2), (("a", 9), block2_3)]]
        best_moves = Game.get_top_moves(the_board, blocks_to_fill, min_score=10, max_nb_moves=1)
        if best_moves != [(("b", 8), block1_2, -1)]:
            raise Exception
        best_moves = Game.get_top_moves(the_board, blocks_to_fill, min_score=6, max_nb_moves=3)
        if best_moves != [(("b", 8), block1_2, -1)]:
            raise Exception
        best_moves = Game.get_top_moves(the_board, blocks_to_fill, min_score=12, max_nb_moves=2)
        if best_moves is not None:
            raise Exception
        score.value += 12
    except:
        pass
Example #5
0
 def __init__(self,*args,**kwargs):
     super().__init__(*args,**kwargs)
     settings.multiplayer = False
     self.fpsDisplay = pyglet.clock.ClockDisplay()
     self.clear()
     self.startScreen = True
     self.startScreenDisplay = StartScreen()
     self.pauseScreenDisplay = PauseScreen()
     self.saveScreenDisplay = SaveScreen()
     self.loadScreenDisplay = LoadScreen()
     self.helpScreenDisplay = HelpScreen()
     self.stlSelectionScreenDisplay = StlSelectionScreen()
     self.playTypeScreenDisplay = PlayTypeScreen()
     self.ipSelectionScreenDisplay = IpSelectionScreen()
     self.stlCompleteScreenDisplay = StlCompleteScreen()
     self.stlConversion = stlConvert()
     self.player = Player(29,29)
     self.blocks = Block()
     self.save= SaveMap()
     self.load = LoadMap()
     self.keys = key.KeyStateHandler()
     self.push_handlers(self.keys)
     self.set_exclusive_mouse(False)
     self.mouse = [0,0]
     self.loadScreen = False
     self.playing= False
     self.pauseScreen = False
     self.saveScreen=False
     self.helpScreen = False
     self.stlSelectionScreen = False
     self.playTypeScreen = False
     self.ipSelectionScreen = False
     self.stlCompleteScreen=False
     pyglet.clock.schedule_interval(self.update,1/settings.FPS)
Example #6
0
def receive():
    port = 7777
    save = []

    while True:
        sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sc.bind(('', port))
        sc.listen(1)
        content, addr = sc.accept()
        data = content.recv(1024).decode('utf-8')
        if data == "bc":
            if os.path.isfile("key.pem") == False:
                KeyGenerator.create_key()
            print("block!")
            f = open('chat.txt', 'a+t')
            f.writelines(str(save))
            f.write('\n')
            pow = ProofOfWork.pow()
            if pow == True:
                Block.brick()
                break

        else:
            print(data)
            save.append(data)
Example #7
0
    def splitBlocks(self, event=None):
        """splitBlocks"""
        if not self._items:
            return

        # all_items = self._items
        sel_items = list(map(int, self.curselection()))
        change = True
        # newblocks = []

        for bid in sel_items:
            n_bl = Block.Block(self.gcode[bid].name())
            for line in self.gcode[bid]:
                if line == "( ---------- cut-here ---------- )":
                    # newblocks.append(bl)
                    # self.insertBlock(bl)
                    self.gcode.addUndo(self.gcode.addBlockUndo(bid + 1, n_bl))
                    n_bl = Block.Block(self.gcode[bid].name())
                else:
                    n_bl.append(line)
        self.gcode.addUndo(self.gcode.addBlockUndo(bid + 1, n_bl))
        # newblocks.append(bl)
        # self.gcode.extend(newblocks)

        if change:
            self.fill()

        self.deleteBlock()
        self.winfo_toplevel().event_generate("<<Modified>>")
Example #8
0
    def creatAppointPeo(self):
        allPeople = []
        # b1=Block.Block(1)
        # b1.x=3
        # b1.y=5
        # b1.type=True
        # allPeople.append(b1)
        #
        # b2=Block.Block(1)
        # b2.x=4
        # b2.y=5
        # b2.type=False
        # allPeople.append(b2)

        b3 = Block.Block(1)
        b3.x = 6
        b3.y = 10
        b3.type = True
        allPeople.append(b3)

        b4 = Block.Block(1)
        b4.x = 2
        b4.y = 10
        b4.type = False
        allPeople.append(b4)

        return allPeople
Example #9
0
    def creatAppointPeo(self):
        allPeople=[]
        b1=Block.Block(1)
        b1.x=3
        b1.y=5
        b1.type=True
        allPeople.append(b1)

        b2=Block.Block(1)
        b2.x=4
        b2.y=5
        b2.type=False
        allPeople.append(b2)

        b3 = Block.Block(1)
        b3.x = 5
        b3.y = 5
        b3.type = False
        allPeople.append(b3)

        b4 = Block.Block(1)
        b4.x = 6
        b4.y = 5
        b4.type = False
        allPeople.append(b4)

        return allPeople
Example #10
0
 def __init__(self, disk_name="Sorted.cbd", indexBy=[]):
     self.disk_name = disk_name
     self.r_block = Block(disk_name)
     self.w_block = Block(disk_name)
     self.indexes = {}
     for i in indexBy:
         self.indexes.update({i: open(i+"_"+disk_name, "w+")})
Example #11
0
def creatAreaPeople():
    allBlock = []  #用于存放格子
    allPeople = []  #用于存放行人
    '''将所有格子全部存入列表'''
    for i in range(10, 14):
        for j in range(7, 13):
            b = Block.Block(1)
            b.x = i
            b.y = j
            if j > Data.ROOM_N / 2:
                b.isInGrend = 2
                b.isNewDefine = 1
            # else:
            #     b.type=True
            b.type = False
            allBlock.append(b)
    b3 = Block.Block(1)
    b3.x = 8
    b3.y = 10
    b3.debug = 1
    b3.type = False
    allBlock.append(b3)
    '''随机排序'''
    # random.shuffle(allBlock)
    '''取前N个'''
    '''可有效防止无限产生随机数'''
    allPeople = allBlock[:Data.PEOPLE_NUMBER]
    return allPeople
Example #12
0
def get_droppable_positions(board, block):
    """
        Return a list of all positions at which the given block can be dropped
        on the given board.
        - The positions in the resulting list are in ascending order.
        ASSUMPTIONS
        - The given board is a proper board.
        - The given block is a proper block.
        NOTE
        - The function should only examine positions at which the given block
          fully fits within the boundaries of the given board.
    """
    block_copy = block.copy()
    droppable_positions = []

    horizontal_offsets = Block.get_horizontal_offsets_from_anchor(block_copy)
    vertical_offsets = Block.get_vertical_offsets_from_anchor(block_copy)

    # check every position where block fully fits within the boundaries of the given board
    for x_value in range(1 - horizontal_offsets[0],
                         dimension(board) - horizontal_offsets[1] + 1):
        for y_value in range(1 - vertical_offsets[0],
                             dimension(board) - vertical_offsets[1] + 1):
            possible_position = (x_value, y_value)
            if can_be_dropped_at(board, block, possible_position):
                droppable_positions.append(possible_position)
    return droppable_positions
Example #13
0
def ply_parse(text):

    tokens = ('BEGIN', 'END', 'COLOR', 'TITLE', 'EMPTY_BLK', 'NEW_LINES')

    t_BEGIN = r'\['
    t_END = r'\]'
    t_COLOR = r'(?:\#[\da-fA-F]{6}|[a-zA-Z]\w*):'
    t_TITLE = r'[^][/\n]+'
    t_EMPTY_BLK = r'\[\]'
    t_NEW_LINES = r'/+'

    t_ignore = ' \t'

    def t_newline(t):
        r'\n+'
        t.lexer.lineno += len(t.value)

    def t_error(t):
        line = t.value.lstrip()
        new_line_idx = line.find('\n')
        line = line if new_line_idx == -1 else line[:new_line_idx]
        raise ParseError('cannot parse line {}'.format(line))

    lexer = ply.lex.lex()
    stack = [Block.create_root_block()]
    block = None
    brackets = 0
    try:
        lexer.input(text)
        for token in lexer:
            if token.type == 'BEGIN':
                block = Block.create_empty_block()
                stack[-1].children.append(block)
                stack.append(block)
                brackets += 1
            elif token.type == 'END':
                block = None
                stack.pop()
                brackets -= 1
                if brackets < 0:
                    raise ParseError('too many "]"')
            elif token.type == 'COLOR':
                if block is None or Block.is_empty(block):
                    raise ParseError("syntax error")
                block.color = token.value[:-1]
            elif token.type == 'TITLE':
                if block is None or Block.is_empty(block):
                    raise ParseError("syntax error")
                block.title = token.value
            elif token.type == 'NEW_LINES':
                for x in range(len(token.value)):
                    stack[-1].children.append(Block.create_empty_row())
            elif token.type == 'EMPTY_BLK':
                stack[-1].children.append(Block.create_empty_block)
        if brackets:
            raise ParseError('unbalanced brackets')
    except ParseError as err:
        raise ValueError('Error {{0}}: line {0}: {1}'.format(
            token.lineno + 1, err))
    return stack[0]
Example #14
0
 def initialize(self):
     """
     A function to create the initial block in the chain.
     """
     initial_block = Block(0, [], time.time(), "0")
     initial_block.hash = initial_block.calc_hash()
     self.chain.append(initial_block)
Example #15
0
def test_Play_Greedy__Two_Rows_Single_Solution(score, max_score):
    """Function play_greedy: blocks to fill two rows with one best solution."""
    max_score.value += 3
    try:
        block1_1 = Block.make_block(2, color=Color.RED)
        block1_2 = Block.make_block(2, color=Color.RED)
        block1_3 = Block.make_block(1, color=Color.RED)
        block2_1 = Block.make_block(2, color=Color.BLUE)
        block2_2 = Block.make_block(3, color=Color.BLUE)
        blocks_to_fill = \
            [[(("a", 1), block1_1), (("a", 5), block1_2), (("a", 7), block1_3)],
             [(("a", 1), block2_1), (("a", 5), block2_2)]]
        # In the first step, block1_1 is moved 1 step to the right.
        # In the second step, the same block is again moved 1 step to the right.
        # This will make it fall in the bottom row, which is then completely
        # filled and yields a score of 7 points.
        total_score, moves = Game.play_greedy(blocks_to_fill, (6, 7))
        if total_score != 7:
            raise Exception
        if moves != [(block1_1, 1), (block1_1, 1)]:
            raise Exception
        if moves[0][0] is not block1_1:
            raise Exception
        score.value += 3
    except:
        pass
Example #16
0
def creatTable():
    allTable = []
    for i in range(5, 37, 2):
        for j in range(6, 19):
            t1 = Block.Block(10)
            t1.x = i
            t1.y = j
            t1.type = True
            allTable.append(t1)
        for k in range(22, 35):
            t1 = Block.Block(10)
            t1.x = i
            t1.y = k
            t1.type = True
            allTable.append(t1)
    return allTable


# def creatWall():
#     allWall=[]
#     for i in range(40):
#         for ii in range(8):
#             D=[i,0]
#             U=[ii,0]
#             L=[0,i]
#             R=[Data.ROOM_M,i]
Example #17
0
def json_to_blockchain(data):
    try:
        chain = create()
        genesis_block = Block.create_genesis_block(data[0]["time"])
        chain.add_genesis_block(genesis_block)

        for block_index in range(1, len(data)):
            block = Block.create(
                data[block_index]["transactions"][0]["receiver"],
                data[block_index]["time"], data[block_index]["prev_hash"],
                data[block_index]["proof"])

            for transaction in range(1,
                                     len(data[block_index]["transactions"])):
                message = bytes.fromhex(
                    data[block_index]["transactions"][transaction]["message"])
                signature = bytes.fromhex(data[block_index]["transactions"]
                                          [transaction]["signature"])
                t = Transaction.create(message, signature)
                block.add_transaction(t)
            if not chain.add_block(block, chain.chain[-1].proof):
                return None

        return chain
    except:
        #raise
        return None
Example #18
0
def print_board(board):
    """
        Print the given board on the standard output stream.
        ASSUMPTIONS
        - The given board is a proper board.
        NOTE
        - This function is already provided (you do not have to work out this function yourself).
    """
    current_position = ("X", 1)
    while current_position is not None:
        for lines in range(0, 2):
            if lines == 1:
                print("\033[1;31;48m" +
                      '{:2}'.format(Position.get_row(current_position)),
                      end="  ")
            else:
                print("\033[1;30;48m" + "  ", end="  ")
            column_position = current_position
            left_position = None
            while column_position is not None:
                current_block = get_block_at(board, column_position)
                right_position = Position.right(get_dimension(board),
                                                column_position)
                if current_block is None:
                    print("\033[1;30;48m" + ("|   " if lines == 1 else "----"),
                          end="")
                else:
                    block_symbol = Block.get_symbol(current_block)
                    if (left_position is None) or \
                            (get_block_at(board, left_position) is not current_block):
                        # Leftmost cell of a block.
                        if lines == 1:
                            print("\033[1;" +
                                  str(Block.get_color(current_block)) +
                                  ";48m|" + block_symbol * 3,
                                  end="")
                        else:
                            print("\033[1;30;48m----", end="")
                    else:
                        if lines == 1:
                            print("\033[1;" +
                                  str(Block.get_color(current_block)) +
                                  ";48m" + block_symbol * 4,
                                  end="")
                        else:
                            print("\033[1;30;48m----", end="")
                left_position = column_position
                column_position = right_position
            print("\033[1;30;48m" + ("|" if lines == 1 else "-"))
        current_position = Position.down(get_dimension(board),
                                         current_position)
    print(
        "   ", "\033[1;30;48m" +
        ("-" * (Dimension.get_nb_of_columns(get_dimension(board)) * 4 + 1)))
    print("    ", end="")
    for column in range(1,
                        Dimension.get_nb_of_columns(get_dimension(board)) + 1):
        print("\033[1;30;48m" + '{:3d}'.format(column), end=" ")
    print()
Example #19
0
 def create_genesis_block(self):
     """
     A function to generate genesis block and appends it to
     the chain. The block has index 0, previous_hash as 0, and
     a valid hash.
     """
     genesis_block = Block(0, [], time.time(), "0")
     genesis_block.hash = genesis_block.compute_hash()
     self.chain.append(genesis_block)
Example #20
0
def test_Is_Proper_Block__False_Case(score, max_score):
    """Function is_proper_block: false case."""
    max_score.value += 2
    try:
        assert not Block.is_proper_block("ku leuven")
        assert not Block.is_proper_block((0, 0))
        score.value += 2
    except:
        pass
Example #21
0
def test_Normalize__Standard_Blocks(score, max_score):
    """Function normalize: standard blocks."""
    max_score.value += 10
    try:
        for block in Block.standard_blocks:
            assert Block.is_normalized(Block.normalize(block))
        score.value += 10
    except:
        pass
Example #22
0
def test_Is_Proper_Block__True_Case(score, max_score):
    """Function is_proper_block: true case."""
    max_score.value += 1
    try:
        the_block = Block.make_block(100)
        if not Block.is_proper_block(the_block):
            return
        score.value += 1
    except:
        pass
Example #23
0
def test_Make_Block__Regular_Case(score, max_score):
    """Function make_block: regular case."""
    max_score.value += 2
    try:
        given_dot_positions = {(0, 0), (1, 0), (0, 1), (1, 1)}
        the_block = Block.make_block(given_dot_positions)
        assert Block.get_all_dot_positions(the_block) == given_dot_positions
        score.value += 2
    except:
        pass
Example #24
0
def test_Is_Proper_Block__True_Case(score, max_score):
    """Function is_proper_block: true case."""
    max_score.value += 4
    try:
        dot_positions = {(0, 0), (1, 0), (0, 1), (1, 1)}
        the_block = Block.make_block(dot_positions)
        assert Block.is_proper_block(the_block)
        score.value += 4
    except:
        pass
Example #25
0
def test_Get_Top_Moves__Single_Row_Several_Solutions_Same_Blocks(score, max_score):
    """Function get_top_moves: single row, several best solutions with same blocks."""
    max_score.value += 14
    try:
        the_board = Board.make_board((6, 10))
        block1_1 = Block.make_block(1, color=Color.RED)
        Board.add_block_at(the_board, block1_1, ("a", 2))
        block1_2 = Block.make_block(1, color=Color.CYAN)
        Board.add_block_at(the_board, block1_2, ("a", 9))
        block2_1 = Block.make_block(2, color=Color.BLUE)
        block2_2 = Block.make_block(2, color=Color.CYAN)
        block2_3 = Block.make_block(2, color=Color.YELLOW)
        block2_4 = Block.make_block(2, color=Color.MAGENTA)
        block3_1 = Block.make_block(4, color=Color.GREEN)
        block3_2 = Block.make_block(1, color=Color.GREEN)
        block3_3 = Block.make_block(3, color=Color.GREEN)
        blocks_to_fill = \
            [[(("a", 1), block2_1), (("a", 4), block2_2), (("a", 6), block2_3), (("a", 9), block2_4)],
             [(("a", 1), block3_1), (("a", 6), block3_2), (("a", 7), block3_3)]]
        # Moving block1_1 one step to the right followed by moving block1_2 one step to
        # the left, yield the requested score. The same score is obtained from moving
        # block1_1 6 steps to the right followed by moving block1_2 6 steps to the
        # left. The function must return the first solution.
        best_moves = Game.get_top_moves(the_board, blocks_to_fill, min_score=10, max_nb_moves=2)
        if best_moves != [(("b", 2), block1_1, 1), (("c", 9), block1_2, -1)]:
            raise Exception
        score.value += 14
    except:
        pass
Example #26
0
def mine(blockData, nonce, address):
    # print(blockData)
    blockDataHash = blockData['blockDataHash']
    difficulty = blockData['difficulty']
    prevBlockHash = blockData['prevBlockHash']
    transactions = blockData['transactions']
    index = blockData['index']
    timestamp = time()/1000
    block = Block(blockDataHash, 
        difficulty,
        nonce, 
        timestamp, 
        prevBlockHash, 
        transactions, 
        index,
        address)
    block.calculateHash()
    timeStart = time()
    while(block.blockHash[0:block.difficulty] != ''.join(str(x) for x in np.zeros(block.difficulty, int))):
        block.nonce = block.nonce + 1
        block.timestamp = datetime.fromtimestamp(time() - 28800).isoformat() + "Z"
        block.calculateHash()
        # print(str(block.nonce) + "\t=>\t" + str(block.blockHash))
    minedBlock = block.minedBlock()
    return minedBlock
Example #27
0
def test_play_greedy__Larger_Sequence_Blocks(score, max_score):
    """Function play_greedy: larger sequence of blocks."""
    max_score.value += 37
    try:
        # This is that same game as in the last test for highest_score
        positions_to_fill = \
            {(1, 4), (2, 1), (3, 2), (3, 4), (3, 6), (4, 2), (5, 1), (5, 3), (5, 4), (5, 6), (6, 3), (6, 5)}
        the_board = Board.make_board(6, positions_to_fill)
        blocks = \
            [Block.make_block({(-3, 0), (-2, 0), (-1, 0), (0, 0)}),
             Block.make_block({(0, 2), (1, 2), (2, 2), (3, 2), (4, 2)}),
             Block.make_block({(-2, 2), (-2, 3), (-2, 4), (-2, 5)}),
             Block.make_block({(0, 0), (0, 1), (1, 0)}),
             Block.make_block({(0, 0), (1, 0), (0, 1), (1, 1)}),
             Block.make_block({(0, 0), (1, 0), (2, 0)}),
             Block.make_block({(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2)}),
             Block.make_block({(0, 0), (1, 0), (2, 0)}),
             Block.make_block \
                 ({(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1), (0, 2), \
                   (1, 2), (2, 2)}),
             Block.make_block({(0, 0)})]
        assert Game.play_greedy(the_board, blocks) is None
        assert Board.get_all_filled_positions(the_board) == \
               {(1, 3), (5, 6), (2, 1), (6, 2), (1, 6), (5, 1), (1, 2), (3, 6), (2, 2),
                (6, 4), (3, 2), (5, 4), (2, 6), (1, 4), (4, 2), (6, 1), (3, 4)}
        score.value += 37
    except:
        pass
Example #28
0
def main():
    pygame.init()

    height = 620
    width = height / 16 * 9

    screen = pygame.display.set_mode((width, height))
    font = pygame.font.Font(pygame.font.get_default_font(), 30)

    running = True
    elapsed_time = 0

    clock = pygame.time.Clock()

    current_block = Block(0, 5, 10)
    board = GameBoard(width, height)

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                break
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_DOWN:
                    current_block.y_pos += 1
                if event.key == pygame.K_LEFT:
                    if current_block.x_pos > 0:
                        current_block.x_pos -= 1
                if event.key == pygame.K_RIGHT:
                    if current_block.x_pos + current_block.block_width < board.grid_width:
                        current_block.x_pos += 1
                if event.key == pygame.K_UP:
                    current_block.rotate()

        if current_block.finished:
            board.add_block(current_block)
            current_block = Block(random.randint(0, 3), 0, 0)

        dt = clock.tick()
        elapsed_time += dt
        if elapsed_time > 500:
            elapsed_time = 0
            if current_block.frozen:
                current_block.finished = True
            current_block.y_pos += 1

        board.check_if_scored()
        board.update_board()
        board.update_block(current_block)
        board.render()

        screen.blit(board.display, (0, 0))
        screen.blit(font.render(str(board.score), True, (255, 255, 255)), (280, 30))
        pygame.display.flip()
Example #29
0
def test_Normalize__Already_Normalized(score, max_score):
    """Function normalize: block already normalized."""
    max_score.value += 2
    try:
        the_block = Block.make_block({(0, 0), (1, 0), (0, 1), (1, 1)})
        normalized_block = Block.normalize(the_block)
        assert Block.is_normalized(normalized_block)
        assert Block.are_equivalent(the_block, normalized_block)
        score.value += 2
    except:
        pass
Example #30
0
def test_Is_Normalized__True_Cases(score, max_score):
    """Function is_normalized: true cases."""
    max_score.value += 2
    try:
        the_block = Block.make_block({(0, 0)})
        assert Block.is_normalized(the_block)
        the_block = Block.make_block({(0, 0), (1, 0), (0, 1), (1, 1)})
        assert Block.is_normalized(the_block)
        score.value += 2
    except:
        pass
Example #31
0
def test_Make_Block__Hackers_Test1(score, max_score):
    """Function make_block: hacker's test 1."""
    max_score.value += 10
    try:
        dot_positions = {(0, 0), (1, 0), (0, 1), (1, 1)}
        the_block = Block.make_block(dot_positions)
        set.add(dot_positions, "hacker")
        assert Block.is_proper_block(the_block)
        score.value += 10
    except:
        pass
Example #32
0
    def create_level(self):
        for l in self.levelFile:
            newStr=l
            if newStr.endswith("\n"):
                newStr=newStr[:-1]
            self.levelLines.append(stripTrailingSpaces(newStr))

        self.readHeaders()
        #print self.messages

        x=0
        y=0
        #an enemy port tells the game where to spawn enemies
        for row in self.levelLines:
            for col in row:
                if col == "X":
                    obstacle = Block(x, y, "world/blocks/cinder.png")
                    self.world.append(obstacle)
                    self.all_sprite.add(self.world)
                if col == "C":
                    obstacle = Block(x, y, "level/tutorial/sign.png")
                    obstacle.solid=False
                    self.world.append(obstacle)
                    self.all_sprite.add(self.world)
                if col in LevelTutorial.DIGITS:
                    obstacle = InfoBlock(x, y, self.messages[int(col)])
                    self.world.append(obstacle)
                    self.all_sprite.add(self.world)
                if col == "P":
                    self.crashman = CrashmanTutorial(x,y,self,self.character)
                    self.all_sprite.add(self.crashman)
                if col == "L":
                    pep = Pipe(x, y-75, "world/pipes/leftpipe.png","left")
                    self.world.append(pep)
                    self.all_sprite.add(self.world)
                    self.enemy_ports.append( (x,y, "left") )
                if col == "R":
                    pep = Pipe(x-125, y-75, "world/pipes/rightpipe.png","right")
                    self.world.append(pep)
                    self.all_sprite.add(self.world)
                    self.enemy_ports.append( (x,y, "right") )
                if col == "l":
                    pep = Pipe(x+25, y-75, "world/pipes/leftpipe.png","left")
                    self.world.append(pep)
                    self.all_sprite.add(self.world)
                if col == "r":
                    pep = Pipe(x-125, y-75, "world/pipes/rightpipe.png","right")
                    self.world.append(pep)
                    self.all_sprite.add(self.world)

                x += 25
            y += 25
            x = 0
def populate_children(items, stack):
    for item in items:
        if isinstance(item, Block.Block):
            stack[-1].children.append(item)
        elif isinstance(item, list) and item:
            stack.append(stack[-1].children[-1])
            populate_children(item, stack)
            stack.pop()
        elif isinstance(item, int):
            if item == EmptyBlock:
                stack[-1].children.append(Block.get_empty_block())
            else:
                for x in range(item):
                    stack[-1].children.append(Block.get_new_row())
Example #34
0
	def __init__(self, id, dataBitSize):
# 		self.count = 0
		self.count = SharedCounter()
		self.dataSum = Block(id, dataBitSize)
		self.hashProd = 1
		self.f = 0
		self.pickleHackCounter = 0
Example #35
0
 def connect(self, name = None, address = None):
     if name != None:
         self.__connect_type = HyperSocket.__LOCAL
         self.__target = Block.find(name)
     else:
         self.__connect_type = HyperSocket.__SOCKET
         socket.socket.connect(address)
 def __init__(self, text):
     self.text = text
     self.pos = 0
     self.line = 1
     self.column = 1
     self.brackets = 0
     self.stack = [Block.get_root_block()]
Example #37
0
 def render_on(self, renderer):
     if hasattr(web.ctx, 'source_page_title'):
         old_source_page_title = web.ctx.source_page_title
     else:
         old_source_page_title = None
     try:
         web.ctx.source_page_title = self.title
         doc = Block.parsestring(self.body())
         return renderer.visit(doc.children)
     finally:
         web.ctx.source_page_title = old_source_page_title
Example #38
0
	def __init__(self, res, screen):
		self.res = res
		self.board = Board()
		self.defs = Defs()
		self.screen = screen
		self.board = self.board.new_board()
		self.block = Block(self.board)
		self.block.new_block()
		self.endgame = False
		self.score = 0
		self.scoreImageName = "./images/score.png"
		self.scoreImage = pygame.image.load(self.scoreImageName).convert()
		self.then = pygame.time.get_ticks()
def main():
    block = Block()
    transaction = Transaction()
    block_user = User()
    running = True

    user_id = block_user.sign_in()

    while running:
        if user_id < 11:
            print("You are an admin. Welcome to the admin page")
            break
        else:
            print("Welcome to the main menu")
            print("1) Create a transaction")
            print("2) Check on the blockchain")
            print("3) look at my account")
            print("Enter the number or word associated with what you want to do "
                  "(i.e. transaction, blockchain, or account")
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
            us_input = input("What would you like to do: ")
            us_input = us_input.lower()

            if us_input == "exit" or us_input == "done":
                running = False
            elif us_input == "1" or us_input == "transaction":
                transaction.candidate_list()
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            elif us_input == "2" or us_input == "blockchain":
                block.block_size()
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            elif us_input == "3" or us_input == "account":
                block_user.handshake()
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            else:
                print("Please enter a valid input")
                print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

    print("Byebye")
 def parse_block_data(data, end):
     color = None
     colon = data.text.find(":", data.pos)
     if -1 < colon < end:
         color = data.text[data.pos:colon]
         data.advance_to_position(colon + 1)
     name = data.text[data.pos:end].strip()
     data.advance_to_position(end)
     if not name and color is None:
         block = Block.get_empty_block()
     else:
         block = Block.Block(name, color)
     data.stack[-1].children.append(block)
     return block
Example #41
0
    def test_bitcoin_chainheaders(self):

        GENESIS_BLOCK = BitcoinBlock(version=1,
                                     prevblock=0,
                                     merkleroot=0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b,
                                     timestamp=1231006505,
                                     bits=0x1d00ffff,
                                     nonce=2083236893)

        state = { GENESIS_BLOCK.get_hash(): GENESIS_BLOCK.as_bytes() }

        next_block_bytes = binascii.unhexlify('010000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000982051fd1e4ba744bbbe680e1fee14677ba1a3c3540bf7b1cdb606e857233e0e61bc6649ffff001d01e36299')

        tx = Transaction(sender=None, fee=None, amount=None, data=[next_block_bytes])

        state2 = ChainHeaders.on_transaction(state.copy(), tx, None)

        next_block_hash = sha256(sha256(next_block_bytes))

        expected_state2 = state.copy()
        expected_state2[next_block_hash] = next_block_bytes

        self.assertEqual(expected_state2, state2)
Example #42
0
def populate_cells(block, row, column, cells):
    cell = Cell(row, column, 1, 1, block.name, block.color)
    if block.children:
        row += 1
    for child in block.children:
        if Block.is_new_row(child):
            row += 1
            column = 0
        else:
            child_cell = populate_cells(child, row, column, cells)
            column += 1
            cell.rows += child_cell.rows
            cell.columns += child_cell.columns
    cells.append(cell)
    return cell
Example #43
0
	def Create_units(self):
	
		self.Keys = []
		self.Blocks = []
		self.tmp = []
		
		#Creamos bloques en las posiciones del mapa
		count = 0 

		#we iterate one time to collect all the coordinates
		tmp_list = []

		for val in  maze_map:
			for i in range(0,21):						  	
				tmp_list.append(int(val[i]))
			maze.append(list(tmp_list))
			tmp_list = []

				
		for i in range(0,21):
			for j in range(0,20):
				if ( maze[i][j] == 0):
					self.screen.blit(self.block_img ,(self.x,self.y))						
					self.Blocks.append( Block.block( self.x, self.y,self.dimension,self.block_img) )
				if(maze[i][j] ==3):
					self.Lock =  Lock.Lock( self.lock_img,self.x, self.y) 
				if ( maze[i][j] ==2):
					self.key_x = i
					self.key_y = j 
					self.key_points = [self.key_x,self.key_y,2]
					self.Key = Key.Key( self.Key_img_list(), self.x, self.y,self.dimension,self.key_points,maze,2)					
					self.key_list.append(self.Key)	
				self.x=self.dimension+self.x			
			self.x=0
			self.y=self.dimension+self.y
			


		print "weey ",maze[0][9]
 def parse_new_row(data):
     data.stack[-1].children.append(Block.get_new_row())
     data.advance_by(1)
def main(argv):
   level1=[[1,2,3,4,5,5,4,3,2,1],[5,4,3,2,1,1,2,3,4,5],[1,2,3,4,5,5,4,3,2,1],[5,4,3,2,1,1,2,3,4,5],[1,2,3,4,5,5,4,3,2,1]]
   # imprime en consola
   print 'Earth Defender'


   ## LEVELS ##

	## COLORS ##

	#         R   G   B
   GRAY=(100, 100,100)
   NAVYBLUE = ( 60,  60, 100)
   WHITE   = (255, 255, 255)
   RED     = (255,   0,   0)
   GREEN   = (  0, 255,   0)
   BLUE    = (  0,   0, 255)
   YELLOW   = (255, 255,   0)
   ORANGE   = (255, 128,   0)
   PURPLE   = (255,   0, 255)
   CYAN    = (  0, 255, 255)
   BLACK   = (  0,   0,   0)
   COMBLUE  = (233, 232, 255)
   Colors=[RED,ORANGE,YELLOW,GREEN,NAVYBLUE]


	## PARAMETERS ##

   BGCOLOR = BLACK
   BLOCKWIDTH = 62
   BLOCKHEIGHT = 25
   BLOCKGAP = 2
   PADDLEWIDTH = 100
   PADDLEHEIGHT = 10
   BALLRADIUS = 20
   BALLCOLOR = WHITE


   w = 640
   h = 480 # alto
   t = 0   # tiempo de conteo para generar meteoritos
   # inicializando ...

   init_pygame((w,h),"Arkanoid")
   init_opengl((w,h))

   # sonidos
   # sound_shoot = pygame.mixer.Sound("laser.wav")
   # sound_shoot.set_volume(0.2)
	
   # # música de fondo
   # pygame.mixer.music.load("background.mp3")
   # pygame.mixer.music.play(-1,0.0)


   # medida de tiempo inicial
   t0=pygame.time.get_ticks()
   paddle=Paddle(WHITE,PADDLEHEIGHT,PADDLEWIDTH)
   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
   run=True
   inity=h - 5*BLOCKHEIGHT
   initx=0
   score=Score(h)
   blockArray=[]
   
   for i in range(0,len(level1)):
   	temp=[]
   	print(inity)
   	for j in range(0,len(level1[i])):
   		try:
   			a=Block(Colors[level1[i][j]-1],Vector(initx,inity),BLOCKHEIGHT,BLOCKWIDTH)
   			a.dibujar()
   		except Exception, e:
   			raise
   		else:
   			pass
   		finally:
Example #46
0
class Game:
	instance = None
	def __new__(cls, *args, **kwargs):
		if not cls.instance:
			cls.instance = super(Game, cls).__new__(cls, *args, **kwargs)
		return cls.instance

	def __init__(self, res, screen):
		self.res = res
		self.board = Board()
		self.defs = Defs()
		self.screen = screen
		self.board = self.board.new_board()
		self.block = Block(self.board)
		self.block.new_block()
		self.endgame = False
		self.score = 0
		self.scoreImageName = "./images/score.png"
		self.scoreImage = pygame.image.load(self.scoreImageName).convert()
		self.then = pygame.time.get_ticks()


	def draw_matrix(self, matrix, offset):
		#print(matrix, offset)
		off_x, off_y  = offset
		for y, row in enumerate(matrix):
			#print(y, row)
			for x, val in enumerate(row):
				#print(x, val)
				if val:
					pygame.draw.rect(
						self.screen,
						self.defs.colors[val],
						pygame.Rect(
							(off_x+x) *
							  self.defs.cell_size,
							(off_y+y) *
							  self.defs.cell_size,
							self.defs.cell_size,
							self.defs.cell_size),0)
					#print((off_x+x)*self.defs.cell_size, (off_y + y)*self.defs.cell_size)
	def Check_keys(self):
		for event in pygame.event.get():
			print("checking keys")
			if event.type == pygame.KEYDOWN:
				if not self.defs.check_collision(self.board, self.block.shape, (self.block.x, self.block.y)):
					self.score += 1
					if event.key == K_s:
						print("dropping~")
						self.block.drop()
					if event.key == K_d:
						self.block.move(1)
					if event.key == K_a:
						self.block.move(-1)
					if event.key == K_w:
						self.block.rotate_clockwise(self.block.shape)
					if event.key == K_ESCAPE:
						self.endgame = True
					if event.key == K_SPACE:
						self.score += 60
						while(not self.defs.check_collision(self.board, self.block.shape, (self.block.x, self.block.y))):
							self.block.drop()

		if not self.defs.check_collision(self.board, self.block.shape, (self.block.x, self.block.y)):
			self.now = pygame.time.get_ticks()
			if self.now - self.then > self.defs.maxfps * 8:
				self.then = self.now
				self.block.drop()

	def Run(self):
		self.Draw()

	def draw_next_block(self, matrix):
		for y, row in enumerate(matrix):
			#print(y, row)
			for x, val in enumerate(row):
				#print(x, val)
				if val:
					pygame.draw.rect(
						self.screen,
						self.defs.colors[val],
						pygame.Rect(
							300+x*self.defs.cell_size,
							self.res[1]-65+y*self.defs.cell_size,
							self.defs.cell_size,
							self.defs.cell_size),0)

	def Draw(self):
		self.board, bonus = Board().check_filled_rows(self.board)
		self.score += bonus
		#self.timer = pygame.time.Clock()
		self.scoreLabel = self.screen.blit(self.scoreImage, (60, self.res[1]-60))
		self.font_size = 48
		self.font = pygame.font.SysFont("arial", self.font_size)
		self.w, self.h = self.font.size(str(self.score))
		self.font_image = self.font.render(str(self.score), 1, (255, 255, 255))
		self.screen.blit(self.font_image, (200, self.res[1]-65))
		#print(self.block.shape, self.block.x, self.block.y)
		print("NSHAPE: ", self.block.nshape, self.block.nx, self.block.ny)
		self.draw_next_block(self.block.nshape)
		# check collision
		if not self.endgame:
			if self.defs.check_collision(self.board, self.block.shape, (self.block.x, self.block.y)):
				self.set_block(self.board, self.block.shape, (self.block.prevX, self.block.prevY))
				# if collides => make a new block
				self.block.new_block()
				print("collision!")
				if self.defs.check_collision(self.board, self.block.shape, (self.block.x, self.block.y)):
					print("endgame!")
					self.endgame = True
			else:
				# draw a block
				if not self.endgame:
					self.draw_matrix(self.block.shape, (self.block.x, self.block.y))
		# draw a board
		self.draw_matrix(self.board, (0,0))

	def set_block(self, board, shape, offset):
		print("setting a block")
		of_x, of_y = offset
		for cy, row in enumerate(shape):
			for cx, val in enumerate(row):
				if val:
					self.board[of_y + cy][of_x + cx] = val

	def Update(self, frameDeltaTime):
			self.Check_keys()
			pygame.display.update()
def ply_parse(text):
    """
    >>> import os
    >>> dirname = os.path.join(os.path.dirname(__file__), "data")
    >>> filename = os.path.join(dirname, "error1.blk")
    >>> with open(filename, encoding="utf8") as file:
    ...     ply_parse(file.read())
    Traceback (most recent call last):
    ...
    ValueError: Error {0}:line 8: unbalanced brackets []
    >>> filename = os.path.join(dirname, "error2.blk")
    >>> with open(filename, encoding="utf8") as file:
    ...     ply_parse(file.read())
    Traceback (most recent call last):
    ...
    ValueError: Error {0}:line 2: syntax error
    >>> filename = os.path.join(dirname, "error3.blk")
    >>> with open(filename, encoding="utf8") as file:
    ...     ply_parse(file.read())
    Traceback (most recent call last):
    ...
    ValueError: Error {0}:line 8: too many ']'s
    >>> expected = "[white: ]\\n[lightblue: Director]\\n/\\n/\\n[white: ]\\n[lightgreen: Secretary]\\n/\\n/\\n[white: Minion #1]\\n[white: ]\\n[white: Minion #2]"
    >>> filename = os.path.join(dirname, "hierarchy.blk")
    >>> with open(filename, encoding="utf8") as file:
    ...     blocks = ply_parse(file.read())
    >>> str(blocks).strip() == expected
    True

    >>> expected = "[#00CCDE: MessageBox Window\\n[lightgray: Frame\\n[white: ]\\n[white: Message text]\\n/\\n/\\n[goldenrod: OK Button]\\n[white: ]\\n[#ff0505: Cancel Button]\\n/\\n[white: ]\\n]\\n]"
    >>> filename = os.path.join(dirname, "messagebox.blk")
    >>> with open(filename, encoding="utf8") as file:
    ...     blocks = ply_parse(file.read())
    >>> str(blocks).strip() == expected
    True
    """
    tokens = ("NODE_START", "NODE_END", "COLOR", "NAME", "NEW_ROWS",
              "EMPTY_NODE")

    t_NODE_START = r"\["
    t_NODE_END = r"\]"
    t_COLOR = r"(?:\#[\dA-Fa-f]{6}|[a-zA-Z]\w*):"
    t_NAME = r"[^][/\n]+"
    t_NEW_ROWS = r"/+"
    t_EMPTY_NODE = r"\[\]"

    t_ignore = " \t"

    def t_newline(t):
        r"\n+"
        t.lexer.lineno += len(t.value)

    def t_error(t):
        line = t.value.lstrip()
        i = line.find("\n")
        line = line if i == -1 else line[:i]
        raise LexError("syntax error: {1}".format(line))


    stack = [Block.get_root_block()]
    block = None
    brackets = 0
    lexer = ply.lex.lex()
    try:
        lexer.input(text)
        for token in lexer:
            if token.type == "NODE_START":
                brackets += 1
                block = Block.get_empty_block()
                stack[-1].children.append(block)
                stack.append(block)
            elif token.type == "NODE_END":
                brackets -= 1
                if brackets < 0:
                    raise LexError("too many ']'s")
                block = None
                stack.pop()
            elif token.type == "COLOR":
                if block is None or Block.is_new_row(block):
                    raise LexError("syntax error")
                block.color = token.value[:-1]
            elif token.type == "NAME":
                if block is None or Block.is_new_row(block):
                    raise LexError("syntax error")
                block.name = token.value
            elif token.type == "EMPTY_NODE":
                stack[-1].children.append(Block.get_empty_block())
            elif token.type == "NEW_ROWS":
                for x in range(len(token.value)):
                    stack[-1].children.append(Block.get_new_row())
        if brackets:
            raise LexError("unbalanced brackets []")
    except LexError as err:
        raise ValueError("Error {{0}}:line {0}: {1}".format(
                         token.lineno + 1, err))
    return stack[0]
def pyparsing_parse(text):
    """
    >>> import os
    >>> dirname = os.path.join(os.path.dirname(__file__), "data")
    >>> filename = os.path.join(dirname, "error1.blk")
    >>> with open(filename, encoding="utf8") as file:
    ...     pyparsing_parse(file.read())
    Traceback (most recent call last):
    ...
    ValueError: Error {0}: syntax error, line 8
    >>> filename = os.path.join(dirname, "error2.blk")
    >>> with open(filename, encoding="utf8") as file:
    ...     pyparsing_parse(file.read())
    Traceback (most recent call last):
    ...
    ValueError: Error {0}: syntax error, line 1
    >>> filename = os.path.join(dirname, "error3.blk")
    >>> with open(filename, encoding="utf8") as file:
    ...     pyparsing_parse(file.read())
    Traceback (most recent call last):
    ...
    ValueError: Error {0}: syntax error, line 4
    >>> expected = "[white: ]\\n[lightblue: Director]\\n/\\n/\\n[white: ]\\n[lightgreen: Secretary]\\n/\\n/\\n[white: Minion #1]\\n[white: ]\\n[white: Minion #2]"
    >>> filename = os.path.join(dirname, "hierarchy.blk")
    >>> with open(filename, encoding="utf8") as file:
    ...     blocks = pyparsing_parse(file.read())
    >>> str(blocks).strip() == expected
    True

    >>> expected = "[#00CCDE: MessageBox Window\\n[lightgray: Frame\\n[white: ]\\n[white: Message text]\\n/\\n/\\n[goldenrod: OK Button]\\n[white: ]\\n[#ff0505: Cancel Button]\\n/\\n[white: ]\\n]\\n]"
    >>> filename = os.path.join(dirname, "messagebox.blk")
    >>> with open(filename, encoding="utf8") as file:
    ...     blocks = pyparsing_parse(file.read())
    >>> str(blocks).strip() == expected
    True
    """

    def add_block(tokens):
        return Block.Block(tokens.name, tokens.color if tokens.color
                                                     else "white")

    left_bracket, right_bracket = map(Suppress, "[]")
    new_rows = Word("/")("new_rows").setParseAction(
            lambda tokens: len(tokens.new_rows))
    name = CharsNotIn("[]/\n")("name").setParseAction(
            lambda tokens: tokens.name.strip())
    color = (Word("#", hexnums, exact=7) |
             Word(alphas, alphanums))("color")
    empty_node = (left_bracket + right_bracket).setParseAction(
            lambda: EmptyBlock)
    nodes = Forward()
    node_data = Optional(color + Suppress(":")) + Optional(name)
    node_data.setParseAction(add_block)
    node = left_bracket - node_data + nodes + right_bracket
    nodes << Group(ZeroOrMore(Optional(new_rows) +
                              OneOrMore(node | empty_node)))
    stack = [Block.get_root_block()]
    try:
        results = nodes.parseString(text, parseAll=True)
        assert len(results) == 1
        items = results.asList()[0]
        populate_children(items, stack)
    except (ParseException, ParseSyntaxException) as err:
        raise ValueError("Error {{0}}: syntax error, line "
                         "{0}".format(err.lineno))
    return stack[0]
Example #49
0
    def __init__(self, filename="getonmy.lvl"):
        """
        Loads a map from a filename according to the Map filetype specifications.
        """
        self.filename = filename
        self.block_list = []
        self.spawner_list = []
        self.player_pos = (0,0)
        self.waypoint_list = []
        s_n = 0
        
        # Iterate over each row in the map
        cur_x = -16
        cur_y = -16
        level_file = open(self.filename)
        for line in level_file:
            for char in line:
                # if it is not an empty space or newline
                if char not in {' ', '\n'}:
                    #===========================================================
                    # Create the thing and add special functionality
                    # based on the type.
                    #===========================================================
                    
                    # Blocks
                    if char in {'-', '='}:
                        block = Block(self.char_to_filename[char], cur_x, cur_y)
                    
                        if char == '-':
                            # Jump through-able platforms
                            block.can_jump_through = True
                        # if char == 'somechar':
                        #    give it some special property
                        #    or initialize it or something
                        #    This is where the enemies and
                        #    players and teleporters and
                        #    whatnot will get initialized.
                        
                        # Add the block to the block_list
                        self.block_list.append(block)
                    
                    # Player
                    if char == 'p':
                        self.player_pos = (cur_x, cur_y)

                    #------------------------------------
                    # Spawner and Spawner Characteristics
                    # spawnlist -> [dict{spawtype:[min_spawn_time, max_spawn_time}]
                    # s_n is the spawner number, topleft
                    # to bottom right
                    #------------------------------------
                    spawn_list = [{"basic":[5,10], "spiky":[20,30]},
                                  {"basic":[5,10], "spiky":[20,30]},
                                  {"basic":[5,10], "spiky":[20,30]},
                                  {"basic":[5,15], "spiky":[20,30]}]
                    if char == 's':
                        spawner = Spawner(self.char_to_filename[char],
                                          cur_x, cur_y,
                                          spawn_list[s_n])

                        self.spawner_list.append(spawner)
                        s_n += 1

                    # Waypoint
                    if char == 'w':
                        self.waypoint_list.append((cur_x, cur_y))
                        
                cur_x += 16
                
            cur_x = -16
            cur_y += 16
class Cell(object):
	def __init__(self, identity, dataBitSize):
		self.count = 0		
		self.dataSum = Block(identity, dataBitSize)
		self.hashProd = 1 #previously 1
		self.f = 0
		self.pickleHackCounter = 0

	def cellFromProtobuf(self, count, hashProd, data):
		self.count = count
		#self.count = (count)
		self.hashprod = hashProd
		self.dataSum.data = bitarray(str(data))

	def zeroCell(self):
		self.count = 0
#		self.count.setValue(0)
		self.dataSum.data.setall(False)
		self.hashProd =  1 #previously 1

	def setCount(self, count):
		self.count = count
#		self.count.setValue(count)

	def setHashProd(self, hashProd):
		self.hashProd = hashProd

	def setDataSum(self, dataSum):
		self.dataSum = dataSum

	def getCount(self):
		return self.count
#		return self.count.getValue()

	def getHashProd(self):
		return self.hashProd

	def getDataSum(self):
		return self.dataSum


	def add(self, block, secret, N, g, keepHashProdOne=False):
		self.count += 1
#		self.count.increment()
		
		self.dataSum.addBlockData(block)
		
		if keepHashProdOne == False:
	            f = MessageAuthenticationCode(secret, block)
        	    self.f = f
          	    self.hashProd = f ^ self.hashProd
			#f = apply_f(block, N, secret, g)
			#self.f = f
			#self.hashProd *= f
			#self.hashProd = gmpy2.powmod(self.hashProd, 1, N)
		else:
			self.hashProd = 1
			
		return

	def remove(self, block, secret, N, g):
		#TODO
		#count handling
		if (self.count < 0):
			self.count += 1
		else:
			self.count -= 1
#		self.count.decrementIfNotZero()
		
		
		if block.isZeroDataSum()==False: #TODO
			self.dataSum.addBlockData(block)
            		f = MessageAuthenticationCode(secret, block)
            
            		self.hashProd = f ^ self.hashProd
			#f = apply_f(block, N, secret, g)
			#fInv = number.inverse(f, N)  #TODO: Not sure this is true
			#self.hashProd *= fInv
			#self.hashProd = gmpy2.powmod(self.hashProd, 1, N)

	def isPure(self):
		if self.count == 1:  
			return True
		return False
#		return self.count.isPure()

	def isEmpty(self):
		if self.count == 0:
			return True
		return False
#		return self.count.isEmpty()

	def subtract(self, otherCell, dataBitSize, N, isHashProdOne=False):
		
		diffCell = Cell(0, dataBitSize)
		
		#counter
 		diffCell.count = self.count - otherCell.getCount()
#		diffCell.count.setValue(self.count.getValue()-otherCell.count.getValue())
		
		#datasum
		diffCell.dataSum.addBlockData(self.getDataSum())
		diffCell.dataSum.addBlockData(otherCell.getDataSum())
		if diffCell.count == 0 and diffCell.dataSum.isZeroDataSum() == False:
			print "AWESOME"
		#dataSum.addBlockData(localDS ^ otherDS)
		
		#hashProd
		diffCell.hashProd = long(1)	
		if isHashProdOne == False:
            		otherF = otherCell.getHashProd()
            		diffCell.hashProd = otherF ^ self.hashProd
			#otherFInv = number.inverse(otherCell.getHashProd(), N)
			#diffCell.hashProd = otherFInv * self.hashProd
			#diffCell.hashProd = gmpy2.powmod(diffCell.hashProd, 1, N) 
		
		return diffCell

	def printSelf(self):
		print "Index:" + str(self.dataSum.getDecimalIndex())
		print "Count: " + str(self.count.getValue())
		print "HashProd: " + str(self.hashProd)
		print "DataSum " + str(self.dataSum.getWholeBlockBitArray())
		print "------"
Example #51
0
    def readVI(self):
        reader = self.reader
        lastPos = -1
        curPos = 0
        header = {}
        while lastPos != curPos:
            lastPos = curPos
            reader.seek(curPos)
            #print curPos
            header['id1'] = reader.read(6)
            header['id2'] = reader.readInt16()
            header['id3'] = reader.read(4)
            header['id4'] = reader.read(4)
            if header['id1'] != "RSRC\r\n":
                raise IOError("Wrong File Format: Missing header 1")
            if header['id3'] != "LVIN":
                raise IOError("Wrong File Format: Missing header 3")
            if header['id4'] != "LBVW":
                raise IOError("Wrong File Format: Missing header 4")
            header['RSRCOffset'] = reader.readUInt32()
            header['RSRCSize'] = reader.readUInt32()
            #print header['RSRCOffset'], header['RSRCSize']
            if header['RSRCOffset'] >= 0 and header['RSRCSize'] >= 0:
                curPos = header['RSRCOffset']
            else:
                raise IOError("Wrong RSRC-Header")

        t = header['DataSet'] = {}
        t['Offset'] = reader.readUInt32()
        t['Size'] = reader.readUInt32()
        t['Int1'] = reader.readUInt32()
        t['Int2'] = reader.readUInt32()
        t['Int3'] = reader.readUInt32()

        t = header['BlockInfo'] = {}
        t['Offset'] = header['RSRCOffset'] + reader.readUInt32()
        t['Size'] = reader.readUInt32()

        self.header = header

        reader.seek(header['BlockInfo']['Offset'])

        blockInfoCount = reader.readUInt32() + 1
        if blockInfoCount > 1000:
            raise IOError("VI.BlockInfoCount too large?")

        blocks = {}
        blocks_arr = []
        block_headers = []

        for i in range(0, blockInfoCount):
            t = {}
            t['Name'] = reader.read(4)
            t['Count'] = reader.readUInt32() + 1
            t['Offset'] = header['BlockInfo']['Offset'] + reader.readUInt32()
            block_headers.append(t)

        self.block_headers = block_headers

        for i in range(0, blockInfoCount):
            block_head = block_headers[i]
            name = block_head['Name']
            if name in globals() and isinstance(globals()[name], type):
                print name, "!",
                block = globals()[name](self, block_head)
            else:
                block = Block(self, block_head)
            blocks_arr.append(block)

        self.blocks_arr = blocks_arr

        for i in range(0, blockInfoCount):
            block = blocks_arr[i]
            block.getData()
            blocks[block.name] = block

        self.blocks = blocks

        self.icon = self.blocks['icl8'].loadIcon() if 'icl8' in self.blocks else None
	def __init__(self, identity, dataBitSize):
		self.count = 0		
		self.dataSum = Block(identity, dataBitSize)
		self.hashProd = 1 #previously 1
		self.f = 0
		self.pickleHackCounter = 0