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 __init__(self, display, images, money=[1, 1, 1, 1, [], 0, 0], mode="won"): self.display = display self.images = images self.mode = mode self.frame = 1 self.frame_time = 0 self.frame_rate = 1 / 25 self.time_passed = 0 self.anim_done = False self.done = False self.text = ["Save + Continue", "Save + Exit"] self.top_selected = True self.money_old, self.money_new, self.bonus, self.bonus1, self.acc, self.lost, self.maxcombo = money try: self.acc_per = self.acc.count(True) / len(self.acc) self.acc_per2 = round(self.acc_per * 100, 3) except ZeroDivisionError: self.acc_per = 0 self.acc_per2 = 0 self.money_new += round(self.bonus) self.money_new += round(self.bonus1 * self.acc_per) self.money_sound = Sound(fix_path("audio/money.wav")) self.register_sound = Sound(fix_path("audio/cashRegister.wav")) if mode == "won": self.money_sound.play(-1) self.exit = False self.stopped = False
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 __init__(self, pos, images, mission, dry=False): super().__init__(pos, images, mission, dry) self.title = "Jupiter Hovercraft" self.name = "jupiter_hover" self.fire_per_sec = 6.5 self.death_frames = 21 self.size = (32, 32) self.boom_size = (256, 256) self.fire_from = (24, 5) self.health = .75 self.max_health = .75 self.shield = 0 self.max_shield = 2 self.rect = self.get_rect() self.hover = True self.rotate = True self.mass = .75 self.max_temp = 500 self.hover_alt = 430 self.frame_rate = 1 / 35 self.extra_dip = 10 self.speed *= .8 self.friction = .5 self.send_to_ground() self.weapon_power = .75 self.death_sound = Sound(fix_path("audio/jupiter_hover_explode.wav"), True)
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 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 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 get_file(filename): if filename.startswith("data"): HOME = str(pathlib.Path().home()) DIR = fix_path( f"{HOME}/.interplanetary_invaders-data/") # Finds home directory if filename in ("data", fix_path("data/")): filename = "" else: filename = filename.replace(fix_path("data/"), "") if not os.path.exists(DIR): print(f"Building personal data directory:\n{DIR}") os.mkdir(DIR) return DIR + filename else: if DEV_RUN: # You're running this as a devolper return fix_path("interplanetary_invaders/" ) + filename # Find it in the current directory return resource_filename("interplanetary_invaders", filename) # Find it in the installation
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 purchase(self): cat = self.catagories[self.rect_sel] if not cat: Sound(fix_path("audio/donk.wav")).play() return selected = list(cat.keys())[self.sel_num[self.rect_sel]] selected.planet = self.profile["planet"].name if self.profile["money"] >= selected.cost: Sound(fix_path("audio/cashRegister.wav")).play() cat[selected] -= 1 if not cat[selected]: self.catagories[self.rect_sel].pop(selected) if self.sel_num[self.rect_sel] >= len(cat): self.sel_num[self.rect_sel] = len(cat) - 1 if selected in self.profile["inventory"][self.rect_sel]: self.profile["inventory"][self.rect_sel][selected] += 1 else: self.profile["inventory"][self.rect_sel][selected] = 1 if selected.type == "Vehicle": self.profile["inventory"][ self.rect_sel][selected] = self.profile["planet"].name self.profile["money"] -= selected.cost else: Sound(fix_path("audio/donk.wav")).play()
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, 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)
def __init__(self, center, images, mission, type="moneyBag", velocity=Vector2([0, 0]), amount=None, value=None, player=None, nobounce=False): self.images = images self.type = type self.size = (24, 24) self.physics = True self.player = player self.gotShot = False self.nobounce = nobounce self.max_lifetime = -1 if self.type == "moneyBag": self.size = (12, 16) if self.type == "rock": self.size = (20, 20) if self.type == "aircraft": self.physics = False self.size = (48, 48) if self.type == "mine": self.size = (32, 32) self.rect_size = self.size if self.type == "laser": self.size = (10, 32) self.rect_size = (10, 32) rect = pygame.Rect((0, 0), self.size) rect.center = center self.pos = list(rect.topleft) self.rect = rect self.time_passed = 0 self.frame = 1 self.frame_rate = 1 / 30 self.frame_time = 0 self.max_frame = 185 self.velocity = copy.copy(velocity) self.dead = False self.kill = False self.amount = amount self.jackpot = False self.mission = mission self.health = .1 self.has_touched_ground = False self.kaboom = False self.immune_to = None self.tracking = True self.update_attraction() if self.type == "block": self.max_frame = 30 if self.type == "moneyBag": self.max_frame = 13 self.frame_rate = 1 / 8 self.frame = random.randint(1, 13) self.frame_time = random.uniform(0, self.frame_rate) self.health = 1 global MoneySerialNumber self.ser_num = MoneySerialNumber MoneySerialNumber += 1 if self.type == "aircraft": self.depart = random.randint(0, 1) self.direction = random.randint(0, 1) if self.direction == 0: self.direction = -1 if self.depart == 0: self.depart = -1 self.frame_rate = 1 self.max_frame = 3 x = 0 y = 0 if self.direction == -1: x = SIZE[0] if self.depart == -1: y = self.mission.ground rect = self.get_rect() rect.center = (x, y) self.pos = list(rect.topleft) self.velocity = Vector2([1 * self.direction, .5 * self.depart ]) * 300 * random.uniform(.9, 1.1) self.jet_sound = Sound(fix_path("audio/jet.wav")) self.jet_sound.play(-1) if self.type == "mine": self.frame_rate = .5 self.max_frame = 3 self.health = 1 self.tracking = True self.max_lifetime = random.uniform(2.3, 2.8) if self.type == "laser": self.max_frame = 5 self.frame_rate = 0.01 self.physics = False self.velocity = Vector2([0, 1200]) self.value = value self.start_health = self.health self.life_bar = True self.hitBy = [] self.lifetime = 0 self.time_on_ground = 0
import os import pathlib from pkg_resources import resource_filename from interplanetary_invaders.scripts.utils import fix_path SOUND_PATH = fix_path("data/sound-cache/") DEV_RUN = os.path.abspath(".").endswith("interplanetary-invaders") def get_file(filename): if filename.startswith("data"): HOME = str(pathlib.Path().home()) DIR = fix_path( f"{HOME}/.interplanetary_invaders-data/") # Finds home directory if filename in ("data", fix_path("data/")): filename = "" else: filename = filename.replace(fix_path("data/"), "") if not os.path.exists(DIR): print(f"Building personal data directory:\n{DIR}") os.mkdir(DIR) return DIR + filename else: if DEV_RUN: # You're running this as a devolper return fix_path("interplanetary_invaders/" ) + filename # Find it in the current directory return resource_filename("interplanetary_invaders", filename) # Find it in the installation
def congrats(display, images, mode, data, profile=None): """Display a screen for awarding achievements / unlocking planets""" done = False pf = 1 pt = 0 pfr = 1 / 25 time_passed = 0 total_time_passed = 0 clock = pygame.time.Clock() if profile and mode == "ach": Sound(fix_path("audio/cashRegister.wav")).play() profile["money"] += data[2] profile["achievements"].append(data[0]) while not done: for event in pygame.event.get(): joystick.Update(event) if not hasattr(event, "key"): event.key = None if event.type == pygame.KEYDOWN or joystick.WasEvent(): if event.key in (pygame.K_RETURN, pygame.K_ESCAPE) or joystick.GoEvent( ) or joystick.BackEvent(): done = True if event.key == pygame.K_F2 or joystick.JustPressedLB(): screenshot.capture("_congrats", display) display.blit(images["background"], (0, 0)) if not mode == "store": retro_text((400, 100), display, 24, "Congratulations!", font="impact", anchor="center") stuff_rect = pygame.Rect(0, 0, 450, 350) if mode == "ach": stuff_rect.w *= 1.5 stuff_rect.midtop = (400, 90) stuff_surf = pygame.Surface(stuff_rect.size) stuff_surf.fill((255, 0, 255)) stuff_surf.set_alpha(50) display.blit(stuff_surf, stuff_rect) if mode == "planet" or mode == "store": rgba = "" if data.rgba: rgba = "RGBA" name = f"spinning{data.name}{rgba}{pf}" if not name in images: name = f"still_{data.name.lower()}" image = images[name] rect = pygame.Rect(0, 0, 100, 100) rect.center = (400, 200) display.blit(pygame.transform.scale(image, (100, 100)), rect) text = "" if not mode == "store": retro_text((400, 300), display, 14, f"You have unlocked Planet {data.name}", anchor="center") else: retro_text((400, 300), display, 14, f"Restocked Store on {data.name}", anchor="center") pt += time_passed if pt >= pfr: pf += 1 pt = 0 if pf > 25: pf = 1 if mode == "ach": # Short for achievement retro_text((400, 250), display, 17, f"{data[0]} Achievement Unlocked!", anchor="center", font="Sans") retro_text((400, 280), display, 15, data[1], anchor="center", bold=True, font="Sans") retro_text((400, 300), display, 15, f"Money Earned: {data[2]}", bold=True, font="Sans", anchor="center") if total_time_passed >= 15: done = True pygame.display.update() time_passed = clock.tick(60) / 1000 total_time_passed += time_passed
"""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(): click = False joystick.Update(event) if not hasattr(event, "key"): event.key = None if event.type == pygame.MOUSEBUTTONDOWN: if self.button_rect.collidepoint(pygame.mouse.get_pos()): click = True if event.type == pygame.KEYUP or joystick.WasEvent(): if event.key == pygame.K_y or joystick.JustPressedY(): cat = self.catagories[self.selected] sel = self.sel_num[self.selected] if self.selected != 2: item = list(cat.keys())[sel] else: item = cat[sel][1] if item: display_info(self.display, self.images, item) if event.type == pygame.KEYDOWN or joystick.WasEvent(): if event.key in (pygame.K_UP, pygame.K_w) or joystick.JustWentUp(): if not self.button_selected: self.selected -= 1 else: self.button_selected = False if event.key in (pygame.K_DOWN, pygame.K_s) or joystick.JustWentDown(): self.selected += 1 if self.selected < 0: self.selected = 0 if self.selected == len(self.rects): self.selected = len(self.rects) - 1 self.button_selected = True if (event.key in (pygame.K_LEFT, pygame.K_a) or joystick.JustWentLeft()) and not self.button_selected: self.sel_num[self.selected] -= 1 if (event.key in (pygame.K_RIGHT, pygame.K_d) or joystick.JustWentRight()) and not self.button_selected: self.sel_num[self.selected] += 1 if self.sel_num[self.selected] < 0: self.sel_num[self.selected] = 0 if self.sel_num[self.selected] == len( self.catagories[self.selected]): self.sel_num[self.selected] = len( self.catagories[self.selected]) - 1 if (event.key == pygame.K_RETURN or joystick.JustPressedA()) and not self.button_selected: cat = self.catagories[self.selected] lcat = list(cat) sel = self.sel_num[self.selected] didSomething = False if self.selected == 1: for x in self.catagories[2]: if x[1] == None: if not lcat: return didSomething = True x[1] = lcat[sel] if cat[lcat[sel]] == 1: cat.pop(lcat[sel]) break else: cat[lcat[sel]] -= 1 break if not didSomething: Sound(fix_path("audio/donk.wav")).play() if self.selected == 2 and cat[sel][1] != None: done = False for x in self.catagories[1]: if x == cat[sel][1]: self.catagories[1][x] += 1 done = True if not done: self.catagories[1][cat[sel][1]] = 1 cat[sel][1] = None if (event.key == pygame.K_RETURN or joystick.JustPressedA()) and self.button_selected: click = True if click and not self.cannotContinue(): self.done = True
from interplanetary_invaders.scripts.utils import fix_path from interplanetary_invaders.scripts.get_file import get_file, SOUND_PATH from interplanetary_invaders import __version__ import os, shutil, sys with open("README.md", "r") as fh: long_description = fh.read() def fmt(txt): return fix_path(txt.replace("interplanetary_invaders/", "") + "/*") img_data = [] for r, d, f in os.walk(fix_path("interplanetary_invaders/images/bitmap")): if not fmt(r) in img_data: img_data.append(fmt(r)) if "install" in sys.argv and __name__ == "__main__": if sys.platform == "linux" and not "sdist" in sys.argv and not os.getuid(): if os.path.exists("/usr/share/icons"): shutil.copyfile( "interplanetary_invaders/icon.png", "/usr/share/icons/interplanetary_invaders-icon.png") if os.path.exists("/usr/share/applications"): shutil.copyfile( "interplanetary_invaders/interplanetary_invaders.desktop", "/usr/share/applications/interplanetary_invaders.desktop") setup(
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)
def fmt(txt): return fix_path(txt.replace("interplanetary_invaders/", "") + "/*")
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