コード例 #1
0
def edit_init():

    globs.mode = "grid_edit"
    globs.grid = Grid()

    listen.launch(editor_camera_loop())
    listen.launch(grid_editor_loop())
コード例 #2
0
def main():
    glfw.init()

    glfw.window_hint(glfw.RESIZABLE, False)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6)

    w, h = 800, 800

    globs.window = glfw.create_window(w, h, 'Tesseland', None, None)
    glfw.make_context_current(globs.window)

    init_polygon_shader()

    levels_init()

    globs.spf = 0.015  # 60ish fps
    listen.launch(game_loop())

    render_init(w, h)
    play_init()
    hud_init()

    # the main loop.
    while not glfw.window_should_close(globs.window):
        glfw.wait_events_timeout(globs.spf / 10)
        listen.trigger_timers()

    glfw.terminate()
コード例 #3
0
def render_init(w,h):
    globs.cam = {
        "pos":Vec(0,0),         # of bottom left corner of screen, in units
        "pixel_scale": 3,       # each asset pixel occupies this many screen pixels
        "pixels_per_unit": 16,  # this is asset pixels, not screen pixels
        "w": w, "h": h,         # width in screen pixels, height in screen pixels
        "projection": None,     # viewport_loop populates this with a matrix
        "projection-inv": None, # and its inverse here.
        "w_asset" : w/16/3,     # width in asset pixels is width / pixels_per_unit / pixel_scale
        "h_asset" : h/16/3,     # height in asset pixels is height / pixels_per_unit / pixel_scale
        "smoothing" : False,    # is the camera's motion smoothed (True), or does it snap to the player (False)
        "smoothing_factor" : 5  # how smooth is the motion (higher numbers are slower, smoother motion
    }
    globs.hud_elements = [
        {
            "function": "test",
            "sprite": "assets/hud.png",
            "location": {"x": 12,"y": 12 },# world units (1 block = 1x1 world units)
            "size" : {"x": 128, "y" : 16} # pixel_width/20, pixel_height/20
        },
        {
            "function": "inventory",
            "sprite": "assets/hud.png",
            "location": {"x": 12 ,"y": 3 },
            "size" : {"x": 128, "y" : 16}# pixel_width/20, pixel_height/20
        },
    ]
    listen.launch(viewport_loop())
    listen.launch(render_loop())
コード例 #4
0
def main():
    glfw.init()

    glfw.window_hint(glfw.RESIZABLE, False)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6)

    w, h = 800, 640

    globs.window = glfw.create_window(w, h, 'PlatformPrototype', None, None)
    x = glfw.make_context_current(globs.window)

    # initialize libraries
    init_quadarray()
    init_textbox(w=2000, h=2000)  # dimension of glyph atlas

    globs.spf = 0.015  # 60ish fps

    # this stuff gets rendered by the render_loop
    globs.quadarrays = []
    globs.textboxes = []

    # launch loops (order matters here)
    listen.launch(game_loop())
    render_init(w, h)
    load_assets()
    edit_init()
    play_init()

    # the main loop.
    while not glfw.window_should_close(globs.window):
        glfw.wait_events_timeout(globs.spf / 10)
        listen.trigger_timers()

    glfw.terminate()
コード例 #5
0
def render_init(w, h):
    globs.cam = {
        "w": w,
        "h": h,
        "scale": 100,
        "projection": None,
    }

    listen.launch(viewport_loop())
    listen.launch(render_loop())
コード例 #6
0
def play_init():
    # globs.playerarray renders the player
    animator = Animator()
    animator.enqueue(globs.assets["dino-idle-right"],
                     loop=True,
                     label="idle-right")
    globs.playerarray = QuadArray(animator)
    globs.quadarrays.append(globs.playerarray)

    listen.launch(play_loop())
    listen.launch(escape_loop())
コード例 #7
0
def render_init(w, h):
    globs.cam = {
        "pos": Vec(0, 0),  # of bottom left corner of screen, in units
        "pixel_scale": 3,  # each asset pixel occupies this many screen pixels
        "pixels_per_unit": 16,  # this is asset pixels, not screen pixels
        "w": w,
        "h": h,
        "projection": None,  # viewport_loop populates this with a matrix
        "projection-inv": None,  # and its inverse here.
    }

    listen.launch(viewport_loop())
    listen.launch(render_loop())
コード例 #8
0
def render_init(w,h):
    globs.cam = {
        "pos":Vec(0,0),         # of bottom left corner of screen, in units
        "target_pos": Vec(0,0), # camera slowly moves to here
        "pixel_scale": 3,       # each asset pixel occupies this many screen pixels
        "pixels_per_unit": 32,  # this is asset pixels, not screen pixels
        "w": w, "h": h,
        "projection": None,     # viewport_loop populates this with a matrix
        "projection-inv": None, # and its inverse here.
    }

    # dimensions of the viewport in world coordinates
    dims = Vec(globs.cam["w"], globs.cam["h"])
    dims /= globs.cam["pixel_scale"]
    dims /= globs.cam["pixels_per_unit"]
    globs.cam["dims"] = dims

    listen.launch(viewport_loop())
    listen.launch(render_loop())
コード例 #9
0
def render_init(w, h):
    globs.cam = {
        "w": w,
        "h": h,
        "projection": None,
    }

    globs.hud_elements = [
        {
            "function": "switchColors",
            "sprite": "assets/hud_switchColors.png",
            "location": {
                "x": 2,
                "y": 12
            },  # world units (1 block = 1x1 world units)
            "size": {
                "x": 16,
                "y": 16
            }  # pixel_width/20, pixel_height/20
        },
        {
            "function": "inventory",
            "sprite": "assets/hud.png",
            "location": {
                "x": 5,
                "y": 12
            },
            "size": {
                "x": 128,
                "y": 16
            }  # pixel_width/20, pixel_height/20
        },
    ]

    listen.launch(viewport_loop())
    listen.launch(render_loop())
コード例 #10
0
def levels_init():
    globs.play_disabled = True

    globs.selected_color = 0
    globs.bgcolor = Vec(0.0, 0.0, 0)

    globs.polydata = {
        "unit_dx": Vec(1, 0),
        "unit_dy": Vec(0, 1),
        "nx": 10,
        "ny": 10,
        "origin": Vec(0, 0),
        "colors": [],
    }

    globs.level_idx = -1
    globs.levels = [
        level1, level2, level0, level5, level4, level3, level7, level6,
        level555555
    ]
    globs.polygons = []

    listen.launch(next_level_loop())
    listen.launch(reset_level_loop())
コード例 #11
0
def hud_init():
    globs.hud_polygons = []
    globs.textboxes = []
    globs.move_count = 0
    # initialize libraries
    init_textbox(w=2000, h=2000)  # dimension of glyph atlas

    listen.launch(update_hud())
    listen.launch(title_screen())
    listen.launch(ending_screen())
コード例 #12
0
def edit_init():

    globs.mode = "grid_edit"
    globs.grid = Grid()

    globs.world_state = "light"
    globs.fpsbox.color = Vec(0, 0, 0, 1.0)
    populate_grid()

    listen.launch(editor_camera_loop())
    listen.launch(editor_key_loop())
    listen.launch(grid_editor_loop())
コード例 #13
0
def play_init():
    # globs.playerarray renders the player
    animator = Animator()
    animator.enqueue(globs.assets["dino-idle-right"],
                     loop=True,
                     label="idle-right")
    globs.playerarray = QuadArray(animator)
    globs.quadarrays.append(globs.playerarray)

    globs.circlearray = QuadArray(globs.assets["circle"])
    globs.quadarrays.append(globs.circlearray)

    globs.boxcounttext = TextBox("IBMPlexSans-Regular.ttf",
                                 size=30,
                                 color=Vec(1, 0, 0),
                                 pos=Vec(globs.cam["w"] - 30, 5, 0.9))
    globs.textboxes.append(globs.boxcounttext)
    globs.boxcounttext.text = "0"
    globs.boxcount = 0

    listen.launch(play_loop())
    listen.launch(escape_loop())
    listen.launch(camera_move_loop())
    listen.launch(play_mouse_loop())
コード例 #14
0
def edit_init():
    globs.mode = "grid_edit"
    listen.launch(grid_editor_loop())
コード例 #15
0
def play_init():
    listen.launch(play_loop())
コード例 #16
0
def play_loop():
    velocities = [Vec(0, 0), Vec(0, 0)]
    dpad = Vec(0, 0)
    listen.launch(dpad_loop(dpad))
    direction = "right"

    collision_radius = 3

    while True:
        events = yield from listen.any(frame=listen.event("on_frame"), )

        if globs.mode != "play": continue
        _, dt = events["frame"]

        for pn in range(len(globs.playerarray.quads)):

            playerpos = globs.playerarray.quads[pn]
            velocity = velocities[pn]

            # is the player touching a wall?
            touch = {
                "bot": Vec(0, -1, 0),
                "left": Vec(-1, 0, 0),
                "right": Vec(1, 0, 0)
            }
            for key in touch:
                found = False
                for (x, y) in grid_positions_nearby(playerpos,
                                                    collision_radius):
                    if squares_intersect(Vec(x, y),
                                         playerpos + touch[key] / 16):
                        if globs.grid[(x, y)] == "terrain-top":
                            found = True
                            break
                touch[key] = found  # replace dict entry with boolean
            print(touch)

            if touch["bot"]:
                # if upstream of obstacle, make the vertical velocity 0
                velocity.y = 0

            else:
                # otherwise apply downstream current
                if velocity.y <= 1:
                    velocity.y -= 5 * dt

            # horizontal movement
            velocity.x = dpad.x * 3

            for (x, y) in grid_positions_nearby(playerpos, collision_radius):
                if rect_in_rect(Vec(x, y), playerpos, Vec(1, 1), Vec(1, 1)):
                    if globs.grid[(x, y)] == "terrain-side-right":
                        if velocity.x <= 5:
                            velocity.x += 1 * dt
                    if globs.grid[(x, y)] == "terrain-side-left":
                        if velocity.x >= -5:
                            velocity.x -= 1 * dt

            # bonk on sides
            if touch["right"] and velocity.x > 0: velocity.x = 0
            if touch["left"] and velocity.x < 0: velocity.x = 0

            # compute the delta, and apply it with collision detection
            delta = velocity * dt

            # move the player. split the delta into lots of tiny nudges
            # and then apply as many as you can before we collide
            for nudge in split_delta(delta, 1 / 16):
                any_collisions = False
                for (x, y) in globs.grid:
                    if globs.grid[x, y] == "terrain-top": continue
                    if squares_intersect(Vec(x, y), playerpos + nudge.xy0):
                        any_collisions = True
                        break

                if any_collisions: break
                playerpos += nudge.xy0

        # finalize playerpos
        globs.playerarray.update()

        # adjust the player sprite animation
        # compute the new label
        newlabel = "idle"
        if touch["bot"]:
            if velocity.x != 0: newlabel = "sneak"
            else: newlabel = "idle"
        else: newlabel = "move"

        # compute the direction the player is facing
        if velocity.x != 0:
            if velocity.x > 0: direction = "right"
            else: direction = "left"
        newlabel += "-" + direction

        # update the animator
        if globs.playerarray.asset.label != newlabel:
            globs.playerarray.asset.clear()
            globs.playerarray.asset.enqueue(globs.assets["dino-" + newlabel],
                                            loop=True,
                                            label=newlabel)
コード例 #17
0
def play_loop():
    velocity = Vec(0, 0)
    dpad = Vec(0, 0)
    listen.launch(dpad_loop(dpad))
    direction = "right"

    while True:
        events = yield from listen.any(frame=listen.event("on_frame"), )
        # only allow play mode
        if globs.mode != "play": continue
        _, dt = events["frame"]

        playerpos = globs.playerarray.quads[0]

        center_camera(playerpos.x, playerpos.y)

        # is the player touching something?
        touch = {
            "top": Vec(0, 1, 0),
            "bot": Vec(0, -1, 0),
            "left": Vec(-1, 0, 0),
            "right": Vec(1, 0, 0)
        }
        for key in touch:
            found = False
            for (x, y) in globs.grid:
                if squares_intersect(Vec(x, y), playerpos + touch[key] / 16):
                    found = True
                    break
            touch[key] = found  # replace dict entry with boolean

        if touch["bot"]:
            # if grounded, make the vertical velocity 0
            velocity.y = 0

            # if the player is pressing up, make them jump
            if dpad.y == 1:
                velocity.y = 5
        else:
            # otherwise apply gravity
            velocity.y -= 5 * dt
            if (velocity.y < 0):  # after peak jump, fall faster
                velocity.y -= 5 * dt

        # head bonk
        if touch["top"] and velocity.y > 0:
            velocity.y = 0

        # horizontal movement
        velocity.x = dpad.x * 3

        # bonk on sides
        if touch["right"] and velocity.x > 0: velocity.x = 0
        if touch["left"] and velocity.x < 0: velocity.x = 0

        # compute the delta, and apply it with collision detection
        delta = velocity * dt

        # move the player. split the delta into lots of tiny nudges
        # and then apply as many as you can before we collide
        for nudge in split_delta(delta, 1 / 16):
            any_collisions = False
            for (x, y) in globs.grid:
                if squares_intersect(Vec(x, y), playerpos + nudge.xy0):
                    any_collisions = True
                    break

            if any_collisions: break
            playerpos += nudge.xy0

        # finalize playerpos
        globs.playerarray.update()

        # adjust the player sprite animation
        # compute the new label
        newlabel = "idle"
        if touch["bot"]:
            if velocity.x != 0: newlabel = "sneak"
            else: newlabel = "idle"
        else: newlabel = "move"

        # compute the direction the player is facing
        if velocity.x != 0:
            if velocity.x > 0: direction = "right"
            else: direction = "left"
        newlabel += "-" + direction

        # update the animator
        if globs.playerarray.asset.label != newlabel:
            globs.playerarray.asset.clear()
            globs.playerarray.asset.enqueue(globs.assets["dino-" + newlabel],
                                            loop=True,
                                            label=newlabel)
コード例 #18
0
def main():
    glfw.init()

    # for windowed windows
    glfw.window_hint(glfw.RESIZABLE, True)

    # opengl options
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6)

    global w
    w = glfw.create_window(800, 600, 'Window Title', None, None)
    glfw.make_context_current(w)

    ####################
    shaderProgram = make_shader_program()
    glUseProgram(shaderProgram)

    vao = glGenVertexArrays(1)
    glBindVertexArray(vao)

    tri_vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, tri_vbo)
    vertices = Vec(0, 0), Vec(0, 1), Vec(1, 1), Vec(1, 0)
    vertices = Vec(*vertices)
    glBufferData(GL_ARRAY_BUFFER, vertices.size, vertices.buffer,
                 GL_STATIC_DRAW)
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    colorUniform = glGetUniformLocation(shaderProgram, "color")
    glUniform4f(colorUniform, 1, 1, 1, 1)
    ###################

    node = PaddingNode(
        vertical="*",
        children=[
            RowsNode(children=[
                RowsNode(children=[
                    HintedNode(width=100, height=300, key="node1"),
                    HintedNode(width=200, height=100, key="node2"),
                    HintedNode(width=150, height=200, key="node3"),
                ])
            ])
        ])

    def fbresize():
        x = None
        while True:
            if x is None: x, y = glfw.get_framebuffer_size(w)
            else: _, x, y = yield from listen.on_framebuffer_size(w)

            # adjust viewport
            glViewport(0, 0, x, y)

            # adjust projection
            projection.set_uniform(shaderProgram, 'projection')
            projection.clear()
            projection.ortho(0, x, 0, y, 0, 100)

            # adjust node
            node_window_fit(node, w)

    listen.launch(fbresize())

    def rectnode(node, color):
        while True:
            yield from node.on_draw()
            colorUniform = glGetUniformLocation(shaderProgram, "color")
            glUniform4f(colorUniform, color.x, color.y, color.z, color.w)

            projection.set_uniform(shaderProgram, 'modelview')

            projection.push()
            projection.translate(node.x, node.y, 0.0)
            projection.scale(node.width, node.height, 1)
            glDrawArrays(GL_TRIANGLE_FAN, 0, 4)
            projection.pop()

    listen.launch(rectnode(node["node1"], Vec(1, 0, 0, 1)))
    listen.launch(rectnode(node["node2"], Vec(0, 1, 0, 1)))
    listen.launch(rectnode(node["node3"], Vec(0, 0, 1, 1)))
    listen.launch(rectnode(node, Vec(0.2, 0.4, 0.3, 1)))

    while not glfw.window_should_close(w):
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClear(GL_COLOR_BUFFER_BIT)

        node.draw()

        glfw.swap_buffers(w)

        glfw.wait_events_timeout(0.01)  # 100 fps
        listen.trigger_timers()

    glfw.terminate()
コード例 #19
0
def main():
    glfw.init()

    glfw.window_hint(glfw.RESIZABLE, False)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6)

    w, h = 800, 640
    globs.h = h
    globs.w = w

    globs.window = glfw.create_window(w, h, 'Polygon', None, None)
    x = glfw.make_context_current(globs.window)

    init_polygon_shader()

    # flood-fill colors
    globs.colors = [
        Vec(1.0, 0.0, 1.0, 1.0),
        Vec(1.0, 1.0, 1.0, 1.0),
        Vec(0.5, 0.5, 1.0, 1.0),
        Vec(0.0, 1.0, 1.0, 1.0)
    ]
    globs.colorIndex = 0
    # data to scale and shape the triangle array
    globs.tri = {}
    globs.tri["i_max"] = 7  # number of columns
    globs.tri["j_max"] = 5  # number of rows
    globs.tri[
        "offsetX"] = 50  # x, y (pixel) position of lower left corner of the array
    globs.tri["offsetY"] = 50
    globs.tri["scaleX"] = 50  # 1/2 the width of a triangle
    globs.tri["scaleY"] = 50  # 1/2 the height of a triangle
    # score
    globs.numberClicksThisLevel = 0

    # this stuff gets rendered by the render_loop
    globs.polygons = []
    #generate arrays
    for i in range(0, globs.tri["i_max"]):
        for j in range(0, globs.tri["j_max"]):
            isStaggered = (j % 2 == 1)
            if not isStaggered:
                p1, p2, p3 = grid_index_to_position(i, j, True)  # upward point
                globs.polygons.append(
                    Polygon(globs.colors[0 if isStaggered else 2],
                            [p1, p2, p3]))
                p1, p2, p3 = grid_index_to_position(i, j,
                                                    False)  # downward point
                globs.polygons.append(
                    Polygon(globs.colors[1 if isStaggered else 3],
                            [p1, p2, p3]))
            else:
                p1, p2, p3 = grid_index_to_position(i, j,
                                                    False)  # downward point
                globs.polygons.append(
                    Polygon(globs.colors[1 if isStaggered else 3],
                            [p1, p2, p3]))
                p1, p2, p3 = grid_index_to_position(i, j, True)  # upward point
                globs.polygons.append(
                    Polygon(globs.colors[0 if isStaggered else 2],
                            [p1, p2, p3]))

    # launch loops (order matters here)
    globs.spf = 0.015  # 60ish fps
    listen.launch(game_loop())

    render_init(w, h)
    edit_init()

    # the main loop.
    while not glfw.window_should_close(globs.window):
        glfw.wait_events_timeout(globs.spf / 10)
        listen.trigger_timers()

    glfw.terminate()
コード例 #20
0
def main():
    glfw.init()

    # Common window hints and their defaults

    glfw.window_hint(glfw.FOCUS_ON_SHOW, True)

    # for windowed windows
    glfw.window_hint(glfw.RESIZABLE, True)
    glfw.window_hint(glfw.VISIBLE, True)
    glfw.window_hint(glfw.DECORATED, True)
    glfw.window_hint(glfw.FOCUSED, True)
    glfw.window_hint(glfw.FLOATING, False)
    glfw.window_hint(glfw.MAXIMIZED, False)

    # for full screen windows
    # To make full screen, pass a monitor as the 5th argument to glfw.create_window,
    # or use glfw.set_window_monitor(w,mon).
    # Auto_iconify means to minimize when focus lost.
    glfw.window_hint(glfw.AUTO_ICONIFY, True)
    glfw.window_hint(glfw.CENTER_CURSOR, True)

    # opengl options
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6)

    glfw.window_hint(glfw.DEPTH_BITS, 24)
    glfw.window_hint(glfw.STENCIL_BITS, 8)

    # transparency
    glfw.window_hint(glfw.TRANSPARENT_FRAMEBUFFER, False)
    # later call glfw.set_window_opacity(w, 0.5)
    # and use glfw.get_window_opacity(w)

    # for X11
    glfw.window_hint_string(glfw.X11_CLASS_NAME, "")
    glfw.window_hint_string(glfw.X11_INSTANCE_NAME, "")

    #####################

    global w
    w = glfw.create_window(800, 600, 'Window Title', None, None)
    glfw.make_context_current(w)

    # glfw.set_window_title(w, "Window Title")

    # controlling window size
    # get/set interchangable
    # glfw.set_window_pos(w, x, y)
    # glfw.set_window_size(w, width, height)
    # glfw.set_window_size_limits(w, minW, minH, maxW, maxH)
    # glfw.set_window_aspect_ratio(w, 16, 9)
    # get only
    # glfw.get_window_frame_size(w)   # with borders and all, get only
    # glfw.get_framebuffer_size(w)    # get only

    # window status
    # glfw.iconify_window(w) / glfw.restore_window(w)
    # glfw.get_window_attrib(w, glfw.ICONIFIED)
    # glfw.maximize_window(w) / glfw.restore_window(w)
    # glfw.get_window_attrib(w, glfw.MAXIMIZED)
    # glfw.hide_window / glfw.show_window
    # glfw.get_window_attrib(w, glfw.VISIBLE)
    # glfw.focus_window(w) or glfw.request_window_attention(w)
    # glfw.get_window_attrib(w, glfw.FOCUSED)
    # glfw.set_window_should_close(w, False)

    # clipboard
    # glfw.get_clipboard_string(w)
    # glfw.set_clipboard_string(w, "hello")

    def clock():
        while True:
            dt = yield from listen.wait(0.2)

    listen.launch(clock())

    ####################
    shaderProgram = make_shader_program()
    glUseProgram(shaderProgram)

    vao = glGenVertexArrays(1)
    glBindVertexArray(vao)

    tri_vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, tri_vbo)
    v1, v2, v3 = Vec(0, 0, 0), Vec(1, 1, 0), Vec(1, 0, 0)
    vertices = Vec(v1, v2, v3)
    glBufferData(GL_ARRAY_BUFFER, vertices.size, vertices.buffer,
                 GL_STATIC_DRAW)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    ###################

    def fbresize():
        x = None
        while True:
            if x is None: x, y = glfw.get_framebuffer_size(w)
            else: _, x, y = yield from listen.on_framebuffer_size(w)

            # adjust viewport
            glViewport(0, 0, x, y)

            # adjust projection
            projection.set_uniform(shaderProgram, "projection")
            projection.clear()
            projection.ortho(0, x, 0, y, 0, 100)

    listen.launch(fbresize())

    import time, math
    t0 = time.time()

    while not glfw.window_should_close(w):
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClear(GL_COLOR_BUFFER_BIT)

        projection.set_uniform(shaderProgram, "modelview")

        projection.push()
        theta = 10 * (time.time() - t0)
        projection.translate(100, 100, 0.0)
        projection.translate(10 * math.sin(theta), 10 * math.cos(theta), 0.0)

        projection.scale(100, 100, 1)
        glDrawArrays(GL_TRIANGLES, 0, 3)
        projection.pop()

        glfw.swap_buffers(w)

        # glfw.poll_events()  # non-blocking
        # glfw.wait_events()  # blocks until an event is received
        # glfw.wait_events_timeout(0.4) # blocks until event or timeout
        # To unblock the main thread from wait_events(), use glfw.post_empty_event()

        glfw.wait_events_timeout(0.01)  # 100 fps
        listen.trigger_timers()

    glfw.terminate()
コード例 #21
0
def play_loop():
    velocity = Vec(0, 0)
    dpad = Vec(0, 0)
    listen.launch(dpad_loop(dpad))
    direction = "right"

    collision_prec = 0.01
    collision_radius = 2

    playersize = globs.playerarray.asset["size"]
    gridsize = Vec(1, 1)

    recent_portal = None

    while True:
        events = yield from listen.any(frame=listen.event("on_frame"), )

        if globs.mode != "play": continue
        _, dt = events["frame"]

        playerpos = globs.playerarray.quads[0]

        # is the player touching something?
        touch = {
            "top": Vec(0, 1, 0),
            "bot": Vec(0, -1, 0),
            "left": Vec(-1, 0, 0),
            "right": Vec(1, 0, 0)
        }
        for key in touch:
            found = False
            for (x, y) in grid_positions_nearby(playerpos, collision_radius):
                if "dark" not in globs.grid[x, y]: continue
                if rects_intersect(Vec(x, y),
                                   playerpos + touch[key] * collision_prec,
                                   gridsize, playersize):
                    found = True
                    break
            touch[key] = found  # replace dict entry with boolean

        if touch["bot"]:
            # if grounded, make the vertical velocity 0
            velocity.y = 0

            # if the player is pressing up, make them jump
            if dpad.y == 1:
                velocity.y = 3
        else:
            # otherwise apply gravity
            velocity.y -= 3 * dt

        # horizontal movement
        velocity.x = dpad.x * 3

        # head bonk
        if touch["top"] and velocity.y > 0:
            velocity.y = 0

        # bonk on sides
        if touch["right"] and velocity.x > 0: velocity.x = 0
        if touch["left"] and velocity.x < 0: velocity.x = 0

        # compute the delta, and apply it with collision detection
        delta = velocity * dt

        # move the player. split the delta into lots of tiny nudges
        # and then apply as many as you can before we collide
        for nudge in split_delta(delta, collision_prec):
            any_collisions = False
            for (x, y) in grid_positions_nearby(playerpos, collision_radius):
                if "dark" not in globs.grid[x, y]: continue
                if rects_intersect(
                        Vec(x, y),
                        playerpos + nudge.xy0,
                        gridsize,
                        playersize,
                ):
                    any_collisions = True
                    break

            if any_collisions: break
            playerpos += nudge.xy0

        # finalize playerpos
        globs.playerarray.update()
        globs.circlearray.quads[0] = Vec(0, 0, 0) + playerpos
        globs.circlearray.quads[0] -= globs.circlearray.asset["size"].xy0 / 2
        globs.circlearray.quads[0] += globs.playerarray.asset["size"].xy0 / 2
        globs.circlearray.update()

        for (x, y) in grid_positions_nearby(playerpos, collision_radius):
            if globs.grid[x, y] != "portal": continue
            if not rect_in_rect(playerpos, Vec(x, y), playersize, gridsize):
                continue
            if (x, y) == recent_portal: continue
            mode_switch()
            velocity = Vec(0, 0)
            recent_portal = (x, y)

        if recent_portal is not None:
            if not rects_intersect(playerpos, Vec(*recent_portal), playersize,
                                   gridsize):
                recent_portal = None

        # adjust the camera if we are not falling
        if touch["bot"]:
            globs.cam["target_pos"] = -playerpos.xy + globs.cam["dims"] / 2

        # adjust the player sprite animation
        # compute the new label
        newlabel = "idle"
        if touch["bot"]:
            if velocity.x != 0: newlabel = "sneak"
            else: newlabel = "idle"
        else: newlabel = "move"

        # compute the direction the player is facing
        if velocity.x != 0:
            if velocity.x > 0: direction = "right"
            else: direction = "left"
        newlabel += "-" + direction

        # update the animator
        if globs.playerarray.asset.label != newlabel:
            globs.playerarray.asset.clear()
            globs.playerarray.asset.enqueue(globs.assets["dino-" + newlabel],
                                            loop=True,
                                            label=newlabel)