我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用pygame.locals()。
def showStartScreen(titlescreen): which = 0 directions = {pygame.locals.K_s: 1, pygame.locals.K_DOWN: 1, pygame.locals.K_w: -1, pygame.locals.K_UP: -1} whichgamemode = {0: runsingleplayer, 1: runmultibattle, 2: runcoop} titlescreen.drawStartScreen(which) pygame.display.update() running = True while running: # menu key handler for event in pygame.event.get(): # event handling loop if event.type == pygame.locals.QUIT or ( event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_ESCAPE): terminate() elif event.type == pygame.locals.KEYDOWN and \ event.key in directions: which = (which + directions[event.key]) % 3 titlescreen.drawPressChooseModeScreen(which) pygame.display.update() elif event.type == pygame.locals.KEYDOWN and \ event.key == pygame.locals.K_RETURN: global runGame runGame = whichgamemode[which] running = False break
def showGameOverScreen(titlescreen): titlescreen.drawGameOverScreen() pygame.display.update() pygame.time.wait(1000) pygame.event.get() running = True while running: # menu key handler for event in pygame.event.get(): # event handling loop if event.type == pygame.locals.QUIT or ( event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_ESCAPE): terminate() elif event.type == pygame.locals.KEYDOWN or \ event.type == pygame.locals.MOUSEBUTTONDOWN: pygame.event.get() # clear queue running = False break
def showWinnerScreen(titlescreen): titlescreen.drawWinnerScreen() pygame.display.update() pygame.time.wait(1000) pygame.event.get() running = True while running: # menu key handler for event in pygame.event.get(): # event handling loop if event.type == pygame.locals.QUIT or ( event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_ESCAPE): terminate() elif event.type == pygame.locals.KEYDOWN or \ event.type == pygame.locals.MOUSEBUTTONDOWN: pygame.event.get() # clear queue running = False break
def showPlayerWonScreen(result, titlescreen): titlescreen.drawBatlleWinnerScreen(result+1) pygame.display.update() pygame.time.wait(1000) pygame.event.get() running = True while running: # menu key handler for event in pygame.event.get(): # event handling loop if event.type == pygame.locals.QUIT or ( event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_ESCAPE): terminate() elif event.type == pygame.locals.KEYDOWN or \ event.type == pygame.locals.MOUSEBUTTONDOWN: pygame.event.get() # clear queue running = False break
def showChangeMode(titlescreen): which = 0 directions = {pygame.locals.K_s: 1, pygame.locals.K_DOWN: 1, pygame.locals.K_w: -1, pygame.locals.K_UP: -1} whichgamemode = {0: runsingleplayer, 1: runmultibattle, 2: runcoop} titlescreen.drawStartScreen(which) pygame.display.update() while True: # menu key handler for event in pygame.event.get(): # event handling loop if event.type == pygame.locals.QUIT or ( event.type == pygame.locals.KEYDOWN and event.key == pygame.locals.K_ESCAPE): terminate() elif event.type == pygame.locals.KEYDOWN and \ event.key in directions: which = (which+directions[event.key]) % 3 titlescreen.drawPressChooseModeScreen(which) pygame.display.update() elif event.type == pygame.locals.KEYDOWN and \ event.key == pygame.locals.K_RETURN: newmode = whichgamemode[which] return newmode
def __init__(self,data,globals=None,locals=None,loader=None,**params): gui.Document.__init__(self,**params) # This ensures that the whole HTML document is left-aligned within # the rendered surface. self.style.align = -1 _globals,_locals = globals,locals if _globals == None: _globals = {} if _locals == None: _locals = {} self._globals = _globals self._locals = _locals #font = gui.theme.get("label","","font") if (htmllib): # The constructor is slightly different p = _html(None, 0) else: p = _html() p.init(self,self.style.font,self.style.color,_globals,_locals, loader=loader) p.feed(data) p.close() p.mydone()
def update(self, game): action = self._readAction(game) if action is None: action = (0, 0) from pygame.locals import K_SPACE if game.keystate[K_SPACE] and self.orientation[1] == 0: action = (action[0] * sqrt(self.strength), -self.strength) elif self.orientation[1] == 0 or self.airsteering: action = (action[0] * sqrt(self.strength), 0) else: action = (0, 0) self.physics.activeMovement(self, action) VGDLSprite.update(self, game) # --------------------------------------------------------------------- # Termination criteria # ---------------------------------------------------------------------
def test_issue_208(self): """PATCH: pygame.scrap on X11, fix copying into PRIMARY selection Copying into theX11 PRIMARY selection (mouse copy/paste) would not work due to a confusion between content type and clipboard type. """ from pygame import display, event, freetype from pygame.locals import SCRAP_SELECTION, SCRAP_TEXT from pygame.locals import KEYDOWN, K_y, QUIT success = False freetype.init() font = freetype.Font(None, 24) display.init() display.set_caption("Interactive X11 Paste Test") screen = display.set_mode((600, 200)) screen.fill(pygame.Color('white')) text = "Scrap put() succeeded." msg = ('Some text has been placed into the X11 clipboard.' ' Please click the center mouse button in an open' ' text window to retrieve it.' '\n\nDid you get "{}"? (y/n)').format(text) word_wrap(screen, msg, font, 6) display.flip() event.pump() scrap.init() scrap.set_mode(SCRAP_SELECTION) scrap.put(SCRAP_TEXT, text.encode('UTF-8')) while True: e = event.wait() if e.type == QUIT: break if e.type == KEYDOWN: success = (e.key == K_y) break pygame.display.quit() self.assertTrue(success)
def update_position(self, eventkey): if eventkey in player1_keys: self.movement.feet_left = not self.movement.feet_left if eventkey == pygame.locals.K_a: self.x -= self.movement.step_size_x self.rect.x = self.x walking_direction = 1 elif eventkey == pygame.locals.K_d: self.x += self.movement.step_size_x self.rect.x = self.x walking_direction = 2 elif eventkey == pygame.locals.K_w: self.y -= self.movement.step_size_y self.rect.y = self.y walking_direction = 3 elif eventkey == pygame.locals.K_s: self.y += self.movement.step_size_y self.rect.y = self.y walking_direction = 4 if not self.movement.cover and not ( self.movement.shot and self.wasincover): self.image = self.imagedict[self.movement.current_direction][ self.movement.which_leg()] self.rect = self.image.get_rect() [self.rect.x, self.rect.y] = [self.x, self.y] self.moved = True else: return self.fix_position(self.check_wall_collision() + self.check_character_collision(), walking_direction)
def update_position(self, eventkey): if (eventkey == pygame.locals.K_LEFT): self.x -= self.movement.step_size_x self.rect.x = self.x self.image = self.imagedict['l'][self.movement.which_leg()] self.direction = 1 self.movement.cover = False elif (eventkey == pygame.locals.K_RIGHT): self.x += self.movement.step_size_x self.rect.x = self.x self.image = self.imagedict['r'][self.movement.which_leg()] self.direction = 2 self.movement.cover = False elif (eventkey == pygame.locals.K_UP): self.y -= self.movement.step_size_y self.rect.y = self.y self.image = self.imagedict['u'][self.movement.which_leg()] self.direction = 3 self.movement.cover = False elif (eventkey == pygame.locals.K_DOWN): self.y += self.movement.step_size_y self.rect.y = self.y self.image = self.imagedict['d'][self.movement.which_leg()] self.direction = 4 self.movement.cover = False else: return self.fix_position(self.check_wall_collision() + self.check_character_collision(), self.direction)
def declare_possible_actions(self): from pygame.locals import K_LEFT, K_RIGHT, K_UP, K_DOWN actions = {} actions["UP"] = K_UP actions["DOWN"] = K_DOWN actions["LEFT"] = K_LEFT actions["RIGHT"] = K_RIGHT actions["NO_OP"] = 0 return actions
def _readMultiActions(self, game): """ Read multiple simultaneously pressed button actions. """ from pygame.locals import K_LEFT, K_RIGHT, K_UP, K_DOWN, K_a, K_s, K_d, K_w res = [] if self.alternate_keys: if game.keystate[K_d]: res += [RIGHT] elif game.keystate[K_a]: res += [LEFT] if game.keystate[K_w]: res += [UP] elif game.keystate[K_s]: res += [DOWN] else: if game.keystate[K_RIGHT]: res += [RIGHT] elif game.keystate[K_LEFT]: res += [LEFT] if game.keystate[K_UP]: res += [UP] elif game.keystate[K_DOWN]: res += [DOWN] return res
def declare_possible_actions(self): from pygame.locals import K_LEFT, K_RIGHT actions = {} actions["LEFT"] = K_LEFT actions["RIGHT"] = K_RIGHT actions["NO_OP"] = 0 return actions
def declare_possible_actions(self): from pygame.locals import K_UP, K_DOWN actions = {} actions["UP"] = K_UP actions["DOWN"] = K_DOWN actions["NO_OP"] = 0 return actions
def declare_possible_actions(self): from pygame.locals import K_SPACE actions = HorizontalAvatar.declare_possible_actions(self) actions["SPACE"] = K_SPACE return actions
def declare_possible_actions(self): from pygame.locals import K_SPACE actions = MovingAvatar.declare_possible_actions(self) actions["SPACE"] = K_SPACE return actions
def _shoot(self, game): from pygame.locals import K_SPACE if self.stype and game.keystate[K_SPACE]: u = unitVector(self.orientation) newones = game._createSprite([self.stype], (self.lastrect.left + u[0] * self.lastrect.size[0], self.lastrect.top + u[1] * self.lastrect.size[1])) if len(newones) > 0 and isinstance(newones[0], OrientedSprite): newones[0].orientation = unitVector(self.orientation) self._reduceAmmo()
def isDone(self, game): """ returns whether the game is over, with a win/lose flag """ from pygame.locals import K_ESCAPE, QUIT if game.keystate[K_ESCAPE] or pygame.event.peek(QUIT): return True, False else: return False, None # This needs to go at the bottom so that classes in core are already loaded
def runsingleplayer(SCREEN, ImagesPlayer, ImagesEnemy, DISPLAYSURF, FPSCLOCK, FPS, titlescreen): # Group for drawing all sprites rendergroup = pygame.sprite.RenderPlain() wall_list = utils.createwalls(SCREEN, rendergroup) # Initiate main character player_list = pygame.sprite.Group() enemy_list = pygame.sprite.Group() Marcus = characters.Player('Marcus', ImagesPlayer, SCREEN, rendergroup, wall_list, player_list, enemy_list) friendly_bullet_list = pygame.sprite.Group() enemy_bullet_list = pygame.sprite.Group() # Create enemies N = 2 utils.createenemies(N, ImagesEnemy, player_list, SCREEN, rendergroup, wall_list, enemy_list) while (not Marcus.dead) and len(enemy_list.sprites()) > 0: # main loop for event in pygame.event.get(): # event handling loop if event.type == pygame.locals.QUIT: terminate() elif event.type == pygame.locals.KEYDOWN and \ event.key == pygame.locals.K_ESCAPE: newmode = showPauseScreen(titlescreen) if newmode != 'no changes': global runGame runGame = newmode return 2 elif event.type == pygame.locals.KEYDOWN and \ event.key == pygame.locals.K_r: Marcus.reload() elif event.type == pygame.locals.KEYDOWN: Marcus.update_position(event.key) elif event.type == pygame.locals.MOUSEBUTTONDOWN: Marcus.shoot(friendly_bullet_list, rendergroup) player_list.update() enemy_list.update(enemy_bullet_list, rendergroup) for i in range(10): friendly_bullet_list.update(enemy_list, wall_list) enemy_bullet_list.update(player_list, wall_list) DISPLAYSURF.fill(BACKGROUND) rendergroup.draw(DISPLAYSURF) pygame.display.update() FPSCLOCK.tick(FPS) return int(Marcus.dead)
def runmultibattle(SCREEN, ImagesPlayer, ImagesEnemy, DISPLAYSURF, FPSCLOCK, FPS, titlescreen): # 1v1 battle multiplayer mode # Group for drawing all sprites rendergroup = pygame.sprite.RenderPlain() wall_list = utils.createwalls(SCREEN, rendergroup) # Initiate player1 player_list = pygame.sprite.Group() enemy_list = pygame.sprite.Group() Marcus = characters.Player('Marcus', ImagesPlayer, SCREEN, rendergroup, wall_list, player_list, enemy_list) # initiating bullet sprite groups friendly_bullet_list = pygame.sprite.Group() enemy_bullet_list = pygame.sprite.Group() Cole = characters.Player2('Cole', ImagesPlayer, SCREEN, rendergroup, wall_list, player_list, enemy_list, True) while not Marcus.dead and not Cole.dead: # main game loop for event in pygame.event.get(): # event handling loop if event.type == pygame.locals.QUIT: terminate() elif event.type == pygame.locals.KEYDOWN and \ event.key == pygame.locals.K_ESCAPE: newmode = showPauseScreen(titlescreen) if newmode != 'no changes': global runGame runGame = newmode return 2 elif event.type == pygame.locals.KEYDOWN and \ event.key == pygame.locals.K_r: Marcus.reload() elif event.type == pygame.locals.KEYDOWN and \ event.key == pygame.locals.K_k: Cole.reload() elif event.type == pygame.locals.KEYDOWN and \ event.key == pygame.locals.K_l: Cole.shoot(enemy_bullet_list, rendergroup) elif event.type == pygame.locals.KEYDOWN: Marcus.update_position(event.key) Cole.update_position(event.key) elif event.type == pygame.locals.MOUSEBUTTONDOWN: Marcus.shoot(friendly_bullet_list, rendergroup) player_list.update() enemy_list.update() for i in range(10): friendly_bullet_list.update(enemy_list, wall_list) enemy_bullet_list.update(player_list, wall_list) DISPLAYSURF.fill(BACKGROUND) rendergroup.draw(DISPLAYSURF) pygame.display.update() FPSCLOCK.tick(FPS) return int(Marcus.dead)
def runcoop(SCREEN, ImagesPlayer, ImagesEnemy, DISPLAYSURF, FPSCLOCK, FPS, titlescreen): # Group for drawing all sprites rendergroup = pygame.sprite.RenderPlain() wall_list = utils.createwalls(SCREEN, rendergroup) # Initiate main character player_list = pygame.sprite.Group() enemy_list = pygame.sprite.Group() Marcus = characters.Player('Marcus', ImagesPlayer, SCREEN, rendergroup, wall_list, player_list, enemy_list) Cole = characters.Player2('Cole', ImagesPlayer, SCREEN, rendergroup, wall_list, player_list, enemy_list, False) friendly_bullet_list = pygame.sprite.Group() enemy_bullet_list = pygame.sprite.Group() # Create enemies N = 2 utils.createenemies(N, ImagesEnemy, player_list, SCREEN, rendergroup, wall_list, enemy_list) # main game loop while (not Marcus.dead or not Cole.dead) and len(enemy_list.sprites()) > 0: for event in pygame.event.get(): # event handling loop if event.type == pygame.locals.QUIT: terminate() elif event.type == pygame.locals.KEYDOWN and \ event.key == pygame.locals.K_ESCAPE: newmode = showPauseScreen(titlescreen) if newmode != 'no changes': global runGame runGame = newmode return 2 elif event.type == pygame.locals.KEYDOWN and \ event.key == pygame.locals.K_r: Marcus.reload() elif event.type == pygame.locals.KEYDOWN and \ event.key == pygame.locals.K_k: Cole.reload() elif event.type == pygame.locals.KEYDOWN and \ event.key == pygame.locals.K_l: Cole.shoot(friendly_bullet_list, rendergroup) elif event.type == pygame.locals.KEYDOWN: Marcus.update_position(event.key) Cole.update_position(event.key) elif event.type == pygame.locals.MOUSEBUTTONDOWN: Marcus.shoot(friendly_bullet_list, rendergroup) player_list.update() enemy_list.update(enemy_bullet_list, rendergroup) for i in range(10): friendly_bullet_list.update(enemy_list, wall_list) enemy_bullet_list.update(player_list, wall_list) DISPLAYSURF.fill(BACKGROUND) rendergroup.draw(DISPLAYSURF) pygame.display.update() FPSCLOCK.tick(FPS) return int(Marcus.dead and Cole.dead)
def render_multiline(self,font,text): """ renders multiline TEXT on the pygame surface SURF with the font style FONT. A new line in text is denoted by \n, no other characters are escaped. Other forms of white-spaces should be converted to space. returns the updated surface, words and the character bounding boxes. """ # get the number of lines lines = text.split('\n') lengths = [len(l) for l in lines] # font parameters: line_spacing = font.get_sized_height() + 1 # initialize the surface to proper size: line_bounds = font.get_rect(lines[np.argmax(lengths)]) fsize = (round(2.0*line_bounds.width), round(1.25*line_spacing*len(lines))) surf = pygame.Surface(fsize, pygame.locals.SRCALPHA, 32) bbs = [] space = font.get_rect('O') x, y = 0, 0 for l in lines: x = 0 # carriage-return y += line_spacing # line-feed for ch in l: # render each character if ch.isspace(): # just shift x += space.width else: # render the character ch_bounds = font.render_to(surf, (x,y), ch) ch_bounds.x = x + ch_bounds.x ch_bounds.y = y - ch_bounds.y x += ch_bounds.width bbs.append(np.array(ch_bounds)) # get the union of characters for cropping: r0 = pygame.Rect(bbs[0]) rect_union = r0.unionall(bbs) # get the words: words = ' '.join(text.split()) # crop the surface to fit the text: bbs = np.array(bbs) surf_arr, bbs = crop_safe(pygame.surfarray.pixels_alpha(surf), rect_union, bbs, pad=5) surf_arr = surf_arr.swapaxes(0,1) #self.visualize_bb(surf_arr,bbs) return surf_arr, words, bbs
def render(self): # Close the display if the renderer options is set to disable the display if not self.display_quitted and not self.renderer_options.show_display: # Replace the screen surface with in-memory surface self.screen = self.screen.copy() # Close the display pygame.display.quit() # Prevent from further closing self.display_quitted = True # Clear the overlays self.dirty_groups.clear(self.screen, self.background) # Update the overlays by the environment state self._update_overlay_pos() self._update_overlay_visibility() # Draw the overlays dirty = self.dirty_groups.draw(self.screen) # Update only the dirty surface if self.renderer_options.show_display: pygame.display.update(dirty) # Limit the max frames per second if self.renderer_options.show_display: self.clock.tick(self.renderer_options.max_fps) # Handle the events if self.renderer_options.show_display: for event in pygame.event.get(): # Detect the quit event if event.type == pygame.locals.QUIT: # Indicate the rendering should stop return False # Detect the keydown event if self.renderer_options.enable_key_events: if event.type == pygame.locals.KEYDOWN: # Get the agent index of the first player team_agent_index = 0 agent_index = self.env.get_agent_index( 'PLAYER', team_agent_index) # Prepare the cached action cached_action = None if event.key == pygame.locals.K_RIGHT: cached_action = 'MOVE_RIGHT' elif event.key == pygame.locals.K_UP: cached_action = 'MOVE_UP' elif event.key == pygame.locals.K_LEFT: cached_action = 'MOVE_LEFT' elif event.key == pygame.locals.K_DOWN: cached_action = 'MOVE_DOWN' elif event.key == pygame.locals.K_s: cached_action = 'STAND' # Take the cached action and update the state if cached_action: self.env.take_cached_action(agent_index, cached_action) self.env.update_state() # Indicate the rendering should continue return True
def render(self): # Close the display if the renderer options is set to disable the display if not self.display_quitted and not self.renderer_options.show_display: # Replace the screen surface with in-memory surface self.screen = self.screen.copy() # Close the display pygame.display.quit() # Prevent from further closing self.display_quitted = True # Clear the overlays self.dirty_groups.clear(self.screen, self.background) # Update the overlays by the environment state self._update_overlay_pos() self._update_overlay_visibility() # Draw the overlays dirty = self.dirty_groups.draw(self.screen) # Update only the dirty surface if self.renderer_options.show_display: pygame.display.update(dirty) # Limit the max frames per second if self.renderer_options.show_display: self.clock.tick(self.renderer_options.max_fps) # Handle the events if self.renderer_options.show_display: for event in pygame.event.get(): # Detect the quit event if event.type == pygame.locals.QUIT: # Indicate the rendering should stop return False # Detect the keydown event if self.renderer_options.enable_key_events: if event.type == pygame.locals.KEYDOWN: if event.key == pygame.locals.K_RIGHT: self.env.take_cached_action(0, 'MOVE_RIGHT') elif event.key == pygame.locals.K_UP: self.env.take_cached_action(0, 'MOVE_UP') elif event.key == pygame.locals.K_LEFT: self.env.take_cached_action(0, 'MOVE_LEFT') elif event.key == pygame.locals.K_DOWN: self.env.take_cached_action(0, 'MOVE_DOWN') elif event.key == pygame.locals.K_s: self.env.take_cached_action(0, 'STAND') # Update the state self.env.update_state() # Indicate the rendering should continue return True