def main(): display.init() maxX,maxY = display.list_modes()[0] screen = display.set_mode( (maxX/3, maxY/3 ) ) display.flip() pgw = PygameWidget( ) p = Player( pgw, pipe_desc=Player.test_pipe_desc ) p.play() clock = pygame.time.Clock() running = True while running: clock.tick( 60 ) for evt in [pygame.event.wait()] + pygame.event.get(): if evt.type == pygame.KEYDOWN: if p._playing: p.pause() else: p.play() elif evt.type == pygame.QUIT: p.stop() running = False
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 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 run(self): while self.can_run: self.check_gamestate() #want delay for the ideal FPS lastframedelay = self.fps_clock.tick(GAME_GLOBALS.MAX_FPS) update_count = lastframedelay + self.cycles_left if update_count > (GAME_GLOBALS.MAX_FPS * GAME_GLOBALS.UPDATE_INT): update_count = GAME_GLOBALS.MAX_FPS * GAME_GLOBALS.UPDATE_INT #Do at least 1 update if for some reason #the computer is super fast event = pygame.event.get() self.check_exit(event) self.GAME_STATE.update(event) update_count -= GAME_GLOBALS.UPDATE_INT if update_count > GAME_GLOBALS.UPDATE_INT: while update_count > GAME_GLOBALS.UPDATE_INT: update_count -= GAME_GLOBALS.UPDATE_INT #Do update stuff event = pygame.event.get() self.check_exit(event) self.GAME_STATE.update(event) self.cycles_left = update_count DISP.flip() if self.exitting: #TODO: save stuff? pygame.quit() sys.exit(0) else: #something kicked us out of the event loop but #the exitting flag is still false self.can_run = True
def run(self): running = True while running: new_time = PT.get_ticks() frame_time = (new_time - self.current_time)/1000.0 self.current_time = new_time self.clock.tick() running = self.handleEvents() if(running == False): return False #Key Handling---------------------------- # self.character.handle_keys() # handle the keys self.screen.fill((0,0,0)) # fill the screen with white # self.character.handle_collision(self.block_group) #move and draw the enemies player_face = self.character.get_face() for enemy in self.enemy_list.sprites(): Enemy_face = enemy.get_face() enemy.set_face(player_face) enemy.draw() #draw blocks Draw.draw_map(self.block_group) self.character.draw(self.screen, self.block_group) # draw the character to the screen PD.flip() self.updates = 0 #clock is added clock = PT.Clock() while frame_time > 0.0: delta = min(frame_time, self.interval) for enemy in self.enemy_list.sprites(): enemy.update(delta) self.character.handle_keys(self.block_group, self.interval) frame_time -= delta self.updates += 1 last = PT.get_ticks() clock.tick() PD.flip() elapsed = (PT.get_ticks() - last) / 1000.0 if (PG.key.get_pressed()): self.update(self.character, elapsed) #camera handling self.cam.update(self.character) #end camera handle PD.update() # update the screen
def render(self): screen.blit(self.IMAGE, (0, 0)) PDI.flip() if not PX.music.get_busy(): PX.music.load(SONG0) PX.music.set_volume(Globals.VOLUME) PX.music.play(0, 0.0)
def draw(self): self.background.draw() self.showText(self.title, .5, min(.4, self.timeAlive / 4000.0)) if self.timeAlive % 1000 < 650: self.showText(self.text, .5, .6) display.flip()
def __draw(self): self.__gen.draw(self.__canvas) if self.__mouseDown: diffX = self.__mouseCurrPos[0] - self.__mouseDownPos[0] diffY = self.__mouseCurrPos[1] - self.__mouseDownPos[1] if diffX > 0 and diffY > 0: sizeX = max([diffX, diffY]) sizeY = sizeX elif diffX > 0: sizeX = max([abs(diffX), abs(diffY)]) sizeY = -sizeX elif diffY > 0: sizeY = max([abs(diffX), abs(diffY)]) sizeX = -sizeY else: sizeX = min([diffX, diffY]) sizeY = sizeX self.__drawSize = (sizeX, sizeY) pygame.draw.rect(self.__canvas, self.__highlightColor, Rect(self.__mouseDownPos, self.__drawSize), 1) display.flip() display.update()
def update(self): """ redraw """ self.screen.fill(config.bgcolor) w2s = self.viewport.world_to_screen # draw grid for debug # self.draw_grid() # draw bodies # for b in self.world.bodies: # polygon = [] # fflag = 0 # for node in b.shape.nodes: # p, flag = w2s(b.coor.apply(mat((node[0], node[1], 0)).T)) # fflag = fflag or flag # polygon.append(p) # if fflag: # pg.draw.polygon(self.screen, b.shape.color, polygon) # draw points for point in self.world.points: p, flag = w2s(point.s.T) if flag: pg.draw.circle(self.screen, pg.Color("blue"), vint(p), 2) # draw joints jointColor = (0x22, 0xff, 0) for j in self.world.joints: p1, flag1 = w2s(j.t1.s.T) p2, flag2 = w2s(j.t2.s.T) if flag1 or flag2: pg.draw.aaline(self.screen, jointColor, vint(p1), vint(p2)) pgdisplay.flip()
def display_loading_progress(search_term, term_url_count, total_urls, urls_processed, term_count): percent_complete = (urls_processed/float(total_urls)) * 100 percent_complete = int(percent_complete) msg = "{}%".format(percent_complete) loading_font_size = LOADING_FONT.get_ascent() text = LOADING_FONT.render(msg, 1, (random.randint(0,255), random.randint(0,255), random.randint(0,255))) x_coord = SCREEN_WIDTH - len(msg) * loading_font_size y_coord = 0 screen.fill(RGB_BLACK, Rect(x_coord, y_coord, len(msg) * loading_font_size, loading_font_size + TEXT_PADDING)) screen.blit(text, (x_coord, y_coord)) if not DETAILED_PROGRESS: display.flip() return progress_font_size = LOADING_FONT_DETAILED.get_ascent() y_coord = SCREEN_HEIGHT - progress_font_size - TEXT_PADDING screen.fill(RGB_BLACK, Rect(0, y_coord, SCREEN_WIDTH, progress_font_size + TEXT_PADDING)) msg = 'Total: {}/{} urls Search Term:"{}":{}/{} urls'.format(urls_processed, total_urls, search_term, term_count, term_url_count) text = LOADING_FONT_DETAILED.render(msg, 1, FONT_COLOR) screen.blit(text, (0, y_coord)) display.flip()
def __init__(self, size, tilesize=100, message_font=None, glyph_font=None, margin=50, circle=False, tile_cls=None): Board.__init__(self, size, tile_cls) font.init() message_font = message_font or (None, 60) glyph_font = glyph_font or (None, 70) self.message_font = font.Font(message_font[0], message_font[1]) self.glyph_font = font.Font(glyph_font[0], glyph_font[1]) n = tilesize + 1 self.margin = margin self.scr = display.set_mode((size[0]*n + margin*2, size[1]*n + margin*2)) self.scr.fill(white) self.sfc = Surface(self.scr.get_size()) self.sfc = self.sfc.convert() self.sfc.fill(white) self.scr.blit(self.sfc, (0,0)) self.tilesize = tilesize self.circle = circle self.tile_locs = [[ (iround(margin+x+tilesize/2) , iround(margin+y+tilesize/2)) for x in range(0, size[0]*n, n)] for y in range(0, size[1]*n, n)] for tile in self: self.mkgui_tile(tile.loc) self.scr.blit(self.sfc, (0,0)) display.flip()
def main(argv=sys.argv[1:]): pygame.init() screen = display.set_mode(DISPLAY_SIZE) ball = image.load('samples/4-2/ball.png') # 描画座標を保持する変数 x, y = 0, 0 while True: event_dispatch() screen.fill((0, 0, 0)) # 右矢印キーの入力状態と左矢印キーの入力状態を見て 1, 0, -1 の値を生成する dx = get_key_state('right') - get_key_state('left') # 下矢印キーの入力状態と上矢印キーの入力状態を見て 1, 0, -1 の値を生成する dy = get_key_state('down') - get_key_state('up') # キー入力状態から座標を変化させる x += dx * 5 y += dy * 5 # 変化させた座標に描画する screen.blit(ball, (x, y)) display.flip() time.delay(100)
def render(self): if PX.music.get_busy(): PX.music.stop() CONT_IMAGE = PI.load(CONTINUE + str(self.curr_player.get_continues()) + ".png").convert_alpha() screen.blit(self.IMAGE, (0, 0)) screen.blit(CONT_IMAGE, (0, 0)) PDI.flip()
def endScene(self): fpsClock = PT.Clock() DURATION = 2000.0 start_time = PT.get_ticks() ratio = 0.0 while ratio < 1.0: current_time = PT.get_ticks() ratio = (current_time - start_time)/DURATION if ratio > 1.0: ratio = 1.0 value = int(255*ratio) fade_color = PC.Color(0, 0, 0, 0) fade_color.a = value # PD.rect(Globals.SCREEN, fade_color, (0,0,400,300)) surf = PG.Surface((800, 600)) surf.set_alpha(value) surf.fill((0, 0, 0)) Globals.SCREEN.blit(surf, (0, 0)) PD.flip() fpsClock.tick(60) levelTwoEvents[1] = False Player.events[4] = False self.stone_mound = item.Item(54*Setup.PIXEL_SIZE, 26*Setup.PIXEL_SIZE, stone_mound_image) Globals.WORLD.addEntity(self.stone_mound) Globals.STATE = LevelTwo()
def runloop(window, world, render): clock = pygame.time.Clock() clock.tick() FPS = 30 while True: clock.tick(FPS) #TODO: hacky hack. This is not very accurate, will do for now. elapsed_time = 1./FPS if handle_events(window, world): # show score outro break ## return True Sounds.sounds.update(elapsed_time) world.update() render.draw_world() display.flip() if world.end_game: break #show score window.sounds.play_music("intro", loop=1) quit = outro_main(window, handle_events, world.player_character.score) return quit
def update(self, time): Globals.WORLD.background(Globals.SCREEN) Globals.WORLD.dr(Globals.SCREEN) Globals.WORLD.update(self.npc1) if self.Timer == 0: Globals.WORLD.addEntity(self.npc1) while self.Timer < 150: key = PG.event.get(PG.KEYDOWN) for event in key: if event.type == PG.KEYDOWN: self.Timer = 181 Globals.WORLD.background(Globals.SCREEN) Globals.WORLD.dr(Globals.SCREEN) Globals.WORLD.update(self.npc1) set_timer = self.Timer % 10 if set_timer == 0: self.npc1.rect.centery += 4 self.npc1.update_image(self.npc1.image_tracker*4, self.npc1.change_direction) self.Timer += 1 PDI.flip() if self.Timer == 175: self.npc1.update_image(self.npc1.image_tracker*4+3, True) Globals.WORLD.addEntity(self.npc2) if self.Timer == 176: Dialogue = DB.Dialogue_box('cutscene1_dialogue.txt') while Dialogue.isOpen: Dialogue.update() self.Timer += 1 if self.Timer == 183: Globals.WORLD.addEntity(self.npc2) self.npc1.rect.centery += 60 self.npc1.update_image(self.npc1.image_tracker*4+3, True) self.endScene()
def main(window, handle_events): ## window = Window() ## window.init() world = World() world.stage = 1 p1 = Platform(600, 300, 400, 50) world.add_item(p1) p2 = Platform(500, 600, 800, 100) world.add_item(p2) """ vert order: 0 3 1 2 """ rest_length, stiffness, damping = 200, 10, 1 spring = Spring(p1, p2, lambda vs: vs[1], lambda vs: vs[0], rest_length, stiffness, damping) world.add_spring(spring) spring = Spring(p1, p2, lambda vs: vs[2], lambda vs: vs[3], rest_length, stiffness, damping) world.add_spring(spring) spring = Spring( p1, p2, lambda vs: (vs[1] + vs[3]) / 2, lambda vs: (vs[1] + vs[3]) / 2, rest_length, 10 * stiffness, damping ) world.add_spring(spring) font_path = os.path.join(data_dir(), "fonts", "vinque", "vinque.ttf") fnt = font.Font(font_path, 36) surface = fnt.render("The adventures of...", True, (255, 255, 255)) word = Word(p2, surface, (200, 50)) world.add_word(word) fnt = font.Font(font_path, 48) text = "Woger the wibbly wobbly wombat" words = [fnt.render(word, True, (255, 255, 255)) for word in text.split()] word_positions = ((200, 75), (500, 75), (175, 250), (350, 250), (550, 250)) for surface, position in zip(words, word_positions): word = Word(p1, surface, position) world.add_word(word) fnt = font.Font(font_path, 24) surface = fnt.render("space to continue, use awwow keys in game to weach owanges", True, (0, 0, 0)) word = Word(p2, surface, (40, 550)) world.add_word(word) render = Render(window, world) while True: quit = handle_events(window, world) if quit: break world.update() render.draw_world() display.flip()
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 draw(self): Constants.SCREEN.fill((0, 0, 0)) font = pygame.font.Font(None, 30) new_high = font.render("Congratulations! You have a new high score", 1, (255, 255, 255)) background = pygame.Surface(Constants.SCREEN.get_size()) new_high_rect = new_high.get_rect() new_high_rect.centerx = background.get_rect().centerx new_high_rect.centery = 75 Constants.SCREEN.blit(new_high, new_high_rect) font = pygame.font.Font(None, 30) presskey = font.render("Please type your name, then hit 'Enter'", 1, (255, 255, 255)) background = pygame.Surface(Constants.SCREEN.get_size()) presskeyrect = presskey.get_rect() presskeyrect.centerx = background.get_rect().centerx presskeyrect.y = Constants.HEIGHT - 40 Constants.SCREEN.blit(presskey, presskeyrect) #Print a red rectangle in the middle of the screen rect = pygame.draw.rect(Constants.SCREEN, (255, 0, 0), (0, Constants.HEIGHT / 2, Constants.WIDTH, 30)) if len(self.name) != 0: name_msg = font.render(string.join(self.name, ""), 1, (0, 0, 0)) name_msg_rect = name_msg.get_rect() name_msg_rect.center = rect.center Constants.SCREEN.blit(name_msg, name_msg_rect) alphaSurface = pygame.Surface((Constants.WIDTH,Constants.HEIGHT)) # The custom-surface of the size of the screen. alphaSurface.fill((0,0,0)) alphaSurface.set_alpha(Constants.ALPHA_SURFACE) # Set the incremented alpha-value to the custom surface. Constants.SCREEN.blit(alphaSurface,(0,0)) display.flip()
def render(self): #Music if not PX.music.get_busy(): if Globals.CURRENTSONG == HIGHSONG: PX.music.load(HIGHSONG) Globals.CURRENTSONG = SONG1 elif Globals.CURRENTSONG == SONG1: PX.music.load(SONG1) Globals.CURRENTSONG = SONG0 elif Globals.CURRENTSONG == SONG0: PX.music.load(SONG0) Globals.CURRENTSONG = HIGHSONG PX.music.set_volume(Globals.VOLUME) PX.music.play(0, 0.0) lasttime = PT.get_ticks() #screen.fill(BLACK) self.current_level.draw(screen, self.player_group) self.player_group.draw(screen) self.ui_group.draw(screen) clock.tick() PDI.flip() elapsed = (PT.get_ticks() - lasttime) / 1000.0 if elapsed > 2.0: elapsed = 2.0 #Update Player and Enemy while elapsed >= 0 and Globals.ALIVE: self.player_group.update(INTERVAL, self.PLAYER_X_POS, self.PLAYER_X_NEG, self.PLAYER_Y_POS, \ self.PLAYER_Y_NEG, self.SELECTEDWEAPON, self.ATTACK, self.CROUCH, \ self.USING, self.TOOLS, self.current_level) Globals.ALIVE = self.new_player.is_alive() self.current_level.update(INTERVAL, self.player_group) self.ui_group.update(self.new_player) elapsed -= INTERVAL if self.new_player.get_win(): Globals.STATE = Win(self.level_num) self.USING = False #Reset jump status for this_player in self.player_group: if not this_player.on_ladder(): self.PLAYER_Y_POS = False #Reset ladder status self.TOOLS = -1 #Check to see if the player is alive if not Globals.ALIVE: while elapsed >= 0: self.new_player.die(INTERVAL) elapsed -= INTERVAL if self.new_player.finishedDying(): #Reset Music if PX.music.get_busy(): PX.music.stop() Globals.LASTCHECK = self.current_level.get_last_check() Globals.STATE = Lose(self.new_player)
def draw(self): """Perform all graphical tasks for this frame.""" self.background.draw() for i in range(0, len(self.choices)): self.drawItem(i) self.drawTitle() display.flip()
def display_box(self, screen, message): screen.fill(PC.Color("black")) fontobject = Globals.FONT PD.rect(screen, (0, 0, 0), ((screen.get_width()/2) - 100, (screen.get_height()/2) - 12, 204, 24), 1) PD.rect(screen, (255, 255, 255), ((screen.get_width()/2) - 102, (screen.get_height()/2) - 12, 204, 24), 1) if len(message) != 0: screen.blit(fontobject.render(message, 1, (255, 255, 255)), ((screen.get_width()/2) - 100, (screen.get_height()/2) - 10)) PDI.flip()
def update(): """ Updates the display by swapping the back buffer and screen buffer. According to the pygame documentation, the flip should wait for a vertical retrace when both HWSURFACE and DOUBLEBUF are set on the surface. """ display.flip()
def draw(self): self.screen.blit(self.background,(0,0)) y = self.mlist.y for item in self.mlist.items: x = self.mlist.x - item.rendered.get_size()[0]/2 self.screen.blit(item.rendered, (x,y)) y = y + self.mlist.margin_y + item.rendered.get_size()[1] display.flip() return
def initLoadScreen(group, textBar): global curGroup, screen, curTextBar, background screen = Display.get_surface() background = pygame.image.load(LOADIMG) screen.blit(background, background.get_rect()) curGroup = group curTextBar = textBar curGroup.draw(screen) Display.flip()
def draw(self): """Perform all graphical tasks for this frame.""" # Draw each layer in order, from back to front. for layer in self.layers: layer.draw(self.camera) # Display the new frame. display.flip()
def _draw(_): """ Ask the current GameState to redraw itself :param _: unused interp provided by GameClock :return: """ # gamestate.draw() CONTEXT["gamestate"].draw() flip()
def show(self): while self.running: self.draw() display.flip() self.clock.tick(FPS) for event in pygame.event.get(): self.handle_event(event) if android: if android.check_pause(): android.wait_for_resume()
def draw( self ): """ """ self._init_scene() # Begin Test self.__draw_quad() # End Test display.flip() return
def test_issue_208(self): """PATCH: pygame.scrap on X11, fix copying into PRIMARY selection Copying into theX11 PRIMARY selection (mouse copy/paste) would not work due to a confusion between content type and clipboard type. """ from pygame import display, event, freetype from pygame.locals import SCRAP_SELECTION, SCRAP_TEXT from pygame.locals import KEYDOWN, K_y, QUIT success = False freetype.init() font = freetype.Font(None, 24) display.init() display.set_caption("Interactive X11 Paste Test") screen = display.set_mode((600, 200)) screen.fill(pygame.Color("white")) text = "Scrap put() succeeded." msg = ( "Some text has been placed into the X11 clipboard." " Please click the center mouse button in an open" " text window to retrieve it." '\n\nDid you get "{}"? (y/n)' ).format(text) word_wrap(screen, msg, font, 6) display.flip() event.pump() scrap.init() scrap.set_mode(SCRAP_SELECTION) scrap.put(SCRAP_TEXT, text.encode("UTF-8")) while True: e = event.wait() if e.type == QUIT: break if e.type == KEYDOWN: success = e.key == K_y break pygame.display.quit() self.assertTrue(success)
def main_loop(self): ''' This is the main loop of the scene, don't overrive if not necesary. Here you will find the main workflow for an scene ''' # Ensures the starts conditions self.running = True self.return_value = -1 # Calls the start function, to configurate the scene self.start() # Main loop of the scene while self.running: # Event catch # Set the event queue of the objet itself self.events = [] for e in event.get(): self.events.append(e) for s in self.event_group.sprites(): s.add_event(e) if e.type == QUIT: self.exit(-1) # Group update self.update_group.update(self.clock.get_time()) # Calls the update function for every tick of the game self.update() # Render group self.render_group.draw(self.screen) display.flip() # Ensure frame rate if DEBUG: print(self.clock.get_fps()) self.clock.tick(60) return self.return_value
def display_maze_game(self): """ displays the items of maze after each movement of MacGyver """ # the sleep mode wil be actived at the end of game sleep = False # display the background in the window "fenetre" self.fenetre.blit(self.fond_pic, (0, 0)) # display MacGyver in the window "fenetre" self.fenetre.blit(self.macgyver_pic, self.macgyver_pic_position) # display differents items of the maze in the window "fenetre" for (coords, element) in self.maze.grid.items(): if element == "w": # "w" is equivalent to a wall self.fenetre.blit(self.mur_pic, (coords[0] * 40, coords[1] * 40)) elif element == "G": # "G" is equivalent to the Guardian # game_result != 0 => "end of game" => no more Guardian if self.game_result == 0: self.fenetre.blit(self.guardian_pic, (coords[0] * 40, coords[1] * 40)) elif element == "needle": self.fenetre.blit(self.needle_pic, (coords[0] * 40, coords[1] * 40)) elif element == "tube": self.fenetre.blit(self.tube_pic, (coords[0] * 40, coords[1] * 40)) elif element == "ether": self.fenetre.blit(self.ether_pic, (coords[0] * 40, coords[1] * 40)) if self.game_result == 1: # if the player win self.fenetre.blit(self.win_pic, (40, 10)) # actives the sleep mode sleep = True elif self.game_result == 2: # if the player lose self.fenetre.blit(self.game_over_pic, (0, 0)) # actives the sleep mode sleep = True display.flip() # Screen refresh # maintains display for a few seconds after the game ends if sleep: time.sleep(DELAY)
def setup_tabuleiro(): tela_jogo = transform.scale(image.load('Tela_inicial/tela_jogo.png'), (DIM_TELA_X, DIM_TELA_Y)) tela.blit(tela_jogo, (0, 0)) lista = ['testar.png', 'apagar.png', 'Voltar_inst.png'] for botao in BOTOES: lista.append(botao) contador_botoes = [320, 420] indices = [0, 0, 0, 0, 0, 0, 0, 0, 0] i = 1 index = 0 outros = False for item in lista: if 0 == (i % 4): outros = True contador_botoes = [0, 435] i = 1 if outros: bot = transform.scale(image.load('cores/' + item), (40, 40)) contador_botoes[0] = contador_botoes[0] + 50 tela.blit(bot, (contador_botoes[0], contador_botoes[1])) indices[index] = [[contador_botoes[0], contador_botoes[0] + 40], [contador_botoes[1], contador_botoes[1] + 40]] i = 1 else: botao = transform.scale(image.load('Tela_inicial/' + item), (150, 60)) contador_botoes[0] = contador_botoes[0] + 160 tela.blit(botao, (contador_botoes[0], contador_botoes[1])) indices[index] = [[contador_botoes[0], contador_botoes[0] + 150], [contador_botoes[1], contador_botoes[1] + 60]] i += 1 index += 1 display.flip()
def show_end_adventure_screen(self): end_surface = Surface((WIDTH, HEIGHT), SRCALPHA) end_text = Label('Good Nice!', 'assets/fonts/blocks.ttf', 20, (HEIGHT / 2) - 100, font_size=72) score_text = Label(f'Score: {self.score.calculate_score()}', 'assets/fonts/future_narrow.ttf', 20, (HEIGHT / 2) - 120, font_size=24) return_text = Label('You will return to home and see you score ranking', 'assets/fonts/future_narrow.ttf', 20, (HEIGHT / 2) - 160, font_size=24) for alpha in range(255): end_surface.fill((0, 0, 0, alpha)) self.screen.blit(end_surface, (0, 0)) self.screen.blit(end_text.surface, end_text.rect) self.screen.blit(score_text.surface, score_text.rect) self.screen.blit(return_text.surface, return_text.rect) display.flip() time.delay(10)
def draw(self): """Draws the universe on a screen. Draws a black background which overwrites the existing screen. Then renders a hollow circle for each point in points. If the point is a star it is colored yellow, otherwise the point is colored gray. At any point the user can press the exit button and the program will exit. """ if (not self._surface): self._surface = display.set_mode((self.SIZE, self.SIZE)) self._surface.fill(self.BACKGROUND_COLOR) for point in self.points: color = self.NOT_STAR_COLOR if (point.star): color = self.STAR_COLOR draw.circle(self._surface, color, point.position.round.tuple, point.radius, self.BORDER_THICKNESS) display.flip() for e in event.get(): if e.type == QUIT: quit() exit(0)
def _update(self): "Update the display surface; record frame if requested" cursor = self.cursor if self.light: self.tint(self.light) for img, posn in self._lumin: self.blit(img, posn) self._lumin = [] grab = 0 if self.capture is not None: interval = self.capture.interval if interval: if self.frameCount % interval == 0: grab = 1 if self.capture.gui else -1 if grab == -1: self.capture.capture() if self.gui: if self.gui.widgets: self.gui.draw() if self.gui.hover.dialog in self.gui.widgets if self.gui.hover else False: cursor = self.gui.cursorId setCursor(cursor) if grab == 1: self.capture.capture() display.flip()
def start(self): pygame.init() screen = display.set_mode(self.size) display.set_caption(self.title) clock = Clock() running = True clock.tick(self.frame) __import__('time').sleep(5) while running: clock.tick(self.frame) for event in events.get(): if event.type == pygame.QUIT: running = False self.draw(screen) display.flip() pygame.quit()
def Points(self): self.__PointsBlack,self.__PointsWhite = 0,0 for y in self.__Board: for x in y: if x[2] == 1: self.__PointsWhite += 1 if x[2] == 2: self.__PointsBlack += 1 draw.rect(self.__screen, (32,32,32), Rect(385, 23, 30, 30)), draw.rect(self.__screen, (32,32,32), Rect(435, 23, 30, 30)) if self.__PointsBlack + self.__PointsWhite != 64 and self.__possible_moves != []: textPointsBlack = self.__font.render(str(self.__PointsBlack), True, (255,255,255,255)) textPointsWhite = self.__font.render(str(self.__PointsWhite),True,(255,255,255,255)) self.__screen.blits([(textPointsBlack,(412-textPointsBlack.get_rect()[2],23)),(textPointsWhite,(438,23))]) if self.__PointsBlack + self.__PointsWhite == 64 or self.__possible_moves == []: if self.__PointsBlack > self.__PointsWhite: self.__screen.blits([(self.__won,(362,23)),(self.__lost,(438,23))]) else: self.__screen.blits([(self.__lost,(359,23)),(self.__won,(438,23))]) display.flip()
def HareketEttir(self, Aksiyon): Olay.pump() Skor = 0 OyunEkrani.fill(RGBSiyahRenk) self.AjanRaketYEkseni = RaketGuncelle("Ajan", Aksiyon, self.AjanRaketYEkseni, self.TopYEkseni) RaketOlustur("Ajan", self.AjanRaketYEkseni) self.NormalRaketYEkseni = RaketGuncelle("Normal", Aksiyon, self.NormalRaketYEkseni, self.TopYEkseni) RaketOlustur("Normal", self.NormalRaketYEkseni) [Skor, self.TopXEkseni, self.TopYEkseni, self.TopXYonu, self.TopYYonu] = TopGuncelle(self.AjanRaketYEkseni, self.NormalRaketYEkseni, self.TopXEkseni, self.TopYEkseni, self.TopXYonu, self.TopYYonu) TopOlustur(self.TopXEkseni, self.TopYEkseni) if Skor == 0.05: self.AjanSkor += 1 if Skor == -10: self.NormalSkor += 1 if (Skor > 0.5 or Skor < -0.5): self.OyunSkor = self.OyunSkor * 0.9 + 0.1 * Skor EkranGoruntusu = DiziEkran.array3d(Goruntule.get_surface()) SkorYazdir(OyunEkrani, str(self.AjanSkor), 0) SkorYazdir(OyunEkrani, str(self.NormalSkor), 1) Goruntule.flip() return [Skor, EkranGoruntusu]
def draw_frame(frame, trial_pars): ''' Draw the possible screens. frame -- which frame to draw, e.g., 'fix', 'cue', 'target' trial_pars -- parameters, [cue_pos, tar_pos, isti, cueing, cor_key]''' # Unpack the trial parameters cue_pos, tar_pos, isi, cueing, cor_key = trial_pars # Clear the screen and fill it with black win.fill(colors['black']) # The place holders are visible on all screens # Here, 'pos' is a dictionary; # we retrieve both the key and value pairs in a for-loop for key, (x, y) in pos.items(): # Draw the place holder draw.rect(win, colors['gray'], Rect(x - sz / 2, y - sz / 2, sz, sz), 1) # The fixation cross is visible on all screens if key == 'center': draw.line(win, colors['gray'], (x - 20, y), (x + 20, y), 3) draw.line(win, colors['gray'], (x, y - 20), (x, y + 20), 3) # Draw the fixation screen-- three placeholders with a cross if frame == 'fix': pass # Draw the cue (a bright box--a Rect) if frame == 'cue': c_x, c_y = pos[cue_pos] # coordinates of the cue draw.rect(win, colors['white'], Rect(c_x - sz / 2, c_y - sz / 2, sz, sz), 5) # Draw the target (a filled white disk) if frame == 'target': draw.circle(win, colors['white'], pos[tar_pos], 20) display.flip()
def __init__(self, evManager): self.evManager = evManager self.evManager.RegisterListener(self) self.window = display.set_mode((720, 420)) self.winsize = self.window.get_size() display.set_caption("Blokus") self.background = Surface(self.window.get_size()) self.background.fill((255, 255, 255)) self.window.blit(self.background, (0, 0)) sbLoc = (len(o.board.matrix) * 20 + 5, 0) self.scorebox = {"surf": Surface((100, 200)), "loc": sbLoc} self.scorebox["surf"].fill((255, 255, 255)) self.font = font.Font(None, 40) pbLoc = (sbLoc[0] + 100, 0) self.piecebox = self.window.subsurface(Rect(pbLoc, (200, 420))) self.piecebox.fill((255, 255, 255)) self.drawBoard() self.drawPiece() self.drawScores() self.drawPlayerPieces() display.flip()
def main(argv=sys.argv[1:]): # pygame の初期化 pygame.init() # サイズ 640x480 のウィンドウを生成する screen = display.set_mode(DISPLAY_SIZE) # プログラムの処理を行うループ while True: # ウィンドウを閉じるなどのイベント処理 event_dispatch() # ウィンドウを黒で塗りつぶす screen.fill((0, 0, 0)) # ディスプレイに色を反映させる display.flip() # 0.1秒待つ time.delay(100)
def loop(config, cars): dt = config.clock.tick(config.framerate) check_events(config) config.screen.fill(WHITE) road_outer_radius_pixels = int(((config.road_length / math.pi) + config.road_width) * 0.5 * config.cars_to_pixels) road_inner_radius_pixels = int(((config.road_length / math.pi) - config.road_width) * 0.5 * config.cars_to_pixels) draw.circle(config.screen, BLACK, config.center, road_outer_radius_pixels, 2) draw.circle(config.screen, BLACK, config.center, road_inner_radius_pixels, 2) draw.circle(config.screen, BLACK, config.center, 20, 5) for car in cars: car.update(config, dt, cars) car.draw(config) text_surface = config.font.render("Car " + str(car.label) + " speed: " + format(car.speed, ".2f"), True, BLACK) config.screen.blit(text_surface, (0, car.label*25)) text_surface = config.font.render("Current FPS: " + str(int(config.clock.get_fps())), True, BLACK) config.screen.blit(text_surface, (0, 0)) display.flip()
def text_info(self): self.screen.blit(self.slash, (1000, 580)) display.flip() time.delay(400) self.screen.blit(self.i, (1040, 580)) display.flip() time.delay(400) self.screen.blit(self.n, (1060, 580)) display.flip() time.delay(400) self.screen.blit(self.f, (1080, 580)) display.flip() time.delay(400) self.screen.blit(self.o, (1100, 580)) display.flip() mixer.music.stop()
def render(self): buffer = self.buffer screen = self.screen title_font = self.title_font prompt_font = self.prompt_font title = self.title background_color = 0, 0, 0 default_font_color = 255, 255, 255 buffer.fill(background_color) if self.prompt_blinking and self.menu_time >= 0.25: self.menu_time = 0 self.prompt_blinking = False elif not self.prompt_blinking and self.menu_time >= 1: self.menu_time = 0 self.prompt_blinking = True if self.prompt_blinking: prompt_font_color = background_color else: prompt_font_color = default_font_color title_text = title_font.render(self.title, 0, default_font_color) title_rect = title_text.get_rect(center=(round(SCREEN_W / 2), round(SCREEN_H / 2))) prompt_text = prompt_font.render('Press Enter to start', 0, prompt_font_color) prompt_rect = prompt_text.get_rect(center=(round(SCREEN_W / 2), round(SCREEN_H / 2) + 50)) buffer.blit(title_text, title_rect) buffer.blit(prompt_text, prompt_rect) screen.blit(buffer, buffer.get_rect()) display.flip()
def draw_frame(frame, trial_pars): ''' Draw the possible screens. frame -- which frame to draw, e.g., 'fix','cue', 'target' trial_pars -- parameters, [cue_pos, tar_pos, isti, cueing, cor_key]''' # unpack the trial parameters cue_pos, tar_pos, itiisi, cueing, cor_key = trial_pars # clear the screen and fill it with black color win.fill(colors['black']) # the fixation cross and the place holders are always shown visible on all screens # 'pos' is a dictionary, in which the key and value pairs can be retrieved on-by-one in a for-loop for key, (x, y) in pos.items(): # draw the place holder draw.rect(win, colors['gray'], Rect(x - sz / 2, y - sz / 2, sz, sz), 1) # draw the cross with two lines if key == 'center': draw.line(win, colors['gray'], (x - 20, y), (x + 20, y), 3) draw.line(win, colors['gray'], (x, y - 20), (x, y + 20), 3) # draw the fixation screen (do nothing because nothing needs to change) if frame == 'fix': pass # draw the cue (a bright box--a Rect) if frame == 'cue': c_x, c_y = pos[cue_pos] # coordinates of the cue draw.rect(win, colors['white'], Rect(c_x - sz / 2, c_y - sz / 2, sz, sz), 5) # draw the target (a filled disk) if frame == 'target': draw.circle(win, colors['white'], pos[tar_pos], 20) display.flip()
def main(self): exit_ = False while not exit_: self.draw() display.flip() for event in pygame.event.get(): if event.type == QUIT: exit_ = True elif event.type == KEYDOWN: if event.key == pygame.K_UP: self.camera_y -= 10 self.player_y -= 10 if event.key == pygame.K_DOWN: self.camera_y += 10 self.player_y += 10 if event.key == pygame.K_RIGHT: self.camera_x += 10 self.player_x += 10 if event.key == pygame.K_LEFT: self.camera_x -= 10 self.player_x -= 10 self.draw() display.flip() pygame.quit()
def update_display(self, things, character): """Update of the display : background and items""" background = image.load(BACKGROUND_IMG).convert() self.screen.blit(background, (0, 0)) line_nb = 0 for line in self.maze: pos_y = line_nb * PIXEL_SPRITE tile_nb = 0 for tile in line: pos_x = tile_nb * PIXEL_SPRITE if tile == 1: self.screen.blit(self.wall, (pos_x, pos_y)) elif tile == 2: self.screen.blit(self.skeleton, (pos_x, pos_y)) elif tile == 3: self.screen.blit(self.guy, (pos_x, pos_y)) elif tile == 4: self.screen.blit(self.mac_gyver, (pos_x, pos_y)) character.mg_pos = [line_nb, tile_nb] elif tile == 5: self.screen.blit(self.watchman, (pos_x, pos_y)) tile_nb += 1 line_nb += 1 syringe = image.load(SYRINGE_IMG).convert_alpha() ether = image.load(ETHER_IMG).convert_alpha() plastic_tube = image.load(PLASTIC_TUBE_IMG).convert_alpha() self.screen.blit(syringe, (things.syr_pos[1] * PIXEL_SPRITE, things.syr_pos[0] * PIXEL_SPRITE)) self.screen.blit(ether, (things.eth_pos[1] * PIXEL_SPRITE, things.eth_pos[0] * PIXEL_SPRITE)) self.screen.blit(plastic_tube, (things.pla_pos[1] * PIXEL_SPRITE, things.pla_pos[0] * PIXEL_SPRITE)) display.flip()
def Wolfram(rule): field, cases = initWolfram(rule, width / cellWidth) c = 1 while c: for e in event.get(): if e.type == QUIT: c = 0 elif e.type == MOUSEBUTTONDOWN: field[e.pos[0] / cellWidth] = 1 window.blit(blackCell, (e.pos[0] - e.pos[0] % cellWidth, 0)) display.flip() elif e.type == KEYDOWN: if e.key == K_RETURN: c = 0 for row in range(1, height): updateScreenWolfram(field, row - 1) field = updateWolfram(row, field, cases) c = 1 while c: for e in event.get(): if e.type == QUIT: c = 0
def error_message(): global clock # font = pygame.font.Font(None, 64) # orig_surf = font.render('Enter your text', True, blue) # txt_surf = orig_surf.copy() # # This surface is used to adjust the alpha of the txt_surf. # alpha_surf = pygame.Surface(txt_surf.get_size(), pygame.SRCALPHA) # alpha = 255 # The current alpha value of the surface. # # if alpha > 0: # # Reduce alpha each frame, but make sure it doesn't get below 0. # alpha = max(alpha-4, 0) # txt_surf = orig_surf.copy() # Don't modify the original text surf. # # Fill alpha_surf with this color to set its alpha value. # alpha_surf.fill((255, 255, 255, alpha)) # # To make the text surface transparent, blit the transparent # # alpha_surf onto it with the BLEND_RGBA_MULT flag. # txt_surf.blit(alpha_surf, (0, 0), special_flags=pygame.BLEND_RGBA_MULT) screen.fill((30, 30, 30)) screen.blit(txt_surf, (30, 60)) display.flip() clock.tick(30)
def render(self, screen, rooms: List[Room], moveable_rooms: List[int], current_room_id: int, set_current_room, showMessage, dropCount, aMode) -> bool: while True: screen.fill(BLACK) for dot, room in zip(self._dots, rooms): self._fill_shape(dot, room, moveable_rooms, current_room_id) if room.is_boss(): screen.blit( Screen()._draw_surface(100, 100, 30, "Boss", RED, None), (dot.rect.x, dot.rect.y + 10)) self._paths.draw(screen) self._dots.draw(screen) if showMessage: self._message.update_map(screen) display.flip() for e in event.get(): if e.type == KEYDOWN and e.key == K_m and dropCount >= 0 and not aMode: return False if e.type == KEYDOWN and e.key == K_m and not rooms[ current_room_id].cleared(): return False elif e.type == MOUSEBUTTONDOWN: x, y = e.pos for _id in moveable_rooms: if self._dot_list[_id].rect.collidepoint(x, y): set_current_room(_id) return False elif e.type == QUIT: exit()
def main(): """ Fractals Main """ # Initialize settings object settings = Settings() logging.basicConfig(level=logging.DEBUG) # Initialize Pygame and create a screen init() settings.SCREEN = display.set_mode( (settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT)) while True: fractal = settings.fractal_alg[settings.FRACTAL_ALGORITHM] colorize = settings.color_alg[settings.COLOR_ALGORITHM] if settings.COLOR: # Regenreate color settings.palette. logging.debug("Generating color palette...") settings.palette = colorize(settings) settings.COLOR = False if settings.DRAW: # Regenerate settings.point_list logging.debug("Generating point list palette...") settings.point_list = fractal(settings) settings.DRAW = False pf.display_fractal(settings) # Set display title display.set_caption(f"RE:({settings.RE_START}, {settings.RE_END}), " f"IM:({settings.IM_START}, {settings.IM_END})") display.flip() pf.check_events(settings)
def render(self): """ Renders the cheat mode screen. This includes a transparent button with text **Args**: None. **Preconditions**: None. **Postconditions**: CheatMode's contents will be rendered to the main pygame display surface. **Returns**: None. """ self.drawWindow.blit(self.gameSurf, (0, 0)) self.drawWindow.blits([(self.textBackgroundSurf, self.textBackgroundPos), (self.titleSurf, self.titlePos), (self.subtitleSurf, self.subtitlePos)]) display.flip()
def display_game(screen, snake, apple, count, max_count, obstacles=[], ddx=0): # the background draw.rect(screen, gris_clair, (0, 0, tfx, tfy)) display_upper_bar(screen, count, max_count) # obstacles display_obstacles(screen, obstacles) # the apple display_apple(screen, apple[0], apple[1]) # the snake u = len(snake.list) if u == 1: # too short for a tail or a head display_body_part(screen, snake.list[0], ddx) else: for i in range(1, u - 1): display_body_part(screen, snake.list[(snake.head + i) % u], ddx) display_tail(screen, snake.list[snake.head - 1], snake.list[snake.head - 2]) display_head(screen, snake.list[snake.head], snake.list[(snake.head + 1) % u]) display.flip()
def initialize_game(): pygame.init() window = display.set_mode((gc.DISPLAY_WIDTH, gc.DISPLAY_HEIGHT)) display.set_caption("Terrible Games") pygame.font.init() load_font = pygame.font.SysFont(('Comic Sans MS'), 45) load_text = load_font.render("Loading...", True, (0, 0, 0)) x = (gc.DISPLAY_WIDTH * 1.03 - load_text.get_rect().right) // 2 y = (gc.DISPLAY_HEIGHT - load_text.get_rect().bottom) // 2 window.fill((210, 127, 73)) window.blit(load_text, (x, y)) display.flip() image = pygame.image.load("./resources/wood_texture.jpg").convert() image = pygame.transform.scale(image, (gc.DISPLAY_WIDTH, gc.DISPLAY_HEIGHT)) main_window = gameWindow(window=window, running=True, curr_screen="Title", img=image) return main_window
def render(self): """ Renders the minefield, reset button, flag counter, and timer **Args**: None. **Preconditions**: None. **Postconditions**: None. **Returns**: None. """ for y in range(self.minefield.y_size): for space in self.grid[y]: self.renderSpace(space) self.renderReset() self.updateClock() self.updateFlags() display.flip()
def draw_neighbor(self, screen, sx1, sx2, sy1, sy2) -> None: """draw wall between neighbors in the screen Parameters: screen (Surface): game screen sx1 (Integer): main coordinates sx2 (Integer): main coordinates sy1 (Integer): neighbors coordinates sy2 (Integer): neighbors coordinates Returns: None """ posX = (self.margin + self.width) * (sy2) + self.margin posY = (self.margin + self.height) * (sx2) + self.margin draw.rect(screen, WALL, (posX, posY, 13, 13)) display.flip() posX = (self.margin + self.width) * (sy2 + (sy1 - sy2) / 2) + self.margin posY = (self.margin + self.height) * (sx2 + (sx1 - sx2) / 2) + self.margin draw.rect(screen, WALL, (posX, posY, 13, 13)) display.flip()
def testing(td=[]): global s,tdata print "testing, 1,2,3..." global tdata # import pdb; pdb.set_trace() bogus_config(fff=tdata) #print tdata, "from testing app" v=tdata[1] f=tdata[2] a=tdata[3] print "v",v,"f",f,"a",a sc=scr() #c=cfg() att=display_attribs() sc.fields=f sc.set_assignments(a) sc.display_field("f3") #sc.display_fields() #screen.blit(sc.win,(0,0)) screen.fill((180,180,0)) tm.wait(200) dsp.flip() tm.wait(200) for fff in f: it=a[fff][1] tp=a[fff][2] frec=f[fff] there=(frec[1],frec[2]) if tp == 'S': that=ren(it,True,(0,0,200)) else: that=load(it) # assuming picture; number unimplemented screen.blit(that,there) tm.wait(500) dsp.flip() print "end of test"
def text_play(self): self.screen.blit(self.p, (900, 580)) display.flip() time.delay(400) self.screen.blit(self.l, (920, 580)) display.flip() time.delay(400) self.screen.blit(self.a, (940, 580)) display.flip() time.delay(400) self.screen.blit(self.y, (960, 580)) display.flip() time.delay(400) self.text_info()