示例#1
0
def run(linefile):
	sdl2ext.init()
	for line in linefile:
		l = line.split()
		if len(l) == 0:
			pass
		elif l[0] == "pixels":
			xpix = int(l[1])
			ypix = int(l[2])
	window = sdl2ext.Window("Pixel Access", size=(xpix, ypix))
	window.show()
	renderer = sdl2ext.Renderer(window)
	running = True
	while running:
		events = sdl2ext.get_events()
		for event in events:
			if event.type == SDL_QUIT:
				running = False
				break
		with Timer() as t:
			grid = draw.dofile(linefile)
		print "=> elasped grid: %s s" % t.secs
		with Timer() as t:
			draw_pixels(renderer, xpix, ypix, grid)
		print "=> elasped render: %s s" % t.secs
		window.refresh()
	sdl2ext.quit()
	return 0
示例#2
0
def main():
    ext.init()

    #Initialiser l'audio
    Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 1024)

    #Creation de 16 canaux
    #Chaque son doit etre joué sur un canal
    #Avec 16 canaus on peut jouer 16 sons simultanement
    Mix_AllocateChannels(16)

    #charger le sample
    chunk = Mix_LoadWAV(b"quack.wav")

    #jouer le son, on récupere le canal dans lequel le son est joué
    # Mix_PlayChannel(canal, sample, loop)
    # canal : le canal dans lequel on joue le son, -1 = n'importe lequel de libre
    # loop : 0 = joué 1 fois, 2 = joué 3 fois, -1 = joué à l'infini
    channel = Mix_PlayChannel(-1, chunk, -1)

    #Attendre tant que le son est joué
    while(Mix_Playing(channel)):
        SDL_Delay(250)

    #décharger le sample
    Mix_FreeChunk(chunk)

    ext.quit()
示例#3
0
def run(linefile):
	sdl2ext.init()
	for line in linefile:
		l = line.split()
		if len(l) == 0:
			pass
		elif l[0] == "pixels":
			xpix = int(l[1])
			ypix = int(l[2])
	window = sdl2ext.Window("Pixel Access", size=(xpix, ypix))
	window.show()
	windowsurface = window.get_surface()
	running = True
	while running:
		events = sdl2ext.get_events()
		for event in events:
			if event.type == SDL_QUIT:
				running = False
				break
		grid = draw.dofile(linefile)
		draw_pixels(windowsurface, xpix, ypix, grid)
		window.refresh()
	sdl2ext.quit()
	return 0
	'''		
示例#4
0
def run():
    # You know those from the helloworld.py example.
    # Initialize the video subsystem, create a window and make it visible.
    sdl2ext.init()
    TTF_Init()
    window = sdl2ext.Window("2D drawing primitives", size=(800, 600))
    window.show()

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

    fps = FPS(windowsurface)

    # 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_lines, (windowsurface, 800, 600)),
                 (draw_rects, (windowsurface, 800, 600)))

    # A storage variable for the function we are currently on, so that we know
    # which function to execute next.
    curindex = 0
    draw_lines(windowsurface, 800, 600)

    textSurface = TTF_RenderText_Shaded(font,
                                        repr(SDL_GetPerformanceFrequency()),
                                        SDL_Color(255, 255, 255),
                                        SDL_Color(40, 90, 120))

    # 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 = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break
            if event.type == 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
        textSurface = TTF_RenderText_Shaded(
            font, "FPS: " + str(SDL_GetPerformanceFrequency()),
            SDL_Color(255, 255, 255), SDL_Color(40, 90, 120))
        SDL_BlitSurface(textSurface, None, windowsurface, None)
        window.refresh()
    TTF_Quit()
    sdl2ext.quit()
    return 0
示例#5
0
def run():
	# You know those from the helloworld.py example.
	# Initialize the video subsystem, create a window and make it visible.
	sdl2ext.init()
	TTF_Init()
	window = sdl2ext.Window("2D drawing primitives", size=(800, 600))
	window.show()
	

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

	# 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_lines, (windowsurface, 800, 600)),
				 (draw_rects, (windowsurface, 800, 600))
				 )

	# A storage variable for the function we are currently on, so that we know
	# which function to execute next.
	curindex = 0
	draw_lines(windowsurface, 800, 600)
	

	textSurface = TTF_RenderText_Shaded(font, repr(SDL_GetPerformanceFrequency()), SDL_Color(255, 255, 255), SDL_Color(40, 90, 120))
			
	# 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 = sdl2ext.get_events()
		for event in events:
			if event.type == SDL_QUIT:
				running = False
				break
			if event.type == 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
		textSurface = TTF_RenderText_Shaded(font,"FPS: " + str(SDL_GetPerformanceFrequency()), SDL_Color(255, 255, 255), SDL_Color(40, 90, 120))
		SDL_BlitSurface(textSurface, None, windowsurface, None)
		window.refresh()
	TTF_Quit()
	sdl2ext.quit()
	return 0
示例#6
0
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("sdlgfx drawing examples", size=(800, 600))
    window.show()

    # Create a rendering context for the window. The sdlgfx module requires it.
    context = sdl2ext.RenderContext(window)

    # 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_lines, (context, 800, 600)),
                 (draw_circles, (context, 800, 600)),
                 (draw_ellipsis, (context, 800, 600)),
                 (draw_rects, (context, 800, 600)),
                 (draw_trigons, (context, 800, 600)),
                 (draw_polygons, (context, 800, 600)),
                 (draw_mixed, (context, 800, 600))
                 )

    # A storage variable for the function we are currently on, so that we know
    # which function to execute next.
    curindex = 0
    draw_lines(context, 800, 600)

    # 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
    # detailed description.
    running = True
    while running:
        events = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break
            if event.type == 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
        context.present()
    sdl2ext.quit()
    return 0
示例#7
0
def main():
    cabou = False
    clientes = ConnectionManager()

    while not cabou:
        msgs = clientes.skt.recv_multipart()

        if msgs[1] == b'quit':
            cabou = True
        elif msgs[1] == b'create':
            clientes.create(msgs[0], *msgs[2:])
        elif clientes.conexões.get(msgs[0]):
            getattr(clientes, msgs[1].decode('utf-8'))(msgs[0], *msgs[2:])

    sdlx.quit()
示例#8
0
 def test_init_quit(self):
     sdl2ext.init()
     self.assertEqual(SDL_WasInit(SDL_INIT_VIDEO), SDL_INIT_VIDEO)
     sdl2ext.quit()
     self.assertNotEqual(SDL_WasInit(SDL_INIT_VIDEO), SDL_INIT_VIDEO)
     sdl2ext.init()
     sdl2ext.init()
     sdl2ext.init()
     self.assertEqual(SDL_WasInit(SDL_INIT_VIDEO), SDL_INIT_VIDEO)
     sdl2ext.quit()
     self.assertNotEqual(SDL_WasInit(SDL_INIT_VIDEO), SDL_INIT_VIDEO)
     sdl2ext.quit()
     sdl2ext.quit()
     sdl2ext.quit()
     self.assertNotEqual(SDL_WasInit(SDL_INIT_VIDEO), SDL_INIT_VIDEO)
示例#9
0
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("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
    draw_horizontal_stripes(windowsurface, 300, 500, 200, 400)

    # 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 = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break
            if event.type == 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()
    sdl2ext.quit()
    return 0
示例#10
0
 def test_init_quit(self):
     try:
         sdl2ext.init()
     except sdl2ext.SDLError:
         raise pytest.skip('Video subsystem not supported')
     assert SDL_WasInit(SDL_INIT_VIDEO) == SDL_INIT_VIDEO
     sdl2ext.quit()
     assert SDL_WasInit(SDL_INIT_VIDEO) != SDL_INIT_VIDEO
     sdl2ext.init()
     sdl2ext.init()
     sdl2ext.init()
     assert SDL_WasInit(SDL_INIT_VIDEO) == SDL_INIT_VIDEO
     sdl2ext.quit()
     assert SDL_WasInit(SDL_INIT_VIDEO) != SDL_INIT_VIDEO
     sdl2ext.quit()
     sdl2ext.quit()
     sdl2ext.quit()
     assert SDL_WasInit(SDL_INIT_VIDEO) != SDL_INIT_VIDEO
示例#11
0
 def test_init_quit(self):
     try:
         sdl2ext.init()
     except sdl2ext.SDLError:
         raise unittest.SkipTest('Video subsystem not supported')
     self.assertEqual(SDL_WasInit(SDL_INIT_VIDEO), SDL_INIT_VIDEO)
     sdl2ext.quit()
     self.assertNotEqual(SDL_WasInit(SDL_INIT_VIDEO), SDL_INIT_VIDEO)
     sdl2ext.init()
     sdl2ext.init()
     sdl2ext.init()
     self.assertEqual(SDL_WasInit(SDL_INIT_VIDEO), SDL_INIT_VIDEO)
     sdl2ext.quit()
     self.assertNotEqual(SDL_WasInit(SDL_INIT_VIDEO), SDL_INIT_VIDEO)
     sdl2ext.quit()
     sdl2ext.quit()
     sdl2ext.quit()
     self.assertNotEqual(SDL_WasInit(SDL_INIT_VIDEO), SDL_INIT_VIDEO)
示例#12
0
def main():
    global state
    newstate = np.copy(state)
    width = 600
    height = 600
    sdl2ext.init()
    window = sdl2ext.Window('GRIDLEARN', size=(width, height))
    window.show()
    surface = window.get_surface()
    running = True
    begin_tick = begin_time = time.monotonic()
    mousedown = False
    while running:
        now = time.monotonic()
        elapsed = now - begin_time
        events = sdl2ext.get_events()
        for event in events:
            if event.type == SDL_QUIT:
                running = False
                break
            elif event.type == SDL_KEYDOWN:
                if event.key.keysym.sym == 27:
                    running = False
                    break
                elif event.key.keysym.sym == 113:
                    state[:] = 0
            elif event.type == SDL_MOUSEBUTTONDOWN:
                mousedown = True
            elif event.type == SDL_MOUSEBUTTONUP:
                mousedown = False
            elif mousedown and event.type == SDL_MOUSEMOTION:
                print(dir(event.button))
                x, y = event.button.x, event.button.y
                idx = int(x / width * W)
                idy = int(y / height * H)
                state[idy, idx] = 1
                break
        if now - begin_tick > 0.1:
            begin_tick = now
            newstate = update(state, newstate, weights, 0.1)
            newstate, state = state, newstate
            draw(surface, width, height)
            window.refresh()
    sdl2ext.quit()
示例#13
0
def main():
    ext.init()

    # initialisation de la sortie audio
    Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 1024)

    # chargement de la musique
    music = Mix_LoadMUS(b"dead.ogg")

    # On joue la musique
    Mix_PlayMusic(music, -1)

    # On attend 8 secondes
    SDL_Delay(8000)

    # On va directement à la 60eme seconde
    Mix_SetMusicPosition(60.0)

    SDL_Delay(5000)

    # On met la musique en pause
    Mix_PauseMusic()

    SDL_Delay(1000)

    # on reprend la lecture
    Mix_ResumeMusic()

    SDL_Delay(5000)

    # On revient au début de la musique
    Mix_RewindMusic()

    while(not SDL_QuitRequested()):
        SDL_Delay(250)


    # décharger la musique
    Mix_FreeMusic(music)
    ext.quit()
示例#14
0
def main():
    ext.init()
    graphics = Graphics(640, 480)

    TTF_Init()
    font = TTF_OpenFont(b"rebel.ttf", 16)
    if(not font):
        print(TTF_GetError())
    color = SDL_Color(180, 189, 180)


    s = "Un Deux Trois Quatre"
    text = b"Un Deux Trois Quatre"
    text2 = bytes(s, "utf-8")

    surface = TTF_RenderText_Solid(font, text2, color)

    x = 50
    y = 30

    srcRect = SDL_Rect(0, 0, surface.contents.w, surface.contents.h)
    dstRect = SDL_Rect(x, y, surface.contents.w, surface.contents.h)

    texture = SDL_CreateTextureFromSurface(graphics.renderer, surface)
    graphics.blit_surface(texture, srcRect, dstRect)


    while(not SDL_QuitRequested()):
        SDL_Delay(250)
        graphics.flip()



    TTF_CloseFont(font)

    TTF_Quit()
    ext.quit()
示例#15
0
文件: text.py 项目: Rejurhf/Python
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
示例#16
0
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
示例#17
0
    def handle_event(self, event):
        if event.type == SDL_QUIT:
            self.running = False
        elif event.type == SDL_DROPFILE:
            self.clock.tick()
        elif event.type == SDL_KEYDOWN and event.key.repeat == 0:
            if event.key.keysym.sym == SDLK_ESCAPE:
                self.running = False
            elif event.key.keysym.sym == SDLK_F1:
                self.debug_info = not self.debug_info

    def draw(self):
        pass

    def stop(self):
        self.running = False


if __name__ == "__main__":
    ext.init()
    graphics = Graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
    AllSprite.load_sprites(graphics)
    AudioManager.init_audio()
    load_audio()
    FontManager.load_font("ressources/Rebellion.ttf", "rebel", 28)
    FontManager.load_font("ressources/DejaVuSansMono.ttf", "dejavu", 20)
    game = Menu(graphics)
    game.run()
    ext.quit()
示例#18
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()
示例#19
0
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()
示例#20
0
def quit():
    ext.quit()
示例#21
0
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
示例#22
0
import sys,os
import init

try:
    import sdl2.ext as sdl2ext
except ImportError:
    import traceback
    traceback.print_exc()
    sys.exit(1)

from sdl2.ext import Resources
RESOURCES = Resources(__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("totoro.png"))

spriterenderer = factory.create_sprite_renderer(window)
spriterenderer.render(sprite)

processor = sdl2ext.TestEventProcessor()
processor.run(window)

sdl2ext.quit()
示例#23
0
    def game_board(self, board, player_one, player_two, player_types, ai_difficulty=None):

        from player_data import PlayerData

        pd=PlayerData()

        if 'AI' in player_types:
            from ai import AI
            ai=AI()
            if 'AI: Easy' in [player_one,player_two]:
                ai.difficulty=0
            elif 'AI: Medium' in [player_one,player_two]:
                ai.difficulty=1
            elif 'AI: Hard' in [player_one,player_two]:
                ai.difficulty=2

        sdl2ext.init()

        window = sdl2ext.Window("c4o5x5", size=(320, 420))

        window.show()

        factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)

        spriterenderer = factory.create_sprite_render_system(window)

        moves = 0
        running = True
        updated_p1 = False
        updated_p2 = False

        while running:
            if moves % 2 == 0:
                this_player = player_one
                that_player = player_two
                if player_types[0]=='AI':
                    mode='AI'
                    player_graphic="ai.bmp"
                else:
                    mode='Human'
                    player_graphic = "player_one.bmp"
            if moves % 2 == 1:
                this_player = player_two
                that_player = player_one
                if player_types[1]=='AI':
                    mode='AI'
                    player_graphic="ai.bmp"
                else:
                    mode='Human'
                    player_graphic = "player_two.bmp"
            for x in range(5):
                for y in range(5):
                    if board.marks[x][y] is None:
                        spriterenderer.render(factory.from_image(self.RESOURCES.get_path("tile.bmp")),x*64,y*64)
                    if board.marks[x][y] == player_one:
                        spriterenderer.render(factory.from_image(self.RESOURCES.get_path("tile_o.bmp")),x*64,y*64)
                    if board.marks[x][y] == player_two:
                        spriterenderer.render(factory.from_image(self.RESOURCES.get_path("tile_x.bmp")),x*64,y*64)
            if board.check_winning_positions() != (False,False):
                winning_player = board.check_winning_positions()[0]
                if winning_player == player_one:
                    winning_graphic = 'player_one_wins.bmp'
                    if player_one != 'Guest' and not updated_p1:
                        player=pd.load_player(player_one)
                        pd.update_player(player_one,player.wins+1,player.losses)
                        updated_p1 = True
                    if player_two != 'Guest' and not updated_p2:
                        player=pd.load_player(player_two)
                        pd.update_player(player_two,player.wins,player.losses+1)
                        updated_p2=True
                elif winning_player == player_two:
                    winning_graphic = 'player_two_wins.bmp'
                    if player_one != 'Guest' and not updated_p2:
                        player=pd.load_player(player_two)
                        pd.update_player(player_two,player.wins+1,player.losses)
                        updated_p2=True
                    if player_two != 'Guest' and not updated_p1:
                        player=pd.load_player(player_one)
                        pd.update_player(player_one,player.wins,player.losses+1)
                        updated_p1=True
                spriterenderer.render(factory.from_image(self.RESOURCES.get_path(winning_graphic)),0,(x+1)*64)
                events = sdl2ext.get_events()
                for event in events:
                    if event.type == SDL_MOUSEBUTTONDOWN:
                        running = False
                        SDL_Delay(1000)
                        break
            elif moves == 25:
                winning_graphic = "tie_game.bmp"
                spriterenderer.render(factory.from_image(self.RESOURCES.get_path(winning_graphic)),0,(x+1)*64)
                events = sdl2ext.get_events()
                for event in events:
                    if event.type == SDL_MOUSEBUTTONDOWN:
                        running = False
                        break
            elif mode == 'Human':
                spriterenderer.render(factory.from_image(self.RESOURCES.get_path(player_graphic)),0,(x+1)*64)
                events = sdl2ext.get_events()
                for event in events:
                    if event.type == SDL_QUIT:
                        running = False
                        break
                    elif event.type == SDL_MOUSEBUTTONDOWN:
                        x_pos = int(event.button.x/64)
                        y_pos = int(event.button.y/64)
                        if x_pos <= 4 and y_pos <= 4 and board.marks[x_pos][y_pos] is None:
                            board.marks[x_pos][y_pos]=this_player
                            moves = moves + 1
            elif mode=='AI':
                move = ai.make_move(board,this_player,that_player)
                moves = moves + 1
                board.update_position(move[0],move[1],this_player)
                for x in range(5):
                    for y in range(5):
                        if board.marks[x][y] is None:
                            spriterenderer.render(factory.from_image(self.RESOURCES.get_path("tile.bmp")),x*64,y*64)
                        if board.marks[x][y] == player_one:
                            spriterenderer.render(factory.from_image(self.RESOURCES.get_path("tile_o.bmp")),x*64,y*64)
                        if board.marks[x][y] == player_two:
                            spriterenderer.render(factory.from_image(self.RESOURCES.get_path("tile_x.bmp")),x*64,y*64)
                spriterenderer.render(factory.from_image(self.RESOURCES.get_path(player_graphic)),0,(x+1)*64)
                SDL_Delay(500)
                events = sdl2ext.get_events()
                for event in events:
                    if event.type == SDL_QUIT:
                        running = False
                        break
                    else:
                        pass
            else:
                raise Exception
            SDL_Delay(10)

        sdl2ext.quit()
 def tearDownClass(cls):
     sdl2ext.quit()
示例#25
0
        if self.keyDown(sdl.SDLK_RIGHT):
            s = self.entities['test'].sprite()
            self.entities['test'].xspeed = self.entities['test'].xspeed + 0.5

        if self.keyDown(sdl.SDLK_LEFT):
            s = self.entities['test'].sprite()
            self.entities['test'].xspeed = self.entities['test'].xspeed - 0.5

    def run(self):
        while self.running:
            self.timer.tick()
            self.checkEvents()
            self.updateGame()
            self.renderer.render()
            delta = (time.time() - self.timer.currentTime)
            sleepTime = self.gameSpeed - delta
            if sleepTime > 0:
                sdl.SDL_Delay(int(sleepTime * 1000))

        return 0

    def __del__(self):
        return 0


if __name__ == "__main__":
    sdle.init()
    g = Game()
    sys.exit(g.run())
    sdle.quit()
示例#26
0
# ---------- main event (game) loop ---

print(" .. LEFT/RIGHT cycle through scenes")
print(" .. ESC quits")

running = True
while running:
  # [x] output - draw world
  world.process()
  # [x] input and [x] update the world
  events = lib.get_events()
  for e in events:
    if e.type == sdl2.SDL_QUIT:
      running = False
      break
    if e.type == sdl2.SDL_KEYDOWN:
      if e.key.keysym.sym == sdl2.SDLK_ESCAPE:
        running = False
        break
      if e.key.keysym.sym == sdl2.SDLK_LEFT:
        world.cycle(-1)
      if e.key.keysym.sym == sdl2.SDLK_RIGHT:
        world.cycle(1)

# /--------- main event (game) loop ---


lib.quit()  # /-- init ---

print("----------------// rainforce // 2014-2016 //--")
示例#27
0
                elif event.key.keysym.sym == SDLK_DOWN:
                    # For clarity, here is an alternate way in which a temporary variable
                    # is created and modified. The previous way above is recommended instead.
                    player_velocity_component = world.component_for_entity(player, Velocity)
                    player_velocity_component.y = 3
                elif event.key.keysym.sym == SDLK_LEFT:
                    world.component_for_entity(player, Velocity).x = -3
                elif event.key.keysym.sym == SDLK_RIGHT:
                    world.component_for_entity(player, Velocity).x = 3
                elif event.key.keysym.sym == SDLK_ESCAPE:
                    running = False
                    break
            elif event.type == SDL_KEYUP:
                if event.key.keysym.sym in (SDLK_UP, SDLK_DOWN):
                    world.component_for_entity(player, Velocity).y = 0
                if event.key.keysym.sym in (SDLK_LEFT, SDLK_RIGHT):
                    world.component_for_entity(player, Velocity).x = 0

        # A single call to world.process() will update all Processors:
        world.process()

        # A crude FPS limiter for about 60fps
        current_time = SDL_GetTicks()
        sleep_time = int(start_time + 16.667 - current_time)
        if sleep_time > 0:
            SDL_Delay(sleep_time)

if __name__ == "__main__":
    run()
    ext.quit()
示例#28
0
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("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 = sdl2ext.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
        # get_events() 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 == 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 == 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 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 sdl2ext.quit(), since we also
    # called sdl2ext.init().
    sdl2ext.quit()
    return 0
示例#29
0
 def teardown_class(cls):
     sdl2ext.quit()
示例#30
0
def run():
	sdl2ext.init()
	draw.pixels(500, 500)
	window = sdl2ext.Window("Pixel Access", size=(draw.xpix, draw.ypix))
	window.show()
	renderer = sdl2ext.Renderer(window)
	running = True
	mat = []
	temp = []
	while running:
		events = sdl2ext.get_events()
		for event in events:
			if event.type == SDL_QUIT:
				running = False
				break
			if event.type == SDL_MOUSEBUTTONDOWN:
				
				x = c_int(0)
				y = c_int(0)
				print(SDL_GetMouseState(x,y))
				print(x,y)
				x = x.value
				y = y.value
				x = float(x)
				y = float(y)
				print(x, y)
				temp = draw.box_t(0.25,0.25,0.25,0,0,0,float((x-250)/125),float((250-y)/125),0)
				
			
                        #############################
			#####                   #####
			##### PRESS ESC TO QUIT #####
			#####                   #####
			#############################
			if event.type == SDL_KEYDOWN:
				if event.key.keysym.sym == SDLK_ESCAPE:
					running = False
		with Timer() as t:
			draw.setFrames(1,100)
			draw.screen(-2, 2, -2, 2)
			draw.pixels(500,500)
			draw.vary("turn", 0, 360, 1, 100)
			draw.trans_matrix = draw.rotate_y("turn", draw.trans_matrix)
			draw.trans_matrix = draw.move(0, -.05, 0, draw.trans_matrix)
			draw.trans_matrix = draw.scale(.75, .75, .75, draw.trans_matrix)
			draw.trans_matrix = draw.rotate_x(30, draw.trans_matrix)
			draw.sphere_t(1.2, 1, 0.37, 0, 0, 0, 0, 0, 0)
			print draw.trans_matrix
			print draw.frames
			print draw.currentframe
			print draw.varys
			#temp = draw.transform(draw.trans_matrix, temp)
			draw.triangle_matrix = draw.triangle_matrix + mat
			draw.triangle_matrix = draw.transform(draw.trans_matrix, draw.triangle_matrix)
			draw.triangle_matrix = draw.triangle_matrix + temp
			mat = mat + temp
			temp = []
			draw.render_parallel()
			grid = draw.end()
		print "=> elasped grid: %s s" % t.secs
		with Timer() as t:
			draw_pixels(renderer, draw.xpix, draw.ypix, grid)
		print "=> elasped render: %s s" % t.secs
		window.refresh()
	sdl2ext.quit()
	return 0
示例#31
0
with open("figure.json", "r") as ff:
    figure = json.loads(ff.read())

figure["points"] = np.array(figure["points"])
print(figure["points"])
figure["points"] -= np.mean(figure["points"], axis=0)
print(figure["points"])
figure["points"] = np.hstack(
    (figure["points"], np.ones((figure["points"].shape[0], 1))))
print(figure["points"])
figure["AB"] = np.array(figure["AB"])

sdl2e.init()
window = sdl2e.Window("...", size=(WIDTH, HEIGHT))
window.show()
draw(window, transform(world, figure["points"]), figure["polygons"])

running = True
while running:
    events = sdl2e.get_events()
    for event in events:
        if event.type == sdl2.SDL_QUIT:
            running = False
            break
        if event.type == sdl2.SDL_KEYDOWN:
            if handle_key(window, event.key.keysym.sym):
                draw(window, transform(world, figure["points"]),
                     figure["polygons"])

sdl2e.quit()
示例#32
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