Beispiel #1
0
 def load_data(self):
     try:
         with open(
                 'blockchain_{}.txt'.format(self.node_id), mode='r'
         ) as f:  #The mode is write and not append (a) because we plan overwriting the data all the time.
             file_content = f.readlines()
             blockchain = json.loads(file_content[0][:-1])
             updated_blockchain = []
             for block in blockchain:
                 converted_tx = [
                     Transaction(tx['sender'], tx['recipient'],
                                 tx['signature'], tx['amount'])
                     for tx in block['transactions']
                 ]
                 updated_block = Block(block['hash_previous_block'],
                                       block['index'], converted_tx,
                                       block['proof'], block['timestamp'])
                 updated_blockchain.append(updated_block)
             self.chain = updated_blockchain
             open_transactions = json.loads(file_content[1][:-1])
             updated_open_transactions = []
             for transaction in open_transactions:
                 updated_transaction = Transaction(transaction['sender'],
                                                   transaction['recipient'],
                                                   transaction['signature'],
                                                   transaction['amount'])
                 updated_open_transactions.append(updated_transaction)
             self.open_transactions = updated_open_transactions
             peer_nodes = json.loads(file_content[2])
             self.peer_nodes = set(peer_nodes)
     except (IOError, IndexError):
         pass
Beispiel #2
0
 def save_data(self):
     try:
         with open(
                 'blockchain_{}.txt'.format(self.node_id), mode='w'
         ) as f:  #The mode is write and not append (a) because we plan overwriting the data all the time.
             saveable_chain = [
                 block.__dict__ for block in [
                     Block(block_el.hash_previous_block, block_el.index,
                           [tx.__dict__ for tx in block_el.transactions],
                           block_el.proof, block_el.timestamp)
                     for block_el in self.chain
                 ]
             ]
             f.write(json.dumps(saveable_chain))  #we write the blockchain
             f.write('\n')  #we jump a line
             saveable_open_transactions = [
                 tx.__dict__ for tx in self.open_transactions
             ]
             f.write(json.dumps(saveable_open_transactions)
                     )  #We then write the open transactions
             f.write("\n")
             f.write(json.dumps(list(self.peer_nodes)))
             #The with block statement will close the file automatically
     except IOError:
         print("Error while saving the file")
def blub2(times):
    for i in range(times):
        block2 = Block(None, spacesship2, 50, 50, 2)

        block2.rect.x = random.randint(-300, -50)
        block2.rect.y = random.randrange(75, screen_height - 450)

        block2_list.add(block2)
        all_sprites_list.add(block2)
def blub3(times):
    for i in range(times):
        bomber = Block(None, bomberpic, 200, 75, 4)

        bomber.rect.x = random.randint(-500, -200)
        bomber.rect.y = random.randrange(75, screen_height - 450)

        bomber_list.add(bomber)
        all_sprites_list.add(bomber)
def drop(x, y):
    zufall = random.randint(0, 4)
    if zufall == 1:
        drop_ammo = Block(None, ammo1, 25, 25, 0)
        drop_ammo.rect.x = x
        drop_ammo.rect.y = y

        ammo_drop_list.add(drop_ammo)
        all_sprites_list.add(drop_ammo)
def blub(times):
    for i in range(times):
        block = Block(None, spaceship, 50, 50, 1)

        block.rect.x = random.randint(-300, -50)
        block.rect.y = random.randint(75, screen_height - 450)

        block_list.add(block)
        all_sprites_list.add(block)
Beispiel #7
0
 def __init__(self, public_key, node_id):
     #Genesis block
     genesis_block = Block('', 0, [], 100)
     #initializing the chain
     self.chain = [genesis_block]
     #unhandled transactions
     self.open_transactions = []
     self.node_id = node_id
     self.peer_nodes = set()
     self.load_data()
     self.public_key = public_key
Beispiel #8
0
def spawnBlock(window):
    global blocksOnScreen, possibleBlockShapes
    block = Block()
    blockShape = random.choice(possibleBlockShapes)
    columnUpperLimit = getColumnUpperLimit(blockShape)
    block.returnRandomBlockShape(blockShape, columnUpperLimit)
    block.generateBlock(window)
    blocksOnScreen.append(block)
    return block
Beispiel #9
0
def lightweight():
    fullchain = [json.loads(block) for block in blockchain.chain]
    lightWeight = []
    for block in fullchain:
        blockObject = Block(block['index'], block['transactions'],
                            block['timestamp'], block['previous_hash'],
                            block['difficulty'])
        blockObject.merkle_root = block['merkle_root']
        blockObject.nonce = block['nonce']
        blockObject.difficulty = block['difficulty']
        lightWeight.append(blockObject.to_dict())
    response = {'chain': json.dumps(lightWeight), 'length': len(lightWeight)}
    return jsonify(response), 200
Beispiel #10
0
 def mine_block(self):
     if self.public_key == None:
         return None
         #return False
     if not Verification.verify_chain(self.chain):
         return None
     last_block = self.chain[-1]
     hashed_blocks = hash_block(last_block)
     proof = self.proof_of_work()
     reward_transaction = Transaction('MINING', self.public_key, '',
                                      MINING_REWARD)
     copied_transactions = self.open_transactions[:]
     for tx in copied_transactions:
         if not Wallet.verify_signature(tx):
             return None
             #return False
     copied_transactions.append(reward_transaction)
     block = Block(hashed_blocks, len(self.chain), copied_transactions,
                   proof)
     self.chain.append(block)
     self.open_transactions = []
     self.save_data()
     return block
Beispiel #11
0
 def mine_block(self):
     if self.public_key == None:
         return None
         #return False
     if not Verification.verify_chain(self.chain):
         return None
     last_block = self.chain[-1]
     hashed_blocks = hash_block(last_block)
     proof = self.proof_of_work()
     reward_transaction = Transaction('MINING', self.public_key, '',
                                      MINING_REWARD)
     copied_transactions = self.open_transactions[:]
     for tx in copied_transactions:
         if not Wallet.verify_signature(tx):
             return None
             #return False
     copied_transactions.append(reward_transaction)
     block = Block(hashed_blocks, len(self.chain), copied_transactions,
                   proof)
     self.chain.append(block)
     self.open_transactions = []
     self.save_data()
     for node in self.peer_nodes:
         url = 'http://{}/broadcast_block'.format(node)
         block_converted = block.__dict__.copy()
         block_converted['transactions'] = [
             tx.__dict__ for tx in block_converted['transactions']
         ]
         try:
             response = requests.post(url, json={'block': block_converted})
             if response.status_code == 400:
                 print('Block declined, needs resolving')
             if response.status_code == 500:
                 print('Block declined')
         except requests.exceptions.ConnectionError:
             continue
     return block
Beispiel #12
0
 def add_block(self, block):
     transactions = [
         Transaction(tx['sender'], tx['recipient'], tx['signature'],
                     tx['amount']) for tx in block['transactions']
     ]
     proof_is_valid = Verification.valid_proof(transactions[:-1],
                                               block['hash_previous_block'],
                                               block['proof'])
     hashes_match = hash_block(
         self.chain[-1]) == block['hash_previous_block']
     print("hash block ", hash_block(self.chain[-1]))
     print("block previous hash ", block['hash_previous_block'])
     print(proof_is_valid)
     print(hashes_match)
     if not proof_is_valid or not hashes_match:
         return False
     converted_block = Block(block['hash_previous_block'], block['index'],
                             transactions, block['proof'],
                             block['timestamp'])
     self.chain.append(converted_block)
     stored_transactions = self.open_transactions[:]
     for incomingtx in block['transactions']:
         for opentx in stored_transactions:
             print("incoming tx ", incomingtx)
             print("opentx ", opentx)
             if incomingtx['sender'] == opentx.sender and incomingtx[
                     'recipient'] == opentx.recipient and incomingtx[
                         'amount'] == opentx.amount and incomingtx[
                             'signature'] == opentx.signature:
                 #Only transactions that are the same everywhere should be mined
                 try:
                     self.open_transactions.remove(opentx)
                 except ValueError:
                     print('Item is already removed')
     self.save_data()
     return True
def readdxf(infile):
    infile = infile.readlines()
    file_index = 0

    block_record = []
    block_record_start_flag = False
    block_record_id_flag = False
    block_record_end_flag = False

#block record collection program start
#goes through dxf file and collects the unique ids of the blocks
    while block_record_end_flag == False:
        infile[file_index] = infile[file_index].strip()

        if infile[file_index] == 'BLOCK_RECORD':
            block_record_start_flag = True
            bloc_rec = Block_Record()

        elif infile[file_index] == '5':
            block_record_id_flag = True

        elif block_record_start_flag == True and block_record_id_flag == True:
            bloc_rec.name = infile[file_index]
            #l = copy.copy(bloc_rec)
            block_record.append(bloc_rec) #when using outside of class, you can append directly without the danger of overwriting

            block_record_start_flag = False
            block_record_id_flag = False

        elif infile[file_index] == 'ENDTAB':
            if infile[file_index+2].strip() == 'ENDSEC':
                block_record_start_flag = False
                block_record_id_flag = False
                block_record_end_flag = True
        file_index += 1


#block record collection program end

    block_list = []
    block_section_end_flag = False
#block collection program start
    while block_section_end_flag == False:
        block_id_flag = False
        block_acbdblockbegin_flag = False
        block_end_flag = False

        line_flag = False
        polyline_flag = False

        infile[file_index] = infile[file_index].strip()

        if infile[file_index] == 'BLOCK':
            block_start_flag = True
            bloc = Block()

        elif block_start_flag == True and infile[file_index] == '330':
            block_id_flag = True

        elif block_start_flag == True and block_id_flag == True:
            bloc.id = infile[file_index]
            block_id_flag = False

        elif infile[file_index] == 'AcDbBlockBegin' and block_start_flag == True:
            acbdblockbegin_flag = True

        elif infile[file_index] == '2' and acbdblockbegin_flag == True and block_start_flag == True:
            bloc.name = infile[file_index+1].strip()

        elif infile[file_index] == 'AcDbLine' and acbdblockbegin_flag == True and block_start_flag == True:
            line_flag = True

        elif line_flag == True and acbdblockbegin_flag == True and block_start_flag == True:
            if infile[file_index] == '10' and infile[file_index+2].strip() == '20':
                lin = Line(bloc.name)
                lin.x_start = entities[index+1].strip()
                lin.y_start = entities[index+3].strip()
                lin.x_end = entities[index+7].strip()
                lin.y_end = entities[index+9].strip()
                bloc.object_list['line'].append(lin)
                line_flag = False

        elif infile[file_index] == 'AcDbPolyline' and acbdblockbegin_flag == True and block_start_flag == True:
            polyline_flag = True

        elif polyline_flag == True and acbdblockbegin_flag == True and block_start_flag == True:
            if infile[file_index] == '10' and infile[file_index+2].strip() == '20':
                poly = Polyline(bloc.name)
                x_coordinates = entities[file_index+1:file_index+14:4].strip()
                y_coordinates = entities[file_index+3:file_index+16:4].strip()
                x_coordinates = [float(item) for item in self.x_coordinates]
                y_coordinates = [float(item) for item in self.y_coordinates]
                poly.x_bl = min(self.x_coordinates)
                poly.y_bl = min(self.y_coordinates)
                poly.x_tr = max(self.x_coordinates)
                poly.y_tr = max(self.y_coordinates)
                bloc.object_list['poly'].append(poly)
                polyline_flag = False

        elif infile[file_index] == 'AcDbBlockEnd' and acbdblockbegin_flag == True and block_start_flag == True:
            acbdblockbegin_flag = False
            block_start_flag = False
            block_list.append(bloc)

        elif infile[file_index] == 'ENDSEC':
            block_section_end_flag = True
            block_id_flag = False

        file_index += 1
def start_screen():
    # setting these vars into global
    global run, buttonpic, clock, health, mouse_visibility, fps

    # killing all sprites from the game-loop
    for block in block_list:
        pygame.sprite.Sprite.kill(block)
    for block in block2_list:
        pygame.sprite.Sprite.kill(block)
    for explosion in all_explosion:
        pygame.sprite.Sprite.kill(explosion)

    # init background
    sc1_background = Background(sc_bg3, 1)
    sc1_background2 = Background(sc_bg3, 1)
    background_list.add(sc1_background)
    background_list.add(sc1_background2)
    sc_background = Background(sc_bg2, 2)
    sc_background2 = Background(sc_bg2, 2)
    background_list.add(sc_background)
    background_list.add(sc_background2)
    background = Background(sc_bg1, 3)
    background2 = Background(sc_bg1, 3)
    background_list.add(background)
    background_list.add(background2)

    background.rect.x = 0
    background2.rect.x = screen_width
    sc_background.rect.x = 0
    sc_background2.rect.x = screen_width
    sc1_background.rect.x = 0
    sc1_background2.rect.x = screen_width

    # init mouse
    mouse_box = Block(red, None, 10, 10, 0)
    mouse_list.add(mouse_box)

    # here starts the loop
    start_screen_run = True
    mouse_visibility = pygame.mouse.set_visible(True)
    while start_screen_run:
        # the clock aka. max fps
        clock.tick(30)

        # setting the health value to default
        health = 100

        # getting information's from mouse
        mouse = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()

        # defining the the mouse-hitbox
        mouse_box.rect.x = mouse[0]
        mouse_box.rect.y = mouse[1]

        # checking for events like quit
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    start_screen_run = False
                if event.key == pygame.K_x:
                    pygame.quit()

        # moving the background to side
        for background in background_list:
            if background.layer == 1:
                background.rect.x -= 1
            if background.layer == 2:
                background.rect.x -= 2
            if background.layer == 3:
                background.rect.x -= 3
            if background.rect.x <= -screen_width:
                pygame.sprite.Sprite.kill(background)
                background_list.add(background)
                background.rect.x = screen_width

        # drawing everything
        window.fill(black)
        background_list.draw(window)
        fps = pygame.font.Font.render(font2, str(int(clock.get_fps())), True,
                                      green)
        window.blit(fps, (10, 10))
        window.blit(title2, ((screen_width / 2) - (titelx / 2),
                             (screen_height / 2) - (titely / 2)))
        button_list.draw(window)
        mouse_list.draw(window)
        pygame.display.flip()

    mouse_visibility = pygame.mouse.set_visible(False)
    for bg in background_list:
        pygame.sprite.Sprite.kill(bg)
    # after exiting killing all sprites
    for mouse in mouse_list:
        pygame.sprite.Sprite.kill(mouse)
Beispiel #15
0
def readdxf(infile, xmlfile):

    file = ET.parse('file.xml')
    tree = file.getroot()

    infile = infile.readlines()
    file_index = 0

    block_list = []
    block_section_start_flag = False
    block_section_end_flag = False

    block_start_flag = False
    block_id_flag = False
    acbdblockbegin_flag = False
    block_end_flag = False

    line_flag = False
    polyline_flag = False

    while block_section_end_flag == False:
        infile[file_index] = infile[file_index].strip()

        if infile[file_index] == 'BLOCKS':
            block_section_start_flag = True

        elif block_section_start_flag == True and infile[file_index] == 'BLOCK':
            block_start_flag = True
            bloc = Block()

        elif block_start_flag == True and infile[file_index] == '330':
            block_id_flag = True

        elif block_start_flag == True and block_id_flag == True:
            bloc.id = infile[file_index]
            block_id_flag = False

        elif infile[file_index] == 'AcDbBlockBegin' and block_start_flag == True and infile[file_index+1].strip() == '2':
            acbdblockbegin_flag = True
            bloc.name = infile[file_index+2].strip()

        elif infile[file_index] == 'AcDbLine' and acbdblockbegin_flag == True and block_start_flag == True:
            line_flag = True

        elif line_flag == True and acbdblockbegin_flag == True and block_start_flag == True:
            if infile[file_index] == '10' and infile[file_index+2].strip() == '20':
                lin = Line(bloc.name)
                lin.x_start = infile[file_index+1].strip()
                lin.y_start = infile[file_index+3].strip()
                lin.x_end = infile[file_index+7].strip()
                lin.y_end = infile[file_index+9].strip()
                bloc.object_list['line'].append(lin)
                line_flag = False

        elif infile[file_index] == 'AcDbPolyline' and acbdblockbegin_flag == True and block_start_flag == True:
            polyline_flag = True

        elif polyline_flag == True and acbdblockbegin_flag == True and block_start_flag == True:
            if infile[file_index] == '10' and infile[file_index+2].strip() == '20':
                poly = Polyline(bloc.name)
                x_coordinates = infile[file_index+1:file_index+14:4]
                for item in x_coordinates: item.strip()
                y_coordinates = infile[file_index+3:file_index+16:4]
                for item in y_coordinates: item.strip()
                x_coordinates = [float(item) for item in x_coordinates]
                y_coordinates = [float(item) for item in y_coordinates]
                poly.x_bl = min(x_coordinates)
                poly.y_bl = min(y_coordinates)
                poly.x_tr = max(x_coordinates)
                poly.y_tr = max(y_coordinates)
                bloc.object_list['poly'].append(poly)
                polyline_flag = False

        elif infile[file_index] == 'AcDbBlockEnd' and acbdblockbegin_flag == True and block_start_flag == True:
            acbdblockbegin_flag = False
            block_start_flag = False
            block_list.append(bloc)

        elif block_section_start_flag == True and infile[file_index] == 'ENDSEC':
            block_section_end_flag = True
            block_id_flag = False

        file_index += 1

    return block_list
Beispiel #16
0
def main():
    # print("enter var >>>")
    # var = input()

    data = [
        Data("test_file.csv", 1),
        Data("test_file.csv", 2),
        Data("test_file.csv", 3),
        Data("test_file.csv", 4),
        Data("test_file.csv", 5),
        Data("test_file2.csv", 1),
        Data("test_file2.csv", 2),
        Data("test_file2.csv", 3),
        Data("test_file2.csv", 4),
        Data("test_file2.csv", 5),
        Data("test_file2.csv", 1),
        Data("test_file.csv", 2),
    ]

    block1 = Block()
    block1.expand("5")

    block1.add_data(x for x in data)
    print(block1.name, "is of size", block1.max_size)
    print(block1.name, "has", block1.size, "entries")
    block1.hash_block()
    block1.confirm()
    print(block1.confirmed)

    print("\n")
    time.sleep(2)
    print("\n")

    block2 = Block()
    block2.expand(2)
    block2.add_data(x for x in data)
    print("{0} is of size {1}".format(block2.name, block2.max_size))
    print(block2.name, "has", block2.size, "entries")
    block2.hash_block()
    print(block2.confirm())

    print("\n")
    time.sleep(2)
    print("\n")

    block2 = Block()
    block2.expand("6")
    for x in data:
        block2.add_data(x)
    print(block2.name, "is of size", block2.max_size)
    print(block2.name, "has", block2.size, "entries")
    block2.hash_block()
    print(block2.confirm())

    print("\n")
    time.sleep(2)
    print("\n")

    block2 = Block()
    block2.expand("-2")
    for x in data:
        block2.add_data(x)
    print(block2.name, "is of size", block2.max_size)
    print(block2.name, "has", block2.size, "entries")
    block2.hash_block()
    print(block2.confirm())

    print("\n")
    time.sleep(2)
    print("\n")

    block2 = Block()
    for x in data:
        block2.add_data(x)
    print(block2.name, "is of size", block2.max_size)
    print(block2.name, "has", block2.size, "entries")
    block2.hash_block()
    print(block2.confirm())

    print("\n")
    time.sleep(2)
    print("\n")

    block2 = Block()
    block2.expand("4")
    for x in data:
        block2.add_data(x)
    print(block2.name, "is of size", block2.max_size)
    print(block2.name, "has", block2.size, "entries")
    block2.hash_block()
    print(block2.confirm())
    def run(self):
        # missile = Block(red, None, 5, 10, None)
        player = Player(spaceship, 50, 50)
        player.rect.x = screen_width / 2
        cursor = Block(None, cursorpic, 40, 40, None)
        ammopic = Block(None, ammo1, 25, 25, 0)
        wall = Wall(red, 10, screen_height)
        wall_list.add(wall)
        cursor_list.add(cursor)
        ammopic_list.add(ammopic)
        all_sprites_list.add(wall)
        all_sprites_list.add(player)
        player_list.add(player)
        ammopic.rect.y = screen_height - 200
        ammopic.rect.x = 50
        blub(2)
        while self.endless_run:
            # clock
            clock.tick(120)
            # count for waves
            self.count += 1
            # drawing the layers
            window.blit(bg, (0, 0))
            body(self.health)
            self.mouse = pygame.mouse.get_pos()
            self.keys = pygame.key.get_pressed()
            # defining wall position
            wall.rect.x = screen_width + 30
            wall.rect.y = 0
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_x:
                        self.endless_run = False
                    if event.key == pygame.K_ESCAPE:
                        self.endless_run = False

                # shoot missiles
                if event.type == pygame.MOUSEBUTTONDOWN and self.ammo > 0:

                    if event.button == 1:
                        self.ammo -= 1
                        missile = Missile(white, 5, 10, self.mouse[0],
                                          self.mouse[1], player.rect.x,
                                          player.rect.y)
                        missile.rect.x = player.rect.x + 25
                        missile.rect.y = player.rect.y
                        missiles.add(missile)
                        all_sprites_list.add(missile)
                        missile.dest_x = self.mouse[0]
                        missile.dest_y = self.mouse[1]

            # moving the missile
            for missile in missiles:
                start_x = player.rect.x
                start_y = player.rect.y

                x_diff = missile.dest_x - start_x
                y_diff = missile.dest_y - start_y
                angle = math.atan2(y_diff, x_diff)
                # missile.angle = math.degrees(angle)
                change_x = math.cos(angle) * 20
                change_y = math.sin(angle) * 20

                missile.rect.x += change_x
                missile.rect.y += change_y

            # moving block
            for block in block_list:
                # speed
                block.rect.x += 1
            # moving block2
            for block2 in block2_list:
                # speed
                block2.rect.x += 3
            # moving bomber
            for bomber in bomber_list:
                # speed
                bomber.rect.x += 1

            # defining position of the cursor
            cursor.rect.x = self.mouse[0]
            cursor.rect.y = self.mouse[1]

            # defining position of the player
            player.rect.y = screen_height - 300
            if self.keys[pygame.K_a]:
                player.rect.x -= 10
            if self.keys[pygame.K_d]:
                player.rect.x += 10

            # Checking for all interactions of block
            for block in block_list:
                blocks_hit_list = pygame.sprite.spritecollide(
                    block, missiles, True)
                end_screen = pygame.sprite.spritecollide(
                    block, wall_list, False)
                bomber_exploded = pygame.sprite.spritecollide(
                    block, bomber_exploded_list, False)

                if end_screen:
                    self.health -= 10
                    pygame.sprite.Sprite.kill(block)
                if blocks_hit_list:
                    block.health -= 1
                    print(block.health)
                if bomber_exploded:
                    self.score += 5
                    pygame.sprite.Sprite.kill(block)
                    explosion = Explosion(explosionpic, 50, 50)
                    explosion.rect.x, explosion.rect.y = block.rect.x, block.rect.y
                    all_explosion.add(explosion)
                    all_sprites_list.add(explosion)
                if block.health <= 0:
                    self.score += 5
                    pygame.sprite.Sprite.kill(block)
                    explosion = Explosion(explosionpic, 50, 50)
                    explosion.rect.x, explosion.rect.y = block.rect.x, block.rect.y
                    all_explosion.add(explosion)
                    all_sprites_list.add(explosion)
                    drop(block.rect.x, block.rect.y)

            # Checking for all interactions of block2
            for block in block2_list:
                blocks_hit_list = pygame.sprite.spritecollide(
                    block, missiles, True)
                end_screen = pygame.sprite.spritecollide(
                    block, wall_list, False)
                bomber_exploded = pygame.sprite.spritecollide(
                    block, bomber_exploded_list, False)

                if end_screen:
                    self.health -= 20
                    pygame.sprite.Sprite.kill(block)
                if blocks_hit_list:
                    block.health -= 1
                    print(block.health)
                if bomber_exploded:
                    self.score += 5
                    pygame.sprite.Sprite.kill(block)
                    explosion = Explosion(explosionpic, 50, 50)
                    explosion.rect.x, explosion.rect.y = block.rect.x, block.rect.y
                    all_explosion.add(explosion)
                    all_sprites_list.add(explosion)
                if block.health <= 0:
                    self.score += 5
                    pygame.sprite.Sprite.kill(block)
                    explosion = Explosion(explosionpic, 50, 50)
                    explosion.rect.x, explosion.rect.y = block.rect.x, block.rect.y
                    all_explosion.add(explosion)
                    all_sprites_list.add(explosion)

            # checking for all interactions of bomber
            for bomber in bomber_list:
                blocks_hit_list = pygame.sprite.spritecollide(
                    bomber, missiles, True)
                end_screen = pygame.sprite.spritecollide(
                    bomber, wall_list, False)
                bomber_exploded = pygame.sprite.spritecollide(
                    bomber, bomber_exploded_list, False)
                if end_screen:
                    self.health -= 20
                    pygame.sprite.Sprite.kill(bomber)
                if blocks_hit_list:
                    bomber.health -= 1
                    print(bomber.health)
                if bomber_exploded:
                    self.score += 15
                    pygame.sprite.Sprite.kill(bomber)
                    explosion = Explosion(bomber_explosion, 300, 150)
                    explosion.rect.x, explosion.rect.y = bomber.rect.x, bomber.rect.y
                    bomber_exploded_list.add(explosion)
                    all_sprites_list.add(explosion)
                if bomber.health <= 0:
                    self.score += 15
                    pygame.sprite.Sprite.kill(bomber)
                    explosion = Explosion(bomber_explosion, 300, 150)
                    explosion.rect.x, explosion.rect.y = bomber.rect.x, bomber.rect.y
                    bomber_exploded_list.add(explosion)
                    all_sprites_list.add(explosion)

            for player in player_list:
                player_pickup = pygame.sprite.spritecollide(
                    player, ammo_drop_list, True)
                if player_pickup:
                    self.ammo += 10

            # Checking all interactions with ammo_drop
            for drop_ammo in ammo_drop_list:
                if drop_ammo.rect.y < screen_height - 300:
                    drop_ammo.rect.y += 2

            # Checking the countdown for explosions
            for explosion in all_explosion:
                explosion.explosion_count += 1
                if explosion.explosion_count >= 60:
                    pygame.sprite.Sprite.kill(explosion)
                    explosion.explosion_count = 0

            for explosion in bomber_exploded_list:
                explosion.explosion_count += 1
                if explosion.explosion_count >= 120:
                    pygame.sprite.Sprite.kill(explosion)
                    explosion.explosion_count = 0

            # Checking for all interaction of missile
            for missile in missiles:
                if missile.rect.y <= -10:
                    pygame.sprite.Sprite.kill(missile)

            # Checking for all interaction of health
            if self.health <= 1:
                self.endless_run = False

            # Checking for count to create new wave
            if self.count >= speed:
                blub(2)
                zufall = random.randint(0, 4)
                if zufall == 1:
                    blub2(1)
                self.count = 0
                if zufall == 2:
                    blub3(1)

            all_sprites_list.draw(window)
            cursor_list.draw(window)
            text = pygame.font.Font.render(font1, f"SCORE {self.score}", True,
                                           green)
            fps = pygame.font.Font.render(font2, str(int(clock.get_fps())),
                                          True, green)
            window.blit(text, (50, screen_height - 100))
            window.blit(fps, (10, 10))
            ammo_text = pygame.font.Font.render(font3, f"{self.ammo}", True,
                                                green)
            window.blit(ammo_text, (100, screen_height - 200))
            ammopic_list.draw(window)
            pygame.display.update()

        # after exiting, killing sprites
        for cursor in cursor_list:
            pygame.sprite.Sprite.kill(cursor)
        for player in all_sprites_list:
            pygame.sprite.Sprite.kill(player)
Beispiel #18
0
def game_loop():
    block_arr = []
    rect_arr = []
    welcome()
    #loop variables
    exit_game = False
    game_start = False
    game_over = False
    ball_thrown = False
    platform = pygame.Rect(screen_width/2 , screen_height/2+200 , 100,10)
    ball = Ball([screen_width/2+30 , screen_height/2 + 200-7] , 7 , 1.5 ,  [math.cos(math.pi/4) , math.sin(math.pi/4)])
    score = 0
    lifes = 1


    #make list of blocks
    for _ in range(no_of_block):
        temp = Block([random.randint(100,800) , random.randint(50,300) , block_size , block_size] , Colors.rand_col() , 40)
        rect_arr.append(pygame.Rect(temp.list_info[0] , temp.list_info[1] , block_size , block_size))
        block_arr.append(temp)

    #game loop
    while not exit_game:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit_game = True
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    game_start = True
                elif event.key == pygame.K_ESCAPE:
                    game_start = False
                    ball_thrown = False
                    platform = pygame.Rect(screen_width / 2, screen_height / 2 + 200, 100, 10)
                    ball = Ball([screen_width / 2 + 30, screen_height / 2 + 200 - 7], 7, 1.5 ,[math.cos(math.pi/4) , math.sin(math.pi/4)])

            if event.type == pygame.MOUSEBUTTONDOWN and game_start:
                ball_thrown = True


        gameWindow.fill(Colors.white)
        if game_over:
            temp_color = Colors.rand_col()
            while not exit_game:
                gameWindow.fill(temp_color)
                text_screen("press x to restart", Colors.black, 350, 300)
                pygame.display.update()
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        exit_game = True
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_x:
                            game_loop()
        pygame.draw.rect(gameWindow , Colors.black , platform) #draw platform
        tr = pygame.draw.circle(gameWindow , Colors.black ,ball.center , ball.radius) #draw circle
        for i in range(len(block_arr)):
            if block_arr[i].color == (0,0,0):
                if(random.randint(1,5) == 1):
                    temp = Block([random.randint(100, 800), random.randint(50, 300), block_size, block_size],Colors.rand_col(), 40)
                    rect_arr[i] = pygame.Rect(temp.list_info[0] , temp.list_info[1] , block_size , block_size)
                    block_arr[i] = temp
            else:
                pygame.draw.rect(gameWindow, block_arr[i].color, block_arr[i].list_info)
        text_screen(f"Score {score}", Colors.red, 330, 525)
        text_screen(f"Lifes {lifes}", Colors.red, 530, 525)

        pygame.display.update()

        #move platform
        pos = pygame.mouse.get_pos()
        x = pos[0]
        y = pos[1]
        if game_start == True:
            try:
                platform.left = platform.left + 8*(x-platform.left)/((x-platform.left)*(x-platform.left) + (y-platform.top)*(y-platform.top) )**0.5
            except:
                pass
        
        #move ball
        if ball_thrown == False:
            ball.center = [platform.left+platform.width/2 , platform.top-7]
        else:
            temp_x = ball.center[0]
            temp_y = ball.center[1]
            ball.center = [temp_x + ball.direction[0]*ball.magnitude , temp_y - ball.direction[1]*ball.magnitude]
            if (ball.center[0] >= 893 and ball.direction[0] >0) or (ball.center[0] <= 0 and ball.direction[0]<0):
                ball.direction[0] = -1*ball.direction[0]
            if  ball.center[1] <= 0:
                if (ball.center[0] >= 893 and ball.direction[0] >0) or (ball.center[0] <= 0 and ball.direction[0]<0):
                    ball.direction = [math.cos(math.pi/4) , math.sin(math.pi/4)]
                else:
                    ball.direction[1] = -1*ball.direction[1]
            if pygame.Rect.colliderect(tr , platform) and ball.direction[1] <0:
                ball.direction[1] = -1*ball.direction[1]
            if ball.direction[0] == 0:
                ball.direction[0]= 1.5
            if ball.direction[1] == 0:
                ball.direction = 1.5

        #collision with block
        for i in range(no_of_block):
            if pygame.Rect.colliderect(tr , rect_arr[i]) and block_arr[i].color != (0,0,0):
                if abs(tr.left - rect_arr[i].right) <= 3:
                    ball.direction[0] = -1*ball.direction[0]
                elif abs(tr.right - rect_arr[i].left) <= 3:
                    ball.direction[0] = -1*ball.direction[0]
                elif abs(tr.top - rect_arr[i].bottom) <= 3:
                    ball.direction[1] = -1*ball.direction[1]
                elif abs(tr.bottom - rect_arr[i].top) <= 3:
                    ball.direction[1] = -1*ball.direction[1]
                temp0 = block_arr[i].color[0]
                temp1 = block_arr[i].color[1]
                temp2 = block_arr[i].color[2]
                block_arr[i].color = (int(temp0/1.2) , int(temp1/1.2) , int(temp2/1.2))
                if(random.randint(1,20) == 1):
                    score+=1

        #ball falls down
        if ball.center[1]>= 600:
            game_start = False
            ball_thrown = False
            lifes-=1
            if lifes == 0:
                game_over = True
            platform = pygame.Rect(screen_width / 2, screen_height / 2 + 200, 100, 10)
            ball = Ball([screen_width / 2 + 30, screen_height / 2 + 200 - 7], 7, 1.5,[math.cos(math.pi / 4), math.sin(math.pi / 4)])
        clock.tick(fps)
Beispiel #19
0
def renderBlocksForTesting(window):
    global collapsedBlocks
    cubeBlock = Block()
    jBlock = Block()
    lBlock = Block()
    cubeBlock.shape = cubeBlock.gameWindow.loadImage("cube-block.png")
    cubeBlock.blockShape = "cube"
    cubeBlock.row = 21
    cubeBlock.column = 2
    cubeBlock.isFalling = False
    jBlock.shape = jBlock.gameWindow.loadImage("j-block.png")
    jBlock.blockShape = "j"
    jBlock.isFalling = False
    jBlock.row = 18
    jBlock.column = 5
    lBlock.shape = lBlock.gameWindow.loadImage("L-block.png")
    lBlock.blockShape = "L"
    lBlock.isFalling = False
    lBlock.row = 21
    lBlock.column = 6
    collapsedBlocks.addToCollapsedBlocks(cubeBlock)
    collapsedBlocks.addToCollapsedBlocks(jBlock)
    collapsedBlocks.addToCollapsedBlocks(lBlock)
    return collapsedBlocks
Beispiel #20
0
def readdxf(infile):
    infile = infile.readlines()
    file_index = 0

    block_list = []
    block_section_start_flag = False
    block_section_end_flag = False

    block_start_flag = False
    block_id_flag = False
    acbdblockbegin_flag = False
    block_end_flag = False

    line_flag = False
    polyline_flag = False

    while block_section_end_flag == False:
        infile[file_index] = infile[file_index].strip()

        if infile[file_index] == "BLOCKS":
            block_section_start_flag = True

        elif block_section_start_flag == True and infile[file_index] == "BLOCK":
            block_start_flag = True
            bloc = Block()

        elif block_start_flag == True and infile[file_index] == "330":
            block_id_flag = True

        elif block_start_flag == True and block_id_flag == True:
            bloc.id = infile[file_index]
            block_id_flag = False

        elif (
            infile[file_index] == "AcDbBlockBegin"
            and block_start_flag == True
            and infile[file_index + 1].strip() == "2"
        ):
            acbdblockbegin_flag = True
            bloc.name = infile[file_index + 2].strip()

        elif infile[file_index] == "AcDbLine" and acbdblockbegin_flag == True and block_start_flag == True:
            line_flag = True

        elif line_flag == True and acbdblockbegin_flag == True and block_start_flag == True:
            if infile[file_index] == "10" and infile[file_index + 2].strip() == "20":
                lin = Line(bloc.name)
                lin.x_start = infile[file_index + 1].strip()
                lin.y_start = infile[file_index + 3].strip()
                lin.x_end = infile[file_index + 7].strip()
                lin.y_end = infile[file_index + 9].strip()
                bloc.object_list["line"].append(lin)
                line_flag = False

        elif infile[file_index] == "AcDbPolyline" and acbdblockbegin_flag == True and block_start_flag == True:
            polyline_flag = True

        elif polyline_flag == True and acbdblockbegin_flag == True and block_start_flag == True:
            if infile[file_index] == "10" and infile[file_index + 2].strip() == "20":
                poly = Polyline(bloc.name)
                x_coordinates = infile[file_index + 1 : file_index + 14 : 4]
                for item in x_coordinates:
                    item.strip()
                y_coordinates = infile[file_index + 3 : file_index + 16 : 4]
                for item in y_coordinates:
                    item.strip()
                x_coordinates = [float(item) for item in x_coordinates]
                y_coordinates = [float(item) for item in y_coordinates]
                poly.x_bl = min(x_coordinates)
                poly.y_bl = min(y_coordinates)
                poly.x_tr = max(x_coordinates)
                poly.y_tr = max(y_coordinates)
                bloc.object_list["poly"].append(poly)
                polyline_flag = False

        elif infile[file_index] == "AcDbBlockEnd" and acbdblockbegin_flag == True and block_start_flag == True:
            acbdblockbegin_flag = False
            block_start_flag = False
            block_list.append(bloc)

        elif block_section_start_flag == True and infile[file_index] == "ENDSEC":
            block_section_end_flag = True
            block_id_flag = False

        file_index += 1

    return block_list
Beispiel #21
0
 def gen_blocks(note_tuple):
     # index, note
     return Block(tile_positions[note_tuple[1][0], note_tuple[0]],
                  note_tuple[1][0], note_tuple[1][1])