def run(): sdl2ext.init() window = sdl2ext.Window("The Pong Game", size=(800, 600)) window.show() if "-hardware" in sys.argv: print("Using hardware acceleration") renderer = sdl2ext.RenderContext(window) factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) else: print("Using software rendering") factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) # 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 == sdl2ext.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 sdl2ext.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.SDL_Delay(10) world.process()
def test_SpriteFactory(self): factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) assert isinstance(factory, sdl2ext.SpriteFactory) assert factory.default_args == {} factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE, bananas="tasty") assert isinstance(factory, sdl2ext.SpriteFactory) assert factory.default_args == {"bananas": "tasty"} window = sdl2ext.Window("Test", size=(1, 1)) renderer = sdl2ext.Renderer(window) factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) assert isinstance(factory, sdl2ext.SpriteFactory) factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) assert isinstance(factory, sdl2ext.SpriteFactory) assert factory.default_args == {"renderer": renderer} with pytest.raises(ValueError): sdl2ext.SpriteFactory("Test") with pytest.raises(ValueError): sdl2ext.SpriteFactory(-456) with pytest.raises(ValueError): sdl2ext.SpriteFactory(123) with pytest.raises(ValueError): sdl2ext.SpriteFactory(sdl2ext.TEXTURE) dogc()
def main(): #cause I don't want to pass these around global WINDOW, REN, SPRITE_FACTORY, SPRITE_RENDERER, MUSIC SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) WINDOW = ext.Window("Tetromino", size=(WINDOWWIDTH, WINDOWHEIGHT)) REN = ext.Renderer(WINDOW) WINDOW.show() font_file = sysfont.get_font("freesans", sysfont.STYLE_BOLD) font_manager = ext.FontManager(font_file, size=18) #fontmanager=font_manager will be default_args passed to every sprite creation method SPRITE_FACTORY = ext.SpriteFactory(renderer=REN, fontmanager=font_manager, free=True) SPRITE_RENDERER = SPRITE_FACTORY.create_sprite_render_system(WINDOW) sdlmixer.Mix_Init(sdlmixer.MIX_INIT_OGG) sdlmixer.Mix_OpenAudio(22050, sdlmixer.MIX_DEFAULT_FORMAT, 2, 1024) #BEEP1 = sdlmixer.Mix_LoadWAV(b"beep1.ogg") showTextScreen("Tetromino") while True: if random.randint(0, 1) == 0: MUSIC = sdlmixer.Mix_LoadMUS(b"tetrisb.mid") else: MUSIC = sdlmixer.Mix_LoadMUS(b"tetrisc.mid") sdlmixer.Mix_PlayMusic(MUSIC, -1) runGame() sdlmixer.Mix_HaltMusic() showTextScreen("Game Over")
def test_SpriteFactory_create_software_sprite(self): factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) for w in range(0, 100): for h in range(0, 100): for bpp in (1, 4, 8, 12, 15, 16, 24, 32): sprite = factory.create_software_sprite((w, h), bpp) self.assertIsInstance(sprite, sdl2ext.SoftwareSprite) #self.assertRaises(ValueError, factory.create_software_sprite, (-1,-1)) #self.assertRaises(ValueError, factory.create_software_sprite, (-10,5)) #self.assertRaises(ValueError, factory.create_software_sprite, (10,-5)) self.assertRaises(TypeError, factory.create_software_sprite, size=None) self.assertRaises(sdl2ext.SDLError, factory.create_software_sprite, size=(10, 10), bpp=-1) self.assertRaises(TypeError, factory.create_software_sprite, masks=5) self.assertRaises((ArgumentError, TypeError), factory.create_software_sprite, size=(10, 10), masks=(None, None, None, None)) self.assertRaises((ArgumentError, TypeError), factory.create_software_sprite, size=(10, 10), masks=("Test", 1, 2, 3)) dogc()
def run(): # init sdl and get window up sdl2ext.init() window = sdl2ext.Window("Traction Edge RL", size=(800, 600)) window.show() #create hardware accelerated context for drawing on context = sdl2ext.RenderContext(window, index=-1, flags=SDL_RENDERER_ACCELERATED) #create our custom renderer with the context renderer = systems.Renderer(context) # init world world = sdl2ext.World() world.add_system(renderer) # create our sprites factory = sdl2ext.SpriteFactory(sprite_type=sdl2ext.TEXTURE, renderer=context) sp_player = factory.from_color(WHITE, size=(32,32)) #create player player = entities.Creature(world, sp_player, 100, 400) #main loop running = True while running: events = sdl2ext.get_events() for event in events: if event.type == SDL_QUIT: running = False break SDL_Delay(10) world.process() return
def test_fill(self): # TODO: add exceptions and more bounding tests. rects = ((0, 0, 3, 2), (2, 3, 4, 2), (5, -1, 2, 2), (1, 7, 4, 8) ) factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) sprite = factory.create_sprite(size=(10, 10), bpp=32) view = sdl2ext.PixelView(sprite) for rect in rects: sdl2ext.fill(sprite, 0) colorval = sdl2ext.prepare_color(0xAABBCCDD, sprite) sdl2ext.fill(sprite, 0xAABBCCDD, rect) for y, row in enumerate(view): for x, col in enumerate(row): if y >= rect[1] and y < (rect[1] + rect[3]): if x >= rect[0] and x < (rect[0] + rect[2]): self.assertEqual(col, colorval, "color mismatch at (x, y)") else: self.assertEqual(col, 0, "color mismatch at (x, y)") else: self.assertEqual(col, 0, "color mismatch at (x, y)")
def test_pixels2d(self): factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) sprite = factory.create_sprite(size=(5, 10), bpp=32, masks=(0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF)) sdl2ext.fill(sprite, 0x01, (2, 2, 2, 2)) nparray = sdl2ext.pixels2d(sprite)
def test_prepare_color(self): rcolors = ( Color(0, 0, 0, 0), Color(255, 255, 255, 255), Color(8, 55, 110, 220), ) icolors = ( 0x00000000, 0xFFFFFFFF, 0xAABBCCDD, ) scolors = ( "#000", "#FFF", "#AABBCCDD", ) factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) sprite = factory.create_sprite(size=(10, 10), bpp=32, masks=(0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF)) for color in rcolors: c = sdl2ext.prepare_color(color, sprite) self.assertEqual(c, int(color)) for color in icolors: c = sdl2ext.prepare_color(color, sprite) cc = COLOR(color) self.assertEqual(c, int(cc)) for color in scolors: c = sdl2ext.prepare_color(color, sprite) cc = COLOR(color) self.assertEqual(c, int(cc))
def test_SpriteFactory_create_sprite(self): window = sdl2ext.Window("Test", size=(1, 1)) renderer = sdl2ext.Renderer(window) tfactory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) sfactory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) for w in range(0, 100): for h in range(0, 100): for bpp in (1, 4, 8, 12, 15, 16, 24, 32): sprite = sfactory.create_sprite(size=(w, h), bpp=bpp) assert isinstance(sprite, sdl2ext.SoftwareSprite) if w == 0 or h == 0: with pytest.raises(sdl2ext.SDLError): tfactory.create_sprite(size=(w, h)) continue sprite = tfactory.create_sprite(size=(w, h)) assert isinstance(sprite, sdl2ext.TextureSprite) dogc()
def run(): # print sdl2ext.get_image_formats() # return sdl2ext.init() window = sdl2ext.Window("The Pong Game", size=(800, 600)) window.show() world = sdl2ext.World() factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) sp_ball = factory.from_color(WHITE, size=(20, 20)) sp_paddle1 = factory.from_color(WHITE, size=(20, 100)) sp_paddle2 = factory.from_color(WHITE, size=(20, 100)) movement = MovementSystem(0, 0, 800, 600) collision = CollisionSystem(0, 0, 800, 600, 390, 290) aicontroller = TrackingAIController(0, 600) spriterenderer = SoftwareRenderer(window) 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 = -3 collision.ball = ball aicontroller.ball = ball collision.player1 = player1 collision.player2 = player2 running = True while running: events = sdl2ext.get_events() for event in events: if event.type == SDL_QUIT: running = False break if event.type == SDL_KEYDOWN: if event.key.keysym.sym == SDLK_UP: player1.velocity.vy = -3 elif event.key.keysym.sym == SDLK_DOWN: player1.velocity.vy = 3 elif event.type == SDL_KEYUP: if event.key.keysym.sym in (SDLK_UP, SDLK_DOWN): player1.velocity.vy = 0 SDL_Delay(10) world.process() return 0
def test_SpriteFactory_from_image(self): window = sdl2ext.Window("Test", size=(1, 1)) renderer = sdl2ext.Renderer(window) tfactory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) sfactory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) for suffix in ("tif", "png", "jpg"): imgname = RESOURCES.get_path("surfacetest.%s" % suffix) tsprite = tfactory.from_image(imgname) self.assertIsInstance(tsprite, sdl2ext.TextureSprite) ssprite = sfactory.from_image(imgname) self.assertIsInstance(ssprite, sdl2ext.SoftwareSprite) for factory in (tfactory, sfactory): self.assertRaises((ArgumentError, ValueError), factory.from_image, None) #self.assertRaises((IOError, SDLError), # factory.from_image, "banana") if not _ISPYPY: self.assertRaises(ArgumentError, factory.from_image, 12345) dogc()
def test_Renderer_copy(self): surface = SDL_CreateRGBSurface(0, 128, 128, 32, 0, 0, 0, 0).contents sdl2ext.fill(surface, 0x0) renderer = sdl2ext.Renderer(surface) factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) w, h = 32, 32 sp = factory.from_color(0xFF0000, (w, h)) sp.x, sp.y = 40, 50 renderer.copy(sp, (0, 0, w, h), (sp.x, sp.y, w, h)) view = sdl2ext.PixelView(surface) self.check_pixels(view, 128, 128, sp, 0xFF0000, (0x0, )) del view
def test_SpriteFactory_from_surface(self): window = sdl2ext.Window("Test", size=(1, 1)) renderer = sdl2ext.Renderer(window) tfactory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) sfactory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) sf = SDL_CreateRGBSurface(0, 10, 10, 32, 0, 0, 0, 0) tsprite = tfactory.from_surface(sf.contents) self.assertIsInstance(tsprite, sdl2ext.TextureSprite) ssprite = sfactory.from_surface(sf.contents) self.assertIsInstance(ssprite, sdl2ext.SoftwareSprite) SDL_FreeSurface(sf) for factory in (tfactory, sfactory): self.assertRaises((sdl2ext.SDLError, AttributeError, ArgumentError, TypeError), factory.from_surface, None) self.assertRaises((AttributeError, ArgumentError, TypeError), factory.from_surface, "test") # TODO: crashes pypy 2.0 #self.assertRaises((AttributeError, ArgumentError, TypeError), # factory.from_surface, 1234) dogc()
def test_PixelView(self): factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) sprite = factory.create_sprite(size=(10, 10), bpp=32) view = sdl2ext.PixelView(sprite) view[1] = (0xAABBCCDD, ) * 10 rcolor = sdl2ext.prepare_color(0xAABBCCDD, sprite) for index, row in enumerate(view): if index == 1: for col in row: assert col == rcolor else: for col in row: assert col == 0x0
def test_SpriteFactory_from_text(self): sfactory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) fm = sdl2ext.FontManager(RESOURCES.get_path("tuffy.ttf")) # No Fontmanager passed self.assertRaises(KeyError, sfactory.from_text, "Test") # Passing various keywords arguments sprite = sfactory.from_text("Test", fontmanager=fm) self.assertIsInstance(sprite, sdl2ext.SoftwareSprite) sprite = sfactory.from_text("Test", fontmanager=fm, alias="tuffy") self.assertIsInstance(sprite, sdl2ext.SoftwareSprite) # Get text from a texture sprite factory window = sdl2ext.Window("Test", size=(1, 1)) renderer = sdl2ext.Renderer(window) tfactory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer, fontmanager=fm) sprite = tfactory.from_text("Test", alias="tuffy") self.assertIsInstance(sprite, sdl2ext.TextureSprite) dogc()
def test_SpriteFactory(self): factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) self.assertIsInstance(factory, sdl2ext.SpriteFactory) self.assertEqual(factory.default_args, {}) factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE, bananas="tasty") self.assertIsInstance(factory, sdl2ext.SpriteFactory) self.assertEqual(factory.default_args, {"bananas": "tasty"}) window = sdl2ext.Window("Test", size=(1, 1)) renderer = sdl2ext.Renderer(window) factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) self.assertIsInstance(factory, sdl2ext.SpriteFactory) factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) self.assertIsInstance(factory, sdl2ext.SpriteFactory) self.assertEqual(factory.default_args, {"renderer": renderer}) self.assertRaises(ValueError, sdl2ext.SpriteFactory, "Test") self.assertRaises(ValueError, sdl2ext.SpriteFactory, -456) self.assertRaises(ValueError, sdl2ext.SpriteFactory, 123) self.assertRaises(ValueError, sdl2ext.SpriteFactory, sdl2ext.TEXTURE) dogc()
def test_pixels3d(self): factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) sprite = factory.create_sprite(size=(5, 10), bpp=32, masks=(0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF)) sdl2ext.fill(sprite, 0xAABBCCDD, (1, 2, 3, 4)) nparray = sdl2ext.pixels3d(sprite) for x in range(1, 4): for y in range(2, 6): self.assertTrue(numpy.all([nparray[x, y], [0xAA, 0xBB, 0xCC, 0xDD]])) self.assertFalse(numpy.all([nparray[0, 0], [0xAA, 0xBB, 0xCC, 0xDD]])) self.assertFalse(numpy.all([nparray[1, 0], [0xAA, 0xBB, 0xCC, 0xDD]])) self.assertFalse(numpy.all([nparray[0, 1], [0xAA, 0xBB, 0xCC, 0xDD]])) self.assertFalse(numpy.all([nparray[3, 6], [0xAA, 0xBB, 0xCC, 0xDD]])) self.assertFalse(numpy.all([nparray[4, 6], [0xAA, 0xBB, 0xCC, 0xDD]]))
def test_SpriteFactory_create_texture_sprite(self): window = sdl2ext.Window("Test", size=(1, 1)) renderer = sdl2ext.Renderer(window) factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) for w in range(1, 100): for h in range(1, 100): sprite = factory.create_texture_sprite(renderer, size=(w, h)) self.assertIsInstance(sprite, sdl2ext.TextureSprite) del sprite # Test different access flags for flag in (SDL_TEXTUREACCESS_STATIC, SDL_TEXTUREACCESS_STREAMING, SDL_TEXTUREACCESS_TARGET): sprite = factory.create_texture_sprite(renderer, size=(64, 64), access=flag) self.assertIsInstance(sprite, sdl2ext.TextureSprite) del sprite dogc()
def main(): sdl2ext.init() TTF_Init() window = sdl2ext.Window("Text display", size=(800, 600)) window.show() renderer = sdl2ext.RenderContext(window) factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) world = sdl2ext.World() fps = FPSCounter(world, renderer=renderer) spriteRenderer = factory.create_sprite_renderer() fpsController = FPSController() world.add_system(fpsController) world.add_system(spriteRenderer) running = True while running: for event in sdl2ext.get_events(): if event.type == sdlevents.SDL_QUIT: running = False break elif event.type == sdlevents.SDL_USEREVENT: entity = cast(event.user.data1, POINTER(py_object)).contents.value entity.textsprite.text = "FPS: " + str(entity.fps.counter) entity.fps.counter = 0 renderer.clear() world.process() TTF_Quit() sdl2ext.quit() return 0
def run(): # Create the environment, in which our particles will exist. world = sdl2ext.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. sdl2ext.init() window = sdl2ext.Window("Particles", size=(800, 600)) window.show() # Create a hardware-accelerated sprite factory. The sprite factory requires # a rendering context, which enables it to create the underlying textures # that serve as the visual parts for the sprites. renderer = sdl2ext.RenderContext(window) factory = sdl2ext.SpriteFactory(sdl2ext.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 # sdl2.ext.Window class, we have to pass the window's SDL_Window to it. SDL_WarpMouseInWindow(window.window, world.mousex, world.mousey) # Hide the mouse cursor, so it does not show up - just show the # particles. SDL_ShowCursor(0) # 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 sdl2ext.get_events(): if event.type == SDL_QUIT: running = False break if event.type == 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. SDL_FlushEvent(SDL_MOUSEMOTION) break world.process() SDL_Delay(1) sdl2ext.quit() return 0
def test_SpriteFactory_from_object(self): window = sdl2ext.Window("Test", size=(1, 1)) renderer = sdl2ext.Renderer(window) tfactory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) sfactory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)
def run(): # Initialize the video system - this implicitly initializes some # necessary parts within the SDL2 DLL used by the video module. # # You SHOULD call this before using any video related methods or # classes. sdl2ext.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 = sdl2ext.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() # Create a sprite factory that allows us to create visible 2D elements # easily. Depending on what the user chosses, we either create a factory # that supports hardware-accelerated sprites or software-based ones. # The hardware-accelerated SpriteFactory requres a rendering context # (or SDL_Renderer), which will create the underlying textures for us. if "-hardware" in sys.argv: print("Using hardware acceleration") renderer = sdl2ext.RenderContext(window) factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) else: print("Using software rendering") factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) # 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 = sdl2ext.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. sdl2ext.quit()
def run(): # You know those from the helloworld.py example. # Initialize the video subsystem, create a window and make it visible. sdl2ext.init() window = sdl2ext.Window("UI Elements", size=(800, 600)) window.show() # Create a sprite factory that allows us to create visible 2D elements # easily. Depending on what the user chosses, we either create a factory # that supports hardware-accelerated sprites or software-based ones. # The hardware-accelerated SpriteFactory requres a rendering context # (or SDL_Renderer), which will create the underlying textures for us. if "-hardware" in sys.argv: print("Using hardware acceleration") renderer = sdl2ext.RenderContext(window) factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) else: print("Using software rendering") factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) # 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 = sdl2ext.UIFactory(factory) # 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(sdl2ext.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(sdl2ext.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_color(sdl2ext.CHECKBUTTON, RED, size=(50, 50)) 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 checkbutton.click += oncheck checkbutton.factory = factory # 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 = factory.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 = sdl2ext.UIProcessor() running = True while running: events = sdl2ext.get_events() for event in events: if event.type == 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) # Render all user interface elements on the window. spriterenderer.render((button, entry, checkbutton)) sdl2ext.quit() return 0
import sys import os try: import sdl2.ext as sdl2ext except ImportError: import traceback traceback.print_exc() sys.exit(1) from sdl2.ext import Resources RESOURCES = Resources(os.path.dirname(os.path.abspath(__file__)), "resources") sdl2ext.init() window = sdl2ext.Window("Hello World!", size=(640, 480)) window.show() factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) sprite = factory.from_image(RESOURCES.get_path("Hello.png")) sprite_renderer = factory.create_sprite_renderer(window) sprite_renderer.render(sprite) processor = sdl2ext.TestEventProcessor() processor.run(window) sdl2ext.quit()