Exemple #1
0
 def add_block(self, type_, col, row):
     if type_ == 'wall':
         self.walls.append(block.Block('wall.png', col, row))
     elif type_ == 'box':
         self.boxs.append(block.Block('box.png', col, row))
     else:
         self.targets.append(block.Block('target.png', col, row))
def initGrid():
    clearGrid()
    wall = block.Block("wall", "[  ]", (80, 80, 80, 255))

    for y in range(0, grid_dim[1]):
        for x in range(0, grid_dim[0]):
            if x == 0 or x == grid_dim[0] - 1 or y == 0 or y == grid_dim[1] - 1:
                if not (x == int(grid_dim[0] / 2) and
                        (y == 0 or y == grid_dim[1] - 1)):
                    grid[x][y] = wall
            else:
                if random.random() < 0.12 and not x == int(grid_dim[0] / 2):
                    grid[x][y] = wall
                #SPECIAL ITEM: PI (Increases heart spawn rate)
                if random.random() < 0.03 or (random.random() < 0.06 and
                                              getCurrentItemName() == "Pie"):
                    grid[x][y] = block.Block("heart", "❤", (255, 0, 0, 255),
                                             True)
                #SPECIAL ITEM: Gammos (Increases chest spawn rate)
                if random.random() < 0.015 or (random.random() < 0.01
                                               and getCurrentItemName()
                                               == "Gammos"):
                    grid[x][y] = block.Block("chest", "[?]", (0, 255, 0, 255))
    pl_pos[0] = int(grid_dim[0] / 2)
    pl_pos[1] = 0
 def __init__(self, mc, position=minecraft.Vec3(0, 0, 0)):
     #set defaults
     self.mc = mc
     #start position
     self.startposition = position
     #set turtle position
     self.position = position
     #set turtle angles
     self.heading = 0
     self.verticalheading = 0
     #set pen down
     self._pendown = True
     #set pen block to black wool
     self._penblock = block.Block(block.WOOL.id, 15)
     #flying to true
     self.flying = True
     #set speed
     self.turtlespeed = 6
     #create turtle
     self.showturtle = True
     # create drawing object
     self.mcDrawing = MinecraftDrawing(self.mc)
     # set turtle block
     self.turtleblock = block.Block(block.DIAMOND_BLOCK.id)
     # draw turtle
     self._drawTurtle(int(self.position.x), int(self.position.y),
                      int(self.position.y))
    def __init__(self, _width, _height, posX, posY, _level, _levelSpeed,
                 _itemsEnabled):
        self.height = _height
        self.width = _width
        self.fieldPosX = posX * configs.zoom
        self.fieldPosY = posY * configs.zoom
        self.field = []
        self.score = 0
        self.state = "running"
        self.goDownCounter = 1
        self.series = 0
        self.pressingRight = False
        self.pressingRightCounter = 0
        self.pressingRightFirstUpdate = 0
        self.pressingLeft = False
        self.pressingLeftCounter = 0
        self.pressingLeftFirstUpdate = 0
        self.level = _level
        self.itemEnabled = _itemsEnabled
        self.nextLevel = configs.levelUp[_level - 1] * _levelSpeed
        self.levelSpeed = _levelSpeed
        self.block = block.Block(3, 0)
        self.nextBlock = block.Block(3, 0)

        self.updateDropSpeed()

        # create the field lines and values
        for i in range(_height):
            new_line = []
            for j in range(_width):
                new_line.append(0)
            self.field.append(new_line)
Exemple #5
0
def validate_pow(bch, num):
    miners = bch[num - 1].powminers
    miners.sort(reverse=True)
    i = ((int(bch[num - 1].txs[num - 1].hash) + int(bch[num - 1].txs[-3].hash))
         % int(len(miners)**0.5))**2
    i1 = i
    bl = block.Block(miners[i][1], [miners[i][2]], bch, [], [], miners[i][3])
    while True:
        bl = block.Block(miners[i][1], [miners[i][2]], bch, [], [],
                         miners[i][3])
        bl.prevhash = bch[i - 1].h
        if int(bl.calc_pow_hash()) <= miners[i][0] <= pow_max:
            print('i167', i)
            break
        else:
            miners.remove(miners[i])
            if i == i1:
                raise NoValidMinersError
            if i == len(bch):
                i = i - len(bch) + 1
    if not miners[i][2] == bch[num].creators[0] or not bch[
            num].timestamp == miners[i][3] or not bch[num].n == miners[i][1]:
        print(
            hash(miners[i][2]) % 100,
            hash(bch[num].creators[0]) % 100, bch[num].timestamp, miners[i][3],
            bch[num].n, miners[i][1], i)
        return False
    return True
Exemple #6
0
 def load(self,filename):
     #######################################################################################
     # Programmer Name: Alec
     # Date: 5/20/17
     # Purpose: to load the level's elements from a file
     # Input: self, filename
     # Output: element_list attribute, height attribute
     #######################################################################################
     file=open("data/level/"+filename,"r")   # open file
     lines=file.readlines()                  # list of lines
     pos=[0,0]                               # origin position
     for line in lines:                      # for each line go through each character:
         for char in line:                       # for each character: 
             if char=="#":                           # determine the block it creates
                 b=block.Block(self.player,(pos),"brick")
                 self.element_list.append(b)
             elif char=="D":
                 self.exit=[pos[0],pos[1]]
             elif char=="F":
                 b=block.Block(self.player,(pos),"door")
                 self.element_list.append(b)
             elif char=="B":
                 b=block.Block(self.player,(pos),"bookshelf")
                 self.element_list.append(b)
             elif char=="S":
                 self.start=[pos[0]+25,pos[1]+25]
             pos[0]+=50              # move the x position for the next block
         pos[0]=0                    # reset x coordinate
         pos[1]+=50                  # move the y position for the next row
     self.height=pos[1]              # assign the height as the final y position
     file.close()                    # close the file
Exemple #7
0
 def test_blockchain(self):
     t = tn.CoinbaseTransaction(wt.pubToAddress(wt.privToPub(pk)))
     t.sign(pk)
     genesis_block = bk.Block(time.time(), '0' * 64,
                              s.Serializer.serialize(t))
     genesis_block.mine(2)
     bv.validate(genesis_block)
     '''genesis'''
     tr = tn.Transaction(wt.pubToAddress(wt.privToPub(pk)),
                         '12pULxeW59imr1mWs8AjQogji8H77KD3KT', 5)
     tr.sign(pk)
     sr = s.Serializer.serialize(tr)
     lst = []
     lst.append(s.Serializer.serialize(t))
     lst.append(sr)
     lst.append(sr)
     lst.append(sr)
     b1 = bk.Block(time.time(), genesis_block.hash, lst)
     b1.mine(2)
     bv.validate(b1)
     b2 = bk.Block(time.time(), b1.hash, lst)
     b2.mine(2)
     bv.validate(b2)
     chain = []
     chain.append(genesis_block)
     chain.append(b1)
     chain.append(b2)
     #b2.timestamp = "1241"
     self.assertTrue(is_valid_chain(chain))
     chain
Exemple #8
0
    def add_block(self, data):

        if (len(self.blocks) == 0):
            new_block = block.Block(data, genesis_block=True)
        else:
            most_recent_block = self.get_most_recent()
            new_block = block.Block(data, previous_block=most_recent_block)
        self.blocks.append(new_block)
Exemple #9
0
    def __init__(self):
        self.donkey = block.Block(donkeyImage, 20, 20)
        self.donkey.rect.x = 10
        self.donkey.rect.y = 80

        self.player = block.Block(playerImage, 15, 15)
        self.score = 0
        self.player.rect.x = 15
        self.player.rect.y = 475
    def compute_blocks(self, test=False):
        """Put repeats into MPPHB form."""
        self.blocks = []

        print("There are {} repeats".format(len(self.repeats)))
        counter = 0
        for repeat in self.repeats:
            if counter % 1000 == 0:
                if len(self.repeats) > 1000:
                    print("Processed {} repeats".format(counter))
            counter += 1
            # get repeat info
            starts = repeat[0]
            length = repeat[1]
            start = starts[0]
            # print("Length of this repeat is {}".format(length))
            # print("-----Processing repeats at starts {}".format(starts))
            occ, one_left, one_right = self.\
                get_occ_from_long_string(start, length)
            # check that these repeats are all valid
            self.check_repeats_while_processing(starts, length, occ)
            # figure out which paths are involved in the repeat
            indices, names = self.get_path_indices_and_names(starts,
                                                             length, occ)
            # figure out which snps
            snps = self.decode_snps(occ)
            # if this is actually a block (at least 1 snp and at least two
            # paths):
            if len(snps) > 0 and len(set(indices)) > 1:

                # create Block differently based on r_method
                if self.r_method == "distance":
                    # figure out location on the genome of first and last snp
                    distance = self.get_distance(names, snps)
                    # create block with these snps, these path indices and
                    # names, and computed length and overall genome length
                    self.blocks.append(block.Block(snps,
                                                   list(set(indices)),
                                                   list(set(names)),
                                                   self.r_method,
                                                   self.y_0,
                                                   distance,
                                                   self.genome_length))
                elif self.r_method == "frequency":
                    # we have a dictoinary with keys [(startsnp, endsnp)]
                    # pointing to a list of frequencies for this pair
                    snp1 = snps[0].split(":")[0]
                    snp2 = snps[-1].split(":")[0]
                    distance = self.get_distance(names, snps)
                    self.blocks.append(block.Block(snps,
                                       list(set(indices)),
                                       list(set(names)),
                                       self.r_method,
                                       self.y_0,
                                       freqs=self.freqs[(snp1, snp2)],
                                       length=distance))
Exemple #11
0
	def fillBlocks(self):
		### blocks
		import vector
		import block

		self.blocks.append(block.Block(vector.Vector(0.0, 1.75), 1.0, 3.5))
		self.blocks.append(block.Block(vector.Vector(self.field_width / 2.0  + 0.25, self.field_height / 2.0 - 0.5), 0.5, self.field_height + 1.0))
		self.blocks.append(block.Block(vector.Vector(-self.field_width / 2.0 - 0.25, self.field_height / 2.0 - 0.5), 0.5, self.field_height + 1.0))
		self.blocks.append(block.Block(vector.Vector(0.0, -0.5), self.field_width, 1.0))
		self.blocks.append(block.Block(vector.Vector(0.0, self.field_height - 0.25), self.field_width, 0.5))
    def read(self, address, current_step):
        r = None
        #Check if this is main memory
        #Main memory is always a hit
        if not self.next_level:
            r = response.Response({self.name: True}, self.hit_time)
        else:
            #Parse our address to look through this cache
            block_offset, index, tag = self.parse_address(address)

            #Get the tags in this set
            in_cache = list(self.data[index].keys())

            #If this tag exists in the set, this is a hit
            if tag in in_cache:
                r = response.Response({self.name: True}, self.hit_time)
            else:
                #Read from the next level of memory
                r = self.next_level.read(address, current_step)
                r.deepen(self.write_time, self.name)

                if self.policy == 'Inclusive':
                    print('Inclusive cache')
                    #TODO: your code here
                elif self.policy == 'Exclusive':
                    print('Exclusive cache')
                    #TODO: your code here
                else:
                    #If there's space in this set, add this block to it
                    if len(in_cache) < self.associativity:
                        self.data[index][tag] = block.Block(
                            self.block_size, current_step, False, address)
                    else:
                        #Find the oldest block and replace it
                        oldest_tag = in_cache[0]
                        for b in in_cache:
                            if self.data[index][b].last_accessed < self.data[
                                    index][oldest_tag].last_accessed:
                                oldest_tag = b
                        #Write the block back down if it's dirty and we're using write back
                        if self.write_back:
                            if self.data[index][oldest_tag].is_dirty():
                                self.logger.info('\tWriting back block ' +
                                                 address + ' to ' +
                                                 self.next_level.name)
                                temp = self.next_level.write(
                                    self.data[index][oldest_tag].address, True,
                                    current_step)
                                r.time += temp.time
                        #Delete the old block and write the new one
                        del self.data[index][oldest_tag]
                        self.data[index][tag] = block.Block(
                            self.block_size, current_step, False, address)

        return r
Exemple #13
0
def add_block():
    if len(blockchain) == 0:
        inp = input("Please enter the Data of your choice : ")
        blk_obj = block.Block('3kj13j4hbjh243b4hj23', inp)
        print('Block created with hash :', blk_obj.get_hash())
        blockchain.append(blk_obj)

    else:
        data = input("Please enter the Data of your choice : ")
        b_obj = block.Block(blockchain[-1].get_hash(), data)
        print('Block created with hash :', b_obj.get_hash())
        blockchain.append(b_obj)
 def generateNewblock(self, lastBlock, stop=False):
     while True:
         if self.type == 'PoW':
             new_hash, nonce, timestamp, tx = self.POW(lastBlock, stop)
             if not nonce:
                 return None
             if new_hash:
                 return block.Block(lastBlock.index + 1, lastBlock.hash, nonce, new_hash, timestamp, tx)
         elif self.type == 'PoS':
             new_hash, nonce, timestamp, tx = self.POS(lastBlock, stop)
             if new_hash:
                 return block.Block(lastBlock.index + 1, lastBlock.hash, nonce, new_hash, timestamp, tx)
Exemple #15
0
 def initcastle(self, screen):
     self.castleblocks = [
         block.Block("Images/castle.png", "Images/castle.png", (110, 50),
                     180, 10),
         block.Block("Images/castlepillar.png", "Images/castlepillar.png",
                     (100, 20), 20, 40),
         block.Block("Images/castlepillar.png", "Images/castlepillar.png",
                     (280, 20), 20, 40),
     ]
     self.castle_block_group = pygame.sprite.RenderPlain(*self.castleblocks)
     if (self.MODE == 1):
         self.castle_block_group.draw(screen)
Exemple #16
0
 def __init__(self, center, surface, board):
     Form.__init__(self, center, cst.CYAN, surface, board)
     self.blocks.append(
         block.Block(self.color, center, False, surface, board))
     center[0] += 1
     self.blocks.append(
         block.Block(self.color, center, False, surface, board))
     center[0] += 1
     self.blocks.append(
         block.Block(self.color, center, False, surface, board))
     center[0] -= 3
     self.blocks.append(
         block.Block(self.color, center, False, surface, board))
Exemple #17
0
 def __init__(self, center, surface, board):
     Form.__init__(self, center, cst.ORANGE, surface, board)
     self.blocks.append(
         block.Block(self.color, center, False, surface, board))
     center[0] -= 1
     self.blocks.append(
         block.Block(self.color, center, False, surface, board))
     center[0] += 2
     self.blocks.append(
         block.Block(self.color, center, False, surface, board))
     center[1] -= 1
     self.blocks.append(
         block.Block(self.color, center, False, surface, board))
Exemple #18
0
 def create_shape(self):
     if len(self.shape_group) < 1:
         new_shape = block.Block(self)
         self.shape_group.append(new_shape)
     elif len(self.shape_group) < 2:
         p1 = self.shape_group[-1].shape
         new_shape = block.Block(self, p1)
         self.shape_group.append(new_shape)
     else:
         p1 = self.shape_group[-1].shape
         p2 = self.shape_group[-2].shape
         new_shape = block.Block(self, p1, p2)
         self.shape_group.append(new_shape)
Exemple #19
0
def test_blockEquals():
    transaction.Transaction.id = 0
    block.Block.id = 0

    t = [transaction.Transaction(i, i + 1, 0) for i in range(10)]

    a = block.Block(t[:3])
    b = block.Block([t[2], t[1], t[0]])
    c = block.Block(t[-3:])

    assert a == b
    assert a != c
    assert b != c
Exemple #20
0
def mine(last_block):
    nonce = 0
    this_index = last_block.index + 1
    this_timestamp = date.datetime.now()
    this_data = "This is the #" + str(this_index) + " block!"
    this_hash = last_block.hash
    this_nonce = nonce
    new_block = block.Block(this_index, this_timestamp, this_data, this_hash,
                            nonce)
    while new_block.hash[:2] != "00":
        nonce += 1
        new_block = block.Block(this_index, this_timestamp, this_data,
                                this_hash, nonce)
    return new_block
Exemple #21
0
    def squaremaker(x,y,game_objects):

        for i in range(x,x+150,50):
            game_objects.append(block.Block(x=i, y=y, batch=main_batch))
            game_objects.append(finish.Finish(x=x+50, y=y+50, batch=main_batch))
            

        for i in range (y,y+150,50):
            game_objects.append(block.Block(x=x, y=i, batch=main_batch))

        for i in range(x,x+150,50):
            game_objects.append(block.Block(x=i, y=y+100, batch=main_batch))
        
        for i in range (y,y+150,50):
            game_objects.append(block.Block(x=x+100, y=i, batch=main_batch))
Exemple #22
0
def test(): # tester function to test/demo basic blockchain functionality
    blockchain = generateNewBlockchain() # generate new blockchain

    # add two blocks to the newblockchain
    paper1 = "There has been a recent resurgence in the area of explainable artificial intelligence as researchers and practitioners seek to provide more transparency to their algorithms. Much of this research is focused on explicitly explaining decisions or actions to a human observer, and it should not be controversial to say that looking at how humans explain to each other can serve as a useful starting point for explanation in artificial intelligence. However, it is fair to say that most work in explainable artificial intelligence uses only the researchers’ intuition of what constitutes a ‘good’ explanation. There exist vast and valuable bodies of research in philosophy, psychology, and cognitive science of how people define, generate, select, evaluate, and present explanations, which argues that people employ certain cognitive biases and social expectations to the explanation process. This paper argues that the field of explainable artificial intelligence can build on this existing research, and reviews relevant papers from philosophy, cognitive psychology/science, and social psychology, which study these topics. It draws out some important findings, and discusses ways that these can be infused with work on explainable artificial intelligence."
    block1 = block.Block(paper1)
    blockchain.add(block1)
    paper2 = "Recently, the notion of explainable artificial intelligence has seen a resurgence, after having slowed since the burst of work on explanation in expert systems over three decades ago; for example, see Chandrasekaran et al. [23], [168], and Buchanan and Shortliffe [14]. Sometimes abbreviated XAI (eXplainable artificial intelligence), the idea can be found in grant solicitations [32] and in the popular press [136]. This resurgence is driven by evidence that many AI applications have limited take up, or are not appropriated at all, due to ethical concerns [2] and a lack of trust on behalf of their users [166,101]. The running hypothesis is that by building more transparent, interpretable, or explainable systems, users will be better equipped to understand and therefore trust the intelligent agents [129,25,65]. While there are many ways to increase trust and transparency of intelligent agents, two complementary approaches will form part of many trusted autonomous systems: (1) generating decisions1 in which one of the criteria taken into account during the computation is how well a human could understand the decisions in the given context, which is often called interpretability or explainability; and (2) explicitly explaining decisions to people, which we will call explanation. Applications of explanation are considered in many sub-fields of artificial intelligence, such as justifying autonomous agent behaviour [129,65], debugging of machine learning models [89], explaining medical decision-making [45], and explaining predictions of classifiers [157]."
    block2 = block.Block(paper2)
    blockchain.add(block2)

    blockchain.print() # print the blockchain
    blockchain.save()  # save it to local file
    bc = loadBlockchain() # load the blockchain
    bc.print() # print the loaded blockchain
Exemple #23
0
    def new(self):
        # Starts a new game
        self.allSprites = pg.sprite.Group()
        self.balls = pg.sprite.Group()
        self.blocks = pg.sprite.Group()

        # Add Player Sprites
        self.player = player.Player()
        self.allSprites.add(self.player)

        # Add Enemy Sprites
        self.ball = ball.Ball()
        self.allSprites.add(self.ball)
        self.balls.add(self.ball)

        # Add any other sprites
        for row in range(self.noOfRows):
            for column in range(0, self.blockCount):
                block1 = block.Block(settings.RED, column * (settings.BLOCK_WIDTH + 2) + 1, self.top)
                self.blocks.add(block1)
                self.allSprites.add(block1)

            # Move the top of the next row down
            self.top += settings.BLOCK_HEIGHT + 2

        self.run()
Exemple #24
0
 def create_and_append_block(self, block_tx):
     """Create a block from a list of transactions"""
     new_block = block.Block(block_tx)
     # Lock block creation so that the blocks form a consistent chain
     # Only lock a small part of the creation so that multiple blocks
     # can be created at once and a small part is synchronised
     self.create_block_lock.acquire()
     new_block.set_prev_block(self.prev_block)
     new_block.calc_and_set_block_hash()
     self.prev_block = new_block
     self.blocks_created += 1
     # If the block cap has been reached, change the cleaning interval to
     # a predefined fixed value
     if self.blocks_created > self.block_cap:
         self.cleaning_interval = self.interval_after_cap
     store_block_thread = threading.Thread(target=self.store_block,
                                           args=[new_block])
     store_block_thread.start()
     self.last_n_blocks.append(new_block.block_hash)
     if len(self.last_n_blocks) > self.n_blocks_stored:
         self.last_n_blocks = self.last_n_blocks[1:]
     store_block_thread.join()
     self.check_block_tx_types(new_block.block_hash, block_tx)
     self.create_block_lock.release()
     # If we are benchmarking and the number of blocks created is the number
     # of blocks we are expecting based off the number of transactions
     # expected, then start the thread where it waits to kill this process
     if self.benchmark and self.blocks_created >= self.num_blocks \
             and not self.check_to_kill:
         self.check_to_kill = True
         kill_thread = threading.Thread(target=self.wait_to_kill)
         kill_thread.start()
Exemple #25
0
def erasure_decoder(pkg_name):
    """when there is enough block for decoding
    """
    block_manager = block.Block("{}/{}_donut.zip".format(
        os.getcwd(), pkg_name))
    block_manager.erasure_decode()
    print("donut--> decode done!!!")
Exemple #26
0
 def genesis_block(self):
     self.height = 0
     genesis = block.Block()
     genesis.GetMerkleRoot()
     genesis.MineBlock(self.complexity)
     self.chain.clear()
     self.chain.append(genesis)
Exemple #27
0
 def __init__(self, num_txs=None, block_cap=1000000, num_stored=1000,
              post_cap_interval=10):
     self.transactions = []
     self.running_threads = []
     # Synchronisation for block creation and list of running threads
     self.create_sync_vars()
     self.blocks_created = 0
     # How many blocks can be reached before using a fixed cleaning interval
     # This can be set to zero or one to always use a fixed cleaning interval
     self.block_cap = block_cap
     # How many block hashes to store when using a fixed cleaning interval
     # More blocks = longer fixed cleaning interval but higher possibility
     # of remove succeeding
     self.n_blocks_stored = num_stored
     # The fixed cleaning interval in seconds when using a fixed interval
     self.interval_after_cap = post_cap_interval
     try:
         # Try to open an existing database first
         self.db = plyvel.DB("/home/ben/mof-bc")
         last_tuple = pickle.loads(self.db.get('last'.encode('utf-8')))
         # Get the details of the existing database
         # (last block created and number of blocks)
         if last_tuple:
             self.prev_block = pickle.loads(self.db.get(last_tuple[0]))
             self.blocks_created = last_tuple[1]
         else:
             self.blocks_created = 0
     except plyvel.Error:
         # Database doesn't exist - create a new one
         self.db = plyvel.DB("/home/ben/mof-bc", create_if_missing=True)
         self.genesis = block.Block()
         self.genesis.calc_and_set_block_hash()
         self.prev_block = self.genesis
         self.store_block(self.genesis)
     self.sock = socket.socket()
     self.start_socket()
     self.key_hash_map = {}
     self.create_new_key()
     self.prev_tx = 'first'
     self.init_optimisation_variables()
     self.tx_per_block = 10
     # Create up to 5 threads that will create new blocks from transactions
     self.num_create_block_threads = 5
     # Spin up a thread that accepts new connections from users
     self.listen_thread = threading.Thread(target=self.accept_conn)
     self.listen_thread.start()
     # Spin up a new thread that checks the number of transactions received
     # and create new blocks if there are enough transactions
     self.check_tx_thread = threading.Thread(target=self.check_num_tx)
     self.check_tx_thread.start()
     # Spin up a new thread that will run cleaning period operations
     self.cleaning_thread = threading.Thread(target=self.clean_bc)
     self.cleaning_thread.start()
     # Used to terminate the miner when benchmarking
     self.check_to_kill = False
     self.benchmark = False
     if num_txs:
         self.benchmark = True
         self.start_time = None
         self.num_blocks = num_txs / self.tx_per_block
Exemple #28
0
    def nextRound(self, heartbeat):
        """Simulates the next round"""

        self.heartbeat = heartbeat

        # if start of round, reset validator, proposer set & update common blockchain
        if heartbeat % Solver.N_HEARTBEATS_IN_ROUND == 0:
            self.propSet = self.chooseProposers()  # choose proposer set

            # update common blockchain among players
            currBlock = self.players[0].blockchain
            same = True
            for i in self.players:
                if currBlock != i.blockchain:
                    same = False
                    break

            if same and currBlock != None:
                currBlock = block.Block(currBlock.txs,
                                        id=currBlock.id,
                                        proposer=currBlock.proposer)
                currBlock.next = self.blockchain
                self.blockchain = currBlock

        for i in self.players:
            i.action(heartbeat)
Exemple #29
0
    def gen_state(self, states):
        """
        Generate the current state as a useable dictonary and save it in the list of states.
        """

        # generate current block list
        new_block_list = []
        for blk in self.blk_list:
            # copy block
            b = block.Block(copy.deepcopy(blk.shape), blk.x, blk.y, blk.screen,
                            blk.color, blk.rotate_en, blk.letter, True)
            new_block_list.append(b)

        #depending on the representation, update it
        if (constants.REPRESENTATION_COMPLEX):
            r = RepresentationComplex.RepresentationComplex()
        else:
            r = representation.Representation()
        r.update(self.blk_list)
        formatted_r = r.format()
        gen_state = {
            "blk_list": new_block_list,
            "score": self.score,
            "representation": r,
            "formatted_representation": formatted_r
        }
        states.append(gen_state)
Exemple #30
0
def mine():
    # 获取区块链中最后一个区块的证明数字
    last_block = blockchain[-1]
    last_proof = last_block.data['proof_of_work']
    # 计算即将被挖掘区块的证明数字
    proof = proof_of_work(last_proof)
    # 一旦挖到新区块,则奖励矿工一笔交易
    this_nodes_transactions.append({
        'from': 'network',
        'to': miner_address,
        'amount': 1
    })
    # 收集交易信息等,生成新区块
    new_block_data = {
        "transactions": list(this_nodes_transactions),
        "proof_of_work": proof
    }
    this_block_index = last_block.index + 1
    this_block_timestamp = date.datetime.now()
    last_block_hash = last_block.hash
    # 清空本node交易信息列表
    this_nodes_transactions[:] = []
    # 创建新区块
    mined_block = block.Block(this_block_index, this_block_timestamp,
                              new_block_data, last_block_hash)
    # 加入到区块链
    blockchain.append(mined_block)
    # 让客户端知道我们挖到了新的区块
    return json.dumps({
        "index": this_block_index,
        "timestamp": str(this_block_timestamp),
        "data": new_block_data,
        "hash": last_block_hash
    }) + '\n'