Example #1
0
 def __init__(self,
              surface,
              clock,
              screen_w,
              screen_h,
              background_color=(0, 0, 0)):
     self.surface = surface
     self.clock = clock
     self.screen_w = screen_w
     self.screen_h = screen_h
     self.level = 0
     self.state = Game.STATE_ONGOING
     self.terrain = Terrain(screen_w, screen_h)
     self.lander = Lander(self)
     self.sound_fx = SoundFX()
     self.ended = False
     self.crash_animation = None
Example #2
0
    def reproduction(self):

        # elitism selection
        elitism_pool = []
        for i in range(int(0.2 * self.population_size)):
            elitism_pool.append(copy(self.population[i]))
        self.population.clear()
        self.population.extend(copy(elitism_pool))
        while len(self.population) < self.population_size:
            # Spin the wheel of fortune to pick two parents

            m = np.random.randint(len(self.mating_pool))
            d = np.random.randint(len(self.mating_pool))
            # Pick two parents
            mom = self.mating_pool[m]
            dad = self.mating_pool[d]
            # Get their genes
            mom_genes = mom.get_chromosome()
            dad_genes = dad.get_chromosome()
            # Mate their genes
            # Cross over rate = 1
            child0, child1 = mom_genes.cross_over(dad_genes)
            child0.mutate(self.mutation_rate)
            child1.mutate(self.mutation_rate)

            # Fill the new population with the new child
            self.population.append(
                Lander(chromosome=child0,
                       init_state=Population.INIT_STATE,
                       ground=self.ground_points,
                       max_lifecycle=Population.MAX_LIFECYCLE))
            self.population.append(
                Lander(chromosome=child1,
                       init_state=Population.INIT_STATE,
                       ground=self.ground_points,
                       max_lifecycle=Population.MAX_LIFECYCLE))
        # Increase the generation count
        self.simulate()
        self.generation_count += 1
Example #3
0
    def on_init(self):

        pygame.init()
        self.screen = pygame.display.set_mode(
            self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)
        self._running = True
        pygame.display.set_caption("py-lander")

        # Start sounds
        pygame.mixer.init()
        self.engine_sound = pygame.mixer.Sound("./sounds/engine.wav")
        self.landing_sound = pygame.mixer.Sound("./sounds/landing.wav")
        self.rekt_sound = pygame.mixer.Sound("./sounds/rekt.wav")
        self.played_landing_sound = False
        self.played_rekt_sound = False

        self.font = pygame.font.SysFont("monospace", 18)

        # Create our Lander
        self.lander = Lander()

        # Score multiplier
        self.score_multiplier = 1.0
        self.can_multiply = True

        # Basic settings
        self.gravity = 0.01
        self.ground_height = 30

        # Controls
        self.holding_left = False
        self.holding_right = False
        self.holding_up = False

        # Space
        self.space = []
        for i in range(0, 500):
            self.space.append((randint(0, self.width), randint(0,
                                                               self.height)))
Example #4
0
 def __init__(self, neural_net=None):
     self.lander = Lander()
     self.lives = 2
     self.allsprites = pygame.sprite.Group()
     self.allsprites.add(self.lander)
     self.maxipads = pygame.sprite.Group()
     self.obstacles = pygame.sprite.Group()
     # for i in range(5):
     #    newobj = Obstacle()
     #    while pygame.sprite.spritecollideany(newobj, self.obstacles) is not None or pygame.sprite.spritecollideany(newobj, self.maxipads) is not None:
     #        newobj = Obstacle()
     #    self.obstacles.add(newobj)
     #    self.allsprites.add(newobj)
     for i in range(3):
         newpad = Pad(low=True)
         while pygame.sprite.spritecollideany(
                 newpad, self.maxipads
         ) is not None or pygame.sprite.spritecollideany(
                 newpad, self.obstacles) is not None:
             newpad = Pad(low=True)
         self.maxipads.add(newpad)
         self.allsprites.add(newpad)
     self.score = 0
     self.gameover = False
     self.starttime = datetime.now()
     self.thrust_img = pygame.image.load("resources/thrust.png")
     self.thrust_img_rect = self.thrust_img.get_rect()
     self.control_blocked = [False, False, False]
     self.control_blocked_start = datetime.now()
     self.meteors = pygame.sprite.Group()
     self.neural_network = neural_net
     self.drawing = False
     self.slow_down_learned = False
     self.straight_angle_learned = False
     self.gain_xvel_learned = False
     self.point_against_xvel_learned = False
     self.xvel_slowdown_learned = False
     self.cancel_xvel_learned = False
Example #5
0
    def __init__(self, mutation_rate, pop_size, init_state, ground_points,
                 max_lifecycle):
        self.mutation_rate = mutation_rate
        self.population = []
        self.mating_pool = []
        self.population_size = pop_size
        self.generation_count = 1
        self.batch_simulations = []
        self.all_simulations = []
        Population.MAX_LIFECYCLE = max_lifecycle
        Population.CHROMOSOME_SIZE = max_lifecycle
        Population.INIT_STATE = init_state
        self.ground_points = ground_points

        # create and run the landers
        for _ in range(self.population_size):
            new_lander = Lander(chromosome=Chromosome(
                Population.CHROMOSOME_SIZE),
                                init_state=Population.INIT_STATE,
                                ground=self.ground_points,
                                max_lifecycle=Population.MAX_LIFECYCLE)
            self.population.append(new_lander)
        self.simulate()
    def simulate(self, init_position, fuel, ground_points):
        """From each chromosome in population we create object
        of Lander class and compute trajectory
        """
        x, y = init_position[0], init_position[1]
        lander_init_state = State(fuel, 0, 0,
                                  Particle(Point(x, y), Speed(Vector(0, 0))))
        ground_line = ground_inputs_to_line(ground_points)
        self.ground_points = ground_line
        self.simulations = []
        for member in self.population:
            commands = []
            previous_gene = CMD_TUPLE(0, 0)
            for gene in member.genes:
                angle = previous_gene.angle + coerce_range(
                    gene.angle - previous_gene.angle, -15, 15)
                power = previous_gene.power + coerce_range(
                    gene.power - previous_gene.power, -15, 15)
                commands.append(ControlCommands(angle, power))
                previous_gene = gene

            new_lander = Lander(lander_init_state, commands, ground_line)
            self.simulations.append(new_lander)
        self.all_simulations.append(deepcopy(self.simulations))
Example #7
0
class App:
    def __init__(self):

        self._running = True
        self.screen = None
        self.size = self.width, self.height = 600, 300
        self.clock = pygame.time.Clock()

    #
    # Game setup
    #
    def on_init(self):

        pygame.init()
        self.screen = pygame.display.set_mode(
            self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)
        self._running = True
        pygame.display.set_caption("py-lander")

        # Start sounds
        pygame.mixer.init()
        self.engine_sound = pygame.mixer.Sound("./sounds/engine.wav")
        self.landing_sound = pygame.mixer.Sound("./sounds/landing.wav")
        self.rekt_sound = pygame.mixer.Sound("./sounds/rekt.wav")
        self.played_landing_sound = False
        self.played_rekt_sound = False

        self.font = pygame.font.SysFont("monospace", 18)

        # Create our Lander
        self.lander = Lander()

        # Score multiplier
        self.score_multiplier = 1.0
        self.can_multiply = True

        # Basic settings
        self.gravity = 0.01
        self.ground_height = 30

        # Controls
        self.holding_left = False
        self.holding_right = False
        self.holding_up = False

        # Space
        self.space = []
        for i in range(0, 500):
            self.space.append((randint(0, self.width), randint(0,
                                                               self.height)))

    #
    # Process input
    #
    def on_event(self, event):

        # Key Down
        if event.type == pygame.KEYDOWN:

            self.can_multiply = False

            if not self.lander.is_rekt and not self.lander.is_landed:
                if event.key == pygame.K_LEFT:
                    self.engine_sound.play(loops=1)
                    self.holding_left = True
                elif event.key == pygame.K_RIGHT:
                    self.engine_sound.play(loops=1)
                    self.holding_right = True
                elif event.key == pygame.K_UP:
                    self.engine_sound.play(loops=1)
                    self.holding_up = True

            if event.key == pygame.K_r:
                self.on_init()

        # Key Up
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                self.holding_left = False
            elif event.key == pygame.K_RIGHT:
                self.holding_right = False
            elif event.key == pygame.K_UP:
                self.holding_up = False
        elif event.type == pygame.QUIT:
            self._running = False

    #
    # Main game logic
    #
    def on_loop(self):

        self.clock.tick(60)

        # Score multiplier
        if self.can_multiply:
            self.score_multiplier = self.score_multiplier + 0.01

        # Ship logic (including controls and movement)
        if not self.lander.is_rekt and not self.lander.is_landed:
            self.lander.on_loop(self.gravity, self.holding_right,
                                self.holding_left, self.holding_up)

        # Check ground collision
        if not (self.lander.is_rekt or self.lander.is_landed
                ) and self.lander.y >= self.height - self.ground_height:

            # Check if rekt
            if self.lander.speed_y >= 1.0 or self.lander.speed_x >= 1.0:

                self.lander.is_rekt = True
                self.lander.current_color = self.lander.rekt_color
                self.rekt_sound.play()

            else:

                self.lander.is_landed = True

                if not self.played_landing_sound:
                    self.engine_sound.stop()
                    self.landing_sound.play()
                    self.played_landing_sound = True

            # Stop
            self.lander.speed_x = 0
            self.lander.speed_y = 0

    #
    # Render
    #
    def on_render(self):

        # Clear screen
        self.screen.fill((0, 0, 0))

        # Draw the score multiplier
        multiplier_text = self.font.render(
            "Score x" + str(self.score_multiplier), 1, (255, 255, 255))
        self.screen.blit(multiplier_text, (20, 40))

        # Draw space
        for star in self.space:
            self.screen.set_at((star[0], star[1]), (255, 255, 255))

        # Draw lander
        self.lander.on_render(self.screen)

        # Draw ground
        pygame.draw.rect(
            self.screen, (255, 255, 255),
            (0, self.height - self.ground_height, self.width, self.height))

        # Show rekt message
        if self.lander.is_rekt:

            text = self.font.render("Rekt! Press R to try again", 1,
                                    (255, 255, 255))
            text_rect = text.get_rect()
            text_rect.centerx = self.width / 2
            text_rect.centery = 80
            self.screen.blit(text, text_rect)

        elif self.lander.is_landed:

            text = self.font.render("A perfect landing!", 1, (255, 255, 255))
            text_rect = text.get_rect()
            text_rect.centerx = self.width / 2
            text_rect.centery = 80
            self.screen.blit(text, text_rect)

            fuel_score = int(self.lander.fuel * 10)
            total_score = int(fuel_score * self.score_multiplier) * 10

            text = self.font.render(
                str(fuel_score) + " fuel x " + str(self.score_multiplier), 1,
                (255, 255, 255))
            text_rect = text.get_rect()
            text_rect.centerx = self.width / 2
            text_rect.centery = 120
            self.screen.blit(text, text_rect)

            text = self.font.render("Score: " + str(total_score), 1,
                                    (255, 255, 255))
            text_rect = text.get_rect()
            text_rect.centerx = self.width / 2
            text_rect.centery = 140
            self.screen.blit(text, text_rect)

        # Draw the fuel bar
        pygame.draw.rect(self.screen, (255, 255, 255),
                         (20, 20,
                          ((self.width - 40) * (self.lander.fuel / 25.0)), 20),
                         0)

        pygame.display.update()

    #
    # Ends the game
    #
    def on_cleanup(self):
        pygame.quit()

    #
    # Starts the game
    #
    def on_execute(self):
        if self.on_init() == False:
            self._running = False

        while (self._running):
            for event in pygame.event.get():
                self.on_event(event)
            self.on_loop()
            self.on_render()
        self.on_cleanup()
Example #8
0
class Game:
    def __init__(self, neural_net=None):
        self.lander = Lander()
        self.lives = 2
        self.allsprites = pygame.sprite.Group()
        self.allsprites.add(self.lander)
        self.maxipads = pygame.sprite.Group()
        self.obstacles = pygame.sprite.Group()
        # for i in range(5):
        #    newobj = Obstacle()
        #    while pygame.sprite.spritecollideany(newobj, self.obstacles) is not None or pygame.sprite.spritecollideany(newobj, self.maxipads) is not None:
        #        newobj = Obstacle()
        #    self.obstacles.add(newobj)
        #    self.allsprites.add(newobj)
        for i in range(3):
            newpad = Pad(low=True)
            while pygame.sprite.spritecollideany(
                    newpad, self.maxipads
            ) is not None or pygame.sprite.spritecollideany(
                    newpad, self.obstacles) is not None:
                newpad = Pad(low=True)
            self.maxipads.add(newpad)
            self.allsprites.add(newpad)
        self.score = 0
        self.gameover = False
        self.starttime = datetime.now()
        self.thrust_img = pygame.image.load("resources/thrust.png")
        self.thrust_img_rect = self.thrust_img.get_rect()
        self.control_blocked = [False, False, False]
        self.control_blocked_start = datetime.now()
        self.meteors = pygame.sprite.Group()
        self.neural_network = neural_net
        self.drawing = False
        self.slow_down_learned = False
        self.straight_angle_learned = False
        self.gain_xvel_learned = False
        self.point_against_xvel_learned = False
        self.xvel_slowdown_learned = False
        self.cancel_xvel_learned = False

    def show_telemetry(self, screen):
        elapsed_time = (datetime.now() - self.starttime).total_seconds()
        if self.drawing:
            display_text(screen, str(self.lander.fuel) + "kg", 110, 45)
            display_text(screen,
                         str(round(self.lander.x_vel * 100) / 100) + "ms", 305,
                         45)
            display_text(screen,
                         str(round(self.lander.y_vel * 100) / 100) + "ms", 305,
                         66)
            display_text(screen,
                         str(round(1000 / 750 * (750 - self.lander.y))) + "m",
                         305, 22)
            display_text(screen,
                         str(round(self.lander.damage * 100)) + "%", 110, 66)
            s_passed = int(elapsed_time % 60)
            m_passed = int(elapsed_time // 60)
            display_text(screen,
                         str(m_passed) + ":" + str(f"{s_passed:02d}"), 110, 22)
            display_text(screen, str(f"{self.score:03d}"), 110, 95)

    def create_failure(self):
        if any(self.control_blocked) and (
                datetime.now() -
                self.control_blocked_start).total_seconds() >= 2:
            self.control_blocked = [False, False, False]
        elif not any(self.control_blocked) and random() < 0.002:
            self.control_blocked[randint(0, 2)] = True
            self.control_blocked_start = datetime.now()

    def wait_key(self):
        keypressed = True
        while not keypressed:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit(0)
                if event.type == pygame.KEYDOWN:
                    keypressed = True

    def create_storm(self):
        if len(self.meteors) == 0 and random() < 0.001:
            for i in range(randint(5, 10)):
                new_meteor = Meteor(randint(3, 5), randint(2, 3))
                while pygame.sprite.spritecollideany(new_meteor,
                                                     self.meteors) is not None:
                    new_meteor = Meteor(randint(3, 5), randint(2, 3))
                self.meteors.add(new_meteor)
                self.allsprites.add(new_meteor)
        else:
            collided_meteor = pygame.sprite.spritecollideany(
                self.lander, self.meteors)
            if collided_meteor is not None:
                self.lander.damage += 0.25
                self.meteors.remove(collided_meteor)
            for meteor in self.meteors:
                if meteor.y >= HEIGHT:
                    self.meteors.remove(meteor)
                    self.allsprites.remove(meteor)

    def play(self):
        thrusting = False
        thrust_counter = 0
        if not self.gameover:
            # self.create_failure()
            # self.create_storm()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit("0")
                if event.type == pygame.KEYDOWN and self.lander.damage < 1 and self.neural_network is None:
                    if event.key == pygame.K_SPACE and not self.control_blocked[
                            1]:
                        self.lander.thrust()
                        if self.lander.fuel >= 5:
                            thrusting = True
                            thrust_counter = 5
                    if event.key == pygame.K_RIGHT and not self.control_blocked[
                            2]:
                        self.lander.rotate(-5)
                    if event.key == pygame.K_LEFT and not self.control_blocked[
                            0]:
                        self.lander.rotate(5)

            if self.neural_network is not None:

                controls = self.neural_network.get_outputs()

                if controls[0] >= 0.6 or controls[2] >= 0.6:
                    if controls[0] > controls[2]:
                        self.lander.rotate(5)  # left
                    elif controls[2] > controls[0]:
                        self.lander.rotate(-5)  # right
                if controls[1] >= 0.5:
                    self.lander.thrust()
                    if self.lander.fuel >= 5:
                        thrusting = True
                        thrust_counter = 5

            self.allsprites.update()
            collidedobj = pygame.sprite.spritecollideany(
                self.lander, self.obstacles)
            if collidedobj is not None:
                self.lander.damage += 0.1
                old_distance = sqrt(
                    (self.lander.x - collidedobj.rect.centerx)**2 +
                    (self.lander.y - collidedobj.rect.centery)**2)
                self.lander.x = collidedobj.rect.centerx + (
                    (self.lander.x - collidedobj.rect.centerx) /
                    old_distance) * (old_distance + 5)
                self.lander.y = collidedobj.rect.centery + (
                    (self.lander.y - collidedobj.rect.centery) /
                    old_distance) * (old_distance + 5)

            collidedpad = pygame.sprite.spritecollideany(
                self.lander, self.maxipads)
            if collidedpad is not None:
                self.neural_network.fitness_boosts.append(40)
                if self.lander.pad_collide(collidedpad):
                    self.score += 50
                    display_text(screen, "Landed!", 600, 375)
                    # print("landed")
                    # pygame.display.flip()
                    # sleep(0.5)
                    # self.wait_key()

                    for landing_pad in self.maxipads:
                        # remove all landing pads
                        self.allsprites.remove(landing_pad)
                        self.maxipads.remove(landing_pad)

                    for i in range(3):
                        newpad = Pad(low=True)
                        while pygame.sprite.spritecollideany(
                                newpad, self.maxipads
                        ) is not None or pygame.sprite.spritecollideany(
                                newpad, self.obstacles) is not None:
                            newpad = Pad(low=True)
                        self.maxipads.add(newpad)
                        self.allsprites.add(newpad)

                    self.lander.reset()
                    self.starttime = datetime.now()

            if self.lander.dead:
                if self.lives > 0:
                    self.lives -= 1
                    self.allsprites.remove(self.lander)
                    self.lander = Lander()
                    self.allsprites.add(self.lander)
                    display_text(screen, "You crashed!", 600, 375)
                    #pygame.display.flip()
                    #sleep(0.5)
                    #self.wait_key()

                    for landing_pad in self.maxipads:
                        # remove all landing pads
                        self.allsprites.remove(landing_pad)
                        self.maxipads.remove(landing_pad)

                    for i in range(3):
                        newpad = Pad(low=True)
                        while pygame.sprite.spritecollideany(
                                newpad, self.maxipads
                        ) is not None or pygame.sprite.spritecollideany(
                                newpad, self.obstacles) is not None:
                            newpad = Pad(low=True)
                        self.maxipads.add(newpad)
                        self.allsprites.add(newpad)

                    self.starttime = datetime.now()
                else:
                    display_text(screen, "Game over!", 600, 375)
                    #pygame.display.flip()
                    #sleep(0.5)
                    #self.wait_key()
                    if self.slow_down_learned:
                        self.neural_network.fitness_boosts.append(150)
                    if self.straight_angle_learned:
                        self.neural_network.fitness_boosts.append(150)
                    if self.gain_xvel_learned:
                        self.neural_network.fitness_boosts.append(40)
                    if self.point_against_xvel_learned:
                        self.neural_network.fitness_boosts.append(50)
                    if self.xvel_slowdown_learned:
                        self.neural_network.fitness_boosts.append(50)
                    if self.cancel_xvel_learned:
                        self.neural_network.fitness_boosts.append(30)
                    self.gameover = True

            if self.drawing:
                if any(self.control_blocked):
                    display_text(screen, "Alert!", 215, 95)
                self.allsprites.draw(screen)
                if thrusting:
                    thrust_counter -= 1
                    screen.blit(self.thrust_img,
                                (self.lander.rect.centerx -
                                 self.thrust_img_rect.width / 2,
                                 self.lander.rect.centery +
                                 (self.lander.rect.height / 2)))
                    if thrust_counter == 0:
                        thrusting = False

            self.show_telemetry(screen)

            if self.lander.y > 680 and self.lander.x_vel < 5 and self.lander.y_vel < 5:
                self.slow_down_learned = True

            if self.lander.y > 680 and self.lander.angle == 0:
                self.straight_angle_learned = True

            if self.lander.x_vel != 0:
                self.gain_xvel_learned = True

            if self.lander.angle > 0 and self.lander.x_vel > 0:
                self.point_against_xvel_learned = True
            elif self.lander.angle < 0 and self.lander.x_vel < 0:
                self.point_against_xvel_learned = True

            if self.gain_xvel_learned and self.point_against_xvel_learned and self.lander.x_vel < 5:
                self.xvel_slowdown_learned = True

            if self.gain_xvel_learned and self.point_against_xvel_learned and self.lander.x_vel == 0:
                self.cancel_xvel_learned = True

            if self.neural_network is not None:

                left_down = 0
                middle_down = 0
                right_down = 0

                for landing_pad in self.maxipads:
                    if abs(
                            self.lander.x - landing_pad.rect.centerx
                    ) - landing_pad.rect.width / 2 < 750 - self.lander.y < abs(
                            self.lander.x - landing_pad.rect.centerx
                    ) + landing_pad.rect.width / 2:
                        if left_down < 1 - (sqrt(
                            (self.lander.x - landing_pad.rect.centerx)**2 +
                            (self.lander.y - landing_pad.rect.centery)**2) /
                                            800):
                            left_down = 1 - (sqrt(
                                (self.lander.x - landing_pad.rect.centerx)**2 +
                                (self.lander.y - landing_pad.rect.centery)**2)
                                             / 800)
                    if abs(
                            landing_pad.rect.centerx - self.lander.x
                    ) - landing_pad.rect.width / 2 > 750 - self.lander.y > abs(
                            landing_pad.rect.centerx -
                            self.lander.x) + landing_pad.rect.width / 2:
                        if right_down < 1 - (sqrt(
                            (self.lander.x - landing_pad.rect.centerx)**2 +
                            (self.lander.y - landing_pad.rect.centery)**2) /
                                             800):
                            right_down = 1 - (sqrt(
                                (self.lander.x - landing_pad.rect.centerx)**2 +
                                (self.lander.y - landing_pad.rect.centery)**2)
                                              / 800)
                    if landing_pad.rect.centerx - landing_pad.rect.width / 2 + self.lander.rect.width / 2 < self.lander.x < landing_pad.rect.centerx + landing_pad.rect.width / 2 - self.lander.rect.width / 2:
                        if middle_down < 1 - (
                            (landing_pad.rect.centery - self.lander.y) / 750):
                            middle_down = 1 - (
                                (landing_pad.rect.centery - self.lander.y) /
                                750)

                inputs = [
                    1 / (751 - self.lander.y), self.lander.x_vel / 100,
                    self.lander.y_vel / 100, self.lander.angle / 180,
                    left_down, middle_down, right_down
                ]
                self.neural_network.set_inputs(inputs)
                #print(inputs)

                self.neural_network.feed_forward()
Example #9
0
    def play(self):
        thrusting = False
        thrust_counter = 0
        if not self.gameover:
            # self.create_failure()
            # self.create_storm()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit("0")
                if event.type == pygame.KEYDOWN and self.lander.damage < 1 and self.neural_network is None:
                    if event.key == pygame.K_SPACE and not self.control_blocked[
                            1]:
                        self.lander.thrust()
                        if self.lander.fuel >= 5:
                            thrusting = True
                            thrust_counter = 5
                    if event.key == pygame.K_RIGHT and not self.control_blocked[
                            2]:
                        self.lander.rotate(-5)
                    if event.key == pygame.K_LEFT and not self.control_blocked[
                            0]:
                        self.lander.rotate(5)

            if self.neural_network is not None:

                controls = self.neural_network.get_outputs()

                if controls[0] >= 0.6 or controls[2] >= 0.6:
                    if controls[0] > controls[2]:
                        self.lander.rotate(5)  # left
                    elif controls[2] > controls[0]:
                        self.lander.rotate(-5)  # right
                if controls[1] >= 0.5:
                    self.lander.thrust()
                    if self.lander.fuel >= 5:
                        thrusting = True
                        thrust_counter = 5

            self.allsprites.update()
            collidedobj = pygame.sprite.spritecollideany(
                self.lander, self.obstacles)
            if collidedobj is not None:
                self.lander.damage += 0.1
                old_distance = sqrt(
                    (self.lander.x - collidedobj.rect.centerx)**2 +
                    (self.lander.y - collidedobj.rect.centery)**2)
                self.lander.x = collidedobj.rect.centerx + (
                    (self.lander.x - collidedobj.rect.centerx) /
                    old_distance) * (old_distance + 5)
                self.lander.y = collidedobj.rect.centery + (
                    (self.lander.y - collidedobj.rect.centery) /
                    old_distance) * (old_distance + 5)

            collidedpad = pygame.sprite.spritecollideany(
                self.lander, self.maxipads)
            if collidedpad is not None:
                self.neural_network.fitness_boosts.append(40)
                if self.lander.pad_collide(collidedpad):
                    self.score += 50
                    display_text(screen, "Landed!", 600, 375)
                    # print("landed")
                    # pygame.display.flip()
                    # sleep(0.5)
                    # self.wait_key()

                    for landing_pad in self.maxipads:
                        # remove all landing pads
                        self.allsprites.remove(landing_pad)
                        self.maxipads.remove(landing_pad)

                    for i in range(3):
                        newpad = Pad(low=True)
                        while pygame.sprite.spritecollideany(
                                newpad, self.maxipads
                        ) is not None or pygame.sprite.spritecollideany(
                                newpad, self.obstacles) is not None:
                            newpad = Pad(low=True)
                        self.maxipads.add(newpad)
                        self.allsprites.add(newpad)

                    self.lander.reset()
                    self.starttime = datetime.now()

            if self.lander.dead:
                if self.lives > 0:
                    self.lives -= 1
                    self.allsprites.remove(self.lander)
                    self.lander = Lander()
                    self.allsprites.add(self.lander)
                    display_text(screen, "You crashed!", 600, 375)
                    #pygame.display.flip()
                    #sleep(0.5)
                    #self.wait_key()

                    for landing_pad in self.maxipads:
                        # remove all landing pads
                        self.allsprites.remove(landing_pad)
                        self.maxipads.remove(landing_pad)

                    for i in range(3):
                        newpad = Pad(low=True)
                        while pygame.sprite.spritecollideany(
                                newpad, self.maxipads
                        ) is not None or pygame.sprite.spritecollideany(
                                newpad, self.obstacles) is not None:
                            newpad = Pad(low=True)
                        self.maxipads.add(newpad)
                        self.allsprites.add(newpad)

                    self.starttime = datetime.now()
                else:
                    display_text(screen, "Game over!", 600, 375)
                    #pygame.display.flip()
                    #sleep(0.5)
                    #self.wait_key()
                    if self.slow_down_learned:
                        self.neural_network.fitness_boosts.append(150)
                    if self.straight_angle_learned:
                        self.neural_network.fitness_boosts.append(150)
                    if self.gain_xvel_learned:
                        self.neural_network.fitness_boosts.append(40)
                    if self.point_against_xvel_learned:
                        self.neural_network.fitness_boosts.append(50)
                    if self.xvel_slowdown_learned:
                        self.neural_network.fitness_boosts.append(50)
                    if self.cancel_xvel_learned:
                        self.neural_network.fitness_boosts.append(30)
                    self.gameover = True

            if self.drawing:
                if any(self.control_blocked):
                    display_text(screen, "Alert!", 215, 95)
                self.allsprites.draw(screen)
                if thrusting:
                    thrust_counter -= 1
                    screen.blit(self.thrust_img,
                                (self.lander.rect.centerx -
                                 self.thrust_img_rect.width / 2,
                                 self.lander.rect.centery +
                                 (self.lander.rect.height / 2)))
                    if thrust_counter == 0:
                        thrusting = False

            self.show_telemetry(screen)

            if self.lander.y > 680 and self.lander.x_vel < 5 and self.lander.y_vel < 5:
                self.slow_down_learned = True

            if self.lander.y > 680 and self.lander.angle == 0:
                self.straight_angle_learned = True

            if self.lander.x_vel != 0:
                self.gain_xvel_learned = True

            if self.lander.angle > 0 and self.lander.x_vel > 0:
                self.point_against_xvel_learned = True
            elif self.lander.angle < 0 and self.lander.x_vel < 0:
                self.point_against_xvel_learned = True

            if self.gain_xvel_learned and self.point_against_xvel_learned and self.lander.x_vel < 5:
                self.xvel_slowdown_learned = True

            if self.gain_xvel_learned and self.point_against_xvel_learned and self.lander.x_vel == 0:
                self.cancel_xvel_learned = True

            if self.neural_network is not None:

                left_down = 0
                middle_down = 0
                right_down = 0

                for landing_pad in self.maxipads:
                    if abs(
                            self.lander.x - landing_pad.rect.centerx
                    ) - landing_pad.rect.width / 2 < 750 - self.lander.y < abs(
                            self.lander.x - landing_pad.rect.centerx
                    ) + landing_pad.rect.width / 2:
                        if left_down < 1 - (sqrt(
                            (self.lander.x - landing_pad.rect.centerx)**2 +
                            (self.lander.y - landing_pad.rect.centery)**2) /
                                            800):
                            left_down = 1 - (sqrt(
                                (self.lander.x - landing_pad.rect.centerx)**2 +
                                (self.lander.y - landing_pad.rect.centery)**2)
                                             / 800)
                    if abs(
                            landing_pad.rect.centerx - self.lander.x
                    ) - landing_pad.rect.width / 2 > 750 - self.lander.y > abs(
                            landing_pad.rect.centerx -
                            self.lander.x) + landing_pad.rect.width / 2:
                        if right_down < 1 - (sqrt(
                            (self.lander.x - landing_pad.rect.centerx)**2 +
                            (self.lander.y - landing_pad.rect.centery)**2) /
                                             800):
                            right_down = 1 - (sqrt(
                                (self.lander.x - landing_pad.rect.centerx)**2 +
                                (self.lander.y - landing_pad.rect.centery)**2)
                                              / 800)
                    if landing_pad.rect.centerx - landing_pad.rect.width / 2 + self.lander.rect.width / 2 < self.lander.x < landing_pad.rect.centerx + landing_pad.rect.width / 2 - self.lander.rect.width / 2:
                        if middle_down < 1 - (
                            (landing_pad.rect.centery - self.lander.y) / 750):
                            middle_down = 1 - (
                                (landing_pad.rect.centery - self.lander.y) /
                                750)

                inputs = [
                    1 / (751 - self.lander.y), self.lander.x_vel / 100,
                    self.lander.y_vel / 100, self.lander.angle / 180,
                    left_down, middle_down, right_down
                ]
                self.neural_network.set_inputs(inputs)
                #print(inputs)

                self.neural_network.feed_forward()
Example #10
0
def main():    
    print "You are aboard the lunar Lander and you are about to leave for the" 
    print "lunar surface"
    play = True

    while play:
        print "You have left the spacecraft"
        print "try to land with less than 5 m/sec velociy"

        # rest of the program goes here

        # temporary test code
        lem = Lander()
        lem.print_reading()
        lem.height = 800
        lem.print_reading()
        lem.velocity=7
        lem.height=0
        lem.print_reading()
        sleep(5)

        print "Do you want to play again (y/n)?"
        y = str(raw_input()).lower()
        if y == 'n' or y == "no":
            play = False
            del lem
            print "Have a nice day"
            sys.exit(0)
Example #11
0
def main():
    pygame.init()
    display_surface = pygame.display.set_mode((640, 640), pygame.locals.SCALED)
    frame_clock = pygame.time.Clock()

    lander = Lander()
    planet = Planet(x=display_surface.get_width() / 2,
                    y=display_surface.get_height() / 2,
                    radius=display_surface.get_width() / 4,
                    mass=3000000000000000.0)

    lander.x = display_surface.get_width() / 2
    lander.y = display_surface.get_height() / 8

    lander.set_planet(planet=planet)

    up_pressed = False
    left_pressed = False
    right_pressed = False
    down_pressed = False

    prediction_points = list()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.locals.QUIT:
                pygame.quit()
                return
            elif event.type == pygame.locals.KEYDOWN:
                if event.key == pygame.locals.K_UP:
                    up_pressed = True
                elif event.key == pygame.locals.K_RIGHT:
                    right_pressed = True
                elif event.key == pygame.locals.K_LEFT:
                    left_pressed = True
                elif event.key == pygame.locals.K_DOWN:
                    down_pressed = True
            elif event.type == pygame.locals.KEYUP:
                if event.key == pygame.locals.K_UP:
                    up_pressed = False
                elif event.key == pygame.locals.K_RIGHT:
                    right_pressed = False
                elif event.key == pygame.locals.K_LEFT:
                    left_pressed = False
                elif event.key == pygame.locals.K_DOWN:
                    down_pressed = False

        # Clear the display
        display_surface.fill(pygame.color.Color(0, 0, 0),
                             display_surface.get_rect())

        # Draw the planet
        pygame.draw.circle(display_surface, pygame.color.Color(255, 255, 255),
                           (planet.x, planet.y), planet.radius)
        pygame.draw.circle(display_surface, pygame.color.Color(0, 0, 0),
                           (planet.x, planet.y), planet.radius - 1)

        # Draw the lander
        lander_points = lander.get_points()

        pygame.draw.lines(display_surface, pygame.color.Color(255, 255, 255),
                          False, lander_points)

        # Draw future points
        for p in prediction_points:
            pygame.draw.circle(display_surface,
                               pygame.color.Color(255, 255, 255), p, 1)

        # Update lander control inputs
        thr_vals = [0.0, 0.0, 0.0, 0.0]
        thr_f: typing.List[typing.Callable[[float], None]] = [
            lander.set_thruster_a, lander.set_thruster_b,
            lander.set_thruster_c, lander.set_thruster_d
        ]
        main_val = 0.0
        if left_pressed:
            thr_vals[1] += 1.0
            thr_vals[2] += 1.0

        if right_pressed:
            thr_vals[0] += 1.0
            thr_vals[3] += 1.0

        if up_pressed:
            main_val += 1.0

        if down_pressed:
            thr_vals[2] += 1.0
            thr_vals[3] += 1.0

        lander.set_main_engine(value=main_val)
        for f, v in zip(thr_f, thr_vals):
            f(v)

        # Finish Loop
        pygame.display.update()
        millis = frame_clock.tick(100)
        time_step = millis / 1000.0
        lander.step(time_step=time_step)
        prediction_points = lander.predict_position(time_step=0.1,
                                                    log_interval=2.0,
                                                    end_time=60.0)
Example #12
0
class Game:
    STATE_ONGOING = 0
    STATE_SUCCESS = 1
    STATE_CRASH = 2

    def __init__(self,
                 surface,
                 clock,
                 screen_w,
                 screen_h,
                 background_color=(0, 0, 0)):
        self.surface = surface
        self.clock = clock
        self.screen_w = screen_w
        self.screen_h = screen_h
        self.level = 0
        self.state = Game.STATE_ONGOING
        self.terrain = Terrain(screen_w, screen_h)
        self.lander = Lander(self)
        self.sound_fx = SoundFX()
        self.ended = False
        self.crash_animation = None

    def set_sound(self, sound_stream):
        self.sound_fx.set_sound_stream(sound_stream)

    def reset(self):
        self.terrain.reset()
        self.lander.reset()
        self.state = Game.STATE_ONGOING

    def paint(self):
        self.surface.fill(BACKGROUND_COLOR)
        self.terrain.paint(self.surface)

        if self.state in (Game.STATE_ONGOING, Game.STATE_SUCCESS):
            self.lander.paint(self.surface)
        elif self.state == Game.STATE_CRASH and self.crash_animation is not None:
            self.crash_animation.paint(self.surface)

        # Draw info
        txt = 'FUEL %3d     ALT %3d     VERT SPD %3d     HORZ SPD %3d     LEVEL %3d' % (
            self.lander.fuel, self.screen_h - self.lander.y,
            self.lander.v_speed, self.lander.h_speed, self.level)
        sp_info = FONT.render(txt, 0, WHITE)
        self.surface.blit(sp_info, (0, self.screen_h - 22))
        # Display Success/Fail
        ending = 'LANDED' if self.state == Game.STATE_SUCCESS else (
            'CRASHED' if self.state == Game.STATE_CRASH else '')
        sp_ending = FONT.render(ending, 0, WHITE)
        surface.blit(sp_ending, (self.screen_w / 3, self.screen_h / 2))

    def step(self):
        # Check for state changes
        if self.lander.did_land():
            # Success landing
            self.state = Game.STATE_SUCCESS
        if self.state == Game.STATE_ONGOING and self.lander.did_collide():
            # Collision
            self.state = Game.STATE_CRASH
            self.crash_animation = CrashAnimation(self.lander.x, self.lander.y)

        # Run steps
        if self.state == Game.STATE_ONGOING:
            self.lander.step()
            # Out of screen
            if self.lander.x < 0 or self.lander.x > self.screen_w:
                self.lander.x -= (abs(self.lander.x) /
                                  self.lander.x) * self.screen_w

        elif self.state == Game.STATE_CRASH:
            if not self.crash_animation.ended:
                self.crash_animation.step()
                self.sound_fx.set_sound_stream(self.sound_fx.CRASH_SOUND)
            else:
                self.level = 0
                self.reset()

        elif self.state == Game.STATE_SUCCESS:
            self.level += 1
            self.reset()

    def step_end(self):
        self.lander.step_end()
        # Play sound and reset
        self.sound_fx.play()
        # Finish iteration
        self.clock.tick(5)

    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.ended = True

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.ended = True

                elif event.key == pygame.K_r:
                    self.reset()

                elif event.key == pygame.K_SPACE and self.lander.fuel > 0:
                    self.lander.fire_thruster_middle()
                    self.sound_fx.set_sound_stream(self.sound_fx.THRUST_SOUND)

                elif event.key == pygame.K_LEFT and self.lander.fuel > 0:
                    self.lander.fire_thruster_left()
                    self.sound_fx.set_sound_stream(self.sound_fx.THRUST_SOUND)

                elif event.key == pygame.K_RIGHT and self.lander.fuel > 0:
                    self.lander.fire_thruster_right()
                    self.sound_fx.set_sound_stream(self.sound_fx.THRUST_SOUND)

    def loop(self):
        while self.ended is False:
            # Handle events
            self.handle_events()
            # Step
            self.step()
            # Draw
            self.paint()
            # Step end
            self.step_end()
            # Commit to screen
            pygame.display.flip()

    def terminate(self):
        self.sound_fx.terminate()