def __init__(self, arbalet, sim_height, sim_width): Thread.__init__(self) self.arbalet = arbalet self.sim_width = sim_width self.sim_height = sim_height self.border_thickness = 1 self.cell_height = sim_width / arbalet.width self.cell_width = sim_height / arbalet.height self.rate = Rate(arbalet.config['refresh_rate']) display.set_caption("Arbalet simulator", "Arbalet") if get_extended(): try: self.icon = load_extended(join(dirname(__file__), 'icon.png')) except error: raise else: display.set_icon(self.icon) environ['SDL_VIDEO_CENTERED'] = '1' print("Launching simulator %dx%d " % (self.sim_width, self.sim_height)) with self.arbalet.sdl_lock: self.display = display.set_mode([self.sim_width, self.sim_height], 0, 32) self.running = False self.start()
def __initialize_window(self): self.running = False init() display.set_icon(image.load(read_preferences().get_logo_image())) display.set_caption(read_preferences().get_title())
def __init__(self, state): """ Args: state ('dict of class:Pokemon'): A dictionary with all the information needed to display the a battle. Note: This dict have as key: "Ally_0", "Ally_1", "Foe_0" and "Foe_1" with the corresponding pokemon as a value. Action: Create and execute a window where the 'state' of a battle is displayed. """ pygame.init() width, height = Display_Config['BATTLE_SIZE'] height += Display_Config['LOG_SIZE'][1] height += Display_Config['SELECT_SIZE'][1] if state['use_agent'] and Display_Config['VISUALIZE_AGENT_INFO']: width *= 2 SCREEN_SIZE = (width, height) self.SCREEN = display.set_mode(scale(SCREEN_SIZE)) display.set_icon(load_image(Directory['ICON_FILE'])) display.set_caption(Display_Config['TITLE']) self.battle = Battle_display(state) self.dialog = Dialog_display() self.select = Selection_Manager(state) self.visualize_items = [self.battle, self.dialog, self.select] if Display_Config["PLAY_MUSIC"]: Song().play() if state['use_agent'] and Display_Config['VISUALIZE_AGENT_INFO']: self.visualize_items.append(Stats_display(state)) self.visualize_items.append(Moves_display(state))
def init() -> None: pygame.init() global g_surface g_surface = pgdisplay.set_mode((670, 600)) pgdisplay.set_caption("Violin Note Practice") pgdisplay.set_icon(pgimage.load("./data/Images/treble_clef.png"))
def run(self): icon = image.load("Icon.png") display.set_icon(icon) self.__window = display.set_mode(SIZE) display.set_caption("Twenty Nine") self.__window.fill(COLOURS.get('BOARD')) display.flip() while True: r, w, x = select(self.__read, self.__write, self.__error, 0) for f in r: if f is self.__listener: data = receive(f) if data: print data if data[0] == "ID": self.__ID = int(data[1]) if data[0] == "Cards": print data[1] event = pyevent.poll() if event.type == QUIT: self.__Quit() break elif event.type == KEYDOWN: if event.key == K_ESCAPE: self.__Quit() break else: send(self.__listener, chr(event.key)) elif event.type == MOUSEBUTTONDOWN: print event
def help_window(): global run_help size = [1000, 720] screen = display.set_mode(size) display.set_caption("Help") display.set_icon(pygame.image.load("images/help/help.png")) clock = pygame.time.Clock() fps = 60 x = 880 y = 600 image_ok_global = pygame.image.load("images/help/ok.png") image_ok = pygame.transform.scale(image_ok_global, (110, 110)) # mixer.music.load("images/audio/music.mp3") # mixer.music.play() image_global = pygame.image.load("images/help/asteroid.jpg") image = pygame.transform.scale(image_global, (size)) font = pygame.font.SysFont("arial", 20) text1 = font.render("Hello. The rules of the game are as follows:", True, (255, 255, 255)) text2 = font.render("1. You have 3 lives", True, (255, 255, 255)) text3 = font.render( "2. You have to catch meteorites with the numbers you choose", True, (255, 255, 255)) text4 = font.render("3. To catch, left-click on the meteorite", True, (255, 255, 255)) text5 = font.render( "4. If not guessed, the planet explodes, if a meteorite with the correct number falls to earth, it also explodes", True, (255, 255, 255)) text6 = font.render("5. each correct answer +1 point", True, (255, 255, 255)) run_help = True while run_help: screen.blit(image, (0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: run_help = False pygame.quit() quit() if event.type == pygame.MOUSEBUTTONDOWN: position = pygame.mouse.get_pos() if position[0] >= x and position[1] >= y: if position[0] <= x + 110 and position[1] <= y + 110: run_help = False # game_intro() screen.blit(text1, (0, 0)) screen.blit(text2, (0, 30)) screen.blit(text3, (0, 60)) screen.blit(text4, (0, 90)) screen.blit(text5, (0, 120)) screen.blit(text6, (0, 150)) screen.blit(image_ok, (x, y)) clock.tick(fps) display.update() game_intro()
def __init__(self,width,height,title=DEFAULT_TITLE,display_color=DEFAULT_COLOR,icon=DEFAULT_ICON_PATH): display.set_mode([width,height]) display.set_caption(title) display.set_icon(image.load(icon)) self.__display = display.get_surface() self.__color = display_color self.drawDisplay()
def init(cls): init() os.environ['SDL_VIDEO_CENTERED'] = "{!s},{!s}".format(0, 0) display.set_icon( image.load(os.path.join(os.getcwd(), 'data', 'favicon.png'))) display.set_caption("WorldBuilding") display.set_mode((ANCHO, ALTO), SCALED) cls.contents = LayeredUpdates()
def init_screen(self): screen_info = display.Info() self.desktop_width = screen_info.current_w self.desktop_height = screen_info.current_h self.get_screen_size() display.set_icon(load_image(self.main_path, 'iancraft.ico', convert=False)) self.screen = display.set_mode((self.sw, self.sh), self.flags) display.set_caption('IanCraft')
def init(): state = 0 display.init() font.init() settings = load_settings_file() screen = display.set_mode(settings.frame_resolution, DOUBLEBUF) display.set_caption("beeSim") display.set_icon(game_icon) return state, screen, settings
def __init__(self): init() set_caption('BomberMan') set_icon(load('Resources\images\icon.png')) self.fps = 60 self.screen = set_mode((1024, 768)) self.bg_color = Color('#153515') self.load_images() self.btns = [(70, 490, 182, 552), (70, 555, 334, 602), (70, 620, 351, 681), (70, 685, 168, 733)] self.checked_btn = 0 self.reload() self.cycle()
def play(self, caption="sc8pr", icon=None, mode=True): "Initialize pygame and run the main drawing / event handling loop" # Initialize pygame.init() self._clock = pygame.time.Clock() pygame.key.set_repeat(400, 80) _pd.set_caption(caption) try: try: icon = pygame.image.load(icon) except: icon = Image.fromBytes(sc8prData("alien")).image _pd.set_icon(icon) except: logError() w, h = self._size self._fixedAspect = w / h mode = self._pygameMode(mode) self._mode = mode self.image = _pd.set_mode(self._size, mode) self.key = None self.mouse = pygame.event.Event(pygame.USEREVENT, code=None, pos=(0,0), description="Sketch startup") # Run setup try: if hasattr(self, "setup"): self.setup() else: main = sys.modules["__main__"] if hasattr(main, "setup"): main.setup(self) except: logError() # Drawing/event loop while not self.quit: try: self.frameCount += 1 br = self.dirtyRegions flip = br is None self.draw() if not flip: br += self.dirtyRegions flip = self._largeArea() self._clock.tick(self.frameRate) if flip: _pd.flip() else: _pd.update(br) if self.capture is not None: self.capture.capture(self) if self.ondraw: self.ondraw() self._evHandle() except: logError() pygame.quit() mod = sys.modules.get("sc8pr.text") if mod: mod.Font.dumpCache() return self
def __init__(self): Fretboard.__init__(self) display.set_caption("Fretboard Trainer") screen.fill((221, 237, 128)) self.icon = pygame.image.load(path + 'img\\' + 'guitar.png') display.set_icon(self.icon) self.noteIndex = -1 Game.make_quiz(self) self.score = 0 self.time = [5,0]
def init(cls): init() os.environ['SDL_VIDEO_CENTERED'] = "{!s},{!s}".format(0, 0) try: icon = image.load( os.path.join(os.getcwd(), 'lib', 'frontend', 'icon.png')) except error: icon = image.load(os.path.join(os.getcwd(), 'frontend', 'icon.png')) icon.set_colorkey((255, 255, 255, 0)) display.set_icon(icon) display.set_caption("PMCDB: PyMavisCustomDatabase v0.2.2") display.set_mode((ANCHO, ALTO)) cls.contents = LayeredUpdates()
def Board(self): init() self.__screen = display.set_mode((850,900)) self.__players = [image.load(resource_path("assets/img/Player_White.png")),image.load(resource_path("assets/img/Player_Black.png"))] self.__Options = image.load(resource_path("assets/img/Player_Possible_move.png")) self.__font = font.Font(resource_path('assets/fonts/SF-Compact-Rounded-Regular.otf'),24) self.__won,self.__lost = self.__font.render("WON",True,(255,255,255)),self.__font.render("LOST",True,(255,255,255)) display.set_caption("Reversi") display.set_icon(image.load(resource_path("assets/img/Icon.ico"))) self.__screen.blits([(image.load(resource_path("assets/img/Board.png")),(0,0)),(self.__players[0],self.__Board[3][3][:2]),(self.__players[1],self.__Board[3][4][:2]),(self.__players[1],self.__Board[4][3][:2]),(self.__players[0],self.__Board[4][4][:2])]) self.__Board[3][3][2],self.__Board[3][4][2],self.__Board[4][3][2],self.__Board[4][4][2]= 1,2,2,1 shadow = self.__font.render("HUMAN", True, (255,255,255,255)) self.__screen.blit(shadow,(23.7,23)) self.Options() self.listen()
def __init__(self): display.init() font.init() mixer.init(buffer=0) self.screen_size = [800, 500] self.surface = display.set_mode(self.screen_size) life_image = image.load(Utils.get_path("image/icon.png")).convert_alpha() display.set_icon(life_image) display.set_caption("Ping Pong") display.set_icon(life_image) self.theme_sound = mixer.Sound(Utils.get_path("sound/menu-screen-theme.wav")) self.theme_sound.set_volume(0.25) if Setting.MUSIC: self.theme_sound.play(-1) self.switch_screen(Setting.MENU_SCREEN)
def open(self): # Create the Window, load its title, icon environ['SDL_VIDEO_CENTERED'] = '1' self.sim_width = self.width * self.CELL_WIDTH self.sim_height = self.height * self.CELL_HEIGHT self.border_thickness = 2 path_icon = join(realpath(dirname(__file__)), "icon.png") icon = image.load(path_icon) self.display = display.set_mode((self.sim_width, self.sim_height), 0, 32) display.set_caption( "Arbalet Frontage simulator [{}x{}]".format( self.height, self.width), "Arbalet") display.set_icon(icon) display.update() self.opened = True
def __init__(self, screen1, screen2): self.screen1 = screen1 self.screen2 = screen2 self.is_round_over = None self.is_game_over = None self.win_round_player = None self.win_game_player = None self.players_names = None # Score self.font = None self.score1_value = None self.score2_value = None self.score1_x = None self.score1_y = None self.score2_x = None self.score2_y = None # Game Over self.game_over_font = None # Round Over self.round_over_font = None # Game self.flag_game_over = None # Gravity self.gravity = None # Background self.background2 = None self.background1 = None # Caption and Icon display.set_caption("Игра Трясунчик") icon = image.load('./Media/Images/ufo.png') display.set_icon(icon)
def __init__(self): display.init() font.init() mixer.init(buffer=0) self.screen_size = [800, 500] self.surface = display.set_mode(self.screen_size) life_image = image.load( Utils.get_path('image/icon.png')).convert_alpha() display.set_icon(life_image) display.set_caption('Ping Pong') display.set_icon(life_image) self.theme_sound = mixer.Sound( Utils.get_path('sound/menu-screen-theme.wav')) self.theme_sound.set_volume(0.25) if Setting.MUSIC: self.theme_sound.play(-1) self.switch_screen(Setting.MENU_SCREEN)
def grid_init(self): self.screen.fill((50, 0, 0)) self.screen.blit(self.background_img, (0, general.IMG_Y_SHIFT)) display.set_caption("Fighting Corona Virus #STAY_HOME_STAY_SAFE") display.set_icon(self.icon) score = self.screen_font.render("Quarantine Days: {}".format(self.quarantine_days), True, (255, 255, 225)) self.screen.blit(score, (self.quarantine_days_X, self.quarantine_days_Y)) sprayer = self.screen_font.render("Sprayer: {}".format(self.sprayer_nums), True, (255, 255, 225)) self.screen.blit(sprayer, (self.sprayer_X, self.sprayer_Y)) dist = self.dist_font.render("|-- Social Distance --|", True, (255, 255, 225)) self.screen.blit(dist, (self.distance_X, self.distance_Y)) infection = self.screen_font.render("Number of Infected People: {}".format(self.infection_nums), True, (255, 255, 225)) self.screen.blit(infection, (self.infection_X, self.infection_Y)) for key, value in self.buildings.items(): self.screen.blit(value['image'], value['origin'] + (0, general.IMG_Y_SHIFT)) self.screen.blit(value['guard'], value['origin'] + (0, general.IMG_Y_SHIFT))
def main(): global c display.set_caption('lemon operating language') try: icon = image.load('icon32x32.png') display.set_icon(icon) except: pass fix_keyboard() change_font_size() c = lemon_client.Client(thread_message_signal, send_thread_message) keybindings.setup(c) initial_resize() c.after_start() if args.no_timers: args.dontblink = True else: pygame.time.set_timer(pygame.USEREVENT, 777) #poll for SIGINT once in a while reset_cursor_blink_timer() try: if args.profile: import cProfile cProfile.run('mainloop()', filename="lemon.profile") else: mainloop() # except KeyboardInterrupt() as e: # pygame.display.iconify() # raise e except Exception as e: #log(e),pass pygame.display.iconify() raise
def hide(screen): paint_screen(screen, gl.BLACK) set_icon(pygame.image.load(gl.DATA_DIR + "imgv-icon-blank.png")) normal_cursor() while 1: event = pygame.event.poll() pygame.time.wait(150) check_quit(event) if event.type == KEYDOWN and event.key not in (K_LALT, K_RALT, K_LCTRL, K_RCTRL, K_TAB): if gl.CORRECT_PASSWORD.lower() not in ("none", None): pw = ask(screen, "Password") if pw == gl.CORRECT_PASSWORD: break else: show_message(screen, "Incorrect Password", (150), 24, ("bold", "transparent")) show_message(screen, "Press any key to try again", (175), 12, ("bold", "transparent")) f = open(gl.DATA_DIR + "security.log", "a") f.write("Password failure: %s\n" % ctime()) f.close() continue else: break set_icon(pygame.image.load(gl.DATA_DIR + "imgv-icon.png"))
def main(): #---- Prepare # Game field size SCREEN_W, SCREEN_H = (640, 420) # Shape drag machine states (ST_MOVE, ST_ROTATE, ST_NONE) = range(3) state = ST_NONE # Setup game window display.set_caption(TITLE) display.set_icon(image.load('pytang.bmp')) # Create and setup game field screen = display.set_mode((SCREEN_W, SCREEN_H)) screen.fill(BACKGROUND_COLOR) # Create a game field copy for internal purposes background = screen.copy() # Game objects - different shapes shapes = [ Triangle((0, 0), (60, 60), (0, 120)), Triangle((0, 0), (60, 0), (30, 30)), Triangle((60, 0), (120, 0), (120, 60)), Triangle((0, 120), (60, 60), (120, 120)), Triangle((60, 60), (90, 30), (90, 90)), Parallelogram((60, 0), (90, 30), (60, 60)), Parallelogram((90, 30), (120, 60), (120, 120)) ] # Game object bounding rectangles as a dictionary, # where key is the game object instance, and # the appropriate value is it's bounding rectangle frames = {} # Each shape is located in a separate cell of the game field # at first time. The game field is divided by 3 rows and # 3 columns, ergo, 3 x 3 = 9 cells. # One cell size CELL_SIZE = (SCREEN_W / 3, SCREEN_H / 3) # Shapes initial locations as (column, row) tuples. locations = ((0, 0), (1, 0), (2, 1), (2, 2), (0, 1), (0, 2), (2, 0)) if DRAFT_MODE: draw_shape = _draw_shape_draft else: draw_shape = _draw_shape_filled # Move shapes to the initial locations for i in range(len(shapes)): shapes[i].move_to([(locations[i][coord] + 0.5) * CELL_SIZE[coord] for coord in (0, 1)]) frames[shapes[i]] = draw_shape(screen, shapes[i]) #---- Event loop do_exit = False # Shape object which is moving or rotating now active_shape = None # Mouse previous position, is valid when some shape # is rotating or moving prev_pos = None while not do_exit: display.flip() for ev in event.get(): # Game is over - user close main window if ev.type == QUIT: do_exit = True break # Mouse button is push down: # user wants to move or rotate one of the shapes elif (ev.type == MOUSEBUTTONDOWN) and (state == ST_NONE): touchpoint = mouse.get_pos() # Search for the first shape including # the mouse button down point. for shape in shapes: if shape.include(touchpoint): active_shape = shape prev_pos = touchpoint # If the touchpoint is laying inside the # inner circle, the shape s.b. moved; # the shape s.b. rotated otherwise if (distance(touchpoint, shape.get_ref_point()) <= shape.get_r_inner()): state = ST_MOVE else: state = ST_ROTATE # Take the active shape from the shapes # common list, # draw other shapes on the background surface. shapes.remove(active_shape) background.fill(BACKGROUND_COLOR) for shape in shapes: draw_shape(background, shape) break # Mouse button is up: shape moving/rotating is done elif (ev.type == MOUSEBUTTONUP) and (state != ST_NONE): shapes.append(active_shape) active_shape = None state = ST_NONE # Mouse is moving. If the mouse button is down # (i.e. if we are in ST_MOVE or ST_ROTATE state), # the active shape s.b. moved or rotated. elif (ev.type == MOUSEMOTION) and (state != ST_NONE): screen.blit(background, frames[active_shape].topleft, frames[active_shape]) curr_pos = mouse.get_pos() if state == ST_MOVE: active_shape.move_by(vectorAB(prev_pos, curr_pos)) else: active_shape.rotate( inclination(active_shape.get_ref_point(), curr_pos) - inclination(active_shape.get_ref_point(), prev_pos)) prev_pos = curr_pos frames[active_shape] = draw_shape(screen, active_shape) # Game is over, print shapes location if needed if PRINT_OUT: for i in range(len(shapes)): print "Shape %u vertices:" % (i, ) for vertex in shapes[i].get_vertices(): print "\t (%.2f, %.2f)" % vertex
pg.font.init() quicksand80 = pg.font.SysFont("quicksand", 80) notomono35 = pg.font.SysFont("notomono", 35) notomono30_italic = pg.font.SysFont("notomono", 30, italic=True) quicksand22 = pg.font.SysFont("quicksand", 22) quicksand22b = pg.font.SysFont("quicksand", 22, bold=True) notomono22 = pg.font.SysFont("notomono", 22) quicksand20 = pg.font.SysFont("quicksand", 20, bold=True) quicksand20n = pg.font.SysFont("quicksand", 20) quicksand16 = pg.font.SysFont('quicksand', 16, italic=True) notomono20_italic = pg.font.SysFont("notomono", 20, italic=True) # Textos do Menu Inicial: display.set_caption('NEO PLAYER') display.set_icon(player_icon) player = quicksand80.render('{ NEO PLAYER }', True, (220, 220, 220)) player3 = quicksand80.render('{ NEO PLAYER }', True, (0, 0, 180)) player2 = quicksand80.render('{ NEO PLAYER }', True, (0, 0, 0)) author = quicksand16.render('by $Neo', True, (255, 255, 255)) loading = quicksand22b.render('Loading . . .', True, (0, 250, 0)) loading2 = quicksand22b.render('Loading . . .', True, (0, 0, 0)) capa = transform.scale(image.load('./assets/player_back.jpg'), (1720, 720)) #---------- Função "música tocando" -----------# def playing(i): v = 1 color_change = n = 0 img_alpha_change = 1
class GLDisplayContext(object): def __init__(self): self.reset() def getWindowSize(self): w, h = (config.settings.windowWidth.get(), config.settings.windowHeight.get()) return max(20, w), max(20, h) def displayMode(self): return pygame.OPENGL | pygame.RESIZABLE | pygame.DOUBLEBUF def reset(self): pygame.key.set_repeat(500, 100) try: display.gl_set_attribute(pygame.GL_SWAP_CONTROL, config.settings.vsync.get()) except Exception, e: logging.warning('Unable to set vertical sync: {0!r}'.format(e)) display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8) d = display.set_mode(self.getWindowSize(), self.displayMode()) try: pygame.scrap.init() except: logging.warning('PyGame clipboard integration disabled.') display.set_caption('MCEdit ~ ' + release.get_version(), 'MCEdit') if sys.platform == 'win32' and config.settings.setWindowPlacement.get( ): config.settings.setWindowPlacement.set(False) config.save() X, Y = config.settings.windowX.get(), config.settings.windowY.get() if X: w, h = self.getWindowSize() hwndOwner = display.get_wm_info()['window'] flags, showCmd, ptMin, ptMax, rect = mcplatform.win32gui.GetWindowPlacement( hwndOwner) realW = rect[2] - rect[0] realH = rect[3] - rect[1] showCmd = config.settings.windowShowCmd.get() rect = (X, Y, X + realW, Y + realH) mcplatform.win32gui.SetWindowPlacement( hwndOwner, (0, showCmd, ptMin, ptMax, rect)) config.settings.setWindowPlacement.set(True) config.save() elif sys.platform == 'linux2' and mcplatform.hasXlibDisplay: # Looks like KDE need to loose time or to instanciate Xlib atoms to get the right window to place at screen # Keep this code untill the end of the 'for windowID in windowIDs' loop dis = mcplatform.Xlib.display.Display() root = dis.screen().root windowIDs = root.get_full_property( dis.intern_atom('_NET_CLIENT_LIST'), mcplatform.Xlib.X.AnyPropertyType).value for windowID in windowIDs: window = dis.create_resource_object('window', windowID) name = window.get_wm_name() # Title pid = window.get_full_property( dis.intern_atom('_NET_WM_PID'), mcplatform.Xlib.X.AnyPropertyType) # PID dis = mcplatform.Xlib.display.Display() dRoot = dis.screen().root win = dRoot.get_full_property( dis.intern_atom('_NET_ACTIVE_WINDOW'), mcplatform.Xlib.X.AnyPropertyType).value[0] win = dis.create_resource_object('window', win) win.configure(x=config.settings.windowX.get(), y=config.settings.windowY.get()) # self.win = win dis.sync() try: iconpath = os.path.join(directories.getDataDir(), 'favicon.png') iconfile = file(iconpath, 'rb') icon = pygame.image.load(iconfile, 'favicon.png') display.set_icon(icon) except Exception, e: logging.warning('Unable to set icon: {0!r}'.format(e))
class GLDisplayContext(object): def __init__(self, splash=None): self.reset(splash) @staticmethod def getWindowSize(): w, h = (config.settings.windowWidth.get(), config.settings.windowHeight.get()) return max(20, w), max(20, h) @staticmethod def displayMode(): return pygame.OPENGL | pygame.RESIZABLE | pygame.DOUBLEBUF def reset(self, splash=None): pygame.key.set_repeat(500, 100) try: display.gl_set_attribute(pygame.GL_SWAP_CONTROL, config.settings.vsync.get()) except Exception, e: logging.warning('Unable to set vertical sync: {0!r}'.format(e)) display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8) wwh = self.getWindowSize() d = display.set_mode(wwh, self.displayMode()) GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glAlphaFunc(GL.GL_NOTEQUAL, 0) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) # textures are 256x256, so with this we can specify pixel coordinates GL.glMatrixMode(GL.GL_TEXTURE) GL.glScale(1 / 256., 1 / 256., 1 / 256.) if splash: swh = splash.get_size() x, y = (wwh[0] / 2 - swh[0] / 2, wwh[1] / 2 - swh[1] / 2) w, h = swh data = image.tostring(splash, 'RGBA', 1) GL.glWindowPos2d(x, y) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glDrawPixels(w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, numpy.fromstring(data, dtype='uint8')) display.flip() display.set_caption('MCEdit ~ ' + release.get_version(), 'MCEdit') if sys.platform == 'win32' and config.settings.setWindowPlacement.get( ): config.settings.setWindowPlacement.set(False) config.save() X, Y = config.settings.windowX.get(), config.settings.windowY.get() if X: hwndOwner = display.get_wm_info()['window'] flags, showCmd, ptMin, ptMax, rect = mcplatform.win32gui.GetWindowPlacement( hwndOwner) realW = rect[2] - rect[0] realH = rect[3] - rect[1] showCmd = config.settings.windowShowCmd.get() rect = (X, Y, X + realW, Y + realH) mcplatform.win32gui.SetWindowPlacement( hwndOwner, (0, showCmd, ptMin, ptMax, rect)) config.settings.setWindowPlacement.set(True) config.save() elif sys.platform == 'linux2' and mcplatform.hasXlibDisplay: dis = mcplatform.Xlib.display.Display() root = dis.screen().root windowIDs = root.get_full_property( dis.intern_atom('_NET_CLIENT_LIST'), mcplatform.Xlib.X.AnyPropertyType).value for windowID in windowIDs: window = dis.create_resource_object('window', windowID) name = window.get_wm_name() if "MCEdit ~ Unified" in name: win = window win.configure(x=config.settings.windowX.get(), y=config.settings.windowY.get()) self.win = win dis.sync() try: iconpath = os.path.join(directories.getDataDir(), 'favicon.png') iconfile = file(iconpath, 'rb') icon = pygame.image.load(iconfile, 'favicon.png') display.set_icon(icon) except Exception, e: logging.warning('Unable to set icon: {0!r}'.format(e))
window = dis.create_resource_object('window', windowID) name = window.get_wm_name() if "MCEdit ~ Unified" in name: win = window win.configure(x=config.settings.windowX.get(), y=config.settings.windowY.get()) except Exception, e: logging.debug('ERROR: Xlib could not find the MCEdit wondow object:') logging.debug(' %s'%e) self.win = win dis.sync() try: iconpath = os.path.join(directories.getDataDir(), 'favicon.png') iconfile = file(iconpath, 'rb') icon = pygame.image.load(iconfile, 'favicon.png') display.set_icon(icon) except Exception, e: logging.warning('Unable to set icon: {0!r}'.format(e)) self.display = d self.loadTextures() def getTerrainTexture(self, level): return self.terrainTextures.get(level.materials.name, self.terrainTextures["Alpha"]) def loadTextures(self): self.terrainTextures = {} def makeTerrainTexture(mats): w, h = 1, 1
def main(): #---- Prepare # Game field size SCREEN_W, SCREEN_H = (640, 420) # Shape drag machine states (ST_MOVE, ST_ROTATE, ST_NONE) = range(3) state = ST_NONE # Setup game window display.set_caption(TITLE) display.set_icon(image.load('pytang.bmp')) # Create and setup game field screen = display.set_mode((SCREEN_W, SCREEN_H)) screen.fill(BACKGROUND_COLOR) # Create a game field copy for internal purposes background = screen.copy() # Game objects - different shapes shapes = [ Triangle((0, 0), (60, 60), (0, 120)), Triangle((0, 0), (60, 0), (30, 30)), Triangle((60, 0), (120, 0), (120, 60)), Triangle((0, 120), (60, 60), (120, 120)), Triangle((60, 60), (90, 30), (90, 90)), Parallelogram((60, 0), (90, 30), (60, 60)), Parallelogram((90, 30), (120, 60), (120, 120)) ] # Game object bounding rectangles as a dictionary, # where key is the game object instance, and # the appropriate value is it's bounding rectangle frames = {} # Each shape is located in a separate cell of the game field # at first time. The game field is divided by 3 rows and # 3 columns, ergo, 3 x 3 = 9 cells. # One cell size CELL_SIZE = (SCREEN_W / 3, SCREEN_H / 3) # Shapes initial locations as (column, row) tuples. locations = ( (0, 0), (1, 0), (2, 1), (2, 2), (0, 1), (0, 2), (2, 0) ) if DRAFT_MODE: draw_shape = _draw_shape_draft else: draw_shape = _draw_shape_filled # Move shapes to the initial locations for i in range(len(shapes)): shapes[i].move_to( [ (locations[i][coord] + 0.5) * CELL_SIZE[coord] for coord in (0, 1) ] ) frames[shapes[i]] = draw_shape(screen, shapes[i]) #---- Event loop do_exit = False # Shape object which is moving or rotating now active_shape = None # Mouse previous position, is valid when some shape # is rotating or moving prev_pos = None while not do_exit: display.flip() for ev in event.get(): # Game is over - user close main window if ev.type == QUIT : do_exit = True break # Mouse button is push down: # user wants to move or rotate one of the shapes elif (ev.type == MOUSEBUTTONDOWN) and (state == ST_NONE): touchpoint = mouse.get_pos() # Search for the first shape including # the mouse button down point. for shape in shapes: if shape.include(touchpoint): active_shape = shape prev_pos = touchpoint # If the touchpoint is laying inside the # inner circle, the shape s.b. moved; # the shape s.b. rotated otherwise if ( distance(touchpoint, shape.get_ref_point()) <= shape.get_r_inner() ): state = ST_MOVE else: state = ST_ROTATE # Take the active shape from the shapes # common list, # draw other shapes on the background surface. shapes.remove(active_shape) background.fill(BACKGROUND_COLOR) for shape in shapes: draw_shape(background, shape) break # Mouse button is up: shape moving/rotating is done elif (ev.type == MOUSEBUTTONUP) and (state != ST_NONE) : shapes.append(active_shape) active_shape = None state = ST_NONE # Mouse is moving. If the mouse button is down # (i.e. if we are in ST_MOVE or ST_ROTATE state), # the active shape s.b. moved or rotated. elif (ev.type == MOUSEMOTION) and (state != ST_NONE) : screen.blit( background, frames[active_shape].topleft, frames[active_shape] ) curr_pos = mouse.get_pos() if state == ST_MOVE : active_shape.move_by(vectorAB(prev_pos, curr_pos)) else: active_shape.rotate( inclination( active_shape.get_ref_point(), curr_pos ) - inclination( active_shape.get_ref_point(), prev_pos ) ) prev_pos = curr_pos frames[active_shape] = draw_shape(screen, active_shape) # Game is over, print shapes location if needed if PRINT_OUT: for i in range(len(shapes)): print "Shape %u vertices:" % (i,) for vertex in shapes[i].get_vertices(): print "\t (%.2f, %.2f)" % vertex
from Npcs import Npc from Bullet import Bullet import math import random import sys pygame.init() screen = pygame.display.set_mode((1000, 600)) background = pygame.image.load('background.jpg') ## Set icons for games ## pygame.display.set_caption("Space Invaders") icon = pygame.image.load('spaceship.png') set_icon(icon) ''' set player options ''' player_img = pygame.image.load('spaceship.png') playerX = 500 # x position playerY = 500 # y position player1 = Npc(playerImg=player_img) player_valx = 0 player_valy = 0 enemy_img = pygame.image.load('ufo.png') enemy = Npc(playerImg=enemy_img) enemyX = 500 enemyY = 50 enemy_valx = 0.3 enemy_valy = 30
class GLDisplayContext(object): def __init__(self, splash=None, caption=("", "")): self.win = None self.reset(splash, caption=caption) @staticmethod def getWindowSize(): w, h = (config.settings.windowWidth.get(), config.settings.windowHeight.get()) return max(20, w), max(20, h) @staticmethod def displayMode(): return pygame.OPENGL | pygame.RESIZABLE | pygame.DOUBLEBUF def reset(self, splash=None, caption=("", "")): pygame.key.set_repeat(500, 100) try: display.gl_set_attribute(pygame.GL_SWAP_CONTROL, config.settings.vsync.get()) except Exception, e: logging.warning('Unable to set vertical sync: {0!r}'.format(e)) display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8) if DEBUG_WM: print "config.settings.windowMaximized.get()", config.settings.windowMaximized.get() wwh = self.getWindowSize() if DEBUG_WM: print "wwh 1", wwh d = display.set_mode(wwh, self.displayMode()) GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glAlphaFunc(GL.GL_NOTEQUAL, 0) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) # textures are 256x256, so with this we can specify pixel coordinates GL.glMatrixMode(GL.GL_TEXTURE) GL.glScale(1 / 256., 1 / 256., 1 / 256.) display.set_caption(*caption) if mcplatform.WindowHandler: self.win = mcplatform.WindowHandler(mode=self.displayMode()) # The following Windows specific code won't be executed if we're using '--debug-wm' switch. if not USE_WM and sys.platform == 'win32' and config.settings.setWindowPlacement.get(): config.settings.setWindowPlacement.set(False) config.save() X, Y = config.settings.windowX.get(), config.settings.windowY.get() if X: hwndOwner = display.get_wm_info()['window'] flags, showCmd, ptMin, ptMax, rect = mcplatform.win32gui.GetWindowPlacement(hwndOwner) realW = rect[2] - rect[0] realH = rect[3] - rect[1] showCmd = config.settings.windowShowCmd.get() rect = (X, Y, X + realW, Y + realH) mcplatform.win32gui.SetWindowPlacement(hwndOwner, (0, showCmd, ptMin, ptMax, rect)) config.settings.setWindowPlacement.set(True) config.save() elif self.win: maximized = config.settings.windowMaximized.get() if DEBUG_WM: print "maximized", maximized if maximized: geom = self.win.get_root_rect() in_w, in_h = self.win.get_size() x, y = int((geom[2] - in_w) / 2), int((geom[3] - in_h) / 2) os.environ['SDL_VIDEO_CENTERED'] = '1' else: os.environ['SDL_VIDEO_CENTERED'] = '0' x, y = config.settings.windowX.get(), config.settings.windowY.get() wwh = self.win.get_size() if DEBUG_WM: print "x", x, "y", y print "wwh 2", wwh if splash: GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glWindowPos2d(0, 0) back = Surface(wwh) back.fill((0, 0, 0)) GL.glDrawPixels(wwh[0], wwh[1], GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, numpy.fromstring(image.tostring(back, 'RGBA'), dtype='uint8')) swh = splash.get_size() _x, _y = (wwh[0] / 2 - swh[0] / 2, wwh[1] / 2 - swh[1] / 2) w, h = swh data = image.tostring(splash, 'RGBA', 1) GL.glWindowPos2d(_x, _y) GL.glDrawPixels(w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, numpy.fromstring(data, dtype='uint8')) if splash: display.flip() if self.win: if not maximized: wwh = self.getWindowSize() if DEBUG_WM: print "wwh 3", wwh self.win.set_position((x, y), update=True) if DEBUG_WM: print "* self.win.get_position()", self.win.get_position() try: iconpath = os.path.join(directories.getDataDir(), 'favicon.png') iconfile = file(iconpath, 'rb') icon = pygame.image.load(iconfile, 'favicon.png') display.set_icon(icon) except Exception, e: logging.warning('Unable to set icon: {0!r}'.format(e))
wf = wave.open(WF_FILE_PATH, 'rb') p = PyAudio() # 设置声道频率并输出 stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) # 窗口、音频数据初始化 data = wf.readframes(CHUNK) init() counter = 0 display.set_caption('Music Visualizer') icon = image.load('./music_128px_1230638_easyicon.net.ico') display.set_icon(icon) screen = display.set_mode(WINDOW_SIZE, 0, 32) # 在界面中显示当前播放的音乐文件名 font_surface, font_rect = set_title(FILENAME) screen.blit(font_surface, font_rect, font_rect) display.update() np.seterr(divide='ignore', invalid='ignore') while data: # 监听pygame事件保证模块正常工作 event = py_event.poll() if event.type == QUIT: quit() break
def reset(cls): display.set_icon( image.load(os.path.join(os.getcwd(), 'data', 'favicon.png'))) display.set_caption("WorldBuilding") display.set_mode((ANCHO, ALTO), SCALED) event.clear()
from pygame.display import set_caption, set_icon, set_mode, get_surface, flip from pygame.event import get from constants import LEVEL_WIDTH, LEVEL_HEIGHT from GameStateMenu import GameStateMenu import Tkinter as Tk if __name__ == '__main__': ROOT = Tk.Tk() ROOT.withdraw() init() Assets.load_images() GAME_ICON = Assets.gameIcon set_caption('BlockBuster') set_icon(GAME_ICON) # WINDOW = set_mode((LEVEL_WIDTH, LEVEL_HEIGHT)) set_mode((LEVEL_WIDTH, LEVEL_HEIGHT)) SCREEN = get_surface() flip() CONTEXT = dict() GAMESTATE = GameStateMenu(CONTEXT, SCREEN) CONTEXT["gamestate"] = GAMESTATE # noinspection PyUnusedLocal def _update(_): """ Pump events to the current GameState and tell its objects to update :param _: unused dt provided by GameClock
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
def reset(self, splash=None, caption=("", "")): pygame.key.set_repeat(500, 100) try: display.gl_set_attribute(pygame.GL_SWAP_CONTROL, config.settings.vsync.get()) except Exception as e: logging.warning('Unable to set vertical sync: {0!r}'.format(e)) display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8) if DEBUG_WM: print "config.settings.windowMaximized.get()", config.settings.windowMaximized.get() wwh = self.getWindowSize() if DEBUG_WM: print "wwh 1", wwh d = display.set_mode(wwh, self.displayMode()) # Let initialize OpenGL stuff after the splash. GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glAlphaFunc(GL.GL_NOTEQUAL, 0) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) # textures are 256x256, so with this we can specify pixel coordinates # GL.glMatrixMode(GL.GL_TEXTURE) # GL.glScale(1 / 256., 1 / 256., 1 / 256.) display.set_caption(*caption) if mcplatform.WindowHandler: self.win = mcplatform.WindowHandler(mode=self.displayMode()) # The following Windows specific code won't be executed if we're using '--debug-wm' switch. if not USE_WM and sys.platform == 'win32' and config.settings.setWindowPlacement.get(): config.settings.setWindowPlacement.set(False) config.save() X, Y = config.settings.windowX.get(), config.settings.windowY.get() if X: hwndOwner = display.get_wm_info()['window'] flags, showCmd, ptMin, ptMax, rect = mcplatform.win32gui.GetWindowPlacement(hwndOwner) realW = rect[2] - rect[0] realH = rect[3] - rect[1] showCmd = config.settings.windowShowCmd.get() rect = (X, Y, X + realW, Y + realH) mcplatform.win32gui.SetWindowPlacement(hwndOwner, (0, showCmd, ptMin, ptMax, rect)) config.settings.setWindowPlacement.set(True) config.save() elif self.win: maximized = config.settings.windowMaximized.get() if DEBUG_WM: print "maximized", maximized if maximized: geom = self.win.get_root_rect() in_w, in_h = self.win.get_size() x, y = int((geom[2] - in_w) / 2), int((geom[3] - in_h) / 2) os.environ['SDL_VIDEO_CENTERED'] = '1' else: os.environ['SDL_VIDEO_CENTERED'] = '0' x, y = config.settings.windowX.get(), config.settings.windowY.get() wwh = self.win.get_size() if DEBUG_WM: print "x", x, "y", y print "wwh 2", wwh if splash: # Setup the OGL display GL.glLoadIdentity() GLU.gluOrtho2D(0, wwh[0], 0, wwh[1]) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_ACCUM_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT) swh = splash.get_size() _x, _y = (wwh[0] / 2 - swh[0] / 2, wwh[1] / 2 - swh[1] / 2) w, h = swh try: data = image.tostring(splash, 'RGBA_PREMULT', 1) except ValueError: data = image.tostring(splash, 'RGBA', 1) except ValueError: data = image.tostring(splash, 'RGB', 1) # Set the raster position GL.glRasterPos(_x, _y) GL.glDrawPixels(w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, numpy.fromstring(data, dtype='uint8')) if splash: display.flip() if self.win: if not maximized: wwh = self.getWindowSize() if DEBUG_WM: print "wwh 3", wwh self.win.set_position((x, y), update=True) if DEBUG_WM: print "* self.win.get_position()", self.win.get_position() try: iconpath = os.path.join(directories.getDataDir(), 'favicon.png') iconfile = file(iconpath, 'rb') icon = pygame.image.load(iconfile, 'favicon.png') display.set_icon(icon) except Exception as e: logging.warning('Unable to set icon: {0!r}'.format(e)) # Let initialize OpenGL stuff after the splash. # GL.glEnableClientState(GL.GL_VERTEX_ARRAY) # GL.glAlphaFunc(GL.GL_NOTEQUAL, 0) # GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) # textures are 256x256, so with this we can specify pixel coordinates GL.glMatrixMode(GL.GL_TEXTURE) GL.glScale(1 / 256., 1 / 256., 1 / 256.) self.display = d self.loadTextures()
def setup(self): pygame.init() self.database.connect() self.config.read() self.data = self.core.get_data self.speed = self.config.parse["settings"]["speed"] set_caption(self.config.getName + " " + self.config.getVersion) self.screen = set_mode(self.config.getRect.size) self.core.load_assets() if self.data["icon"]: self.logs.info("Mengatur icon") set_icon(self.data["icon"]) set_visible(True) self.clock = Clock() #=== Background game ===# self.BACKGROUND = self.data["backgrounds"][random.choice( [x for x in self.data["backgrounds"]][1:])] self.BACKGROUND = scale(self.BACKGROUND, self.config.getRect.size) #=== Settings tanah texture ===# self.tanah = self.data["textures"]["tanah0"] self.tanah = scale(self.tanah, (1000, self.tanah.get_height())) self.tanah_diff = self.tanah.get_width() - self.BACKGROUND.get_width() self.tanah_position = [0, self.config.getRect.height * 0.95] #=== Settings grass texture ===# self.grass = self.data["textures"]["grass0"] self.grass = scale(self.grass, (1000, 10)) self.grass_diff = self.grass.get_width() - self.BACKGROUND.get_width() self.grass_position = [10, self.config.getRect.height * 0.94] #=== Settings rumput texture ===# rumput_image_list = [] for x in self.data["textures"]: if "rumput" in x: rumput_image_list.append(x) self.rumputGroup = Group() for x in range(random.randint(2, 4)): image = self.data["textures"]["rumput0"] self.rumputGroup.add( Rumput(image, [ random.randint(self.config.getRect.width, 3000), self.config.getRect.height * 0.80 ])) #=== Settings keris image ===# self.kerisGroup = Group() for x in range(random.randint(1, 3)): keris = Keris(self.data["anim"]["keris"], [ random.randint(self.config.getRect.width, self.config.getRect.width * 2), 10 ]) keris.rect.bottom += random.randint( 10, self.config.getRect.height - 130) self.kerisGroup.add(keris) #=== Settings bambu image ===# self.bambuGroup = Group() for x in range(random.randint(1, 3)): bambu = Bambu(self.data["other"]["bambu"], [ random.randint(self.config.getRect.width, self.config.getRect.width * 2), 10 ]) bambu.rect.bottom += self.config.getRect.height * 0.78 self.bambuGroup.add(bambu) #=== Settings player image ===# self.player = Player(self.data["anim"]["player1"], [60, self.config.getRect.height - 40]) #=== Settings score ===# self.score = Score(self.data) #=== Health bar ===# self.health = Health(self.data)
def reset(self, splash=None, caption=("", "")): pygame.key.set_repeat(500, 100) try: display.gl_set_attribute(pygame.GL_SWAP_CONTROL, config.settings.vsync.get()) except Exception as e: logging.warning('Unable to set vertical sync: {0!r}'.format(e)) display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8) if DEBUG_WM: print "config.settings.windowMaximized.get()", config.settings.windowMaximized.get() wwh = self.getWindowSize() if DEBUG_WM: print "wwh 1", wwh d = display.set_mode(wwh, self.displayMode()) # Let initialize OpenGL stuff after the splash. GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glAlphaFunc(GL.GL_NOTEQUAL, 0) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) # textures are 256x256, so with this we can specify pixel coordinates # GL.glMatrixMode(GL.GL_TEXTURE) # GL.glScale(1 / 256., 1 / 256., 1 / 256.) display.set_caption(*caption) if mcplatform.WindowHandler: self.win = mcplatform.WindowHandler(mode=self.displayMode()) # The following Windows specific code won't be executed if we're using '--debug-wm' switch. if not USE_WM and sys.platform == 'win32' and config.settings.setWindowPlacement.get(): config.settings.setWindowPlacement.set(False) config.save() X, Y = config.settings.windowX.get(), config.settings.windowY.get() if X: hwndOwner = display.get_wm_info()['window'] flags, showCmd, ptMin, ptMax, rect = mcplatform.win32gui.GetWindowPlacement(hwndOwner) realW = rect[2] - rect[0] realH = rect[3] - rect[1] showCmd = config.settings.windowShowCmd.get() rect = (X, Y, X + realW, Y + realH) mcplatform.win32gui.SetWindowPlacement(hwndOwner, (0, showCmd, ptMin, ptMax, rect)) config.settings.setWindowPlacement.set(True) config.save() elif self.win: maximized = config.settings.windowMaximized.get() if DEBUG_WM: print "maximized", maximized if maximized: geom = self.win.get_root_rect() in_w, in_h = self.win.get_size() x, y = int((geom[2] - in_w) / 2), int((geom[3] - in_h) / 2) os.environ['SDL_VIDEO_CENTERED'] = '1' else: os.environ['SDL_VIDEO_CENTERED'] = '0' x, y = config.settings.windowX.get(), config.settings.windowY.get() wwh = self.win.get_size() if DEBUG_WM: print "x", x, "y", y print "wwh 2", wwh if splash: # Setup the OGL display GL.glLoadIdentity() GLU.gluOrtho2D(0, wwh[0], 0, wwh[1]) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_ACCUM_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT) swh = splash.get_size() _x, _y = (wwh[0] / 2 - swh[0] / 2, wwh[1] / 2 - swh[1] / 2) w, h = swh try: data = image.tostring(splash, 'RGBA_PREMULT', 1) except ValueError: data = image.tostring(splash, 'RGBA', 1) except ValueError: data = image.tostring(splash, 'RGB', 1) # Set the raster position GL.glRasterPos(_x, _y) GL.glDrawPixels(w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, numpy.fromstring(data, dtype='uint8')) if splash: display.flip() if self.win: if not maximized: wwh = self.getWindowSize() if DEBUG_WM: print "wwh 3", wwh self.win.set_position((x, y), update=True) if DEBUG_WM: print "* self.win.get_position()", self.win.get_position() try: #iconpath = os.path.join(directories.getDataDir(), 'favicon.png') iconpath = directories.getDataFile('favicon.png') iconfile = file(iconpath, 'rb') icon = pygame.image.load(iconfile, 'favicon.png') display.set_icon(icon) except Exception as e: logging.warning('Unable to set icon: {0!r}'.format(e)) # Let initialize OpenGL stuff after the splash. # GL.glEnableClientState(GL.GL_VERTEX_ARRAY) # GL.glAlphaFunc(GL.GL_NOTEQUAL, 0) # GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) # textures are 256x256, so with this we can specify pixel coordinates GL.glMatrixMode(GL.GL_TEXTURE) GL.glScale(1 / 256., 1 / 256., 1 / 256.) self.display = d self.loadTextures()
def __init__(self, width, height, timings, time_to_show, startCirclePos, startPlayer, timeStart=0): # self.background_image = pygame.image.load(back_image_filename) #self.frame_rate = frame_rate self.game_over = False self.timeStart = timeStart pygame.mixer.pre_init(44100, 16, 2, 4096) pygame.init() pygame.font.init() self.myfont = pygame.font.SysFont('serif', 30) self.res = (width, height) self.safeTime = 500 self.surface = display.set_mode((width, height)) display.set_caption("Destroy the flower!") ##########ICON########## ico = "flower.png" if not os.path.exists(ico): ico = "main/flower.png" gameIcon = pygame.image.load(ico) display.set_icon(gameIcon) ############## self.clock = pygame.time.Clock() self.keydown_handlers = defaultdict(list) self.keyup_handlers = defaultdict(list) self.mouse_handlers = [] self.curTime = 0 self.showTime = time_to_show self.ct = datetime.datetime.now # ().time self.skip = 0 self.timings = timings self.half = startCirclePos self.halfINT = (int(startCirclePos[0]), int(startCirclePos[1])) self.isStart = False temp = (startPlayer[0] - startCirclePos[0], startPlayer[1] - startCirclePos[1]) self.startPlayer = startPlayer self.distantion = math.sqrt(temp[0]*temp[0] + temp[1]*temp[1]) # S1 # time = self.showTime# T = t1+t2 self.speed = (self.distantion / (self.showTime)) # u1 = s1/t1 self.size = int(self.safeTime * self.speed/2.0) # r radius # self.speed += self.size/self.showTime/2 self.isPause = False self.pauseDate = None self.prerar = 255*2/self.safeTime self.closeZone = int(self.safeTime/2) self.timeOffset = 0 self.fps_pos = width-100 self.lCircle = int(self.size/2.5) #(255, 233, 38), self.colors = [ (0, 0, 0), (196, 0, 100), (10, 50, 10), (255, 0, 0), (255, 165, 0), (255, 128, 128), (0, 0, 255), (255, 0, 255), (163, 54, 81), (77, 190, 111), (182, 33, 196), (145, 196, 5), (159, 12, 196), (14, 48, 240), (22, 150, 11) ] self.clrPointer = 0 #self.hidePos = -self.closeZone #self.hidePos = 0 self.hidePos = -self.lCircle pass
def set_icon(self): if self.get_configuration().has_option("display", "icon-path"): path = self.get_resource("display", "icon-path") display.set_icon(image.load(path).convert_alpha())
from game import Player, Map from constantes import ICONE, TITLE_WINDOW, SCREEN_SIZE, HOME,\ Grey_GROUND, window, BACKGROUND, WELCOME, FILE, WIN, GAMEOVER from pygame.locals import K_ESCAPE, K_RETURN, K_RIGHT, K_LEFT, K_UP, K_DOWN from pygame import transform, display, event, font, QUIT, KEYDOWN, time display.set_icon(ICONE) display.set_caption(TITLE_WINDOW) display.set_mode(SCREEN_SIZE) SCORE = 0 MAIN_LOOP = True while MAIN_LOOP: window.blit(Grey_GROUND, (0, 0)) window.blit(transform.scale(HOME, SCREEN_SIZE), (0, 0)) FONT = font.Font(None, 30) TEXT_SCORE = FONT.render(f"SCORE is {SCORE}\n Press Enter To Play", True, (200, 200, 200)) window.blit(TEXT_SCORE, (15, 370)) display.flip() HOME_LOOP = True while HOME_LOOP: for e in event.get(): if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE): MAIN_LOOP = False HOME_LOOP = False GAME_LOOP = False