示例#1
0
def test_event():
    """Multiple tasks can be blocked on an event."""
    event = Event()

    log = []

    async def event_waiter():
        log.append("event_waiter started")
        await event
        log.append("event_waiter finished")

    do(event_waiter())
    do(event_waiter())

    async def runtest():
        await loop.next_tick()
        log.append(f"Tasks blocked: {len(event)}; setting event")
        event.set()
        log.append(f"Tasks blocked: {len(event)}")
        await loop.next_tick()

    run(runtest())
    assert log == [
        "event_waiter started",
        "event_waiter started",
        "Tasks blocked: 2; setting event",
        "Tasks blocked: 0",
        "event_waiter finished",
        "event_waiter finished",
    ]
示例#2
0
def test_interpolate(clock):
    """We can interpolate a value over multiple frames."""
    vs = []

    async def interpolator():
        async for v in clock.coro.interpolate(1.0, 2.0, duration=0.5):
            vs.append(v)

    do(interpolator())
    run(run_clock(clock, frames=10, framerate=5))
    assert vs == pytest.approx([1.4, 1.8, 2.0])
示例#3
0
def test_await_seconds(clock):
    """We can iterate over a sequence of frames, in seconds."""
    ts = []

    async def multi_frame_waiter():
        async for t in clock.coro.frames(seconds=1.0):
            ts.append(t)

    do(multi_frame_waiter())
    run(run_clock(clock, frames=10, framerate=5))
    assert ts == pytest.approx([0.2, 0.4, 0.6, 0.8, 1.0])
示例#4
0
def test_await_frames(clock):
    """We can iterate over a sequence of frames."""
    ts = []

    async def multi_frame_waiter():
        async for t in clock.coro.frames(frames=3):
            ts.append(t)

    do(multi_frame_waiter())
    run(run_clock(clock, frames=3, framerate=10))

    assert ts == pytest.approx([0.1, 0.2, 0.3])
示例#5
0
def test_next_frame(clock):
    """We can await the very next frame."""
    dt = None

    async def frame_waiter():
        nonlocal dt
        dt = await clock.coro.next_frame()

    clock.coro.run(frame_waiter())
    assert dt is None
    run(run_clock(clock, frames=1))
    assert dt == 1 / 60
示例#6
0
def test_schedule(clock):
    """We can schedule a coroutine."""
    v = None

    async def set_v(val):
        nonlocal v
        await clock.coro.sleep(0.1)
        v = val

    do(set_v(3))

    assert v is None
    run(run_clock(clock, frames=10))
    assert v == 3
示例#7
0
def test_cancel(clock):
    """We can cancel a task."""
    ts = []

    async def multi_frame_waiter():
        try:
            async for t in clock.coro.frames():
                ts.append(t)
        except clock.coro.Cancelled:
            ts.append('cancelled')

    async def start_cancel():
        task = do(multi_frame_waiter())
        await loop.next_tick()  # Allow task to start and block on clock
        clock.tick(0.1)
        await loop.next_tick()  # Allow task to run one loop
        task.cancel()
        await loop.next_tick()  # Allow task to cancel

    run(start_cancel())
    assert ts == [0.1, 'cancelled']
示例#8
0
文件: memory.py 项目: tjguk/wasabi2d
    # hide cards after a timeout
    for pos in STATUS:
        board[pos[0]][pos[1]].flip()
    del STATUS[:]


@event
def on_mouse_down(pos, button):
    if len(STATUS) == 2:  # ignore until timeout redisplays
        return
    if button == mouse.LEFT and (pos):
        # not sure why "and (pos)" - especially the parens!
        coords = findTile(pos)
        if coords in ignore:  # has already been matched
            return
        board[coords[0]][coords[1]].flip()
        if coords not in STATUS:
            STATUS.append(coords)  # now they are

            if len(STATUS) == 1:  # 1st click - turn not yet over
                pass
            elif len(STATUS) == 2:  # 2nd click - check for match
                (x1, y1), (x2, y2) = STATUS  # an "unpacking assignment"
                if board[x1][y1].title == board[x2][y2].title:
                    success()
                else:
                    failure()


run()
示例#9
0
def on_joybutton_up(joy, button):
    print("Button %s up on joystick %s" % (button, joy))


def sanitise_axis(value):
    # make a small 'dead spot' in the middle or we'll drift
    if -0.05 < value < 0.05:
        return 0
    else:
        return value


# NB: Add the following to wasabi2d's game.py, line 61 if necessary:
#       'on_joyaxis_motion': pygame.JOYAXISMOTION,


@w2d.event
def on_joyaxis_motion(joy, axis, value):
    stick = controllers[joy]
    print("Movement on joystick %s: joy %s, axis: %s, value: %s" %
          (stick, joy, axis, value))

    if axis == 0:
        alien.speed[0] = sanitise_axis(value) * ALIEN_SPEED

    if axis == 1:
        alien.speed[1] = sanitise_axis(value) * ALIEN_SPEED


w2d.run()
示例#10
0
    PLACED = 2  # die was chosen and place, please throw
    DONE = 3  # no more rolls or placements, passive plays


state = State.THROWN


@w.event
def on_mouse_down(pos):
    global state, dice, silver, fixed
    if state == State.THROWN:
        if click_die_then_field(pos):
            if len(fixed.dice) == 3 or len(dice.dice) < 1:
                state = State.DONE
                dice.clear()
                fixed.clear()
                silver.clear()
                dice = Dice(scene.layers[20])
                fixed = None
                silver = None
                state = State.THROWN
                print('------------------')
                print('fixed', fixed, 'and dice', dice)
            else:
                state = State.PLACED
                dice.throw()
                state = State.THROWN


w.run()
示例#11
0
    )

    # Twist phase
    await clock.coro.sleep(0.1)

    # Collapse phase
    await animate(
        sprite,
        duration=0.5,
        scale=1,
        color=(0, 0, 0, 0),
    )

    # Delete it again
    sprite.delete()


async def spawn_explosions():
    """Continue spawning explosions."""
    while True:
        px = random.uniform(50, scene.width - 50)
        py = random.uniform(50, scene.height - 50)
        do(explode((px, py)))
        await clock.coro.sleep(random.uniform(0.5, 3))


if __name__ == '__main__':
    scene = w2d.Scene()
    scene.background = '#ccddff'
    w2d.run(spawn_explosions())
示例#12
0
                  duration=0.1,
                  scale=10,
                  tween='accelerate',
                  color=(*color, 0))
    e.delete()


@w2d.event
def on_mouse_move(pos):
    global target
    cursor.pos = pos
    target = vec2(pos)


async def spawn_baddies():
    async with w2d.Nursery() as ns:
        ns.do(enemy())
        for _ in range(5):
            await clock.coro.sleep(2)
            ns.do(enemy())

    scene.layers[0].add_label("The End",
                              align="center",
                              fontsize=48,
                              color='#88ccff',
                              pos=center)
    await clock.coro.sleep(5)


w2d.run(spawn_baddies())
示例#13
0
scene = w2d.Scene()

particles = scene.layers[0].add_particle_group(
    max_age=2,
    grow=0.1,
)


async def particle_spray():
    ev = await w2d.next_event(pygame.MOUSEBUTTONDOWN)
    emitter = particles.add_emitter(pos=ev.pos,
                                    rate=50,
                                    color='cyan',
                                    size=6,
                                    vel_spread=30)
    async for ev in w2d.events.subscribe(pygame.MOUSEMOTION,
                                         pygame.MOUSEBUTTONUP):
        if ev.type == pygame.MOUSEBUTTONUP:
            emitter.delete()
            return
        else:
            emitter.pos = ev.pos


async def main():
    while True:
        await particle_spray()


w2d.run(main())
示例#14
0
 def run(self) -> None:
     assert self.stack, "Nothing to do, no controllers set up"
     event(self.update)
     event(self.on_key_down)
     run()
示例#15
0
    if key == key.F12:
        if mod & SHIFT:
            game.scene.toggle_recording()
        else:
            game.scene.screenshot()



# reminder:
#
# (0, 0) is the upper left
#
# (0, 0)---------------------------+
# |                                |
# |                                |
# |                                |
# |                                |
# |                                |
# |                                |
# |                                |
# +----------------------(1024, 768)

settings = load_settings()
init_sound(settings)
init_controls(settings)

game = Game(settings, "larry")
level = game.new()

run()  # keep this at the end of the file