Exemple #1
0
    def add_connection(self, block_1: Block, index_1, block_2: Block, index_2):
        """
        Add an edge between index_1 of block_1 and index_2 of block_2

        :param block_1: Block
        :param index_1: int
        :param block_2: Block
        :param index_2: int
        :return: None
        """
        # Since Value Blocks only allow one connection, get_block() always returns a new block for that variable
        block_1 = block_1.get_block()
        if block_1 not in self.block:
            self.block.append(block_1)
        block_2 = block_2.get_block()
        if block_2 not in self.block:
            self.block.append(block_2)
        if block_2 in block_1.adjacent.keys():
            block_1.adjacent[block_2].append((index_1, index_2))
        else:
            block_1.adjacent[block_2] = [(index_1, index_2)]
        if block_1 in block_2.adjacent.keys():
            block_2.adjacent[block_1].append((index_2, index_1))
        else:
            block_2.adjacent[block_1] = [(index_2, index_1)]
Exemple #2
0
 def create_block_select(self):
     b = Block()
     for i in range(len(b.colors)):
         b = Block(live=i)
         b.sprite.position = (300 + i * 100, 50)
         self.block_select.append(b)
         self.add(b.sprite)
Exemple #3
0
    def __process_block(self, data, is_inverted):
        if is_inverted:
            block = Block(1 - data)
        else:
            block = Block(data)
        if block.is_crc_ok:
            # # # # # # # ecc lut # # # # # # #
            if block.index in self.ecc_lut:
                self.ecc_lut[block.index].append(block.index_ecc)
            else:
                self.ecc_lut[block.index] = [block.index_ecc]
            # # # # # # # # # # # # # # # # # #
            try:
                if block.is_index_ecc_correct:
                    if block.is_metadata_block:
                        if self.__metadata_block is None:
                            self.__process_metadata_block(block)
                    else:
                        if self.__metadata_block_found:
                            self.__process_message_block(block)
                            if self.__blocks_received == self.__metadata_block.block_count - 1:
                                self.__processing_done = True
                                self.format_text()
            except IndexError:
                print("unknown block ecc: \n\tindex: {}\n\tecc: {}".format(
                    block.index, block.index_ecc))

        return self.__processing_done
Exemple #4
0
    def contract(self, x: Block, y: Block):
        """
        Contract two blocks on the edges between them. Removes both blocks from the network and adds a new block.
        Edges between the blocks x and y and other blocks are carried over to the new block.

        :param x:
        :param y:
        :return: None
        """
        xi = [i[0] for i in x.adjacent[y]]
        yi = [i[0] for i in y.adjacent[x]]

        def construct_index_list(node, start, index_list):
            l = []
            correspondence = {}
            compensation = 0
            for i in range(1, node.get_value().ndim + 1):
                idx = i + start
                if i not in index_list:
                    l.append(-idx + compensation)
                    # correspondence between old and new
                    correspondence[i] = idx - compensation
                else:
                    l.append(0)
                    compensation += 1
            return l, correspondence

        x_links, x_corr = construct_index_list(x, 0, xi)
        y_links, y_corr = construct_index_list(y, abs(min(x_links)), yi)
        common = 1
        for x_out, y_in in x.adjacent[y]:
            # Accounting for zero based indexing
            x_links[x_out - 1] = common
            y_links[y_in - 1] = common
            common += 1

        val = ncon([x.get_value(), y.get_value()], [x_links, y_links])
        new_block = Block(val)
        self.add_block(new_block)
        # Restoring old connections
        for z in x.adjacent.keys():
            if z == y:
                continue
            for x_out, z_in in x.adjacent[z]:
                self.add_connection(new_block, x_corr[x_out], z, z_in)

        for z in y.adjacent.keys():
            if z == x:
                continue
            for y_out, z_in in y.adjacent[z]:
                self.add_connection(new_block, y_corr[y_out], z, z_in)

        self.remove_block(x)
        self.remove_block(y)
 def create_block(self, data):
     last_block = self.handler.blockchain.get_last_blocks()
     block = Block(last_block[0].index + 1, data, last_block[0].hash,
                   datetime.now(), str(self.handler.server_host))
     block.mine(number_0=self.handler.blockchain.number_0)
     message = "****"
     message += "mined_block|"
     message += json.dumps(block, cls=BlockEncoder)
     self.handler.blockchain.new_block(block)
     self.handler.send_message_to_all(message)
     message_dict = {"sender": "Me", "content": message}
     self.handler.message_list.append(message_dict)
Exemple #6
0
    def generate_block_sequnce(self, data):
        block_sequnce = []
        if len(data):
            for i in range(0, len(data), config.USABLE_BLOCK_SIZE):
                block = Block.new(data[i:i + config.USABLE_BLOCK_SIZE])
                if i < len(data) - config.USABLE_BLOCK_SIZE:
                    block.set_next_block(self.block_manager.get_empty_block())
                block_sequnce.append(block)
        else:
            block_sequnce.append(Block.new(b""))

        return block_sequnce
Exemple #7
0
 def reset(self):
     '''生成blocks'''
     self.load()
     self.blocks = []
     blocks_props = self.blocks_props
     number_of_blocks = len(blocks_props)
     for i in range(number_of_blocks):
         x, y, live = blocks_props[i]
         b = Block()
         bx = int(x)
         by = int(y)
         b.sprite.position = (bx, by)
         b.live = live
         b.reset()
         self.blocks.append(b)
 def create_block(self):
     """
     Create a block from what is typed in the GUI, mine it and send it
     """
     data = self.dataText.toPlainText()
     last_block = self.handler.blockchain.get_last_blocks()
     block = Block(last_block[0].index + 1, data, last_block[0].hash,
                   datetime.now(), str(self.handler.server_host))
     block.mine(number_0=self.handler.blockchain.number_0)
     message = "****"
     message += "mined_block|"
     message += json.dumps(block, cls=BlockEncoder)
     self.handler.blockchain.new_block(block)
     self.handler.send_message_to_all(message)
     message_dict = {"sender": "Me", "content": message}
     self.handler.message_list.append(message_dict)
Exemple #9
0
    def create_first_block(self):
        """
        Create the frist block of the blockchain
        """

        first_block = Block(
            0,
            "First Block",
            None,
            datetime.now(),
            "unknown",
            branch_id=0,
        )
        # We can reduce the format if we want to take less space
        fork_id = self.add_fork(first_block.hash, 0)
        first_block.branch_id = fork_id
        self.add_block(first_block)
    def blockchain_protocol(self, message):
        blockchain = json.loads(message.split("|")[1])
        leaves = json.loads(message.split("|")[2])
        blockchain = [Block(**block) for block in blockchain]
        blockchain.sort()  # The blocks are sorted by height.

        for block in blockchain:
            self.blockchain.new_block(block)
Exemple #11
0
 def add_block(self, x, y):
     b = Block(live=self.block_live)
     for r in self.recttmp:
         if r.contains(x, y) and all(
             [r.position != b.sprite.position for b in self.blocks]):
             b.sprite.position = r.position
             self.add(b.sprite)
             self.blocks.append(b)
             break
Exemple #12
0
 def add_block(self, block: Block):
     """
     Adds a new block to the network
     :param block: Block to be added
     :return: None
     """
     if isinstance(block, ValueBlock):
         self.value_block.append(block)
     self.block.append(block.get_block())
 def test_rotating_4_times_should_result_in_same_shape(self):
     input_block = Block(5, [2, 4], [[0, 1], [1, 0], [1, 1], [1, 2]])
     expected_coords = [[-1, 0], [0, -1], [0, 0], [0, 1]]
     actual_block = transformer.rotate_90(input_block, 2)
     actual_block = transformer.rotate_90(actual_block, 2)
     actual_block = transformer.rotate_90(actual_block, 2)
     actual_block = transformer.rotate_90(actual_block, 2)
     actual_coords = actual_block.coordinates
     self.assertEqual(actual_coords, expected_coords)
Exemple #14
0
def validate(blockchain):
	genesisBlock =  blockchain[0] #Genesis
	blocks = blockchain[1:] #Resto de los bloques
	if str(genesisBlock)!=str(Block.getGenesis()): #El genesis de blockchain debe ser igual al de Block.getGenesis() ya que es una variable de clase.
		raise Exception('Invalid Genesis Block')
	for i, bl in enumerate(blocks):
		previousHash = bl.previousHash
		timestamp = bl.timestamp
		hash = bl.hash
		data = bl.data
		previousBlock = blockchain[i]
		#El bloque actual debe apuntar al Hash del bloque anterior.
		if previousHash!=previousBlock.hash:
			raise Exception('Invalid previous hash')
		#El hash del bloque actual debe ser correcto. Para eso comparo el hash del bloque actual con el devuelto por la funcion Hash en base a los datos del bloque.
		if hash!=Block.getHash(timestamp,previousHash,data):
			raise Exception('Invalid hash')

	return True
Exemple #15
0
 def create_grid(self):
     b = Block()
     ewidth = self.editor_right - self.editor_left
     left = int(self.editor_left + ewidth % b.sprite.width / 2)
     right = self.editor_right
     top = self.editor_top
     bottom = self.editor_bottom
     for x in range(left, right, b.sprite.width):
         for y in range(bottom, top, b.sprite.height):
             self.recttmp.append(Rect(x, y, b.sprite.width,
                                      b.sprite.height))
Exemple #16
0
def mine():
    # get the last proof of work
    last_block = blockchain.get_most_recent_block()
    last_proof = last_block['data']['proof_of_work']

    new_block_index = last_block['index'] + 1
    logger.info('mining new block with height {}'.format(new_block_index))

    # find the new proof of work for the current block being mined
    # The program will hang here until the proof of work is found
    proof = ProofOfWork(last_proof).calculate()

    # once we find a valid proof of work, we know we can mine a block so
    # we reward the miner by adding a transaction
    transactions.add_transaction({
        'from': 'network',
        'to': MINER_ADDRESS,
        'amount': MINER_REWARD
    })

    new_block_data = {
        'proof_of_work': proof,
        'transactions': transactions.get_transactions()
    }

    new_block_timestamp = str(date.datetime.now())
    last_block_hash = last_block['hash']

    # create the new block
    new_block = Block(
        new_block_index,
        new_block_timestamp,
        new_block_data
    )
    new_block.hash_block(last_block_hash)

    blockchain.write_block_to_disk(new_block)
    transactions.clear_transactions()

    # notify all nodes in network of new block
    network.broadcast_new_block(new_block)
Exemple #17
0
 def testInstantiationBasicBlock(self):
     index = 123
     transactions = [ 1, 2, 3 ]
     timestamp = 999388
     hashvalue = 123456
     
     b = Block(index, transactions, timestamp, hashvalue)
     self.assertEqual(b.index, index)
     self.assertEqual(b.transactions, transactions)
     self.assertEqual(b.timestamp, timestamp)
     self.assertEqual(b.previousHash, hashvalue)
     
Exemple #18
0
def post_newblock():
    if request.method == 'POST':
        data = json.loads(request.get_json(force=True))
        logger.info('Received new block from {}'.format(request.remote_addr))

        # load block object from json data
        new_block = Block(data['index'], data['timestamp'], data['data'],
                          data['hash'])

        blockchain.write_block_to_disk(new_block)
        txns.clear_transactions()
    return 'ok'
Exemple #19
0
 def augment_qgm(self, qgm: QGM, node_to_block):
     x1 = node_to_block[self.node1]
     x2 = node_to_block[self.node2]
     d1 = Diag(1, np.sqrt(np.exp(self.b + self.a / 2)))
     qgm.add_block(d1)
     d1c = Diag(1, np.sqrt(np.exp(self.b + self.a / 2)))
     qgm.add_block(d1c)
     d2 = Diag(1, np.sqrt(np.exp(self.c + self.a / 2)))
     qgm.add_block(d2)
     d2c = Diag(1, np.sqrt(np.exp(self.c + self.a / 2)))
     qgm.add_block(d2c)
     l1 = 2
     l2 = 2 * np.exp(-self.a / 2)
     m = Block(
         np.array([[.5 * (l1 + l2), .5 * (l1 - l2)],
                   [.5 * (l1 - l2), .5 * (l1 + l2)]]))
     qgm.add_block(m)
     trileg = []
     for i in range(2):
         trileg.append(Block(np.array([[[1, 0], [0, 0]], [[0, 0], [0,
                                                                   1]]])))
         qgm.add_block(trileg[i])
     hadamard = []
     for i in range(4):
         hadamard.append(Hadamard())
         qgm.add_block(hadamard[i])
     qgm.add_connection(d1c, 1, hadamard[0], 1)
     qgm.add_connection(hadamard[0], 2, trileg[0], 1)
     qgm.add_connection(trileg[0], 2, m, 1)
     qgm.add_connection(trileg[0], 3, hadamard[1], 1)
     qgm.add_connection(hadamard[1], 2, d2c, 1)
     qgm.add_connection(d1c, 2, x1, 1)
     qgm.add_connection(x1, 1, d1, 1)
     qgm.add_connection(d1, 2, hadamard[2], 1)
     qgm.add_connection(hadamard[2], 2, trileg[1], 1)
     qgm.add_connection(m, 2, trileg[1], 2)
     qgm.add_connection(trileg[1], 3, hadamard[3], 1)
     qgm.add_connection(d2c, 2, x2, 1)
     qgm.add_connection(x2, 1, d2, 1)
     qgm.add_connection(d2, 2, hadamard[3], 2)
Exemple #20
0
class test_block(unittest.TestCase):
    def setUp(self):
        self.sample_block = Block('0x123fff', 123123123, 'my_doc')

    def test_mine_hash_val_less_than_target(self):
        # arrange
        difficulty = 3

        # act
        hash_val = self.sample_block.mine(difficulty)

        # assert
        assert hash_val < 2**(257 - difficulty) - 1
Exemple #21
0
    def load_block_sequnce(self, address):
        block_sequnce = []

        with open(self.filepath, 'rb') as f:
            f.seek(address)

            while True:
                block_bytes = f.read(config.BLOCK_SIZE)
                block = Block.load(block_bytes)
                block_sequnce.append(block)

                if not block.is_last:
                    f.seek(BlockManager.address_from_id(block.next_block_id))
                else:
                    break

        return block_sequnce
Exemple #22
0
 def __parse_block(self, line, noerror=False):
     tokens = []
     self.emit_block_tokens = True
     error = True
     for tok in self:
         if tok.id == token.TOKEN_LBLOCK:
             tok.item = self.__parse_block(-1, True)
             self.emit_block_tokens = True
             tok.id = token.TOKEN_BLOCK
         elif tok.id == token.TOKEN_RBLOCK:
             error = False
             break
         tokens.append(tok)
     if self.__at_end and error and not noerror:
         raise Exception("[line {}] Unmatched [".format(line))
     self.emit_block_tokens = False
     return Block(tokens)
def test_from_block_json():
    test_index = 0
    test_nonce = 0
    test_hash = "0000abc"
    test_prev_hash = "prevHash"
    test_miner_id = "miner_id"
    test_reward = 5

    from_address = "from"
    to_address = "to"
    amount = 10.99
    id_ = "randomid"
    signature = "randomsignature"
    timestamp = 00000

    test_json = {
        "transaction": {
            "from_address": from_address,
            "to_address": to_address,
            "amount": amount,
            "id": id_,
            "signature": signature,
            "timestamp": timestamp,
        },
        "index": test_index,
        "nonce": test_nonce,
        "prev_hash": test_prev_hash,
        "miner_id": test_miner_id,
        "reward_amount": test_reward,
        "hash": test_hash,
    }
    block = Block.from_json(test_json)
    transaction = block.transaction
    assert block.miner_id == test_miner_id
    assert block.reward_amount == test_reward
    assert block.index == test_index
    assert block.nonce == test_nonce
    assert block.prev_hash == test_prev_hash

    assert transaction.from_address == from_address
    assert transaction.to_address == to_address
    assert transaction.id == id_
    assert transaction.signature == signature
    assert transaction.amount == amount
    assert transaction.timestamp == timestamp
    def mined_block_protocol(self, message):
        block_info_json = json.loads(message.split("|")[1])
        self.block_to_add = Block(**block_info_json)
        self.client.hiddenRefreshButton.click()
        if self.manual_validation:
            self.wait = True
            while self.wait:
                pass

        else:
            message = self.blockchain.new_block(self.block_to_add)
            for ip_node in self.other_nodes:
                send_message(ip_node, message)
            message_dict = {"sender": "Me", "content": message}
            self.message_list.append(message_dict)

        self.block_to_add = None
        self.client.hiddenRefreshButton.click()
def test_block_constructor():
    test_index = 0
    test_transaction = Transaction("toAddress", "fromAddress", 5,
                                   int(time.time()), "id", "signature")
    test_nonce = 0
    test_hash = "0000abc"
    test_prev_hash = "prevHash"
    test_miner_id = "miner_id"
    test_reward = 5

    test_block = Block(
        test_index,
        test_transaction,
        test_nonce,
        test_hash,
        test_prev_hash,
        test_miner_id,
        test_reward,
    )
    assert (test_block.index == test_index and test_block.transaction != None
            and test_block.nonce == 0 and len(test_block.hash) != 0
            and test_block.prev_hash == test_prev_hash
            and test_block.miner_id == "miner_id"
            and test_block.reward_amount == test_reward)
Exemple #26
0
                        os.system("cls")
                    print('Receiving peers  updated')

                    public_list_of_peers = pickle.loads(data_)
                    print(public_list_of_peers)
                    peersr = False

            except: 
                obj = pickle.loads(data_)
                print(type(obj).__name__)
                if type(obj).__name__ == 'Blockchain':
                    chain = obj
                    miner.savechain(chain)
                    miner.printchain()
                if type(obj) == list:
                    blk = Block(time.time(), miner.getchain().return_last_block().get_hash())
                    blk.add_transactions(obj)
                    blk.hashblock = blk.get_hashblock()
                    print('Mining block')
                    chain = miner.getchain()
                    proof = miner.proof_of_work(blk.get_hash())
                    blk.proof_of_work = proof
                    blk.miner = socket.gethostname()
                    print('Proof Generated',proof)
                    chain.add_block(blk)
                    sock.send(pickle.dumps(chain))

                #chain.print_block_chain()

                
    if sys.argv[1] == 'wallet':
Exemple #27
0
 def generate_block(self, x, y):
     """Create a new Block object at the given x,y and return it"""
     new_block = Block(self.settings, self.screen, self.block_image)
     new_block.rect.top = y
     new_block.rect.left = x
     return new_block
Exemple #28
0
def main():
    global play_intro_music
    """ Main Program """
    pygame.time.set_timer(USEREVENT + 1, 1000)
    pygame.time.set_timer(USEREVENT + 2, 1000)

    # Sound

    pygame.mixer.pre_init(44100, -16, 1, 512)
    pygame.init()
    pygame.mixer.init()
    bg_sound = pygame.mixer.Sound("src/sound/bg.wav")
    welcome_music = pygame.mixer.Sound("src/sound/welcome.wav")
    sound_coin = pygame.mixer.Sound("src/sound/coin.wav")
    oof = pygame.mixer.Sound("src/sound/oof.wav")
    oof.set_volume(0.6)

    # Set the height and width of the screen
    size = [SCREEN_WIDTH, SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("Lode Runner")

    # health

    heart = pygame.image.load('src/heart.png')

    font = pygame.font.Font('src/Pixel.otf', 20)
    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()
    FPS = 50
    score = 0
    removed_blocks = []
    health = 5
    last_time_hit = 0
    removed_enemies = []
    game_over = True
    start_game = True
    bg = pygame.image.load("src/oof.jpg")
    welcome_bg = pygame.image.load("src/welcome_bg.jpg")
    help = pygame.image.load('src/how_to.jpg')
    # -------- Main Program Loop -----------
    while not done:
        if game_over:
            if start_game:
                choice = start_game_screen(screen, clock, welcome_music, welcome_bg, help)
                start_game = False

                game_over = False
                score = 0
                removed_blocks = []
                health = 5
                last_time_hit = 0
                removed_enemies = []
                # restart  game

                # player
                if choice == 1:
                    # Create the player
                    bg_sound.play()
                    player = Player()
                    player_list = pygame.sprite.Group()
                    player_list.add(player)

                    # Create all the levels
                    level_list = [Level_01(player, 'src/brick_2.jpg')]

                    # Set the current level
                    current_level_no = 0
                    current_level = level_list[current_level_no]

                    player.level = current_level

                    # initialize player
                    player.rect.x = 500
                    player.rect.y = 490
                    # ladder
                    ladder_list = pygame.sprite.Group()
                    for i in range(10):
                        ladder = Ladder(210, 410 - (20 * (i + 1)), 'src/ladder.png')  # 1
                        ladder_list.add(ladder)
                    for i in range(7):
                        ladder = Ladder(610, 215 - (20 * (i + 1)), 'src/ladder.png')  # 2
                        ladder_list.add(ladder)
                    for i in range(11):
                        ladder = Ladder(790, 570 - (20 * (i + 1)), 'src/ladder.png')  # 3
                        ladder_list.add(ladder)
                    for i in range(9):
                        ladder = Ladder(2.5, 570 - (20 * (i + 1)), 'src/ladder.png')  # 4
                        ladder_list.add(ladder)
                    for i in range(8):
                        ladder = Ladder(680, 360 - (20 * (i + 1)), 'src/ladder.png')  # 5
                        ladder_list.add(ladder)

                    # enemy
                    enemy_list = pygame.sprite.Group()
                    enemy = Enemy(5, 64, 64, current_level.get_platform_list(), current_level.get_levels())
                    enemy_list.add(enemy)
                    enemy = Enemy(3, 64, 64, current_level.get_platform_list(), current_level.get_levels())
                    enemy_list.add(enemy)
                    enemy = Enemy(1, 64, 64, current_level.get_platform_list(), current_level.get_levels())
                    enemy_list.add(enemy)
                    enemy = Enemy(0, 64, 64, current_level.get_platform_list(), current_level.get_levels())
                    enemy_list.add(enemy)
                    enemy = Enemy(6, 64, 64, current_level.get_platform_list(), current_level.get_levels())
                    enemy_list.add(enemy)

                    # coins
                    for i in range(1):
                        #  This represents a block
                        block = Block('src/coin.png')
                    block_list = pygame.sprite.Group()
                    all_sprites_list = pygame.sprite.Group()
                    prev_level = random.randrange(0, 6)
                    prev_level = block.new_coin(current_level.get_levels(), prev_level)
                    while True:
                        if pygame.sprite.spritecollide(block, ladder_list, False):
                            prev_level = block.new_coin(current_level.get_levels(), prev_level)
                        else:
                            break
                    # Add the block to the list of objects
                    block_list.add(block)
                    all_sprites_list.add(block)
                elif choice == 2:
                    # Create the player
                    bg_sound.play()
                    player = Player()
                    player_list = pygame.sprite.Group()
                    player_list.add(player)

                    # Create all the levels
                    level_list = [Level_02(player, 'src/brick_purple.jpg')]

                    # Set the current level
                    current_level_no = 0
                    current_level = level_list[current_level_no]

                    player.level = current_level

                    # initialize player
                    player.rect.x = 500
                    player.rect.y = 490
                    # ladder
                    ladder_list = pygame.sprite.Group()
                    for i in range(25):
                        ladder = Ladder(180, 570 - (20 * (i + 1)), 'src/ladder.png')  # 1
                        ladder_list.add(ladder)
                    for i in range(25):
                        ladder = Ladder(770, 570 - (20 * (i + 1)), 'src/ladder.png')  # 2
                        ladder_list.add(ladder)

                    # enemy
                    enemy_list = pygame.sprite.Group()
                    enemy = Enemy(5, 64, 64, current_level.get_platform_list(), current_level.get_levels())
                    enemy_list.add(enemy)
                    enemy = Enemy(3, 64, 64, current_level.get_platform_list(), current_level.get_levels())
                    enemy_list.add(enemy)
                    enemy = Enemy(1, 64, 64, current_level.get_platform_list(), current_level.get_levels())
                    enemy_list.add(enemy)
                    enemy = Enemy(0, 64, 64, current_level.get_platform_list(), current_level.get_levels())
                    enemy_list.add(enemy)
                    enemy = Enemy(6, 64, 64, current_level.get_platform_list(), current_level.get_levels())
                    enemy_list.add(enemy)
                    # blocks
                    for i in range(1):
                        #  This represents a block
                        block = Block('src/coin.png')
                    block_list = pygame.sprite.Group()
                    all_sprites_list = pygame.sprite.Group()
                    prev_level = random.randrange(0, 6)
                    prev_level = block.new_coin(current_level.get_levels(), prev_level)
                    while True:
                        if pygame.sprite.spritecollide(block, ladder_list, False):
                            prev_level = block.new_coin(current_level.get_levels(), prev_level)
                        else:
                            break
                    # Add the block to the list of objects
                    block_list.add(block)
                    all_sprites_list.add(block)
                elif choice == -1:
                    done = True
                elif choice == 3:
                    return_button = Button('src/return_white.png', 930, 20, 10)
                    button_list = pygame.sprite.Group()
                    button_list.add(return_button)
                    x = pygame.mouse.get_pos()[0]
                    y = pygame.mouse.get_pos()[1]
                    cursor_list = pygame.sprite.Group()
                    cursor = Cursor('src/cursor.png', x, y)
                    cursor_list.add(cursor)

            else:
                if choice == 1:
                    choice = show_go_screen(screen, clock, bg_sound, 'src/oof.jpg', score, choice)
                elif choice == 2:
                    choice = show_go_screen(screen, clock, bg_sound, 'src/oof_level02.jpg', score, choice)
                start_game = True
        if choice != -1 and choice != 3:
            screen.fill(BLACK)
            if pygame.sprite.spritecollide(player, ladder_list, False):
                climbing = True
                player.set_is_climbing(True)
                player.setchangey(0)
            else:
                climbing = False
                player.setpressingbutton(False)

                player.set_is_climbing(False)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
                if event.type == USEREVENT + 1:
                    for block in removed_blocks:
                        if block[1] >= 3:
                            replace_block = current_level.replace_block(block[0])
                            removed_blocks.remove(block)
                            hit_list = pygame.sprite.spritecollide(replace_block, enemy_list, False)
                            for enemies in hit_list:
                                enemies.set_vel(0)
                                removed_enemy = enemies.getID()
                                removed_enemies.append([removed_enemy, 0])
                                enemy_list.remove(enemies)
                            hit_list = pygame.sprite.spritecollide(replace_block, player_list, False)
                            for players in hit_list:
                                health = 0
                                player_list.remove(players)

                            platform_list = current_level.get_platform_list()
                            for enemies in enemy_list:
                                enemies.set_platform(platform_list)
                        else:
                            block[1] += 1
                if event.type == USEREVENT + 2:
                    for enemies in removed_enemies:
                        enemies[1] += 1
                        if enemies[1] >= 10:
                            enemy = Enemy(enemies[0][0], enemies[0][1], enemies[0][2], enemies[0][3], enemies[0][4])
                            enemy_list.add(enemy)
                            removed_enemies.remove(enemies)

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        player.go_left(screen)
                    if event.key == pygame.K_RIGHT:
                        player.go_right(screen)
                    if event.key == pygame.K_SPACE:
                        player.jump()
                    if event.key == pygame.K_UP and climbing == True:
                        player.climb(-3, True)
                    if event.key == pygame.K_DOWN and climbing == True:
                        player.climb(3, True)
                    if event.key == pygame.K_r:
                        block_for_remove = player.destroy_block(current_level)

                        if block_for_remove != 0:
                            removed_blocks.append([block_for_remove, 0])
                            current_level.remove_block(block_for_remove)

                        platform_list = current_level.get_platform_list()
                        for enemies in enemy_list:
                            enemies.set_platform(platform_list)

                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_UP:
                        player.climb(0, False)
                    if event.key == pygame.K_DOWN:
                        player.climb(0, False)

                    if event.key == pygame.K_LEFT and player.change_x < 0:
                        player.stop()
                    if event.key == pygame.K_RIGHT and player.change_x > 0:
                        player.stop()

            # Update items in the level
            current_level.update()
            # If the player gets near the right side, shift the world left (-x)
            if player.rect.right > SCREEN_WIDTH:
                player.rect.right = SCREEN_WIDTH

            # If the player gets near the left side, shift the world right (+x)
            if player.rect.left < 0:
                player.rect.left = 0

            # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
            blocks_hit_list = pygame.sprite.spritecollide(player, block_list, False)

            # Check the list of collisions.
            for block in blocks_hit_list:
                score += 1
                sound_coin.play()
                prev_level = block.new_coin(current_level.get_levels(), prev_level)
                while True:
                    if pygame.sprite.spritecollide(block, ladder_list, False):
                        prev_level = block.new_coin(current_level.get_levels(), prev_level)
                    else:
                        break
            for players in player_list:
                if pygame.time.get_ticks() > last_time_hit + 3000 or last_time_hit == 0:
                    if pygame.sprite.spritecollide(players, enemy_list, False):
                        health -= 1
                        oof.play()
                        last_time_hit = pygame.time.get_ticks()
                        if health == 0:
                            player_list.remove(players)

            # health
            for i in range(health):
                if choice == 1:
                    screen.blit(heart, [850 + (i * 30), 30])
                elif choice == 2:
                    screen.blit(heart, [437 + (i * 30), 30])

            # Draw all the sprites
            # Update the player.

            text2 = font.render("Score:   " + str(score), True, WHITE)
            if choice == 1:
                screen.blit(text2, [850, 0])
            elif choice == 2:
                screen.blit(text2, [450, 0])
            current_level.draw(screen)
            block_list.update(screen)
            ladder_list.draw(screen)
            player_list.update(screen)
            for enemies in enemy_list:
                enemies.movement(screen)

            # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
            if health == 0:
                game_over = True
        elif choice == 3:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
                if event.type == pygame.MOUSEBUTTONDOWN and pygame.sprite.spritecollide(cursor, button_list, False):
                    buttons = pygame.sprite.spritecollide(cursor, button_list, False)
                    for button in buttons:
                        level = button.selected()
                        if level == 10:
                            start_game = True
                            game_over = True
                            play_intro_music = False
            image = pygame.image.load('src/how_to.jpg')
            screen.blit(image, (0, 0))
            isOverOut = False
            for button in pygame.sprite.spritecollide(cursor, button_list, False):
                isOverOut = True
                level = button.selected()
                if level == 10:
                    button.isOver('src/return.png')
            if not isOverOut:
                for button in button_list:
                    level = button.selected()
                    if level == 10:
                        button.isOver('src/return_white.png')
            button_list.draw(screen)
            x = pygame.mouse.get_pos()[0]
            y = pygame.mouse.get_pos()[1]
            cursor.update(x, y)
            cursor_list.draw(screen)

            # Limit to 50 frames per second
        clock.tick(FPS)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

    pygame.quit()
Exemple #29
0
 def addBlock(self, data):
     previousBlock = self.blocks[-1]
     block = Block.mine(previousBlock, data)
     self.blocks.append(block)
     return block
Exemple #30
0
 def __init__(self):
     self.blocks = [Block.getGenesis()]