def findSolution(state, algorithm): global max_depth global queue global visited global run2 if args.v: # inits game pygame.get_init() # sets window caption pygame.display.set_caption("Box World 2") while run2: if algorithm == "idfs" and len(queue) == 0: queue = [State(Level(l), algorithm)] visited = [] max_depth = max_depth + 10 print("\n Retrying idfs with new depth limit: ", max_depth, "\n") if algorithm == "greedy" or algorithm == "astar": state = queue.get() else: state = queue[0] # add node to already visited if algorithm == "greedy" or algorithm == "astar": visited.append(state) else: visited.append(queue[0]) if args.v: # draws game state drawGameState(state.level) # Update the full Surface to the screen pygame.display.flip() screen.fill((0, 0, 0)) # calculates next move nextMove(algorithm, state) # remove the first queue element if algorithm != "greedy" and algorithm != "astar": queue.remove(queue[0]) # break condition if not run: print(solution.moves) break
def __init__(self, size=(0, 0), flags=0, fps=60, bg_color=(0, 0, 0), bg_music=None): if not pygame.get_init(): pygame.mixer.pre_init(44100, -16, 2, 512) status = pygame.init() if status[1] > 0: sys.exit(84) pygame.key.set_repeat(25, 100) Window.load_sound_volume_from_save() self.window = pygame.display.get_surface() self.main_window = False if self.window is None: if size[0] <= 0 or size[1] <= 0: video_info = pygame.display.Info() size = video_info.current_w, video_info.current_h self.window = pygame.display.set_mode(tuple(size), flags) self.main_window = True self.window_rect = self.window.get_rect() self.main_clock = pygame.time.Clock() self.loop = False self.objects = list() self.event_handler_dict = dict() self.key_handler_dict = dict() self.mouse_handler_list = list() self.fps = fps self.bg_color = bg_color self.time_after = -1 self.time_start = 0 self.callback_after = None Window.all_opened.append(self) self.bg_music = bg_music self.no_object = True
def get_event(self, event_list): """[this funktion will check and queue user input, also will register quits] Args: event_list (list): [ongoinm events, if none will get events from pygame video system] Returns: [Bool]: [Will return true if running, and false if there has been a quit input] """ if pygame.get_init(): event_list = pygame.event.get() running = True for event in event_list: if event.type == pygame.KEYDOWN: keypress = None if event.key == pygame.K_LEFT: keypress = "L" elif event.key == pygame.K_RIGHT: keypress = "R" elif event.key == pygame.K_UP: keypress = "U" elif event.key == pygame.K_DOWN: keypress = "D" elif event.key == pygame.K_ESCAPE: running = False if keypress and keypress != self._previous_command: self._events.append(keypress) self._previous_command = keypress if event.type == pygame.QUIT: running = False return running
def setup(self): # setup parameters self.path = os.path.dirname(os.path.abspath(__file__)) + '/movies/' self.size = (self.monitor['resolution_x'], self.monitor['resolution_y'] ) # window size self.color = [127, 127, 127] # default background color self.phd_size = (50, 50) # default photodiode signal size in pixels # setup pygame if not pygame.get_init(): pygame.init() self.screen = pygame.display.set_mode(self.size) self.unshow() pygame.mouse.set_visible(0) pygame.display.toggle_fullscreen() # setup movies from omxplayer import OMXPlayer self.player = OMXPlayer # store local copy of files if not os.path.isdir(self.path): # create path if necessary os.makedirs(self.path) for cond in self.conditions: file = self.get_clip_info(cond, 'Movie.Clip', 'file_name') filename = self.path + file[0] if not os.path.isfile(filename): print('Saving %s ...' % filename) clip = self.get_clip_info(cond, 'Movie.Clip', 'clip') clip[0].tofile(filename) # initialize player self.vid = self.player(filename, args=['--aspect-mode', 'stretch', '--no-osd'], dbus_name='org.mpris.MediaPlayer2.omxplayer1') self.vid.stop()
def setup(self): # setup parameters self.path = 'stimuli/' # default path to copy local stimuli self.size = (800, 480) # window size self.color = [127, 127, 127] # default background color self.loc = (0, 0) # default starting location of stimulus surface self.fps = 30 # default presentation framerate self.phd_size = (50, 50) # default photodiode signal size in pixels self.set_intensity(self.params['intensity']) # setup pygame if not pygame.get_init(): pygame.init() self.screen = pygame.display.set_mode(self.size) self.unshow() pygame.mouse.set_visible(0) pygame.display.toggle_fullscreen() # setup movies from omxplayer import OMXPlayer self.player = OMXPlayer # store local copy of files if not os.path.isdir(self.path): # create path if necessary os.makedirs(self.path) for cond in self.conditions: clip_info = self.get_clip_info(cond) filename = self.path + clip_info['file_name'] if not os.path.isfile(filename): print('Saving %s ...' % filename) clip_info['clip'].tofile(filename) # initialize player self.vid = self.player(filename, args=['--aspect-mode', 'stretch', '--no-osd'], dbus_name='org.mpris.MediaPlayer2.omxplayer1') self.vid.stop()
def __init__(self, **kwargs): # define interface parameters self.screen_size = kwargs.get('screen_size', (800, 480)) self.fill_color = kwargs.get('fill_color', (0, 0, 0)) self.font_color = kwargs.get('font_color', (255, 255, 255)) self.font_size = kwargs.get('font_size', 20) self.font = kwargs.get('font', "freesansbold.ttf") cmd = 'echo %d > /sys/class/backlight/rpi_backlight/brightness' % 64 os.system(cmd) # define interface variables self.screen = None self.ts = Touchscreen() if not pygame.get_init(): pygame.init() pygame.mouse.set_visible(0) self.screen = pygame.display.set_mode(self.screen_size) for touch in self.ts.touches: touch.on_press = self._touch_handler touch.on_release = self._touch_handler self.ts.run() self.screen.fill(self.fill_color) self.buttons = [] self.texts = [] self.button = [] self.numpad = ''
def setUp(cls): # This makes sure pygame is always initialized before each tests (in # case a tests calls pygame.quit()). if not pygame.get_init(): pygame.init() if not pygame.display.get_init(): pygame.display.init()
def render(self, mode="graphic"): if mode == "graphic": # Check if rendering was already initialized if not pygame.get_init(): pygame.init() self.background = pygame.display.set_mode( (self.WINDOW_WIDTH, self.WINDOW_HEIGHT)) # avoid 'not-responding' error pygame.event.get() # Pygame has coordinates starting on top left corner of the screen # with positive directions going right (x) and down (y) x = self.CENTER[0] - np.sin(self._angle) * self.POLE_RENDER_LENGTH y = self.CENTER[1] - np.cos(self._angle) * self.POLE_RENDER_LENGTH # Draw blank page self.background.fill(self.WHITE) # Draw pendulum pygame.draw.lines(self.background, self.BLACK, False, [self.CENTER, (x, y)], 2) pygame.draw.circle(self.background, self.BLACK, (x, y), self.RADIUS) pygame.draw.circle(self.background, self.RED, (x, y), self.RADIUS - 2) pygame.draw.circle(self.background, self.BLACK, (self.CENTER[0], self.CENTER[1]), 5) pygame.display.update() else: print(f"ang={self._angle:.2f}, vel={self._velocity:.2f}")
def main(): pg.init() if not pg.get_init(): return pgbase.set_logo() pgbase.set_game_window_title("Futbol") surface = pgbase.setup_display_surface(500, 1000) players_in_team = 7 # F-M-D formation = ["3-2-1", "1-3-2", "2-2-2"] team_1 = Team(5, formation[0], 'red') team_2 = Team(5, formation[2], 'blue') team1_y = 100 for player in team_1: player.draw(surface, center=Position(100, team1_y)) team1_y += 50 team2_y = 100 for player in team_2: player.draw(surface, center=Position(800, team2_y)) team2_y += 50 game_running = True while game_running: pg.display.update() for event in pg.event.get(): if event.type == pg.QUIT: game_running = False return
def init(): if pygame.get_init(): print("\n\nnQUIT PYGAME\n\n") pygame.display.quit() init_pygame() init_display() play()
def _on_quit(self): """ Aufräumarbeiten bei Programmende. """ if pygame.get_init(): event = pygame.event.Event(pygame.QUIT) pygame.event.post(event)
def run(): ''' Initialize all pygame imported modules and run main loop ''' pygame.init() if pygame.get_init(): main_loop()
def refresh(self): """Keep the screen updated""" if not pg.get_init(): pg.init() self.screen = pg.display.set_mode(self.settings.size) for component in self.components: component.init(self.screen) pg.display.set_caption(self.settings.name) self.clean() self.initiated = True self.stop = False while not self.stop: events = [] for event in pg.event.get(): events.append(event) if event.type == pg.QUIT: self.stop = True self.clean() for component in self.components: component.update(self.screen, events=events) pg.display.flip() # Update the full display Surface to the screen self.clock.tick(self.settings.fps) self.ticks += 1 self.screen = None pg.quit() self.initiated = False
def __new__(cls): if not ResourceManager.__instance: if not pygame.get_init(): pygame.init() ResourceManager.__instance = super(ResourceManager, cls).__new__(cls) return ResourceManager.__instance
def test(): if not pygame.get_init(): pygame.init() screen = pygame.display.set_mode(SCREEN, 0, 32) while True: fu = load(screen) print(fu)
def __init__(self, game_name, icon=None): self.game_name = game_name self.icon = icon self.timer = pygame.time.Clock() self.is_running = True # Game variables self.flying = False self.game_over = False self.score = 0 self.pass_pipe = False # Sound pygame.mixer.pre_init(buffer=256) pygame.mixer.init() self.theme = pygame.mixer.music.load(path_themesong) self.flap_sound = pygame.mixer.Sound(path_wingsound) self.hit_sound = pygame.mixer.Sound(path_hitsound) self.die_sound = pygame.mixer.Sound(path_diesound) self.hit_played = False self.score_sound = pygame.mixer.Sound(path_scoresound) # PyGame Initialization pygame.init() while not pygame.get_init(): print("PyGame Initialization Failed.") self.game_window = pygame.display.set_mode((display[0], display[1]), DOUBLEBUF | OPENGL) pygame.display.set_caption(self.game_name) glViewport(0, 0, display[0], display[1]) # pygame.display.set_icon(pygame.image.load(self.icon)) glMatrixMode(GL_MODELVIEW) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glClearColor(1, 1, 1, 1) shader.compile_shader()
def main(): # init the python game module. num_of_ok_init, num_of_bad_init = pygame.init() logging.info( "Number of successful inits {}. Number of bad inits {}".format( num_of_ok_init, num_of_bad_init)) # check if the game is correctly init. if pygame.get_init() == False: return logging.info("Game initialized. Starting..") # Set a logo. Recommended file formats for images are .jpeg and .png game_logo_path = os.path.join(os.path.dirname(__file__), "..", "resources/my_game_icon.jpeg") logging.debug("Icon resource path - {}".format(game_logo_path)) game_logo = pygame.image.load(game_logo_path) pygame.display.set_icon(game_logo) logging.debug("Set game window logo..") # Set a window title pygame.display.set_caption("MyGame") # set up the window of the game screen = pygame.display.set_mode(size=(200, 200)) game_running = True while game_running: for event in pygame.event.get(): if event.type == pygame.QUIT: game_running = False
def main(): numpass, numfail = pg.init() print(f'pass:{numpass}, fail:{numfail}') inited = pg.get_init() print(f'Inited: {inited}') try: raise pg.error('Custom Error') except RuntimeError as re: print(f'Exception: {re}') pg.set_error('Set Error') err = pg.get_error() print(f'Error: {err}') major, minor, path = pg.get_sdl_version() print(f'SDL: {major}.{minor}.{path}') pg.register_quit(quit) unencoded = '你好' encoded = pg.encode_string(unencoded, encoding='utf-8') print(f'Encoded: {encoded}, Original: {unencoded}') encoded_path = pg.encode_file_path(os.path.join(__file__)) print(f'Encoded Path: {encoded_path}') print(f'{pg.version.PygameVersion(1, 2, 3)}, {pg.vernum}')
def __init_pygame(self, size: Tuple[int, int], flags: int, nb_joystick: int, loading, config: bool) -> None: if not pygame.get_init(): pygame.mixer.pre_init(Window.MIXER_FREQUENCY, Window.MIXER_SIZE, Window.MIXER_CHANNELS, Window.MIXER_BUFFER) status = pygame.init() if status[1] > 0: print( "Error on pygame initialization ({} modules failed to load)" .format(status[1]), file=sys.stderr) sys.exit(1) Window.__use_config = bool(config) Window.load_config() Window.__joystick.set(nb_joystick) Window.bind_event_all_window(pygame.JOYDEVICEADDED, Window.__joystick.event_connect) Window.bind_event_all_window(pygame.CONTROLLERDEVICEADDED, Window.__joystick.event_connect) Window.bind_event_all_window(pygame.JOYDEVICEREMOVED, Window.__joystick.event_disconnect) Window.bind_event_all_window(pygame.CONTROLLERDEVICEREMOVED, Window.__joystick.event_disconnect) if size[0] <= 0 or size[1] <= 0: video_info = pygame.display.Info() size = video_info.current_w, video_info.current_h pygame.display.set_mode(tuple(size), flags) self.__load_resources(loading)
def __init__(self): if not pygame.get_init(): pygame.init() self.screen = pygame.display.set_mode(flags=pygame.FULLSCREEN | pygame.DOUBLEBUF | pygame.HWSURFACE) screen_rect = self.screen.get_rect() self.screen_size = screen_rect.w, screen_rect.h self.font_score = resource_manager.get_font(12) self.font_game_over = resource_manager.get_font(36) self.font_instructions = resource_manager.get_font(12) self.instructions = self.font_instructions.render("Arrow keys to move, space bar to fire, and ESC to exit", False, white) self.instructions_rect = self.instructions.get_rect() self.instructions_rect.bottomleft = screen_rect.bottomleft self.move_map = self.get_move_map() self.clock = pygame.time.Clock() self.delta_time = 0 self.actors = {objects.asteroid.Asteroid: [], objects.ship.Ship: [], objects.laser.Laser: [], objects.particle.Particle: []} self.ship = None self.lives = lives self.level = 0 self.score = 0 self.playing = True self.spawn_ship() self.advance_level()
def exit(self): try: self.ts.stop() finally: if pygame.get_init(): pygame.mouse.set_visible(1) pygame.quit()
def pub_commands(): ## Read inputs from Dualshock Controller & publish to remote_commands message pub = rospy.Publisher('remote_commands', DualshockInputs, queue_size=10) rospy.init_node('remote_commands', anonymous=True) ## Determine if pygame is already initialized if not pygame.get_init(): pygame.init() controller = pygame.joystick.Joystick(0) controller.init() ## Initialize all inputs to 0 inputs = DualshockInputs() rate = rospy.Rate(10) while not rospy.is_shutdown(): ## Update joystick and button values for event in pygame.event.get(): if event.type == pygame.JOYAXISMOTION: for axis in AXIS_NAMES.keys(): if INVERTED_Y_AXIS and axis in [1, 4]: setattr(inputs, AXIS_NAMES[axis], -1 * controller.get_axis(axis)) else: setattr(inputs, AXIS_NAMES[axis], controller.get_axis(axis)) pub.publish(inputs) if event.type == pygame.JOYBUTTONDOWN: setattr(inputs, BUTTON_NAMES[event.button], True) pub.publish(inputs) if event.type == pygame.JOYBUTTONUP: setattr(inputs, BUTTON_NAMES[event.button], False) rate.sleep()
def get_piece(self): # Pygame precisa estar inicializado if pygame.get_init(): return (self.image, self.rect) else: return (None, None)
def __init__(self): if not pygame.get_init(): pygame.init() self.playing = True self.clock = pygame.time.Clock() self.size = 400, 400 self.screen = pygame.display.set_mode(self.size) self.font = resource_manager.get_font(24) self.text_start_game = self.font.render("Start Game", False, white) # todo: one day. # self.text_high_scores = self.font.render("View High Scores", False, white) self.text_quit = self.font.render("Quit", False, white) self.menu_items = [self.text_start_game, self.text_quit] self.menu_options_map = self.get_options_map() self.menu_item_rect_map = self.get_menu_item_rect_map(self.menu_items) self.key_map = self.get_key_map() self.selected_index = 0 self.tick_rect = tick.get_rect() self.tick_blink_frequency = 300 self.tick_blink_time = -self.tick_blink_frequency self.move_tick()
def events_handler(mouse=None): """ This function handle all events in pygame :param mouse: current mouse position :return: those updated mouse and mouse_on_click """ mouse_on_click = [[0, 0], 0] if mouse is None: mouse = [0, 0] keys = [] if pg.get_init(): for event in pg.event.get(): if event.type == pg.QUIT: raise SystemExit if event.type == pg.MOUSEMOTION: mouse = event.pos if event.type == pg.MOUSEBUTTONUP: mouse_on_click = [event.pos, event.button] if event.type == pg.KEYUP: if chr(event.key) == '\x1b': raise SystemExit keys.append(chr(event.key)) variables_dict = { 'mouse': mouse, 'mouse_on_click': mouse_on_click, 'keys': keys } return variables_dict
def load_png(name, rect=None): """Loads image Parameters: name: str, path name of image in image_folder Keywords: rect: pygame.rect object with size attribute for resizing Returns: image: image object rect: if rect not given as keyword """ fullname = os.path.join(IMAGE_FOLDER, name) if pg.get_init(): try: image = pg.image.load(fullname) if image.get_alpha() is None: image = image.convert() else: image = image.convert_alpha() if rect: image = pg.transform.scale(image, rect.size) return image except pg.error as message: print('Cannot load image:', fullname) raise SystemExit(message) else: return image, image.get_rect()
def drawBtn(screen, mouseOnButton=-1): if not pygame.get_init(): pygame.init() btnSurface = screen.convert_alpha() # 创建一个透明图层 font = pygame.font.Font(FONT_FILE, BTN_FONT_SIZE) # 读取字体 font.set_bold(True) for btn in hotArea: # 当前按钮的左上角坐标 # 绘制按钮 if mouseOnButton == btn[1]: pygame.draw.rect(btnSurface, BTN_ON_COLOR, btn[2], 0) else: pygame.draw.rect(btnSurface, BTN_COLOR, btn[2], 0) # 绘制按钮文字 fntSurface = font.render(btn[0], False, BTN_TXT_COLOR) # 渲染文字 fontRect = fntSurface.get_rect() # 取得渲染后画板的尺寸 # 将文字图层合并到按钮图层合适的位置,文字位置计算基于按钮的左上角坐标和按钮宽度与高度,这样可以适应不同布局的按钮排列 btnSurface.blit(fntSurface, (btn[2][0] + (btn[2][2] - fontRect[2]) / 2, btn[2][1] + (btn[2][3] - fontRect[3]) / 2 + 2)) # 实际应用将文字向下修正两个像素,否则显得文字在按钮上偏上 return btnSurface
def init(screen, config): # 初始化界面 if not pygame.get_init(): pygame.init() # 绘制背景 global background background = pygame.image.load(new_img_filename) background = pygame.transform.scale(background, SCREEN) screen.blit(background, (0, 0)) # 构造按钮组 buttonList = [] if config["music_on"]: buttonList.append(["音乐:开", 7]) else: buttonList.append(["音乐:关", 7]) if config["show_order"]: buttonList.append(["落子顺序:显示", 6]) else: buttonList.append(["落子顺序:隐藏", 6]) buttonList.append(["返回", 5]) # 绘制按钮 button.init(buttonList) surf = button.drawBtn(screen) # 合并图层 screen.blit(surf, (0, 0)) # 展示 pygame.display.update()
def exibir_resultado(self, resultado): if resultado == -1: msg = ("Você Perdeu! Todas as suas vidas acabaram!", True, self.fonte.cor) else: msg = ("Parabéns, Você ganhou!", True, self.fonte.cor) msg_palavra = (f'A palavra era: {self.forca.palavra}', True, self.fonte.cor) altu = self.tela.altura // 3 larg = self.tela.largura // 2 - (len(msg[0]) * 10) self.limpar_tela() self.tela.exibir_mensagem(self.fonte.fonte_pygame.render(*msg), (larg, altu)) self.tela.exibir_mensagem(self.fonte.fonte_pygame.render(*msg_palavra), (larg, altu * 2)) self.tela.atualizar_tela() if pygame.get_init() is True: exe = True while exe: for evento in pygame.event.get(): if evento.type == pygame.QUIT: self.executar = False exe = False
def onUserDisplay(self, screen): if pygame.get_init(): pygame.draw.rect(screen, (50, 50, 50), [self.posX, self.posY, self.width, self.height], 0) pygame.draw.rect(screen, (0, 0, 0), [ self.posX + self.height * 0.09, self.posY + self.height * 0.09, self.width - self.height * 0.16, self.height - self.height * 0.16 ], 0) color = (0, 255, 0) if self.rectViewText / self.charLenght != len( self.textString) else (255, 150, 0) renderedText = self.font.render( self.textString[:self.letterPos] + ("|" if self.blinkCursor >= 15 else " ") + self.textString[self.letterPos:], True, color) screen.blit(renderedText, (self.posX + self.height * 0.09, self.posY + self.height * 0.09)) renderedText = self.font.render( self.textLabel + self.editableLabel, True, (255, 255, 255)) screen.blit(renderedText, (self.posX - renderedText.get_width() * 0.5 + self.width * 0.5, self.posY - self.height * 0.75)) if self.blockingKeyboardEvent: self.blinkCursor = (self.blinkCursor + 1) % 31 else: self.blinkCursor = 0