Ejemplo n.º 1
0
Archivo: blocks.py Proyecto: pjht/game
 def init(cls):
   GameRegistry.registerBlock(cls,cls.unlocalisedName)
   Block.registerTexture(cls.unlocalisedName)
   for i in range(3):
     path=os.path.join("animation",cls.unlocalisedName,"{}.png".format(i))
     img=pygame.image.load(path)
     cls.frames.append(img)
Ejemplo n.º 2
0
    def gen_blocks(self):
        ret_group = pygame.sprite.Group()
        y_value = 0
        for y in range(14):
            x_value = 0
            row = []
            for x in range(25):

                # Ending block
                if (x_value, y_value) != (840, 480):
                    # Starting block
                    if (x_value, y_value) == (80, 40):
                        b = Block((x_value, y_value), False)
                        b.color = (0, 0, 255)
                        b.image.fill((0, 0, 255))
                    else:
                        b = Block((x_value, y_value), False)
                else:
                    b = Block((x_value, y_value), True)
                    b.color = (255, 0, 0)
                    b.image.fill((255, 0, 0))
                    self.end_block = b

                ret_group.add(b)
                row.append(b)
                x_value += 40
            self.grid.append(row)
            y_value += 40

        for b in ret_group:
            b.get_neighbors(self.grid)
        return ret_group
Ejemplo n.º 3
0
Archivo: blocks.py Proyecto: pjht/game
 def __init__(self,x,y,screen):
   Block.__init__(self,x,y,screen)
   self.setTextureName(BlockFurnace.unlocalisedName)
   self.unlocalisedName=BlockFurnace.unlocalisedName
   self.frameno=0
   self.forward=True
   self.burn=False
   self.count=0
   self.inp=""
   self.inp_amount=0
   self.outp=""
   self.outp_amount=0
   self.fuel=""
   self.fuel_amount=0
   self.fuel_num=0
   self.originator=True
Ejemplo n.º 4
0
class Miner:
    FLAG = 1e6  #number of iteration of mining before check if the block has been found

    def __init__(self, blockchain, address):
        self.blockchain = blockchain
        self.address = address
        self.relay = RelayClient()
        self.updater = Updater(self.blockchain, self.relay)
        self.flag = 0
        self.index = 0

    def create_block(self):
        self.block = Block(self.blockchain.get_last_hash(), self.address)
        self.block.set_transactions(self.get_transactions())
        self.index = 0

    def get_transactions(self):
        """Allow to choose wich transactions will be placed in the block
        For now, it just take them in the chronological order"""
        ts = self.relay.get_transactions()
        if ts is None:
            return []
        # filter invalid transactions
        ts = list(filter(lambda t: t.is_valid(self.blockchain), ts))
        # transactions can be valid alone and invalid together
        # (e.g. 2 transactions with same sender)
        if not self.block.valid_transactions(self.blockchain):
            self.block.set_transactions([])
        # TODO: sort as you want (fee ?)
        return ts

    def run(self, strategy):
        """Strategy is the function called to find the next PoW"""
        print('Mining for address ' + str(self.address) + ' ', end='')
        self.create_block()
        while (1):
            if self.flag == 0:  # check relay for new block
                self.flag = Miner.FLAG
                if self.updater.update():
                    print('Downloaded new block')
                    print('Mining for address ' + str(self.address) + ' ',
                          end='')
                    self.create_block()
                print('.', end='', flush=True)  # show state to the user
            self.flag = self.flag - 1
            self.block.set_proof(strategy(self.index))
            self.index = self.index + 1
            if (self.block.good_difficulty()):
                print('\nMined block ' + self.block.get_hash())
                self.relay.submit_block(self.block)
                self.flag = 0  #Need to take new transactions
Ejemplo n.º 5
0
 def get_block(self, previous_hash):
     """send GET request to self.url/blocks/previous_hash
     """
     r = get_request(self.url+'blocks/'+previous_hash)
     if r is None:
         return None
     if not r.status_code == 200:
         return None
     return Block.fromJson(r.text)
Ejemplo n.º 6
0
 def post_block(self, json):
     b = Block.fromJson(json)
     if b is None:
         debug('JSON error')
         self.no_response(400)  # Bad Request
     elif not self.server.blockchain.add_block(b):
         debug('invalid block')
         self.no_response(400)  # Bad Request
     else:
         self.no_response(200)  # OK
         return b
Ejemplo n.º 7
0
Archivo: blocks.py Proyecto: pjht/game
def make_block(klass_name,name,clear=False,drops=False):
  def blk_init():
    pass
  def init(self,x,y,screen):
    Block.__init__(self,x,y,screen)
    self.setTextureName(name)
    self.clear=clear
    self.drops=drops
    self.unlocalisedName=name
  attr_table={
    "unlocalisedName":name,
    "__init__":init,
    "init":blk_init,
  }
  klass=type(klass_name,(Block,),attr_table)
  GameRegistry.registerBlock(klass,name)
  Block.registerTexture(name)
  glob=globals()
  glob[klass_name]=klass
  global dy_blocks
  dy_blocks[klass_name]=name
  return klass
Ejemplo n.º 8
0
    def __init__(self, h, w):
        # Size
        self.h = h
        self.w = w

        # Tiles number
        self.tilesH = h // TILESIZE
        self.tilesW = w // TILESIZE

        # Blocks
        self.blocks = []
        # Outer bounds
        for i in range(self.tilesH):
            for j in range(self.tilesW):
                if (i == 0 or i == self.tilesH - 1 or j == 0
                        or j == self.tilesW - 1):
                    self.blocks.append(Block(i * TILESIZE, j * TILESIZE))
        # Random block
        self.blocks.append(Block(self.h // 3, self.w // 2))

        # Map colors
        self.map = [COLORS["WHITE"] for i in range(self.tilesH * self.tilesW)]
Ejemplo n.º 9
0
def block_submit():
    """Submit a new block to the blockchain."""
    try:
        if not request.json:
            abort(400, "Invalid block")

        block = Block.deserialise_dict(request.json)
        CHAIN.blockdb.write_new_block(block, CHAIN.q)
        # Delete transactions from pending.
        for tx in block.transactions:
            CHAIN.transdb.delete_transaction(tx.txid)
        return "SUCCESS"
    except BlockValidationError as exc:
        abort(400, "Invalid block: {}".format(exc))
    except BlockChainError:
        abort(500, "Blockchain error")
Ejemplo n.º 10
0
Archivo: blocks.py Proyecto: pjht/game
 def __init__(self,x,y,screen):
   Block.__init__(self,x,y,screen)
   self.setTextureName(BlockWorkbench.unlocalisedName)
   self.unlocalisedName=BlockWorkbench.unlocalisedName
   self.inv=Inventory()
Ejemplo n.º 11
0
Archivo: blocks.py Proyecto: pjht/game
 def __init__(self,x,y,screen):
   Block.__init__(self,x,y,screen)
   self.setTextureName(BlockDoor.unlocalisedName)
   self.unlocalisedName=BlockDoor.unlocalisedName
Ejemplo n.º 12
0
Archivo: blocks.py Proyecto: pjht/game
 def init(cls):
   GameRegistry.registerBlock(cls,cls.unlocalisedName)
   Block.registerTexture(cls.unlocalisedName)
Ejemplo n.º 13
0
 def get_next_block(self, previous_hash):
     json = self.db.get_json_block(previous_hash)
     if json is None:
         return None
     return Block.fromJson(json[0])
Ejemplo n.º 14
0
import pprint

from lib.block import Block
from lib.chain import Chain

pp = pprint.PrettyPrinter(indent=4)

bc = Chain()
bc.MINE_DIFFICULTY = 6

# Generate genesis block
b0 = Block("Genesis block", "0")
bc.add_block(b0)

b1 = Block("first transaction", b0.hash)
bc.add_block(b1)

b2 = Block("second transaction", b1.hash)
bc.add_block(b2)

pp.pprint(bc.present())

hb = Block("first transaction - fake", b0.hash)
bc.blocks[1] = hb

pp.pprint(bc.present())
Ejemplo n.º 15
0
Archivo: blocks.py Proyecto: pjht/game
 def init(self,x,y,screen):
   Block.__init__(self,x,y,screen)
   self.setTextureName(name)
   self.clear=clear
   self.drops=drops
   self.unlocalisedName=name
Ejemplo n.º 16
0
    previousHash = blockchain.get_last_hash()
    print("previousHash")
    print(previousHash)

    print("TESTING Blocks DB")

    sender_address = Address()
    receiver1_address = Address()
    receiver2_address = Address()
    miner_address = Address()
    transaction = Transaction(sender_address.public(),
                              [(str(receiver1_address), 123),
                               (str(receiver2_address), 321)])
    print("transaction")
    print(str(transaction.toJson()))
    block = Block(previousHash, str(miner_address), [transaction])
    block.set_proof("43334")
    print("block")
    print(str(block.toJson()))
    json_block = block.toJson()
    print("json_block")
    print(str(json_block))

    db.add_json_block(previousHash, json_block)
    print("updated DB")
    print_blocks(db)

    db.set_last_hash(block.get_hash())
    previousHash2 = db.get_last_hash()

    sender2_address = Address()
Ejemplo n.º 17
0
Archivo: client.py Proyecto: pjht/game
def recvall(sock):
    BUFF_SIZE = 4096
    data = b''
    while True:
        part = sock.recv(BUFF_SIZE)
        data += part
        if len(part) < BUFF_SIZE:
            break
    # print("Got data: "+pp.pformat(pickle.loads(data)))
    return data


UNAME = input("UNAME:")
pygame.init()
Block.init()
recipes.init()
pygame.display.set_caption(UNAME)
screen = pygame.display.set_mode((constants.WINDWIDTH, constants.WINDHEIGHT))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# show_step("Connecting to game server")
sock.connect(("localhost", 2000))
# show_step("Adding user to server (Sending ADD_USR {})".format(UNAME))
send_str(sock, "ADD_USR")
send_str(sock, UNAME)
# show_step("Recieving UID")
my_uid = int(recv_str(sock))
# show_step("Got UID {}".format(my_uid))
# show_step("Initializing UID map")
uid_map = {}
# show_step("Initializing level map")
Ejemplo n.º 18
0
def build(working_dir):

    # Reading Front-End File
    data = initialize()

    # Creating dictionary of block types and their names
    # Example: (d62a6403-2db3-4832-9f4f-0f2dc8ac407d, Camera)
    info = data['dependencies']
    keys = info.keys()
    type_names = []

    for key in keys:

        name = info[key]['package']['name']
        name += info[key]['package']['version'].replace('.', '')
        type_names.append((key, name))
        loginfo("Creating Block: " + name)

    # Creating dictionary of block types and their ID's
    identifiers = data['design']['graph']['blocks']

    blocks = []
    parameters_list = []
    count = 1
    for block in identifiers:

        hex_id, block_type = block['id'], block['type']

        if block_type == 'basic.code':

            code_name = "Code_" + str(count)
            count += 1

            script = block['data']['code']
            generate_py_script(working_dir, script, code_name)

            new_block = Block(hex_id, block_type)
            new_block.name = code_name
            blocks.append(new_block)

        elif block_type == 'basic.constant':
            parameters_list.append((hex_id, block['data']['value']))

        elif block_type == 'basic.info':
            pass

        else:
            new_block = Block(hex_id, block_type)
            new_block.set_name(type_names)
            blocks.append(new_block)

    ############# Generating Scripts for User Code & Setting Parameters #################
    for key in keys:

        components = info[key]['design']['graph']['blocks']

        for element in components:

            if element['type'] == 'basic.code':

                script = element['data']['code']
                scr_name = info[key]['package']['name']
                scr_name += info[key]['package']['version'].replace('.', '')
                generate_py_script(working_dir, script, scr_name)

            elif element['type'] == 'basic.constant':

                for block in blocks:
                    if block.id_type == key:
                        block.add_parameter(element['data']['value'],
                                            element['id'])
    #####################################################################################

    # Reading Wires Mapping
    wires = data['design']['graph']['wires']

    ###################### Setting up communication between blocks ######################
    loginfo("Setting up connections...")

    for wire in wires:

        src_block, src_port = wire['source']['block'], wire['source']['port']
        tgt_block, tgt_port = wire['target']['block'], wire['target']['port']

        wire_id = src_block + str(src_port)

        # Connecting Paramters to Blocks
        if src_port == 'constant-out':

            param_value = None
            for param in parameters_list:
                if param[0] == src_block:
                    param_value = param[1]
                    break

            for block in blocks:
                if tgt_block == block.id:
                    block.add_parameter(param_value, tgt_port)
                    break

        # Connecting Wires to Blocks
        else:

            for block in blocks:
                if tgt_block == block.id:
                    block.connect_input_wire(wire_id, tgt_port)
                    break

            for block in blocks:
                if src_block == block.id:
                    block.connect_output_wire(wire_id, src_port)
                    break
    ######################################################################################

    return blocks
Ejemplo n.º 19
0
                if cmd[0] == "stop":
                    s.close()
                    f = open("worlds/map_{}.pkl".format(map_name), "wb")
                    pickle.dump(map, f)
                    f.close()
                    exit(1)


def exit_cleanup(signal, frame):
    s.close()
    f = open("worlds/map_{}.pkl".format(map_name), "wb")
    pickle.dump(map, f)
    f.close()


Block.init()
files = glob.glob("worlds/map_*.pkl")
if len(files) == 0:
    new = "y"
else:
    new = input("New world?").lower()
if new == "n" or new == "no":
    i = 1
    map_map = []
    for name in files:
        name = name.split("_")
        name.pop(0)
        name = "_".join(name)
        name, _ = os.path.splitext(name)
        print("{}. {}".format(i, name))
        map_map.append(name)
Ejemplo n.º 20
0
 def create_block(self):
     self.block = Block(self.blockchain.get_last_hash(), self.address)
     self.block.set_transactions(self.get_transactions())
     self.index = 0
Ejemplo n.º 21
0
            txlist = data.get('txlist')
            if not txlist:
                time.sleep(60)
                continue

            next_index = data.get('num_blocks')
            prev_hash_raw = data.get('prev_hash')
            pow_difficulty = data.get('pow')

            if not next_index or not prev_hash_raw or not pow_difficulty:
                exit_with_error("Server returned invalid info")

            prev_hash = Hash512.deserialise(prev_hash_raw)

            print("Mining block {} ...".format(next_index))
            block = Block(index=next_index, prev_hash=prev_hash)
            block.transactions = [Transaction.deserialise(x) for x in txlist]
            block.merkle_root = block.calculate_merkle_root()
            block.hash = block.calculate_hash()
            block.ensure_difficulty(pow_difficulty)

            r = requests.post(server_url + "/block/submit",
                              json=block.serialise_dict())
            if r.status_code != 200:
                exit_with_error("Error submitting block")

            print("Successfully mined block {}".format(block.index))
            print("Waiting for new transactions to mine ...")
    except KeyboardInterrupt:
        print("Exiting.")