def get_window(): global _window if _window is None: _window = sf.RenderWindow(sf.VideoMode(*_window_size), "EUSDAB", sf.Style.Close) _window.SetFramerateLimit(60) icon_image = load_image(_icon_image, _assets_dir) _window.SetIcon(icon_image.GetWidth(), icon_image.GetHeight(), icon_image.GetPixels()) return _window
def _setup_window(self): self._window = sf.RenderWindow( sf.VideoMode( self._conf.child('width').value, self._conf.child('height').value, self._conf.child('bpp').value), self._window_title, sf.Style.Fullscreen if self._conf.child('full').value else 0, sf.WindowSettings( AntialiasingLevel=self._conf.child('antialias').value)) self._window.ShowMouseCursor(self._conf.child('showmouse').value) self._window.SetFramerateLimit(self._conf.child('fps').value) self._window.UseVerticalSync(self._conf.child('vsync').value) self._tf_window = Window(self._window) self._tf_view = View(self._tf_window, self._window.GetDefaultView())
def Main(): Buffer = sf.SoundBuffer() if not Buffer.LoadFromFile("data/fart.wav"): # Loads the sound return Fart = sf.Sound(Buffer, False) WindowWidth, WindowHeight = 640, 480 App = sf.RenderWindow(sf.VideoMode(WindowWidth, WindowHeight, 32), "Sound with PySFML", sf.Style.Close, sf.ContextSettings(24, 8, 0)) App.SetFramerateLimit(30) EventHandler = sf.Event() InputHandler = App.GetInput() Text = sf.Text( "Turn the sound on.\nClick anywhere on the screen.\nMove the mouse. Click again.\nTry clicking in the corners." ) Text.SetX(30.) Text.SetY(20.) Text.SetColor(sf.Color(150, 100, 10, 255)) while App.IsOpened(): # Main loop while App.GetEvent(EventHandler): # Event Handler if EventHandler.Type == sf.Event.Closed: App.Close() if EventHandler.Type == sf.Event.KeyPressed and EventHandler.Key.Code == sf.Key.Escape: App.Close() if EventHandler.Type == sf.Event.MouseButtonPressed and EventHandler.MouseButton.Button == sf.Mouse.Left: Fart.SetPitch(1.5 - 1. * InputHandler.GetMouseY() / WindowHeight) Fart.SetPosition( 1. * (InputHandler.GetMouseX() - WindowWidth / 2) / (WindowWidth / 20), 2., -2.) Fart.Play() App.Draw(Text) App.Display() App.Clear(sf.Color.Black)
def __init__(self): # Initialize the window self.win = sf.RenderWindow(sf.VideoMode(800, 600, 32), "PyWorm", sf.Style.Close) # Creates the window self.win.EnableKeyRepeat(False) background_color = sf.Color(100, 100, 0, 255) self.win.SetFramerateLimit(30) event = sf.Event() self.keys = {} # keys to watch self.menu_begin() # Boucle principale while self.win.IsOpened(): while self.win.GetEvent(event): # Event Handler if event.Type == sf.Event.Closed: self.win.Close() elif event.Type == sf.Event.KeyPressed or event.Type == sf.Event.KeyReleased: if event.Key.Code in self.keys: self.keys[event.Key.Code]( event.Type == sf.Event.KeyPressed) self.win.Display() self.win.Clear(background_color) self.next_frame(self.win)
def main(json_file, animation_folder, image_folder): # IO preparations animation_folder_full = os.path.join(image_folder, animation_folder) if not os.path.exists(animation_folder_full): msg = '"%s" folder does not exist' % animation_folder_full raise RuntimeError(msg) image_files = os.listdir(animation_folder_full) # main window window = sf.RenderWindow(sf.VideoMode.GetMode(0), \ 'HitboxMaker', sf.Style.Close | sf.Style.Resize) window_center = window.GetWidth() / 2., window.GetHeight() / 2. # mouse start click start = None # current hitbox semantic semantic = None # currently selected hitboxes selected = [] # currently copied hitboxes copied = [] # hitbox semantic key mapping semantic_mapping = { sf.Key.A : Semantics.ATTACK, sf.Key.Z : Semantics.DEFENSE, sf.Key.E : Semantics.FOOT, sf.Key.R : Semantics.GRABABLE, sf.Key.T : Semantics.GRAB, sf.Key.Y : None } # lambdas for more explicit calls is_image_filename = lambda x: x in ('png', 'jpeg', 'jpg', 'bmp') get_clean_extension = lambda x: os.path.splitext(x)[1][1:].lower() is_readable = lambda x: x.mode[0] == 'r' # image list image_frames = [] if is_readable(json_file): animation = load_hitboxes(animation_folder, image_folder, json_file, *window_center) else: for x in image_files: if is_image_filename(get_clean_extension(x)): df = DrawableFrame(x, animation_folder, image_folder, \ *window_center) image_frames.append(df) if len(image_frames) == 0: msg = 'No images found in "%s"' % animation_folder_full raise RuntimeError(msg) image_frames = sorted(image_frames, key=lambda x: x.filename) animation = DrawableAnimation(image_frames) # camera setup camera = sf.View() camera.SetCenter(*window_center) camera.SetHalfSize(*window_center) # helper for mouse querying real_mouse_position = lambda x, y: window.ConvertCoords(x, y) # helper for zooming def zoomBy(delta): assert delta != 0, 'Cannot zoom by 0' zoom_ratio = 1.2 if delta > 0: zoom_factor = zoom_ratio else: zoom_factor = 1. / zoom_ratio camera.Zoom(zoom_factor) # program loop while window.IsOpened(): # continuous input input_ = window.GetInput() # event based input event = sf.Event() while window.GetEvent(event): if event.Type == sf.Event.Closed: # close window when requested window.Close() elif event.Type == sf.Event.Resized: # resize view when requested width, height = window.GetWidth(), window.GetHeight() camera.SetHalfSize(width / 2., height / 2.) else: # mouse events if event.Type == sf.Event.MouseButtonPressed: button = event.MouseButton.Button pos = event.MouseButton.X, event.MouseButton.Y x, y = real_mouse_position(*pos) if button == sf.Mouse.Left: if input_.IsKeyDown(sf.Key.LControl) \ or input_.IsKeyDown(sf.Key.RControl): drawable_list = animation.current().drawable_list selected = drawable_list.toggle_select(x, y) elif semantic is not None: start = x, y elif event.Type == sf.Event.MouseButtonReleased: button = event.MouseButton.Button pos = event.MouseButton.X, event.MouseButton.Y x, y = real_mouse_position(*pos) if button == sf.Mouse.Left: if semantic is not None and start is not None: hitbox = make_hitbox(start, (x, y), semantic) if hitbox is not None: dhb = DrawableHitbox(hitbox) cur = animation.current() drawable_list = cur.drawable_list drawable_list.append(dhb) semantic = None start = None elif event.Type == sf.Event.MouseWheelMoved \ and input_.IsKeyDown(sf.Key.LControl) \ or input_.IsKeyDown(sf.Key.RControl): zoomBy(event.MouseWheel.Delta) # key events if event.Type == sf.Event.KeyPressed: key = event.Key.Code if input_.IsKeyDown(sf.Key.LControl) \ or input_.IsKeyDown(sf.Key.RControl): # Ctrl + key if key == sf.Key.A: # select all print 'Selecting all hitboxes for current frame' drawable_list = animation.current().drawable_list selected = drawable_list.select_all() elif key == sf.Key.C: # copy print 'Copying selected hitboxes' drawable_list = animation.current().drawable_list copied = drawable_list.get_selected() elif key == sf.Key.V: # paste print 'Pasting selected hitboxes' drawable_list = animation.current().drawable_list for c in copied: cp = c.copy() print 'Pasting hitbox', repr(cp.hitbox) drawable_list.append(cp) elif key in semantic_mapping: # change semantic new_semantic = semantic_mapping[key] if len(selected) > 0 and new_semantic is not None: print "Changing selected hitboxes' semantic to", \ new_semantic for s in selected: s.set_semantic(new_semantic) else: print 'Switching to semantic', new_semantic semantic = new_semantic elif key == sf.Key.Delete: # delete selected print 'Deleting selected hitboxes' for s in selected: drawable_list = animation.current().drawable_list drawable_list.remove(s) selected = [] elif key == sf.Key.Escape: # unselect print 'Unselecting selected hitboxes' drawable_list = animation.current().drawable_list selected = drawable_list.clear_selection() elif key == sf.Key.B: # previous frame print 'Previous frame' drawable_list = animation.current().drawable_list animation.advance(-1) selected = drawable_list.clear_selection() elif key == sf.Key.N: # next frame print 'Next frame' drawable_list = animation.current().drawable_list animation.advance(1) selected = drawable_list.clear_selection() window.Clear() # get mouse position (relative to window) mouse = input_.GetMouseX(), input_.GetMouseY() mouse = real_mouse_position(*mouse) # move camera by continuous input camera_motion = [0, 0] if input_.IsKeyDown(sf.Key.Left): camera_motion[0] -= 1 if input_.IsKeyDown(sf.Key.Right): camera_motion[0] += 1 if input_.IsKeyDown(sf.Key.Up): camera_motion[1] -= 1 if input_.IsKeyDown(sf.Key.Down): camera_motion[1] += 1 camera_motion = map(lambda x: x * 5, camera_motion) camera.Move(*camera_motion) # apply view window.SetView(camera) # draw animation window.Draw(animation) # draw current rect if start is not None and input_.IsMouseButtonDown(sf.Mouse.Left): rect = sfml_make_rect_from_corners(mouse, start) rect.EnableOutline(True) rect.EnableFill(False) rect.SetOutlineWidth(1) rect = sfml_set_rect_outline_color(rect, sf.Color.White) window.Draw(rect) # display window window.Display() # produce filename -> hitboxes dict for JSON serialization save_hitboxes(animation, json_file)
def boucle_de_rendu(): app = sf.RenderWindow(sf.VideoMode(APPW, APPH), "") #, sf.Style.Fullscreen) view = sf.View(sf.FloatRect(0, 0, APPW, APPH)) app.SetView(view) e = sf.Event() #son sound = random.choice(['ds1', 'ds2', 'ds3', 'elf']) son.sounds[sound].SetLoop(True) son.sounds[sound].Play() # animations statiques nbanim = 0 for anim in animenv.ANIMS: nbanim -= 1 GLOB['objets'][nbanim] = persoclient.PersoClient(anim) while app.IsOpened(): t0 = time.time() #print "window is still opened" while app.GetEvent(e): if e.Type == sf.Event.Closed: app.Close() elif e.Type == sf.Event.KeyPressed: if e.Key.Code == sf.Key.Escape: app.Close() reactor.stop() else: k = e.Key.Code if k in KEYS: if 'sock' in GLOB: GLOB['sock'].send_input(KEYS[k], True) elif e.Type == sf.Event.KeyReleased: if e.Key.Code == sf.Key.Escape: app.Close() else: k = e.Key.Code if k in KEYS: if 'sock' in GLOB: GLOB['sock'].send_input(KEYS[k], False) elif e.Type == sf.Event.MouseButtonPressed: x = e.MouseButton.Button if x == sf.Mouse.Left: x = 'cg' else: x = 'cd' if 'sock' in GLOB: GLOB['sock'].send_input(x, True) elif e.Type == sf.Event.MouseButtonReleased: x = e.MouseButton.Button if x == sf.Mouse.Left: x = 'cg' else: x = 'cd' if 'sock' in GLOB: GLOB['sock'].send_input(x, False) elif e.Type == sf.Event.MouseMoved: x, y = app.ConvertCoords(e.MouseMove.X, e.MouseMove.Y) if 'sock' in GLOB and 'moi' in GLOB: GLOB['sock'].send_mousemove(x, y) # dessin app.Clear() # effacement app.Draw(FOND) # blit du fond if 'objets' in GLOB: for obj in GLOB['objets'].values(): obj.fuckdrawon(app) print obj.id app.Display() # affichage ! # attente : deltat = time.time() - t0 try: # au cas ou on rame time.sleep(1 / FREQ - deltat) except: pass
def main(): # Create main window App = sf.RenderWindow(sf.VideoMode(800, 600), "SFML OpenGL") App.SetActive() # Create a sprite for the background BackgroundImage = sf.Image() if not BackgroundImage.LoadFromFile( "../../samples/bin/datas/opengl/background.jpg"): return Background = sf.Sprite(BackgroundImage) # Load an OpenGL texture. # We could directly use a sf.Image as an OpenGL texture (with its Bind() member function), # but here we want more control on it (generate mipmaps, ...) so we create a new one Image = sf.Image() if not Image.LoadFromFile("../../samples/bin/datas/opengl/texture.jpg"): return # The next line is a bit different from the C++ version Texture = glGenTextures(1) # instead of glGenTextures(1, &Texture); glBindTexture(GL_TEXTURE_2D, Texture) # It is almost the same line there, except in C++, the last argument was Image.GetPixelsPtr(). # In python, GetPixels simply returns a string. gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, Image.GetWidth(), Image.GetHeight(), GL_RGBA, GL_UNSIGNED_BYTE, Image.GetPixels()) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) # Enable Z-buffer read and write glEnable(GL_DEPTH_TEST) glDepthMask(GL_TRUE) glClearDepth(1.) # Setup a perspective projection glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(90., 1., 1., 500.) # Bind our texture glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, Texture) glColor4f(1., 1., 1., 1.) # Create a clock for measuring the time elapsed Clock = sf.Clock() # Start game loop while App.IsOpened(): # Process events Event = sf.Event() while App.GetEvent(Event): # Close window : exit if Event.Type == sf.Event.Closed: App.Close() # Escape key : exit if (Event.Type == sf.Event.KeyPressed) and (Event.Key.Code == sf.Key.Escape): App.Close() # Adjust the viewport when the window is resized if Event.Type == sf.Event.Resized: glViewport(0, 0, Event.Size.Width, Event.Size.Height) # Draw background App.Draw(Background) # Active window to be able to perform OpenGL commands. App.SetActive() # Clear depth buffer glClear(GL_DEPTH_BUFFER_BIT) # Apply some transformations glMatrixMode(GL_MODELVIEW) glLoadIdentity() glTranslatef(0, 0, -200) glRotatef(Clock.GetElapsedTime() * 50, 1, 0, 0) glRotatef(Clock.GetElapsedTime() * 30, 0, 1, 0) glRotatef(Clock.GetElapsedTime() * 90, 0, 0, 1) # Draw a cube glBegin(GL_QUADS) glTexCoord2f(0, 0) glVertex3f(-50., -50., -50.) glTexCoord2f(0, 1) glVertex3f(-50., 50., -50.) glTexCoord2f(1, 1) glVertex3f(50., 50., -50.) glTexCoord2f(1, 0) glVertex3f(50., -50., -50.) glTexCoord2f(0, 0) glVertex3f(-50., -50., 50.) glTexCoord2f(0, 1) glVertex3f(-50., 50., 50.) glTexCoord2f(1, 1) glVertex3f(50., 50., 50.) glTexCoord2f(1, 0) glVertex3f(50., -50., 50.) glTexCoord2f(0, 0) glVertex3f(-50., -50., -50.) glTexCoord2f(0, 1) glVertex3f(-50., 50., -50.) glTexCoord2f(1, 1) glVertex3f(-50., 50., 50.) glTexCoord2f(1, 0) glVertex3f(-50., -50., 50.) glTexCoord2f(0, 0) glVertex3f(50., -50., -50.) glTexCoord2f(0, 1) glVertex3f(50., 50., -50.) glTexCoord2f(1, 1) glVertex3f(50., 50., 50.) glTexCoord2f(1, 0) glVertex3f(50., -50., 50.) glTexCoord2f(0, 1) glVertex3f(-50., -50., 50.) glTexCoord2f(0, 0) glVertex3f(-50., -50., -50.) glTexCoord2f(1, 0) glVertex3f(50., -50., -50.) glTexCoord2f(1, 1) glVertex3f(50., -50., 50.) glTexCoord2f(0, 1) glVertex3f(-50., 50., 50.) glTexCoord2f(0, 0) glVertex3f(-50., 50., -50.) glTexCoord2f(1, 0) glVertex3f(50., 50., -50.) glTexCoord2f(1, 1) glVertex3f(50., 50., 50.) glEnd() # Draw some text on top of our OpenGL object Text = sf.Text("This is a rotating cube") Text.SetPosition(230., 300.) Text.SetColor(sf.Color(128, 0, 128)) App.Draw(Text) # Finally, display the rendered frame on screen App.Display() # Don't forget to destroy our texture # In C++, the call to this function was a bit different glDeleteTextures(Texture) # instead of glDeleteTextures(1, &Texture); return
#include PySFML from PySFML import sf #Create the main window window = sf.RenderWindow(sf.VideoMode(1024, 768), "PySFML test") #Create a string to display text = sf.String("Hello SFML") #Start the game loop running = True while running: event=sf.Event() while window.GetEvent(event): if event.Type == sf.Event.Closed: running = False #Clear screen, draw text, update window window.Clear() window.Draw(text) window.Display()
def main(): nombreGentils = 100 nombreMechants = 100 taillex = 800.0 tailley = 700.0 window = sf.RenderWindow(sf.VideoMode(int(taillex), int(tailley)), "Test de LU") running = True while (running): event = sf.Event() while window.GetEvent(event): if event.Type == sf.Event.Closed: running = False texte = sf.String() terre = lu.Planet(taillex, tailley) for i in range(nombreGentils): terre.newAnimal(reprod=0.95, vie=150) for i in range(nombreMechants): terre.newAnimal(1, vie=150) terre.newRandomFood(1) terre.newRandomFood(0) terre.newRandomFood(1) terre.newRandomFood(0) window.Clear() window.Display() a = 0 for i in range(500): window.Clear() a += 1 drawlist = terre.round() print "ROUND : " + str(a) pointList = [] for t in range(len(drawlist.a) - 1): if drawlist.d[t] == True: if drawlist.c[t] == 0: rectangle = sf.Shape.Circle(drawlist.a[t], drawlist.b[t], 1, sf.Color.Green) pointList.append(rectangle) if drawlist.c[t] == 1: rectangle = sf.Shape.Circle(drawlist.a[t], drawlist.b[t], 1, sf.Color.Blue) pointList.append(rectangle) for f in pointList: window.Draw(f) for f in terre.foodList: if f.duree > 0: if f.sorte == 0: rectangle = sf.Shape.Circle(f.x, f.y, 3, sf.Color.White) if f.sorte == 1: rectangle = sf.Shape.Circle(f.x, f.y, 3, sf.Color.Yellow) window.Draw(rectangle) texte.SetText(str(terre.nombreAnim)) texte.SetSize(30) window.Draw(texte) window.Display() running = False
# Simple class for an apple. class Apple: sprite = None speed = (2, 2) rotationstep = 1 def __init__(self, image): self.sprite = sf.Sprite(image) self.sprite.SetOrigin(image.GetWidth() / 2, image.GetHeight() / 2) # Set resolution and create the window. Resolution = (800, 600) wnd = sf.RenderWindow(sf.VideoMode(Resolution[0], Resolution[1], 32), "Hello SFML!") wnd.UseVerticalSync(True) # Load a fancy font. cheese = sf.Font() cheese.LoadFromFile("data/cheeseburger.ttf") # Create a text. text = sf.Text(u"Hello SFML from Python!", cheese, 50) text.SetOrigin(text.GetRect().GetSize()[0] / 2, text.GetRect().GetSize()[1] / 2) text.SetPosition(400, 300) text.SetColor(sf.Color(0, 100, 0, 100)) # Create a text for FPS display. fpstext = sf.Text(u"FPS: --", cheese)