Beispiel #1
0
 def spawn_block(self, direction):
     block_x = self.block_objects[-1].x
     block_y = self.block_objects[-1].y
     if direction == Direction.LEFT:
         block_x += self.width
     elif direction == Direction.RIGHT:
         block_x -= self.width
     elif direction == Direction.UP:
         block_y += self.height
     elif direction == Direction.DOWN:
         block_y -= self.height
     block = Block(block_x, block_y, self.width, self.height,
                   self.background)
     block.set_color(random_green())
     self.block_objects.append(block)
Beispiel #2
0
 def __init__(self, x, y, unit_width, unit_height, background, wait_time=0):
     super().__init__()
     self.x = x
     self.y = y
     self.width = unit_width
     self.height = unit_height
     self.background = background
     head = Block(self.x, self.y, self.width, self.height, self.background)
     head.set_color(DARK_RED)
     self.block_objects = [head]
     self.spawn_block(Direction.UP)
     self.spawn_block(Direction.UP)
     pygame.time.Clock()
     self.last_move_time = 0
     self.wait_time = wait_time
Beispiel #3
0
    def create_blok_by_csv(self, csv_file):
        df_data = pd.read_csv(csv_file, header=None)
        shape = df_data.shape
        assert len(shape) >= 2
        if shape[1] == 2:
            df_data.columns = ["time", "size"]
        elif shape[1]== 3:
            df_data.columns = ["time", "size", "key_frame"]

        for idx in range(shape[0]):
            det = 1
            priority = 0
            deadline = 0.2
            # change priority
            if "video" in csv_file:
                priority = 2
            elif "audio" in csv_file:
                priority = 1
            if "priority-" in csv_file:
                priority = csv_file[int(csv_file.index("priority-") + len("priority-"))]
            # change deadline
            if "ddl-" in csv_file:
                idx = csv_file.index("ddl-") + len("ddl-")
                for i in range(idx, len(csv_file)):
                    if csv_file[i] == '-':
                        deadline = float(csv_file[idx:i])
                        break
            # create block
            block = Block(bytes_size=float(df_data["size"][idx])*det,
                          deadline=deadline,
                          priority=priority,
                          timestamp=float(df_data["time"][idx]))
            self.block_queue.append(block)
Beispiel #4
0
def generate_genesis_block(WalletA):

    coinbase = Wallet()

    genesis = Transaction("0", coinbase.publicKey, WalletA.publicKey, 100,
                          None)
    genesis.generate_signature(coinbase.privateKey)
    genesis.outputs.append(
        TransactionOutput(genesis.transaction_id, genesis.reciepient,
                          genesis.value))
    main_utxo[genesis.outputs[0].id] = genesis.outputs[0]

    print("Creating and Mining Genesis block... ")
    block = Block("Hi I am a block 0", "0")
    block.add_transaction(genesis, main_utxo)
    add_block(block)
Beispiel #5
0
def load_blocks(level_manager: LevelManager):
    blocks = []
    layer = list(filter(lambda l: l["name"] == "blocks", level_manager.data["layers"]))[0]
    try:
        movement_layer = list(filter(lambda l: l["name"] == "block_move", level_manager.data["layers"]))[0]
    except IndexError:
        movement_layer = {"objects": []}
    for b in layer["objects"]:
        properties = b.get("properties", [])
        breakable = get_value_from_properties("breakable", True, properties)
        colour = get_value_from_properties("colour", "blue", properties)
        health = get_value_from_properties("health", 1, properties)
        colour_offset = get_value_from_properties("colour_offset", 0, properties)
        moving = get_value_from_properties("moving", False, properties)
        _id = b["id"]
        speed = get_value_from_properties("speed", 0, properties)
        end_x, end_y = (0, 0)
        if moving:
            max_move = find_max_move_from_id(movement_layer["objects"], _id)
            if max_move:
                end_x = max_move["x"] + max_move["width"]
                end_y = max_move["y"] + max_move["height"]
        blocks.append(Block(b["x"], b["y"], _id, colour, colour_offset, moving, breakable, health,
                            end_x, end_y, speed))
    return blocks
Beispiel #6
0
def main_node_block_miner():
    global blockchain
    transactions = miner_start_check_get_transaction()
    if transactions is False:
        return
    b = None
    if blockchain.chain == []:
        b = blockchain.genesis_block(transactions)
    else:
        b = Block(time.time(), blockchain.chain[-1].hash, transactions)
    b.sign(MINER_PRIVATE_KEY)
    if blockchain.mine(b) is True:
        # подпись транзакции
        for t in transactions:
            FileSystem.removeTransactionFromMempool(t)
        # Рассказываю тут всем дружественным нодам о то что я смайнил новый блок
        if block_validator.validate(b) != ReturnCode.OK:
            print("pezda")
            return
        print(b.hash)
Beispiel #7
0
def new_block():
    block = None
    try:
        block = Block.from_dict(request.get_json())
    except Exception as msg:
        print("ERROR. Block wasn't added. " + str(msg))
        return get_return_value(ReturnCode.INVALID_ARGUMENT)
    if block.validate_transactions() is False:
        return get_return_value(ReturnCode.INVALID_ARGUMENT)
    blockchain.new_block(block)
    return get_return_value(ReturnCode.OK.value)
	def __init__(self, screen, screen_width, screen_height, block_width):
		self.screen = screen
		self.width = screen_width
		self.height = screen_height
		self.block_width = block_width
		self.blocks_array = []
		self.width_blocks_count = 0
		self.height_blocks_count = 0;
		lowest_y = 0
		for i in range(self.block_height(), self.height - self.block_height(), self.block_height()):
			self.height_blocks_count += 1
			self.blocks_array.append(
				Block(0, i, self.block_width, self.block_height(), self))
			self.blocks_array.append(
				Block(self.width - self.block_width, i, self.block_width, self.block_height(), self))
			lowest_y = i + self.block_height()
		for i in range(0, self.width, self.block_width):
			self.width_blocks_count += 1
			self.blocks_array.append(
				Block(i, 0, self.block_width, self.block_height(), self))
			self.blocks_array.append(
				Block(i, lowest_y, self.block_width, self.block_height(), self))
Beispiel #9
0
    def parse(self):
        self.tokenizer.get_and_check_next("make a")

        block_type = self.tokenizer.get_and_check_next("block|goal")

        self.tokenizer.get_and_check_next("called")
        self.block_name = self.tokenizer.get_next()

        self.tokenizer.get_and_check_next("at")
        block_x = int(self.tokenizer.get_next())
        self.tokenizer.get_and_check_next(",")
        block_y = int(self.tokenizer.get_next())

        self.block = Block(block_type, block_x, block_y)
Beispiel #10
0
def main():

    WalletA = Wallet()
    WalletB = Wallet()
    WalletC = Wallet()
    generate_genesis_block(WalletA)

    block = Block("Hi I am a block " + str(len(blockchain)),
                  blockchain[len(blockchain) - 1].hash)
    print("\nWalletA's balance is: " + str(WalletA.get_balance(main_utxo)))
    print("\nWalletA is Attempting to send funds 40 to WalletB...")
    if (block.add_transaction(
            WalletA.send_funds(WalletB.publicKey, 40, main_utxo), main_utxo)):
        add_block(block)
        print("\nWalletA's balance is: " + str(WalletA.get_balance(main_utxo)))

    block = Block("Hi I am a block " + str(len(blockchain)),
                  blockchain[len(blockchain) - 1].hash)
    print("\nWalletB's balance is: " + str(WalletB.get_balance(main_utxo)))
    print("\nWalletB is Attempting to send funds 40 to WalletA...")
    if (block.add_transaction(
            WalletB.send_funds(WalletA.publicKey, 40, main_utxo), main_utxo)):
        add_block(block)
        print("\nWalletB's balance is: " + str(WalletB.get_balance(main_utxo)))

    block = Block("Hi I am a block " + str(len(blockchain)),
                  blockchain[len(blockchain) - 1].hash)
    print("\nWalletA's balance is: " + str(WalletA.get_balance(main_utxo)))
    print("\nWalletA is Attempting to send funds 20 to WalletC...")
    if (block.add_transaction(
            WalletA.send_funds(WalletC.publicKey, 20, main_utxo), main_utxo)):
        add_block(block)
        print("\nWalletC's balance is: " + str(WalletC.get_balance(main_utxo)))
        print("\nWalletA's balance is: " + str(WalletA.get_balance(main_utxo)))

    if (is_chain_valid()):
        print("Blockchain is valid")
Beispiel #11
0
    def create_block_by_file(self, block_file, det=0.1):
        with open(block_file, "r") as f:
            self.block_nums = int(f.readline())

            pattern_cols = ["type", "size", "ddl"]
            pattern=[]
            for line in f.readlines():
                pattern.append(
                    { pattern_cols[idx]:item.strip() for idx, item in enumerate(line.split(',')) }
                )

            peroid = len(pattern)
            for idx in range(self.block_nums):
                ch = idx % peroid
                block = Block(bytes_size=float(pattern[ch]["size"]),
                              deadline=float(pattern[ch]["ddl"]),
                              timestamp=self.init_time+self.pass_time+idx*det,
                              priority=pattern[ch]["type"])
                self.block_queue.append(block)
Beispiel #12
0
    def create_blok_by_csv(self, csv_file):
        df_data = pd.read_csv(csv_file, header=None)
        shape = df_data.shape
        assert len(shape) >= 2
        if shape[1] == 2:
            df_data.columns = ["time", "size"]
        elif shape[1]== 3:
            df_data.columns = ["time", "size", "key_frame"]

        for idx in range(shape[0]):
            det = 1
            priority = 0
            if "video" in csv_file:
                priority = 2
            elif "audio" in csv_file:
                priority = 1
            block = Block(bytes_size=float(df_data["size"][idx])*det,
                          deadline=0.2,
                          priority=priority,
                          timestamp=float(df_data["time"][idx]))
            self.block_queue.append(block)
Beispiel #13
0
 def genesis_block(self, transactions):
     gb = Block(str(time.time()), '0' * 64, transactions)
     return gb
Beispiel #14
0
        head = {'x': x_pos, 'y': y_pos}
        snake_size.append(head)

        if len(snake_size) > snake_length:
            del snake_size[0]

        for x in snake_size[:-1]:
            if x == head:
                close_game = True

        SNAKE.draw(snake_size, snake_block)
        WINDOW.display_score(str(snake_length - 1))
        WINDOW.refresh()

        if x_pos == Food.x_pos and y_pos == Food.y_pos:
            FOOD.random_position(snake_block)
            snake_length += 1

        WINDOW.snake_speed(Snake.SPEED)

    Windows.quit()
    sys.exit()


WINDOW = setup(Window.MEDIUM_SIZE, Window.TITLE)
BLOCK = Block(WINDOW)
FOOD = Food(copy(BLOCK), Colors.GREEN)
SNAKE = Python(copy(BLOCK), Colors.GRAY)

game_loop()
Beispiel #15
0
 def generate_block(self):
     """Создает и добавляет новый блок в список блоков."""
     self.blocks.append(Block(self.conf))
Beispiel #16
0
 def create_new_block(self):
     del self.current_block
     self.current_block = Block(self.form_handler.get_random_form(), self)