def __init__(self, display, images, options = False, simple = False): self.images = images self.display = display self.options_lock = options if options: self.background = display.copy() try: screenshot_count = len(os.listdir(fix_path(get_file("data/screenshots")))) except FileNotFoundError: screenshot_count = 0 s = "s" if screenshot_count == 1: s = "" self.options = ["Volume", "Cache Screenshots", f"Delete {screenshot_count} Screenshot{s}", "Stretch to Fullscreen", "Save", "Cancel"] self.DEL = f"Delete {screenshot_count} Screenshot{s}" self.options_dict = saves.load_options() self.profiles = ["Profile #1", "Profile #2", "Profile #3", "Profile #4", "Profile #5", "Back"] self.profile_selected = 0 self.pause_motion = False for e, p in enumerate(self.profiles[:-1]): if saves.load_profile(e)["new"]: self.profiles[e] = f"New Profile #{e + 1}" if simple: return if not options: if not os.path.exists(fix_path(get_file("data/menuStarsCache"))): for x in range(300): stars.main() with shelve.open(fix_path(get_file("data/menuStarsCache"))) as data: data["stars"] = stars.stars else: with shelve.open(fix_path(get_file("data/menuStarsCache"))) as data: stars.stars = data["stars"] pygame.mixer.music.stop() pygame.mixer.music.load(fix_path(get_file("audio/music/MainMenu.mp3"))) pygame.mixer.music.play(-1) self.frame = 1 self.frame_rate = 1 / 120 self.frame_time = 0 self.finished = False self.time_passed = 0 self.star_rotation = 0 self.rotation_speed = 20 self.done = False self.item_selected = 0 self.items = ["Play", "Options", "Credits", "Quit"] self.play_mode = False self.options_mode = options self.option_selected = 0 self.text_time = 0 self.text_rate = 0.1 self.text = "Interplanetary Invaders" self.bool_images = [self.images["x"], self.images["check"]]
def confirm_delete(self): stuff_rect = pygame.Rect(0, 0, 300, 400) stuff_rect.center = self.display.get_rect().center options = ["No", "Yes"] sel = 0 done = False while not done: for event in pygame.event.get(): joystick.Update(event) if event.type == pygame.KEYDOWN or joystick.WasEvent(): if not hasattr(event, "key"): event.key = None if event.key in (pygame.K_UP, pygame.K_w) or joystick.JustWentUp(): sel = 0 if event.key in (pygame.K_DOWN, pygame.K_s, pygame.K_x) or joystick.JustWentDown(): sel = 1 if event.key == pygame.K_TAB: sel = not sel if event.key == pygame.K_RETURN or joystick.JustPressedA(): if sel: os.remove(fix_path(get_file(f"data/profile{self.profile_selected}"))) self.profiles[self.profile_selected] = f"New Profile #{self.profile_selected + 1}" self.pause_motion = True done = True if not self.options_lock: self.draw_stars() self.draw_menu_box(stuff_rect) self.draw_items(options, sel, stuff_rect) retro_text(stuff_rect.move(0, 5).midtop, self.display, 14, "Are you sure you want", anchor="midtop") retro_text(stuff_rect.move(0, 20).midtop, self.display, 14, f"to erase Profile #{self.profile_selected + 1}?", anchor="midtop") pygame.display.update()
def __init__(self, filename, no_slow=False): self.original_filename = filename filename = get_file(filename) global is_slow if not no_slow and is_slow: filename = SlowDownSound(filename) super().__init__(filename) self.set_volume(options["volume"])
def retro_text(pos, display, size, text, font="monospace", color=(255, 255, 255), italic=False, bold=False, AA=False, underline=False, anchor="topleft", render=True, res=13, smooth=False, eraseColor=None): if len(FONT_CACHE) > MAX_FONTS: FONT_CACHE.clear() font = font.lower() checksum = font_checksum(size, font, italic, bold, underline) if checksum in FONT_CACHE: rfont = FONT_CACHE[checksum] else: if os.path.exists(get_file(fix_path("fonts/" + font + ".ttf"))): rfont = pygame.font.Font(get_file(fix_path(f"fonts/{font}.ttf")), res) else: rfont = pygame.font.SysFont(font, res) rfont.set_italic(italic) rfont.set_bold(bold) rfont.set_underline(underline) FONT_CACHE[checksum] = rfont Text = rfont.render(str(text), AA, color) scale = pygame.transform.scale if smooth: scale = pygame.transform.smoothscale Text = pygame.transform.scale(Text, (int(Text.get_width() * (size / 8)), size)) TextRect = Text.get_rect() setattr(TextRect, anchor, pos) if render: if eraseColor: pygame.draw.rect(display, eraseColor, TextRect) display.blit(Text, TextRect) return Text, TextRect
def __init__(self, images, display, profile, profile_number, point=None): self.images = images self.display = display self.profile = profile self.done = False self.planet = profile["planet"] self.time_passed = 0 try: self.map = profile["map"][self.planet.name] except: self.map = [ MapPoint((400, 300), "Landing Zone", type=None), MapPoint((450, 300), f"Spaceport {self.planet.name}", type="spaceport") ] if point == None: point = profile["points"][self.planet.name] if point >= len(self.map): point = len(self.map) - 1 self.selected_point = point self.old_selected_point = point self.avatar_frame = 1 self.frame_rate = 1 / 6 self.frame_time = 0 self.avatar_frames = 2 self.avatar_idle_frame = 1 self.idle_frame_rate = 2 / 3 self.idle_frame_time = 0 self.avatar_pos = self.get_point(self.selected_point) self.target_pos = copy.copy(self.avatar_pos) self.target_pos = self.get_point(point) self.set_velocity() self.waypoints = [] self.clock = pygame.time.Clock() self.text_yellow = False self.text_rate = 1 / 5 self.text_time = 0 self.profile_number = profile_number self.toMenu = False self.base_rect = pygame.Rect(0, 0, 300, 50) self.base_rect.midbottom = display.get_rect().midbottom self.prev_dist = self.get_dist(self.avatar_pos, self.target_pos) self.pause_time = False self.ForwardOrBack = False self.ForwardOrBack2 = False self.click = False self.last_hit_point = point self.avatar_speed = 200 self.changed = False if self.planet.has_music: pygame.mixer.music.load(get_file(fix_path(self.planet.music_file))) pygame.mixer.music.play(-1)
def run_credits(display, images): # pygame.mixer.music.stop() pygame.mixer.music.load(get_file(fix_path("audio/music/Credits.ogg"))) pygame.mixer.music.play(-1) clock = pygame.time.Clock() done = False text = [] time_passed = 0 for e, x in enumerate(credits_text.split("\n")): text.append(list(retro_text((400, 24 * e + 10), display, 14, x, font = "sans", anchor = "midtop", res = 11))) scroll = -600 scroll_rate = 55 total_length = 1400 while not done: for event in pygame.event.get(): joystick.Update(event) if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key in (pygame.K_RETURN, pygame.K_ESCAPE): done = True if joystick.BackEvent() or joystick.JustPressedA(): done = True if scroll > total_length: done = True display.blit(images["background"], (0, 0)) for line in text: if line[1][1] - scroll < 100: if line[0].get_width() <= 3: text.remove(line) continue s1 = line[0].get_width() if line[1][1] - scroll > 90: s1 *= 1.025 else: s1 /= 1.03 line[0] = pygame.transform.scale(line[0], (round(s1), line[0].get_height())) r2 = pygame.Rect((0, 0), line[0].get_size()) r2.center = line[1].center line[1] = r2 display.blit(line[0], (line[1][0], line[1][1] - scroll)) img = images["nachomonkeylogo"] img_rect = img.get_rect() img_rect.centerx = display.get_width() // 2 img_rect.top = total_length - img_rect.height - scroll - 10 display.blit(img, img_rect) scroll += scroll_rate * time_passed pygame.display.update() time_passed = clock.tick(60) / 1000 pygame.mixer.music.stop()
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 = []
"""Autoloader gets images from IMAGE_PATH and puts in in a dictionary""" import sys import os import time import pygame from interplanetary_invaders.scripts.get_file import get_file from interplanetary_invaders.scripts.utils import colorize, fix_path from interplanetary_invaders.scripts.retro_text import retro_text from interplanetary_invaders.scripts import joystick from interplanetary_invaders import __version__ IMAGE_PATH = get_file(fix_path("images/bitmap/")) BAR_WIDTH = 200 BAR_HEIGHT = 30 def remove_extension(filename): """Remove the extension from a filename string""" return filename[:filename.index(".")] 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")
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 __init__(self, display, images, profile, profile_selected, map_point): self.display = display self.images = images self.profile = profile self.profile_selected = profile_selected center = display.get_rect().center self.main_rect = pygame.Rect(0, 0, 750, 550) self.main_rect.center = center self.list_rect = pygame.Rect(0, 0, 730, 300) self.list_rect.midbottom = self.main_rect.move(0, -10).midbottom self.buy_rect = pygame.Rect(0, 0, 355, 290) self.buy_rect.topleft = self.list_rect.move(5, 5).topleft self.inv_rect = self.buy_rect.copy() self.inv_rect.topleft = self.buy_rect.move(5, 0).topright self.item_rects = [self.buy_rect, self.inv_rect] self.items_rect = pygame.Rect(0, 0, 200, 40) self.items_rect.topright = self.main_rect.move(-5, 5).topright self.missiles_rect = self.items_rect.copy() self.missiles_rect.topleft = self.items_rect.move(0, 4).bottomleft self.licenses_rect = self.items_rect.copy() self.licenses_rect.topleft = self.missiles_rect.move(0, 4).bottomleft self.vehicles_rect = self.items_rect.copy() self.vehicles_rect.topleft = self.licenses_rect.move(0, 4).bottomleft self.drones_rect = self.items_rect.copy() self.drones_rect.topleft = self.vehicles_rect.move(0, 4).bottomleft self.money_rect = self.items_rect.copy() self.money_rect.w *= 1.35 self.money_rect.midbottom = self.inv_rect.move(0, -10).midbottom self.data_rect = pygame.Rect(0, 0, 450, 225) self.data_rect.topleft = self.main_rect.move(5, 5).topleft self.rects = [ self.items_rect, self.missiles_rect, self.licenses_rect, self.vehicles_rect, self.drones_rect ] self.rect_names = [ "Items", "Missiles", "Licenses", "Vehicles", "Drones" ] self.rect_sel = 0 self.done = False self.clock = pygame.time.Clock() self.items = store_data.getStuff("items", profile) self.missiles = {} self.licenses = store_data.getStuff("licenses", profile) self.vehicles = store_data.getStuff("vehicles", profile) self.drones = {} self.mapPoint = map_point if not hasattr(self.mapPoint, "store_data"): self.catagories = [ self.items, self.missiles, self.licenses, self.vehicles, self.drones ] self.mapPoint.store_data = self.catagories else: if self.mapPoint.store_data: self.catagories = self.mapPoint.store_data else: self.catagories = [ self.items, self.missiles, self.licenses, self.vehicles, self.drones ] self.mapPoint.store_data = self.catagories self.sel_num = [0, 0, 0, 0, 0] self.purchase_rect = pygame.Rect(0, 0, 175, 50) self.purchase_rect.midbottom = self.buy_rect.move(0, -5).midbottom self.exit_rect = pygame.Rect(0, 0, 275, 50) self.exit_rect.midbottom = self.purchase_rect.move(0, -5).midtop pygame.mixer.music.load(get_file(fix_path("audio/music/Store.ogg"))) pygame.mixer.music.play(-1)
import os import wave import pygame pygame.init() from interplanetary_invaders import __version__ as ver from interplanetary_invaders.scripts import saves from interplanetary_invaders.scripts.get_file import get_file, SOUND_PATH from interplanetary_invaders.scripts.utils import fix_path options = saves.load_options() is_slow = False SOUND_PATH = get_file(SOUND_PATH) if not os.path.exists(SOUND_PATH): os.mkdir(SOUND_PATH) versionFile = SOUND_PATH + "version" if os.path.exists(versionFile): with open(versionFile) as file: if file.read() != ver: for f in os.listdir(SOUND_PATH): if f != "version": os.remove(SOUND_PATH + f) with open(versionFile, "w") as file: file.write(ver)
import os import pygame import time import copy from interplanetary_invaders.scripts.retro_text import retro_text from interplanetary_invaders.scripts.sound import Sound from interplanetary_invaders.scripts.utils import fix_path, colorize from interplanetary_invaders.scripts.get_file import get_file from interplanetary_invaders.scripts import saves directory = get_file(fix_path("data/screenshots")) pygame.init() sound = Sound(fix_path("audio/click.wav")) options = saves.load_options() save_for_later = {} FirstScreenshot = True 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)
import shelve import os from copy import deepcopy from interplanetary_invaders.scripts.get_file import get_file from interplanetary_invaders.scripts.utils import fix_path debugMode = True DATA_PATH = "data/" DATA_PATH = get_file(DATA_PATH) if not os.path.exists(DATA_PATH): os.mkdir(DATA_PATH) if debugMode: print(f"Directory \"{DATA_PATH}\" found missing!") def load_profile(index): profile = {} if debugMode: if not os.path.exists(f"{DATA_PATH}/profile{index}"): print(f"Profile {index} missing!") with shelve.open(f"{DATA_PATH}/profile{index}") as data: profile["money"] = data.get("money", 0) profile["hiscore"] = data.get("hiscore", 0) profile["moons_locked"] = data.get("moons_locked", True) profile["exoplanets_locked"] = data.get("exoplanets_locked", True) profile["planet"] = data.get("planet", planets.Earth) profile["new"] = data.get("new", True)