def capture(profile_num, surf, ingame=False): global FirstScreenshot if FirstScreenshot: print(colorize(f"Saving screenshots at: {directory}", "bold")) FirstScreenshot = False surf = copy.copy(surf) data = time.localtime() if not os.path.exists(directory): print(colorize("Screenshot directory missing.", "warning")) os.mkdir(directory) name = f"ii{profile_num}_{data.tm_year}{data.tm_mon}{data.tm_mday}{data.tm_hour}{data.tm_min}{data.tm_sec}" done_this = False p = fix_path(directory + "/" + name + ".png") while os.path.exists(p) or name in save_for_later: if not done_this: name += "_2" done_this = True else: name = name[:-1] + str(int(name[-1]) + 1) p = fix_path(directory + "/" + name + ".png") sound.play() if ingame and options["cache_screen_shots"]: print(colorize(f"Caching screenshot {name}", "blue")) save_for_later[name] = surf else: save(surf, name)
def save(surf, name): print(colorize("Saving screenshot...", "blue")) t1 = time.time() pygame.image.save(surf, fix_path(f"{directory}/{name}.png")) t2 = time.time() print( colorize(f"Saved screenshot \"{name}\" in {round(t2-t1, 2)} seconds", "green"))
def update(self): self.text_time += self.time_passed if self.text_time >= self.text_rate and self.text and not self.options_lock: print(colorize(self.text[0], "bold"), end="", flush=True) self.text = self.text[1:] if not self.text and self.had_text: print() self.text_time = 0 if self.frame_time >= self.frame_rate and not self.frame >= 150: self.frame += 1 self.frame_time = 0 if self.frame == 150 and not self.frame_finished: self.frame_finished = True self.finished = True self.frame_rate = (1 / 25) self.flash_time = self.flash_delay self.can_flash = True self.flash_time -= self.time_passed if self.flash_time < 0 and self.can_flash: self.flash_time = self.flash_delay self.frame = self.frame_flash_start self.frame_time += self.time_passed self.star_rotation += self.rotation_speed * self.time_passed pygame.display.update() time_passed = clock.tick(60) / 1000 if not self.pause_motion: self.time_passed = time_passed else: self.pause_motion = False
def write_stars(self): print("\n", colorize("Generating Star Data...", "bold"), "\n", sep="") background = self.display.copy() self.display.fill((0, 0, 0)) retro_text( (self.display.get_width() // 2, self.display.get_height() // 2), self.display, 30, "Please Wait...", anchor="center") fade_in(self.display, 3, background) for x in range(300): stars.main() with shelve.open(fix_path(get_file("data/menuStarsCache"))) as data: data["stars"] = stars.stars data["version"] = __version__
def __init__(self): self.options = saves.load_options() fullscreen = 0 if self.options["fullscreen"]: fullscreen = pygame.FULLSCREEN pygame.display.set_icon(pygame.image.load(get_file("icon.png"))) self.Display = pygame.display.set_mode((800, 600), fullscreen | pygame.HWACCEL) self.display = pygame.Surface((800, 600)) pygame.display.set_caption("Interplanetary Invaders") t1 = time.time() self.images, num = auto_load.fetch_images(self.Display) t2 = time.time() self.first_time = True print( colorize(f"Loaded {num} images in {round(t2-t1, 2)} seconds", "green")) self.menu() self.cat = []
def keepGoing(self, lw): try: lw.main() except KeyboardInterrupt: print(colorize("Nope. Answer the questions", "fail")) self.keepGoing(lw)
from interplanetary_invaders.scripts import saves from interplanetary_invaders.scripts.saves import load_options from interplanetary_invaders.scripts import map_menus as maps from interplanetary_invaders.scripts import lose_win from interplanetary_invaders.scripts.congrats import congrats from interplanetary_invaders.scripts.planets import * from interplanetary_invaders.scripts import stores from interplanetary_invaders.scripts.achievements import ACHIEVEMENTS from interplanetary_invaders.scripts.get_file import get_file from interplanetary_invaders.scripts.utils import colorize from interplanetary_invaders.scripts.transition import black_out from interplanetary_invaders.scripts import joystick from interplanetary_invaders.scripts import game import time print(colorize(f"Your data directory is: {get_file('data')}", "bold"), "\n") pygame.init() saves.debugMode = debugMode SIZE = (800, 600) if joystick.hasJoystick: print( colorize(f"Detected a \"{joystick.name}\" Joystick", "green" if joystick.IsSupported() else "fail")) if not joystick.IsSupported(): print(colorize(f"This joystick may not be supported", "warning"))
def fetch_images(display): """Collect images from the IMAGE_PATH and return dictionary with pygame.Surface objects as values and their names as keys""" names = [] images = [] num = 0 print("Loading... \n") mx = 0 display.fill((0, 0, 0)) retro_text(display.get_rect().move(0, -30).center, display, 18, "LOADING...", anchor="center") for x in range(10): g = 255 * x / 10 retro_text(display.get_rect().move(0, 60 - x).midtop, display, 22, "INTERPLANETARY INVADERS", anchor="center", bold=True, color=(g, g, g)) retro_text(display.get_rect().move(0, 85 - x).midtop, display, 18, f"V{__version__}", anchor="center", bold=True, color=(g, g, g)) if joystick.hasJoystick: retro_text(display.get_rect().move(0, 200).center, display, 18, "Detected Joystick:", anchor="center", bold=True) retro_text(display.get_rect().move(0, 225).center, display, 20, '"' + joystick.name + '"', anchor="center") if not joystick.IsSupported(): retro_text(display.get_rect().move(0, 240).center, display, 20, "Unsupported Joystick", anchor="center", bold=True, color=(255, 0, 0)) borderRect = pygame.Rect(0, 0, BAR_WIDTH + 10, BAR_HEIGHT + 5) borderRect.center = display.get_rect().center barRect = borderRect.copy() barRect.h = BAR_HEIGHT barRect.center = borderRect.center LastRefresh = 0 pygame.display.update() for data in os.walk(IMAGE_PATH): for collect_file in data[2]: if not collect_file.startswith("."): mx += 1 for data in os.walk(IMAGE_PATH): root = data[0] files = data[2] for collect_file in files: if not collect_file.startswith("."): num += 1 name = remove_extension(collect_file) img = pygame.image.load(root + os.sep + collect_file) if (name.startswith("spinning") and not "RGBA" in name): img = img.convert() img.set_colorkey((0, 0, 0)) else: if not "animation" in root: if name.startswith("map_"): img = img.convert() else: img = img.convert_alpha() if name.startswith("ROT_"): name = name[4:] x = 0 for r in range(-90, 91): x += 1 names.append(name + str(int(r % 360))) images.append(pygame.transform.rotate(img, r)) names.append(name) images.append(img) print( f"\rLoaded {colorize(num, 'blue' if num!=mx else 'green')} / {colorize(mx, 'green')} images %s" % colorize(collect_file + (" " * (40 - len(collect_file))), 'bold'), flush=True, end="") if time.time() - LastRefresh >= .1: LastRefresh = time.time() barRect.w = int((BAR_WIDTH * (num / mx)) * 10) / 10 g = 255 * (num / mx) b = 255 - g pygame.draw.rect(display, (0, g, b), barRect) for x in range(0, BAR_WIDTH, BAR_WIDTH // 10): X_Val = barRect.x + x pygame.draw.line(display, (0, 0, 0), (X_Val, borderRect.y), (X_Val, borderRect.y + borderRect.h), 2) pygame.draw.rect(display, (25, 25, 25), borderRect, 1) text, text_rect = retro_text(display.get_rect().move( 0, 30).center, display, 18, f"{round(num/mx*100)}%", anchor="center", eraseColor=(0, 0, 0)) pygame.display.update([barRect, text_rect]) print() return dict(zip(names, images)), num
def __init__(self, images, display, profile, profile_number, focus = "theSun"): self.images = images self.Display = display self.display = pygame.Surface((800, 600)) self.done = False self.time_passed = 0 self.planets1 = [Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune] for planet in MOONS: for moon in MOONS[planet]: self.planets1.append(moon) self.planets1.reverse() self.planets = [] for p in self.planets1: self.planets.append(p()) self.sunRect = pygame.Rect(0, 0, 20, 20) self.sunRect.center = self.Display.get_rect().center self.real_world_time = 0 self.offset = [0, 0] self.target_offset = [0, 0] self.zoom = 1 self.target_zoom = 1.5 self.scroll_speed = 300 self.scroll_range = 10 self.zoom_amount = .1 self.focused = None self.sun_frame = 1 self.next_sun_frame = 0 self.sun_frame_len = 1 / 25 self.overlay_pos = None self.moving_start = 0 self.moving = False if focus in PLANET_BY_NAME: focus = self.planets1.index(PLANET_BY_NAME[focus]) self.focused = focus self.mouse_on = False self.profile = profile self.profile_number = profile_number self.money = self.profile["money"] self.text_yellow = False self.text_rate = 1 / 5 self.text_time = 0 self.start_click = None self.last_sample = None unlocked_planets = self.profile["unlocked_planets"] self.unlocked_planets = [] for u in unlocked_planets: for p in self.planets: if isinstance(p, PLANET_BY_NAME[u]): self.unlocked_planets.append(p) self.missions_left = {} for planet in self.unlocked_planets: self.missions_left[planet.name] = 0 try: for p in self.profile["map"][planet.name]: if p.alien_flag: self.missions_left[planet.name] += 1 except KeyError: print(colorize(f"No map for {planet.name} found!", "fail")) self.speed = 1 pygame.mixer.music.load(fix_path(get_file("audio/music/AmbientSpace.mp3"))) pygame.mixer.music.play(-1)
def events(self): for event in pygame.event.get(): joystick.Update(event) if event.type == pygame.QUIT: self.exit() if event.type == pygame.MOUSEBUTTONDOWN: if not self.finished and not self.options_lock: self.finished = True print(colorize(self.text, 'bold')) self.text = "" if event.type == pygame.KEYDOWN or joystick.WasEvent(): if not hasattr(event, "key"): event.key = None if event.key == pygame.K_F2 or joystick.JustPressedLB(): screenshot.capture("M", self.display) if not self.finished and not self.options_lock: self.finished = True print(colorize(self.text, 'bold')) self.text = "" else: item = self.item_selected items = self.items if self.options_mode: item = self.option_selected items = self.options if self.play_mode: item = self.profile_selected items = self.profiles if event.key == pygame.K_ESCAPE or joystick.BackEvent(): if self.play_mode: self.play_mode = False elif self.options_mode: self.options_mode = False self.options_dict = saves.load_options() else: self.exit() if event.key == pygame.K_UP or joystick.JustWentUp(): item -= 1 if (event.key == pygame.K_DOWN) or joystick.JustWentDown(): item += 1 if item < 0: item = 0 if item >= len(items): item = len(items) - 1 if self.options_mode: self.option_selected = item if self.play_mode: self.profile_selected = item elif self.play_mode: pass else: self.item_selected = item if self.options_mode: op = self.options[self.option_selected] if op == "Volume": vol = self.options_dict["volume"] if event.key == pygame.K_LEFT or joystick.JustWentLeft(): vol -= .1 if event.key == pygame.K_RIGHT or joystick.JustWentRight(): vol += .1 if vol < 0: vol = 0 if vol > 1: vol = 1 self.options_dict["volume"] = vol if op == "Cache Screenshots": if event.key == pygame.K_RETURN or joystick.JustPressedA(): self.options_dict["cache_screen_shots"] = not self.options_dict["cache_screen_shots"] if op == "Stretch to Fullscreen": if event.key == pygame.K_RETURN or joystick.JustPressedA(): self.options_dict["fullscreen"] = not self.options_dict["fullscreen"] if op == self.DEL: if event.key == pygame.K_RETURN or joystick.JustPressedA(): try: DID_SOMETHING = False for e, x in enumerate(os.listdir(fix_path(get_file("data/screenshots")))): os.remove(fix_path(get_file("data/screenshots/")) + x) DID_SOMETHING = True if DID_SOMETHING: print(colorize(f"Deleted screenshots: {e+1}", "green")) self.options[self.options.index(self.DEL)] = "Deleted screenshots" self.DEL = "Deleted screenshots" except FileNotFoundError: print(colorize("Failed to delete screenshots!", "fail")) print(colorize("File not found error.", "fail")) if event.key == pygame.K_x or joystick.JustPressedX(): if self.play_mode: if self.profile_selected < 5 and not self.profiles[self.profile_selected].startswith("New"): self.confirm_delete() if event.key == pygame.K_RETURN or joystick.JustPressedA() or joystick.JustPressedStart(): if self.options_mode: sel = self.option_selected if self.options[sel] == "Cancel": self.option_selected = 2 self.options_mode = False self.options_dict = saves.load_options() if self.options[sel] == "Save": self.options_mode = False saves.save_data("options", self.options_dict) elif self.play_mode: if self.profiles[self.profile_selected] == "Back": self.play_mode = False else: profile = saves.load_profile(self.profile_selected) if profile["version"] != __version__: if profile["new"]: profile["version"] = __version__ else: print(colorize("Warning: this profile is from a different version \ of Interplanetary Invaders; \nerrors may occur", "warning")) profile["new"] = False saves.save_data(self.profile_selected, profile) self.done = True else: sel = self.item_selected if self.items[sel] == "Play": self.play_mode = True if self.items[sel] == "Options": self.options_mode = True if self.items[sel] == "Quit": self.exit() if self.items[sel] == "Credits": run_credits(self.display, self.images) pygame.mixer.music.load(fix_path(get_file("audio/music/MainMenu.mp3"))) pygame.mixer.music.play(-1) if not self.options_mode and self.options_lock: self.done = True
def fetch_images(display): """Collect images from the IMAGE_PATH and return dictionary with pygame.Surface objects as values and their names as keys""" names = [] images = [] num = 0 mx = 0 display.fill((0, 0, 0)) retro_text(display.get_rect().move(0, -30).center, display, 18, "LOADING...", anchor="center") for x in range(10): g = 255 * x / 10 retro_text(display.get_rect().move(0, 60 - x).midtop, display, 22, "INTERPLANETARY INVADERS", anchor="center", bold=True, color=(0, g, 0)) retro_text(display.get_rect().move(0, 85 - x).midtop, display, 18, f"V{__version__}", anchor="center", bold=True, color=(0, g * .75, 0)) if joystick.hasJoystick: retro_text(display.get_rect().move(0, 200).center, display, 18, "Detected Joystick:", anchor="center", bold=True) retro_text(display.get_rect().move(0, 225).center, display, 20, '"' + joystick.name + '"', anchor="center") if not joystick.IsSupported(): retro_text(display.get_rect().move(0, 240).center, display, 20, "Unsupported Joystick", anchor="center", bold=True, color=(255, 0, 0)) borderRect = pygame.Rect(0, 0, BAR_WIDTH + 10, BAR_HEIGHT + 5) borderRect.center = display.get_rect().center pygame.draw.rect(display, (100, 100, 100), borderRect, 1) barRect = borderRect.copy() barRect.h = BAR_HEIGHT barRect.center = borderRect.center barRect.x += 2 LastRefresh = 0 pygame.display.update() for data in os.walk(IMAGE_PATH): for collect_file in data[2]: if not collect_file.startswith("."): mx += 1 for data in os.walk(IMAGE_PATH): root = data[0] files = data[2] for collect_file in files: if not collect_file.startswith("."): num += 1 name = remove_extension(collect_file) img = pygame.image.load(root + os.sep + collect_file) store_img = True print( f"\rLoading image {colorize(num, 'blue' if num!=mx else 'green')} of {colorize(mx, 'green')} %s" % colorize(collect_file + (" " * (40 - len(collect_file))), 'bold'), flush=True, end="") if name.startswith("NoA_"): name = name.split("NoA_")[1] img = img.convert() elif (name.startswith("spinning") and not "RGBA" in name): img = img.convert() img.set_colorkey((0, 0, 0)) else: if not "animation" in root: if name.startswith("map_"): img = img.convert() else: img = img.convert_alpha() if name.startswith("ROT_"): name = name[4:] x = 0 for r in range(-90, 91): x += 1 names.append(name + str(int(r % 360))) images.append(pygame.transform.rotate(img, r)) if name.endswith("_sheet"): name = name.split("_sheet")[0] for e, surf in enumerate(extract_sprites(img)): names.append(name + str(e + 1)) images.append(surf) store_img = False if store_img: names.append(name) images.append(img) if time.time() - LastRefresh >= .025: LastRefresh = time.time() barRect.w = int((BAR_WIDTH * (num / mx)) * 10) / 10 color = pygame.color.Color(0) hue = lerp(HUE_BLUE, HUE_CYAN, num / mx) color.hsva = (hue, 100, 100, 100) pygame.draw.rect(display, color, barRect) for x in range(0, BAR_WIDTH, BAR_WIDTH // 10)[1:]: X_Val = barRect.x + x pygame.draw.line(display, (0, 0, 0), (X_Val, borderRect.y), (X_Val, borderRect.y + borderRect.h), 1) text, text_rect = retro_text(display.get_rect().move( 0, 30).center, display, 18, f"{round(num/mx*100)}%", anchor="center", eraseColor=(0, 0, 0)) pygame.display.update([barRect, text_rect]) # This makes pygame rerender the screen when the window is brought up for event in pygame.event.get(): pass print() return dict(zip(names, images)), num