def show_list_nick(): # Функция смены ника global index_nick # Получаем фон img_nick = load_image( path.join('static', 'img', 'background', 'background_nick.jpg'), True, DISPLAYMODE) window.blit(img_nick, (0, 0)) # Устанавливаю фон list_nick = [] for j in range(NUMBER_NIK): # Загружаем картинки ников для выбора path_image = os.path.join('static', 'img', 'spaceship', str(j + 1), "spaceship_3.png") list_nick.append( load_image(path_image, False, (LENGTH_SPACESHIP, WIDTH_SPACESHIP))) image_nick = list_nick[j] window.blit(image_nick, (150 * (j + 1), 150)) pygame.display.update() # Пользователь не начнет игру, пока не нажмет на BACK # Но пользователь может выйти из игры # Может выбрать ник нажав на цифру порядкового номера ника while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: # Клавиша esc вызывает выход из игры exit_game() if event.key == pygame.K_BACKSPACE: return key_pressed = pygame.key.get_pressed() if key_pressed[pygame.K_1]: index_nick = 1 # Устанавливаю новый ник return update_player(index_nick) # Получаю изменения if key_pressed[pygame.K_2]: index_nick = 2 # Устанавливаю новый ник return update_player(index_nick) # Получаю изменения
def show_list_nick(): global index_nick img_nick = load_image( path.join('data', 'images', 'background', 'background_nick.jpg'), True, DISPLAYMODE) window.blit(img_nick, (0, 0)) # Изображение для покрытия фона list_nick = [] for j in range(NUMBER_NIK): # Загружаем картинки path_image = os.path.join('data', 'images', 'spaceship', str(j + 1), "spaceship_3.png") list_nick.append( load_image(path_image, False, (LENGTH_SPACESHIP, WIDTH_SPACESHIP))) image_nick = list_nick[j] window.blit(image_nick, (150 * (j + 1), 150)) pygame.display.update() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: # Клавиша esc вызывает выход из игры exit_game() if event.key == pygame.K_BACKSPACE: return key_pressed = pygame.key.get_pressed() if key_pressed[pygame.K_1]: index_nick = 1 return update_player(index_nick) if key_pressed[pygame.K_2]: index_nick = 2 return update_player(index_nick)
def __init__(self, lvl): pygame.sprite.Sprite.__init__(self) self.list_enemy_img = [] # Создаем пустой список для картинок врага # Индекс текущего изображения врага и начальная скорость смены изображения self.index, self.speed_image = -1, 0 for i in range(COUNT_ENEMY): # Загружаем картинки path_img = os.path.join('static', 'img', f'level_{lvl}', 'new_enemy', "enemy_" + str(i + 1) + '.png') if lvl in [1, 5, 6, 8]: # На 1, 5, 6, 8 уровне у нас враги человечки, для них размеры другие if i < 10: # До 10 изображения человечик шагает, следвательно размер изображения меньше self.list_enemy_img.append(load_image(path_img, False, (WIDTH_ENEMY, LENGTH_ENEMY))) else: # После 10 изображения человечик достает оружие, следовательно размер увеличивается self.list_enemy_img.append(load_image(path_img, False, (WIDTH_ENEMY_SHOOTING, LENGTH_ENEMY_SHOOTING))) else: # Для уровней 2, 3, 4, 7, 9 врагом является или танк, или корабль. # Их размер идентичен рпзмеру стреляющего человечка, поэтому мы используем размеры стреляющего человечка self.list_enemy_img.append(load_image(path_img, False, (WIDTH_ENEMY_SHOOTING, LENGTH_ENEMY_SHOOTING))) self.image = self.list_enemy_img[self.index] # Устанавливаю старовое изображение # Получаю размеры изображения, квадрат self.rect = self.image.get_rect() # Стартовое расположение врага на экране self.rect.center = (WINDOW_WIDTH - WIDTH_ENEMY, random.randint(LENGTH_ENEMY, WINDOW_HEIGHT - LENGTH_ENEMY - 100)) self.x_speed = 1 # Скорость врага по x (по y он не будет двигаться) self.lvl = lvl # Передаем lvl в update
def show_game_result(points): # Функция отображения результатов уровня global destroyed_enemy_counter, game_challenge, lvl, count_laser, index_nick, score_top # Если мы выполнили норму уровня по количеству убитых дроидов, то мы выйграли if destroyed_enemy_counter >= game_challenge: sound = game_won_sound # Музыка для победы img = load_image( path.join('static', 'img', 'background', 'game_won.jpg'), True, DISPLAYMODE) # Получаем фон lvl += 1 # Увеличиваем уровень game_challenge += 5 # Увеличиваем задачу на следующий уровень else: sound = game_over_sound # Музыка для проигрыша img = load_image( path.join('static', 'img', 'background', 'game_lost.jpg'), True, DISPLAYMODE) # Получаем фон lvl = 1 # Обнуляем уровень до 1 game_challenge = 3 # Устонавливаем задачу для 1 уровня destroyed_enemy_counter = 0 # Обнуляем количество убитых на текущем уровне new_data(lvl, game_challenge, index_nick, score_top, destroyed_enemy_counter) # Вносим изменения в базу данных window.blit(img, (0, 0)) # Устанавливаю новый фон # Выводим результат игрока на экран draw_text(str(points), font_2, window, (WINDOW_WIDTH / 2) - 20, (WINDOW_HEIGHT / 2) - 20) pygame.display.update() music_channel.play(sound, loops=0, maxtime=0, fade_ms=0) # Включаем музыку
def __init__(self, surface, pos_x, pos_y, height, width, color_btn=(0, 0, 0), text='None', color_text=(255, 255, 255), path_font='None', size_font=30): pygame.sprite.Sprite.__init__(self) self.surface = surface self.pos_x = pos_x self.pos_y = pos_y self.__dict_select_btn = { 'up': load_image(path_button_up), 'down': load_image(path_button_down) } self.image = self.__dict_select_btn['up'] self.height = height self.width = width self.rect = pygame.Rect(pos_x, pos_y, width, height) self.color_btn = color_btn self.text = text self.color_text = color_text self.path_font = path_font self.size_font = size_font self.input_btn = False
def __init__(self): pygame.sprite.Sprite.__init__(self) # Скорость по оси X self.__speed_player_x = 5 # Скорость по оси Y self.__speed_player_y = 2 # Скорость движения игрока self.speed_player = 5 # Словарь с двумя состояниями игрока self.dict_right_left = { 'right': load_image(path_player_right), 'left': load_image(path_player_left) } # Загрузка изображения игрока self.image = self.dict_right_left['right'] # Блокировка вправо self.lock_right = False # Блокировка влево self.lock_left = False self.rect = self.image.get_rect() # В какую сторону двигается персонаж self.right_moving = False self.left_moving = False # Находится ли игрока на земле или нет self.onGround = False # Поражение self.game_over = False
def show_game_result(points): global destroyed_enemy_counter, game_challenge, lvl, count_laser, index_nick, score_top if destroyed_enemy_counter >= game_challenge: sound = game_won_sound img = load_image( path.join('data', 'images', 'background', 'game_won.jpg'), True, DISPLAYMODE) lvl += 1 game_challenge += 5 else: sound = game_over_sound img = load_image( path.join('data', 'images', 'background', 'game_lost.jpg'), True, DISPLAYMODE) lvl = 1 game_challenge = 3 destroyed_enemy_counter = 0 new_data(lvl, game_challenge, index_nick, score_top, destroyed_enemy_counter) window.blit(img, (0, 0)) pygame.display.update() draw_text(str(points), font_2, window, (WINDOW_WIDTH / 2) - 20, (WINDOW_HEIGHT / 2) - 20) pygame.display.update() music_channel.play(sound, loops=0, maxtime=0, fade_ms=0)
def load_profile_sheet(): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"] # The ID and range of a sample spreadsheet. # https://docs.google.com/spreadsheets/d/1BXJIRv7EUZGb2EgSIueUz7Cv2fFjvdmRGoUxPrt8-Jc/edit?usp=sharing SAMPLE_SPREADSHEET_ID = '1BXJIRv7EUZGb2EgSIueUz7Cv2fFjvdmRGoUxPrt8-Jc' SAMPLE_RANGE_NAME = 'A:R' creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('sheets', 'v4', credentials=creds) # Call the Sheets API sheet = service.spreadsheets() result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME).execute() values = result.get('values', []) if not values: print('No data found.') else: df = pd.DataFrame(values[1:], columns=values[0]) tsl = list(df['Timestamp']) nameL = list(df["Name"]) imgL = list(df['Image']) i = 0 while i < len(imgL): imgL[i] = imgL[i][imgL[i].find("?id=")+4:] i+=1 i = 0 while i < len(tsl): load_image(imgL[i], nameL[i], tsl[i]) i+=1 return df
def main(imgs): for i in imgs: img.load_image(i + ext) pixel_left = img.find_pixel_left(img.width, img.height) pixel_right = img.find_pixel_right(pixel_left) x.append(img.count_pixel([pixel_left[0], pixel_right])) pixels.append([pixel_left, [pixel_right, pixel_left[1]]]) img.red_mark(pixel_left, pixel_right, i, ext) print_result()
def main(): parser = argparse.ArgumentParser() parser.add_argument('timestamps_path', type=str, help='...') args = parser.parse_args() timestamps_path = args.timestamps_path if not os.path.isfile(timestamps_path): timestamps_path = os.path.join(args.dir, os.pardir, os.pardir, camera + '.timestamps') if not os.path.isfile(timestamps_path): raise IOError("Could not find timestamps file") timestamps_ns = [] timestamps_file = open(timestamps_path) for line in timestamps_file: tokens = line.split() timestamp_us = long(tokens[0]) timestamp_ns = timestamp_us * long(1000) chunk = int(tokens[1]) filename = os.path.join(args.dir, tokens[0] + '.png') if not os.path.isfile(filename): if chunk != current_chunk: print("Chunk " + str(chunk) + " not found") current_chunk = chunk continue current_chunk = chunk img = load_image(filename, model)
def show_help(): img_help = load_image( path.join('data', 'images', 'background', 'background_help.jpg'), True, DISPLAYMODE) window.blit(img_help, (0, 0)) # Изображение для покрытия фона pygame.display.update() wait_for_keystroke() # Мы не выйдем из цикла, пока не нажмем любую клавишу
def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = image.load_image("particle").convert() self.rect = self.image.get_rect() self.rect.center = (rnd(0, consts.screen_size[0]), rnd(0, consts.screen_size[1])) self.dx, self.dy = (rnd(-2, 2), rnd(-2, 2))
def parse_test( root, dir_output, extensions, image_height=256, image_width=256, image_channels=3, resize_mode='squash', ): dir_output = os.path.expanduser( dir_output ) root = os.path.expanduser( root ) folder_out = os.path.join( dir_output, 'test' ) folder_in = os.path.join( root, 'test' ) images = make_dirs(folder_in, extensions) with open( os.path.join(dir_output, '{}.txt'.format( 'test' )) , 'w') as f: for i, path in enumerate( tqdm(images) ): #print(i, path) image_pathname = os.path.join(folder_out,'{:06d}.jpg'.format(i) ) # load image img = image.load_image(path) # transform img = image.resize_image(img, image_height, image_width, channels=image_channels, resize_mode=resize_mode, ) # save image PIL.Image.fromarray(img).save( image_pathname ) # save label f.write('{}\n'.format( image_pathname ) )
def __init__(self, position, target): pygame.sprite.Sprite.__init__(self) self.__dict_images_right_left = { 'right': load_image(path_enemy_right), 'left': load_image(path_enemy_left) } self.image = self.__dict_images_right_left['right'] self.rect = pygame.Rect(position[0], position[1], self.image.get_width(), self.image.get_height()) self.target = target self.select_side_number = 1 self.enemy_speed = 2 self.enemy_y_momentum = 0 self.onGround = False self.enemy_movement = [0, 0]
def on_scheduled_tweet(self): """ Make a public tweet to the bot's own timeline. """ print("Posting next tweet") # get image id image_id = self.state['last_image_id'] # get image url url = self.image_urls[image_id] print("Image URL: {}".format(url)) # load image file = image.load_image(url) # get filename filename = url.split('/')[-1] # get some awkward text text = self.create_awkward_text() # post image tweet self.post_tweet(text, media=filename, file=file) # update bot state, picking the next image id self.state['last_image_id'] = (image_id + 1) % len(self.image_urls)
def __init__(self, fixing_argument = None): pygame.sprite.Sprite.__init__(self) self.image = image.load_image('particle') self.rect = self.image.get_rect() self.rect.center = (random.randint(0, consts.screen_size[0]), random.randint(0, consts.screen_size[1])) self.dx, self.dy = (0, 0)
def show_help(): # Функция отображения подсказки # Получаем фон img_help = load_image( path.join('static', 'img', 'background', 'background_help.jpg'), True, DISPLAYMODE) window.blit(img_help, (0, 0)) # Устанавливаю фон pygame.display.update() wait_for_keystroke() # Мы не выйдем из цикла, пока не нажмем любую клавишу
def won_game(score_top, kill_enemy): # Функция отрисовки фона при победе intro_sound.play() # Включаем музыку global lvl if lvl < 8: # Проверка на уровень дает понять, конец ли игры или нужно задать новый уровень lvl += 1 new_data(lvl, score_top, kill_enemy) # Сохраняем новые данные в базу данных img = load_image( path.join('static', 'img', 'background', 'game_won.jpg'), True, DISPLAYMODE) # Получаем фон show_image(img) # Отображаем фон else: # Обнуляем уровни, игра закончилась, но можно продолжить играть поновой lvl = 1 new_data(lvl, score_top, kill_enemy) # Сохраняем новые данные в базу данных img = load_image(path.join('static', 'img', 'background', 'end.jpg'), True, DISPLAYMODE) # Получаем фон show_image(img) # Отображаем фон
def menu_new_game(): # Функция отображения новой игры pygame.mixer.init(frequency=22050, size=-16, channels=8, buffer=4096) music_channel.play(intro_sound, loops=-1, maxtime=0, fade_ms=0) # Включаем музыку img = load_image(path.join('static', 'img', 'background', 'background.jpg'), True, DISPLAYMODE) # Получаем фон show_image(img) # Отображаем фон music_channel.stop() # Выключаем музыку
def load_image(camera_dir, timestamp, camera_model, size=None): image_file = os.path.join(camera_dir, '{}.png'.format(int(timestamp))) image = sdk_image.load_image(image_file, model=camera_model) pil_image = Image.fromarray(image.astype('uint8')) if size is not None: pil_image = pil_image.resize(size) return image, pil_image
def __init__(self): pygame.display.init() pygame.sprite.Sprite.__init__(self) self.image = image.load_image('particle').convert() alpha = random.randint(0, 255) self.image.set_alpha(alpha) self.rect = self.image.get_rect() self.rect.center = (random.randint(0, consts.screen_size[0]), random.randint(0, consts.screen_size[1]))
def __init__(self, surface): pygame.sprite.Sprite.__init__(self) self.dict_images_right_left = { 'right': load_image(path_sword_right), 'left': load_image(path_sword_left) } self.side_sword = SideSwordAndEnemy.RIGHT # Атакует игрок или нет self.attack = False self.image = self.dict_images_right_left['right'] self.surface = surface self.rect = pygame.Rect(5, 0, self.image.get_width(), self.image.get_height()) self.__pos_x_max = 5 self.__pos_x_min = -10 self.position_start = (0, 0) self.speed_move_sword = 2.5
def process_images(root_dir, camera_description, models_dir): print "Processing images, ", camera_description if 'stereo' in camera_description: timestamps_path = os.path.join(root_dir, 'stereo.timestamps') else: timestamps_path = os.path.join(root_dir, camera_description + '.timestamps') if not os.path.isfile(timestamps_path): raise IOError("Could not find timestamps file") images_dir = os.path.join(root_dir, camera_description) model = CameraModel(models_dir, images_dir) current_chunk = 0 timestamps_file = open(timestamps_path) idx = 0 for line in timestamps_file: tokens = line.split() if len(tokens) < 2: break timestamp_us = long(tokens[0]) timestamp_ns = timestamp_us * long(1000) datetime = dt.utcfromtimestamp(int(tokens[0]) / 1000000) chunk = int(tokens[1]) filename = os.path.join(images_dir, tokens[0] + '.png') if not os.path.isfile(filename): if chunk != current_chunk: print("Chunk " + str(chunk) + " not found") current_chunk = chunk continue current_chunk = chunk filename_processed = os.path.join(images_dir, tokens[0] + '_ds2_undistorted.png') if not os.path.exists(filename_processed): img = load_image(filename, model) im_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) im_gray_downscaled = cv2.resize( im_gray, (im_gray.shape[1] / 2, im_gray.shape[0] / 2)) cv2.imwrite(filename_processed, im_gray_downscaled) if idx % 100 == 0: print "At ", idx idx += 1 print "Done with ", camera_description
def test_mapper(self, sample): img, label = sample # 我这里使用的是本地的image,如果你的paddlepaddle是最新的,也可以使用padd.v2.image # 因为是灰度图,所以is_color=False img = image.load_image(img, is_color=False) img = image.simple_transform(img, 32, self.imageSize, False, is_color=False) return img.flatten().astype('float32'), label
def post(self, asset_path): #postprocess data count = 0 for l in self.proto_map.layers: print self, ': Decompressing data in layer' l.data.ProcessData() #and organise map data print self, ': Creating tile map array' l.data.getOrdered(self.proto_map.map.width, self.proto_map.map.height) print self, ': Loading tilesets' tilesets = self.proto_map.tilesets self.proto_map.tiles = StorageClass() for t in tilesets.items(): path = asset_path + os.path.sep + os.path.sep.join(t[1].source[3:].split('/')) t[1].image = load_image(path) v = ['tileheight', 'tilewidth', 'margin', 'spacing'] args = [] for i in v: if hasattr(t[1], i): args.append(vars(t[1])[i]) else: args.append(0) t[1].rects = BuildTileRects(t[0], t[1].image, args[0], args[1], args[2], args[3]) #FIXME - quick work around self.proto_map.tiles.tilesets = tilesets self.proto_map.tiles.globalID = BuildGIDList(tilesets) #print self.proto_map.tiles.globalID.items()[0] # #change local property gids to global ones # for tileset in tilesets.values(): # if hasattr(tileset, 'properties'): # #print tileset.__dict__ # count = 0 # for tile in tileset.rects: # gid[tileset.firstgid + count] = tileset.rects[count] # count+=1 # def check_gid(self, map): # ret = False # #print id # #try: # tile_id = self.raw.layers[0].data.ordered[id[0],id[1]] # print id, tile_id # if tile_id > 0: # tile_set = self.raw.tiles.globalID[tile_id][0] # print tile_set # tile_set_obj = self.raw.tiles.tilesets[tile_set] # if hasattr(tile_set_obj, 'properties'): # #prop = tile_set_obj.properties # if hasattr( tile_set_obj.properties, keyword): # ret = True del self.proto_map.tilesets return self.proto_map
def paralel_augment(image_proto, in_path, out_path): """ Augment data method called in parallel by multiple threads :param image: rois metadata :param in_path: input images folder :param out_path: out images folder :return: generated metadata """ output_metadata = [] image_path = in_path + "/" + image_proto.metadata.image_path image_data = image_operations.load_image(image_path) image_size = image_data.shape shutil.copy(image_path, out_path + "/") crop_file = crop(image_proto, output_metadata) shutil.copy(image_path, out_path + "/" + crop_file) slide_file = slide_window(image_proto, image_size, output_metadata) shutil.copy(image_path, out_path + "/" + slide_file) ccw_rotated_image, ccw_rotation_matrix = image_operations.rotate_image( image_data, 5) ccw_rotated_file = rotate_ccw( image_proto, image_size, ccw_rotation_matrix, output_metadata) image_operations.save_image( ccw_rotated_image, out_path + "/" + ccw_rotated_file) cw_rotated_image, cw_rotation_matrix = image_operations.rotate_image( image_data, -5) cw_rotated_file = rotate_cw( image_proto, image_size, cw_rotation_matrix, output_metadata) image_operations.save_image(cw_rotated_image, out_path + "/" + cw_rotated_file) darken_image_data = image_operations.adjust_gamma(image_data, 0.9) darken_image_file = darken_image(image_proto, output_metadata) image_operations.save_image( darken_image_data, out_path + "/" + darken_image_file) brighten_image_data = image_operations.adjust_gamma(image_data, 1.1) brighten_image_file = brighten_image(image_proto, output_metadata) image_operations.save_image( brighten_image_data, out_path + "/" + brighten_image_file) return output_metadata
def get_uvd(image_dir, laser_dir, poses_file, models_dir, extrinsics_dir, image_idx): model = CameraModel(models_dir, image_dir) extrinsics_path = os.path.join(extrinsics_dir, model.camera + '.txt') with open(extrinsics_path) as extrinsics_file: extrinsics = [float(x) for x in next(extrinsics_file).split(' ')] G_camera_vehicle = build_se3_transform(extrinsics) G_camera_posesource = None poses_type = re.search('(vo|ins|rtk)\.csv', poses_file).group(1) if poses_type in ['ins', 'rtk']: with open(os.path.join(extrinsics_dir, 'ins.txt')) as extrinsics_file: extrinsics = next(extrinsics_file) G_camera_posesource = G_camera_vehicle * build_se3_transform([float(x) for x in extrinsics.split(' ')]) else: # VO frame and vehicle frame are the same G_camera_posesource = G_camera_vehicle timestamps_path = os.path.join(image_dir, os.pardir, model.camera + '.timestamps') if not os.path.isfile(timestamps_path): timestamps_path = os.path.join(image_dir, os.pardir, os.pardir, model.camera + '.timestamps') timestamp = 0 with open(timestamps_path) as timestamps_file: for i, line in enumerate(timestamps_file): if i == image_idx: timestamp = int(line.split(' ')[0]) pointcloud, reflectance = build_pointcloud(laser_dir, poses_file, extrinsics_dir, timestamp - 1e7, timestamp + 1e7, timestamp) pointcloud = np.dot(G_camera_posesource, pointcloud) #print(pointcloud) #print('pose', G_camera_posesource.shape) #print('pc', pointcloud[0].shape) image_path = os.path.join(image_dir, str(timestamp) + '.png') image = load_image(image_path, model) uv, depth = model.project(pointcloud, image.shape) # plt.imshow(image) # plt.scatter(np.ravel(uv[0, :]), np.ravel(uv[1, :]), s=2, c=depth, edgecolors='none', cmap='jet') # plt.xlim(0, image.shape[1]) # plt.ylim(image.shape[0], 0) # plt.xticks([]) # plt.yticks([]) # plt.show() return uv, depth, timestamp, model
def main(): images_dir = input("Please enter the directory containing the shredded images to be reassembled: ") filenames = files_in_directory(images_dir) print("files to be reassembled: {0}".format(filenames)) slices = [] for filename in filenames: slices.append(load_image(filename)) #show_all_images(slices[0], tuple(slices[1:])) while len(slices) > 1: left_index, right_index = findBestMatch(slices) print((left_index, right_index)) merge(slices, left_index, right_index) show_image(slices[0])
def new_game(): pygame.mixer.init(frequency=22050, size=-16, channels=8, buffer=4096) music_channel.play(intro_sound, loops=-1, maxtime=0, fade_ms=0) pygame.display.set_caption("Star Wars") # pygame.display.set_mode((0, 0), pygame.FULLSCREEN) # Фоновое изображение background = load_image( path.join('data', 'images', 'background', 'background_1.jpg'), True, DISPLAYMODE) window.blit(background, (0, 0)) pygame.mouse.set_visible(False) # Прячем мышку на поле pygame.display.update() wait_for_keystroke_menu() music_channel.stop()
def load_image(self, path, is_filename=True, scale=1.0, target_width=None): orig = load_image(path, is_filename) # crop to face region # from facial import facecrop # orig = facecrop(orig) if target_width is not None: scale = target_width / orig.shape[1] self.orig = orig self.scale = scale # set expected output h and w self.orig_h, self.orig_w = orig.shape[0:2] self.target_h, self.target_w = int(self.orig_h * scale), int( self.orig_w * scale) self.orig_hw = [self.orig_h, self.orig_w] self.target_hw = [self.target_h, self.target_w] # resize target = vis.resize_perfect(self.orig, self.target_h, self.target_w, cubic=True, a=3) # log print( 'loading image {}, scale:{:2.2f}, orig[{}x{}], now[{}x{}]'.format( path, scale, self.orig_w, self.orig_h, self.target_w, self.target_h)) # floatify target = (target / 255.).astype('float32') target = self.preprocess(target) if self.grayscale: # b/w target = np.einsum('ijk,kt->ijt', target, np.array([[.3], [.6], [.1]])) # clip to normal range target = np.clip(target, 0, 1) self.target = target self.set_metric()
def __call__(self, i): out = os.path.join(self._out_dir, self._images[i]) if os.path.exists(out): return in_image = os.path.join(self._in_dir, self._images[i]) img = image.load_image(in_image, self._model) img = img[:820, :, :] img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img = skimage.measure.block_reduce(img, block_size=(2, 2), func=np.mean).astype('uint8') im = PIL.Image.fromarray(img) im.save(out) print(i)
def main(): images_dir = input( "Please enter the directory containing the shredded images to be reassembled: " ) filenames = files_in_directory(images_dir) print("files to be reassembled: {0}".format(filenames)) slices = [] for filename in filenames: slices.append(load_image(filename)) #show_all_images(slices[0], tuple(slices[1:])) while len(slices) > 1: left_index, right_index = findBestMatch(slices) print((left_index, right_index)) merge(slices, left_index, right_index) show_image(slices[0])
def new_game(): # Функция меню игры при первом входе и сбросе на новую игру pygame.mixer.init(frequency=22050, size=-16, channels=8, buffer=4096) # Настраиваем музыку music_channel.play(intro_sound, loops=-1, maxtime=0, fade_ms=0) # Включаем музыку pygame.display.set_caption("Star Wars") # pygame.display.set_mode((0, 0), pygame.FULLSCREEN) # Развертывание на полный экран # Фоновое изображение background = load_image( path.join('static', 'img', 'background', 'background_1.jpg'), True, DISPLAYMODE) window.blit(background, (0, 0)) pygame.mouse.set_visible(False) # Прячем мышку на поле pygame.display.update() wait_for_keystroke_menu() # Клавиши music_channel.stop() # Остонавливаем музыку
def __init__(self, coordinate, lvl): pygame.sprite.Sprite.__init__(self) # Создаю список кадров пули врага определенного размера WIDTH_SHOOTING_ENEMY, LENGTH_SHOOTING_ENEMY (см. const.py) # Функция загрузки изображений находится в image.py self.list_shooting_img = [load_image( os.path.join('static', 'img', f'level_{lvl}', 'enemy_shooting', "shooting_" + str(i + 1) + '.png'), False, (WIDTH_SHOOTING_ENEMY, LENGTH_SHOOTING_ENEMY)) for i in range(COUNT_SHOOTING_ENEMY)] # Индекс текущего изображения пули врага и начальная скорость смены изображения self.index, self.speed_image = -1, 0 self.image = self.list_shooting_img[self.index] # Устанавливаю старовое изображение # Получаю размеры изображения, квадрат self.rect = self.image.get_rect() self.rect.center = (coordinate[0] - 15, coordinate[1] - 42) # Стартовое расположение пули врага на экране
def __init__(self, object_rect): pygame.sprite.Sprite.__init__(self) # Создаю список кадров взрыва определенного размера WIDTH_EXPLOSION, LENGTH_EXPLOSION (см. const.py) # Функция загрузки изображений находится в image.py self.list_explosion_img = [load_image( os.path.join('static', 'img', 'animation', "explosion" + str(i + 1) + '.png'), False, (WIDTH_EXPLOSION, LENGTH_EXPLOSION)) for i in range(COUNT_EXPLOSION)] # Индекс текущего изображения взрыва и начальная скорость смены изображения self.index, self.speed_image = -1, 0 self.image = self.list_explosion_img[self.index] # Устанавливаю старовое изображение # Получаю размеры изображения, квадрат self.rect = self.image.get_rect() # Стартовое расположение взрыва на экране равно расположению предмета до взрыва self.rect.x, self.rect.y = object_rect.x, object_rect.y
def spider(self): directory = self.basepath file_type = 'png' colorkey = None scale = 1 if os.path.exists(directory): file_list = dircache.listdir(directory) tile_list = dict() for i in file_list: ext = i.split('.') if ((len(ext) >= 2) and (ext[1] == (file_type))): #print 'LOADED: ', ext[0] tile_list[ext[0]] = load_image(os.path.join(directory, i), colorkey, scale) self.imageset = tile_list return tile_list else: print 'error opening', directory
def __init__(self): pygame.sprite.Sprite.__init__(self) # Создаю список кадров игрока определенного размера WIDTH_PLAYER, LENGTH_PLAYER (см. const.py) # Функция загрузки изображений находится в image.py self.list_player_img = [load_image( os.path.join('static', 'img', 'player', "player_" + str(i + 1) + '.png'), False, (WIDTH_PLAYER, LENGTH_PLAYER)) for i in range(COUNT_PLAYER)] # Индекс текущего изображения игрока и начальная скорость смены изображения self.index, self.speed_image = -1, 0 self.image = self.list_player_img[self.index] # Устанавливаю старовое изображение # Получаю размеры изображения, квадрат # (Для проверок на сталкновения и расположение игрока на экране) self.rect = self.image.get_rect() self.rect.center = (170, WINDOW_HEIGHT // 2) # Стартовое расположение игрока на экране self.y_speed = 1 # Скорость игрока по y (по x он не будет двигаться)
def main(): print 'TODO: get all (50,250) etc as different variables, esp the colours' playerName = '' # Initialize Pygame pygame.init() # Create a window of 800x600 pixels screen = pygame.display.set_mode(Config.DEFAULT_SCREEN_SIZE) # Set the window caption pygame.display.set_caption('PySnake') bkg = image.load_image('pysnake.jpg', img_dir) rules_one = image.load_image('pysnake_rules_one.jpg', img_dir) rules_two = image.load_image('pysnake_rules_two.jpg', img_dir) menu = generate_main_menu(screen) level_select_menu = generate_level_select(screen) high_scores_menu = generate_high_scores(screen) game_rules_one_menu = generate_game_rules(screen, 1) game_rules_two_menu = generate_game_rules(screen, 2) high_score_input_menu = generate_high_score_input(screen, playerName) state = STATE_MAIN_MENU prev_state = STATE_EXIT # rect_list is the list of pygame.Rect's that will tell pygame where to # update the screen (there is no point in updating the entire screen if only # a small portion of it changed!) rect_list = [] imageIsShown = False EVENT_CHANGE_STATE = pygame.USEREVENT + 1 # only allow what we will be dealing with, therefore speed up the program pygame.event.set_allowed(None) pygame.event.set_allowed([pygame.KEYDOWN, EVENT_CHANGE_STATE, pygame.QUIT]) print 'BUG: in Game rules, press ESC, go back, no image' ourFont = pygame.font.SysFont('Arial', 24) # The main while loop while True: # Check if the state has changed, if it has, then post a user event to # the queue to force the menu to be shown at least once # high_score_input_menu = generate_high_score_input(screen, playerName) # if len(playerName) > 0: # print playerName if prev_state != state: pygame.event.post(pygame.event.Event(EVENT_CHANGE_STATE, key=0)) prev_state = state screen.blit(bkg, (0, 0)) pygame.display.flip() # Get the next event e = pygame.event.wait() # Update the menu, based on which "state" we are in - When using the menu # in a more complex program, definitely make the states global variables # so that you can refer to them by a name if e.type == pygame.KEYDOWN or e.type == EVENT_CHANGE_STATE: if e.type == pygame.KEYDOWN: if e.key == pygame.K_ESCAPE: # if we press escape/q on the main menu, quit if state == STATE_MAIN_MENU: state = STATE_EXIT else: # otherwise return to the main menu state = STATE_MAIN_MENU # don't let the user press # if pygame.key.name(e.key) in string.lowercase: # state = ord(pygame.key.name(e.key)) + HIGH_SCORE_INPUT_OFFSET if state == STATE_MAIN_MENU: (rect_list, state) = menu.update(e, state) elif state == STATE_LEVEL_SELECT: (rect_list, state) = level_select_menu.update(e, state) elif state > LEVEL_ID_OFFSET and state \ < HIGH_SCORE_INPUT_OFFSET: (rect_list, state) = level_select_menu.update(e, state) # G = Game_Module.Game() level_files = get_level_list() fName = level_files[state % 9000 - 1]['fName'] level_settings = get_level_settings(fName) continueBool = False for val in [ 'difficulty', 'level_name', 'initial_food_num', 'initial_food_super_num', 'initial_food_mysterious_num', 'initial_food_curse_num', 'initial_ball_num', 'initial_ball_killer_num', 'max_balls', 'ball_speed', 'ball_size', 'fps', 'background_colour', ]: try: if isinstance(level_settings[val], str): pass except KeyError: print 'KEY ERROR', val continueBool = True if continueBool: continueBool = False continue # surround strings with double quotes, leave integers as they are if isinstance(level_settings[val], str): exec 'Config.' + str(val.upper()) + ' = "' \ + str(level_settings[val]) + '"' else: exec 'Config.' + str(val.upper()) + ' = ' \ + str(level_settings[val]) + '' # print eval('Config.' + str(val.upper())) # end for Config.PAGE_TITLE = Config.PAGE_TITLE + ' ' \ + level_files[state % 9000 - 1]['settings' ]['level_name'] # work out the bonus based on difficulty - will only work for valid difficulties # try: exec 'Config.DIFFICULTY_BONUS = Config.DIFFICULTY_BONUS_' \ + Config.DIFFICULTY.upper() Config.BACKGROUND = pygame.Surface(screen.get_size()) Config.BACKGROUND = Config.BACKGROUND.convert() Config.BACKGROUND.fill(Config.BACKGROUND_COLOUR) Config.screen = \ pygame.display.set_mode(Config.DEFAULT_SCREEN_SIZE) # print "COLOUR: ", Config.BACKGROUND_COLOUR # better way of doing it? # execfile('Snake.py') G = Game_Module.Game(None) running = True while running: G.update() if G.gameOver: playerScore = G.gameScore del G running = False break if HelperFunctions.isNewHighScore(playerScore): state = STATE_HIGH_SCORE_INPUT else: # state = STATE_EXIT state = STATE_HIGH_SCORE_TRY_AGAIN elif state == STATE_HIGH_SCORE_INPUT: # state = STATE_HIGH_SCORE_TRY_AGAIN # #### http://www.facebook.com/l.php?u=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F14111381%2Fhow-to-make-pygame-print-input-from-user&h=kAQHS8xjR (rect_list, state) = high_score_input_menu.update(e, state) if False: pass getInput = True showUpdates = True while getInput: for keypress in pygame.event.get(): if keypress.type == pygame.KEYDOWN: if keypress.unicode.isalpha(): playerName += keypress.unicode showUpdates = True elif keypress.key == pygame.K_BACKSPACE: playerName = playerName[:-1] showUpdates = True elif keypress.key == pygame.K_RETURN: getInput = False continue if showUpdates: screen.fill((0, 0, 0)) text = ourFont.render(playerName, True, (255, 0, 0)) block = text.get_rect() block.center = (400, 300) # dead center rect_list.append(screen.blit(text, block)) text = \ ourFont.render('Please type your name, press enter to finish, and backspace to remove characters. ' , True, (255, 255, 255)) block = text.get_rect() block.center = (400, 250) # block.center[1] -= 100 rect_list.append(screen.blit(text, block)) pygame.display.update(rect_list) showUpdates = False # end while print 'Final name', playerName HelperFunctions.appendHighScore(playerScore, playerName) state = STATE_HIGH_SCORE_TRY_AGAIN elif state == STATE_LEVEL_CREATOR: screen.fill((0, 0, 0)) rect_list.append(HelperFunctions.makeTextRect( 'Please follow the instructions in the console.', (255, 255, 255), (400, 250), screen, ourFont, True, )) rect_list.append(HelperFunctions.makeTextRect( 'Once complete, please restart the menu. ', (255, 255, 255), (400, 300), screen, ourFont, True, )) pygame.display.update(rect_list) os.system(sys.executable + ' level_creator.py') state = STATE_EXIT elif state == STATE_HIGH_SCORES: # print 'High Scores' (rect_list, state) = high_scores_menu.update(e, state) highScoresList = HelperFunctions.getHighScores() yOffset = 220 screen.fill((0, 0, 0)) rect_list.append(HelperFunctions.makeTextRect('Rank', GREEN, (100, yOffset), screen, ourFont)) rect_list.append(HelperFunctions.makeTextRect('Name', GREEN, (200, yOffset), screen, ourFont)) rect_list.append(HelperFunctions.makeTextRect('Score', GREEN, (450, yOffset), screen, ourFont)) yOffset += 30 colour = dict() colour['normal'] = (255, 255, 255) colour['bronze'] = (128, 64, 0) colour['silver'] = (192, 192, 192) colour['gold'] = (232, 232, 0) for (idx, tup) in enumerate(highScoresList): # print idx if idx == 0: c = colour['gold'] elif idx == 1: c = colour['silver'] elif idx == 2: c = colour['bronze'] else: c = colour['normal'] rect_list.append(HelperFunctions.makeTextRect(str(idx + 1) + '. ', c, (100, yOffset), screen, ourFont)) rect_list.append(HelperFunctions.makeTextRect(str(tup[1]), c, (200, yOffset), screen, ourFont)) rect_list.append(HelperFunctions.makeTextRect(str(tup[0]), c, (450, yOffset), screen, ourFont)) yOffset += 30 rect_list.append(HelperFunctions.makeTextRect('Press enter or escape to return' , (255, 255, 255), (500, 300), screen, ourFont)) rect_list.append(HelperFunctions.makeTextRect('to the main menu' , (255, 255, 255), (500, 320), screen, ourFont)) pygame.display.update(rect_list) elif state == STATE_RULES_P_ONE: # High scores menu (rect_list, state) = game_rules_one_menu.update(e, state) if not imageIsShown: # only show on the first page instance, otherwise will need to keep redrawing :. inefficient rect_list.append(screen.blit(rules_one, (20, 250))) imageIsShown = True if prev_state != state: # changed page imageIsShown = False elif state == STATE_RULES_P_TWO: (rect_list, state) = game_rules_two_menu.update(e, state) if not imageIsShown: # only show on the first page instance, otherwise will need to keep redrawing :. inefficient rect_list.append(screen.blit(rules_two, (20, 250))) imageIsShown = True if prev_state != state: # changed page imageIsShown = False elif state == STATE_HIGH_SCORE_TRY_AGAIN: screen.fill((0, 0, 0)) rect_list.append(HelperFunctions.makeTextRect( 'Your final score was ' + str(playerScore) + '. Try again next time!', (255, 255, 255), (400, 250), screen, ourFont, True, )) rect_list.append(HelperFunctions.makeTextRect( 'Press any key to exit. ', (255, 255, 255), (400, 300), screen, ourFont, True, )) pygame.display.update(rect_list) # state = STATE_EXIT # wait until we get some user input, so we know they've seen the message, then exit e = pygame.event.wait() if e.type == pygame.KEYDOWN or e.type == pygame.QUIT: state = STATE_EXIT else: pygame.quit() sys.exit() # Quit if the user presses the exit button if e.type == pygame.QUIT: pygame.quit() sys.exit() # Update the screen pygame.display.update(rect_list)
import consts, image pygame.init() screen = pygame.display.set_mode(consts.screen_size, pygame.FULLSCREEN) scroll_speed = [0, 0] scroll_dir = [0, 0] scroll_acc = 1 pygame.mouse.set_visible(False) clock = pygame.time.Clock() #### Display Title title = image.load_image('erebus') title_size = title.get_size() title = pygame.transform.scale(title, (title_size[0]*5, title_size[1]*5)) title_rect = title.get_rect() title_rect.center = (consts.screen_size[0]/2, consts.screen_size[1]/2) screen.blit(title, title_rect) font12 = pygame.font.FontType(None, 12) anykey = font12.render('Press Any Key To Continue', True, (255, 255, 255)) screen.blit(anykey, (0, 0)) pygame.display.update() title_loop = True while title_loop:
def client_init(): """Initialiaze client state.""" # Set up signal handlers signal.signal(signal.SIGINT, quit_game) signal.signal(signal.SIGTERM, quit_game) # Initializing these modules separately instead of calling # pygame.init() is WAY faster. pygame.display.init() pygame.font.init() # Wait 200 ms before repeating a key that's held down, and send them # as fast as possible. The repeat delay is therefore limited by the # frame rate, not by set_repeat() pygame.key.set_repeat(200, 1) pygame.display.set_caption('{0} {1}'.format(cfg.GAME_NAME, cfg.VERSION)) uname = 'Taimor' usex = 'Male' urace = 'Human' urole = 'Wizard' pygame.display.set_caption('{0} - {1} the {2} {3} {4}'.format( cfg.GAME_TITLE, uname, usex, urace, urole)) CS.clock = pygame.time.Clock() CS.font = pygame.font.SysFont('Arial', cfg.FONT_SIZE) CS.font_h = CS.font.get_height() CS.font_w = CS.font.size('X')[0] # Size of the map surface CS.map_rect.w = (cfg.MAP_W + 2) * cfg.TILE_W CS.map_rect.h = (cfg.MAP_H + 2) * cfg.TILE_H # Size of the status panel CS.status_rect.w = cfg.STATUS_W * CS.font_w CS.status_rect.h = cfg.STATUS_H * CS.font_h # Size of the equipment panel CS.eq_rect.w = cfg.EQ_W * cfg.TILE_W CS.eq_rect.h = CS.status_rect.h # Size of the full game screen CS.screen_rect.w = CS.eq_rect.w + CS.status_rect.w + cfg.MIN_LOG_W if CS.screen_rect.w < cfg.INIT_SCREEN_W: CS.screen_rect.w = cfg.INIT_SCREEN_W CS.screen_rect.h = CS.status_rect.h + cfg.MIN_MAPVIEW_H if CS.screen_rect.h < cfg.INIT_SCREEN_H: CS.screen_rect.h = cfg.INIT_SCREEN_H # Size of the log surface CS.log_rect.w = CS.screen_rect.w - ( CS.eq_rect.w + CS.status_rect.w) - cfg.SCROLLBAR_W - 50 CS.log_rect.h = CS.status_rect.h CS.logview_rect.w, CS.logview_rect.h = CS.log_rect.w, CS.log_rect.h # The mapview size. May be smaller or larger than the actual map size. # This is the location on the screen where the map or a piece thereof # is drawn. It's not an actual surface, but a logical rectangle. CS.mapview_rect.w = CS.screen_rect.w - cfg.SCROLLBAR_W CS.mapview_rect.h = ( CS.screen_rect.h - CS.status_rect.h - cfg.SCROLLBAR_W) # Locations to blit equipment on the equipment panel eq_cent = (int(CS.eq_rect.w / 2.0 - cfg.TILE_W / 2), int(CS.eq_rect.h / 2.0 - cfg.TILE_W / 2)) CS.eq_hands = (eq_cent[0], CS.eq_rect.y + cfg.TILE_H / 2 + 3 * cfg.TILE_H) CS.eq_rweap = (CS.eq_hands[0] - cfg.TILE_W, CS.eq_hands[1]) CS.eq_lweap = (CS.eq_hands[0] + cfg.TILE_W, CS.eq_hands[1]) CS.eq_rring = (CS.eq_hands[0] - cfg.TILE_W, CS.eq_hands[1] + cfg.TILE_H) CS.eq_lring = (CS.eq_hands[0] + cfg.TILE_W, CS.eq_hands[1] + cfg.TILE_H) CS.eq_boots = (CS.eq_hands[0], CS.eq_hands[1] + cfg.TILE_H * 2) CS.eq_armor = (CS.eq_hands[0], CS.eq_hands[1] - cfg.TILE_H) CS.eq_shirt = (CS.eq_hands[0] - cfg.TILE_W, CS.eq_hands[1] - cfg.TILE_H) CS.eq_cloak = (CS.eq_hands[0] + cfg.TILE_W, CS.eq_hands[1] - cfg.TILE_H) CS.eq_neck = (CS.eq_hands[0], CS.eq_hands[1] - cfg.TILE_H * 2) CS.eq_eyes = (CS.eq_hands[0] - cfg.TILE_W, CS.eq_hands[1] - cfg.TILE_H * 2) CS.eq_quiver = (CS.eq_hands[0] + cfg.TILE_W * 2, CS.eq_hands[1] - cfg.TILE_H * 3) CS.eq_light = (CS.eq_hands[0] - cfg.TILE_W * 2, CS.eq_hands[1] - cfg.TILE_H * 3) CS.eq_head = (CS.eq_hands[0], CS.eq_hands[1] - cfg.TILE_H * 3) CS.screen = pygame.display.set_mode( (CS.screen_rect.w, CS.screen_rect.h), pygame.RESIZABLE) # pylint: disable=E1121 CS.eq_surf = Surface((CS.eq_rect.w, CS.eq_rect.h)).convert() CS.status_surf = Surface((CS.status_rect.w, CS.status_rect.h)).convert() CS.map_surf = Surface((CS.map_rect.w, CS.map_rect.h)).convert() # pylint: enable=E1121 # Set the system icon system_icon = image.load_image('icon.xpm') pygame.display.set_icon(system_icon) CS.tiles_img = image.load_image('tiles16.xpm') CS.gray_tiles_img = image.load_image('tiles16_gray.xpm') CS.menu_bg_img = image.load_image('parchment.jpg') CS.tile_dict = image.create_tile_dict() CS.blank_tile = CS.tile_dict['cmap, wall, dark'] CS.x_scrollbar = ScrollBar(cfg.SCROLLBAR_W, 0, CS.map_rect, CS.mapview_rect, always_show=False) CS.y_scrollbar = ScrollBar(cfg.SCROLLBAR_W, 1, CS.map_rect, CS.mapview_rect, always_show=False) CS.log_scrollbar = ScrollBar(cfg.SCROLLBAR_W, 1, CS.log_rect, CS.logview_rect, always_show=False) # Process any initial setup data we've gotten from the server. This # should include the first dungeon level and the Player object. handle_responses() # Set up keystroke actions keys.attach_key_actions() # Make sure everything is aligned correctly gui.center_map() gui.handle_resize(CS.screen_rect.w, CS.screen_rect.h)
def __init__(self): #### why it was so unecessary #### self.window = self.Window() self.scroll = [0, 0] self.scroll_speed = [0, 0] self.scp = [lambda x, a: random.randint(0, a), lambda x, a: 0, lambda x, a: consts.screen_size[x]] # self.cursor = self.Cursor() pygame.mouse.set_visible(False) self.clock = pygame.time.Clock() #### Background that probably won't get used #### self.bg = image.load_image('background2') self.bg = pygame.transform.scale(self.bg, consts.screen_size) #### TODO: Sound... Title... Font... #### pygame.mixer.init() pygame.font.init() title = image.load_image('erebus') title_size = title.get_size() title = pygame.transform.scale(title, (title_size[0]*5, title_size[1]*5)) title_rect = title.get_rect() title_rect.center = consts.screen_size[0]/2, consts.screen_size[1]/2 self.window.screen.blit(title, (title_rect.x, title_rect.y)) pygame.display.update() start = False while True: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: self.on_keydown(event) start = True if start: break # pygame.mouse.set_visible(True) try: pygame.mixer.init() except: print 'Cannot load sound' #### Creates sprite groups #### self.particles = pygame.sprite.Group() self.stars = pygame.sprite.Group() self.bgstars = pygame.sprite.Group() #### Creates Sprites! #### [self.bgstars.add(bgStar()) for x in xrange(1000)] [self.particles.add(Particle('Hydrogen')) for x in xrange(1)] self.Player = Star() self.Nemesis = Nemesis() self.stars.add(self.Player) #### Self executing code. How meta #### self.loop()
def __init__(self): self.window = self.Window() self.clock = pygame.time.Clock() self.scroll = [0, 0] self.scroll_speed = [0, 0] pygame.mouse.set_visible(False) #### Background that probably won't get used #### self.bg = image.load_image("background2") self.bg = pygame.transform.scale(self.bg, consts.screen_size) pygame.mixer.init() pygame.font.init() self.font = pygame.font.FontType(None, 24) title = image.load_image("erebus") title_size = title.get_size() title = pygame.transform.scale(title, (title_size[0] * 5, title_size[1] * 5)) title_rect = title.get_rect() title_rect.center = consts.screen_size[0] / 2, consts.screen_size[1] / 2 self.window.screen.blit(title, title_rect) text = self.font.render("Press Any Key To Play", True, (255, 255, 255)) text_rect = text.get_rect() text_rect.center = (consts.screen_size[0] / 2, consts.screen_size[1] - 24) self.window.screen.blit(text, text_rect) pygame.display.update() start = False while True: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: self.on_keydown(event) start = True if start: break try: pygame.mixer.init() except: print "Cannot load sound" #### Creates sprite groups #### self.particles = pygame.sprite.Group() self.stars = pygame.sprite.Group() self.bgstars = pygame.sprite.Group() #### Creates Sprites! #### [self.bgstars.add(bgStar()) for x in xrange(10)] [self.particles.add(Particle("Hydrogen")) for x in xrange(1)] #### Creat Player + Nemesis #### self.Player = Star() self.Nemesis = Nemesis() #### More precursors #### self.stars.add(self.Player) self.instructions = True self.nemesis_exists = False self.nemesis_start = 1 self.loop()
__author__ = 'anton' import image import encoder import decoder import encoder_gpu if __name__ == '__main__': img = image.load_image('nature.bmp') print img.width, img.height transformations = encoder_gpu.encode(img) print len(transformations), len(transformations[0]) img_data = decoder.decode(10, img.width, img.height, transformations) print len(transformations) img = image.ImageData(img.width, img.height, img_data, img.mode) image.save_image('anture_test.bmp', img)