def create_stars(ai_settings, screen, stars): #MY CODE for star_number in range(ai_settings.amount_of_stars): star = Star(ai_settings, screen) stars.add(star)
def create_star(self, pos_x, pos_y): star = Star(self) star.rect.x, star.rect.y = pos_x, pos_y self.my_stars.add(star)
from star import Star from gpiozero.tools import random_values from signal import pause import requests import schedule import datetime star = Star(pwm=True) leds = star.leds temp = 10 def get_temp(): base_url = "https://api.darksky.net/forecast/" key = "211b3687d8ca6996aa8aa64713a8a2be" lat = "53.1457525" long = "-0.754067" payload = { "exclude": "minutely, hourly, daily, alerts, flags", "units": "uk2" } url = base_url + key + "/" + lat + "," + long r = requests.get(url, params=payload) data = r.json() global temp temp = float(data["currently"]["temperature"]) schedule.every().hour.do(get_temp)
def create_stars(ai_settings, screen, stars, images): number_stars_x = ai_settings.stars_allowed for star_amount in range(number_stars_x): if len(stars) < number_stars_x: star = Star(ai_settings, screen, images) stars.add(star)
def create_stars(ai_settings, screen, stars): """Создает звёзды.""" while len(stars) < ai_settings.stars_allowed: new_star = Star(ai_settings, screen) stars.add(new_star)
from star import Star from time import sleep star = Star() try: star.inner.on() while True: star.toggle() sleep(.5) except KeyboardInterrupt: star.close()
def addGroupStars(setting, screen, stars): for number in range(1, setting.star_number): myStar = Star(setting, screen) myStar.rect.x = myStar.getRandomPosition() myStar.rect.y = myStar.getRandomPosition() stars.add(myStar)
def test_ecosphere_radius(): assert Star(0.5).ecosphere_radius() == 0.25 assert round(Star(2).ecosphere_radius(), 2) == 4.12
def test_greenhouse_radius(): assert Star(0.5).greenhouse_radius() == 0.2325
def test_stellar_dust_limit(): assert round(Star(1.0).stellar_dust_limit()) == 200.0 assert round(Star(1.5).stellar_dust_limit()) == 229.0
def test_main_sequence_life(): assert round(Star(1.0).main_sequence_life()) == 1e10 assert round(Star(0.5).main_sequence_life()) == 80000000000 assert round(Star(1.5).main_sequence_life()) == 2962962963
def test_luminosity_ratio(): assert round(Star(0.5).luminosity_ratio(), 3) == 0.062 assert round(Star(0.75).luminosity_ratio(), 3) == 0.316 assert Star(1.0).luminosity_ratio() == 1.0 assert round(Star(1.5).luminosity_ratio(), 3) == 5.062 assert round(Star(2.0).luminosity_ratio(), 3) == 16.971
def add_star(self): """Add a star.""" self.stars += [Star(self.max_x)]
def create_stars(ai_settings, screen): stars = pygame.sprite.Group() for i in range(ai_settings.stars_limit): new_star = Star(ai_settings, screen) stars.add(new_star) return stars
def create_star(_): x = randint(0, width) y = randint(0, height) return Star(settings, (x, y))
from glob import glob from star import Star import matplotlib.pyplot as plt star = Star('/media/connor/Lore/ultramag/steve_5899_v2/star_059185383.txt') fig, (ax1, ax2) = plt.subplots(2, 1, figsize=[10, 10]) ax1.errorbar(star.data['mjd'], star.data['evry_mag'], yerr=star.data['evry_err'], fmt='o', ms=2) star.filter() ax2.errorbar(star.data['mjd'], star.data['evry_mag'], yerr=star.data['evry_err'], fmt='o', ms=2) ax1.set_title('Unfiltered Magnitude v. MJD') ax2.set_title('Flags and 10% Highest Error Thrown Out') ax1.set_xlabel('MJD') ax1.set_ylabel('EvryScope Magnitude') ax2.set_xlabel('MJD') ax2.set_ylabel('EvryScope Magnitude') plt.subplots_adjust(top=0.926, bottom=0.121, left=0.17, right=0.971, hspace=0.511, wspace=0.2) plt.show()
def show(self): if self._first: self.surface = self._background.copy() drawText(self.surface, "Poziom %d(0%%)..." % self._engine.game['level'], 48, (255, 255, 255), (self._resx / 2, self._resy / 2)) self._engine.show(self.surface) count = 0 planets = random.randint(1, min(self._engine.game['level'] * 2, 8)) stars = random.randint(self._engine.game['level'], self._engine.game['level'] * 5) canisters = random.randint(0, self._engine.game['level']) whole = (planets + stars + canisters + 1) * 0.01 try: for _ in xrange(planets): self.planets.add( Planet( random.randint(planet.MIN_MASS, planet.MAX_MASS), randomPlace([p for p in self.planets], 100, (self._resx, self._resy)))) count += 1 self.surface = self._background.copy() drawText( self.surface, "Poziom %d(%d%%)..." % (self._engine.game['level'], count / whole), 48, (255, 255, 255), (self._resx / 2, self._resy / 2)) self._engine.show(self.surface) except NoMore: pass try: for _ in xrange(stars): self.stars.add( Star( randomPlace([p for p in self.planets] + [s for s in self.stars], 16, (self._resx, self._resy)))) count += 1 self.surface = self._background.copy() drawText( self.surface, "Poziom %d(%d%%)..." % (self._engine.game['level'], count / whole), 48, (255, 255, 255), (self._resx / 2, self._resy / 2)) self._engine.show(self.surface) except NoMore: pass try: for _ in xrange(canisters): self.canisters.add( Canister( randomPlace([p for p in self.planets] + [s for s in self.stars] + [c for c in self.canisters], 16, (self._resx, self._resy)))) count += 1 self.surface = self._background.copy() drawText( self.surface, "Poziom %d(%d%%)..." % (self._engine.game['level'], count / whole), 48, (255, 255, 255), (self._resx / 2, self._resy / 2)) self._engine.show(self.surface) except NoMore: pass self.rocket.add( Rocket( self._engine, self, randomPlace([p for p in self.planets], 48, (self._resx, self._resy)))) count += 1 self.surface = self._background.copy() drawText( self.surface, "Poziom %d(%d%%)..." % (self._engine.game['level'], count / whole), 48, (255, 255, 255), (self._resx / 2, self._resy / 2)) self._engine.show(self.surface) self._first = False try: while self._engine.tick(): for event in pygame.event.get(): if event.type == QUIT: self._engine.quit() if event.type == KEYUP and event.key == K_ESCAPE: raise Pause() if event.type == KEYUP and event.key == K_q: if self._engine.game['godmode']: self._engine.game['godmode'] = False self._engine.game['godlevel'] = self._engine.game[ 'level'] if self._engine.state & engine.STATE_END: self.surface.fill((0, 0, 0)) drawText( self.surface, "Gratulacje! Twoj wynik: %d!" % self._engine.game['score'], 50, (0, 140, 0), (self._resx / 2, self._resy / 2)) self._engine.show(self.surface) continue if len(self.stars) == 0: raise NextLevel() if self._engine.game['life'] <= 0 or not self._engine.game[ 'fuel']: raise GameEnd() self.surface = self._background.copy() self.planets.update() self.stars.update() self.canisters.update() self.rocket.update() self._hub.update() self.planets.draw(self.surface) self.stars.draw(self.surface) self.canisters.draw(self.surface) self.rocket.draw(self.surface) self._hub.draw(self.surface) self._engine.show(self.surface) except Pause: self._engine.state ^= engine.STATE_GAME | engine.STATE_MENU except GameEnd: self._engine.state |= engine.STATE_END except NextLevel: self._engine.nextLevel()
import pygame from star import Star WIN_WIDTH = 800 WIN_HEIGHT = 800 run = True display = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) stars = [] for i in range(0, 300): stars.append(Star(WIN_WIDTH, WIN_HEIGHT)) while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False display.fill((0, 0, 0)) for star in stars: star.update() star.draw(display) pygame.display.update() pygame.quit()
parser.add_argument('-s', '--scale', action='store_true') args = parser.parse_args() nstars = int(args.nstars) nbins = int(args.nbins) scale = bool(args.scale) colors = plt.rcParams['axes.prop_cycle'].by_key()['color'][:7] filenames = glob('/media/connor/Lore/ultramag/steve_5899_v2/star_0*.txt') stars = [] print('\nLoading stars...') pb = ProgressBar(len(filenames[:nstars])) for i, filename in enumerate(filenames[:nstars]): star = Star(filename) if star.data is not None: star.filter() stars.append(star) pb.update() fig, ax1 = plt.subplots(1, 1, figsize=[10, 10]) print('\nSplitting data into nights and plotting...') pb = ProgressBar(len(stars)) all_times = [] all_mags = [] for i, star in enumerate(stars): nights = star.split_nights()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from star import Star # Creo una instancia de estrella altair = Star("Altair") print("Nombre: ", altair.name) altair.set_par(0.195) altair.get_star_number()
def main(): def create_particles(number, x, y, image): for count in range(number): for particle_count in range(MAX_PARTICLES): if particles[particle_count].active == False: particles[particle_count].active = True particles[particle_count].image = image particles[particle_count].rect.left = x particles[particle_count].rect.top = y # Bigger number == bigger range explosion if number > 15: particles[particle_count].move_count = random.randint( 20, 30) else: particles[particle_count].move_count = random.randint( 10, 17) if random.randint(0, 10) > 5: particles[ particle_count].vector_x = 0 - random.randint( 0, 4) particles[ particle_count].vector_y = 0 - random.randint( 0, 4) else: particles[particle_count].vector_x = random.randint( 0, 4) particles[particle_count].vector_y = random.randint( 0, 4) break # Some constants SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 FPS = 60 STARS = 18 PLAYER_BULLETS = 40 MAX_BADDIES = 15 MAX_UFOS = 1 MAX_BADDIE_BULLETS = 30 MAX_PARTICLES = 200 TITLE_SCREEN_MODE = 2 GAME_MODE = 1 high_score = 750000 beaten_high_score = False # Some game control stuff attack_timer = 0 attack_max = 70 ufo_attack_timer = 0 ufo_attack_max = 500 max_baddie_speed = 2 max_ufo_speed = 2 show_smiley = False game_wave = 1 baddies_killed = 0 wave_break = 100 wave_target_kills = 50 game_over = False game_over_timer = 500 game_victory = False game_victory_particle_timer = 0 game_mode = TITLE_SCREEN_MODE baddie_fire_timer = 0 baddie_fire_max = 50 title_freeplay_timer = 0 title_freeplay_on = False title_menu_choice = 0 # Init the pygame library and sort the display pygame.init() screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) pygame.display.set_caption("CrossFire") clock = pygame.time.Clock() # Show loading message... game_font = pygame.font.Font(os.path.join("data", "04b_25__.ttf"), 18) screen.fill((0, 0, 0)) screen.blit(game_font.render("Loading....", 0, ((176, 0, 0))), (270, SCREEN_HEIGHT / 2 - 36)) pygame.display.flip() # Sort the sound driver pygame.mixer.quit() sound = pygame.mixer.init() player_shoot_sound = pygame.mixer.Sound(os.path.join("data", "lazer1.wav")) ufo_sound = pygame.mixer.Sound(os.path.join("data", "ufo.wav")) ufo_sound.set_volume(0.35) baddie_shoot_sound = pygame.mixer.Sound(os.path.join("data", "shoot2.wav")) wave_sound = pygame.mixer.Sound(os.path.join("data", "newwave.wav")) baddie_splosion = pygame.mixer.Sound(os.path.join("data", "explode1.wav")) player_boom_1 = pygame.mixer.Sound(os.path.join("data", "damage.wav")) player_boom_2 = pygame.mixer.Sound(os.path.join("data", "player_dead.wav")) menu_move_sound = pygame.mixer.Sound(os.path.join("data", "menu_move.wav")) exit_sound = pygame.mixer.Sound(os.path.join("data", "exit.wav")) start_sound = pygame.mixer.Sound(os.path.join("data", "start.wav")) win_sound = pygame.mixer.Sound(os.path.join("data", "win.wav")) # Load the gfx in invader_image = pygame.image.load(os.path.join("data", "invader.png")).convert() redinvader_image = pygame.image.load(os.path.join( "data", "redthing.png")).convert() drone_image = pygame.image.load(os.path.join("data", "thingy.png")).convert() ufo_image = pygame.image.load(os.path.join("data", "ufo.png")).convert() player_bullet_image = pygame.image.load(os.path.join( "data", "bullet1.png")).convert() game_font = pygame.font.Font(os.path.join("data", "04b_25__.ttf"), 18) game_font_large = pygame.font.Font(os.path.join("data", "04b_25__.ttf"), 36) game_font_xl = pygame.font.Font(os.path.join("data", "04b_25__.ttf"), 46) baddie_bullet_image = pygame.image.load(os.path.join( "data", "bullet2.png")).convert() player_health_image = pygame.Surface((8, 16)) player_health_image.fill((176, 0, 0)) # Create some particle images red_particle_image = pygame.Surface((8, 8)) red_particle_image.fill((176, 0, 0)) green_particle_image = pygame.Surface((8, 8)) green_particle_image.fill((31, 92, 14)) blue_particle_image = pygame.Surface((8, 8)) blue_particle_image.fill((46, 102, 187)) gray_particle_image = pygame.Surface((8, 8)) gray_particle_image.fill((88, 88, 88)) yellow_particle_image = pygame.Surface((8, 8)) yellow_particle_image.fill((255, 206, 0)) # Setup the player objects player_bottom = PlayerBottom(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH / 2, SCREEN_HEIGHT - 35) player_side = PlayerSide(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_WIDTH - 35, SCREEN_HEIGHT / 2) player_fire_rate = 5 player_fire_delay_left = 0 player_fire_delay_right = 0 player_score = 0 player_shield = 9 player_flash_timer = 0 player_flash_on = False # Prepare the player pointed projectiles! player_bullets = [] for count in range(PLAYER_BULLETS): player_bullets.append( Projectile(SCREEN_WIDTH, SCREEN_HEIGHT, player_bullet_image)) player_bullets[count].active = False # Baddie bullets baddie_bullets = [] for count in range(MAX_BADDIE_BULLETS): baddie_bullets.append( Projectile(SCREEN_WIDTH, SCREEN_HEIGHT, baddie_bullet_image)) baddie_bullets[count].active = False # Setup the starfield stars = [] for count in range(STARS / 3): stars.append( Star(SCREEN_WIDTH, SCREEN_HEIGHT, random.randint(0, SCREEN_WIDTH), random.randint(0, SCREEN_HEIGHT), 4, (175, 175, 175))) for count in range(STARS / 3): stars.append( Star(SCREEN_WIDTH, SCREEN_HEIGHT, random.randint(0, SCREEN_WIDTH), random.randint(0, SCREEN_HEIGHT), 3, (88, 88, 88))) for count in range(STARS / 3): stars.append( Star(SCREEN_WIDTH, SCREEN_HEIGHT, random.randint(0, SCREEN_WIDTH), random.randint(0, SCREEN_HEIGHT), 1, (88, 88, 88))) # Prepare the various baddies (max of 9 each) invaders = [] red_invaders = [] drones = [] for count in range(MAX_BADDIES): # Green invaders invaders.append(Baddie(SCREEN_WIDTH, SCREEN_HEIGHT, invader_image)) invaders[count].rect.top = 0 invaders[count].rect.left = 0 invaders[count].vector_x = 0 invaders[count].vector_y = 0 invaders[count].active = False invaders[count].anim_max_frame = 3 invaders[count].movement_type = 0 # Red invaders red_invaders.append( Baddie(SCREEN_WIDTH, SCREEN_HEIGHT, redinvader_image)) red_invaders[count].rect.top = 0 red_invaders[count].rect.left = 0 red_invaders[count].vector_x = 0 red_invaders[count].vector_y = 0 red_invaders[count].active = False red_invaders[count].anim_max_frame = 3 red_invaders[count].movement_type = 0 # Drone things drones.append(Baddie(SCREEN_WIDTH, SCREEN_HEIGHT, drone_image)) drones[count].rect.top = 0 drones[count].rect.left = 0 drones[count].vector_x = 0 drones[count].vector_y = 0 drones[count].active = False drones[count].anim_max_frame = 3 drones[count].movement_type = 1 ufos = [] for count in range(MAX_UFOS): ufos.append(Baddie(SCREEN_WIDTH, SCREEN_HEIGHT, ufo_image)) ufos[count].anim_max_frame = 9 # Setup particles particles = [] for count in range(MAX_PARTICLES): particles.append( Particle(SCREEN_WIDTH, SCREEN_HEIGHT, red_particle_image)) particles[count].active = False # Here we go..... main loop time # ------------------------------ main_loop = True baddies_onscreen = False while main_loop: # Clear the screen (NOTE: This is not particularly efficient, but deadline is looming!) screen.fill((0, 0, 0)) # Process the stars for count in range(STARS): stars[count].update() screen.blit(stars[count].image, stars[count].rect) # Are we in game or at the title screen? if game_mode == TITLE_SCREEN_MODE: ##################### # TITLE SCREEN MODE # ##################### screen.blit(game_font_xl.render("CrossFire", 0, ((255, 206, 0))), (230, 100)) # Toggle little 'insert coin' message. It was originally 'Freeplay Mode' but I liked 'insert coin' more :) title_freeplay_timer += 1 if title_freeplay_timer > 30: title_freeplay_timer = 0 if title_freeplay_on == True: title_freeplay_on = False else: title_freeplay_on = True if title_freeplay_on == True: screen.blit( game_font.render("Insert Coin", 0, ((175, 175, 175))), (280, 380)) if title_menu_choice == 0: screen.blit(game_font.render("Start", 0, ((255, 206, 0))), (300, 225)) else: screen.blit(game_font.render("Start", 0, ((176, 0, 0))), (300, 225)) if title_menu_choice == 1: screen.blit(game_font.render("Exit", 0, ((255, 206, 0))), (308, 250)) else: screen.blit(game_font.render("Exit", 0, ((176, 0, 0))), (308, 250)) screen.blit( game_font.render( "Z and X to fire, cursor keys control both ships", 0, ((176, 0, 0))), (120, 450)) for event in pygame.event.get(): if event.type == pygame.QUIT: main_loop = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: menu_move_sound.play() title_menu_choice -= 1 if title_menu_choice < 0: title_menu_choice = 0 if event.key == pygame.K_DOWN: title_menu_choice += 1 menu_move_sound.play() if title_menu_choice > 1: title_menu_choice = 1 if event.key == pygame.K_ESCAPE: main_loop = False if event.key == pygame.K_z or event.key == pygame.K_x or event.key == pygame.K_SPACE or event.key == pygame.K_RETURN: if title_menu_choice == 0: # Start new game... reset values to defaults start_sound.play() attack_timer = 0 attack_max = 90 ufo_attack_timer = 0 ufo_attack_max = 500 max_baddie_speed = 2 max_ufo_speed = 2 show_smiley = False game_wave = 1 beaten_high_score = False baddies_killed = 0 wave_break = 100 wave_target_kills = 30 game_over = False game_over_timer = 500 game_mode = GAME_MODE game_victory = False game_victory_particle_timer = 0 baddie_fire_timer = 0 baddie_fire_max = 50 player_fire_rate = 5 player_fire_delay_left = 0 player_fire_delay_right = 0 player_score = 0 player_shield = 9 player_flash_timer = 0 player_flash_on = False # Make sure all the baddies, bullets and particles are deactivated for count in range(MAX_BADDIES): invaders[count].active = False red_invaders[count].active = False drones[count].active = False for count in range(PLAYER_BULLETS): player_bullets[count].active = False for count in range(MAX_UFOS): ufos[count].active = False for count in range(MAX_BADDIE_BULLETS): baddie_bullets[count].active = False for count in range(MAX_PARTICLES): particles[count].active = False if title_menu_choice == 1: exit_sound.play() main_loop = False else: ############# # GAME MODE # ############# # Grab all of the events and search for ones we are interested in, such as keyboard presses for event in pygame.event.get(): if event.type == pygame.QUIT: main_loop = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: game_mode = TITLE_SCREEN_MODE # Has bottom player fired? if event.key == pygame.K_z and player_fire_delay_left > player_fire_rate and game_over == False: # Pop off a few projectiles... for count in range(PLAYER_BULLETS): if (player_bullets[count].active == False ): # Find a 'free' bullet for the bottom ship player_bullets[count].active = True player_bullets[ count].rect.top = player_bottom.rect.top player_bullets[ count].rect.left = player_bottom.rect.left + 12 player_bullets[count].vector_x = 0 player_bullets[count].vector_y = -9 player_fire_delay_left = 0 player_shoot_sound.play() break # Has side player fired if event.key == pygame.K_x and player_fire_delay_right > player_fire_rate and game_over == False: for count in range(PLAYER_BULLETS): if (player_bullets[count].active == False): player_bullets[count].active = True player_bullets[ count].rect.top = player_side.rect.top + 12 player_bullets[ count].rect.left = player_side.rect.left player_bullets[count].vector_x = -9 player_bullets[count].vector_y = 0 player_fire_delay_right = 0 player_shoot_sound.play() break if event.key == pygame.K_F9: show_smiley = True if show_smiley: screen.blit(game_font_large.render("c:)", 0, ((255, 0, 0))), (SCREEN_WIDTH / 2, 10)) # Manage baddie creation... attack_timer += 1 ufo_attack_timer += 1 # Time for an attack? if attack_timer > attack_max and wave_break < 1 and baddies_killed < wave_target_kills and game_over == False: # Time for a new attack formation from the side... how many free baddies are there? attack_timer = 0 # Which baddie? Pick randomly... 0 = Green Invader, 1 = Drone, 2 = Red Invader if game_wave > 2: baddie_type = random.randint(0, 2) else: baddie_type = random.randint(0, 1) direction = random.randint(0, 1) if baddie_type == 0: for count in range(MAX_BADDIES): if invaders[count].active == False: if direction == 0: # from left invaders[count].rect.left = -32 invaders[count].rect.top = random.randint( 0, (SCREEN_HEIGHT - 64) / 32) * 32 invaders[count].vector_x = max_baddie_speed invaders[count].vector_y = 0 invaders[count].active = True break else: # from top invaders[count].rect.left = random.randint( 0, (SCREEN_WIDTH - 64) / 32) * 32 invaders[count].rect.top = -32 invaders[count].vector_x = 0 invaders[count].vector_y = max_baddie_speed invaders[count].active = True break elif baddie_type == 1: for count in range(MAX_BADDIES): if drones[count].active == False: if direction == 0: # from left drones[count].rect.left = -32 drones[count].rect.top = random.randint( 0, (SCREEN_HEIGHT - 64) / 32) * 32 drones[count].vector_x = max_baddie_speed drones[count].vector_y = 0 drones[count].active = True drones[count].movement_type = 2 break else: # from top drones[count].rect.left = random.randint( 0, (SCREEN_WIDTH - 64) / 32) * 32 drones[count].rect.top = -32 drones[count].vector_x = 0 drones[count].vector_y = max_baddie_speed drones[count].active = True drones[count].movement_type = 1 break elif baddie_type == 2: for count in range(MAX_BADDIES): if red_invaders[count].active == False: if direction == 0: # from left red_invaders[count].rect.left = -32 red_invaders[count].rect.top = random.randint( 0, (SCREEN_HEIGHT - 64) / 32) * 32 red_invaders[count].vector_x = max_baddie_speed red_invaders[count].vector_y = random.randint( 0, 1) - random.randint(0, 1) red_invaders[count].active = True break else: # from top red_invaders[count].rect.left = random.randint( 0, (SCREEN_WIDTH - 64) / 32) * 32 red_invaders[count].rect.top = -32 red_invaders[count].vector_x = random.randint( 0, 1) - random.randint(0, 1) red_invaders[count].vector_y = max_baddie_speed red_invaders[count].active = True break # Handle ufo attacks for count in range(MAX_UFOS): if ufos[count].active == False and ufo_attack_timer > ufo_attack_max and wave_break < 1 and game_over == False: ufo_attack_timer = 0 ufo_sound.play() # Pick a random direction if random.randint(0, 10) > 4: # Attack the side player if random.randint(0, 10) > 4: ufos[count].rect.top = -32 ufos[count].rect.left = SCREEN_WIDTH - 32 ufos[count].vector_y = max_ufo_speed ufos[count].vector_x = 0 ufos[count].active = True else: ufos[count].rect.top = SCREEN_HEIGHT + 32 ufos[count].rect.left = SCREEN_WIDTH - 32 ufos[count].vector_y = -max_ufo_speed ufos[count].vector_x = 0 ufos[count].active = True else: # Attack the bottom player if random.randint(0, 10) > 4: ufos[count].rect.top = SCREEN_HEIGHT - 32 ufos[count].rect.left = -32 ufos[count].vector_x = max_ufo_speed ufos[count].vector_y = 0 ufos[count].active = True else: ufos[count].rect.top = SCREEN_HEIGHT - 32 ufos[count].rect.left = SCREEN_WIDTH + 32 ufos[count].vector_x = 0 - max_ufo_speed ufos[count].vector_y = 0 ufos[count].active = True # Process particles for count in range(MAX_PARTICLES): if particles[count].active == True: particles[count].update() screen.blit(particles[count].image, particles[count].rect) # Process the player objects player_bottom.update() player_side.update() # Is player recovering from damage? if player_flash_timer > 0: player_flash_timer -= 1 if player_flash_on == True: player_flash_on = False else: player_flash_on = True else: player_flash_on = False if player_flash_on == False and game_over == False: screen.blit(player_bottom.image, player_bottom.rect) screen.blit(player_side.image, player_side.rect) # Handle all of the player projectiles for count in range(PLAYER_BULLETS): if (player_bullets[count].active): player_bullets[count].update() screen.blit(player_bullets[count].image, player_bullets[count].rect) # Handle all of the baddie projectiles for count in range(MAX_BADDIE_BULLETS): if (baddie_bullets[count].active == True): baddie_bullets[count].update() screen.blit(baddie_bullets[count].image, baddie_bullets[count].rect) # Slight delay for players fire rate player_fire_delay_left += 1 player_fire_delay_right += 1 # Move and draw the invaders for count in range(MAX_BADDIES): if invaders[count].active: invaders[count].update() screen.blit(invaders[count].image, invaders[count].rect, (32 * invaders[count].anim_frame, 0, 32, 32)) # Has invader collided with a player bullet? for collision_count in range(PLAYER_BULLETS): if player_bullets[collision_count].active == True: # Have to use a bit of jiggery pokery on the collision because the sprite.rect won't work as it is (too wide due to animation frames) if player_bullets[ collision_count].rect.colliderect( (invaders[count].rect.left, invaders[count].rect.top, 32, 32)): invaders[count].active = False player_score += 2000 player_bullets[collision_count].active = False baddies_killed += 1 baddie_splosion.play() create_particles(15, invaders[count].rect.left + 8, invaders[count].rect.top + 8, green_particle_image) # Move and draw the red invaders for count in range(MAX_BADDIES): if red_invaders[count].active: red_invaders[count].update() screen.blit( red_invaders[count].image, red_invaders[count].rect, (32 * red_invaders[count].anim_frame, 0, 32, 32)) # Has invader collided with a player bullet? for collision_count in range(PLAYER_BULLETS): if player_bullets[collision_count].active == True: # Have to use a bit of jiggery pokery on the collision because the sprite.rect won't work as it is (too wide due to animation frames) if player_bullets[ collision_count].rect.colliderect( (red_invaders[count].rect.left, red_invaders[count].rect.top, 32, 32)): red_invaders[count].active = False player_score += 4750 player_bullets[collision_count].active = False baddies_killed += 1 baddie_splosion.play() create_particles( 15, red_invaders[count].rect.left + 8, red_invaders[count].rect.top + 8, red_particle_image) # Time for red invaders to shoot? baddie_fire_timer += 1 if baddie_fire_timer > baddie_fire_max and game_over == False: baddie_fire_timer = 0 for count in range(MAX_BADDIES): if red_invaders[count].active == True and red_invaders[ count].rect.top < SCREEN_HEIGHT - 50 and red_invaders[ count].rect.top > 50: baddie_shoot_sound.play() bullets = 0 for bullet_count in range(MAX_BADDIE_BULLETS): if baddie_bullets[bullet_count].active == False: if random.randint(0, 10) > 4: baddie_bullets[bullet_count].active = True baddie_bullets[ bullet_count].rect.top = red_invaders[ count].rect.top + 8 baddie_bullets[ bullet_count].rect.left = red_invaders[ count].rect.left + 12 baddie_bullets[bullet_count].vector_x = 7 baddie_bullets[bullet_count].vector_y = 0 break else: baddie_bullets[bullet_count].active = True baddie_bullets[ bullet_count].rect.top = red_invaders[ count].rect.top + 16 baddie_bullets[ bullet_count].rect.left = red_invaders[ count].rect.left + 8 baddie_bullets[bullet_count].vector_x = 0 baddie_bullets[bullet_count].vector_y = 7 break # Move and draw the ufo for count in range(MAX_UFOS): if ufos[count].active == True: ufos[count].update() screen.blit(ufos[count].image, ufos[count].rect, (32 * ufos[count].anim_frame, 0, 32, 32)) # Has invader collided with a ufo? for collision_count in range(PLAYER_BULLETS): if player_bullets[collision_count].active == True: if player_bullets[ collision_count].rect.colliderect( (ufos[count].rect.left, ufos[count].rect.top, 32, 32)): ufos[count].active = False player_score += 3250 player_bullets[collision_count].active = False baddies_killed += 1 baddie_splosion.play() create_particles(15, ufos[count].rect.left + 8, ufos[count].rect.top + 8, gray_particle_image) # Move and draw the drones for count in range(MAX_BADDIES): if drones[count].active: drones[count].update() screen.blit(drones[count].image, drones[count].rect, (32 * drones[count].anim_frame, 0, 32, 32)) # Has invader collided with a player bullet? for collision_count in range(PLAYER_BULLETS): if player_bullets[collision_count].active == True: # Have to use a bit of jiggery pokery on the collision because the sprite.rect won't work as it is (too wide due to animation frames) if player_bullets[ collision_count].rect.colliderect( (drones[count].rect.left, drones[count].rect.top, 32, 32)): drones[count].active = False player_score += 2500 player_bullets[collision_count].active = False baddies_killed += 1 baddie_splosion.play() create_particles(15, drones[count].rect.left + 8, drones[count].rect.top + 8, blue_particle_image) # Check for baddie to player collisions if player_flash_timer < 1 and game_over == False: player_hit = False for collision_count in range(MAX_BADDIES): # Have any invaders collided with player? if invaders[collision_count].active == True: if player_side.rect.colliderect( (invaders[collision_count].rect.left + 5, invaders[collision_count].rect.top + 5, 24, 24)): invaders[collision_count].active = False create_particles( 15, invaders[collision_count].rect.left + 8, invaders[collision_count].rect.top + 8, green_particle_image) player_hit = True if player_bottom.rect.colliderect( (invaders[collision_count].rect.left + 5, invaders[collision_count].rect.top + 5, 24, 24)): invaders[collision_count].active = False create_particles( 15, invaders[collision_count].rect.left + 8, invaders[collision_count].rect.top + 8, green_particle_image) player_hit = True # Have any drones collided with player? if red_invaders[collision_count].active == True: if player_side.rect.colliderect( (red_invaders[collision_count].rect.left + 5, red_invaders[collision_count].rect.top + 5, 24, 24)): red_invaders[collision_count].active = False create_particles( 15, red_invaders[collision_count].rect.left + 8, red_invaders[collision_count].rect.top + 8, red_particle_image) player_hit = True if player_bottom.rect.colliderect( (red_invaders[collision_count].rect.left + 5, red_invaders[collision_count].rect.top + 5, 24, 24)): red_invaders[collision_count].active = False create_particles( 15, red_invaders[collision_count].rect.left + 8, red_invaders[collision_count].rect.top + 8, red_particle_image) player_hit = True # Have any drones collided with player? if drones[collision_count].active == True: if player_side.rect.colliderect( (drones[collision_count].rect.left + 5, drones[collision_count].rect.top + 5, 24, 24)): drones[collision_count].active = False create_particles( 15, drones[collision_count].rect.left + 8, drones[collision_count].rect.top + 8, blue_particle_image) player_hit = True if player_bottom.rect.colliderect( (drones[collision_count].rect.left + 5, drones[collision_count].rect.top + 5, 24, 24)): drones[collision_count].active = False create_particles( 15, drones[collision_count].rect.left + 8, drones[collision_count].rect.top + 8, blue_particle_image) player_hit = True # Have any ufos collided with player? for collision_count in range(MAX_UFOS): if ufos[collision_count].active == True: if player_side.rect.colliderect( (ufos[collision_count].rect.left + 5, ufos[collision_count].rect.top + 5, 24, 24)): ufos[collision_count].active = 0 create_particles( 15, ufos[collision_count].rect.left + 8, ufos[collision_count].rect.top + 8, gray_particle_image) player_hit = True if player_bottom.rect.colliderect( (ufos[collision_count].rect.left + 5, ufos[collision_count].rect.top + 5, 24, 24)): ufos[collision_count].active = 0 create_particles( 15, ufos[collision_count].rect.left + 8, ufos[collision_count].rect.top + 8, gray_particle_image) player_hit = True # Have any enemy bullets collided with player? for collision_count in range(MAX_BADDIE_BULLETS): if baddie_bullets[collision_count].active == True: if player_side.rect.colliderect( (baddie_bullets[collision_count].rect.left, baddie_bullets[collision_count].rect.top, 8, 8)): baddie_bullets[collision_count].active = 0 player_hit = True if player_bottom.rect.colliderect( (baddie_bullets[collision_count].rect.left, baddie_bullets[collision_count].rect.top, 8, 8)): baddie_bullets[collision_count].active = 0 player_hit = True # Has player been hit by anything nasty? if player_hit == True and game_over == False: player_shield -= 1 create_particles(5, 85 + ((player_shield) * 11), 32, red_particle_image) player_flash_timer = 50 player_boom_1.play() if player_shield == 0: player_boom_2.play() create_particles(20, player_bottom.rect.left + 8, player_bottom.rect.top + 8, red_particle_image) create_particles(20, player_bottom.rect.left + 8, player_bottom.rect.top + 8, yellow_particle_image) create_particles(20, player_side.rect.left + 8, player_side.rect.top + 8, red_particle_image) create_particles(20, player_side.rect.left + 8, player_side.rect.top + 8, yellow_particle_image) game_over = True # Display hud stuff screen.blit( game_font.render("Score: " + str(player_score), 0, ((255, 206, 0))), (10, 10)) screen.blit( game_font.render("High Score: " + str(high_score), 0, ((255, 206, 0))), (460, 10)) # Beaten high score? if player_score > high_score: high_score = player_score # Make a little fuss of the player :) if beaten_high_score == False: beaten_high_score = True for count in range(5): create_particles(5, 460 + (count * 15), 15, yellow_particle_image) if wave_break > 0: wave_break -= 1 if game_over == False: screen.blit( game_font_large.render( "Wave " + str(game_wave) + " of 9", 0, ((255, 206, 0))), (240, SCREEN_HEIGHT / 2 - 36)) for count in range(player_shield): screen.blit(game_font.render("Shields:", 0, ((255, 206, 0))), (10, 30)) screen.blit(player_health_image, (85 + (count * 11), 32)) if game_over == True: # Loss or victory? if game_victory == False: screen.blit( game_font_large.render("GAME OVER", 0, ((176, 0, 0))), (260, SCREEN_HEIGHT / 2 - 36)) else: screen.blit( game_font_large.render("YOU ARE AWESOME!!!", 0, ((255, 206, 0))), (160, SCREEN_HEIGHT / 2 - 36)) game_victory_particle_timer += 1 if game_victory_particle_timer > 10: create_particles(30, random.randint(160, 450), random.randint(160, 300), red_particle_image) game_over_timer -= 1 if game_over_timer == 0: game_mode = TITLE_SCREEN_MODE # Time for a new wave? Only start new wave display when all baddies are dead baddies_onscreen = False for count in range(MAX_BADDIES): if invaders[count].active == True: baddies_onscreen = True break if red_invaders[count].active == True: baddies_onscreen = True break if drones[count].active == True: baddies_onscreen = True break for count in range(MAX_UFOS): if ufos[count].active == True: baddies_onscreen = True if baddies_killed > wave_target_kills and baddies_onscreen == False and game_over == False: wave_break = 300 wave_target_kills += 10 game_wave += 1 if game_wave == 10: game_over = True game_victory = True game_over_timer = 700 win_sound.play() baddies_killed = 0 # Make the next round a bit harder :) if attack_max > 30: attack_max -= 10 if ufo_attack_max > 0: ufo_attack_max -= 50 if game_wave > 6: baddie_fire_rate = 10 wave_sound.play() # Show the newly rendered screen pygame.display.flip() # Limit game speed clock.tick(FPS) # This is not strictly needed, but is included so that IDLE will play nice :) pygame.quit()
#Skip star instantiation if coordinates to not exist if star_obj[69:71] == ' ': continue r_a = convert( int(star_obj[75:77]) * 15, int(star_obj[77:79]) * 15, float(star_obj[79:83]) * 15) d = convert(int(star_obj[84:86]), int(star_obj[86:88]), float(star_obj[88:90])) #Check to see if coordinate is negative if star_obj[83] == '-': d *= (-1) star_data.append( Star(star_obj[4:14], star_obj[14:25], float(star_obj[102:107].strip(' ')), (r_a, d))) #argv[1] = constellation, argv[2] = bool(Show all Stars?) constellation = sys.argv[1] cons_stars = [] for star_obj in star_data: if constellation == star_obj.name[-3:] and \ (star_obj.name.split()[0].isdigit() == False): cons_stars.append(star_obj) if cons_stars == []: sys.exit("Invalid constellation. \nUsage: python {:s} [constellation]" " [show all stars]".format(sys.argv[0])) avg_a = sum( [math.asin(math.sin(star_obj.position[0]))
def creative(c, background, stock, store): debug(c.DEBUG, "ENTERING: campaign") versionID = stock.getVersion() timeClock = clockCounter() allSprites = pygame.sprite.Group() ringSprite = pygame.sprite.GroupSingle() circSprites = pygame.sprite.LayeredUpdates() buttonSprites = pygame.sprite.Group() # @UnusedVariable starSprites = pygame.sprite.LayeredUpdates() caughtSprite = pygame.sprite.GroupSingle() dieingSprites = pygame.sprite.GroupSingle() scoreSprite = pygame.sprite.GroupSingle() pBox = playBox() # a jukebox for handling music settings. pygame.mixer.music.set_endevent(USEREVENT) ring = Ring(c.CENTER, stock.campaign["Ring"], stock.campaign["Ring Glow"], c.FULLSCREEN) '''CREATE IMAGES''' ring.add(ringSprite, allSprites) scoreboard = Scoreboard(c.DISPLAY_W, c.DISPLAY_H) scoreboard.add(scoreSprite, allSprites) box_img = stock.campaign["RGB Light"] background_rect = background.get_rect() background_rect.center = c.CENTER OGBackground = background.copy() '''INSTANTIATING OTHER VARIABLES''' rotAngle = 0 # background rotation angle waitCounterCirc = 0 waitCounterStar = 0 countingCircleTime = False countingStarTime = False countingWaitTime = False totalWaitTime = 0 totalCircleTime = 0 totalStarTime = 0 newStartTime = 0 oldStartTime = 0 pause_selection = 0 newCircleColor = '' oldCircleColor = '' newStarAngle = '' oldStarAngle = '' circleWaitStart = 0 circleWaitMade = 0 circleColor = '' starWaitStart = 0 starWaitMade = 0 pauseStartTime = None #datetime variable pauseEndTime = None #datetime variable finishedCircleActions = False finishedStarActions = False circleAction = '_' starAction = '_' counter = 0 starWaiting = False circleWaiting = False countingWaitTime = False r = 0 g = 0 b = 0 paused = False total_input = 0 fpsList = [] toggle_color_r = False toggle_color_g = False toggle_color_b = False display_sprites = True controls = c.CONTROL_LIST leftHold = False rightHold = False upHold = False downHold = False quitGame = False # if user returns a True from pause, we quit game, etc. startTime = 0 newInput = True currentColor = (0, 0, 0) colorList = "" # open the files that we'll be saving to. genFile = os.path.join(c.DATA_DIR, 'creative_commands/genCommands.txt') circleFile = os.path.join(c.DATA_DIR, 'creative_commands/circleCommands.txt') starFile = os.path.join(c.DATA_DIR, 'creative_commands/starCommands.txt') genFile = open(genFile, 'w') circleFile = open(circleFile, 'w') starFile = open(starFile, 'w') """BUTTON / SPRITE RENDERING""" r_letter = c.FONT_LARGE.render('R', True, c.RED) r_letter.scroll(2, 0) r_letter_rect = r_letter.get_rect() r_letter_rect.center = (c.CENTER_X - 50, (c.CENTER_Y * 2) - 20) box_rectR = r_letter_rect g_letter = c.FONT_LARGE.render('G', True, c.GREEN) g_letter.scroll(1, 0) g_letter_rect = g_letter.get_rect() g_letter_rect.center = (c.CENTER_X, (c.CENTER_Y * 2) - 20) box_rectG = g_letter_rect b_letter = c.FONT_LARGE.render('B', True, c.BLUE) b_letter.scroll(2, 0) b_letter_rect = b_letter.get_rect() b_letter_rect.center = (c.CENTER_X + 50, (c.CENTER_Y * 2) - 20) box_rectB = b_letter_rect stageDisplay = stock.creative["Circle Building"] stageDisplay_rect = stageDisplay.get_rect() stageDisplay_rect.topright = (c.DISPLAY_W, 0) debug(c.DEBUG, "Variable and object instantiating successful.") showSplashScreen(c, stock) load_song(c, "It's Melting.ogg") # stops other music from playing too debug(c.DEBUG, "Stars and Circles ready! ") debug(c.DEBUG, "Now building Circles") # --CIRCLE MAKING Loop//-- going = True pygame.mixer.music.play(0, 0) timeClock.playTimeSet() while going: counter += 1 # Paint the background c.DISPLAYSURFACE.fill((0, 0, 0)) c.DISPLAYSURFACE.blit(background, background_rect) if counter % 5 == 0: background, background_rect, rotAngle = \ rotateBackground(c.CENTER, OGBackground, counter, rotAngle) """LOGGING output information: FPS, event info, AA, etc.""" # for every 30 or FPS number of frames, print an average fps. fpsList.append(c.FPSCLOCK.get_fps()) if counter == (c.FPS * 5): debug(c.DEBUG, ("Average FPS: {0}".format(mean(fpsList)))) debug(c.DEBUG, ("Current Score: {0}".format(scoreboard.scoreString))) counter = 0 pygame.display.set_caption('RGB. FPS: {0}'.format(mean(fpsList))) fpsList = [] #======================================================================= # """Get input to know if we should put in a wait action""" # if total_input == 0: # if not countingWaitTime: # debug(c.DEBUG, "STARTING COUNT WAIT TIME") # countingWaitTime = True # timeClock.setTime(1) #======================================================================= if newCircleColor != '': oldCircleColor = newCircleColor """EVENT HANDLING INPUT""" # grab all the latest input latest_events = pygame.event.get() for event in latest_events: if event.type == QUIT: going = False pygame.quit() sys.exit() elif event.type == KEYDOWN and event.key == K_ESCAPE: if c.DEBUG: going = False pygame.mixer.music.stop() #=============================================================== # else: # # have to time how long pause takes, for the wait. # pauseStartTime = datetime.datetime.now() # pause_selection = pause() # pauseEndTime = datetime.datetime.now() # pauseTotalTime = (pauseEndTime - pauseStartTime) # starWaitStart = starWaitStart + pauseTotalTime # circleWaitStart = circleWaitStart + pauseTotalTime #=============================================================== # --game-play events//-- elif event.type == KEYDOWN and event.key == controls[0]: r = 255 toggle_color_r = True total_input += 1 colorList += 'R' elif event.type == KEYUP and event.key == controls[0]: r = 0 toggle_color_r = False total_input += -1 colorList = colorList.replace('R', '') elif event.type == KEYDOWN and event.key == controls[1]: g = 255 toggle_color_g = True total_input += 1 colorList += 'G' elif event.type == KEYUP and event.key == controls[1]: g = 0 toggle_color_g = False total_input += -1 colorList = colorList.replace('G', '') elif event.type == KEYDOWN and event.key == controls[2]: b = 255 toggle_color_b = True total_input += 1 colorList += 'B' elif event.type == KEYUP and event.key == controls[2]: b = 0 toggle_color_b = False total_input += -1 colorList = colorList.replace('B', '') #==================================== # --non-game-play events//-- #==================================== # if O is pressed, toggle context display -------TO BE REMOVED SOON elif event.type == KEYDOWN and event.key == K_o: if display_sprites == True: display_sprites = False else: display_sprites = True elif event.type == KEYDOWN and event.key == K_s: # add ten seconds to the total playtime. pygame.mixer.music.stop() newStartTime = (datetime.datetime.now() - timeClock.playTime ).total_seconds() + 10 + oldStartTime # since the song is now 10 seconds ahead, we have to make sure there is a 10 second difference # in recording of actions. timeClock.timeIn = timeClock.timeIn - datetime.timedelta( seconds=10) pygame.mixer.music.play(0, newStartTime) # need to record where we last began. oldStartTime = newStartTime debug(c.DEBUG, "new Start Time: %f" % newStartTime) # if P is pressed, pause game. elif event.type == KEYUP and event.key == controls[7]: None #=============================================================== # # have to time how long pause takes, for the wait. # pauseStartTime = datetime.datetime.now() # pause_selection = pause() # pauseEndTime = datetime.datetime.now() # pauseTotalTime = (pauseEndTime - pauseStartTime) # starWaitStart = starWaitStart + pauseTotalTime # circleWaitStart = circleWaitStart + pauseTotalTime #=============================================================== """LOGGING of inputs""" if event.type == KEYDOWN or event.type == KEYUP: debug(c.DEBUG, (pygame.event.event_name(event.type), event.dict)) debug(c.DEBUG, "NEWINPUT FOUND") newInput = True newCircleColor = colorList # grab color at time of recording. if pygame.event.peek(USEREVENT): going = False if pause_selection == 3: going = False return #if an action has been input, test total_inputs: """Get input to know if we should put in a wait action""" if not (total_input == 0): if countingWaitTime: countingWaitTime = False totalWaitTime = timeClock.getDelta(True) debug(c.DEBUG, "Old wait time recorded") circleFile.write(" W{0} ".format(totalWaitTime + totalCircleTime)) # if it isn't counting wait time, then it IS counting circleTime countingCircleTime = True debug(c.DEBUG, "Now counting circle time") timeClock.setTime(1) # newInput is set to false, since we already know its a new # input based on change in counting. newInput is only # relevant for when the circle color changes without a wait # in between. newInput = False else: if countingCircleTime: if newInput: #first, we must store the old input. totalCircleTime = timeClock.getDelta(True) circleFile.write(" C{0},{1} ".format( oldCircleColor, totalCircleTime)) # a wait time must be introduced so that other circles # don't spawn. circleFile.write(" W{0} ".format(totalCircleTime)) newInput = False debug(c.DEBUG, "Old circle time recorded") debug(c.DEBUG, "New circle time recording") #now we start the new Input recording.. timeClock.setTime(1) else: if not countingWaitTime: if countingCircleTime: totalCircleTime = timeClock.getDelta(True) circleFile.write(" C{0},{1} ".format( oldCircleColor, totalCircleTime)) newInput = False debug(c.DEBUG, "Old circle time recorded") countingCircleTime = False else: debug(c.DEBUG, "Now counting wait time") countingWaitTime = True timeClock.setTime(1) elif not (going): totalWaitTime = timeClock.getDelta(True) circleFile.write(" W{0} ".format(totalWaitTime)) """DISPLAY SPRITE TOGGLE""" allSprites.update() if display_sprites == True: dieingSprites.draw(c.DISPLAYSURFACE) caughtSprite.draw(c.DISPLAYSURFACE) circSprites.draw(c.DISPLAYSURFACE) starSprites.draw(c.DISPLAYSURFACE) ringSprite.draw(c.DISPLAYSURFACE) if toggle_color_r: c.DISPLAYSURFACE.blit(r_letter, r_letter_rect) if toggle_color_g: c.DISPLAYSURFACE.blit(g_letter, g_letter_rect) if toggle_color_b: c.DISPLAYSURFACE.blit(b_letter, b_letter_rect) c.DISPLAYSURFACE.blit(box_img, box_rectR) c.DISPLAYSURFACE.blit(box_img, box_rectG) c.DISPLAYSURFACE.blit(box_img, box_rectB) c.DISPLAYSURFACE.blit(stageDisplay, stageDisplay_rect) scoreSprite.draw(c.DISPLAYSURFACE) c.DISPLAYSURFACE.blit(versionID, (0, 0)) """DELAY""" c.FPSCLOCK.tick_busy_loop(c.FPS) """UPDATE""" pygame.display.flip() # update() circleFile.close() if quitGame == 3: return debug(c.DEBUG, "Now building Stars") """Reinitializing Variables.""" newStartTime = 0 oldStartTime = 0 stageDisplay = stock.creative["Star Building"] stageDisplay_rect = stageDisplay.get_rect() stageDisplay_rect.topright = (c.DISPLAY_W, 0) # --STAR MAKING Loop//-- going = True pygame.mixer.music.play(0, 0) timeClock.playTimeSet() while going: counter += 1 # Paint the background c.DISPLAYSURFACE.fill((0, 0, 0)) c.DISPLAYSURFACE.blit(background, background_rect) if counter % 5 == 0: background, background_rect, rotAngle = \ rotateBackground(c.CENTER, OGBackground, counter, rotAngle) """LOGGING output information: FPS, event info, AA, etc.""" # for every 30 or FPS number of frames, print an average fps. fpsList.append(c.FPSCLOCK.get_fps()) if counter == (c.FPS * 5): debug(c.DEBUG, ("Average FPS: {0}".format(mean(fpsList)))) debug(c.DEBUG, ("Current Score: {0}".format(scoreboard.scoreString))) counter = 0 pygame.display.set_caption('RGB. FPS: {0}'.format(mean(fpsList))) fpsList = [] #======================================================================= # """Get input to know wif we should put in a wait action""" # if total_input == 0: # if not countingWaitTime: # debug(c.DEBUG, "STARTING COUNT WAIT TIME") # countingWaitTime = True # timeClock.setTime(1) #======================================================================= if newStarAngle != '': oldStarAngle = newStarAngle """EVENT HANDLING INPUT""" # grab all the latest input latest_events = pygame.event.get() for event in latest_events: if event.type == QUIT: going = False pygame.quit() sys.exit() elif event.type == KEYDOWN and event.key == K_ESCAPE: if c.DEBUG: going = False pygame.mixer.music.stop() else: None #=========================================================== # # have to time how long pause takes, for the wait. # pauseStartTime = datetime.datetime.now() # pause_selection = pause() # pauseEndTime = datetime.datetime.now() # pauseTotalTime = (pauseEndTime - pauseStartTime) # starWaitStart = starWaitStart + pauseTotalTime # circleWaitStart = circleWaitStart + pauseTotalTime #=========================================================== # --game-play events//-- # Ring Spinning elif event.type == KEYDOWN and event.key == controls[5]: total_input += 1 leftHold = True if upHold: ring.spin('upleft') elif downHold: ring.spin('downleft') else: ring.spin('left') elif event.type == KEYUP and event.key == controls[5]: leftHold = False total_input += -1 elif event.type == KEYDOWN and event.key == controls[6]: rightHold = True total_input += 1 if upHold: ring.spin('upright') elif downHold: ring.spin('downright') else: ring.spin('right') elif event.type == KEYUP and event.key == controls[6]: rightHold = False total_input += -1 elif event.type == KEYDOWN and event.key == controls[3]: upHold = True total_input += 1 if leftHold: ring.spin('upleft') elif rightHold: ring.spin('upright') else: ring.spin('up') elif event.type == KEYUP and event.key == controls[3]: upHold = False total_input += -1 elif event.type == KEYDOWN and event.key == controls[4]: downHold = True total_input += 1 if leftHold: ring.spin('downleft') elif rightHold: ring.spin('downright') else: ring.spin('down') elif event.type == KEYUP and event.key == controls[4]: downHold = False total_input += -1 #==================================== # --non-game-play events//-- #==================================== # if O is pressed, toggle context display -------TO BE REMOVED SOON elif event.type == KEYDOWN and event.key == K_o: if display_sprites == True: display_sprites = False else: display_sprites = True elif event.type == KEYDOWN and event.key == K_s: # add ten seconds to the total playtime. pygame.mixer.music.stop() newStartTime = (datetime.datetime.now() - timeClock.playTime ).total_seconds() + 10 + oldStartTime # since the song is now 10 seconds ahead, we have to make sure there is a 10 second difference # in recording of actions. timeClock.timeIn = timeClock.timeIn - datetime.timedelta( seconds=10) pygame.mixer.music.play(0, newStartTime) # need to record where we last began. oldStartTime = newStartTime debug(c.DEBUG, "new Start Time: %f" % newStartTime) # if P is pressed, pause game. elif event.type == KEYUP and event.key == controls[7]: None #=============================================================== # # have to time how long pause takes, for the wait. # pauseStartTime = datetime.datetime.now() # pause_selection = pause() # pauseEndTime = datetime.datetime.now() # pauseTotalTime = (pauseEndTime - pauseStartTime) # starWaitStart = starWaitStart + pauseTotalTime # circleWaitStart = circleWaitStart + pauseTotalTime #=============================================================== """LOGGING of inputs""" if event.type == KEYDOWN or event.type == KEYUP: debug(c.DEBUG, (pygame.event.event_name(event.type), event.dict)) debug(c.DEBUG, "NEWINPUT FOUND") newInput = True newStarAngle = ring.angle # grab angle at time of recording. if pygame.event.peek(USEREVENT): pygame.mixer.music.stop() going = False if pause_selection == 3: going = False return #if an action has been input, test total_inputs: """Get input to know if we should put in a wait action""" if not (total_input == 0): if countingWaitTime: countingWaitTime = False totalWaitTime = timeClock.getDelta(True) debug(c.DEBUG, "Old wait time recorded") starFile.write(" W{0} ".format(totalWaitTime + totalStarTime)) # if it isn't counting wait time, then it IS counting circleTime countingStarTime = True debug(c.DEBUG, "Now counting star time") timeClock.setTime(1) # newInput is set to false, since we already know its a new # input based on change in counting. newInput is only # relevant for when the circle color changes without a wait # in between. newInput = False else: if countingStarTime: if newInput: #first, we must store the old input. totalStarTime = timeClock.getDelta(True) starFile.write(" F{0},{1} ".format( oldStarAngle, totalStarTime)) # a wait time must be introduced so that other circles # don't spawn. starFile.write(" W{0} ".format(totalStarTime)) newInput = False debug(c.DEBUG, "Old star time recorded") debug(c.DEBUG, "New star time recording") #now we start the new Input recording.. timeClock.setTime(1) else: if not countingWaitTime: if countingStarTime: totalStarTime = timeClock.getDelta(True) starFile.write(" F{0},{1} ".format(oldStarAngle, totalStarTime)) newInput = False debug(c.DEBUG, "Old star time recorded") countingStarTime = False else: debug(c.DEBUG, "Now counting wait time") countingWaitTime = True timeClock.setTime(1) elif not (going): totalWaitTime = timeClock.getDelta(True) starFile.write(" W{0} ".format(totalWaitTime)) """DISPLAY SPRITE TOGGLE""" allSprites.update() if display_sprites == True: dieingSprites.draw(c.DISPLAYSURFACE) caughtSprite.draw(c.DISPLAYSURFACE) circSprites.draw(c.DISPLAYSURFACE) starSprites.draw(c.DISPLAYSURFACE) ringSprite.draw(c.DISPLAYSURFACE) if toggle_color_r: c.DISPLAYSURFACE.blit(r_letter, r_letter_rect) if toggle_color_g: c.DISPLAYSURFACE.blit(g_letter, g_letter_rect) if toggle_color_b: c.DISPLAYSURFACE.blit(b_letter, b_letter_rect) c.DISPLAYSURFACE.blit(box_img, box_rectR) c.DISPLAYSURFACE.blit(box_img, box_rectG) c.DISPLAYSURFACE.blit(box_img, box_rectB) c.DISPLAYSURFACE.blit(stageDisplay, stageDisplay_rect) scoreSprite.draw(c.DISPLAYSURFACE) c.DISPLAYSURFACE.blit(versionID, (0, 0)) """DELAY""" c.FPSCLOCK.tick_busy_loop(c.FPS) """UPDATE""" pygame.display.flip() # update() starFile.close() if quitGame == 3: return debug(c.DEBUG, "Showing built commands") """REINITIALIZING""" stageDisplay = stock.creative["Build Testing"] stageDisplay_rect = stageDisplay.get_rect() stageDisplay_rect.topright = (c.DISPLAY_W, 0) genList = os.path.join(c.DATA_DIR, 'creative commands/genCommands.txt') circleList = os.path.join(c.DATA_DIR, 'creative commands/circleCommands.txt') starList = os.path.join(c.DATA_DIR, 'creative commands/starCommands.txt') genList, circleList, starList = commander(c, genList, circleList, starList) # commander takes the # commands.txt and converts it into a formatted list. circleList, starList = iter(circleList), iter(starList) # take in the genList parameters now, before the level begins. for loop in range(len(genList)): setting = genList[loop] if setting[0] == 'B': # if the command is BPM, set the proper variables. pBox.cWait = setting[1] pBox.fWait = setting[2] pBox.cSpeed = setting[3] pBox.fSpeed = setting[4] elif setting[0] == 'J': startTime = setting[1] # change the general speed for circles/stars elif setting[0][0] == 'W': if setting[0] == 'WG': pBox.cWait = setting[1] pBox.fWait = setting[1] elif setting[0] == 'WC': pBox.cWait = setting[1] elif setting[0] == 'WF': pBox.fWait = setting[1] # --Main Game Loop//-- going = True pygame.mixer.music.play(0, startTime) while going: counter += 1 waitCounterCirc += 1 waitCounterStar += 1 # Paint the background c.DISPLAYSURFACE.fill((0, 0, 0)) c.DISPLAYSURFACE.blit(background, background_rect) if counter % 5 == 0: background, background_rect, rotAngle = \ rotateBackground(c.CENTER, OGBackground, counter, rotAngle) """LOGGING output information: FPS, event info, AA, etc.""" # for every 30 or FPS number of frames, print an average fps. fpsList.append(c.FPSCLOCK.get_fps()) if counter == (c.FPS * 5): debug(c.DEBUG, ("Average FPS: {0}".format(mean(fpsList)))) debug(c.DEBUG, ("Current Score: {0}".format(scoreboard.scoreString))) counter = 0 pygame.display.set_caption('RGB. FPS: {0}'.format(mean(fpsList))) fpsList = [] """TAKE ACTION COMMAND LIST""" # for every new action, if the wait was long enough, perform the action if not circleWaiting: if not finishedCircleActions: try: circleAction = circleList.next() except: finishedCircleActions = True # if the circleAction is to spawn a circle/star, gotta que it up. if circleAction[0] == 'C': circleWaiting = True # change the general speed for circles/stars elif circleAction[0] == 'CS': if circleAction[0] == 'CS': pBox.cSpeed = circleAction[1] elif circleAction[0][0] == 'W': if circleAction[0] == 'W': circleWaitStart = datetime.datetime.now() circleWaiting = True circleWaitMade = datetime.datetime.now( ) # time started waiting elif circleAction[0] == 'WC': pBox.cWait = circleAction[1] elif circleAction[0] == 'S': pygame.mixer.music.stop() going = False if circleWaiting: # All main actions have to wait before they can be performed, # so once an action is read, waiting becomes True, and we test to # see if the time passed is valid for the given wait time. if circleAction[0] == 'C': if waitCounterCirc >= pBox.cWait: if circleAction[2] == '': # if there is no given speed, then it's the global # speed. . . tempSpeed = pBox.cSpeed else: tempSpeed = circleAction[2] tempColor = circleAction[1] debug(c.DEBUG, ("{0}'s speed: {1}".format(tempColor, tempSpeed))) tempCirc = Circle(stock.campaign['Circle'], c.CENTER, tempSpeed, tempColor, pBox.layer) tempCirc.add(circSprites, allSprites) circMade = datetime.datetime.now() #for debugging pBox.layer += 1 #determines which get drawn on top circleWaiting = False waitCounterCirc = 0 elif circleAction[0] == 'W': change = datetime.datetime.now() - circleWaitStart # if the action is to JUST wait x amount of time if change.total_seconds() >= circleAction[1] / c.FPS: circleWaiting = False totalWaitTime = datetime.datetime.now() - circleWaitMade debug(c.DEBUG, ("Wait Time: ", totalWaitTime.total_seconds())) waitCounterCirc = 0 if not starWaiting: if not finishedStarActions: try: starAction = starList.next() except: finishedStarActions = True if starAction[0] == 'F': starWaiting = True # change the general speed for circles/stars elif starAction[0] == 'FS': pBox.fSpeed = starAction[1] elif starAction[0][0] == 'W': if starAction[0] == 'W': starWaitStart = datetime.datetime.now() starWaiting = True starWaitMade = datetime.datetime.now() elif starAction[0] == 'WF': pBox.fWait = starAction[1] elif starAction[0] == 'S': pygame.mixer.music.stop() going = False if starWaiting: if starAction[0] == 'F': if waitCounterStar >= pBox.fWait: if starAction[2] == '': tempSpeed = pBox.fSpeed else: tempSpeed = starAction[2] tempAngle = starAction[1] images = (stock.campaign['Star Lit'], stock.campaign['Star Unlit']) tempStar = Star(images, c.CENTER, tempSpeed, tempAngle) tempStar.add(starSprites, allSprites) # no longer waiting, bring on the next starAction! starWaiting = False waitCounterStar = 0 elif starAction[0] == 'W': change = datetime.datetime.now() - starWaitStart # if the starAction is to JUST wait x amount of time if change.total_seconds() >= starAction[1] / 30.0: starWaiting = False totalWaitTime = datetime.datetime.now() - starWaitMade debug(c.DEBUG, ("Wait Time: ", totalWaitTime.total_seconds())) waitCounterStar = 0 # we must also set the wait for the next starAction to 0, # or else the wait would be Wx + Wcircle/star. # test real quick to see if the song is over. if pygame.event.peek(USEREVENT): pygame.mixer.music.stop() going = False if pause_selection == 3: going = False return """EVENT HANDLING INPUT""" # grab all the latest input latest_events = pygame.event.get() for event in latest_events: if event.type == QUIT: going = False pygame.quit() sys.exit() elif event.type == KEYDOWN and event.key == K_ESCAPE: if c.DEBUG: going = False else: # have to time how long pause takes, for the wait. pauseStartTime = datetime.datetime.now() pause_selection = pause() pauseEndTime = datetime.datetime.now() pauseTotalTime = (pauseEndTime - pauseStartTime) starWaitStart = starWaitStart + pauseTotalTime circleWaitStart = circleWaitStart + pauseTotalTime # --game-play events//-- elif event.type == KEYDOWN and event.key == controls[0]: r = 255 toggle_color_r = True total_input += 1 elif event.type == KEYUP and event.key == controls[0]: r = 0 toggle_color_r = False total_input += -1 elif event.type == KEYDOWN and event.key == controls[1]: g = 255 toggle_color_g = True total_input += 1 elif event.type == KEYUP and event.key == controls[1]: g = 0 toggle_color_g = False total_input += -1 elif event.type == KEYDOWN and event.key == controls[2]: b = 255 toggle_color_b = True total_input += 1 elif event.type == KEYUP and event.key == controls[2]: b = 0 toggle_color_b = False total_input += -1 # Ring Spinning elif event.type == KEYDOWN and event.key == controls[5]: leftHold = True if upHold: ring.spin('upleft') elif downHold: ring.spin('downleft') else: ring.spin('left') elif event.type == KEYUP and event.key == controls[5]: leftHold = False elif event.type == KEYDOWN and event.key == controls[6]: rightHold = True if upHold: ring.spin('upright') elif downHold: ring.spin('downright') else: ring.spin('right') elif event.type == KEYUP and event.key == controls[6]: rightHold = False elif event.type == KEYDOWN and event.key == controls[3]: upHold = True if leftHold: ring.spin('upleft') elif rightHold: ring.spin('upright') else: ring.spin('up') elif event.type == KEYUP and event.key == controls[3]: upHold = False elif event.type == KEYDOWN and event.key == controls[4]: downHold = True if leftHold: ring.spin('downleft') elif rightHold: ring.spin('downright') else: ring.spin('down') elif event.type == KEYUP and event.key == controls[4]: downHold = False #==================================== # --non-game-play events//-- #==================================== # if O is pressed, toggle context display -------TO BE REMOVED SOON elif event.type == KEYDOWN and event.key == K_o: if display_sprites == True: display_sprites = False else: display_sprites = True # if P is pressed, pause game. elif event.type == KEYUP and event.key == controls[7]: # have to time how long pause takes, for the wait. pauseStartTime = datetime.datetime.now() pause_selection = pause() pauseEndTime = datetime.datetime.now() pauseTotalTime = (pauseEndTime - pauseStartTime) starWaitStart = starWaitStart + pauseTotalTime circleWaitStart = circleWaitStart + pauseTotalTime """LOGGING of inputs""" if event.type == KEYDOWN or event.type == KEYUP: debug(c.DEBUG, (pygame.event.event_name(event.type), event.dict)) """CATCH CIRCLES MATCHING COLORS""" # catch matching circles!! for circle in circSprites.sprites(): if circle.catchable: # catchable becomes true when the circle comes in contact # with the ring. debug(c.DEBUG, (circle.color, (r, g, b))) circle.add(caughtSprite) circle.remove(circSprites) circle.catch() totalCircTime = datetime.datetime.now() - circMade """REPEATED POINTS HOLDING COLORS CAUGHT""" # every .1 seconds should add or remove points based on accuracy if not (caughtSprite.sprite is None): for circle in caughtSprite.sprites(): if circle.color == (r, g, b) and not (circle.dieing): debug(c.DEBUG, ("CIRCTIME: ", totalCircTime.total_seconds())) #if the circle is more than 1 color, than we give bonus if circle.color[0] + circle.color[1] + circle.color[ 2] > 255: scoreboard.addScore(40) else: scoreboard.addScore(20) circle.remove(caughtSprite) circle.add(dieingSprites) else: circle.remove(caughtSprite) circle.add(dieingSprites) scoreboard.addScore(-10) # a circle begins in circSprites, then hits the ring, gets caught, and # goes into "caughtSprite" group. From there, it tries to match with # the user's input, then dies and goes into the "dieingCircs" group. # the purpose of the last group is just to have it animate the fading # or "dieing" sequence before disappearing. for circle in dieingSprites.sprites(): circle.death() """DELETE FREE STARS SHOOTING""" for star in starSprites.sprites(): if star.travDist >= (264 - star.speed) and not (star.shooting): # this tests the stars' distance, once it's close enough. . . if not ((ringSprite.sprite.angle) % 360 == (star.angleDeg) % 360): debug(c.DEBUG, "Star Died at:") debug(c.DEBUG, ("Ring Angle: ", ringSprite.sprite.angle)) debug(c.DEBUG, ("Star Angle: ", star.angleDeg)) star.kill() scoreboard.addScore(-30) else: debug(c.DEBUG, "Star Made it at:") debug(c.DEBUG, ("Ring Angle: ", ringSprite.sprite.angle)) debug(c.DEBUG, ("Star Angle: ", star.angleDeg)) if star.shooting: # debug(c.DEBUG, 'I AM SHOOTING1!') # if the star has gone off the screen in the x or y direction # kill it and add points!! if star.pos[0] > c.DISPLAY_W or star.pos[0] < 0: star.kill() # debug(c.DEBUG, 'KILLED A STAR') scoreboard.addScore(50) elif star.pos[1] > c.DISPLAY_H or star.pos[1] < 0: star.kill() # debug(c.DEBUG, 'KILLED A STAR') scoreboard.addScore(50) # debug(c.DEBUG, ('Stars #: {0}'.format(len(starSprites.sprites()))) """DISPLAY SPRITE TOGGLE""" allSprites.update() if display_sprites == True: dieingSprites.draw(c.DISPLAYSURFACE) caughtSprite.draw(c.DISPLAYSURFACE) circSprites.draw(c.DISPLAYSURFACE) starSprites.draw(c.DISPLAYSURFACE) ringSprite.draw(c.DISPLAYSURFACE) if toggle_color_r: c.DISPLAYSURFACE.blit(r_letter, r_letter_rect) if toggle_color_g: c.DISPLAYSURFACE.blit(g_letter, g_letter_rect) if toggle_color_b: c.DISPLAYSURFACE.blit(b_letter, b_letter_rect) c.DISPLAYSURFACE.blit(box_img, box_rectR) c.DISPLAYSURFACE.blit(box_img, box_rectG) c.DISPLAYSURFACE.blit(box_img, box_rectB) c.DISPLAYSURFACE.blit(stageDisplay, stageDisplay_rect) scoreSprite.draw(c.DISPLAYSURFACE) c.DISPLAYSURFACE.blit(versionID, (0, 0)) """DELAY""" c.FPSCLOCK.tick_busy_loop(c.FPS) """UPDATE""" pygame.display.flip() # update() return
def create_star(ai_settings, screen, stars): if len(stars) < ai_settings.star_allowed: new_star = Star(ai_settings, screen) stars.add(new_star)
def star_creation(game_settings, screen, stars): if time_to_create_star(game_settings): new_star = Star(game_settings, screen) stars.add(new_star)
REFRESH_RATE = 120 # [how much per second] # On lower refresh rate you will not notice planet that is rotating very fast, or you can see it rotating slowly. # That's because of stroboscopic effect time_scale = 1 * 3600 # [sec] start_flag = False trail_flag = False # SCENE: scene = canvas(width=1200, height=700) scene.title = int(0.1 * scene.width) * ' ' + 'Solar System\n', scene.ambient = color.gray(0.7) scene.autoscale = False scene.lights = [] # SOLAR SYSTEM OBJECTS: sun = Star(1392000, 27 * 24, 'textures/sunmap.jpg', 0, time_scale, REFRESH_RATE, SUN_SCALE) mercury = Planet(4879, 57910000, 58.65 * 24, 87.969, 'textures/mercurymap.jpg', 0, sun, PLANET_SCALE, DISTANCE_SCALE, time_scale, REFRESH_RATE) venus = Planet(12100, 108200000, 243 * 24, 224.7, 'textures/venusmap.jpg', 0, sun, PLANET_SCALE, DISTANCE_SCALE, time_scale, REFRESH_RATE) earth = Planet(12740, 149600000, 23.93, 365.25, 'textures/earthmap1k.jpg', 0, sun, PLANET_SCALE, DISTANCE_SCALE, time_scale, REFRESH_RATE) moon = Satellite(3476, 380000, 27.3 * 24, 27.3, 'textures/moonmap4k.jpg', 0, earth) mars = Planet(6779, 227900000, 24.62, 686.738, 'textures/mars_1k_color.jpg', 0, sun, PLANET_SCALE, DISTANCE_SCALE, time_scale, REFRESH_RATE) jupiter = Planet(139800, 778600000, 9.8, 11 * 365.25 + 315,
def create_some_star(ai_settings,stats,screen,ship,stars): star=Star(ai_settings,screen) for a in range(int((stats.level)/10)+1): creat_one_star(ai_settings,stats,screen,ship,stars)
def create_star(ai_settings, screen, stars, star_x, star_y): """Creates a star in given coordinates""" star = Star(ai_settings, screen) star.rect.x = star_x star.rect.y = star_y stars.add(star)
def create_star(ai_settings, screen, stars): for i in range(1, 5): star = Star(ai_settings, screen) stars.add(star)
def create_grid(settings, screen, stars): star = Star(settings, screen) for _ in range(100): x = randint(0, settings.screen_width - star.rect.right) y = randint(0, settings.screen_height - star.rect.bottom) create_star(settings, screen, stars, x, y)