我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pygame.display()。
def todo_test_flip(self): # __doc__ (as of 2008-08-02) for pygame.display.flip: # pygame.display.flip(): return None # update the full display Surface to the screen # # This will update the contents of the entire display. If your display # mode is using the flags pygame.HWSURFACE and pygame.DOUBLEBUF, this # will wait for a vertical retrace and swap the surfaces. If you are # using a different type of display mode, it will simply update the # entire contents of the surface. # # When using an pygame.OPENGL display mode this will perform a gl buffer swap. self.fail()
def todo_test_get_wm_info(self): # __doc__ (as of 2008-08-02) for pygame.display.get_wm_info: # pygame.display.get_wm_info(): return dict # Get information about the current windowing system # # Creates a dictionary filled with string keys. The strings and values # are arbitrarily created by the system. Some systems may have no # information and an empty dictionary will be returned. Most platforms # will return a "window" key with the value set to the system id for # the current display. # # New with pygame 1.7.1 self.fail()
def todo_test_gl_set_attribute(self): # __doc__ (as of 2008-08-02) for pygame.display.gl_set_attribute: # pygame.display.gl_set_attribute(flag, value): return None # request an opengl display attribute for the display mode # # When calling pygame.display.set_mode() with the pygame.OPENGL flag, # Pygame automatically handles setting the OpenGL attributes like # color and doublebuffering. OpenGL offers several other attributes # you may want control over. Pass one of these attributes as the flag, # and its appropriate value. This must be called before # pygame.display.set_mode() # # The OPENGL flags are; # GL_ALPHA_SIZE, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE, # GL_ACCUM_GREEN_SIZE, GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE, # GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_STEREO self.fail()
def todo_test_list_modes(self): # __doc__ (as of 2008-08-02) for pygame.display.list_modes: # pygame.display.list_modes(depth=0, flags=pygame.FULLSCREEN): return list # get list of available fullscreen modes # # This function returns a list of possible dimensions for a specified # color depth. The return value will be an empty list if no display # modes are available with the given arguments. A return value of -1 # means that any requested resolution should work (this is likely the # case for windowed modes). Mode sizes are sorted from biggest to # smallest. # # If depth is 0, SDL will choose the current/best color depth for the # display. The flags defaults to pygame.FULLSCREEN, but you may need # to add additional flags for specific fullscreen modes. # self.fail()
def todo_test_mode_ok(self): # __doc__ (as of 2008-08-02) for pygame.display.mode_ok: # pygame.display.mode_ok(size, flags=0, depth=0): return depth # pick the best color depth for a display mode # # This function uses the same arguments as pygame.display.set_mode(). # It is used to depermine if a requested display mode is available. It # will return 0 if the display mode cannot be set. Otherwise it will # return a pixel depth that best matches the display asked for. # # Usually the depth argument is not passed, but some platforms can # support multiple display depths. If passed it will hint to which # depth is a better match. # # The most useful flags to pass will be pygame.HWSURFACE, # pygame.DOUBLEBUF, and maybe pygame.FULLSCREEN. The function will # return 0 if these display flags cannot be set. # self.fail()
def todo_test_set_gamma_ramp(self): # __doc__ (as of 2008-08-02) for pygame.display.set_gamma_ramp: # change the hardware gamma ramps with a custom lookup # pygame.display.set_gamma_ramp(red, green, blue): return bool # set_gamma_ramp(red, green, blue): return bool # # Set the red, green, and blue gamma ramps with an explicit lookup # table. Each argument should be sequence of 256 integers. The # integers should range between 0 and 0xffff. Not all systems and # hardware support gamma ramps, if the function succeeds it will # return True. # self.fail()
def todo_test_set_icon(self): # __doc__ (as of 2008-08-02) for pygame.display.set_icon: # pygame.display.set_icon(Surface): return None # change the system image for the display window # # Sets the runtime icon the system will use to represent the display # window. All windows default to a simple pygame logo for the window # icon. # # You can pass any surface, but most systems want a smaller image # around 32x32. The image can have colorkey transparency which will be # passed to the system. # # Some systems do not allow the window icon to change after it has # been shown. This function can be called before # pygame.display.set_mode() to create the icon before the display mode # is set. # self.fail()
def __init__(self, points, center, color=None, width=0, pygame_surface=None): """ Create centered figure from point list with center (x,y). :param points: Vertices tuple list (ex. [(10,10), (10,5)...]) :type points: list :param center: Center list (ex [10, 10]) :type center: list :param color: Pygame color :type color: pygame.Color :param width: Border width (px) :param pygame_surface: Pygame surface object :type pygame_surface: pygame.display """ self._points = points self._center = center self._color = color self._width = width self._surface = pygame_surface
def stage_default_game_loop_callback(game_loop: GameLoop): """ The default game loop callback to use if none is given when staging a Scene. Order: Clamps dt (to avoid extreme values), ticks all stages, renders all stages, updates the pygame.display :param GameLoop game_loop: the currently playing (active) GameLoop """ # clamp dt if game_loop.dt < 0: game_loop.dt = 1.0 / 60 elif game_loop.dt > 1.0 / 15: game_loop.dt = 1.0 / 15 # tick all Stages for i, stage in enumerate(Stage.stages): Stage.active_stage = i if stage: stage.tick(game_loop) # render all Stages and refresh the pygame.display Stage.render_stages(game_loop.display, refresh_after_render=True) Stage.active_stage = 0
def render_stages(display, refresh_after_render=False): """ Loops through all Stages and renders all of them. :param Display display: Display object on which to render :param bool refresh_after_render: do we refresh the pygame.display after all Stages have been called with `render`? """ # black out display (really necessary? I think so) display.surface.fill(pygame.Color("#000000")) # call render on all Stages for i, stage in enumerate(Stage.stages): Stage.active_stage = i if stage: stage.render(display) # for debugging purposes if refresh_after_render: pygame.display.flip()
def render(self, display): """ Gets called each frame by the GameLoop (after 'tick' is called on all Stages). Renders all its layers (ordered by 'render_order' property of the TiledTileLayer in the tmx file). TODO: renders Sprites that are not part of any layer. :param Display display: the Display object to render on """ if self.is_hidden: return False self.trigger_event("pre_render", display) # loop through the sorted to_render list and render all TiledTileLayer and Sprite objects in this list for layer_or_sprite in self.to_render: if getattr(layer_or_sprite, "ignore_after_n_ticks", 1) <= 0: continue layer_or_sprite.render(display) self.trigger_event("post_render", display)
def letter_by_letter(string): """ Display a black screen with text typed letter by letter :param string: Text you want displayed """ text = '' for i in range(len(string)): screen.fill(colors.Black) text += string[i] text_surface = font.render(text, True, colors.White) text_rect = text_surface.get_rect() text_rect.center = (constants.display_width / 2, constants.display_height / 2) screen.blit(text_surface, [text_rect[0], text_rect[1], text_rect[2], text_rect[3]]) sounds.text() pg.display.update() pg.time.wait(100)
def level_marquee(number): """ This while display a neat little scrolling marquee that tells you what stage you are playing :param number: The number indicating the stage number :return: """ card = pg.image.load(os.path.join("resources", "img", "marquee.png")).convert_alpha() stage = font.render("STAGE {}".format(str(number)), True, colors.White) stage = pg.transform.scale2x(stage) for i in range(400): screen.blit(graphics.img_background, (0, 0)) screen.blit(card, (i*2, 300)) if i <= 180: screen.blit(stage, (constants.display_width/2, 320)) video.update() pg.time.delay(2) i += 1 video.flip() video.update()
def thread_grab_frames(queue_frames, queue_poses): win = pygame.Surface(win_size) frame = pygame.Surface(img_size) hmsurf = pygame.Surface(hmsurf_size) screen = pygame.display.set_mode(screen_size) while True: get_frame(frame) x = surface_to_array(win, frame) queue_frames.put(x) screen.blit(frame, (0,0)) pred = queue_poses.get() # Unpack received data x = pred[-1][0] hm = pred[-2][0] v = pred[-3] p = pred[-4] draw_pose(screen, p, v, img_size[0], img_size[1], prob_thr=0.7) draw_heatmaps(screen, hmsurf, hm) pygame.display.update()
def todo_test_get_active(self): # __doc__ (as of 2008-08-02) for pygame.display.get_active: # pygame.display.get_active(): return bool # true when the display is active on the display # # After pygame.display.set_mode() is called the display Surface will # be visible on the screen. Most windowed displays can be hidden by # the user. If the display Surface is hidden or iconified this will # return False. # self.fail()
def todo_test_get_caption(self): # __doc__ (as of 2008-08-02) for pygame.display.get_caption: # pygame.display.get_caption(): return (title, icontitle) # get the current window caption # # Returns the title and icontitle for the display Surface. These will # often be the same value. # self.fail()
def todo_test_get_init(self): # __doc__ (as of 2008-08-02) for pygame.display.get_init: # pygame.display.get_init(): return bool # true if the display module is initialized # # Returns True if the pygame.display module is currently initialized. self.fail()
def todo_test_get_surface(self): # __doc__ (as of 2008-08-02) for pygame.display.get_surface: # pygame.display.get_surface(): return Surface # get a reference to the currently set display surface # # Return a reference to the currently set display Surface. If no # display mode has been set this will return None. # self.fail()
def todo_test_gl_get_attribute(self): # __doc__ (as of 2008-08-02) for pygame.display.gl_get_attribute: # pygame.display.gl_get_attribute(flag): return value # get the value for an opengl flag for the current display # # After calling pygame.display.set_mode() with the pygame.OPENGL flag, # it is a good idea to check the value of any requested OpenGL # attributes. See pygame.display.gl_set_attribute() for a list of # valid flags. # self.fail()
def todo_test_init(self): # __doc__ (as of 2008-08-02) for pygame.display.init: # pygame.display.init(): return None # initialize the display module # # Initializes the pygame display module. The display module cannot do # anything until it is initialized. This is usually handled for you # automatically when you call the higher level pygame.init(). # # Pygame will select from one of several internal display backends # when it is initialized. The display mode will be chosen depending on # the platform and permissions of current user. Before the display # module is initialized the environment variable SDL_VIDEODRIVER can # be set to control which backend is used. The systems with multiple # choices are listed here. # # Windows : windib, directx # Unix : x11, dga, fbcon, directfb, ggi, vgl, svgalib, aalib # On some platforms it is possible to embed the pygame display into an # already existing window. To do this, the environment variable # SDL_WINDOWID must be set to a string containing the window id or # handle. The environment variable is checked when the pygame display # is initialized. Be aware that there can be many strange side effects # when running in an embedded display. # # It is harmless to call this more than once, repeated calls have no effect. self.fail()
def todo_test_quit(self): # __doc__ (as of 2008-08-02) for pygame.display.quit: # pygame.display.quit(): return None # uninitialize the display module # # This will shut down the entire display module. This means any active # displays will be closed. This will also be handled automatically # when the program exits. # # It is harmless to call this more than once, repeated calls have no effect. self.fail()
def todo_test_set_caption(self): # __doc__ (as of 2008-08-02) for pygame.display.set_caption: # pygame.display.set_caption(title, icontitle=None): return None # set the current window caption # # If the display has a window title, this function will change the # name on the window. Some systems support an alternate shorter title # to be used for minimized displays. # self.fail()
def todo_test_set_palette(self): # __doc__ (as of 2008-08-02) for pygame.display.set_palette: # pygame.display.set_palette(palette=None): return None # set the display color palette for indexed displays # # This will change the video display color palette for 8bit displays. # This does not change the palette for the actual display Surface, # only the palette that is used to display the Surface. If no palette # argument is passed, the system default palette will be restored. The # palette is a sequence of RGB triplets. # self.fail()
def todo_test_toggle_fullscreen(self): # __doc__ (as of 2008-08-02) for pygame.display.toggle_fullscreen: # pygame.display.toggle_fullscreen(): return bool # switch between fullscreen and windowed displays # # Switches the display window between windowed and fullscreen modes. # This function only works under the unix x11 video driver. For most # situations it is better to call pygame.display.set_mode() with new # display flags. # self.fail()
def set_surface(self, surface): """ Set pygame surface object. :param surface: Pygame display surface. :type surface: pygame.display :return: """ self._surface = surface
def render(self, display): """ Paints the Sprite with its current image onto the given Display object. :param Display display: the Display object to render on (Display has a pygame.Surface, on which we blit our image) """ if self.image: #print("render at x={}".format(self.rect.x + self.image_rect.x - display.offsets[0])) display.surface.blit(self.image, (self.rect.x + self.image_rect.x - display.offsets[0], self.rect.y + self.image_rect.y - display.offsets[1])) if DEBUG_FLAGS & DEBUG_RENDER_SPRITES_RECTS: pygame.draw.rect(display.surface, DEBUG_RENDER_SPRITES_RECTS_COLOR, pygame.Rect((self.rect.x - display.offsets[0], self.rect.y - display.offsets[1]), (self.rect.w, self.rect.h)), 1)
def render(self, display): # debug rendering (no backgrounds) -> early out if DEBUG_FLAGS & DEBUG_DONT_RENDER_TILED_TILE_LAYERS: return self.ignore_after_n_ticks = 100 # replenish counter so that the repeater never goes out of the Viewport's scope view_x = display.offsets[0] view_y = display.offsets[1] offset_x = self.rect.x + view_x * self.vx offset_y = self.rect.y + view_y * self.vy if self.repeat_x: start_x = math.floor(-offset_x % self.repeat_w) if start_x > 0: start_x -= self.repeat_w else: start_x = self.rect.x - view_x if self.repeat_y: start_y = math.floor(-offset_y % self.repeat_h) if start_y > 0: start_y -= self.repeat_h else: start_y = self.rect.y - view_y scale = 1.0 cur_y = start_y while cur_y < display.height / scale: cur_x = start_x while cur_x < display.width / scale: #display.surface.blit(self.image, dest=(math.floor(cur_x + view_x), math.floor(cur_y + view_y))) display.surface.blit(self.image, dest=(math.floor(cur_x), math.floor(cur_y))) cur_x += self.repeat_w if not self.repeat_x: break cur_y += self.repeat_h if not self.repeat_y: break
def __init__(self, width=600, height=400, title="Spygame Rocks!"): """ :param int width: the width of the Display :param int height: the height of the Display :param str title: the caption to use on the pygame display """ assert not Display.instantiated, "ERROR: can only create one {} object!".format(type(self).__name__) Display.instantiated = True pygame.display.set_caption(title) self.width = width self.height = height self.surface = pygame.display.set_mode((width, height)) self.offsets = [0, 0]
def change_dims(self, width, height): """ Changes the Display's size dynamically (during the game). :param int width: the new width to use :param int height: the new height to use """ self.width = width self.height = height pygame.display.set_mode((width, height)) assert self.surface is pygame.display.get_surface(), "ERROR: self.display is not same object as pygame.display.get_surface() anymore!"
def debug_refresh(self): """ Force-refreshes the display (used only for debug purposes). """ pygame.display.flip() pygame.event.get([]) # we seem to have to do this
def __init__(self, pytmx_layer, pytmx_tiled_map, tile_sprite_handler): """ :param pytmx.pytmx.TiledTileLayer pytmx_layer: the underlying pytmx TiledTileLayer :param pytmx.pytmx.TiledMap pytmx_tiled_map: the underlying pytmx TiledMap object (representing the tmx file) :param callable tile_sprite_handler: the callable that returns an ndarray, populated with TileSprite objects for storage in this layer """ super().__init__(pytmx_layer, pytmx_tiled_map) self.type_str = self.properties.get("type", "none") self.type = 0 # get type mask of this layer from `type` property for t in self.type_str.split(","): self.type |= Sprite.get_type(t) # an ndarray holding all single tiles (by x/y position) from this layer # non-existing tiles are not(!) stored in this ndarray and return None at the respective x/y position self.tile_sprites = tile_sprite_handler(self) # update do_render indicator depending on some debug settings self.do_render = (self.properties["do_render"] == "true" and not (DEBUG_FLAGS & DEBUG_DONT_RENDER_TILED_TILE_LAYERS)) or \ (self.type != Sprite.get_type("none") and (DEBUG_FLAGS & DEBUG_RENDER_COLLISION_TILES)) self.render_order = int(self.properties["render_order"]) # put this layer in one single Sprite that we can then blit on the display (with 'area=[some rect]' to avoid drawing the entire layer each time) self.pygame_sprite = None # we are rendering this layer, need to store entire image in this structure if self.do_render: self.pygame_sprite = self.build_sprite_surface()
def render(self, display): """ Blits a part of our Sprite's image onto the Display's Surface using the Display's offset attributes. :param Display display: the Display object to render on """ assert self.do_render, "ERROR: TiledTileLayer.render() called but self.do_render is False!" assert not isinstance(self.pygame_sprite, Sprite), "ERROR: TiledTileLayer.render() called but self.pygame_sprite is not a Sprite!" r = pygame.Rect(self.pygame_sprite.rect) # make a clone so we don't change the original Rect # apply the display offsets (camera) r.x += display.offsets[0] r.y += display.offsets[1] r.width = display.width r.height = display.height display.surface.blit(self.pygame_sprite.image, dest=(0, 0), area=r)
def __init__(self, name="physics"): super().__init__(name) self.vx = 0 # velocities self.vy = 0 # physics self.run_acceleration = 300 # running acceleration self.vx_max = 150 # max run-speed self.max_fall_speed = 550 # maximum fall speed self.gravity = True # set to False to make this guy not be subject to y-gravity (e.g. while locked into ladder) self.gravity_y = 9.8 * 100 self.jump_speed = 330 # jump-power self.disable_jump = False # if True: disable jumping so we don't keep jumping when action1 key keeps being pressed self.can_jump = True # set to False to make this guy not be able to jump self.stops_abruptly_on_direction_change = True # Vikings stop abruptly when running in one direction, then the other direction is pressed self.climb_speed = 70 # speed at which player can climb self.type_before_ladder = None self.is_pushable = False # set to True if a collision with the entity causes the entity to move a little self.is_heavy = False # set to True if this object should squeeze other objects that are below it and cannot move away # set to a value > 0 to define the squeezeSpeed at which this object gets squeezed by heavy objects (objects with is_heavy == True) self.squeeze_speed = 0 self.push_back_list = [] # a list of push back x-forces that will be applied (if populated) frame by frame on our GameObject # if an up-slope (e.g. 20°) does not reach it full-tiled right neighbor, would a sprite treat this as stairs and still climb up the full-tile self.allow_stairs_climb = True # self.touching = 0 # bitmap with those bits set that the entity is currently touching (colliding with) self.at_exit = False self.at_wall = False self.is_sinking_til = None # a y-pos at which point the GameObject will stop sinking into a LiquidBody self.on_ladder = None # None if GameObject is not locked into a ladder; Ladder obj if obj is currently locked into a ladder (in climbing position) self.touched_ladder = None # holds the ladder Sprite, if player is currently touching a Ladder (not locked in!), otherwise: None self.climb_frame_value = 0 # int([climb_frame_value]) determines the frame to use to display climbing position self.game_obj_cmp_dockable = None # type: Dockable; the GameObject's Dockable component (that we will add to the GameObject ourselves)
def __init__(self, display): """ :param Display display: the Display object associated with this Viewport """ super().__init__("viewport") # fix name to 'viewport' (only one viewport per Stage) self.display = display # the pygame display (Surface) to draw on; so far we only need it to get the display's dimensions # top/left corner (world coordinates) of the Viewport window # - will be used as offset_x/y for the Display self.x = 0 self.y = 0 # parameters used for shaking the Viewport (if something heavy lands on the ground) self.is_shaking = False self.shake_y = 0 # the current shake-y-offset self.shake_time_total = 0 self.shake_time_switch = 0 self.shake_frequency = 5 self.scale = 1.0 self.directions = {} self.obj_to_follow = None self.max_speed = 10 self.bounding_box = None
def soft_center_on(self, x=None, y=None): """ Soft-centers on a given x/y position respecting the Viewport's max_speed property (unlike center_on). :param Union[int,None] x: the x position to center on (None if we should ignore the x position) :param Union[int,None] y: the y position to center on (None if we should ignore the y position) """ if x: dx = (x - self.display.width / 2 / self.scale - self.x) / 3 # //, this.followMaxSpeed); if abs(dx) > self.max_speed: dx = math.copysign(self.max_speed, dx) if self.bounding_box: if (self.x + dx) < self.bounding_box["min_x"]: self.x = self.bounding_box["min_x"] / self.scale elif self.x + dx > (self.bounding_box["max_x"] - self.display.width) / self.scale: self.x = (self.bounding_box["max_x"] - self.display.width) / self.scale else: self.x += dx else: self.x += dx if y: dy = (y - self.display.height / 2 / self.scale - self.y) / 3 if abs(dy) > self.max_speed: dy = math.copysign(self.max_speed, dy) if self.bounding_box: if self.y + dy < self.bounding_box["min_y"]: self.y = self.bounding_box["min_y"] / self.scale elif self.y + dy > (self.bounding_box["max_y"] - self.display.height) / self.scale: self.y = (self.bounding_box["max_y"] - self.display.height) / self.scale else: self.y += dy else: self.y += dy
def center_on(self, x=None, y=None): """ Centers on a given x/y position without(!) respecting the Viewport's max_speed property (unlike soft_center_on). :param Union[int,None] x: the x position to center on (None if we should ignore the x position) :param Union[int,None] y: the y position to center on (None if we should ignore the y position) """ if x: self.x = x - self.display.width / 2 / self.scale if y: self.y = y - self.display.height / 2 / self.scale
def pre_render(self, display): """ Sets the offset property of the given Display so that it matches our (previously) calculated x/y values. :param Display display: the Display, whose offset we will change here """ self.display.offsets[0] = self.x self.display.offsets[1] = self.y
def __init__(self, name: str = "start", **kwargs): super().__init__() self.name = name self.id = kwargs.get("id", 0) # type: int # handle keyboard inputs self.keyboard_inputs = kwargs.get("keyboard_inputs", KeyboardInputs([])) # type: KeyboardInputs # our Display object self.display = kwargs.get("display", None) # type: Display self.max_fps = kwargs.get("max_fps", 60) # type: float
def screen_func(stage): """ Sets up the Stage by adding all layers (one-by-one) from the tmx file to the Stage. :param Stage stage: """ assert isinstance(stage.screen, Level), "ERROR: screen property of a Stage that uses Level.screen_func to stage a Screen must be a Level object!" # force add the default physics functions to the Stage's options defaults(stage.options, {"components": [Viewport(stage.screen.display)], "physics_collision_detector": AABBCollision.collide, "tile_sprite_handler": functools.partial(PhysicsComponent.tile_sprite_handler, TileSprite) }) for layer in stage.screen.tmx_obj.layers: stage.add_tiled_layer(layer, stage.screen.tmx_obj)