我们从Python开源项目中,提取了以下31个代码示例,用于说明如何使用pygame.USEREVENT。
def test_post__and_poll(self): # __doc__ (as of 2008-06-25) for pygame.event.post: # pygame.event.post(Event): return None # place a new event on the queue e1 = pygame.event.Event(pygame.USEREVENT, attr1='attr1') pygame.event.post(e1) posted_event = pygame.event.poll() self.assertEquals ( e1.attr1, posted_event.attr1, race_condition_notification ) # fuzzing event types for i in range(1, 11): pygame.event.post(pygame.event.Event(i)) self.assertEquals ( pygame.event.poll().type, i, race_condition_notification )
def delete_lines(self): remove = [y for y, row in enumerate(self.board) if all(row)] for y in remove: line_sound = pygame.mixer.Sound("assets/sounds/Line_Clear.wav") line_sound.play() self.delete_line(y) self.score += 10 * self.level self.goal -= 1 if self.goal == 0: if self.level < 10: self.level += 1 self.goal = 5 * self.level else: self.goal = '-' if self.level <= 9: pygame.time.set_timer(pygame.USEREVENT, (500 - 50 * (self.level-1))) else: pygame.time.set_time(pygame.USEREVENT, 100)
def getMove(self, timeout=60): """ Gets the necessary input from the board then calls the TTTNeuralNet's getMove function, passing said input :param timeout: Added to match signature of method in parent class """ move = self.game.board.translateNumToPos(self.neuralNet.getMove(self.game.turn, self.game.board.sBoard)) self.playPiece(move) self.game.board.cursorPos = self.game.board.getEmptySpace() if self.game.board.cursorPos is not None: self.game.board.updateCursor() pygame.display.flip() self.game.clock.tick(self.game.fps) pygame.event.post(pygame.event.Event(pygame.USEREVENT, {})) # posting an event keeps the game loop going return move # this is here for when the multiplayer will be properly added
def test_Event(self): # __doc__ (as of 2008-08-02) for pygame.event.Event: # pygame.event.Event(type, dict): return Event # pygame.event.Event(type, **attributes): return Event # create a new event object # # Creates a new event with the given type. The event is created with # the given attributes and values. The attributes can come from a # dictionary argument, or as string keys from a dictionary. # # The given attributes will be readonly attributes on the new event # object itself. These are the only attributes on the Event object, # there are no methods attached to Event objects. e = pygame.event.Event(pygame.USEREVENT, some_attr=1, other_attr='1') self.assertEquals(e.some_attr, 1) self.assertEquals(e.other_attr, "1")
def __init__(self): pygame.init() pygame.key.set_repeat(10, 100) # set constants self.COLOR_WHITE = (255, 255, 255) self.COLOR_BLACK = (0, 0, 0) self.GAME_WIDTH = 400 self.GAME_HEIGHT = 400 self.BALL_WIDTH = 20 self.BALL_HEIGHT = 20 self.PADDLE_WIDTH = 50 self.PADDLE_HEIGHT = 10 self.GAME_FLOOR = 350 self.GAME_CEILING = 10 self.BALL_VELOCITY = 10 self.PADDLE_VELOCITY = 20 self.FONT_SIZE = 30 self.MAX_TRIES_PER_GAME = 100 self.CUSTOM_EVENT = pygame.USEREVENT + 1 self.font = pygame.font.SysFont("Comic Sans MS", self.FONT_SIZE) # we want to start the game remotely, so moving this block # to its own function self.frames = collections.deque(maxlen=4) self.game_over = False # initialize positions self.paddle_x = self.GAME_WIDTH // 2 self.game_score = 0 self.ball_x = random.randint(0, self.GAME_WIDTH) self.ball_y = self.GAME_CEILING self.num_tries = 0 # set up display, clock, etc self.screen = pygame.display.set_mode( (self.GAME_WIDTH, self.GAME_HEIGHT)) self.clock = pygame.time.Clock()
def __init__(self): # run pygame in headless mode # os.environ["SDL_VIDEODRIVER"] = "dummy" pygame.init() pygame.key.set_repeat(10, 100) # set constants self.COLOR_WHITE = (255, 255, 255) self.COLOR_BLACK = (0, 0, 0) self.GAME_WIDTH = 400 self.GAME_HEIGHT = 400 self.BALL_WIDTH = 20 self.BALL_HEIGHT = 20 self.PADDLE_WIDTH = 50 self.PADDLE_HEIGHT = 10 self.GAME_FLOOR = 350 self.GAME_CEILING = 10 # based on experimentation, the ball tends to move 4 times # between each paddle movement. Since here we alternate ball # and paddle movement, we make ball move 4x faster. self.BALL_VELOCITY = 10 self.PADDLE_VELOCITY = 20 self.FONT_SIZE = 30 # self.MAX_TRIES_PER_GAME = 100 self.MAX_TRIES_PER_GAME = 1 self.CUSTOM_EVENT = pygame.USEREVENT + 1 self.font = pygame.font.SysFont("Comic Sans MS", self.FONT_SIZE)
def test_post_large_user_event(self): pygame.event.post(pygame.event.Event(pygame.USEREVENT, {'a': "a" * 1024})) e = pygame.event.poll() self.assertEquals(e.type, pygame.USEREVENT) self.assertEquals(e.a, "a" * 1024)
def test_get(self): # __doc__ (as of 2008-06-25) for pygame.event.get: # pygame.event.get(): return Eventlist # pygame.event.get(type): return Eventlist # pygame.event.get(typelist): return Eventlist # get events from the queue # Put 10 events on the queue for _ in range(1, 11): pygame.event.post(pygame.event.Event(pygame.USEREVENT)) self.assert_ ( len(pygame.event.get()) >= 10 )
def test_get(self): # __doc__ (as of 2008-08-02) for pygame.fastevent.get: # pygame.fastevent.get() -> list of Events # get all events from the queue for _ in range(1, 11): event.post(event.Event(pygame.USEREVENT)) self.assertEquals ( [e.type for e in fastevent.get()], [pygame.USEREVENT] * 10, race_condition_notification )
def todo_test_set_timer(self): # __doc__ (as of 2008-08-02) for pygame.time.set_timer: # pygame.time.set_timer(eventid, milliseconds): return None # repeatedly create an event on the event queue # # Set an event type to appear on the event queue every given number of # milliseconds. The first event will not appear until the amount of # time has passed. # # Every event type can have a separate timer attached to it. It is # best to use the value between pygame.USEREVENT and pygame.NUMEVENTS. # # To disable the timer for an event, set the milliseconds argument to 0. self.fail()
def run(self): pygame.init() icon = pygame.image.load('assets/images/icon.png') pygame.display.set_icon(icon) pygame.display.set_caption('Tetris') pygame.time.set_timer(pygame.USEREVENT, 500) start_sound = pygame.mixer.Sound('assets/sounds/Start.wav') start_sound.play() bgm = pygame.mixer.music.load('assets/sounds/bgm.mp3') while True: if self.check_reset: self.board.newGame() self.check_reset = False pygame.mixer.music.play(-1, 0.0) if self.board.game_over(): self.screen.fill(BLACK) pygame.mixer.music.stop() self.board.GameOver() self.HighScore() self.check_reset = True self.board.init_board() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYUP and event.key == K_p: self.screen.fill(BLACK) pygame.mixer.music.stop() self.board.pause() pygame.mixer.music.play(-1, 0.0) elif event.type == KEYDOWN: self.handle_key(event.key) elif event.type == pygame.USEREVENT: self.board.drop_piece() # self.screen.fill(BLACK) self.board.draw() pygame.display.update() self.clock.tick(30)
def __init__(self): self.index = pygame.USEREVENT self.pool = []
def get_inputs(self): # add all input events to the queue for event in pygame.event.get(): if event.type == pygame.QUIT: self.add_message(Message(MessageType.EXIT_GAME, None)) else: # timer or move? if event.type >= pygame.USEREVENT: self.add_message(Message(event.type, None)) else: self.add_message(Message(event.type, event)) return False
def add_cl_lines(self, n): linescores = [0, 40, 100, 300, 1200] self.lines += n self.score += linescores[n] * self.level if self.lines >= self.level*6: self.level += 1 newdelay = 1000-50*(self.level-1) newdelay = 100 if newdelay < 100 else newdelay pygame.time.set_timer(pygame.USEREVENT+1, newdelay)
def test_post(self): # __doc__ (as of 2008-08-02) for pygame.fastevent.post: # pygame.fastevent.post(Event) -> None # place an event on the queue # # This will post your own event objects onto the event queue. # You can past any event type you want, but some care must be # taken. For example, if you post a MOUSEBUTTONDOWN event to the # queue, it is likely any code receiving the event will expect # the standard MOUSEBUTTONDOWN attributes to be available, like # 'pos' and 'button'. # # Because pygame.fastevent.post() may have to wait for the queue # to empty, you can get into a dead lock if you try to append an # event on to a full queue from the thread that processes events. # For that reason I do not recommend using this function in the # main thread of an SDL program. for _ in range(1, 11): fastevent.post(event.Event(pygame.USEREVENT)) self.assertEquals ( [e.type for e in event.get()], [pygame.USEREVENT] * 10, race_condition_notification ) try: # Special case for post: METH_O. fastevent.post(1) except TypeError: e = geterror() msg = ("argument 1 must be %s, not %s" % (fastevent.Event.__name__, type(1).__name__)) self.failUnlessEqual(str(e), msg) else: self.fail()
def __init__(self): debug.debugPrint("Main", "Screensize: ", config.screenwidth, config.screenheight) config.Logs.Log("Screensize: " + str(config.screenwidth) + " x " + str(config.screenheight)) config.Logs.Log( "Scaling ratio: " + "{0:.2f}".format(config.dispratioW) + ':' + "{0:.2f}".format(config.dispratioH)) self.dim = 'Bright' # either Bright or Dim (or '' for don't change when a parameter self.state = 'Home' # one of Home, NonHome, Maint, Cover, Alert # Central Task List self.Tasks = EventList() self.WatchNodes = {} # Nodes that should be watched for changes (key is node address, value is [alerts] # todo if ever possible to delete alerts then need id per comment on vars self.WatchVars = {} # Variables that should be watched for changes (key is (vartype,varid) value is [alerts] # todo if watches could be dynamic then delete needs to pass in the alert to id which to delete self.Deferrals = [] self.WatchVarVals = {} # most recent reported watched variable values # Events that drive the main control loop # self.ACTIVITYTIMER = pygame.event.Event( # pygame.USEREVENT + 1) # screen activity timing (Dimming, persistence etc) self.ACTIVITYTIMER = pygame.USEREVENT + 1 self.ISYChange = pygame.USEREVENT + 2 # Node state change in a current screen watched node on the ISY self.ISYAlert = pygame.USEREVENT + 3 # Mpde state change in watched node for alerts self.ISYVar = pygame.USEREVENT + 4 # Var value change for a watched variable on ISY self.NOEVENT = pygame.event.Event(pygame.NOEVENT) self.AS = None # Active Screen self.ScreensDict = {} # all the sceens by name for setting navigation keys self.Chain = 0 # which screen chain is active 0: Main chain 1: Secondary Chain
def __init__(self): self.BaseTime = 0 self.List = [] self.finder = {} self.TASKREADY = pygame.event.Event(pygame.USEREVENT, {}) # todo think this could just be the int constant and remove .type below where used
def init_game(self): self.board = new_board() self.new_stone() self.level = 1 self.score = 0 self.lines = 0 pygame.time.set_timer(pygame.USEREVENT+1, 1000)
def play(self, caption="sc8pr", icon=None, mode=True): "Initialize pygame and run the main drawing / event handling loop" # Initialize pygame.init() self._clock = pygame.time.Clock() pygame.key.set_repeat(400, 80) _pd.set_caption(caption) try: try: icon = pygame.image.load(icon) except: icon = Image.fromBytes(sc8prData("alien")).image _pd.set_icon(icon) except: logError() w, h = self._size self._fixedAspect = w / h mode = self._pygameMode(mode) self._mode = mode self.image = _pd.set_mode(self._size, mode) self.key = None self.mouse = pygame.event.Event(pygame.USEREVENT, code=None, pos=(0,0), description="Sketch startup") # Run setup try: if hasattr(self, "setup"): self.setup() else: main = sys.modules["__main__"] if hasattr(main, "setup"): main.setup(self) except: logError() # Drawing/event loop while not self.quit: try: self.frameCount += 1 br = self.dirtyRegions flip = br is None self.draw() if not flip: br += self.dirtyRegions flip = self._largeArea() self._clock.tick(self.frameRate) if flip: _pd.flip() else: _pd.update(br) if self.capture is not None: self.capture.capture(self) if self.ondraw: self.ondraw() self._evHandle() except: logError() pygame.quit() mod = sys.modules.get("sc8pr.text") if mod: mod.Font.dumpCache() return self
def test_Event(self): # __doc__ (as of 2008-08-02) for pygame.event.Event: # pygame.event.Event(type, dict): return Event # pygame.event.Event(type, **attributes): return Event # create a new event object # # Creates a new event with the given type. The event is created with # the given attributes and values. The attributes can come from a # dictionary argument, or as string keys from a dictionary. # # The given attributes will be readonly attributes on the new event # object itself. These are the only attributes on the Event object, # there are no methods attached to Event objects. e = pygame.event.Event(pygame.USEREVENT, some_attr=1, other_attr='1') self.assertEquals(e.some_attr, 1) self.assertEquals(e.other_attr, "1") # Event now uses tp_dictoffset and tp_members: request 62 # on Motherhamster Bugzilla. self.assertEquals(e.type, pygame.USEREVENT) self.assert_(e.dict is e.__dict__) e.some_attr = 12 self.assertEquals(e.some_attr, 12) e.new_attr = 15 self.assertEquals(e.new_attr, 15) # For Python 2.x a TypeError is raised for a readonly member; # for Python 3.x it is an AttributeError. self.assertRaises((TypeError, AttributeError), setattr, e, 'type', 0) self.assertRaises((TypeError, AttributeError), setattr, e, 'dict', None) # Ensure attributes are visible to dir(), part of the original # posted request. d = dir(e) self.assert_('type' in d) self.assert_('dict' in d) self.assert_('__dict__' in d) self.assert_('some_attr' in d) self.assert_('other_attr' in d) self.assert_('new_attr' in d)
def enter_text(eq, screen, max_length, lower = False, upper = False, title = False): global pressed BLUE = (0,0,255) allowed_values = [i for i in range(97, 123)] +\ [i for i in range(48,58)] BLINK_EVENT = pygame.USEREVENT + 0 pygame.time.set_timer(BLINK_EVENT, 800) blinky = cycle(["_", " "]) next_blink = next(blinky) displaytext('GAME OVER', 16, 320,60, WHITE, screen) displaytext('Enter your name:', 16, 320,125, WHITE, screen) for event in eq: if event.type == BLINK_EVENT: next_blink = next(blinky) # if input is in list of allowed characters, add to variable elif event.type == KEYUP and event.key in allowed_values \ and len(pressed) < max_length: # caps entry? if pygame.key.get_mods() & KMOD_SHIFT or pygame.key.get_mods()\ & KMOD_CAPS: pressed += chr(event.key).upper() # lowercase entry else: pressed += chr(event.key) # otherwise, only the following are valid inputs elif event.type == KEYUP: if event.key == K_BACKSPACE: pressed = pressed[:-1] elif event.key == K_SPACE: pressed += " " # only draw underscore if input is not at max character length if len(pressed) < max_length: displaytext(pressed + next_blink, 16, 320, 180, WHITE, screen) else: displaytext(pressed, 15, 320, 180, WHITE, screen) # perform any selected string operations if lower: pressed = pressed.lower() if upper: pressed = pressed.upper() if title: pressed = pressed.title()
def __init__(self, screen): self.done = False self.screen = screen self.clock = pg.time.Clock() self.fps = 60 self.RADIO_STATION = '39' # or 1591330390268116913 self.BACKGROUND_IMG = 'img/bg/day_tree.png' self.SCREEN_WIDTH = SCREEN_WIDTH self.SCREEN_HEIGHT = SCREEN_HEIGHT self.RADIO_RUNNING = False self.RESTING = False self.SHOWGOALS = False self.grass = 'img/bg/day_grass.png' self.day_clouds = pg.sprite.RenderUpdates() self.night_clouds = pg.sprite.RenderUpdates() self.all_sprites_list = pg.sprite.RenderUpdates() self.quote_list = return_list('quotes.txt') self.contributions = return_list('contributions.txt') self.goals = return_list('goals.txt') self.weather = Weather() self.weather_observation = {} self.phrase = random.choice(self.quote_list) #self.cwd = os.getcwd() #windows self.cwd = '/home/pi/.config/pianobar' # linux ## DAIYE COLORS ### self.HEADER_COLOR = pg.Color('black') self.CONTENT_COLOR = pg.Color('indianred4') self.BG_COLOR = pg.Color('skyblue') self.current_events = [] self.upcoming_events = [] # User events: self.UPDATECALENDAR = pg.USEREVENT + 1 self.UPDATEQUOTE = pg.USEREVENT + 2 self.NIGHTRADIO = pg.USEREVENT + 3 self.CHANGESTATE = pg.USEREVENT + 4 self.UPDATEWEATHER = pg.USEREVENT + 5 #self.SHOWGOALS = pg.USEREVENT + 6 pg.time.set_timer(self.UPDATECALENDAR, 60000) #update calendar every 60 seconds pg.time.set_timer(self.UPDATEQUOTE, 20000) #update quote every 20 seconds pg.time.set_timer(self.NIGHTRADIO,300000) # check for relaxation radio time pg.time.set_timer(self.UPDATEWEATHER, 600000) pg.time.set_timer(self.CHANGESTATE, 300000) #pg.time.set_timer(self.SHOWGOALS, 6000) self.DAYGFX = load_gfx(os.path.join("img", "clouds", "day")) self.NTGFX = load_gfx(os.path.join("img", "clouds", "night")) self.BGIMG = load_gfx(os.path.join('img', 'bg')) self.keymap_dict = {pg.K_n: 'n', pg.K_PLUS: '+', pg.K_KP_PLUS: '+', pg.K_EQUALS: '+', pg.K_MINUS: '-', pg.K_KP_MINUS: '-', pg.K_p: 'p', pg.K_SPACE: 'p', pg.K_q: 'q', pg.K_r: 'r', pg.K_s: 's', pg.K_1: 's6\n', pg.K_2: 's4\n', pg.K_3: 's15\n', pg.K_4: 's25\n', pg.K_5: 's48\n', pg.K_6: 's37\n', pg.K_7: 's52\n', pg.K_8: 's16\n'}
def run(self): key_actions = { 'ESCAPE': self.quit, 'LEFT': lambda:self.move(-1), 'RIGHT': lambda:self.move(+1), 'DOWN': lambda:self.drop(True), 'UP': self.rotate_stone, 'p': self.toggle_pause, 'SPACE': self.start_game, 'RETURN': self.insta_drop } self.gameover = False self.paused = False dont_burn_my_cpu = pygame.time.Clock() while 1: self.screen.fill((0,0,0)) if self.gameover: self.center_msg("""Game Over!\nYour score: %d Press space to continue""" % self.score) else: if self.paused: self.center_msg("Paused") else: pygame.draw.line(self.screen, (255,255,255), (self.rlim+1, 0), (self.rlim+1, self.height-1)) self.disp_msg("Next:", ( self.rlim+cell_size, 2)) self.disp_msg("Score: %d\n\nLevel: %d\ \nLines: %d" % (self.score, self.level, self.lines), (self.rlim+cell_size, cell_size*5)) self.draw_matrix(self.bground_grid, (0,0)) self.draw_matrix(self.board, (0,0)) self.draw_matrix(self.stone, (self.stone_x, self.stone_y)) self.draw_matrix(self.next_stone, (cols+1,2)) pygame.display.update() i = 0 for event in pygame.event.get(): i += 1 if event.type == pygame.USEREVENT+1: self.drop(False) elif event.type == pygame.QUIT: self.quit() elif event.type == pygame.KEYDOWN: for key in key_actions: if event.key == eval("pygame.K_" +key): print "time elapsed in seconds since last epoch: ",time() print "action taken: ",key key_actions[key]() dont_burn_my_cpu.tick(maxfps)