Пример #1
0
    def add_pipe(self):

        display = pygame.display.get_window_size()
        width = display[0]
        height = display[1]
        height_for_the_pipes = height - 30

        def return_random_height():
            return random.randint(height_for_the_pipes - 260,
                                  height_for_the_pipes - 100)

        def get_x():
            x = width + 20 if self.pipes_list == [] else self.pipes_list[
                -1].x + 250

            return x

        x = get_x()

        top = self.pipes_list.append(
            pipe.Pipe(x, 0, 40, return_random_height(), self.color, 'top'))

        y_bottom_pipe = self.pipes_list[-1].rect.bottomleft[1] + 100
        if self.pipes_list[-1].position == 'top':

            if self.pipes_list[-1].rect.bottomleft[1] > height - 130:

                pass
            else:
                self.pipes_list.append(
                    pipe.Pipe(x, y_bottom_pipe, 40,
                              height_for_the_pipes - y_bottom_pipe, self.color,
                              'bottom'))
Пример #2
0
def create_2_pipes():
    random_pipe_height = random.randint(
        int((height / 4) - (floor_height / 2)),
        int((height * 3 / 4) - (floor_height / 2)))
    bottom_pipe = pipe.Pipe(screen, "up", width + 25,
                            random_pipe_height + int(pipe_gap / 2), pygame)
    top_pipe = pipe.Pipe(screen, "down", width + 25,
                         random_pipe_height - int(pipe_gap / 2), pygame)

    return bottom_pipe, top_pipe
Пример #3
0
def createPipePair(offset):
    mingap = 4
    maxgap = 10
    gap = random.randint(mingap, maxgap)
    remainingspace = 30 - gap
    upsize = random.randint(1, remainingspace)
    downsize = remainingspace - upsize

    up = pipe.Pipe(False, offset, upsize)
    down = pipe.Pipe(True, offset, downsize)
    return [up, down]
Пример #4
0
def draw():
    background(0)
    global score
    mybird.show()
    mybird.update()
    for i in reversed(range(len(pipes))):
        pipes[i].update()
        pipes[i].show()

        if pipes[i].passes(mybird):
            score += 1

        if pipes[i].hits(mybird):
            gameover()

        if pipes[i].offscreen():
            pipes.remove(pipes[i])

    if (frameCount) % 80 == 0:
        pipes.append(pipe.Pipe())

    if mybird.offscreen():
        gameover()

    showScores(score)
Пример #5
0
def test_order_retained():
    """ Ensure results are remain in the correct order.

    :raises AssertionError
    :return void
    """
    assert list(pipe.Pipe().run(range(5), lambda x: x)) == list(range(5))
Пример #6
0
    async def _list(self, conn):
        DIR_HEADER = 'dr-xr-xr-x 2 fwd fwd 4096'
        FILE_HEADER = '-r--r--r-- 2 fwd fwd'

        now = datetime.datetime.utcnow()

        def fmt_time(t):
            with utils.clocale():
                if t.year == now.year:
                    return t.strftime('%b %e %H:%M')
                else:
                    return t.strftime('%b %e %Y')

        entries = await self.datasource.list()
        listing = ''
        for name, entry in entries.items():
            if entry.size is None:
                listing += ' '.join([DIR_HEADER, fmt_time(entry.mtime), name])
            else:
                listing += ' '.join([
                    FILE_HEADER,
                    str(entry.size),
                    fmt_time(entry.mtime),
                    name,
                ])
            listing += '\r\n'

        sender = pipe.Pipe(conn)
        await sender.finish(listing.encode())
        await sender.join()
        return True
Пример #7
0
def read_monitor_config(configfile):
    """Reads the monitor configuration file for the Aggregator

    @param configfile: path of the config file
    @return: a list of Monitor or PipeMonitor objects
    """
    config = ConfigParser.ConfigParser()
    config.read(configfile)
    for section in config.sections():
        c = dict(config.items(section))

        if c['type'] == 'monitor':
            ignorelocal = parse_bool(c.get('ignorelocal', False))
            import monitor
            mon = monitor.Monitor(ignorelocal=ignorelocal)
            inc = [c.get('include', '')]
            exc = [c.get('exclude', '')]
            mon.set_filter(inc, exc)

        elif c['type'] == 'pipe':
            import pipe
            port = int(c['port'])
            newhost = c['newhost']
            newport = int(c['newport'])

            mon = pipe.PipeMonitor(pipe.Pipe(port, newhost, newport))
            #mon.set_shape(c.get('shape_threshold', 0))

        else:
            mon = None
            print 'unknown monitor type %s' % c['type']

        if mon:
            yield mon
Пример #8
0
def test_results_returned():
    """ Ensure results are actually returned.

    :raises AssertionError
    :return void
    """
    assert len(list(pipe.Pipe().run(range(5), lambda x: x))) == 5
Пример #9
0
def data_fetcher():
    data_pipe = pipe.Pipe()
    data_pipe.fetch_token()
    if running:
        response = data_pipe.fetch_pedestrian_data(
            'f6057765-ae16-4b8a-b0b8-c48de3b193c6', 1579962143154,
            1580048543154)
        print("Data retrieved... ")
        time.sleep(4)
Пример #10
0
 def add(self):
     if self.center <= 75:
         self.offset_ofCenter = random.randint(0, 125)
     elif self.center >= 435:
         self.offset_ofCenter = random.randint(-125, 0)
     else:
         self.offset_ofCenter = random.randint(-75, 75)
     temp = self.center
     self.center = self.offset_ofCenter + temp
     self.newPipe = p.Pipe(self.center)
     self.pipes.append(self.newPipe)
Пример #11
0
def test_exceptions():
    """ Ensure exceptions are raised in the main thread if 
    a job raises one.

    :raises AssertionError
    :return void
    """
    def work(item):
        raise Exception

    with pytest.raises(Exception):
        list(pipe.Pipe().run(range(5), work))
Пример #12
0
def cnew():
    import sys, os, popen2
    import cdebug
    import subprocess
    from nukescripts import pyQtAppUtils, utils
    mdebug = cdebug.cdebug()
    mdebug(sys.path)
    sys.path.append('/usr/pipeline/lib')
    #import nasset
    import pipe, filesys
    proc = subprocess.Popen(
        'nasset -m nuke',
        shell=True,
        stdout=subprocess.PIPE,
    )
    result = proc.communicate()[0]
    #result = nasset.browse('nuke')
    if result == 'cancel': return
    obj = filesys.get_options(result, 'm:t:d:c:')
    file_path = obj[1][0]
    proj_name = obj[1][1]
    tmp_path_file = os.path.join(filesys.USER_HOME, file_path)

    nuke.scriptSave(tmp_path_file)

    descr = obj[0]['-d']
    tags = obj[0]['-t']
    modes = obj[0]['-m'].split(',')

    type_name = modes[0]
    seq_name = modes[1]
    shot_name = modes[2]
    #print proj_name,tmp_path_file,descr,tags

    new_obj = pipe.Pipe().AddAsset(proj_name,
                                   tmp_path_file,
                                   descr,
                                   tags,
                                   filesys.COMP,
                                   sname=seq_name,
                                   shname=shot_name)
    script_path = new_obj.CheckOut('l')

    if len(modes) == 4:
        new_obj.setDependency(modes[3])

    if os.path.exists(script_path):
        os.system('sync')
        nuke.scriptOpen(script_path)
Пример #13
0
 def _parse_pipes(self, pipes_iter):
     for pipe in pipes_iter:
         pipe_dict = {}
         pipe_dict["arc_id"] = pipe.get("id")
         pipe_dict["from_node"] = pipe.get("from")
         pipe_dict["to_node"] = pipe.get("to")
         for element in pipe.iter():
             tag = self.strip_namespace(element)
             if tag == "pipe":
                 continue
             else:
                 new_name = self.cc_to_us(tag)
             pipe_dict[new_name] = float(element.get("value"))
         p_data = pipe_module.Pipe(**pipe_dict)
         self.pipe_data[p_data.arc_id] = p_data
Пример #14
0
def test_post_results():
    """ Ensure exceptions are provided to the handler if one
    exists

    :raises AssertionError
    :return void
    """
    def work(item):
        return item

    def processor(item):
        return item ** 2

    results = list(pipe.Pipe(
        post_processor = processor
    ).run(range(5), work)) == [0, 1, 4, 9, 16, 25]
Пример #15
0
def test_exception_handler():
    """ Ensure exceptions are provided to the handler if one
    exists

    :raises AssertionError
    :return void
    """
    def work(item):
        raise Exception

    def handler(e):
        pass

    assert not bool(list(pipe.Pipe(
        exception_handler = handler
    ).run(range(5), work)))
Пример #16
0
    async def _retr(self, conn, path):
        sender = pipe.Pipe(conn)
        send_task = asyncio.create_task(sender.join())

        try:
            try:
                async for chunk in self.datasource.fetch(path, self.rest):
                    await sender.send(chunk)
            finally:
                await sender.finish()
                await send_task
        except Exception:
            return False
        finally:
            self.rest = None
        return True
Пример #17
0
    def on_init(self):
        pygame.init()
        pygame.display.set_caption("Flappy Bird")
        self._display_surf = pygame.display.set_mode(
            (SCREEN_WIDTH, SCREEN_HEIGHT), pygame.HWSURFACE)
        self._running = True

        # set icon
        icon = pygame.image.load(BIRD_IMG)
        pygame.display.set_icon(icon)

        # bird object
        self.bird = bird.Bird()

        # images
        self.bird_image = pygame.image.load(BIRD_IMG)
        self.buildings_image = pygame.image.load(BG_CITY_IMG)
        self.sun_image = pygame.image.load(SUN_IMG)

        # clock
        self.clock = pygame.time.Clock()

        # pipe object
        self.pipe = pipe.Pipe()
Пример #18
0
def main():
    parser = argparse.ArgumentParser(
        description=textwrap.dedent('''\
        Demo Receiver

        Receives data directly from the Satellite API though the internet and
        outputs the data to a named pipe just like the Blockstream Satellite
        receiver application (blocksat-rx) would.

        '''),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('-f',
                        '--file',
                        default='/tmp/blocksat/api',
                        help='Pipe on which API data is received ' +
                        '(default: /tmp/blocksat/api)')
    parser.add_argument('-p',
                        '--port',
                        default=None,
                        help='Satellite API server port (default: None)')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('--net',
                       choices=['main', 'test'],
                       default=None,
                       help='Choose Mainnet (main) or Testnet (test) ' +
                       'Satellite API (default: main)')
    group.add_argument('-s',
                       '--server',
                       default='https://api.blockstream.space',
                       help='Satellite API server address (default: ' +
                       'https://api.blockstream.space)')
    parser.add_argument('--debug',
                        action='store_true',
                        help='Debug mode (default: false)')
    args = parser.parse_args()
    pipe_file = args.file
    port = args.port
    server = args.server
    net = args.net

    # Switch debug level
    if (args.debug):
        logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
        logging.debug('[Debug Mode]')

    if (net is not None and net == "main"):
        server = "https://api.blockstream.space"
    elif (net is not None and net == "test"):
        server = "https://api.blockstream.space/testnet"

    # Process the server address
    server_addr = server

    if (port is not None):
        server_addr = server + ":" + port

    if (server_addr == 'https://satellite.blockstream.com'):
        server_addr += '/api'

    # Open pipe
    pipe_f = pipe.Pipe(pipe_file)

    # Always keep a record of the last received sequence number
    last_seq_num = None

    print("Connecting with Satellite API server...")
    while (True):
        try:
            # Server-side Event Client
            r = requests.get(server_addr + "/subscribe/transmissions",
                             stream=True)
            r.raise_for_status()
            client = sseclient.SSEClient(r)
            print("Connected. Waiting for events...\n")

            # Continuously wait for events
            for event in client.events():
                # Parse the order corresponding to the event
                order = json.loads(event.data)

                # Debug
                logging.debug("Order: " +
                              json.dumps(order, indent=4, sort_keys=True))

                # Download the message only if its order has "sent" state
                if (order["status"] == "sent"):
                    # Sequence number
                    seq_num = order["tx_seq_num"]

                    # On a sequence number gap, catch up with missing messages
                    if (last_seq_num is not None):
                        expected_seq_num = (last_seq_num + 1) % (MAX_SEQ_NUM)

                        if (seq_num != expected_seq_num):
                            catch_up(pipe_f, server_addr, seq_num,
                                     last_seq_num)

                    print("[%s]: New transmission - #%-5d - Size: %d bytes\t" %
                          (order["ended_transmission_at"], seq_num,
                           order["message_size"]))

                    # Get the data
                    data = fetch_api_data(server_addr, seq_num)

                    # Output to named pipe
                    if (data is not None):
                        data_struct = create_output_data_struct(data)
                        pipe_f.write(data_struct)
                        logging.debug("Output %d bytes to pipe %s" %
                                      (len(data_struct), pipe_f.name))

                    # Record the sequence number of the order that was received
                    last_seq_num = seq_num

        except requests.exceptions.ChunkedEncodingError:
            print("Reconnecting...")
            pass
        except requests.exceptions.ConnectionError as e:
            print(e)
            logging.info("Connection failed - trying again...")
            time.sleep(1)
            pass
Пример #19
0
def main(genomes, config):
    global GEN
    GEN += 1

    # inits
    score = 0
    birds = []
    base = base_c.Base(730)
    pipes = [pipe_c.Pipe(600)]
    win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))

    nets = []
    ge = []

    for _, g in genomes:
        net = neat.nn.FeedForwardNetwork.create(g, config)
        nets.append(net)
        birds.append(bird_c.Bird(230, 350))
        g.fitness = 0
        ge.append(g)

    # clock
    clock = pygame.time.Clock()

    # game loop
    run = True
    while run:
        # FPS
        clock.tick(30)

        # quit logic
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()

        pipe_ind = 0
        if len(birds) > 0:
            if len(pipes) > 1 and birds[
                    0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width():
                pipe_ind = 1
        else:
            run = False
            break

        for x, bird in enumerate(birds):
            bird.move()
            ge[x].fitness += 0.1

            output = nets[x].activate(
                (bird.y, abs(bird.y - pipes[pipe_ind].height),
                 abs(bird.y - pipes[pipe_ind].bottom)))

            if output[0] > 0.5:
                bird.jump()

        # pipe logic
        rem = []
        add_pipe = False
        for pipe in pipes:
            for x, bird in enumerate(birds):
                if pipe.collide(bird):
                    ge[x].fitness -= 1
                    birds.pop(x)
                    nets.pop(x)
                    ge.pop(x)

                if not pipe.passed and pipe.x < bird.x:
                    pipe.passed = True
                    add_pipe = True

            if pipe.x + pipe.PIPE_TOP.get_width() < 0:
                rem.append(pipe)

            pipe.move()

        if add_pipe:
            score += 1
            for g in ge:
                g.fitness += 5
            pipes.append(pipe_c.Pipe(600))

        for r in rem:
            pipes.remove(r)

        for x, bird in enumerate(birds):
            if bird.y + bird.img.get_height() >= 730 or bird.y < 0:
                birds.pop(x)
                nets.pop(x)

        # bird move
        # bird.move()

        # base move
        base.move()

        draw_window(win, birds, pipes, base, score, GEN)
Пример #20
0
def main():
    parser = argparse.ArgumentParser(
        description=textwrap.dedent('''\
        Example data reader application

        Continuously reads data in the named pipe that receives the API output
        of the Blockstream Satellite receiver application and waits until a
        complete API data transmission is acquired. Then, by default attempts to
        decrypt the data using the local GnuPG key. On successful decryption,
        validates the integrity of the data and then saves the file in the
        "downloads/" directory. By default, assumes the data was transmitted
        using the example "API data sender" application.

        '''),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('-p',
                        '--pipe',
                        default='/tmp/blocksat/api',
                        help='Pipe on which API data is received ' +
                        '(default: /tmp/blocksat/api)')
    parser.add_argument('-g',
                        '--gnupghome',
                        default=".gnupg",
                        help='GnuPG home directory (default: .gnupg)')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('--save-raw',
                       default=False,
                       action="store_true",
                       help='Save the raw decrypted data in the ' +
                       '\"downloads/\" folder while ignoring the ' +
                       'existence of a user-specific data structure. ' +
                       'Individual API transmissions that can be decrypted '
                       'with the GPG keys you possess ' +
                       'are saved in separate files whose names ' +
                       ' correspond to timestamps. (default: false)')
    group.add_argument(
        '--plaintext',
        default=False,
        action="store_true",
        help='Do not try to decrypt the data. Instead, assume ' +
        'that all API data transmissions are plaintext and ' +
        'save them as individual files named by timestamps ' +
        ' in the  \"downloads/\" folder. ' +
        'NOTE: this saves all transmissions in the ' +
        ' \"downloads/\" folder. (default: false)')
    parser.add_argument('--password',
                        default=False,
                        action="store_true",
                        help='Whether to access GPG keyring with a password ' +
                        '(default: false)')
    parser.add_argument('--debug',
                        action='store_true',
                        help='Debug mode (default: false)')
    args = parser.parse_args()
    pipe_file = args.pipe
    gnupghome = args.gnupghome
    save_raw = args.save_raw
    plaintext = args.plaintext

    # Switch debug level
    if (args.debug):
        logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
        logging.debug('[Debug Mode]')

    # Open pipe
    pipe_f = pipe.Pipe(pipe_file)

    # GPG object
    if (not plaintext):
        gpg = gnupg.GPG(gnupghome=gnupghome)

        # Is there a password for GPG keyring?
        if (args.password):
            gpg_password = getpass.getpass()
        else:
            gpg_password = None

    # Read the chosen named pipe continuously and append read data to a
    # buffer. Once complete data structures are ready, output them accordingly.
    rd_buffer = b''

    print("Waiting for data...\n")
    while True:
        rd_buffer += pipe_f.read(MAX_READ)

        # Try to find the data structure that is output by the Blockstream
        # Satellite receiver:
        data = parse_api_out_data(rd_buffer)

        # When the complete structure is found, remove the corresponding data
        # from the read buffer, try to decrypt it and then parse the decrypted
        # user data structure in order to retrieve the embedded file
        if (len(data) > 0):
            # Pop data from the read buffer
            rd_buffer = rd_buffer[(OUT_DATA_HEADER_LEN + len(data)):]

            # In plaintext mode, every API transmission is assumed to be
            # plaintext and output as a file to the downloads folder with a
            # timestamp as name.
            if (plaintext):
                print(
                    "[%s]: Got %7d bytes\tSaving as plaintext" %
                    (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), len(data)))
                save_file(data)
                logging.debug("Message: %s" % data)
                continue

            # Try to decrypt the data when not in plaintext mode
            decrypted_data = gpg.decrypt(data, passphrase=gpg_password)

            if (decrypted_data.ok):
                # Is the message digitally signed?
                if (decrypted_data.fingerprint is not None):
                    signed_by = decrypted_data.fingerprint

                    # Was the signature verified?
                    if decrypted_data.trust_level is not None:
                        sign_str = "Signed by %s (verified w/ trust level: %s)" % (
                            signed_by, decrypted_data.trust_text)
                    else:
                        sign_str = "Signed by %s (unverified)" % (signed_by)

                    unsign_str = ""
                else:
                    unsign_str = "Not signed"
                    sign_str = ""

                print("[%s]: Got %7d bytes\t Decryption: OK    \t%s" %
                      (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), len(data),
                       unsign_str))
                if (len(sign_str) > 0):
                    print(sign_str)
                print("Decrypted data has %d bytes" %
                      (len(str(decrypted_data))))

                # Parse the user-specific data structure. If ignoring the
                # existence of an application-specific data structure, save the
                # raw decrypted data directly to a file.
                if (save_raw):
                    save_file(str(decrypted_data))
                else:
                    parse_ok = parse_user_data(str(decrypted_data))

                    # Save raw data in case parsing fails
                    if (not parse_ok):
                        save_file(str(decrypted_data))
            else:
                print(
                    "[%s]: Got %7d bytes\t Decryption: FAILED\t" %
                    (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), len(data)) +
                    "Not encrypted for us (%s)" % (decrypted_data.status))
Пример #21
0
# Other Variables for use in the program
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600

# Create a black screen
DISPLAYSURF = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
DISPLAYSURF.fill(BLACK)
pygame.display.set_caption("Game")

# Create player
player = bird.Bird(SCREEN_HEIGHT, DISPLAYSURF, WHITE)

# Create pipe array
pipes = []
pipes.append(pipe.Pipe(SCREEN_HEIGHT, SCREEN_WIDTH, DISPLAYSURF, WHITE))

# Pipe spawner
pipe_delay = 2000  # 2 seconds
new_pipe = pygame.USEREVENT + 1
pygame.time.set_timer(new_pipe, pipe_delay)

# Create brain
brain = brain.Brain()

# Sprite groups
# all_sprites = pygame.sprit

# Game Loop
while True:
    # Refresh background
Пример #22
0
def main():
    clock = pygame.time.Clock()
    framecounter = 0
    run = 1
    state = 0

    f = open("highscore.txt", "r")
    highscore = f.read()
    f.close()
    print(highscore)
    # main loop
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = 0
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    run = 0
                if state == 0:
                    if event.key == pygame.K_SPACE:
                        b = bird.Bird()
                        first_base = base.Base(0, VELOCITY)
                        bases = [first_base]
                        first_pipe = pipe.Pipe(512, VELOCITY)
                        pipes = [first_pipe]
                        score = 0
                        distance = 0
                        flag = 0
                        activate = False
                        state = 1
                elif state == 1:
                    if event.key == pygame.K_SPACE:
                        b.jump()
                    if event.key == pygame.K_d:
                        activate = not activate

        if state == 0:
            SCREEN.blit(BG_IMG, (0, 0))
            f = open("highscore.txt", "r")
            highscore = f.read()
            f.close()
            hs = FONT.render("HIGHSCORE : " + highscore, True, (255, 255, 255))
            SCREEN.blit(hs, (WIDTH // 2 - hs.get_width() // 2,
                             HEIGHT // 2 - hs.get_height() // 2 - 50))
            start = FONT.render('Press JUMP (space) to play (esc to quit)',
                                True, (255, 255, 255))
            if (framecounter // 25) % 2 == 0:
                SCREEN.blit(start, (WIDTH // 2 - start.get_width() // 2,
                                    HEIGHT // 2 - start.get_height() // 2))

        elif state == 1:
            # Pipes and bases spawning
            if pipes[-1].x < THRESHOLDS['pipe']:
                pipes.append(pipe.Pipe(288, VELOCITY))
            elif pipes[0].x + pipes[0].sprite1.get_width() < 0:
                flag = 0
                pipes.pop(0)
            if bases[-1].x < 0:
                bases.append(
                    base.Base(bases[-1].x + bases[-1].sprite.get_width(),
                              VELOCITY))
            elif bases[0].x < THRESHOLDS['base']:
                bases.pop(0)

            # Score/distance count
            if flag == 0:
                if pipes[0].x < 144:
                    score += 1
                    flag = 1
            distance -= VELOCITY / 10

            # Updating and drawing
            SCREEN.blit(BG_IMG, (0, 0))
            b.update()
            b.draw(SCREEN)
            for p in pipes:
                p.update()
                p.draw(SCREEN)
            for bs in bases:
                bs.update()
                bs.draw(SCREEN)
            scr = FONT.render('Score : ' + str(score), True, (255, 255, 255))
            dist = FONT.render('Distance : ' + str(round(distance)), True,
                               (255, 255, 255))
            SCREEN.blit(scr, (0, 0))
            SCREEN.blit(dist, (0, 15))

            # Animation
            if framecounter > 12:
                framecounter = 0
                b.img_count = 0
            if framecounter > 9:
                b.img_count = 1
            elif framecounter > 6:
                b.img_count = 2
            elif framecounter > 3:
                b.img_count = 1

            # Collision detection
            for p in pipes:
                if p.collide(b):
                    if score > int(highscore):
                        f = open("highscore.txt", "w")
                        f.write(str(score))
                        f.close()
                    state = 0
            if b.rect.bottom > 400 or b.y < -50:
                if score > int(highscore):
                    f = open("highscore.txt", "w")
                    f.write(str(score))
                    f.close()
                state = 0

        # Update display
        framecounter += 1
        pygame.display.flip()

        # Clock tick
        clock.tick(FPS)
    pygame.quit()
Пример #23
0
 def create_new_pipe(self):
     """
     Creates new pipe objects
     :return: pipe object
     """
     return pipe.Pipe(self.win, random.randint(150, self.height - 150))
Пример #24
0
        start.Render(window)

        
    if Scene.scene == "game":
        
        
        # fill the BG with the color
        window.fill((r, g, b))
        

        # position of pipe 
        pos1 -= 4

    
        # the 3 pipes
        pipeone=pipe.Pipe(window=window, width=40, height=level,
                  color="green", x_start=pos1, y_start=0)
        pipetwo=pipe.Pipe(window=window, width=40, height=level2,
                  color="green", x_start=pos2, y_start=0)
        pipethree=pipe.Pipe(window=window, width=40, height=level3,
                  color="green", x_start=pos3, y_start=0)
        
        # pipe spawn loop
        if pos1 <= 1:
            pos1 = 800
        if pos1 == 800:
            level = random.randint(50, 450)
        if pos1 <= change:
            pos2 -= 4
            change += 4
        if pos2 <= change2:
            pos3 -= 4
Пример #25
0
def main(genomes, config):
    global WIN, gen
    SCREEN = WIN
    gen += 1

    # start by creating lists holding the genome itself, the
    # neural network associated with the genome and the
    # bird object that uses that network to play
    nets = []
    birds = []
    ge = []
    for genome_id, genome in genomes:
        genome.fitness = 0  # start with fitness level of 0
        net = neat.nn.FeedForwardNetwork.create(genome, config)
        nets.append(net)
        birds.append(bird.Bird())
        ge.append(genome)

    first_base = base.Base(0, VELOCITY)
    bases = [first_base]
    first_pipe = pipe.Pipe(512, VELOCITY)
    pipes = [first_pipe]
    framecounter = 0
    score = 0
    distance = 0
    flag = 0
    activate = False

    clock = pygame.time.Clock()
    run = 1

    # main loop
    while run:

        pipe_ind = 0
        if len(birds) > 0:
            if len(pipes
                   ) > 1 and 144 > pipes[0].x + pipes[0].sprite1.get_width():
                pipe_ind = 1
        else:
            run = 0
            break

        for x, b in enumerate(
                birds
        ):  # give each bird a fitness of 0.1 for each frame it stays alive
            ge[x].fitness += 0.1
            output = nets[birds.index(b)].activate(
                (b.y, abs(b.y - pipes[pipe_ind].y),
                 abs(b.y - pipes[pipe_ind].bottom)))

            if output[0] > 0.5:
                b.jump()

        # Pipes and bases spawning
        if pipes[-1].x < THRESHOLDS['pipe']:
            pipes.append(pipe.Pipe(288, VELOCITY))
        elif pipes[0].x + pipes[0].sprite1.get_width() < 0:
            flag = 0
            pipes.pop(0)
        if bases[-1].x < 0:
            bases.append(
                base.Base(bases[-1].x + bases[-1].sprite.get_width(),
                          VELOCITY))
        elif bases[0].x < THRESHOLDS['base']:
            bases.pop(0)

        # Score/distance count
        if flag == 0:
            if pipes[0].x < 144:
                for genome in ge:
                    genome.fitness += 5
                score += 1
                flag = 1
        distance -= VELOCITY / 10

        # Updating and drawing
        SCREEN.blit(BG_IMG, (0, 0))
        for b in birds:
            b.update()
            b.draw(SCREEN)
        for p in pipes:
            p.update()
            p.draw(SCREEN)
        for bs in bases:
            bs.update()
            bs.draw(SCREEN)
        scr = FONT.render('Score : ' + str(score), True, (0, 0, 0))
        dist = FONT.render('Distance : ' + str(round(distance)), True,
                           (0, 0, 0))
        SCREEN.blit(scr, (0, 0))
        SCREEN.blit(dist, (0, 15))

        # Animation
        for b in birds:
            if framecounter > 12:
                framecounter = 0
                b.img_count = 0
            if framecounter > 9:
                b.img_count = 1
            elif framecounter > 6:
                b.img_count = 2
            elif framecounter > 3:
                b.img_count = 1
            framecounter += 1

        # Update display
        pygame.display.flip()

        # controls
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = 0
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_d:
                    activate = not activate
                if event.key == pygame.K_ESCAPE:
                    run = 0
                    pygame.quit()

        # Collision detection
        for p in pipes:
            for b in birds:
                if p.collide(b):
                    ge[birds.index(b)].fitness -= 1
                    nets.pop(birds.index(b))
                    ge.pop(birds.index(b))
                    birds.pop(birds.index(b))
        for b in birds:
            if b.rect.bottom > 400 or b.y < -50:
                ge[birds.index(b)].fitness -= 1
                nets.pop(birds.index(b))
                ge.pop(birds.index(b))
                birds.pop(birds.index(b))

        # Clock tick
        clock.tick(FPS)
Пример #26
0
 def __init__(self, ip='localhost', port=38051):
     self.pipe = pipe.Pipe(ip=ip, at=port)
     self.pipe.open(blocking=False)
Пример #27
0
"""
hierarchy: 
    object
        module
            enter_module
            heat_module
            vent_module
            hot_water_module
            YYTE
        pipe
        equipment
            valve      
            pump        
            exchanger  

"""

import module
import pipe
import valve

heat_module_1 = module.Heat_module("heat_module_1", 1000, 130, 70, 95, 70)
pipe_heat_T12 = pipe.Pipe("pipe_heat_T12 ")

print(heat_module_1.consumption_main)
print(heat_module_1.consumption_out)

print(pipe_heat_T12.pipe_dn(40))
Пример #28
0
                #         frame_skip -= 10
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        show_best = not show_best

            # Frame skipper set
            pressed_keys = pygame.key.get_pressed()
            if pressed_keys[K_UP] and frame_skip < 100:
                frame_skip += 1
            if pressed_keys[K_DOWN] and frame_skip > 1:
                frame_skip -= 1

            # Pipe spawner
            if frame_no % spawn_rate == 0:
                pipes.append(
                    pipe.Pipe(SCREEN_HEIGHT, SCREEN_WIDTH, DISPLAYSURF, WHITE))
            # Frame counter
            frame_no += 1

            # Get closest pipe
            if len(bots) > 0:
                closest_pipe = bots[0].get_closest_pipe(pipes)
                # closest_pipe.colour = GREEN

            for p in pipes:
                p.update()

                # Check if pipe hits bird
                for bot in bots:
                    if p.top_rect.colliderect(
                            bot.bird_rect) or p.bottom_rect.colliderect(
Пример #29
0
import pygame
import bird, pipe, ga

screen = pygame.display.set_mode((600, 600))
screen.fill((0, 0, 0))

POPULATION = 150
birds = []
saved_birds = []
for i in range(POPULATION):
    birds.append(bird.Bird(screen))

pipes = []
pipes.append(pipe.Pipe(screen))

# initiate fonts for displaying scores
current_score = 0
max_score = 0
pygame.font.init()
myfont = pygame.font.SysFont('calibri', 20)
score_surface = myfont.render(f'Score: {current_score}', False,
                              (255, 255, 255))
max_score_surface = myfont.render(f'Max Score: {max_score}', False,
                                  (255, 255, 255))

# create buttons
plus_button = pygame.image.load('plus.png').convert_alpha()
minus_button = pygame.image.load('minus.png').convert_alpha()
plus_b = screen.blit(plus_button, (screen.get_width() - 140, 20))
minus_b = screen.blit(minus_button, (screen.get_width() - 140, 40))
Пример #30
0
    def createPipes(self, group, convertToSolid):
        # Calculate pipe lengths.
        x_pipe_l = self.LX - 2 * self.G
        y_pipe_l = self.LY - 2 * self.G
        z_pipe_l = self.LZ - 2 * self.G
        # First 3 pipes around the (0,0,0) origin in X,Y,Z direction
        pipe = pipemod.Pipe(self.document)
        pipe.OD = self.POD
        pipe.Thk = self.Thk
        pipe.H = z_pipe_l
        zpipe = pipe.create(convertToSolid)
        group.addObject(zpipe)
        zpipe.Placement.Base = FreeCAD.Vector(0, 0, self.G)
        zpipe.Label = "z-" + zpipe.Label
        pipe.H = x_pipe_l
        xpipe = pipe.create(convertToSolid)
        group.addObject(xpipe)
        xpipe.Placement = FreeCAD.Placement(
            FreeCAD.Vector(self.G, 0, 0),
            FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), 90),
            FreeCAD.Vector(0, 0, 0))
        xpipe.Label = "x-" + xpipe.Label
        pipe.H = y_pipe_l
        ypipe = pipe.create(convertToSolid)
        group.addObject(ypipe)
        ypipe.Placement = FreeCAD.Placement(
            FreeCAD.Vector(0, self.G, 0),
            FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0), -90),
            FreeCAD.Vector(0, 0, 0))
        ypipe.Label = "y-" + ypipe.Label

        # Add 3 clones for each x,y,z-type of axis. Place them on the edges of the cube.
        # First add z-pipes (because it simple, and does not require rotation).
        tmp = Draft.clone(zpipe, FreeCAD.Vector(self.LX, 0, self.G))
        group.addObject(tmp)
        tmp = Draft.clone(zpipe, FreeCAD.Vector(0, self.LY, self.G))
        group.addObject(tmp)
        tmp = Draft.clone(zpipe, FreeCAD.Vector(self.LX, self.LY, self.G))
        group.addObject(tmp)
        # Then add x pipes.
        tmp = Draft.clone(xpipe)
        group.addObject(tmp)
        tmp.Placement = FreeCAD.Placement(
            FreeCAD.Vector(self.G, self.LY, 0),
            FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), 90),
            FreeCAD.Vector(0, 0, 0))
        tmp = Draft.clone(xpipe)
        group.addObject(tmp)
        tmp.Placement = FreeCAD.Placement(
            FreeCAD.Vector(self.G, 0, self.LZ),
            FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), 90),
            FreeCAD.Vector(0, 0, 0))
        tmp = Draft.clone(xpipe)
        group.addObject(tmp)
        tmp.Placement = FreeCAD.Placement(
            FreeCAD.Vector(self.G, self.LY, self.LZ),
            FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), 90),
            FreeCAD.Vector(0, 0, 0))
        # Finally add y pipes.
        tmp = Draft.clone(ypipe)
        group.addObject(tmp)
        tmp.Placement = FreeCAD.Placement(
            FreeCAD.Vector(self.LX, self.G, 0),
            FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0), -90),
            FreeCAD.Vector(0, 0, 0))
        tmp = Draft.clone(ypipe)
        group.addObject(tmp)
        tmp.Placement = FreeCAD.Placement(
            FreeCAD.Vector(0, self.G, self.LZ),
            FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0), -90),
            FreeCAD.Vector(0, 0, 0))
        tmp = Draft.clone(ypipe)
        group.addObject(tmp)
        tmp.Placement = FreeCAD.Placement(
            FreeCAD.Vector(self.LX, self.G, self.LZ),
            FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0), -90),
            FreeCAD.Vector(0, 0, 0))