コード例 #1
0
ファイル: game.py プロジェクト: MatWich/FlappyBird
class Game:
    def __init__(self):
        self.screen = pygame.display.set_mode(SCREEN_SIZE)
        pygame.display.set_caption(TITLE)
        self.clock = pygame.time.Clock()
        self.run = True

    # method to call
    def mainLoop(self):
        self.setUp()
        while self.run:
            self.clock.tick(FPS)
            self.events()
            pygame.display.update()

    # setting up all game objects
    def setUp(self):
        self.score = 0
        self.base = Base(BASE_Y)
        self.bird = Bird(int(WIDTH / 2), int(HEIGHT / 2))

    # function contains eg. collision detection
    def events(self):
        self.update()
        self.controls()
        self.movements()

    # this method will handle all obj movements
    def movements(self):
        # Base
        self.base.move()

    """Drawings"""

    def update(self):
        self.drawBg()
        self.drawBase()
        self.drawBird()

    def drawBird(self):
        self.bird.draw(self.screen)

    def drawBg(self):
        self.screen.blit(BG_IMGS[0], (0, 0))

    def drawBase(self):
        self.base.draw(self.screen)

    # key controls
    def controls(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.run = False
コード例 #2
0
def power_optimization(width, height, base, receiver, MURS, COINS,
                       COINS_DIFFRACTION):
    #Cette fonction renvoie la position preferable de l'antenne pour avoir une bonne connexion
    # en plusieurs endroits (receveir = list)
    # et donne, pour la situation preferable, la cartographie complete de l'etage, pour chaque metre carre
    #en termes de puissance recue (en dBm)
    #le resultat est stocke dans la matrice 'powers_dbm'

    print("\nOptimisation de la position de la base pour " +
          str(int(len(receiver))) + " recepteurs")

    pos_base_x = 0
    pos_base_y = 0
    receiver_average = 1
    i = 0
    for i in range(0, int(width)):
        for j in range(0, int(height)):
            base.set_x(i + 0.5)
            base.set_y(j + 0.5)

            n = 1
            for elem in receiver:
                if (base.x == elem.x or base.y == elem.y):
                    n = 0
                    break

            power = 0
            for elem in receiver:
                if (n == 1):
                    data = find_all_rays(base.x, base.y, elem.x, elem.y, MURS,
                                         COINS, COINS_DIFFRACTION)
                    RAYS_DIRECT, RAYS_REFLEXION, RAYS_DIFFRACTION = data[
                        0], data[1], data[2]
                    calculate_all_coefficients(RAYS_DIRECT, RAYS_REFLEXION,
                                               RAYS_DIFFRACTION)
                    power += 10 * log10((calculate_total_power(
                        base, elem, RAYS_DIRECT, RAYS_REFLEXION,
                        RAYS_DIFFRACTION)) * 1000)
            if i == 0 and j == 0:
                receiver_average = power
                pos_base_x = base.x
                pos_base_y = base.y
            elif (receiver_average < power):
                receiver_average = power
                pos_base_x = base.x
                pos_base_y = base.y
            print_progress(i * height + j, width * height)

    receiver_average = receiver_average / len(receiver)
    print('\n\nPuissance en moyenne geometrique :', receiver_average, 'dBm')
    print("Position optimale :", pos_base_x, pos_base_y)
    base = Base(pos_base_x, pos_base_y)
    power_cartography(width, height, base, MURS, COINS, COINS_DIFFRACTION,
                      receiver)
コード例 #3
0
def main(genomes, config):
    global GEN
    BASE_POINT = 700
    GEN += 1

    nets = []
    gens = []
    birds = []

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

    base = Base(BASE_POINT)
    pipes = [Pipe(600)]
    clock = pygame.time.Clock()
    score = 0

    run = True
    while run:
        clock.tick(30)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()

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

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

            output = nets[birds.index(bird)].activate(
                (bird.y, abs(bird.y - pipes[pipe_idx].height),
                 abs(bird.y - pipes[pipe_idx].bottom)))

            if output[
                    0] > 0.5:  # use a tanh activation function so result will be between -1 and 1. if over 0.5 jump
                bird.jump()

        remove = []
        add_pipe = False
        for pipe in pipes:
            for i, bird in enumerate(birds):
                if pipe.collide(bird):
                    gens[i].fitness -= 1
                    birds.pop(i)
                    nets.pop(i)
                    gens.pop(i)

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

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

            pipe.move()

        if add_pipe:
            score += 1

            for g in gens:
                g.fitness += 5

            pipes.append(Pipe(600))

        for pipe in remove:
            pipes.remove(pipe)

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

        base.move()
        draw_window(win, birds, pipes, base, score, GEN)
コード例 #4
0
def base(request):
    race = request.param
    base = Base(startingworkers, race, "normal", "normal", 2, False, True)
    return base
コード例 #5
0
ファイル: game.py プロジェクト: MatWich/FlappyBird
 def setUp(self):
     self.score = 0
     self.base = Base(BASE_Y)
     self.bird = Bird(int(WIDTH / 2), int(HEIGHT / 2))
コード例 #6
0
ファイル: run.py プロジェクト: kelly-cs/fusion-core
            run_simulation(output, gamestate_copy, target)


# ============================================================== #
#  SECTION: Main                                                 #
# ============================================================== #
if __name__ == "__main__":
    goal_units = ["zergling", "zergling", "zergling", "zergling"]

    max_ticks = 16
    output = []
    player = Player(
        Race.ZERG,
        minerals=50,
        gas=0,
        goal_units=goal_units,
        current_units=[],
        buildings=[],
        bases=[Base(12, Race.ZERG, "normal", "normal", 2, False, True)],
        build_order=[],
        supply=3,
        required_tech=get_all_required_tech(goal_units) + goal_units,
        remaining_ticks=max_ticks)
    gamestate = GameState(remaining_ticks=max_ticks, player=player)
    # store results in output
    simulation = run_simulation(output, gamestate, None)
    # print(simulation)
    # print(output)
    # print(len(output))
    LOG.info(json.dumps(output))
コード例 #7
0
def main(genomes, config):
    nets = []
    ge = []
    birds = []
    global GEN
    GEN += 1

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

    base = Base(730)
    pipes = [Pipe(600)]
    win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
    score = 0
    #clock = pygame.time.Clock()

    run = True
    while run:
        #time.sleep(0.2)
        #clock.tick(3000) #pour donner un tempo au jeu quelque soit l'OS mais ne marche pas
        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(
                )  # we use a tanh activation function so result will be between -1 and 1. if over 0.5 jump

        add_pipe = False
        rem = []
        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(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)
                ge.pop(x)

        base.move()
        draw_window(win, birds, pipes, base, score, GEN)
コード例 #8
0
def main():  #
    ### Here goes the action you want to do ########
    base = Base(samples, get_entries, solution)  #
コード例 #9
0
ファイル: IO.py プロジェクト: bjoukovs/PHYSRayTracing2017
def decode_plan(filename):

    #Cette fonction permet de lire le plan et de renvoyer la liste de murs et de coins correspondants
    #ainsi que l'emetteur par defaut et les recepteurs definis

    print("Decodage du plan en cours...", end='')

    input = open(filename, 'r')
    lines = input.readlines()
    input.close()

    murs = []
    tempcoins = {}
    coins = []
    receivers = []

    for line in lines:
        content = line.split(" ")

        #Les premieres lignes (dimensions, base, recepteurs)

        keyword = content[0]
        if keyword == "DIMENSIONS":
            width = float(content[1])
            height = float(content[2])
        elif keyword == "BASE":
            base = Base(float(content[1]), float(content[2]))
        elif keyword == "RECEIVER":
            receivers.append(Receiver(float(content[1]), float(content[2])))

        #Les murs et les coins
        elif keyword == "W":
            x1, y1, x2, y2 = float(content[3]), float(content[4]), float(
                content[5]), float(content[6])
            coin1 = tempcoins.get(
                (x1, y1), None
            )  #Ces etapes permettent de ne pas generer de coins doubles
            coin2 = tempcoins.get((x2, y2), None)
            if (coin1 == None):
                coin1 = Coin(x1, y1)
                tempcoins[(x1, y1)] = coin1
                coins.append(coin1)
            if (coin2 == None):
                coin2 = Coin(x2, y2)
                tempcoins[(x2, y2)] = coin2
                coins.append(coin2)

            eps = EPS_1
            sig = SIG_1
            materiau = content[1]
            if materiau == "2":
                eps = EPS_2
                sig = SIG_2
            elif materiau == "3":
                eps = EPS_3
                sig = SIG_3

            m = Mur(float(content[2]), coin1, coin2, eps, sig)
            coin1.add_mur(m)
            coin2.add_mur(m)
            murs.append(m)

    #Coins eligibles pour la diffraction (coins uniquement associes a un mur ou a deux murs perpendiculaires)
    coins_diffraction = []
    for coin in coins:
        walls = coin.murs_associes
        if (len(walls) == 1):
            coins_diffraction.append(coin)
        elif (len(walls) == 2):
            mur1, mur2 = walls[0], walls[1]
            if (mur1.is_horizontal() and not mur2.is_horizontal()) or (
                    mur2.is_horizontal() and not mur1.is_horizontal()):
                coins_diffraction.append(coin)

    print("OK")

    return [width, height, base, receivers, murs, coins, coins_diffraction]
コード例 #10
0
ファイル: test_geysers.py プロジェクト: kelly-cs/fusion-core
def base(request):
    race = request.param
    base = Base(startingworkers, race, mineral_type, gas_type, amt_geysers,
                under_construction, first_base)
    return base