Exemple #1
0
def run():
    # You know those from the helloworld.py example.
    # Initialize the video subsystem, create a window and make it visible.
    video.init()
    window = video.Window("Pixel Access", size=(800, 600))
    window.show()

    spritefactory = video.SpriteFactory(video.SOFTWARE)
    uifactory = video.UIFactory(spritefactory)

    # Since all gui elements are sprites, we can use the SpriteRenderer
    # class, we learned about in helloworld.py, to draw them on the
    # Window.
    renderer = spritefactory.create_sprite_renderer(window)

    # Create a new UIProcessor, which will handle the user input events
    # and pass them on to the relevant user interface elements.
    uiprocessor = video.UIProcessor()

    # Create a scene manager - this one will take care of managing the
    # different scenes.
    scenemanager = SceneManager()
    # Every time we switch to a different scene, reset the video window, so
    # we do not have any artifacts left on the screen.
    scenemanager.switched += lambda mgr: video.fill(renderer.surface, 0x0)

    # Create the initial scene.
    mainmenu = Scene("Main Menu")

    # We need the uifactory to create buttons for the different scenes.
    mainmenu.uifactory = uifactory

    # Bind the start and end events of the scene. started() will be invoked
    # every time the SceneManager starts the scene. ended() will be invoked,
    # if the scene ends, e.g. if a new scene is pushed to the manager.
    mainmenu.started += start_mainmenu
    mainmenu.ended += end_scene

    # Push the initial scene to the SceneManager.
    scenemanager.push(mainmenu)

    running = True
    while running:
        # Process the SceneManager. This takes care of updating the scene
        # states by checking, if a new scene has to be displayed or not.
        scenemanager.update()
        # The main event loop; we already learned about that in other examples.
        # Check for the events and pass them around.
        for event in video.get_events():
            if event.type == sdlevents.SDL_QUIT:
                running = False
                break
            # Pass the SDL2 events to the UIProcessor, which takes care of
            # the user interface logic.
            uiprocessor.dispatch(scenemanager.current.components, event)
        # Render all components on all scenes.
        renderer.render(scenemanager.current.components)
        window.refresh()
    video.quit()
    return 0
Exemple #2
0
def run():
    video.init()
    window = video.Window("The Pong Game", size=(800, 600))
    window.show()

    factory = video.SpriteFactory(video.SOFTWARE)
    # For hardware acceleration, comment out the above line and uncomment the
    # next two lines
    #
    # renderer = video.RenderContext(window)
    # factory = video.SpriteFactory(video.TEXTURE, renderer=renderer)
    #

    # Create the paddles - we want white ones. To keep it easy enough for us,
    # we create a set of surfaces that can be used for Texture- and
    # Software-based sprites.
    sp_paddle1 = factory.from_color(WHITE, size=(20, 100))
    sp_paddle2 = factory.from_color(WHITE, size=(20, 100))
    sp_ball = factory.from_color(WHITE, size=(20, 20))

    world = World()

    movement = MovementSystem(0, 0, 800, 600)
    collision = CollisionSystem(0, 0, 800, 600)
    aicontroller = TrackingAIController(0, 600)
    if factory.sprite_type == video.SOFTWARE:
        spriterenderer = SoftwareRenderer(window)
    else:
        spriterenderer = TextureRenderer(renderer)

    world.add_system(aicontroller)
    world.add_system(movement)
    world.add_system(collision)
    world.add_system(spriterenderer)

    player1 = Player(world, sp_paddle1, 0, 250)
    player2 = Player(world, sp_paddle2, 780, 250, True)
    ball = Ball(world, sp_ball, 390, 290)
    ball.velocity.vx = -BALL_SPEED
    collision.ball = ball
    aicontroller.ball = ball

    running = True
    while running:
        for event in video.get_events():
            if event.type == sdlevents.SDL_QUIT:
                running = False
                break
            if event.type == sdlevents.SDL_KEYDOWN:
                if event.key.keysym.sym == sdlkc.SDLK_UP:
                    player1.velocity.vy = -PADDLE_SPEED
                elif event.key.keysym.sym == sdlkc.SDLK_DOWN:
                    player1.velocity.vy = PADDLE_SPEED
            elif event.type == sdlevents.SDL_KEYUP:
                if event.key.keysym.sym in (sdlkc.SDLK_UP, sdlkc.SDLK_DOWN):
                    player1.velocity.vy = 0
        sdltimer.delay(10)
        world.process()
Exemple #3
0
def run():
    # Initialize the video system - this implicitly initializes some
    # necessary parts within the SDL DLL used by the video module.
    #
    # You SHOULD call this before using any video related methods or
    # classes.
    video.init()

    # Create a new window (like your browser window or editor window,
    # etc.) and give it a meaningful title and size. We definitely need
    # this, if we want to present something to the user.
    window = video.Window("Hello World!", size=(592, 460))

    # By default, every Window is hidden, not shown on the screen right
    # after creation. Thus we need to tell it to be shown now.
    window.show()

    factory = video.SpriteFactory(video.SOFTWARE)
    # If you want hardware-accelerated rendering, use video.TEXTURE instead
    # and pass a renderer along:
    #
    # renderer = video.RenderContext(window)
    # factory = video.SpriteFactory(video.TEXTURE, renderer=renderer)
    #

    # Creates a simple rendering system for the Window. The
    # SpriteRenderer can draw Sprite objects on the window.
    spriterenderer = factory.create_sprite_renderer(window)

    # Creates a new 2D pixel-based surface to be displayed, processed or
    # manipulated. We will use the one of the shipped example images
    # from the resource package to display.
    sprite = factory.from_image(RESOURCES.get_path("hello.bmp"))

    # Display the surface on the window. This will copy the contents
    # (pixels) of the surface to the window. The surface will be
    # displayed at surface.position on the window. Play around with the
    # surface.x and surface.y values or surface.position (which is just
    # surface.x and surface.y grouped as tuple)!
    spriterenderer.render(sprite)

    # Set up an example event loop processing system. This is a necessity,
    # so the application can exit correctly, mouse movements, etc. are
    # recognised and so on. The TestEventProcessor class is just for
    # testing purposes and does not do anything meaningful.  Take a look
    # at its code to better understand how the event processing can be
    # done and customized!
    processor = video.TestEventProcessor()

    # Start the event processing. This will run in an endless loop, so
    # everything following after processor.run() will not be executed
    # before some quitting event is raised.
    processor.run(window)

    # We called video.init(), so we have to call video.quit() as well to
    # release the resources hold by the SDL DLL.
    video.quit()
Exemple #4
0
def run():
    # You know those from the helloworld.py example.
    # Initialize the video subsystem, create a window and make it visible.
    video.init()
    window = video.Window("Pixel Access", size=(800, 600))
    window.show()

    # As in colorpalettes.py, explicitly acquire the window's surface to
    # draw on.
    windowsurface = window.get_surface()

    # We implement the functionality as it was done in colorpalettes.py and
    # utilise a mapping table to look up the function to be executed, together
    # with the arguments they should receive
    functions = ((draw_horizontal_stripes, (windowsurface, 300, 500, 200, 400)),
                 (draw_vertical_stripes, (windowsurface, 300, 500, 200, 400)),
                 )

    # A storage variable for the function we are currently on, so that we know
    # which function to execute next.
    curindex = 0

    # The event loop is nearly the same as we used in colorpalettes.py. If you
    # do not know, what happens here, take a look at colorpalettes.py for a
    # detailled description.
    running = True
    while running:
        events = video.get_events()
        for event in events:
            if event.type == sdlevents.SDL_QUIT:
                running = False
                break
            if event.type == sdlevents.SDL_MOUSEBUTTONDOWN:
                curindex += 1
                if curindex >= len(functions):
                    curindex = 0
                # In contrast to colorpalettes.py, our mapping table consists
                # of functions and their arguments. Thus, we get the currently
                # requested function and argument tuple and execute the
                # function with the arguments.
                func, args = functions[curindex]
                func(*args)
                break
        window.refresh()
    video.quit()
    return 0
Exemple #5
0
 def test_init_quit(self):
     video.init()
     self.assertEqual(sdl.was_init(sdl.SDL_INIT_VIDEO), sdl.SDL_INIT_VIDEO)
     video.quit()
     self.assertNotEqual(sdl.was_init(sdl.SDL_INIT_VIDEO), sdl.SDL_INIT_VIDEO)
     video.init()
     video.init()
     video.init()
     self.assertEqual(sdl.was_init(sdl.SDL_INIT_VIDEO), sdl.SDL_INIT_VIDEO)
     video.quit()
     self.assertNotEqual(sdl.was_init(sdl.SDL_INIT_VIDEO), sdl.SDL_INIT_VIDEO)
     video.quit()
     video.quit()
     video.quit()
     self.assertNotEqual(sdl.was_init(sdl.SDL_INIT_VIDEO), sdl.SDL_INIT_VIDEO)
Exemple #6
0
 def setUp(self):
     if sys.version.startswith("3.1"):
         self.assertIsInstance = \
             lambda x, t: self.assertTrue(isinstance(x, t))
     video.init()
Exemple #7
0
def run():
    # Create the environment, in which our particles will exist.
    world = World()

    # Set up the globally available information about the current mouse
    # position. We use that information to determine the emitter
    # location for new particles.
    world.mousex = 400
    world.mousey = 300

    # Create the particle engine. It is just a simple System that uses
    # callback functions to update a set of components.
    engine = particles.ParticleEngine()

    # Bind the callback functions to the particle engine. The engine
    # does the following on processing:
    # 1) reduce the life time of each particle by one
    # 2) create a list of particles, which's life time is 0 or below.
    # 3) call createfunc() with the world passed to process() and
    #    the list of dead particles
    # 4) call updatefunc() with the world passed to process() and the
    #    set of particles, which still are alive.
    # 5) call deletefunc() with the world passed to process() and the
    #    list of dead particles. deletefunc() is respsonible for
    #    removing the dead particles from the world.
    engine.createfunc = createparticles
    engine.updatefunc = updateparticles
    engine.deletefunc = deleteparticles
    world.add_system(engine)

    # We create all particles at once before starting the processing.
    # We also could create them in chunks to have a visually more
    # appealing effect, but let's keep it simple.
    createparticles(world, None, 300)

    # Initialize the video subsystem, create a window and make it visible.
    video.init()
    window = video.Window("Particles", size=(800, 600))
    window.show()

    renderer = video.RenderContext(window)
    factory = video.SpriteFactory(video.TEXTURE, renderer=renderer)

    # Create a set of images to be used as particles on rendering. The
    # images are used by the ParticleRenderer created below.
    images = (factory.from_image(RESOURCES.get_path("circle.png")),
              factory.from_image(RESOURCES.get_path("square.png")),
              factory.from_image(RESOURCES.get_path("star.png"))
              )

    # Center the mouse on the window. We use the SDL2 functions directly
    # here. Since the SDL2 functions do not know anything about the
    # video.Window class, we have to pass the window's SDL_Window to it.
    sdlmouse.warp_mouse_in_window(window.window, world.mousex, world.mousey)

    # Hide the mouse cursor, os it does not show up - just show the
    # particles.
    sdlmouse.show_cursor(False)

    # Create the rendering system for the particles. This is somewhat
    # similar to the SoftSpriteRenderer, but since we only operate with
    # hundreds of particles (and not sprites with all their overhead),
    # we need an own rendering system.
    particlerenderer = ParticleRenderer(renderer, images)
    world.add_system(particlerenderer)

    # The almighty event loop. You already know several parts of it.
    running = True
    while running:
        for event in video.get_events():
            if event.type == sdlevents.SDL_QUIT:
                running = False
                break

            if event.type == sdlevents.SDL_MOUSEMOTION:
                # Take care of the mouse motions here. Every time the
                # mouse is moved, we will make that information globally
                # available to our application environment by updating
                # the world attributes created earlier.
                world.mousex = event.motion.x
                world.mousey = event.motion.y
                # We updated the mouse coordinates once, ditch all the
                # other ones. Since world.process() might take several
                # milliseconds, new motion events can occur on the event
                # queue (10ths to 100ths!), and we do not want to handle
                # each of them. For this example, it is enough to handle
                # one per update cycle.
                sdlevents.flush_event(sdlevents.SDL_MOUSEMOTION)
                break
        world.process()

    video.quit()
    return 0
Exemple #8
0
def run():
    # You know those from the helloworld.py example.
    # Initialize the video subsystem, create a window and make it visible.
    video.init()
    window = video.Window("Color Palettes", size=(800, 600))
    window.show()

    # Explicitly acquire the window's surface to draw on. We used the
    # SpriteRenderer class in helloworld.py, which did the drawing magic for
    # us. Now we will do it ourselves, so we have to get a surface to draw on.
    # NOTE: if you intend to use textures or the SDL renderers, you must not
    # use the method.
    windowsurface = window.get_surface()

    # A simple mapping table for the builtin color palettes. We will use
    # the table to look up the color palette to draw an the title to set below.
    palettes = (
        ("Mono Palette", colorpalettes.MONOPALETTE),
        ("2-bit Gray Palette", colorpalettes.GRAY2PALETTE),
        ("4-bit Gray Palette", colorpalettes.GRAY4PALETTE),
        ("8-bit Gray Palette", colorpalettes.GRAY8PALETTE),
        ("3-bit RGB Palette", colorpalettes.RGB3PALETTE),
        ("CGA Palette", colorpalettes.CGAPALETTE),
        ("EGA Palette", colorpalettes.EGAPALETTE),
        ("VGA Palette", colorpalettes.VGAPALETTE),
        ("Web Palette", colorpalettes.WEBPALETTE),
        )

    # A storage variable for the palette we are currently on, so that we know
    # which palette to draw next.
    curindex = 0

    # Since it is not that nice to have a black window right at the start of
    # the application, we will set the window's title to the first entry
    # of our mapping tables. Afterwards, we will draw the matching palette
    # to the window surface.
    window.title = palettes[0][0]
    draw_palette(windowsurface, palettes[0][1])

    # The event loop. In helloworld.py we used the TestEventProcessor class,
    # since there was not much to do. Now however, we want to react on the user
    # input. Every time the user clicks around in our window, we want to
    # show the next palette. Once we reached the last palette within the
    # mapping table, we will start again with the first one.
    running = True
    while running:
        # This will check for any events that piled up since the last check.
        # If one or multiple events were  found (such as a click, a mouse
        # movement, keyboard input, etc.), we will retrieve them.
        events = video.get_events()

        # In case there was no event, we do not need to do anything. This
        # might happen, if  e.g. the user works with another application. Since
        # poll_event() does not wait for an event to occur (that'd mean your
        # application blocks until there is an event), we have to handle
        # this.
        for event in events:
            # The received events can contain different information. There
            # might be mouse movements, clicks, keyboard hits and many more.
            # All of those carry different information. A mouse movement will
            # contain the mouse cursor position, while a keyoard hit will
            # contain the key that was pressed. Depending on that, we need to
            # handle the occured event in a different way, which is done here.
            #
            # In case of a special QUIT event, the user wants to quit the
            # application, just as you are used to closing an editor.
            # If the user wants to quit the application, we should let him do
            # so.  This is done by breaking out of the while loop.
            if event.type == sdlevents.SDL_QUIT:
                running = False
                break

            # We received a mouse button press event. As you can see from the
            # type, the user pressed the mouse button, but did not necesarily
            # release  it. As such, it is not a typical click, but only 50% of
            # it, which is sufficient for our case here.
            if event.type == sdlevents.SDL_MOUSEBUTTONDOWN:
                # If the user pressed the button, we want to draw the next
                # palette and update the window title accordingly. We do this
                # by increasing the storage variable and - in case it reached
                # the last entry, set it back to the first entry.
                curindex += 1
                if curindex >= len(palettes):
                    curindex = 0
                window.title = palettes[curindex][0]
                draw_palette(windowsurface, palettes[curindex][1])
                # If we found a single click (there might be many more)
                # we will break out of checking the rest of events.
                # Improved implementations could use the type= argument
                # for video.get_events() to filter specific events and
                # ignore anything else.
                break

        # Once the events were properly handled, we will refresh the window,
        # since it might have happened that the user moved the window around,
        # pressed a button or did something else. In all those cases, we want
        # the palettes to be shown, so we need to refresh the window. This will
        # cause the  window internally to copy its surface information (those
        # we used to draw the palette on) to the screen, where the window
        # currently is  placed on.
        # Comment this line out to see what happens!
        window.refresh()

    # As for helloworld.py, we have to call video.quit(), since we also
    # called video.init().
    video.quit()
    return 0
Exemple #9
0
def run():
    # You know those from the helloworld.py example.
    # Initialize the video subsystem, create a window and make it visible.
    video.init()
    window = video.Window("UI Elements", size=(800, 600))
    window.show()

    spritefactory = video.SpriteFactory(video.SOFTWARE)
    # If you want hardware-accelerated rendering, use video.TEXTURE instead
    # and pass a renderer along:
    #
    # renderer = video.RenderContext(window)
    # factory = video.SpriteFactory(video.TEXTURE, renderer=renderer)
    #

    # Create a UI factory, which will handle several defaults for
    # us. Also, the UIFactory can utilises software-based UI elements as
    # well as hardware-accelerated ones; this allows us to keep the UI
    # creation code clean.
    uifactory = video.UIFactory(spritefactory)

    # Create a simple Button sprite, which reacts on mouse movements and
    # button presses and fill it with a white color. All UI elements
    # inherit directly from the TextureSprite (for TEXTURE) or SoftwareSprite
    # (for SOFTWARE), so everything you can do with those classes is also
    # possible for the UI elements.
    button = uifactory.from_image \
        (video.BUTTON, RESOURCES.get_path("button.bmp"))
    button.position = 50, 50

    # Create a TextEntry sprite, which reacts on keyboard presses and
    # text input.
    entry = uifactory.from_image \
        (video.TEXTENTRY, RESOURCES.get_path("textentry.bmp"))
    entry.position = 50, 200

    # Create a CheckButton sprite. The CheckButton is a specialised
    # Button, which can switch its state, identified by the 'checked'
    # attribute by clicking.
    checkbutton = uifactory.from_image \
        (video.CHECKBUTTON, RESOURCES.get_path("button.bmp"))
    checkbutton.position = 200, 50

    # Bind some actions to the button's event handlers. Whenever a click
    # (combination of a mouse button press and mouse button release), the
    # onclick() function will be called.
    # Whenever the mouse moves around in the area occupied by the button, the
    # onmotion() function will be called.
    # The event handlers receive the issuer of the event as first argument
    # (the button is the issuer of that event) and the SDL event data as second
    # argument for further processing, if necessary.
    button.click += onclick
    button.motion += onmotion

    # Bind some actions to the entry's event handlers. The TextEntry
    # receives input events, once it has been activated by a mouse
    # button press on its designated area. The UIProcessor class takes
    # care of this internally through its activate() method.  If the
    # TextEntry is activated, SDL_TEXTINPUT events are enabled by the
    # relevant SDL2 functions, causing input events to occur, that are
    # handled by the TextEntry.
    entry.input += oninput
    entry.editing += onedit

    # Since all gui elements are sprites, we can use the
    # SpriteRenderer class, we learned about in helloworld.py, to
    # draw them on the Window.
    spriterenderer = spritefactory.create_sprite_renderer(window)

    # Create a new UIProcessor, which will handle the user input events
    # and pass them on to the relevant user interface elements.
    uiprocessor = video.UIProcessor()

    running = True
    while running:
        events = video.get_events()
        for event in events:
            if event.type == sdlevents.SDL_QUIT:
                running = False
                break
            # Pass the SDL2 events to the UIProcessor, which takes care of
            # the user interface logic.
            uiprocessor.dispatch([button, checkbutton, entry], event)
            event = sdlevents.poll_event(True)

        # Render all user interface elements on the window.
        spriterenderer.render((button, entry, checkbutton))

    video.quit()
    return 0