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 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
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 '''
def run(): WIDTH = 1600 HEIGHT = 1200 THICKNESS = 10 LENGTH = 100 RADIUS = 20 sdlext.init() window = sdlext.Window("the PG", size=(WIDTH, HEIGHT)) window.show() world = sdlext.World() spriterenderer = SoftwareRenderer(window) world.add_system(spriterenderer) factory = sdlext.SpriteFactory(sdlext.SOFTWARE) sp_paddle1 = factory.from_color(WHITE, (THICKNESS, LENGTH)) sp_paddle2 = factory.from_color(WHITE, (THICKNESS, LENGTH)) player1 = Player(world, sp_paddle1, 0, HEIGHT//2 - LENGTH//2) player2 = Player(world, sp_paddle2, WIDTH - THICKNESS, HEIGHT//2 - LENGTH//2) sp_ball = factory.from_color(WHITE, size=(RADIUS, RADIUS)) movement = MovementSystem(0, 0, WIDTH, HEIGHT) world.add_system(movement) ball = Ball(world, sp_ball, WIDTH//2 - THICKNESS//2, HEIGHT//2 - RADIUS//2) ball.velocity.vx = 3 running = True while running: events = sdlext.get_events() for event in events: if event.type == sdl2.SDL_QUIT: running = False break world.process() return 0
def setup_class(cls): cls.testfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources", "surfacetest.bmp") try: sdl2ext.init() except sdl2ext.SDLError: raise pytest.skip('Video subsystem not supported')
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()
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
def init(windowname='ZOMG FORGOT TO NAME IT', width=640, height=400): global renderer, window, window_width, window_height window_width = width window_height = height sdl.init() window = sdl.Window(windowname, size=(window_width, window_height)) window.show() renderer = sdl.Renderer(window)
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 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
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_get_events_issue_6(self): sdl2ext.init() SDL_FlushEvent(SDL_FIRSTEVENT, SDL_LASTEVENT) for x in range(12): event = SDL_Event() event.type = SDL_USEREVENT + x event.user = SDL_UserEvent(type=event.type, timestamp=0, windowID=0, code=0) SDL_PushEvent(event) results = sdl2ext.get_events() for idx, r in enumerate(results): self.assertEqual(idx, r.type - SDL_USEREVENT)
def __init(cls): if not cls.has_init: cls.has_init = True sdl2ext.init() atexit.register(sdl2ext.quit) def update_daemon(): cls.__update_sdl() t = Timer(0.01, update_daemon) t.daemon = True t.start() Thread(target=update_daemon, daemon=True).start()
def test_get_events(self): sdl2ext.init() SDL_FlushEvent(SDL_FIRSTEVENT, SDL_LASTEVENT) for x in range(10): event = SDL_Event() event.type = SDL_USEREVENT + 1 event.user = SDL_UserEvent(type=event.type, timestamp=0, windowID=0, code=0) SDL_PushEvent(event) results = sdl2ext.get_events() self.assertEqual(len(results), 10) for ev in results: self.assertEqual(ev.type, (SDL_USEREVENT + 1))
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
def run(): sdl2ext.init() sdlttf.TTF_Init(SDL_INIT_EVERYTHING) font = sdlttf.TTF_OpenFont(str.encode("himalaya.ttf"), 300) flags = SDL_WINDOW_SHOWN color = sdlttf.SDL_Color(255, 255, 255, 255) tibstring = 'བསྐྱོངས་' sdlstr = (ctypes.c_uint16 * len(tibstring))(*map(ord, tibstring)) window = SDL_CreateWindow(b'TTF TEST', SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, flags) renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC) # message = sdlttf.TTF_RenderUTF8_Blended(font, # str.encode(tibstring), # color) message = sdlttf.TTF_RenderUNICODE_Blended( font, sdlstr, color) tex = SDL_CreateTextureFromSurface(renderer, message) dst = SDL_Rect(0, 0, 640, 480) SDL_RenderCopy(renderer, tex, None, dst) SDL_ShowWindow(window) running = True while running: events = sdl2ext.get_events() for event in events: if event.type == SDL_QUIT: running = False break SDL_RenderPresent(renderer) return 0
def __init__(self): sdl2ext.init() self.window = sdl2ext.Window("Souhatsu", size=(800, 600)) self.window.show() # self.world = sdl2ext.World() self.world = World() self.movement = MovementSystem(0, 0, 800, 600) self.spriterenderer = SoftwareRenderer(self.window) self.world.add_system(self.movement) self.world.add_system(self.spriterenderer) self.factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) self.textbox_manager = TextBoxManager(self.world, self.factory)
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
def test_get_events_issue_6(self): try: sdl2ext.init() except sdl2ext.SDLError: raise unittest.SkipTest('Video subsystem not supported') SDL_FlushEvent(SDL_FIRSTEVENT, SDL_LASTEVENT) for x in range(12): event = SDL_Event() event.type = SDL_USEREVENT + x event.user = SDL_UserEvent(type=event.type, timestamp=0, windowID=0, code=0) SDL_PushEvent(event) results = sdl2ext.get_events() for idx, r in enumerate(results): self.assertEqual(idx, r.type - SDL_USEREVENT)
def test_get_events(self): try: sdl2ext.init() except sdl2ext.SDLError: raise unittest.SkipTest('Video subsystem not supported') SDL_FlushEvent(SDL_FIRSTEVENT, SDL_LASTEVENT) for x in range(10): event = SDL_Event() event.type = SDL_USEREVENT + 1 event.user = SDL_UserEvent(type=event.type, timestamp=0, windowID=0, code=0) SDL_PushEvent(event) results = sdl2ext.get_events() self.assertEqual(len(results), 10) for ev in results: self.assertEqual(ev.type, (SDL_USEREVENT + 1))
def make_score_board(window = None, yaku_list = ['rinshan', 'pinfu'], fusu = 20, hansu = 2 , tensu = 2000): if window == None: sdl2ext.init() window = sdl2ext.Window("The Pong Game", size=(800, 600)) window.show() img = print_yaku_list(yaku_list) window_surface = window.get_surface() surface = pilSurface(img) sdl2ext.fill(window_surface, sdl2ext.Color(0, 0, 0 )) rect_tes1 = rect.SDL_Rect(0, 0, 320, 500) rect_tes2 = rect.SDL_Rect(25, 0, 800, 600) SDL_BlitSurface(surface,rect_tes1,window_surface,rect_tes2) SDL_UpdateWindowSurface(window.window) rect_tes1 = rect.SDL_Rect(0, 0, 800, 600) rect_tes2 = rect.SDL_Rect(25, 550, 800, 600) img = PIL.Image.new("RGBA", (500, 35)) if hansu >= 0: text_hansu = str(hansu) + '飜 ' if hansu >= 13: text_hansu = '数え役満 ' if hansu >= 100: text_hansu = '役満 ' text = str(fusu) + '符 ' + text_hansu + str(tensu) + '点' draw_text(img, text, 0, 0) surface = pilSurface(img) SDL_BlitSurface(surface, rect_tes1, window_surface, rect_tes2) SDL_UpdateWindowSurface(window.window) while True: events = sdl2ext.get_events() for event in events: if event.type == SDL_QUIT: running = False break elif event.type == SDL_MOUSEBUTTONDOWN: return
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()
def run(): sdl2ext.init() window = sdl2ext.Window("Pong Game", size=(1280, 720)) window.show() world = sdl2ext.World() collision = CollisionSystem(0, 0, 1280, 720) movement = MovementSystem(0, 0, 1280, 720) spriterenderer = SoftwareRenderer(window) world.add_system(movement) world.add_system(collision) world.add_system(spriterenderer) factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE) 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)) player1 = Player(world, sp_paddle1, 0, 250) player2 = Player(world, sp_paddle2, 1255, 250) ball = Ball(world, sp_ball, 300, 290) collision.ball = ball ball.velocity.vx = -3 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 run(self): sdl2ext.init() window = sdl2ext.Window("Robot Sandbox", size=(640, 480)) window.show() spriteRender = SoftwareRenderer(window) self.world.add_system(spriteRender) running = True while running: events = sdl2ext.get_events() for event in events: #pdb.set_trace() if event.type == SDL_QUIT: runnig = False break self.world.process() window.refresh() return 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()
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)
def run(): sdl2ext.init() # init window window = sdl2ext.Window("tri", size=(screenwidth, screenheight), flags=SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN_DESKTOP) window.show() # init renderer and generator worldrenderer = WorldRenderer(window) trigen = TriGenerator() # init world world = TriWorld() world.add_system(worldrenderer) world.add_system(trigen) # hide cursor SDL_ShowCursor(SDL_DISABLE) running = True while running: start = SDL_GetTicks() # main loop party time events = sdl2ext.get_events() for event in events: if event.type == SDL_QUIT: running = False break world.process() # try and do 60fps elapsed = (SDL_GetTicks() - start) / 1000.0 delay = 16.6 - elapsed if delay > 0: SDL_Delay(int(delay)) SDL_ShowCursor(SDL_ENABLE) return 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()
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 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
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)
def run(): # Initialize PySDL2 stuff ext.init() window = ext.Window(title="Esper PySDL2 example", size=RESOLUTION) renderer = ext.Renderer(target=window) window.show() # Initialize Esper world, and create a "player" Entity with a few Components. world = esper.World() player = world.create_entity() world.add_component(player, Velocity(x=0, y=0)) world.add_component( player, Renderable(texture=texture_from_image(renderer, "redsquare.png"), width=64, height=64, posx=100, posy=100), ) # Another motionless Entity: enemy = world.create_entity() world.add_component( enemy, Renderable(texture=texture_from_image(renderer, "bluesquare.png"), width=64, height=64, posx=400, posy=250), ) # Create some Processor instances, and asign them to be processed. render_processor = RenderProcessor(renderer=renderer) movement_processor = MovementProcessor(minx=0, maxx=RESOLUTION[0], miny=0, maxy=RESOLUTION[1]) world.add_processor(render_processor) world.add_processor(movement_processor) # A simple main loop running = True while running: start_time = SDL_GetTicks() for event in ext.get_events(): if event.type == SDL_QUIT: running = False break if event.type == SDL_KEYDOWN: if event.key.keysym.sym == SDLK_UP: # Here is a way to directly access a specific Entity's Velocity # Component's attribute (y) without making a temporary variable. world.component_for_entity(player, Velocity).y = -3 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)
class FPS(object): def __init__(self): self.counter = 0 self.timer = Timer(1) def process(self): self.counter += 1 if self.timer.expired: print("FPS: %s" % self.counter) self.counter = 0 self.timer.restart() # ---------------------------- init --- import sdl2.ext as lib lib.init() window = lib.Window('HellFire', size=(WIDTH, HEIGHT)) window.show() # renderer knows how to draw in a window, it provides # universal interface to update window contents regardless # of window type (GDI, OpenGL, ...) renderer = lib.Renderer(window) # ------- graphics helper functions --- def vecsum(la, lb): """ (1,4,2) + (2,-1,1) == (3,3,3) """ return tuple(a + b for a, b in zip(la, lb))
def run(): # Initialize PySDL2 stuff ext.init() window = ext.Window(title="Esper PySDL2 example", size=RESOLUTION) renderer = ext.Renderer(target=window) window.show() # Initialize Esper world, and create a "player" Entity with a few Components. world = esper.World() player = world.create_entity() world.add_component(player, Velocity(x=0, y=0)) world.add_component(player, Renderable(texture=texture_from_image(renderer, "redsquare.png"), width=64, height=64, posx=100, posy=100)) # Another motionless Entity: enemy = world.create_entity() world.add_component(enemy, Renderable(texture=texture_from_image(renderer, "bluesquare.png"), width=64, height=64, posx=400, posy=250)) # Create some Processor instances, and asign them to be processed. render_processor = RenderProcessor(renderer=renderer) movement_processor = MovementProcessor(minx=0, maxx=RESOLUTION[0], miny=0, maxy=RESOLUTION[1]) world.add_processor(render_processor) world.add_processor(movement_processor) # A simple main loop running = True while running: start_time = SDL_GetTicks() for event in ext.get_events(): if event.type == SDL_QUIT: running = False break if event.type == SDL_KEYDOWN: if event.key.keysym.sym == SDLK_UP: # Here is a way to directly access a specific Entity's Velocity # Component's attribute (y) without making a temporary variable. world.component_for_entity(player, Velocity).y = -3 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)
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()
def run(): lib.init() window = lib.Window('RLSnake', size=(window_width, window_height)) window.show() renderer = lib.Renderer(window) font_manager = sdl2.ext.FontManager( font_path="assets/fonts/Roboto-Regular.ttf", size=14) factory = sdl2.ext.SpriteFactory(renderer=renderer) text = factory.from_text("Current score: ", fontmanager=font_manager) snake = Snake(n_grid_x, n_grid_y) snake.reset() moves = 0 running = True game_over = False current_tiles = snake.get_tiles() while running: events = sdl2.ext.get_events() for event in events: if event.type == sdl2.SDL_QUIT: running = False break if event.type == sdl2.SDL_KEYDOWN: if event.key.keysym.sym == sdl2.SDLK_ESCAPE: running = False break if event.key.keysym.sym == 114: snake.reset() game_over = False current_tiles = snake.get_tiles() moves = 0 break if not game_over: if event.key.keysym.sym == sdl2.SDLK_UP: _, game_over, _ = snake.step(3) current_tiles = snake.get_tiles() moves += 1 elif event.key.keysym.sym == sdl2.SDLK_DOWN: _, game_over, _ = snake.step(2) current_tiles = snake.get_tiles() moves += 1 elif event.key.keysym.sym == sdl2.SDLK_LEFT: _, game_over, _ = snake.step(1) current_tiles = snake.get_tiles() moves += 1 elif event.key.keysym.sym == sdl2.SDLK_RIGHT: _, game_over, _ = snake.step(0) current_tiles = snake.get_tiles() moves += 1 renderer.clear(sdl2.ext.Color(0, 0, 0)) draw_grid(renderer) for x in range(len(current_tiles)): for y in range(len(current_tiles[x])): tile = current_tiles[x][y] if tile == 0: continue if tile == 1: continue if tile == 2: if game_over: fill_tile(renderer, int(x), int(y), COLOR_SNAKE_GAME_OVER) else: fill_tile(renderer, int(x), int(y), COLOR_SNAKE) if tile == 4: if game_over: fill_tile(renderer, int(x), int(y), COLOR_SNAKE_GAME_OVER) else: fill_tile(renderer, int(x), int(y), COLOR_SNAKE_HEAD) if tile == 3: fill_circle(renderer, int(x), int(y), COLOR_FOOD) text = factory.from_text("Current score: " + str(snake.get_score()), fontmanager=font_manager) renderer.copy(text, dstrect=(0, 0, text.size[0], text.size[1])) text = factory.from_text("Move: " + str(moves), fontmanager=font_manager) renderer.copy(text, dstrect=(0, 14, text.size[0], text.size[1])) renderer.present() sdl2.SDL_Delay(33) return 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()
def init(): ext.init()
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()
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 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,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()
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 setUpClass(cls): sdl2ext.init()
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
def setUpClass(cls): try: sdl2ext.init() except sdl2ext.SDLError: raise unittest.SkipTest('Video subsystem not supported')
def run(): lib.init() window = lib.Window('RLSnake', size=(window_width, window_height)) window.show() renderer = lib.Renderer(window) fontManager = sdl2.ext.FontManager(font_path = "assets/fonts/Roboto-Regular.ttf", size = 14) factory = sdl2.ext.SpriteFactory(renderer=renderer) text = factory.from_text("Current score: ",fontmanager=fontManager) snake = Snake(n_grid_x, n_grid_y) snake.set_visibility_range(args.visibility_range) snake.reset() network = ActorCriticNetwork(4, fc1_dims=args.neurons, fc2_dims=args.neurons) agent = TfAgent(network) agent.load_weights(args.model_path) autoplay = args.autoplay moves = 0 running = True game_over = False old_score = 0 current_tiles = snake.get_tiles() while running: events = sdl2.ext.get_events() for event in events: if event.type == sdl2.SDL_QUIT: running = False break if event.type == sdl2.SDL_KEYDOWN: if event.key.keysym.sym == sdl2.SDLK_ESCAPE: running = False break if event.key.keysym.sym == 112: autoplay = not autoplay if event.key.keysym.sym == 114: snake.reset() moves = 0 old_score = 0 game_over = False current_tiles = snake.get_tiles() break if not game_over: if not autoplay: if event.key.keysym.sym == sdl2.SDLK_SPACE: action = agent.get_action(snake.get_view_obs()) _, game_over, _ = snake.step(action) current_tiles = snake.get_tiles() moves += 1 if autoplay: action = agent.get_action(snake.get_view_obs()) _, game_over, _ = snake.step(action) current_tiles = snake.get_tiles() moves += 1 renderer.clear(sdl2.ext.Color(0, 0, 0)) draw_grid(renderer) for x in range(len(current_tiles)): for y in range(len(current_tiles[x])): tile = current_tiles[x][y] if tile == 0: continue if tile == 1: continue if tile == 2: if game_over: fill_tile(renderer, int(x), int(y), COLOR_SNAKE_GAME_OVER) else: if snake.get_score() > old_score: fill_tile(renderer, int(x), int(y), COLOR_SNAKE_EATEN) else: fill_tile(renderer, int(x), int(y), COLOR_SNAKE) if tile == 4: if game_over: fill_tile(renderer, int(x), int(y), COLOR_SNAKE_GAME_OVER) else: if snake.get_score() > old_score: fill_tile(renderer, int(x), int(y), COLOR_SNAKE_HEAD_EATEN) else: fill_tile(renderer, int(x), int(y), COLOR_SNAKE_HEAD) if tile == 3: fill_circle(renderer, int(x), int(y), COLOR_FOOD) for tile in snake.get_current_view(): fill_tile(renderer, int(tile[0]), int(tile[1]), COLOR_VIEW_RANGE) if snake.get_score() > old_score: old_score = snake.get_score() text = factory.from_text("Current score: " + str(snake.get_score()), fontmanager=fontManager) renderer.copy(text, dstrect=(0, 0, text.size[0],text.size[1])) if autoplay: text = factory.from_text("Move: " + str(moves) + " / " + str(MAX_MOVES), fontmanager=fontManager) else: text = factory.from_text("Move: " + str(moves), fontmanager=fontManager) renderer.copy(text, dstrect=(0, 14, text.size[0],text.size[1])) renderer.present() sdl2.SDL_Delay(args.sleep) if autoplay and (game_over or moves >= MAX_MOVES): snake.reset() moves = 0 old_score = 0 game_over = False return 0
def setup_class(cls): try: sdl2ext.init() except sdl2ext.SDLError: raise pytest.skip('Video subsystem not supported')
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
"m": [0, 0, 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"])
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