Beispiel #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
Beispiel #2
0
def initpygame(settings, caption, settingsfile):
    pygame.init()
    screen = get_screen(settings["res_x"], settings["res_y"], settings["hardware_buffer"], settings["fullscreen"])
    mode = "game"
    if "--editor" in sys.argv:
        mode = "editor"
        debug("Loading game editor")
    global imagecache
    imagecache = ImageCache()
    global frontend
    frontend = Frontend(mode=mode, settingsfile=settingsfile)
    global tilemaps
    tilemaps = Tilemaps()
    global messages
    imagecache.load()
    wallpaper = imagecache["landscape.png"]
    wallpaper = pygame.transform.smoothscale(wallpaper, (settings["res_x"], settings["res_y"]))
    screen.blit(wallpaper, (0, 0))
    pygame.display.set_caption(caption)
    frontend = Frontend(screen, imagecache, eventstack, tilemaps, mode=mode, settingsfile=settingsfile)
    messages = Messages(screen, eventstack)
    messages.error("Welcome to Mirthless")
    if not "--editor" in sys.argv:
        messages.error(
            "Game mode is barely started. The editor is much further along. Try starting the game with --editor"
        )
        messages.message(":)")
    tilemaps.initialize()
    return screen, frontend.screenlayout(), frontend
Beispiel #3
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
Beispiel #4
0
class Argon(object):
    def __init__(self, width, height):
        self.width  = width
        self.height = height

        self.load = ImageCache([in_module('assets'), os.getcwd(), '.'])
        self.default_font = self.load.font('AnonymousPro_17')

        self.running = False
        self.flags = HWSURFACE | OPENGL | DOUBLEBUF
        self.listeners = {}
        self.frame_latency = []

        pygame.display.set_mode((self.width, self.height), self.flags)
        glEnable(GL_TEXTURE_2D)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        self.render = Renderer(self, self.default_font)

    def listen(self, fn):
        self.listeners[fn.__name__] = fn
        return fn

    def run(self):
        self.running = True
        while self.running:
            now = time.time()
            self.listeners["on_frame"](now)
            pygame.display.flip()
            self.frame_latency.append(time.time() - now)
            while len(self.frame_latency) > 100:
                self.frame_latency.pop(0)
            for event in pygame.event.get():
                if event.type == QUIT:
                    self.running = False
                event_dispatch(event, self.listeners)

    def clear(self, color):
        r, g, b, a = color
        glClearColor(r/255.0, g/255.0, b/255.0, a/255.0)
        glClear(GL_COLOR_BUFFER_BIT)

    def bind(self):
        glBindFramebuffer(GL_FRAMEBUFFER, 0)

    def unbind(self):
        pass

    def show_performance_log(self):
        latency = self.frame_latency
        font = self.default_font
        if len(latency) > 0:
            avg  = sum(latency) / len(latency)
            high = max(latency) 
            text = "avg=%.2fms high=%.2fms" % (avg * 1000, high * 1000)
            self.render.text((0, self.height - font.height + font.baseline), text)
Beispiel #5
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()
Beispiel #6
0
    def __init__(self, width, height):
        self.width  = width
        self.height = height

        self.load = ImageCache([in_module('assets'), os.getcwd(), '.'])
        self.default_font = self.load.font('AnonymousPro_17')

        self.running = False
        self.flags = HWSURFACE | OPENGL | DOUBLEBUF
        self.listeners = {}
        self.frame_latency = []

        pygame.display.set_mode((self.width, self.height), self.flags)
        glEnable(GL_TEXTURE_2D)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        self.render = Renderer(self, self.default_font)
Beispiel #7
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)))
Beispiel #8
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()

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

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

        ball = self.imageCache.getCachedSurface("ball")
        self.screenRect = pygame.Rect(0, 0, width, height)
        self.playerSprite = PlayerSprite(ball, self.screenRect)
        self.sprites = pygame.sprite.Group(self.playerSprite)
        self.mapView = None
Beispiel #9
0
class GameLoop(object):
    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

    def _updateFPS(self, fps):
        self.fontSurf = self.font.render('FPS: %.3f' % fps, True, (0, 255, 0))

    def render(self):
        self.screen.fill(self.black)
        self.mapView.draw(self.screen)
        self.playerSpriteGroup.draw(self.screen)
        self.mobs.draw(self.screen)
        if self.fontSurf and self._displayFPS:
            self.screen.blit(self.fontSurf, (25, 25))
        pygame.display.flip()

    def update(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()

            speed = 15

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    sys.exit()
                elif event.key == pygame.K_a:
                    self.playerSprite.dx -= speed
                elif event.key == pygame.K_d:
                    self.playerSprite.dx += speed
                elif event.key == pygame.K_w:
                    self.playerSprite.dy -= speed
                elif event.key == pygame.K_s:
                    self.playerSprite.dy += speed
                elif event.key == pygame.K_F1:
                    self._displayFPS = not self._displayFPS

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_a:
                    self.playerSprite.dx += speed
                elif event.key == pygame.K_d:
                    self.playerSprite.dx -= speed
                elif event.key == pygame.K_w:
                    self.playerSprite.dy += speed
                elif event.key == pygame.K_s:
                    self.playerSprite.dy -= speed

        self.mapView.update()
        self.playerSpriteGroup.update()
        self.mobs.update()

    def loop(self):
        nextGameTick = pygame.time.get_ticks()

        renderClock = pygame.time.Clock()
        updateTick = 0

        self.levelMap = Map(mapElementCB=initMapElement)
        self.mapView = MapView(self.levelMap, self.imageCache,
                               pygame.Rect(0, 0, 800, 600), 32, 32)
        self.playerSprite.mapView = self.mapView

        while 1:
            loops = 0

            while pygame.time.get_ticks(
            ) > nextGameTick and loops < self.MaxFrameSkip:
                self.update()
                nextGameTick += self.TimePerTick
                loops += 1
                updateTick += 1

                if updateTick % 10 == 0:
                    self._updateFPS(renderClock.get_fps())

            renderClock.tick()
            self.render()
Beispiel #10
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)
Beispiel #11
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()
Beispiel #12
0
class GameLoop (object):
    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()

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

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

        ball = self.imageCache.getCachedSurface("ball")
        self.screenRect = pygame.Rect(0, 0, width, height)
        self.playerSprite = PlayerSprite(ball, self.screenRect)
        self.sprites = pygame.sprite.Group(self.playerSprite)
        self.mapView = None

    def render(self):
        self.screen.fill(self.black)
        self.mapView.draw(self.screen)
        self.sprites.draw(self.screen)
        pygame.display.flip()

    def update(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            
            speed = 5

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    sys.exit()
                elif event.key == pygame.K_a:
                    self.playerSprite.dx -= speed
                elif event.key == pygame.K_d:
                    self.playerSprite.dx += speed
                elif event.key == pygame.K_w:
                    self.playerSprite.dy -= speed
                elif event.key == pygame.K_s:
                    self.playerSprite.dy += speed
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_a:
                    self.playerSprite.dx += speed
                elif event.key == pygame.K_d:
                    self.playerSprite.dx -= speed
                elif event.key == pygame.K_w:
                    self.playerSprite.dy += speed
                elif event.key == pygame.K_s:
                    self.playerSprite.dy -= speed

        self.mapView.update()
        self.sprites.update()

    def loop(self):
        nextGameTick = pygame.time.get_ticks()

        renderClock = pygame.time.Clock()
        updateTick = 0

        levelMap = Map(30, 30, mapElementCB = initMapElement)

        astar = AStar(levelMap.getSquareAdjacencies,
                      lambda elem: getCost(levelMap, elem),
                      lambda x, y: getHeuristicCost(levelMap, x, y),
                      isImpassable)

        self.mapView = MapView(levelMap, self.imageCache, pygame.Rect(0, 0, 800, 600), 32, 32)
        self.playerSprite.setMapView(self.mapView)

        sprinkleMobs(10, 8, self.sprites, self.mapView, self.imageCache, self.screenRect, astar, self.playerSprite)

        while 1:
            loops = 0

            while pygame.time.get_ticks() > nextGameTick and loops < self.MaxFrameSkip:
                self.update()
                nextGameTick += self.TimePerTick
                loops += 1
                updateTick += 1
                
                if updateTick % 100 == 0:
                    print renderClock.get_fps()

            renderClock.tick()    
            self.render()
Beispiel #13
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()
Beispiel #14
0
class GameLoop (object):
    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

    def _updateFPS(self, fps):
        self.fontSurf = self.font.render('FPS: %.3f' % fps, True, (0, 255, 0))

    def render(self):
        self.screen.fill(self.black)
        self.mapView.draw(self.screen)
        self.playerSpriteGroup.draw(self.screen)
        self.mobs.draw(self.screen)
        if self.fontSurf and self._displayFPS:
            self.screen.blit(self.fontSurf, (25, 25))
        pygame.display.flip()

    def update(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            
            speed = 15

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    sys.exit()
                elif event.key == pygame.K_a:
                    self.playerSprite.dx -= speed
                elif event.key == pygame.K_d:
                    self.playerSprite.dx += speed
                elif event.key == pygame.K_w:
                    self.playerSprite.dy -= speed
                elif event.key == pygame.K_s:
                    self.playerSprite.dy += speed
                elif event.key == pygame.K_F1:
                    self._displayFPS = not self._displayFPS
                    
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_a:
                    self.playerSprite.dx += speed
                elif event.key == pygame.K_d:
                    self.playerSprite.dx -= speed
                elif event.key == pygame.K_w:
                    self.playerSprite.dy += speed
                elif event.key == pygame.K_s:
                    self.playerSprite.dy -= speed

        self.mapView.update()
        self.playerSpriteGroup.update()
        self.mobs.update()

    def loop(self):
        nextGameTick = pygame.time.get_ticks()

        renderClock = pygame.time.Clock()
        updateTick = 0

        self.levelMap = Map(mapElementCB = initMapElement)
        self.mapView = MapView(self.levelMap, self.imageCache, pygame.Rect(0, 0, 800, 600), 32, 32)
        self.playerSprite.mapView = self.mapView

        while 1:
            loops = 0

            while pygame.time.get_ticks() > nextGameTick and loops < self.MaxFrameSkip:
                self.update()
                nextGameTick += self.TimePerTick
                loops += 1
                updateTick += 1
                
                if updateTick % 10 == 0:
                    self._updateFPS(renderClock.get_fps())

            renderClock.tick()    
            self.render()