Example #1
0
    def __init__(self, ticks_per_second, max_frame_skip):
        self.TicksPerSecond = ticks_per_second
        self.TimePerTick = 1000.0 / self.TicksPerSecond  # MS per tick
        self.MaxFrameSkip = max_frame_skip

        pygame.init()

        try:
            self.font = pygame.font.Font('VeraMono.ttf', 16)
        except:
            print 'problem loading font'
            self.font = None

        self.fontSurf = None
        self._displayFPS = False

        size = width, height = 800, 600
        self.black = 0, 0, 0
        #self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
        self.screen = pygame.display.set_mode(size)

        self.imageCache = ImageCache()
        self.imageCache.getSurface("units/Player1.png", "ball")
        self.imageCache.getSurface("units/Creature1.png", "mob")
        self.imageCache.getSurface("units/Mine1.png", "mine")
        self.imageCache.getSurface("terrains/Normal.jpg", "normal")
        self.imageCache.getSurface("terrains/Impassable5.jpg", "impassable-1")

        ball = self.imageCache.getCachedSurface("ball")
        self.mobs = pygame.sprite.Group()
        self.playerSprite = PlayerSprite(ball, width / 2 - 16, height / 2 - 16,
                                         self.imageCache, self.mobs)
        self.playerSpriteGroup = pygame.sprite.Group(self.playerSprite)
        self.mapView = None
Example #2
0
 def __init__(self, world, x, y, speed=0, velocity=0, ClimbSpeed=0):
     self.world = world
     self.x = x
     self.y = y
     self.speed = speed
     self.max_velocity = velocity
     self.velocity = 0
     self.ClimbSpeed = ClimbSpeed
     self.height = 160
     self.width = 128
     self.xxx = 0
     self.images = images()
     self.imageCache = ImageCache()
Example #3
0
class World:
    LEFT = -1
    RIGHT = 1
    imageCache = ImageCache()

    def __init__(self, surface_altitudes, bounce, box_position, stairPosX):
        self.surface_altitudes = surface_altitudes
        self.bounce = bounce
        self.box_position = box_position
        self.stairPosX = stairPosX

    def ground_line(self):
        for coordinate in self.surface_altitudes:
            pygame.draw.line(Screen.screen, 0, coordinate[0], coordinate[1], 4)

    def render_box(self):
        for (coordinate) in self.box_position:
            Screen.screen.blit(
                self.imageCache.get_image(images.imagesBox[0]),
                (coordinate[0], coordinate[1] + 60 -
                 self.imageCache.get_image(images.imagesBox[0]).get_height()))
            pygame.draw.line(Screen.screen, 0, (coordinate[0], coordinate[1]),
                             (coordinate[0] + 60, coordinate[1]), 4)
            self.surface_altitudes.append(
                ((coordinate[0], coordinate[1]), (coordinate[0] + 60,
                                                  coordinate[1])))
            pygame.draw.line(Screen.screen, 0,
                             (coordinate[0], coordinate[1] + 60),
                             (coordinate[0] + 60, coordinate[1] + 60), 4)
            self.surface_altitudes.append(
                ((coordinate[0], coordinate[1] + 60), (coordinate[0] + 60,
                                                       coordinate[1] + 60)))
            pygame.draw.line(Screen.screen, 0, (coordinate[0], coordinate[1]),
                             (coordinate[0], coordinate[1] + 60), 4)
            self.surface_altitudes.append(
                ((coordinate[0], coordinate[1]), (coordinate[0],
                                                  coordinate[1] + 60)))
            pygame.draw.line(Screen.screen, 0,
                             (coordinate[0] + 60, coordinate[1]),
                             (coordinate[0] + 60, coordinate[1] + 60), 4)
            self.surface_altitudes.append(
                ((coordinate[0] + 60, coordinate[1]), (coordinate[0] + 60,
                                                       coordinate[1] + 60)))
Example #4
0
def main():
    args = parseArguments()

    MAX_TRAIN_TIME_MINS = args.time
    LEARNING_RATE = args.lrate
    CHECKPOINT_FILE = args.check
    CHECKPOINT_DIR = args.checkpoint_dir
    BATCH_SIZE = args.batch_size
    SAMPLE_STEP = args.sample_freq
    SAVE_STEP = args.checkpoint_freq
    SOFT_LABELS = args.softL
    LOG_DIR = args.logdir
    LOG_FREQUENCY = args.log_frequency
    PIPELINE_TWEAKS['random_flip'] = args.random_flip
    PIPELINE_TWEAKS['random_brightness'] = PIPELINE_TWEAKS[
        'random_saturation'] = PIPELINE_TWEAKS[
            'random_contrast'] = args.random_q
    PIPELINE_TWEAKS['crop_size'] = args.crop

    if SOFT_LABELS:
        softL_c = 0.05
        #softL_c = np.random.normal(1,0.05)
        #if softL_c > 1.15: softL_c = 1.15
        #if softL_c < 0.85: softL_c = 0.85
    else:
        softL_c = 0.0
    print('Soft Labeling: ', softL_c)

    sess = tf.Session()

    # DEFINE OUR MODEL AND LOSS FUNCTIONS
    # -------------------------------------------------------

    real_X = Images(args.input_prefix + '_trainA.tfrecords',
                    batch_size=BATCH_SIZE,
                    name='real_X').feed()
    real_Y = Images(args.input_prefix + '_trainB.tfrecords',
                    batch_size=BATCH_SIZE,
                    name='real_Y').feed()

    # genG(X) => Y            - fake_B
    genG = generator(real_X,
                     norm=args.norm,
                     rnorm=args.rnorm,
                     name="generatorG")
    # genF(Y) => X            - fake_A
    genF = generator(real_Y,
                     norm=args.norm,
                     rnorm=args.rnorm,
                     name="generatorF")
    # genF( genG(Y) ) => Y    - fake_A_
    genF_back = generator(genG,
                          norm=args.norm,
                          rnorm=args.rnorm,
                          name="generatorF",
                          reuse=True)
    # genF( genG(X)) => X     - fake_B_
    genG_back = generator(genF,
                          norm=args.norm,
                          rnorm=args.rnorm,
                          name="generatorG",
                          reuse=True)

    # DY_fake is the discriminator for Y that takes in genG(X)
    # DX_fake is the discriminator for X that takes in genF(Y)
    discY_fake = discriminator(genG, norm=args.norm, reuse=False, name="discY")
    discX_fake = discriminator(genF, norm=args.norm, reuse=False, name="discX")

    g_loss_G = tf.reduce_mean((discY_fake - tf.ones_like(discY_fake) * np.abs(np.random.normal(1.0,softL_c))) ** 2) \
            + L1_lambda * tf.reduce_mean(tf.abs(real_X - genF_back)) \
            + L1_lambda * tf.reduce_mean(tf.abs(real_Y - genG_back))

    g_loss_F = tf.reduce_mean((discX_fake - tf.ones_like(discX_fake) * np.abs(np.random.normal(1.0,softL_c))) ** 2) \
            + L1_lambda * tf.reduce_mean(tf.abs(real_X - genF_back)) \
            + L1_lambda * tf.reduce_mean(tf.abs(real_Y - genG_back))

    fake_X_sample = tf.placeholder(tf.float32, [None, 256, 256, 3],
                                   name="fake_X_sample")
    fake_Y_sample = tf.placeholder(tf.float32, [None, 256, 256, 3],
                                   name="fake_Y_sample")

    # DY is the discriminator for Y that takes in Y
    # DX is the discriminator for X that takes in X
    DY = discriminator(real_Y, norm=args.norm, reuse=True, name="discY")
    DX = discriminator(real_X, norm=args.norm, reuse=True, name="discX")
    DY_fake_sample = discriminator(fake_Y_sample,
                                   norm=args.norm,
                                   reuse=True,
                                   name="discY")
    DX_fake_sample = discriminator(fake_X_sample,
                                   norm=args.norm,
                                   reuse=True,
                                   name="discX")

    DY_loss_real = tf.reduce_mean(
        (DY - tf.ones_like(DY) * np.abs(np.random.normal(1.0, softL_c)))**2)
    DY_loss_fake = tf.reduce_mean(
        (DY_fake_sample - tf.zeros_like(DY_fake_sample))**2)
    DY_loss = (DY_loss_real + DY_loss_fake) / 2

    DX_loss_real = tf.reduce_mean(
        (DX - tf.ones_like(DX) * np.abs(np.random.normal(1.0, softL_c)))**2)
    DX_loss_fake = tf.reduce_mean(
        (DX_fake_sample - tf.zeros_like(DX_fake_sample))**2)
    DX_loss = (DX_loss_real + DX_loss_fake) / 2

    test_X = Images(args.input_prefix + '_testA.tfrecords',
                    shuffle=False,
                    name='test_A').feed()
    test_Y = Images(args.input_prefix + '_testB.tfrecords',
                    shuffle=False,
                    name='test_B').feed()

    testG = generator(test_X,
                      norm=args.norm,
                      rnorm=args.rnorm,
                      name="generatorG",
                      reuse=True)
    testF = generator(test_Y,
                      norm=args.norm,
                      rnorm=args.rnorm,
                      name="generatorF",
                      reuse=True)
    testF_back = generator(testG,
                           norm=args.norm,
                           rnorm=args.rnorm,
                           name="generatorF",
                           reuse=True)
    testG_back = generator(testF,
                           norm=args.norm,
                           rnorm=args.rnorm,
                           name="generatorG",
                           reuse=True)

    t_vars = tf.trainable_variables()
    DY_vars = [v for v in t_vars if 'discY' in v.name]
    DX_vars = [v for v in t_vars if 'discX' in v.name]
    g_vars_G = [v for v in t_vars if 'generatorG' in v.name]
    g_vars_F = [v for v in t_vars if 'generatorF' in v.name]

    # SETUP OUR SUMMARY VARIABLES FOR MONITORING
    # -------------------------------------------------------

    G_loss_sum = tf.summary.scalar("loss/G", g_loss_G)
    F_loss_sum = tf.summary.scalar("loss/F", g_loss_F)
    DY_loss_sum = tf.summary.scalar("loss/DY", DY_loss)
    DX_loss_sum = tf.summary.scalar("loss/DX", DX_loss)
    DY_loss_real_sum = tf.summary.scalar("loss/DY_real", DY_loss_real)
    DY_loss_fake_sum = tf.summary.scalar("loss/DY_fake", DY_loss_fake)
    DX_loss_real_sum = tf.summary.scalar("loss/DX_real", DX_loss_real)
    DX_loss_fake_sum = tf.summary.scalar("loss/DX_fake", DX_loss_fake)

    imgX = tf.summary.image('real_X', real_X, max_outputs=1)
    imgF = tf.summary.image('fake_X', genF, max_outputs=1)
    imgY = tf.summary.image('real_Y', real_Y, max_outputs=1)
    imgG = tf.summary.image('fake_Y', genG, max_outputs=1)

    # SETUP OUR TRAINING
    # -------------------------------------------------------

    def adam(loss, variables, start_lr, end_lr, lr_decay_start, start_beta,
             name_prefix):
        name = name_prefix + '_adam'
        global_step = tf.Variable(0, trainable=False)
        # The paper recommends learning at a fixed rate for several steps, and then linearly stepping down to 0
        learning_rate = (tf.where(
            tf.greater_equal(global_step, lr_decay_start),
            tf.train.polynomial_decay(start_lr,
                                      global_step - lr_decay_start,
                                      lr_decay_start,
                                      end_lr,
                                      power=1.0), start_lr))
        lr_sum = tf.summary.scalar('learning_rate/{}'.format(name),
                                   learning_rate)

        learning_step = (tf.train.AdamOptimizer(learning_rate,
                                                beta1=start_beta,
                                                name=name).minimize(
                                                    loss,
                                                    global_step=global_step,
                                                    var_list=variables))
        return learning_step, lr_sum

    DX_optim, DX_lr = adam(DX_loss, DX_vars, LEARNING_RATE, args.end_lr,
                           args.lr_decay_start, MOMENTUM, 'D_X')

    DY_optim, DY_lr = adam(DY_loss, DY_vars, LEARNING_RATE, args.end_lr,
                           args.lr_decay_start, MOMENTUM, 'D_Y')

    G_optim, G_lr = adam(g_loss_G, g_vars_G, LEARNING_RATE, args.end_lr,
                         args.lr_decay_start, MOMENTUM, 'G')

    F_optim, F_lr = adam(g_loss_F, g_vars_F, LEARNING_RATE, args.end_lr,
                         args.lr_decay_start, MOMENTUM, 'F')

    G_sum = tf.summary.merge([G_loss_sum, G_lr])
    F_sum = tf.summary.merge([F_loss_sum, F_lr])
    DY_sum = tf.summary.merge(
        [DY_loss_sum, DY_loss_real_sum, DY_loss_fake_sum, DY_lr])
    DX_sum = tf.summary.merge(
        [DX_loss_sum, DX_loss_real_sum, DX_loss_fake_sum, DX_lr])

    images_sum = tf.summary.merge([imgX, imgG, imgY, imgF])

    # CREATE AND RUN OUR TRAINING LOOP
    # -------------------------------------------------------

    print("Starting the time")
    timer = utils.Timer()

    sess.run(tf.global_variables_initializer())

    saver = tf.train.Saver(tf.global_variables())
    ckpt = tf.train.get_checkpoint_state('./checkpoint/')

    if ckpt and ckpt.model_checkpoint_path and not args.ignore_checkpoint:
        saver.restore(sess, ckpt.model_checkpoint_path)
        print("Reading model parameters from %s" % ckpt.model_checkpoint_path)
    else:
        print("Created model with fresh parameters.")

    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)

    summary_op = tf.summary.merge_all()
    writer = tf.summary.FileWriter(LOG_DIR, sess.graph)

    cache_X = ImageCache(50)
    cache_Y = ImageCache(50)

    counter = 0
    try:
        while not coord.should_stop():

            # FORWARD PASS
            generated_X, generated_Y = sess.run([genF, genG])
            _, _, _, _, summary_str = sess.run(
                [G_optim, DY_optim, F_optim, DX_optim, summary_op],
                feed_dict={
                    fake_Y_sample: cache_Y.fetch(generated_Y),
                    fake_X_sample: cache_X.fetch(generated_X)
                })

            counter += 1
            print("[%4d] time: %4.4f" % (counter, time.time() - start_time))

            if np.mod(counter, LOG_FREQUENCY) == 0:
                print('writing')
                writer.add_summary(summary_str, counter)

            if np.mod(counter, SAMPLE_STEP) == 0:
                sample_model(sess, counter, test_X, test_Y, testG, testF,
                             testG_back, testF_back)

            if np.mod(counter, SAVE_STEP) == 0:
                save_path = save_model(saver, sess, counter)
                print("Running for '{0:.2}' mins, saving to {1}".format(
                    timer.elapsed() / 60, save_path))

            if np.mod(counter, SAVE_STEP) == 0:
                elapsed_min = timer.elapsed() / 60
                if (elapsed_min >= MAX_TRAIN_TIME_MINS):
                    print(
                        "Trained for '{0:.2}' mins and reached the max limit of {1}. Saving model."
                        .format(elapsed_min, MAX_TRAIN_TIME_MINS))
                    coord.request_stop()

    except KeyboardInterrupt:
        print('Interrupted')
        coord.request_stop()
    except Exception as e:
        coord.request_stop(e)
    finally:
        save_path = save_model(saver, sess, counter)
        print("Model saved in file: %s" % save_path)
        # When done, ask the threads to stop.
        coord.request_stop()
        coord.join(threads)
Example #5
0
class World:
    """
    The Game World. May be expanded to contain all the things (Players, Enemies, etc).
    """

    width: float = 0.0
    height: float = 0.0

    players: list = list()
    enemies: list = list()
    bullets: list = list()

    image_cache = ImageCache()

    font: pygame.font.Font = None
    game_over_font: pygame.font.Font = None
    score_x_pos: int = 10
    score_y_pos: int = 10
    score: int = 0

    is_game_over: bool = False

    def __init__(self, width: float, height: float):
        self.width = width
        self.height = height
        self.font = pygame.font.Font('freesansbold.ttf', 36)
        self.game_over_font = pygame.font.Font('freesansbold.ttf', 48)

    def show_text(self):
        from main import screen
        # Functions that are implemented in C do not have names for their arguments,
        # and you need to provide positional-only arguments.
        if self.is_game_over:
            # Functions that are implemented in C do not have names for their arguments,
            # and you need to provide positional-only arguments.
            game_over_text: pygame.Surface = self.game_over_font.render(
                'GAME OVER - Score: ' + str(self.score), True, (255, 100, 100))
            screen.blit(source=game_over_text, dest=(120, 200))
        else:
            score_text: pygame.Surface = self.font.render(
                "Score: " + str(self.score), True, (255, 255, 255))
            screen.blit(source=score_text, dest=(self.score_x_pos, self.score_y_pos))

    def initialize(self):
        self.image_cache.init_images()

        player: Player = Player(self.image_cache.player_image)
        player.set_position(x=370.0, y=480.0)
        self.players.append(player)

        x = random.randint(0, self.width - 64)
        y = random.randint(50, 150)

        print(str.format("world.x={}, world.y={}", x, y))

        self.add_enemy(Enemy(image=self.image_cache.enemy_image_1), x, y)
        self.add_enemy(Enemy(image=self.image_cache.enemy_image_1), x, y)
        self.add_enemy(Enemy(image=self.image_cache.enemy_image_1), x, y)

        y += 60
        self.add_enemy(Enemy(image=self.image_cache.enemy_image_2), x, y)
        self.add_enemy(Enemy(image=self.image_cache.enemy_image_2), x, y)
        self.add_enemy(Enemy(image=self.image_cache.enemy_image_2), x, y)

    def get_player(self) -> 'Player':
        return self.players[0]

    def add_enemy(self, enemy: 'Enemy', x: int, y: int):
        width: float = enemy.width

        if len(self.enemies) > 0:
            last_enemy: Enemy = self.enemies[-1]
            x = last_enemy.x_pos + (width * 1.5)

        enemy.set_position(x, y)
        self.enemies.append(enemy)

    def update_actor_positions(self):
        self.__update_positions(self.players)
        self.__update_positions(self.enemies)
        self.__update_positions(self.bullets)

        bullets_to_remove = list()
        for bullet in self.bullets:
            if bullet.should_destroy(world=self):
                bullets_to_remove.append(bullet)

        self.__destroy_bullets(bullets_to_remove)

    def __destroy_bullet(self, bullet: 'Bullet'):
        self.bullets.remove(bullet)

    def __destroy_bullets(self, bullets_to_remove: list):
        for bullet in bullets_to_remove:
            self.bullets.remove(bullet)

    def draw_actors(self):
        from main import screen
        for player in self.players:
            player.draw(screen)

        for enemy in self.enemies:
            enemy.draw(screen)

        for bullet in self.bullets:
            bullet.draw(screen)

    def perform_collision_detection(self):
        for enemy in self.enemies:
            for bullet in self.bullets:
                if bullet.is_collision(enemy):
                    print("Collision! Need to destroy enemy: " + str(enemy))
                    self.__destroy_bullet(bullet)
                    enemy.destroy_and_respawn()
                    self.score += 1
                    print(str.format("Score={}", self.score))

            for player in self.players:
                if player.is_collision(enemy):
                    print("Enemy collided with player. Game over!")
                    self.__game_over()
                    return

    def create_bullet(self):
        """
        Creates a bullet instance at the Player's current position.
        Enforces a maximum number of Player projectiles.
        """
        if len(self.bullets) >= PLAYER_MAX_BULLETS:
            print("Maximum number of bullets reached.")
            return

        bullet: Bullet = Bullet(image=self.image_cache.bullet_image)
        bullet.create(self.get_player(), BULLET_SPEED)
        self.bullets.append(bullet)

    def __update_positions(self, actors: list):
        for actor in actors:
            actor.update_position()
            actor.handle_world_collision(world=self)

    def __game_over(self):
        self.is_game_over = True

        for enemy in self.enemies:
            enemy.send_to_the_void()
Example #6
0
done = False
world = World(surface_altitudes=[((0, 420), (800, 420)),
                                 ((800, 600), (880, 600)),
                                 ((900, 420), (2100, 420)),
                                 ((900, 420), (900, 500)),
                                 ((900, 500), (1920, 500)),
                                 ((800, 420), (800, 500)),
                                 ((0, 500), (800, 500))],
              bounce=0.2,
              box_position=[[400, 300], [800, 300], [1800, 600]],
              stairPosX=[[500, 550]])
hero = Hero(world=world, x=960, y=0, speed=7, velocity=HOR_SPEED, ClimbSpeed=5)

GroundLine = world.surface_altitudes

imageCache = ImageCache()

world.ground_line()

world.render_box()

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            done = True

    screen.fill((255, 255, 255))
    world.ground_line()