def main(): """Main program loop""" pygame.init() screen = pygame.display.set_mode(opt.window_size) sys_font = Font(get_default_font(), opt.font_size) clock = Clock() manager = YarsManager() running = True while running: #limit framerate and prepare FPS display text clock.tick(opt.max_framerate) fps = clock.get_fps() fps_text = sys_font.render("FPS: {0:.1f}".format(fps), False, opt.white) if event.get(pygame.QUIT): sys.exit() running = manager.handle_events(event.get(), key.get_pressed()) manager.update() screen.fill(opt.black) manager.draw(screen) screen.blit(fps_text, fps_text.get_rect(top = 0, right = opt.width)) pygame.display.update() sys.exit()
def clearEvents(eventType=None): """Clears all events currently in the event buffer. Optional argument, eventType, specifies only certain types to be cleared. :Parameters: eventType : **None**, 'mouse', 'joystick', 'keyboard' If this is not None then only events of the given type are cleared """ #pyglet if not havePygame or not display.get_init(): #for each (pyglet) window, dispatch its events before checking event buffer wins = pyglet.window.get_platform().get_default_display().get_windows() for win in wins: win.dispatch_events()#pump events on pyglet windows if eventType=='mouse': return # pump pyglet mouse events but don't flush keyboard buffer global _keyBuffer _keyBuffer = [] else: #for pygame if eventType=='mouse': junk = evt.get([locals.MOUSEMOTION, locals.MOUSEBUTTONUP, locals.MOUSEBUTTONDOWN]) elif eventType=='keyboard': junk = evt.get([locals.KEYDOWN, locals.KEYUP]) elif eventType=='joystick': junk = evt.get([locals.JOYAXISMOTION, locals.JOYBALLMOTION, locals.JOYHATMOTION, locals.JOYBUTTONUP, locals.JOYBUTTONDOWN]) else: junk = evt.get()
def step(self,delay): if self.joy: event.get() curve,magnitude=[self.joy.get_axis(x)for x in xrange(2)] else: curve,magnitude=[random.uniform(-1,1)for _ in xrange(2)] self.robot.ApplyLinearImpulse(impulse=b2Vec2(cos(self.robot.angle),-sin(self.robot.angle))*(-magnitude*Robot.IMPULSE),point=self.robot.position) self.robot.ApplyTorque(curve*Robot.IMPULSE) self.world.Step(delay,10,10) self.world.ClearForces()
def get(self): events.pump() notmine = [] inp = NOOP for event in events.get(): if event.type == QUIT: inp = QUITCOMMAND if ((event.type == KEYDOWN or event.type == KEYUP) and self.keyDict.has_key(event.key)): if event.type == KEYDOWN: inp = self.keyDict[event.key] elif event.type == KEYUP: keyDown = key.get_pressed() if(keyDown[self.commandDict[UP]]): inp = UP elif(keyDown[self.commandDict[DOWN]]): inp = DOWN elif(keyDown[self.commandDict[LEFT]]): inp = LEFT elif(keyDown[self.commandDict[RIGHT]]): inp = RIGHT else: inp = STOP else: raise UnexpectedInput else: notmine.append(event) for yours in notmine: events.post(yours) return inp
def play_scene(self): self.screen.blit(self.img, self.origin) while(self.end_cutscene is False): PD.flip() for event in PE.get(): if event.type == PG.KEYDOWN and event.key == PG.K_q: #skip cutscene self.end_cutscene = True return False # end entire cutscene elif event.type == PG.KEYDOWN and event.key == PG.K_SPACE: if(len(self.text) > 0 and len(self.textcoords) > 0): self.screen.blit(self.img, self.origin) #find better way to clear text, maybe layers? txt = self.text.pop() txtcoord = self.textcoords.pop() self.screen.blit(self.font.render(txt, True, self.text_color), txtcoord) elif(len(self.over_img) > 0): oimg = self.over_img.pop() oimgcoord = self.over_imgcoords.pop() self.screen.blit(oimg, oimgcoord) else: self.end_cutscene = True # no more txt or imgs to add return True # go to next scene
def pause(display): global main_score screen = display.get_surface() hsfont = font.Font(FONT, 100) ysfont = font.Font(FONT,100) hs = hsfont.render("HIGH SCORE :-->" + str(highscore/2), True, HIGHSCORE_COLOR) y_score = ysfont.render("YOUR SCORE :-->"+str(main_score/2), True, Y_SCORE_COLOR) main_score = 0 #score = 0 pause_img=image.load('pause.png').convert_alpha() pause_img=transform.scale(pause_img, (1200, 700)) screen.blit(pause_img, (0, 0,)) screen.blit(hs, (200, 60)) screen.blit(y_score, (200, 200)) display.flip() while True: for i in event.get(): if i.type == MOUSEBUTTONDOWN or i.type == KEYDOWN: return main()
def push( self ): evts = event.get() # Push out all events found for evt in evts: print evt self.sock.sendto(self._parse(evt), ('', self.port)) return len(evts)
def handle_general_events(self): """ set quit true if user clicks the close button """ for evt in event.get(): if evt.type == QUIT: self.quit = True
def poll(self, pos): if self._images[0].get_rect().collidepoint(pos): event.get() pressed = mouse.get_pressed()[0] else: pressed = False changed = False if self._pressed != pressed: self._pressed = pressed changed = True if self._pressed: self._down() return changed
def main(): terminou = False term.cout (defaultMessageColor, 'Application Started!') init () screen = display.set_mode (windowSize) snake= Snake(windowSize[0]/2, windowSize[0]/2) snake.generateFood (1, 1, screen.get_width(), screen.get_height()) core = GameCore (screen) core.setMainDelay (0.2) while not terminou: for ev in event.get (): if ev.type == QUIT: terminou = True break; elif ev.type == KEYDOWN: term.cout ('warning', 'Keypressed: ' + str (ev.key)) if ev.key == LEFT or ev.key == RIGHT or ev.key == DOWN or ev.key == UP: snake.move (ev.key) core.blitWalls () snake.blit (screen) snake.blitFood (screen) snake.move (snake.getDirection()) core.flipDisplay ()
def handle_events(self): # handling keyboard for evt in event.get(): if evt.type == QUIT: # quit the game self.quit = True if evt.type == KEYDOWN: if evt.key == K_u and self.stop: try: if not self.rank: r=str(post_score(self.player.name,self.score)) self.msg_center = 'Your Global Rank :'+r self.rank = True except: self.rank = False self.msg_center = 'Sorry! Failed to fetch rank' if evt.key == K_ESCAPE: # quit the game self.quit = True if evt.key == K_p and not self.stop: # press p for pause self.pause = True self.msg_center = "Press 'Space' to resume" if evt.key == K_SPACE: # press space to ... if self.pause: # ...unpause on pressing p self.pause = False self.msg_center = "" if self.stop: # ...start a new game if gameover self.reset() self.stop = False
def clik(): for event in EVENTS.get(): if event.type == GLOBALS.KEYDOWN: if event.key == GLOBALS.K_ESCAPE: quitter() if event.key == GLOBALS.K_RETURN: texte("Entree", 0, 0, blancF) time.sleep(0.5) if event.key == GLOBALS.K_LEFT: texte("Gauche", 0, 0, blancF) time.sleep(0.5) if event.key == GLOBALS.K_RIGHT: texte("Droite", 0, 0, blancF) time.sleep(0.5) if event.key == GLOBALS.K_UP: texte("Haut", 0, 0, blancF) time.sleep(0.5) if event.key == GLOBALS.K_DOWN: texte("Bas", 0, 0, blancF) time.sleep(0.5)
def run(self): window = display.get_surface() for evt in event.get(): if evt.type == pygame.QUIT: self.quit() elif evt.type == pygame.MOUSEMOTION: self.processMouseMotion(evt.pos) elif evt.type == pygame.KEYDOWN: self.processKeyDown(evt.key) elif evt.type == pygame.MOUSEBUTTONDOWN: self.processMouseButtonDown(evt.pos) elif evt.type == pygame.MOUSEBUTTONUP: self.processMouseButtonUp(evt.pos) window.fill(self.aColor) # self.testObj.rect.x = self.mouseX # self.testObj.rect.y = self.mouseY # self.activeSprites.draw(window) self.activeState.update(self.Clock.get_time()) self.activeState.activeSprites.draw(window) if len(self.activeState.pts) > 1: draw.lines(window, (255, 0, 255), False, self.activeState.pts, 3) self.Clock.tick(30) display.flip() self.run()
def exchangeInput(self): """Exchange a round of inputs in a network-safe manner. """ inputs = [] for player in self.playerList: inp = self.getPlayerInput(player) debug("Player " + str(player.name) +\ " input: " + inp + "\n") if self.record and inp != NOOP: self.playerInputFileList[int(player.name)].write( \ str(self.totalGameLoops) +\ ',' + inp + '\n') # Check players input if len(inp) != len(UP): print "Bad input from player",player.getHandle() inp = DISCONNECT # Can quit the game from end splash screen if inp == QUITCOMMAND: sys.exit() inputs.append((player.name,inp)) for netplayer in self.playerList: netplayer.sendCommand(player.getBroadcastable()) self.totalGameLoops += 1 # Clear all useless events eventsWeWant = events.get([KEYDOWN, KEYUP, JOYBUTTONDOWN,\ JOYAXISMOTION]) events.clear() for event in eventsWeWant: events.post(event) return inputs
def update_keys(self, reply=None): """ Update the map self.keys according to user inputs. It uses either the x11 method or the pygame events :reply: If the x11 method is used, this is the message returned from x11 """ with self.keys_lock: if reply: # Use x11 events data = reply.data while len(data): evt, data = rq.EventField(None).parse_binary_value(data, self.record_dpy.display, None, None) if evt.type in [X.KeyPress, X.KeyRelease]: if evt.detail==X11_F1: self.keys[0] = evt.type==X.KeyPress elif evt.detail==X11_F2: self.keys[1] = evt.type==X.KeyPress elif evt.detail==X11_F3: self.keys[2] = evt.type==X.KeyPress elif evt.detail==X11_F4: self.keys[3] = evt.type==X.KeyPress elif evt.detail==X11_F5: self.keys[4] = evt.type==X.KeyPress else: # Use pygame events for evt in event.get(): if evt.type in [KEYDOWN, KEYUP]: if evt.key==K_F1: self.keys[0] = evt.type==KEYDOWN elif evt.key==K_F2: self.keys[1] = evt.type==KEYDOWN elif evt.key==K_F3: self.keys[2] = evt.type==KEYDOWN elif evt.key==K_F4: self.keys[3] = evt.type==KEYDOWN elif evt.key==K_F5: self.keys[4] = evt.type==KEYDOWN
def main(): rect = Rect((0, 0), SCREEN_SIZE) surface = Surface(SCREEN_SIZE) pxarray = PixelArray(surface) P = [(0, 100), (100, 0), (200, 0), (300, 100), (400, 200), (500, 200), (600, 100), (400, 400), (700, 50), (800, 200)] n = len(P) - 1 # n = len(P) - 1; (P[0], ... P[n]) k = 3 # degree of curve m = n + k + 1 # property of b-splines: m = n + k + 1 _t = 1 / (m - k * 2) # t between clamped ends will be evenly spaced # clamp ends and get the t between them t = k * [0] + [t_ * _t for t_ in xrange(m - (k * 2) + 1)] + [1] * k S = Bspline(P, t, k) # insert a knot (just to demonstrate the algorithm is working) S.insert(0.9) step_size = 1 / STEP_N for i in xrange(STEP_N): t_ = i * step_size try: x, y = S(t_) # if curve not defined here (t_ is out of domain): skip except AssertionError: continue x, y = int(x), int(y) pxarray[x][y] = (255, 0, 0) del pxarray for p in zip(S.X, S.Y): draw.circle(surface, (0, 255, 0), p, 3, 0) SCREEN.blit(surface, (0, 0)) while 1: for ev in event.get(): if ev.type == KEYDOWN: if ev.key == K_q: exit() display.update()
def update(self): """Update the event loop Calls the callbacks binded to the mouse and keyboard Calls the USEREVENT callback() methods """ self._keys_up = set([]) for e in event.get(): if e.type == QUIT: pygame.quit() sys.exit() elif e.type == KEYDOWN: self._keys_down.add(e.key) elif e.type == KEYUP: if e.key in self._keys_down: self._keys_down.remove(e.key) self._keys_up.add(e.key) elif e.type in (MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION): self._mouseCallback(self.buttons_down, self.mouse_pos, self.mouse_relpos) elif e.type == USEREVENT: try: e.callback() except AttributeError: print e," is a USEREVENT with no callback function defined." self._keyboardCallback(self.keysdown, self.keysup)
def main_loop(): """Main loop for running the actionRPM game""" # Clock code adapted from Peter's leftover-interval.py clock = time.Clock() current_time = time.get_ticks() leftover = 0.0 while True: Constants.STATE.draw() # Set up clock stuff new_time = time.get_ticks() frame_time = (new_time - current_time) / 1000.0 current_time = new_time clock.tick() #Update the Player & Enemy leftover += frame_time while leftover > Constants.INTERVAL: Constants.STATE.update(Constants.INTERVAL) leftover -= Constants.INTERVAL #Begin key presses pygame.event.pump() for eve in event.get(): if eve.type == pygame.QUIT: exit() elif eve.type == pygame.KEYDOWN and eve.key == pygame.K_m and \ eve.mod & (pygame.KMOD_CTRL or pygame.KMOD_LCTRL): Constants.STATE = Menu.Menu() #elif eve.type == pygame.MOUSEBUTTONDOWN: #print(pygame.mouse.get_pos()) else: Constants.STATE.keyEvent(eve)
def start_editor(self): glyph = self.editor_info glyph_rect = glyph.rect glyph.input(PAGES['editor']) glyph.update() editor = self.editor editor_rect = editor.rect SCREEN.blit(EDITOR_BKGSCREEN, (0, 0)) SCREEN.blit(glyph.image, glyph_rect) SCREEN.blit(editor.image, editor_rect) editor_focus = False while 1: mouse_pos = mouse.get_pos() link = glyph.get_collisions(mouse_pos) if link: mouse.set_cursor(*HAND_CURSOR) else: mouse.set_cursor(*DEFAULT_CURSOR) for ev in event.get(): if ev.type == MOUSEBUTTONDOWN: if link: pass if editor.rect.collidepoint(mouse_pos): editor_focus = True else: editor_focus = False if ev.type == KEYDOWN: if ev.key == K_ESCAPE: exit() if editor_focus == True: editor.input(ev) cursor = editor.get_cursor() editor.image.fill((255, 205, 0), cursor) SCREEN.blit(editor.image, editor_rect) display.update()
def runtrial(self): surface = display.get_surface() surface.fill((255,255,255)) surface.blit(self.image,TOPLEFT) display.flip() self.sound.play() time.sleep(ST_LENGTH) surface.blit(self.fill,TOPLEFT) display.flip() time.sleep(TB_LENGTH) keypresses = [] for e in event.get(KEYDOWN): keypresses += [e.dict['unicode']] if SPACE in keypresses: return None if unicode(KEYLEFT) in keypresses: if self.trgtimg: #print "user hit key \""+ KEYLEFT +"\" correctly" self.result[0] = True else: #print "user hit key \""+ KEYLEFT +"\" incorrectly" self.result[0] = False if unicode(KEYRIGHT) in keypresses: if self.trgtsnd: #print "user hit key \""+ KEYRIGHT +"\" correctly" self.result[1] = True else: #print "user hit key \""+ KEYRIGHT +"\" incorrectly" self.result[1] = False return True
def ask(self, question, text=''): "ask(question, text) -> answer" qw = self.box('%s: ' % question) lasttext = None while 1: if self.cb and self.cbargs: self.cb(*self.cbargs) sleep(0.01) if lasttext != text: self.message(qw, text) lasttext = text events = event.get((KEYDOWN, QUIT)) if not events: continue if QUIT in [e.type for e in events]: return e elif events[0].key == K_BACKSPACE: text = text[:-1] elif events[0].key in (K_ESCAPE, K_END): return None elif events[0].key == K_RETURN: return text elif 31 < events[0].key < 127: key = events[0].unicode.encode('ascii') text += (key.translate(self.transtable) if self.transtable else key)
def eventHandle(self,optionList,selector): self.optionList = optionList self.selector = selector for dummyEv in event.get(): if dummyEv.type == QUIT: exit() elif dummyEv.type == KEYDOWN: if dummyEv.key == K_RIGHT: #Does nothing for now... self.optionList[self.selector.vPos].deselect() self.selector.moveRight() self.optionList[self.selector.vPos].select() elif dummyEv.key == K_LEFT: #Does nothing for now... self.optionList[self.selector.vPos].deselect() self.selector.moveLeft() self.optionList[self.selector.vPos].select() elif dummyEv.key == K_UP: self.optionList[self.selector.vPos].deselect() self.selector.moveUp() self.optionList[self.selector.vPos].select() elif dummyEv.key == K_DOWN: self.optionList[self.selector.vPos].deselect() self.selector.moveDown() self.optionList[self.selector.vPos].select() elif dummyEv.key == K_SPACE: self.optionList[self.selector.vPos].doOption() elif dummyEv.key == K_RETURN: self.optionList[self.selector.vPos].doOption()
def tick(self): for event in Event.get(): if event.type == pygame.QUIT: raise QuitMessage('close button') self._pressed = Key.get_pressed() if self._inputs.has_key('quit'): if self.isPressed('quit'): raise QuitMessage('a quit chord was pressed')
def check(self): """Respond to user input or internal game events..""" for e in event.get(): t = e.type if t in (KEYDOWN, KEYUP): key_name = key.name(e.key) if t == KEYDOWN: self.on_key_down(key_name) elif t == KEYUP: self.on_key_up(key_name)
def main(): game = Manejador('Sembrando para el futuro', (1024, 572), False) game.changeState(menucfg.estado(game)) while game.running: game.handleEvents(event.get()) game.update() game.draw() game.cleanUp()
def handle_events( self ): """Generic event handling """ for evnt in event.get(): if evnt.type == QUIT: self.quit() if evnt.type == VIDEORESIZE: self.resize(*evnt.size)
def menu(gameWindow): load = LoadData() running = 1 init = True menuFont = load.load("EHSMB.TTF", "font", fontSize=60) menuBackground = load.load("menubg.png", "img") backGroundColor = 255, 255, 255 puzzleList, maxPuzzleNumber = load.load(fileType="pzcount") solvedPuzzles = load.loadSolvedPuzzles() puzzleNumber = 1 mainMenuButtons = ["Play random puzzle", "Puzzle select", "Exit"] menuType = "main" while running: if menuType == "main": if init: gameWindow.blit(menuBackground, gameWindow.get_rect()) menuButtons = create_menu(gameWindow, menuFont, mainMenuButtons) display.update() init = False for ev in event.get(): if ev.type == QUIT: quitprogram() elif ev.type == MOUSEBUTTONDOWN: if ev.button == 1: menuButtonClicked = MouseClicksMain(menuButtons) if menuButtonClicked == 1: init = randompuzzle(solvedPuzzles, gameWindow, maxPuzzleNumber) elif menuButtonClicked == 2: print "Function not yet implemented" # Testing # init = True menuType = "select" elif menuButtonClicked == 3: quitprogram() display.update() elif menuType == "select": if init: gameWindow.fill(backGroundColor) display.update() init = False print "I'm in another menu!" # Testing # for ev in event.get(): if ev.type == QUIT: quitprogram() elif ev.type == MOUSEBUTTONDOWN: menuType = "main" init = True
def loop(): while Globals.RUNNING: if Globals.STATE == "Title": title.initialize() Globals.STATE = title.Locals.CHANGESTATE while Globals.STATE == "Title": Globals.STATE = title.Locals.CHANGESTATE last = PT.get_ticks() elapsed = (PT.get_ticks() - last) / 1000.0 event = PE.get() title.run(elapsed,event) elif Globals.STATE == "Game": gamerino = Game.Game(.00625, 40, 13) Game.initialize() Globals.STATE = Game.Locals.CHANGESTATE while Globals.STATE == "Game": Globals.State = Game.Locals.CHANGESTATE num_enemies = 13 interval = 0.005 fps = 40 if(gamerino.run() == False): Globals.STATE = Game.Locals.CHANGESTATE elif Globals.STATE == "Menu": Menu.initialize() Globals.STATE = Menu.Locals.CHANGESTATE while Globals.STATE == "Menu": Globals.STATE = Menu.Locals.CHANGESTATE last = PT.get_ticks() elapsed = (PT.get_ticks() - last) / 1000.0 event = PE.get() if(Menu.run(elapsed,event) == False): return 0 elif Globals.STATE == "Scores": highscores.initialize() Globals.STATE = highscores.Locals.CHANGESTATE while Globals.STATE == "Scores": Globals.STATE = highscores.Locals.CHANGESTATE last = PT.get_ticks() elapsed = (PT.get_ticks() - last) / 1000.0 event = PE.get() highscores.run(elapsed,event)
def check_events(self): """Input checking.""" cursor_keys = ("move_up", "move_down", "move_left", "move_right") screen_keys = ("quit", "new_game") for e in event.get(): k = "" if e.type == JOYAXISMOTION: if e.axis == 1: if -1 == round(e.value): _type = "keydown" self._last_joystick_action = k = "up" if 1 == round(e.value): _type = "keydown" self._last_joystick_action = k = "down" if 0 == round(e.value): _type = "keyup" k = self._last_joystick_action if e.axis == 0: if -1 == round(e.value): _type = "keydown" self._last_joystick_action = k = "left" if 1 == round(e.value): _type = "keydown" self._last_joystick_action = k = "right" if 0 == round(e.value): _type = "keyup" k = self._last_joystick_action elif e.type in (KEYDOWN, KEYUP): k = key.name(e.key) if e.type == KEYDOWN: _type = "keydown" elif e.type == KEYUP: _type = "keyup" if k in State.controls: if self._last_joystick_action: sprite = State.joystick if _type == "keyup": self._last_joystick_action = None else: sprite = State.cursor control = getattr(actions, State.controls[k]) if _type == "keydown": State.pressed.append(control) ctrl = State.controls[k] if ctrl in cursor_keys: control (sprite) else: control(State.screen) elif _type == "keyup": if control in State.pressed: del State.pressed[State.pressed.index(control)] actions.move_stop(sprite) if State.pressed: State.pressed[-1](sprite)
def wait(self, timeout=-1, interruptible=False, process=None): start = time() # We loop while the process is not termianted, the timeout is not expired, and user has not asked 'next' with the joystick while (timeout < 0 or time()-start < timeout) and (process is None or process.poll() is None): for e in event.get(): if interruptible and e.type == JOYBUTTONDOWN: return 'joystick' sleep(0.01) return 'timeout' if (process is None or process.poll() is None) else 'terminated'
row = y // gc.IMAGE_SIZE col = x // gc.IMAGE_SIZE index = row * gc.NUM_TILES_SIDE + col return row, col, index pygame.init() display.set_caption('Match the sharks!') screen = display.set_mode((gc.SCREEN_SIZE, gc.SCREEN_SIZE)) matched = image.load('other_assets/matched.png') running = True tiles = [Animal(i) for i in range(0, gc.NUM_TILES_TOTAL)] current_images_displayed = [] while running: current_events = event.get() for e in current_events: if e.type == pygame.QUIT: running = False if e.type == pygame.KEYDOWN: if e.key == pygame.K_ESCAPE: running = False if e.type == pygame.MOUSEBUTTONDOWN: mouse_x, mouse_y = pygame.mouse.get_pos() row, col, index = find_index_from_xy(mouse_x, mouse_y) if index not in current_images_displayed: if len(current_images_displayed) > 1: current_images_displayed = current_images_displayed[1:] + [
dunofausto = Dunofausto(grupo_torradas) grupo_duno = GroupSingle(dunofausto) grupo_inimigos.add(Spacebug()) clock = Clock() rounds = 0 mortes = 0 while True: if (not (ALIVE)): fonte_lost = fonte.render('Você perdeu', True, (255, 255, 255)) superficie.blit(fonte_lost, (int(tamanho[0] * 0.4), int(tamanho[1] / 2))) display.update() while True: for evento in event.get(): if evento.type == QUIT: pygame.quit() break rounds += 1 clock.tick(120) if rounds % 120 == 0: if mortes < 20: grupo_inimigos.add(Spacebug()) for _ in range(int(mortes / 10)): grupo_inimigos.add(Spacebug()) for evento in event.get(): if evento.type == QUIT:
mouse.set_visible(False) font.init() ff = font.Font(None, int(W / 100 * 12.5)) lable_x_positions = (('PRESS', int(W / 100 * 34.6875)), ('ESC', int(W / 100 * 40.625)), ('FOR', int(W / 100 * 40.625)), ('EXIT', int(W / 100 * 38.75))) lable_start_y = int(W / 100 * 9.375) square_list = [] done = True timer = Clock() while done: for e in event.get(): if e.type == KEYDOWN: if e.key == K_ESCAPE: done = False screen.fill((30, 30, 50)) # draw lables for lable in lable_x_positions: screen.blit(ff.render(lable[0], 1, (40, 40, 70)), (lable[1], lable_start_y * (lable_x_positions.index(lable) + 1))) if len(square_list) < 500: for i in range(randint(1, 5)): square_list.append(Round_square(randint(0, W), randint(0, H)))
def three_player(): global tank_list tank = tanks(680, 680, 0, 35) tank2 = tanks(870, 725, 0, 35) tank3 = tanks(1300, 300, 0, 35) tank_list = [tank, tank2, tank3] pygame.joystick.init() joy1 = pygame.joystick.Joystick(0) joy1.init() while True: global bullet_counter surface.blit(board_image_three, (screensize[0] / 2 - 594, screensize[1] / 2 - 400)) display_score(counter_tank2, counter_tank3, counter_tank, 1000, 900) for event in game_events.get(): if event.type == pygame.JOYHATMOTION: direction = joy1.get_hat(0) if direction[0] == 1: tank3.right_down = True if direction[0] == -1: tank3.left_down = True if direction[1] == 1: tank3.up_down = True if direction[1] == -1: tank3.down_down = True direction = joy1.get_hat(0) if direction[0] == 0: tank3.right_down = False if direction[0] == 0: tank3.left_down = False if direction[1] == 0: tank3.up_down = False if direction[1] == 0: tank3.down_down = False if joy1.get_button(2) == 1 and tank3.status == 'alive': tank3.firing() bullet_counter += 1 if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() quit() if event.key == pygame.K_UP: tank.up_down = True if event.key == pygame.K_DOWN: tank.down_down = True if event.key == pygame.K_LEFT: tank.left_down = True if event.key == pygame.K_RIGHT: tank.right_down = True if event.key == pygame.K_m and tank.status == 'alive': tank.firing() bullet_counter += 1 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: tank.left_down = False if event.key == pygame.K_RIGHT: tank.right_down = False if event.key == pygame.K_UP: tank.up_down = False tank.playervy = math.cos(math.radians( tank.tankangle)) * tank.move_speed tank.playervx = math.sin(math.radians( tank.tankangle)) * tank.move_speed if event.key == pygame.K_DOWN: tank.down_down = False tank.playervy = math.cos(math.radians( tank.tankangle)) * tank.move_speed tank.playervx = math.sin(math.radians( tank.tankangle)) * tank.move_speed if event.type == game_locals.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_e: tank2.up_down = True if event.key == pygame.K_d: tank2.down_down = True if event.key == pygame.K_s: tank2.left_down = True if event.key == pygame.K_f: tank2.right_down = True if event.key == pygame.K_q and tank2.status == 'alive': tank2.firing() bullet_counter += 1 if event.type == pygame.KEYUP: if event.key == pygame.K_s: tank2.left_down = False if event.key == pygame.K_f: tank2.right_down = False if event.key == pygame.K_e: tank2.up_down = False tank2.playervy = math.cos(math.radians( tank2.tankangle)) * tank2.move_speed tank2.playervx = math.sin(math.radians( tank2.tankangle)) * tank2.move_speed if event.key == pygame.K_d: tank2.down_down = False tank2.playervy = math.cos(math.radians( tank2.tankangle)) * tank2.move_speed tank2.playervx = math.sin(math.radians( tank2.tankangle)) * tank2.move_speed for b in tank.bullets: barkhord_be_kodoom_tank(b, tank, tank2, tank3) if time.time() - b.born_time > 12: b.bull_status = 'dead' bullet_counter -= 1 b.bull_x, b.bull_y = 0, 0 if b.bull_status == 'Alive': b.draw() for b in tank2.bullets: barkhord_be_kodoom_tank(b, tank, tank2, tank3) if time.time() - b.born_time > 12: b.bull_status = 'dead' bullet_counter -= 1 b.bull_x, b.bull_y = 0, 0 if b.bull_status == 'Alive': b.draw() for b in tank3.bullets: barkhord_be_kodoom_tank(b, tank, tank2, tank3) if time.time() - b.born_time > 12: b.bull_status = 'dead' bullet_counter -= 1 b.bull_x, b.bull_y = 0, 0 if b.bull_status == 'Alive': b.draw() if tank.status == 'alive': surface.blit(rot_center(tank_image, -tank.tankangle), (tank.player_x, tank.player_y)) if tank2.status == 'alive': surface.blit(rot_center(tank2_image, -tank2.tankangle), (tank2.player_x, tank2.player_y)) if tank3.status == 'alive': surface.blit(rot_center(tank3_image, -tank3.tankangle), (tank3.player_x, tank3.player_y)) tank.move() tank2.move() tank3.move() if len(tank_list) == 1 and bullet_counter <= 0: restart_three_player(tank_list, tank, tank2, tank3) if len(tank_list) == 0: three_player() pygame.display.flip()
def update(self): event.get() keys = pygame.key.get_pressed() if keys is None: print "NONE" if self.ingame is True: if keys[K_RETURN] and not self.lastkeys[K_RETURN]: print self.cursel if self.cursel == RESUMEGAME: self.game.hidemenu() elif self.cursel == SAVEGAME: self.game.save() self.game.hidemenu() elif self.cursel == RETURNMAINMENU: print "main menu" self.game.tomainmenu() elif self.cursel == EXITINGAME: self.running = False elif keys[K_DOWN] and not self.lastkeys[K_DOWN]: self.cursel = min(self.cursel + 1, len(self.menuingame) - 1) elif keys[K_UP] and not self.lastkeys[K_UP]: self.cursel = max(self.cursel - 1, 0) else: if self.curmenu == MENUMAINPAGE: if keys[K_RETURN] and not self.lastkeys[K_RETURN]: if self.cursel == EXITGAME: self.running = False elif self.cursel == STARTNEWGAME: self.curmenu = MENUSTARTPAGE self.cursel = 0 elif self.cursel == OPTIONS: self.curmenu = MENUOPTIONPAGE self.cursel = 0 if keys[K_DOWN] and not self.lastkeys[K_DOWN]: self.cursel += 1 elif keys[K_UP] and not self.lastkeys[K_UP]: self.cursel -= 1 elif self.curmenu == MENUSTARTPAGE: if keys[K_RETURN] and not self.lastkeys[K_RETURN]: self.game.load(self.cursel, True) if keys[K_ESCAPE] and not self.lastkeys[K_ESCAPE]: self.curmenu = 0 self.cursel = 0 if keys[K_DOWN] and not self.lastkeys[K_DOWN]: self.cursel = min(self.cursel + 1, len(self.slots) - 1) elif keys[K_UP] and not self.lastkeys[K_UP]: self.cursel = max(self.cursel - 1, 0) elif self.curmenu == MENUOPTIONPAGE: if keys[K_RETURN] and not self.lastkeys[K_RETURN]: if self.cursel == OPTIONSOK: self.game.mario.life = self.nblives self.curmenu = 0 self.cursel = 0 if keys[K_DOWN] and not self.lastkeys[K_DOWN]: self.cursel = min(self.cursel + 1, len(self.options) - 1) elif keys[K_UP] and not self.lastkeys[K_UP]: self.cursel = max(self.cursel - 1, 0) elif keys[K_RIGHT] and not self.lastkeys[K_RIGHT]: if self.cursel == 0: self.nblives = min(10, self.nblives + 1) elif self.cursel == 1: self.curdifficulty = min(3, self.curdifficulty + 1) elif keys[K_LEFT] and not self.lastkeys[K_LEFT]: if self.cursel == 0: self.nblives = max(1, self.nblives - 1) elif self.cursel == 1: self.curdifficulty = max(0, self.curdifficulty - 1) self.lastkeys = keys
def listen(self): while True: if len(self.__possible_moves) == 0: while True: for playerevent in event.get(): if playerevent.type == KEYDOWN and playerevent.key == K_ESCAPE or playerevent.type == QUIT: sys.exit() if playerevent.type == KEYDOWN and playerevent.key == K_r: execv(sys.executable, ['Reversi.py'] + sys.argv) #---------------------------------<AI's Turn>---------------------------------# if self.__player == 1 and len(self.__possible_moves) > 0 and self.__AI == True: bestMove = 1 for i in self.__flip: if len(i) > bestMove: bestMove,index = len(i),self.__flip.index(i) time.wait(500) self.__hit = [self.__possible_moves[index][0],self.__possible_moves[index][1]] if self.__hit in self.__possible_moves: position = self.__possible_moves.index(self.__hit) for z in range(0,len(self.__flip[position]),2): flip1,flip2 = self.__flip[position][z],self.__flip[position][z+1] self.__Board[flip1][flip2][2] = self.__Color self.__screen.blit(self.__players[self.__Color-1],self.__Board[flip1][flip2][:2]) self.__screen.blit(self.__players[self.__Color-1],self.__Board[self.__hit[0]][self.__hit[1]][:2]) self.__Board[self.__hit[0]][self.__hit[1]][2],self.__player = self.__Color, self.__OppositColor self.Points() self.Options() #---------------------------------<AI's Turn>---------------------------------# if len(self.__possible_moves) > 0 and self.__player == 2 or (self.__player == 1 and self.__AI == False): for playerevent in event.get(): #--------------------------------------------changeEnemyType----------------------------------------------------# mousex, mousey = mouse.get_pos() if mousex >= 755 and mousex <= 824 and mousey >= 28 and mousey <= 46 and self.__AI == True: draw.rect(self.__screen, (32,32,32),(735,20 , 100, 35)) shadow = self.__font.render("ROBOT", True, (200,200,200,255)) self.__screen.blit(shadow,(755,23)) display.flip() if playerevent.type == MOUSEBUTTONDOWN and playerevent.button == 1: self.__AI = False draw.rect(self.__screen, (32,32,32),(735,20 , 100, 35)) shadow = self.__font.render("HUMAN", True, (200,200,200,255)) self.__screen.blit(shadow,(745,23)) display.flip() break if mousex >= 744 and mousex <= 824 and mousey >= 28 and mousey <= 46 and self.__AI == False: draw.rect(self.__screen, (32,32,32),(735,20 , 100, 35)) shadow = self.__font.render("HUMAN", True, (200,200,200,255)) self.__screen.blit(shadow,(745,23)) display.flip() if playerevent.type == MOUSEBUTTONDOWN and playerevent.button == 1: self.__AI = True draw.rect(self.__screen, (32,32,32),(735,20 , 100, 35)) shadow = self.__font.render("ROBOT", True, (200,200,200,255)) self.__screen.blit(shadow,(755,23)) display.flip() break if (mousex == 750 and (mousey >= 23 and mousey <= 51) or mousex == 829 and (mousey >= 23 and mousey <= 51) or mousey == 23 and (mousex >=750 and mousex <= 829) or mousey == 51 and (mousex >=750 and mousex <= 829)) and self.__AI == True: draw.rect(self.__screen, (32,32,32),(735,20 , 100, 35)) shadow = self.__font.render("ROBOT", True, (255,255,255,255)) self.__screen.blit(shadow,(755,23)) display.flip() break if (mousex == 742 and (mousey >= 23 and mousey <= 51) or mousex == 829 and (mousey >= 23 and mousey <= 51) or mousey == 23 and (mousex >=750 and mousex <= 829) or mousey == 51 and (mousex >=750 and mousex <= 829)) and self.__AI == False: draw.rect(self.__screen, (32,32,32),(735,20 , 100, 35)) shadow = self.__font.render("HUMAN", True, (255,255,255,255)) self.__screen.blit(shadow,(745,23)) display.flip() break #--------------------------------------------changeEnemyType----------------------------------------------------# if playerevent.type == KEYDOWN and playerevent.key == K_ESCAPE or playerevent.type ==QUIT: sys.exit() if playerevent.type == KEYDOWN and playerevent.key == K_r: execv(sys.executable, ['Reversi.py'] + sys.argv) if playerevent.type == MOUSEBUTTONDOWN and playerevent.button == 1: x,y = mouse.get_pos() self.__newx, self.__newy = None,None for xs in range(25,825,100): if x > xs and x < xs+100: self.__newx = xs //100 break for ys in range(75,875,100): if y > ys and y < ys+100: self.__newy = ys //100 break if self.__newx == None or self.__newy == None: break self.__hit = [self.__newy,self.__newx] if self.__hit in self.__possible_moves: position = self.__possible_moves.index(self.__hit) for z in range(0,len(self.__flip[position]),2): flip1,flip2 = self.__flip[position][z],self.__flip[position][z+1] self.__Board[flip1][flip2][2] = self.__Color self.__screen.blit(self.__players[self.__Color-1],self.__Board[flip1][flip2][:2]) self.__screen.blit(self.__players[self.__Color-1],self.__Board[self.__hit[0]][self.__hit[1]][:2]) self.__Board[self.__hit[0]][self.__hit[1]][2],self.__player = self.__Color, self.__OppositColor self.Points() self.Options()
gameBeganAt = GAME_TIME.get_ticks() platformsDroppedThrough = -1 platformDelay = 2000 def quitGame(): pygame.quit() sys.exit() # 'main' loop while True: surface.fill((0, 0, 0)) for event in GAME_EVENTS.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: leftDown = True if event.key == pygame.K_RIGHT: rightDown = True if event.key == pygame.K_ESCAPE: quitGame() if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: leftDown = False if event.key == pygame.K_RIGHT: rightDown = False
def graph_loop(mass_lower_limit=0.0, mass_upper_limit=0.0, radius_lower_limit=0.0, radius_upper_limit=0.0, is_gas_drwaf=False): m_lo_l = mass_lower_limit m_hi_l = mass_upper_limit r_lo_l = radius_lower_limit r_hi_l = radius_upper_limit fondo = display.set_mode((witdh, height), SCALED) rect = Rect(60, 2, 529, 476) lineas = LayeredUpdates() linea_h = Linea(rect, rect.x, rect.centery, rect.w, 1, lineas) linea_v = Linea(rect, rect.centerx, rect.y, 1, rect.h, lineas) punto = Punto(rect, rect.centerx, rect.centery, lineas) data = {} if any([ mass_lower_limit < 0, mass_upper_limit < 0, radius_lower_limit < 0, radius_upper_limit < 0 ]): raise ValueError() lim_mass_a = int(find_and_interpolate(m_lo_l, mass_keys, exes)) if m_lo_l else 0 lim_mass_b = int(find_and_interpolate(m_hi_l, mass_keys, exes)) if m_hi_l else 0 lim_radius_a = int(find_and_interpolate(r_lo_l, radius_keys, yes)) if r_lo_l else 0 lim_radius_b = int(find_and_interpolate(r_hi_l, radius_keys, yes)) if r_hi_l else 0 move_x, move_y = True, True lockx, locky = False, False mass_value = 0 radius_value = 0 mass_color = negro radius_color = negro mouse.set_pos(rect.center) event.clear() done = False composition_text_comp = None while not done: for e in event.get(): if e.type == QUIT: py_quit() if __name__ == '__main__': sys.exit() elif e.type == MOUSEBUTTONDOWN: if e.button == 1: if (not lockx) or (not locky): if (not lockx) and (not move_x): lockx = True elif (not locky) and (not move_y): locky = True elif not punto.disabled: data['mass'] = round(mass_value, 3) data['radius'] = round(radius_value, 3) data['gravity'] = round( mass_value / (radius_value**2), 3) data['density'] = round( mass_value / (radius_value**3), 3) done = True else: data = {} done = True elif e.button == 3: if lockx: lockx = False move_x = not lockx if locky: locky = False move_y = not locky elif e.type == MOUSEMOTION: px, py = e.pos if move_y: linea_h.move_y(py) punto.move_y(py) if move_x: linea_v.move_x(px) punto.move_x(px) point_x, point_y = punto.rect.center if rect.collidepoint(point_x, point_y) and (move_x or move_y): if mascara.get_at((point_x, point_y)): punto.select() for name in _lineas: if [point_x, point_y] in _lineas[name]: composition_text_comp = name break else: punto.deselect() elif e.type == KEYDOWN: if e.key == K_ESCAPE: py_quit() sys.exit() if e.key == K_LSHIFT: move_x = False elif e.key == K_LCTRL: move_y = False elif e.key == K_SPACE: data['mass'] = round(mass_value, 3) data['radius'] = round(radius_value, 3) data['gravity'] = round(mass_value / (radius_value**2), 3) data['density'] = round(mass_value / (radius_value**3), 3) done = True elif e.type == KEYUP: if e.key == K_LSHIFT: if not lockx: move_x = True elif e.key == K_LCTRL: if not locky: move_y = True px, py = punto.rect.center alto, bajo = 0, 0 if rect.collidepoint((px, py)): for _y in reversed(range(0, py)): if mascara.get_at((px, _y)): alto = _y break for _y in range(py, 476): if mascara.get_at((px, _y)): bajo = _y break a, b = 0, 0 # creo que esto se puede escribir con oneliners. for name in _lineas: if [px, alto] in _lineas[name]: a = name break for name in _lineas: if [px, bajo] in _lineas[name]: b = name break if a and b: c = composiciones silicates = interpolate(py, alto, bajo, c[a]['silicates'], c[b]['silicates']) hydrogen = interpolate(py, alto, bajo, c[a]['hydrogen'], c[b]['hydrogen']) helium = interpolate(py, alto, bajo, c[a]['helium'], c[b]['helium']) iron = interpolate(py, alto, bajo, c[a]['iron'], c[b]['iron']) water_ice = interpolate(py, alto, bajo, c[a]['water ice'], c[b]['water ice']) values = [ i for i in [silicates, hydrogen, helium, iron, water_ice] if i != 0 ] # sólo mostramos los valores mayores a 0% keys, compo = [], [] if silicates: compo.append(str(round(silicates, 2)) + '% silicates') keys.append('silicates') if hydrogen: compo.append(str(round(hydrogen, 2)) + '% hydrogen') keys.append('hydrogen') if helium: compo.append(str(round(helium, 2)) + '% helium') keys.append('helium') if iron: compo.append(str(round(iron, 2)) + '% iron') keys.append('iron') if water_ice: compo.append(str(round(water_ice, 2)) + '% water ice') keys.append('water ice') composition_text_comp = ', '.join(compo) data['composition'] = dict(zip(keys, values)) if hydrogen or helium: data['clase'] = 'Gas Dwarf' data['albedo'] = 30 else: data['clase'] = 'Terrestial Planet' data['albedo'] = 25 else: data = {} mass_value = find_and_interpolate(linea_v.rect.x, exes, mass_keys) radius_value = find_and_interpolate_flipped(linea_h.rect.y, yes, radius_keys) block = Surface(rect.size, SRCALPHA) block_mask = mask.from_surface(block) if any([lim_mass_b, lim_mass_a, lim_radius_a, lim_radius_b]): block_rect = block.get_rect(topleft=rect.topleft) alpha = 150 if lim_mass_a: block.fill([0] * 3 + [alpha], (0, rect.y - 2, lim_mass_a - rect.x, rect.h)) if lim_mass_b: block.fill([0] * 3 + [alpha], (lim_mass_b - rect.x, rect.y - 2, rect.w, rect.h)) if lim_radius_a: block.fill([0] * 3 + [alpha], (0, lim_radius_a, rect.w, rect.h - lim_radius_a)) if lim_radius_b: block.fill([0] * 3 + [alpha], (0, rect.y - 2, rect.w, lim_radius_b)) if is_gas_drwaf: block.blit(gas_drawf, (0, 0)) block_mask = mask.from_surface(block) point_x, point_y = punto.rect.center if block_rect.collidepoint((point_x, point_y)): if block_mask.get_at((point_x - rect.x, point_y - rect.y)): punto.disable() radius_color = rojo mass_color = rojo else: punto.enable() mass_color = negro radius_color = negro mass_text = 'Mass:' + str(round(mass_value, 3)) radius_text = 'Radius:' + str(round(radius_value, 3)) gravity_text = 'Density:' + str( round(mass_value / (radius_value**3), 3)) density_text = 'Gravity:' + str( round(mass_value / (radius_value**2), 3)) if not done: fondo.fill(blanco) fondo.blit(graph, (0, 0)) if block_mask.count() != 0: fondo.blit(block, rect) if punto.disabled: fondo.blit(texto3, rectT3) else: fondo.blit(fuente1.render(mass_text, True, mass_color), (5, rect.bottom + 43)) fondo.blit(fuente1.render(radius_text, True, radius_color), (140, rect.bottom + 43)) fondo.blit(fuente1.render(density_text, True, negro), (130 * 2 - 5, rect.bottom + 43)) fondo.blit(fuente1.render(gravity_text, True, negro), (140 * 3, rect.bottom + 43)) if composition_text_comp is not None: composition_text = 'Composition:' + composition_text_comp fondo.blit( fuente1.render(composition_text, True, negro, blanco), (5, rect.bottom + 64)) fondo.blit(texto1, rectT1) fondo.blit(texto2, rectT2) punto.update() lineas.update() lineas.draw(fondo) display.update() display.quit() return data
def gameloop(level, dmatch): def find_index_from_xy(x, y): row = y // gc.IMAGE_SIZE col = x // gc.IMAGE_SIZE index = row * gc.NUM_TILES_SIDE + col return row, col, index def draw_timer(screen, x, y, time_left): if level == 'L1': font = pygame.font.Font(None, 40) text = font.render("No time limit.", True, BLACK, WHITE) screen.blit(text, (x, y)) else: if (game_time - time_left) <= 10: pygame.draw.rect(screen, WHITE, (x, y, 250, 60)) font = pygame.font.Font(None, 40) text = font.render("Time Left = " + str(game_time - time_left), True, RED, WHITE) screen.blit(text, (x, y)) display.flip() else: font = pygame.font.Font(None, 40) text = font.render("Time Left = " + str(game_time - time_left), True, BLACK, WHITE) screen.blit(text, (x, y)) display.flip() def match_chances(screen, x, y, chances_left): if level == 'L1': font = pygame.font.Font(None, 40) text = font.render("No chance limit.", True, BLACK, WHITE) screen.blit(text, (x, y)) display.flip() else: if chances_left <= 5: font = pygame.font.Font(None, 40) text = font.render("Chances Left = " + str(chances_left), True, RED, WHITE) screen.blit(text, (x, y)) display.flip() else: font = pygame.font.Font(None, 40) text = font.render("Chances Left = " + str(chances_left), True, BLACK, WHITE) screen.blit(text, (x, y)) display.flip() buzzer = pygame.mixer.Sound('other_assets/Time-up.wav') match_sound = pygame.mixer.Sound('other_assets/Computer Error Alert.wav') success = pygame.mixer.Sound('other_assets/Success.wav') hiss = pygame.mixer.Sound('other_assets/Snake.wav') matched = image.load('other_assets/matched.png') win = image.load('other_assets/WINNER.png') timeout = image.load('other_assets/timeout.png') no_chance = image.load('other_assets/no chance.png') gameover = image.load('other_assets/gameover.png') if level == 'L1': tiles = [Animal(i) for i in range(0, gc.NUM_TILES_TOTAL)] game_time = 0 chances_left = 0 if level == 'L2': tiles = [Animal(i) for i in range(0, gc.NUM_TILES_TOTAL)] game_time = 30 chances_left = 20 elif level == 'L3': tiles = [Animal2(i) for i in range(0, gc.NUM_TILES_TOTAL)] game_time = 40 chances_left = 15 elif level == 'L4': tiles = [Animal3(i) for i in range(0, gc3.NUM_TILES_TOTAL)] game_time = 30 chances_left = 12 current_images_displayed = [] unique = [] mixer.music.load('other_assets/Level1_bgm.mp3') mixer.music.play(-1) start_time = int(pygame.time.get_ticks()) running = True while running: time_left = pygame.time.get_ticks() - start_time time_left = time_left / 1000 time_left = int(time_left) draw_timer(screen, 510, 180, time_left) match_chances(screen, 510, 250, chances_left) if level != 'L1': if (start_time + (game_time * 1000) <= pygame.time.get_ticks()): mixer.music.pause() buzzer.play() sleep(0.5) screen.blit(timeout, (0, 0)) display.flip() sleep(2) running = False pygame.quit() sys.exit() current_events = event.get() for e in current_events: if e.type == pygame.QUIT: running = False pygame.quit() sys.exit() if e.type == pygame.KEYDOWN: if e.key == pygame.K_ESCAPE: running = False pygame.quit() sys.exit() if e.type == pygame.MOUSEBUTTONDOWN: mouse_x, mouse_y = pygame.mouse.get_pos() if (mouse_x <= 512 and mouse_y <= 512): row, col, index = find_index_from_xy(mouse_x, mouse_y) if index not in current_images_displayed: if len(current_images_displayed) > 1: current_images_displayed = current_images_displayed[ 1:] + [index] confirm = all(item in unique for item in current_images_displayed) if level != 'L1': if not confirm: chances_left -= 1 if not chances_left: mixer.music.stop() buzzer.play() sleep(0.5) screen.blit(no_chance, (0, 0)) display.flip() sleep(2) running = False pygame.quit() sys.exit() match_chances(screen, 550, 400, chances_left) else: current_images_displayed.append(index) screen.fill((255, 255, 255)) total_skipped = 0 for i, tile in enumerate(tiles): current_image = tile.image if i in current_images_displayed else tile.box if not tile.skip: screen.blit(current_image, (tile.col * gc.IMAGE_SIZE + gc.MARGIN, tile.row * gc.IMAGE_SIZE + gc.MARGIN)) else: total_skipped += 1 display.flip() if len(current_images_displayed) == 2: index1, index2 = current_images_displayed if tiles[index1].name == 'snake.png' and tiles[ index2].name == 'snakes.png' or tiles[ index1].name == 'snakes.png' and tiles[ index2].name == 'snake.png' or tiles[ index1].name == 'snakes.png' and tiles[ index2].name == 'snakes.png' or tiles[ index1].name == 'snake.png' and tiles[ index2].name == 'snake.png': mixer.music.pause() hiss.play() sleep(0.5) screen.blit(gameover, (0, 0)) display.flip() sleep(2) running = False pygame.quit() sys.exit() if tiles[index1].name == tiles[index2].name: check = all(item in unique for item in current_images_displayed) if not check: tiles[index1].skip = True tiles[index2].skip = True if total_skipped != len(tiles) - dmatch: match_sound.play() sleep(0.2) screen.blit(matched, (0, 0)) display.flip() sleep(0.5) unique.extend(current_images_displayed) current_images_displayed = [] if total_skipped == len(tiles) - dmatch: mixer.music.pause() success.play() screen.blit(win, (0, 0)) display.flip() sleep(2) running = False pygame.quit() sys.exit()
def get_pygame_event(self): lst = [] for event in pyg_event.get(): lst.append(Event(event)) return lst
def main(): windowSize = width, height = 500, 400 pygame.init() clock = pygame.time.Clock() surface = pygame.display.set_mode(windowSize, pygame.RESIZABLE) pygame.display.set_caption('Kingsley Krane') crane_on = False hook_up_slow = False hook_down_slow = False start_screen = pygame.image.load("assets/cmax.jpg") end_screen = pygame.image.load("assets/over.jpg") on_button = pygame.image.load("assets/on.jpg") off_button = pygame.image.load("assets/off.jpg") surface.blit(start_screen, (0, 0)) pygame.display.update() try: hook = krane_parts.krane_hook.KraneHook() while True: if crane_on: surface.blit(on_button, (0, 0)) if hook_up_slow is True: hook.up_slow() elif hook_down_slow is True: hook.down_slow() else: hook.stop() elif not crane_on: surface.blit(off_button, (0, 0)) # Handle user events for event in CRANE_EVENTS.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: safe_exit() if event.key == pygame.K_UP: hook_up_slow = True hook_down_slow = False if event.key == pygame.K_DOWN: hook_up_slow = False hook_down_slow = True if event.key == pygame.K_o: if not crane_on: crane_on = True elif crane_on: crane_on = False elif event.type == pygame.KEYUP: if event.key == pygame.K_UP: hook_up_slow = False hook_down_slow = False if event.key == pygame.K_DOWN: hook_up_slow = False hook_down_slow = False elif event.type == CRANE_GLOBALS.QUIT: safe_exit() print("Krane On, Hook Up, Hook Down") print(crane_on, " ", hook_up_slow, " ", hook_down_slow) clock.tick(10) pygame.display.update() except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt safe_exit() # reset ports on interrupt surface.blit(end_screen, (0, 0)) pygame.display.update() safe_exit() # reset ports on normal exit
def Conway(): field = initConway(width / cellWidth, height / cellHeight) with open("forms", "r") as f: d = loads(f.read()) c = 1 x = 0 done = 0 save = 0 saving = [] while c: for e in event.get(): if e.type == QUIT: c = 0 kill(p.pid, SIGKILL) elif e.type == MOUSEBUTTONDOWN: if (e.pos[0] / cellWidth, e.pos[1] / cellHeight) not in field: field.append((e.pos[0] / cellWidth, e.pos[1] / cellHeight)) window.blit(blackCell, (e.pos[0] - e.pos[0] % cellWidth, e.pos[1] - e.pos[1] % cellHeight)) if save: saving.append( (e.pos[0] / cellWidth, e.pos[1] / cellHeight)) else: del field[field.index( (e.pos[0] / cellWidth, e.pos[1] / cellHeight))] window.blit(whiteCell, (e.pos[0] - e.pos[0] % cellWidth, e.pos[1] - e.pos[1] % cellHeight)) if save: del saving[saving.index( (e.pos[0] / cellWidth, e.pos[1] / cellHeight))] display.flip() elif e.type == KEYDOWN: if e.key == K_RETURN: x = 1 - x if not done: queue = mp.Queue() p = mp.Process(target=updateConway, args=(field, width / cellWidth, height / cellHeight, queue)) p.start() done = 1 elif e.key == K_l: form = ask("form?") pos = int(ask("place?")) field = list(field) for i in d[form]: field.append((i[0] + pos, i[1] + pos)) window.blit(blackCell, ((pos + i[0]) * cellWidth, (pos + i[1]) * cellHeight)) field = set(field) display.flip() elif e.key == K_r: window.fill(WHITE) window.blit(grid, (0, 0)) field = initConway(width / cellWidth, height / cellHeight) x = 0 done = 0 kill(p.pid, SIGKILL) display.flip() elif e.key == K_s: save = 1 - save if not save: saving.sort() saving = [[i[0] - saving[0][0], i[1]][::-1] for i in saving] saving.sort() saving = [[i[0] - saving[0][0], i[1]][::-1] for i in saving] d[ask("form name?")] = tuple(saving) saving = [] with open("forms", "w") as f: f.write(dumps(d)) if x: try: field, dead = queue.get() updateScreenConway(field, dead) except: pass
tx = int((x-len_frame+len_check/2)/(len_check)) ty = int((y-len_frame+len_check/2)/(len_check)) rx = tx*len_check + len_frame ry = ty*len_check + len_frame tcm_x = rx - int(len_cm/2) tcm_y = ry - int(len_cm/2) aim_x = rx - int(len_aim/2) aim_y = ry - int(len_aim/2) x-=int(len_cm/2) y-=int(len_cm/2) for myevent in get(): if button_restart.isOver() and myevent.type == MOUSEBUTTONDOWN: initail() if ai2==1: mymatrix[sy][sx] = 1 player=2 tx,ty=(sx,sy) continue if button_retract.isOver() and myevent.type == MOUSEBUTTONDOWN and cnt>0: tem=premymatrix[cnt-1] del premymatrix[cnt-1] #print(premymatrix) mymatrix[tem[0]][tem[1]]=0 cnt-=1 player=3-player
def getKeys(keyList=None, modifiers=False, timeStamped=False): """Returns a list of keys that were pressed. :Parameters: keyList : **None** or [] Allows the user to specify a set of keys to check for. Only keypresses from this set of keys will be removed from the keyboard buffer. If the keyList is `None`, all keys will be checked and the key buffer will be cleared completely. NB, pygame doesn't return timestamps (they are always 0) modifiers : **False** or True If True will return a list of tuples instead of a list of keynames. Each tuple has (keyname, modifiers). The modifiers are a dict of keyboard modifier flags keyed by the modifier name (eg. 'shift', 'ctrl'). timeStamped : **False**, True, or `Clock` If True will return a list of tuples instead of a list of keynames. Each tuple has (keyname, time). If a `core.Clock` is given then the time will be relative to the `Clock`'s last reset. :Author: - 2003 written by Jon Peirce - 2009 keyList functionality added by Gary Strangman - 2009 timeStamped code provided by Dave Britton - 2016 modifiers code provided by 5AM Solutions """ keys = [] if havePygame and display.get_init(): # see if pygame has anything instead (if it exists) for evts in evt.get(locals.KEYDOWN): # pygame has no keytimes keys.append((pygame.key.name(evts.key), 0)) elif havePyglet: # for each (pyglet) window, dispatch its events before checking event # buffer defDisplay = pyglet.window.get_platform().get_default_display() for win in defDisplay.get_windows(): try: win.dispatch_events() # pump events on pyglet windows except ValueError as e: # pragma: no cover # Pressing special keys, such as 'volume-up', results in a # ValueError. This appears to be a bug in pyglet, and may be # specific to certain systems and versions of Python. logging.error(u'Failed to handle keypress') global _keyBuffer if len(_keyBuffer) > 0: # then pyglet is running - just use this keys = _keyBuffer # _keyBuffer = [] # DO /NOT/ CLEAR THE KEY BUFFER ENTIRELY elif haveGLFW: # 'poll_events' is called when a window is flipped, all the callbacks # populate the buffer if len(_keyBuffer) > 0: keys = _keyBuffer if keyList is None: _keyBuffer = [] # clear buffer entirely targets = keys # equivalent behavior to getKeys() else: nontargets = [] targets = [] # split keys into keepers and pass-thrus for key in keys: if key[0] in keyList: targets.append(key) else: nontargets.append(key) _keyBuffer = nontargets # save these # now we have a list of tuples called targets # did the user want timestamped tuples or keynames? if modifiers == False and timeStamped == False: keyNames = [k[0] for k in targets] return keyNames elif timeStamped == False: keyNames = [(k[0], modifiers_dict(k[1])) for k in targets] return keyNames elif hasattr(timeStamped, 'getLastResetTime'): # keys were originally time-stamped with # core.monotonicClock._lastResetTime # we need to shift that by the difference between it and # our custom clock _last = timeStamped.getLastResetTime() _clockLast = psychopy.core.monotonicClock.getLastResetTime() timeBaseDiff = _last - _clockLast relTuple = [[_f for _f in (k[0], modifiers and modifiers_dict(k[1]) or None, k[-1] - timeBaseDiff) if _f] for k in targets] return relTuple elif timeStamped is True: return [[_f for _f in (k[0], modifiers and modifiers_dict(k[1]) or None, k[-1]) if _f] for k in targets] elif isinstance(timeStamped, (float, int, int)): relTuple = [[_f for _f in (k[0], modifiers and modifiers_dict(k[1]) or None, k[-1] - timeStamped) if _f] for k in targets] return relTuple
SCREEN_SIZE = (800, 600) # initialize screen size SCREEN = display.set_mode(SCREEN_SIZE) # load screen triangle = Polygon([(0, 70), (110, 0), (110, 70)]) rhombus = Polygon([(0, 80), (20, 0), (80, 0), (60, 80)]) triangle.move_ip(200, 200) rhombus.move_ip(300, 300) grab, other, theta = None, None, 0 while 1: SCREEN.fill((0, 0, 0)) draw.polygon(SCREEN, (255, 0, 0), triangle.P, 1) draw.polygon(SCREEN, (0, 0, 255), rhombus.P, 1) mouse_pos = array(mouse.get_pos()) for ev in event.get(): if ev.type == KEYDOWN: if ev.key == K_q: exit() if ev.key == K_LEFT: theta = -0.01 if ev.key == K_RIGHT: theta = 0.01 if ev.type == KEYUP: if ev.key == K_LEFT: theta = 0 if ev.key == K_RIGHT: theta = 0 if ev.type == MOUSEBUTTONDOWN: if grab: grab, other = None, None elif rhombus.collidepoint(mouse_pos): grab = rhombus other = triangle elif triangle.collidepoint(mouse_pos): grab = triangle other = rhombus
def two_player(): global bullet_counter global tank_list tank = tanks(725, 600, 0, 35) tank2 = tanks(1100, 200, 0, 35) tank_list = [tank, tank2] while True: surface.blit(board_image_two, (screensize[0] / 2 - 594, screensize[1] / 2 - 400)) display_score(counter_tank2, counter_tank) for event in game_events.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() quit() if event.key == pygame.K_UP: tank.up_down = True if event.key == pygame.K_DOWN: tank.down_down = True if event.key == pygame.K_LEFT: tank.left_down = True if event.key == pygame.K_RIGHT: tank.right_down = True if event.key == pygame.K_m and tank.status == 'alive': tank.firing() bullet_counter += 1 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: tank.left_down = False if event.key == pygame.K_RIGHT: tank.right_down = False if event.key == pygame.K_UP: tank.up_down = False tank.playervy = math.cos(math.radians( tank.tankangle)) * tank.move_speed tank.playervx = math.sin(math.radians( tank.tankangle)) * tank.move_speed if event.key == pygame.K_DOWN: tank.down_down = False tank.playervy = math.cos(math.radians( tank.tankangle)) * tank.move_speed tank.playervx = math.sin(math.radians( tank.tankangle)) * tank.move_speed if event.type == game_locals.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_e: tank2.up_down = True if event.key == pygame.K_d: tank2.down_down = True if event.key == pygame.K_s: tank2.left_down = True if event.key == pygame.K_f: tank2.right_down = True if event.key == pygame.K_q and tank2.status == 'alive': tank2.firing() bullet_counter += 1 if event.type == pygame.KEYUP: if event.key == pygame.K_s: tank2.left_down = False if event.key == pygame.K_f: tank2.right_down = False if event.key == pygame.K_e: tank2.up_down = False tank2.playervy = math.cos(math.radians( tank2.tankangle)) * tank2.move_speed tank2.playervx = math.sin(math.radians( tank2.tankangle)) * tank2.move_speed if event.key == pygame.K_d: tank2.down_down = False tank2.playervy = math.cos(math.radians( tank2.tankangle)) * tank2.move_speed tank2.playervx = math.sin(math.radians( tank2.tankangle)) * tank2.move_speed for b in tank.bullets: barkhord_be_kodoom_tank(b, tank, tank2) if time.time() - b.born_time > 12: b.bull_status = 'dead' bullet_counter -= 1 b.bull_x, b.bull_y = 0, 0 if b.bull_status == 'Alive': b.draw() for b in tank2.bullets: barkhord_be_kodoom_tank(b, tank, tank2) if time.time() - b.born_time > 12: b.bull_status = 'dead' bullet_counter -= 1 b.bull_x, b.bull_y = 0, 0 if b.bull_status == 'Alive': b.draw() if tank.status == 'alive': surface.blit(rot_center(tank_image, -tank.tankangle), (tank.player_x, tank.player_y)) if tank2.status == 'alive': surface.blit(rot_center(tank2_image, -tank2.tankangle), (tank2.player_x, tank2.player_y)) tank.move() tank2.move() if len(tank_list) == 1 and bullet_counter <= 0: restart_two_player(tank_list, tank, tank2) if len(tank_list) == 0: two_player() pygame.display.flip()
screen.blit(gc.paper, (display_size / 3, (5 / 6) * display_size - gc.MARGINE)) screen.blit(gc.scissors, (display_size * 2 / 3, (5 / 6) * display_size - gc.MARGINE)) #button text = font.SysFont('freesansbold.ttf', 50) text = text.render('Reset', True, (0, 0, 255)) draw.rect(screen, (255, 255, 200), (50, 780, text.get_width() + 40, text.get_height() + 40)) screen.blit(text, (70, 800)) running = True while running: events = event.get() for e in events: if e.type == pygame.QUIT: running = False if e.type == pygame.KEYDOWN: if e.key == pygame.K_ESCAPE: running = False if e.type == pygame.MOUSEBUTTONDOWN: x, y = pygame.mouse.get_pos() #print(x,y) if y >= ( 5 / 6 ) * display_size - gc.MARGINE and y <= display_size - gc.MARGINE: show = get_image(x, y) screen.blit(show, (display_size * 1 / 12, display_size * 2 / 6))
def gameloop( playerOrder: bool, p1Char: str, nick1: str, p2Char: str, nick2: str, udp: UDP_P2P, ) -> str: # region DocString """ Function that starts the loop for pygame ### Arguments `playerOrder {bool}`: `summary`: true if this host is the first player, false otherwise `p1Char {str}`: `summary`: the character chosen by this host `nick1 {str}`: `summary`: the username of this host `p2Char {str}`: `summary`: the character chosen by the remote player `nick2 {str}`: `summary`: the username of the remote player `udp {UDP_P2P}`: `summary`: the udp object ### Returns `str`: the exit status. It can be 'Lost' if this host lose, 'Quit' if this host closed the window,\n 'Win' if the remote host lose, 'Quitted' if the remote host closed the window """ # endregion global gamestate clock = Clock() COORDSYNC = USEREVENT + 1 set_timer(COORDSYNC, 1000) # region Screen setup screen = set_mode((Game.SIZE[0] + 400, Game.SIZE[1])) set_caption(Game.TITLE) set_icon(load(Game.ICON_PATH)) bg = load(Game.BG_PATH).convert_alpha() bg = scale(bg, Game.SIZE) manager = UIManager((Game.SIZE[0] + 400, Game.SIZE[1])) chat = Chat((400, Game.SIZE[1]), manager, udp, nick1) # endregion all_sprites = Group() # region Players setup if p1Char == "Ichigo": pl = Ichigo(playerOrder, nick1, all_sprites) elif p1Char == "Vegeth": pl = Vegeth(playerOrder, nick1, all_sprites) if p2Char == "Ichigo": pl2 = Ichigo(not playerOrder, nick2, all_sprites) elif p2Char == "Vegeth": pl2 = Vegeth(not playerOrder, nick2, all_sprites) # endregion rcvT = udp.receptionThread( lambda data, addr, time: rcv(pl2, data, addr, time, chat), rcvErr) rcvT.start() while True: dt = clock.tick(Game.FPS) / 1000 # region Handle window close pressed_keys = get_pressed() for event in get(): if event.type == QUIT: snd(nick1, "Quit", udp) gamestate = "Quit" if event.type == COORDSYNC: sndCoords(nick1, (pl.rect.x, pl.rect.y), udp) manager.process_events(event) # endregion manager.update(dt) # region Handle key press and update sprites all_sprites.update(pressed_keys) sndKeys( nick1, ( pressed_keys[K_LEFT], pressed_keys[K_RIGHT], pressed_keys[K_UP], pressed_keys[K_z], ), udp, ) if pl.update(pressed_keys): snd(nick1, "Lost", udp) gamestate = "Lost" # endregion # region Sprite drawing screen.fill(Color.WHITE) screen.blit(bg, (0, 0)) all_sprites.draw(screen) pl.draw(screen) pl2.draw(screen) pl.health.draw(screen) pl2.health.draw(screen) # endregion manager.draw_ui(screen) flip() if gamestate: udp.stopThread() quit() return gamestate
# create a new mob object createMob() # initialise game score - default to 0 game_score = 0 # play background music pygame.mixer.music.play(loops=-1) running = True # create game loop while running: # check loop is running at set speed clock.tick(FPS) # 'processing' inputs (events) for event in EVENTS.get(): # check keyboard events - keydown if event.type == pygame.KEYDOWN: # check for ESCAPE key if event.key == pygame.K_ESCAPE: gameExit() # check click on window exit button if event.type == pygame.QUIT: gameExit() # 'updating' the game # update all game sprites game_sprites.update() # add check for sprite group collide with another sprite group - projectiles hitting enemy objects - use True to delete sprites from each group... collisions = pygame.sprite.groupcollide(mob_sprites, projectiles, True,
def main(username: str) -> int: global isMuted run, fps = True, 60 lives, font_, clock = 5, SysFont("comicsans", 50), Clock() level = 0 player = Player(300, 650, username) bgy, bgy2 = 0.0, -float(BACKGROUND.get_height()) enemies, enemy_lasers = [], [] player_laser_vel = -8 wave_length, enemy_vel, laser_vel = 5, 1, 5 mixer.music.load("assets/background.wav") mixer.music.play(-1) def update_window() -> None: WIN.blit(BACKGROUND, (0, bgy)) WIN.blit(BACKGROUND, (0, bgy2)) level_label = font_.render(f"Score: {player.score}", True, (255, 255, 255)) lives_label = font_.render(f"Lives: {lives}", True, (255, 255, 255)) WIN.blit(lives_label, (10, 10)) for enemy in enemies: enemy.draw(WIN) for laser in enemy_lasers: laser.draw(WIN) WIN.blit(level_label, (WIDTH - level_label.get_width()-10, 10)) player.draw(WIN) update() while run: clock.tick(fps) if len(enemies) == 0: if level == 10: update_scores(player) return 1 wave_length += 1 enemies.extend(spawn(wave_length)) level += 1 if level % 4 == 0: enemy_vel += 1 player.v += 1 player_laser_vel -= 1 level_label = font_.render(F"Level {level}...", True, (255, 255, 255)) WIN.blit(level_label, (WIDTH//2 - level_label.get_width()//2, HEIGHT//2)) update() pygame.time.wait(2500) update_window() bgy += 1.4 bgy2 += 1.4 if bgy > HEIGHT: bgy = -BACKGROUND.get_height() if bgy2 > HEIGHT: bgy2 = -BACKGROUND.get_height() for event in get(): if event.type == QUIT: quit() keys = get_pressed() if len(keys): player.move(keys) if keys[K_SPACE]: bulletSound.play() player.shoot() if keys[K_m]: isMuted = not isMuted if isMuted: mixer.music.stop() else: mixer.music.play(-1) for enemy in enemies[:]: enemy.move(enemy_vel) if randint(0, 2*30) == 1 and enemy.y > 0: enemy.shoot(enemy_lasers) if collide(enemy, player): enemies.remove(enemy) lives -= 1 elif enemy.off_screen(): enemies.remove(enemy) player.score -= 1 player.score = max(player.score, 0) lives = move_lasers(laser_vel, player, enemy_lasers, lives) if lives <= 0: update_scores(player) return 1 player.move_lasers(player_laser_vel, enemies) update_scores(player) return 1
def getKeys(keyList=None, timeStamped=False): """Returns a list of keys that were pressed. :Parameters: keyList : **None** or [] Allows the user to specify a set of keys to check for. Only keypresses from this set of keys will be removed from the keyboard buffer. If the keyList is None all keys will be checked and the key buffer will be cleared completely. NB, pygame doesn't return timestamps (they are always 0) timeStamped : **False** or True or `Clock` If True will return a list of tuples instead of a list of keynames. Each tuple has (keyname, time). If a `core.Clock` is given then the time will be relative to the `Clock`'s last reset :Author: - 2003 written by Jon Peirce - 2009 keyList functionality added by Gary Strangman - 2009 timeStamped code provided by Dave Britton """ keys = [] if havePygame and display.get_init( ): #see if pygame has anything instead (if it exists) for evts in evt.get(locals.KEYDOWN): keys.append( (pygame.key.name(evts.key), 0)) #pygame has no keytimes elif havePyglet: #for each (pyglet) window, dispatch its events before checking event buffer wins = pyglet.window.get_platform().get_default_display().get_windows() for win in wins: win.dispatch_events() #pump events on pyglet windows global _keyBuffer if len(_keyBuffer) > 0: #then pyglet is running - just use this keys = _keyBuffer # _keyBuffer = [] # DO /NOT/ CLEAR THE KEY BUFFER ENTIRELY if keyList == None: _keyBuffer = [] #clear buffer entirely targets = keys # equivalent behavior to getKeys() else: nontargets = [] targets = [] # split keys into keepers and pass-thrus for key in keys: if key[0] in keyList: targets.append(key) else: nontargets.append(key) _keyBuffer = nontargets # save these #now we have a list of tuples called targets #did the user want timestamped tuples or keynames? if timeStamped == False: keyNames = [k[0] for k in targets] return keyNames elif hasattr(timeStamped, 'timeAtLastReset'): relTuple = [(k[0], k[1] - timeStamped.timeAtLastReset) for k in targets] return relTuple elif timeStamped == True: return targets
button = Button(master, text="OK", command=ok) button.pack() mainloop() # --------- pygame --------- init() # ------ constants ------------ clock = time.Clock() FPS = 60 # desired frame rate in frames per second. playtime = 0 while c.game_open: manager = SceneManager(TitleScene()) c.game_over = False while not c.game_over: # do all this each frame milliseconds = clock.tick(FPS) # do not go faster than this frame rate playtime += milliseconds / 1000.0 if event.get(QUIT): c.game_open = False break manager.scene.handle_events(event.get()) manager.scene.update() manager.scene.render() display.flip() # flip the screen FPS times a second quit()
def main_loop(self): while True: self.handle_events(event.get()) self.step() self.draw()
def process_pygame_event(self): # pygame event for event in pyg_event.get(): if event.type == L.QUIT: exit()
if (event.type == self.event_types['JOY_AXIS_MOTION']): if (event.axis == self.joystick_axes['Y_LEFT']): self.left_value = event.value if (abs(self.left_value) < 0.05): self.left_value = 0 self.velocity_vector[0] = self.left_value * -1 self.velocity_vector[1] = self.right_value * -1 self._send_dif_drive_message() def _send_dif_drive_message(self): self.velocity_vector[0] = self.sensitivity_constant * ( self.velocity_vector[0])**3 + ( 1 - self.sensitivity_constant) * self.velocity_vector[0] self.velocity_vector[1] = self.sensitivity_constant * ( self.velocity_vector[1])**3 + ( 1 - self.sensitivity_constant) * self.velocity_vector[1] self.messenger.send_dif_drive_command(self.velocity_vector[0], self.velocity_vector[1], 0) #print (self.velocity_vector[0], self.velocity_vector[1], 0) if __name__ == '__main__': pygame.init() joystick.init() joystick.Joystick(0).init() jc = nikhil_joystick() while True: event_list = event.get() for event_obj in event_list: jc.handle_event(event_obj)
def update(cls): events = event.get([ KEYDOWN, KEYUP, MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION, QUIT ]) event.clear() # esto es para que se pueda reemplazar un locutor sin tener que reseleccionarlo. cls.selected.add([ i for i in cls.widgets.widgets() if i.is_selected and (i not in cls.selected) ]) for e in events: mods = key.get_mods() ctrl = mods & KMOD_CTRL shift = mods & KMOD_SHIFT if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE): salir() elif e.type == KEYDOWN: widgets = cls.selected.widgets() if System.type_mode: if e.key == K_F3: System.toggle_typemode('MainTB') else: EventHandler.trigger('Key', cls.name, { 'key': e.key, 'mod': e.mod }) elif e.key == K_c: if len(widgets) == 2 and all( [o.numerable for o in widgets]): widgets.sort( key=lambda o: o.idx) # lower idx's go first if not shift: widgets[0].connect(widgets[1]) else: widgets[0].disconnect(widgets[1]) elif e.key == K_a and len(widgets) == 2: base, other = widgets EventHandler.trigger('AddMidPoint', 'System', { 'base': base, 'other': other }) elif e.key == K_RETURN: EventHandler.trigger('CreateDialog', cls.name, {'nodes': cls.numerable}) elif e.key == K_F3: if any([o.order == 'b' for o in widgets]): System.toggle_typemode('MainTB') else: for widget in widgets: widget.on_keydown(e) elif e.key == K_s: x, y = mouse.get_pos() color, text = None, None if any([o.order == 'a' for o in widgets]): color = [i for i in widgets if i.order == 'a'][0].color text = [i for i in widgets if i.order == 'a'][0].text if System.area_nodos.collidepoint(x, y) and text is not None: EventHandler.trigger('AddNode', cls.name, { 'text': text, 'pos': [x, y], 'color': color }) elif e.key == K_d and any([o.order == 'a' for o in widgets]): widgets.sort(key=lambda o: o.order) color_namer = widgets.pop(0) for other in widgets: other.colorize(color_namer) elif len(cls.selected): for widget in cls.selected.widgets(): widget.on_keydown(e) elif e.type == KEYUP: if len(cls.selected): for widget in cls.selected.widgets(): widget.on_keyup(e) elif e.type == MOUSEBUTTONDOWN: # pos, button widgets = [ w for w in cls.widgets.widgets() if w.selectable and w.rect.collidepoint(e.pos) ] if not len( widgets ) and e.button == 1 and cls.active_area.collidepoint(e.pos): if not shift and not System.type_mode: cls.selected.empty() if not ctrl: EventHandler.trigger('AddSelection', cls.name, { "pos": e.pos, 'value': True }) elif len(widgets) and not len(cls.selected): cls.selected.sumar([w for w in widgets if w.selectable]) elif not cls.selected.has(widgets) and e.button == 1 and len( widgets): order_c = [i for i in widgets if i.order == 'c'] if not ctrl and not System.type_mode and not len(order_c): cls.selected.empty() cls.selected.sumar(widgets) if len(widgets): for widget in cls.selected.widgets(): if widget is not cls.selection: widget.on_mousedown(e) elif e.button != 1: widgets = [w for w in cls.widgets.widgets() if w.numerable] if ctrl and not shift: dx, dy = 1, 0 elif shift and not ctrl: dx, dy = 0, 5 elif ctrl and shift: dx, dy = 5, 0 else: dx, dy = 0, 1 for widget in widgets: if e.button == 4: dx *= -1 dy *= -1 elif e.button == 5: dx *= 1 dy *= 1 widget.rect.move_ip(dx, dy) elif e.type == MOUSEBUTTONUP: # pos, button if cls.on_selection and e.button == 1: cls.selection.on_mouseup(e) selected = [ i for i in cls.widgets if cls.selection.rect.contains(i.rect) ] cls.selected.sumar(selected) elif e.type == MOUSEMOTION: # pos, rel, buttons if e.buttons[0] and len( cls.selected) and not shift and not System.type_mode: for widget in [ i for i in cls.selected.widgets() if i.draggable is True ]: widget.on_mousemotion(e) elif cls.on_selection and e.buttons[0]: cls.selection.on_mousemotion(e) elif ctrl and e.buttons[0]: widgets = [ w for w in cls.widgets.widgets() if w.selectable and w.draggable ] for widget in widgets: widget.on_mousemotion(e) cls.widgets.update()
def menu(): init() FPS = 15 clock = pygame.time.Clock() red = (255, 0, 0) green = (0, 255, 0) blue = (255, 255, 100) screen.fill((0, 0, 0)) display.update() play_is_pressed = False chosen_pers = None chosen_btn = 0 first_screen_chosen_btn = 0 #music pygame.mixer.music.load('2.mp3') pygame.mixer.music.play(-1) bg = pygame.image.load('images/bg1.png') bg1 = pygame.image.load('images/bg2.png') x = 250 y = 250 r = 20 dx = 0 dy = 0 btn_play = [512 - 100, 368 - 50, 200, 90] btn_exit = [5, 690, 80, 50] first_screen_btns_r = [btn_play, btn_exit] btn_play = [512 - 100, 368 - 50,pygame.image.load('images/play.png')] btn_exit = [18, 700, pygame.image.load('images/exit.png')] first_screen_btns = [btn_play, btn_exit] btn1 = [512 - 100 - 250, 368 - 100] btn2 = [512 - 100, 368 - 100] btn3 = [512 - 100 + 250, 368 - 100] btn_back = [18, 700] btn_rating = [900, 700] r_btn1 = [512 - 100 - 250, 368 - 100, 200, 200] r_btn2 = [512 - 100, 368 - 100, 200, 200] r_btn3 = [512 - 100 + 250, 368 - 100, 200, 200] r_btn_back = [18, 700, 60, 50] r_rating = [900, 700, 100, 60] buttons_r = [r_btn1, r_btn2, r_btn3, r_btn_back, r_rating] btn1 += [pygame.image.load('images/Nps/Рыцарь/2(Стоит).png')] btn2 += [pygame.image.load('images/Nps/Принцесса/Стоит.png')] btn3 += [pygame.image.load('images/Nps/Маг/2(Стоит).png')] btn_back += [pygame.image.load('images/back.png')] btn_rating += [pygame.image.load('images/rating.png')] buttons_ = [btn1, btn2, btn3, btn_back, btn_rating] display.update() loop = 1 rating_screen = 0 st = 0 check = 0 while loop: pygame.mouse.set_visible(0) clock.tick(FPS) screen.fill((0, 0, 0)) if st == 0: screen.blit(bg, (0,0)) for btn in first_screen_btns: screen.blit(btn[2], btn[:2]) draw.rect(screen, blue, first_screen_btns_r[first_screen_chosen_btn], 5) display.update() for i in event.get(): if i.type == QUIT: loop = 0 elif i.type == KEYDOWN: if i.key == K_SPACE: if first_screen_chosen_btn == 0: st = 1 else: loop = 0 if i.key == K_s: first_screen_chosen_btn = 1 if i.key == K_w: first_screen_chosen_btn = 0 elif st == 2: text_get("Last 5 player results", (255 ,255,255), 512, 100, 100) with open("history.txt", "r") as file: text = list(map(str, [line[:-1] for line in file]))[-5:] for i in range(5): text_get(text[i], (255,255,255), 512, 250 + i * 100, 79) for i in event.get(): if i.type == QUIT: loop = 0 elif i.type == KEYDOWN: if i.key == K_a: check = 1 elif i.key == K_d: check = 1 elif i.key == K_w: check = 1 elif i.key == K_s: check = 1 elif i.key == K_SPACE: st = 1 screen.blit(buttons_[3][2], buttons_[3][:2]) draw.rect(screen, blue, buttons_r[3], 5) if keyPressed(pygame.K_SPACE) and check: st = 1 sleep(0.5) display.update() elif chosen_pers == None and st == 1: screen.blit(bg1, (0,0)) text_get("Choose one of sprites:", (255, 255, 255), 512, 100, 50) for button in buttons_: screen.blit(button[2], button[:2]) # draw.rect(screen, (255, 255, 255), button) draw.rect(screen, blue, buttons_r[chosen_btn], 5) display.update() for i in event.get(): if i.type == QUIT: loop = 0 elif i.type == KEYDOWN: if i.key == K_a: chosen_btn = max(0, chosen_btn - 1) elif i.key == K_d: chosen_btn = min(4, chosen_btn + 1) elif i.key == K_w: if chosen_btn == 3 or chosen_btn == 4: chosen_btn = 0 elif i.key == K_s: chosen_btn = 3 elif i.key == K_SPACE: if chosen_btn < 3: chosen_pers = chosen_btn elif chosen_btn == 4: st = 2 else: st = 0 # sleep(0.5) else: loop = 0 # quit() return chosen_pers quit() time.delay(30)
def setUp(self): pygame.display.init() fastevent.init() event.clear() self.assert_(not event.get())
def start_game(is_opponent=False): pygame.init() game = Tetris() game.start_game() if is_opponent: opponent = Tetris(name='Opponent') game.connect_opponent(opponent) opponent.start_game() opponent.connect_opponent(game) screen = display.set_mode((1280, 720), pg_locals.DOUBLEBUF) vis = Visualizer(game, screen) display.set_caption('NenwTris') clock = time.Clock() key_mapping = { pg_locals.K_LEFT: Controller.key_left, pg_locals.K_RIGHT: Controller.key_right, pg_locals.K_x: Controller.key_spin_cw, pg_locals.K_z: Controller.key_spin_ccw, pg_locals.K_c: Controller.key_hold, pg_locals.K_DOWN: Controller.key_softdrop, pg_locals.K_SPACE: Controller.key_harddrop } game_delay = 0 opponent_delay = 0 events = [] def handle_event(ev): if ev.type == pg_locals.QUIT: pygame.quit() sys.exit() elif ev.type == pg_locals.KEYDOWN: if ev.key in key_mapping: if not game_paused: game.controller.keydown(key_mapping[ev.key]) else: events.append(ev) elif ev.type == pg_locals.KEYUP: if ev.key in key_mapping: if not game_paused: game.controller.keyup(key_mapping[ev.key]) else: events.append(ev) while True: game_paused = game_delay > 0 for ev in event.get(): handle_event(ev) for i in range(len(events)): handle_event(events.pop(0)) if game_delay <= 0: game.update() else: game_delay -= 1 if is_opponent: if opponent_delay <= 0: opponent.update() else: opponent_delay -= 1 game_delay_delta, opponent_delay_delta = vis.update() opponent_delay += opponent_delay_delta else: game_delay_delta, = vis.update() game_delay += game_delay_delta clock.tick(60)
pygame_init() screen = set_mode((400, 300)) clock = Clock() font = Font(None, 15) # default pygame Font, height in pixels borders = [Rect(0, 0, 2, 300), Rect(0, 0, 400, 2), Rect(398, 0, 2, 300), Rect(0, 298, 400, 2)] dx, dy = 0, 1 # start direction: down delay = 0 # start moving right away while True: clock.tick(50) # frames per second poll() # push and pull network messages for event in pygame_event.get(): # inputs if event.type == QUIT: exit() if event.type == KEYDOWN: key = event.key if key == K_ESCAPE: exit() elif key == K_UP: dx, dy = 0, -1 elif key == K_DOWN: dx, dy = 0, 1 elif key == K_LEFT: dx, dy = -1, 0 elif key == K_RIGHT: dx, dy = 1, 0