def __init__(self, name): self.name = name self.planets = [ planet.Planet(100, 100), planet.Planet(200, 200), planet.Planet(200, 0) ] self.ships = []
def init_simulation(): position1 = np.array([0., 0., 0.]) velocity1 = np.array([0., 0., 0.]) planet1 = planet.Planet(1E10, position1, velocity1, "Finera") position2 = np.array([1., 0., 0.]) velocity2 = np.array([0., 0., 0.]) planet2 = planet.Planet(1E10, position2, velocity2, "Genobi") return simulation.EulerLeapfrog([planet1, planet2], 100, 0.01)
def setUp(self): super().setUp() self.t = bhtree.BHTree() self.planet_nw = planet.Planet(None, r=[0, 260]) self.planet_ne = planet.Planet(None, r=[280, 260]) self.planet_sw1 = planet.Planet(None, r=[0, 0]) self.planet_sw2 = planet.Planet(None, r=[240, 0]) self.planet_sw3 = planet.Planet(None, r=[120, 0]) self.little_nodes = [] for i in range(1, 10): node = bhtree.BHTree.BHNode(bhtree.Area(i, i, 1)) self.little_nodes.append(node)
def init_RungeKutta4(): position1 = np.array([0., 0., 0.]) velocity1 = np.array([0., 0., 0.]) planet1 = planet.Planet(1E10, position1, velocity1, "Finera") position2 = np.array([1., 0., 0.]) velocity2 = np.array([0., 0., 0.]) planet2 = planet.Planet(1E10, position2, velocity2, "Genobi") position3 = np.array([1., 0., 0.]) velocity3 = np.array([0., 0., 0.]) planet3 = planet.Planet(1E10, position3, velocity3, "Endor") return simulation.RungeKutta4([planet1, planet2], 0.01, 0.001)
def __init__(self, width_app, height_app): self._width = width_app self._height = height_app self._sun = planet.Planet(width_app, height_app) self._mercury = planet.Planet(width_app, height_app) self._venus = planet.Planet(width_app, height_app) self._background_img = pygame.image.load("fon.jpg") self._background_img.convert() self._mercury_img = pygame.image.load("mercury.png") self._mercury_img.convert() self._sun_img = pygame.image.load("sun.png") self._sun_img.convert() self._venus_img = pygame.image.load("venus.png") self._venus_img.convert()
def test_02_move_character(self): """ add a single character to a world and move them around """ traits = character.CharacterCollection(ref_folder) a1 = mod_agt.Agent(name='a2', fldr=os.getcwd()) a1.characteristics = traits.generate_random_character() world = planet.Planet('SimWorld', num_seeds=5, width=70, height=10, wind=0.3, rain=0.10, sun=0.3, lava=0.4) #world.build_random( 2, 30, 40, 1) actions = ['walk'] s = simulator.SimAdventureGame('Test of SimWorld', world, [a1], actions) s.run() self.assertEqual(len(str(s)), 184) s.command({'name': 'walk', 'type': 'move', 'direction': [1, 1]}, a1) s.command({'name': 'run', 'type': 'run', 'direction': [2, 1]}, a1) s.command({'name': 'fight', 'type': 'fight', 'direction': [2, 1]}, a1)
def test_01_instantiate_sim(self): # make 3 agents a1 = mod_agt.Agent(name='a1', fldr=os.getcwd()) a2 = mod_agt.Agent(name='a2', fldr=os.getcwd()) a3 = mod_agt.Agent(name='a3', fldr=os.getcwd()) # create 3 characters from the Character generator and assign to agents traits = character.CharacterCollection(ref_folder) a1.characteristics = traits.generate_random_character() a2.characteristics = traits.generate_random_character() a3.characteristics = traits.generate_random_character() world = planet.Planet('SimWorld', num_seeds=5, width=20, height=15, wind=0.3, rain=0.10, sun=0.3, lava=0.4) actions = ['walk', 'run', 'fight', 'buy', 'sell', 'collect'] s = simulator.SimAdventureGame('Test of SimWorld', world, [a1, a2, a3], actions) s.run() self.assertEqual(len(str(s)), 354)
def create_planets(self): rng = random.Random(self.seed) for _ in range(self.get_num_planets()): new_seed = str(self.seed) + str(rng.randint( 0, 10000)) + "createplanet" p = planet.Planet(new_seed, self) self.planets.append(p)
def test_11_game_of_life(self): traits = character.CharacterCollection(ref_folder) a1 = mod_agt.Agent(name='Life', fldr=os.getcwd()) a1.characteristics = traits.generate_random_character( ) # No, this should not be a adventure character world = planet.Planet('SimWorld', num_seeds=5, width=20, height=15, wind=0.3, rain=0.10, sun=0.3, lava=0.4) actions = ['walk'] s = simulator.SimAdventureGame('Test of Game of Life', world, [a1], actions) s.run() #print(s) self.assertTrue(len(str(s)) > 10) tst_world, tst_status, tst_log = s.get_state() print('game of life state tst_world= ', tst_world) print('game of life state tst_status= ', tst_status) print('game of life state tst_log= ', tst_log) self.assertTrue(len(str(tst_world)) > 10) self.assertEqual(tst_status, 'Waiting for Command') self.assertEqual(tst_log, [])
def test_onefeed(self): configp = ConfigParser() configp.readfp(StringIO("""[http://www.example.com/] name = Mary """)) my_planet = planet.Planet(configp) my_planet.run("Planet Name", "http://example.com", [], True)
def startgame(difficulty=0): ''' difficuly factors: -size of planet to defend: larger planet = harder since less time to kill enemies -number enemies (duh) -capability of beam to fire through multiple enemies or just 1 ''' global rungame rungame.difficulty = difficulty #make players players_exist = False for x in rungame.entities: if isinstance(x, player.PlayerLeft): players_exist = True break if players_exist == False: p1 = player.PlayerLeft(50, 50) p2 = player.PlayerRight(200, 50) rungame.entities.append(p1) rungame.entities.append(p2) if difficulty == 0: #current all-encompasing difficulty p = planet.Planet(500, 75) #hp, radius rungame.entities.append(p) rungame.dolevel()
def __init__(self, width=800, height=800): pygame.init() pygame.display.set_caption("Steven Lander") self.width = width self.height = height self.window = pygame.display.set_mode((width, height)) self.background = pygame.Surface(self.window.get_size()).convert() self.clock = pygame.time.Clock() #FONTS USED IN THE GUI self.titleFont = pygame.font.SysFont("monospace", 45) self.mainFont = pygame.font.SysFont("monospace", 22) scoreFile = open("score.txt", "r") self.highscore = float(scoreFile.readline()) scoreFile.close() self.win = False self.died = False self.menu = True self.enableInput = True self.score = 0 self.difficulty = 0 #used for score calculation self.spawnRate = 5 #used to determine the spawn rate of asteroids and fuelpods self.planet = planet.Planet(.1, 20) self.asteroids = [] #lists to keep track of objects on the screen self.fuelpods = [] self.sprites = pygame.sprite.Group() self.terrain = pygame.Rect(0, 0, 0, 0)
def deviation( dvx1: object, dvy1: object, dvx2: object, dvy2: object, dist, plot: object = False ) -> object: #simulation of first half of the orbit if plot: arrX.clear() arrY.clear() global dt unitmass = 1.0 ut = unit.Unit(np.array([1.0, 0.0, 0.0]), np.array([0.0 + dvx1, 1.0 + dvy1, 0.0]), unitmass) sp = space.Space() planetmass = 1.0 / G pl = planet.Planet(planetmass) sp.planet = pl sp.unit = ut pos = ut.pos angle = 0 E0 = ut.getEnergy(planetmass) A0 = ut.vectorLenc(planetmass) flag = False while True: #Condition for the whole orbit if (ut.pos[1] < ut.vel[1] * dt) and (ut.pos[0] < 0) and not flag: flag = True ut.vel[0] += dvx2 ut.vel[1] += dvy2 elif flag and (ut.pos[0] > 0) and (ut.pos[1] > 0): #pos_next = ut.pos[1] + ut.vel[1] * dt #vel_next = ut.vel + pl.acceleration(ut.pos) * dt #ut.vel = (ut.vel * abs(pos_next) + vel_next * abs(ut.pos[1])) / (abs(ut.pos[1]) + abs(pos_next)) break angle += math.degrees(0.001 / 57) sp.step_rot(dt, dist, angle) if plot: arrX.append(ut.pos[0]) arrY.append(ut.pos[1]) E = ut.getEnergy(planetmass) A = ut.vectorLenc(planetmass) glob_vel = ut.vel glob_pos = ut.pos delta = ((E - E0)**2) + vectors.squarelength(A - A0) return delta
class main: pygame.init() screen = pygame.display.set_mode((3000, 2000)) clock = pygame.time.Clock() font = pygame.font.Font(None, 30) planet1 = pl.Planet("Earth", (0, 128, 0), 100, pygame.Vector2(1000, 500)) planet2 = pl.Planet("Mars", (255, 100, 0), 7, pygame.Vector2(700, 1000)) planet3 = pl.Planet("Venus", (0, 0, 255), 8, pygame.Vector2(100, 800)) planet4 = pl.Planet("Uranus", (0, 255, 255), 300, pygame.Vector2(1500, 1000)) planet2.setVelocity(pygame.math.Vector2(-0.5, 0.5)) planet1.setVelocity(pygame.math.Vector2(-2, 1)) planet3.setVelocity(pygame.math.Vector2(0, -1)) planets = [planet1, planet2, planet3, planet4] #planets = [planet1, planet2] def update(self): for planet in self.planets: planet.update(self.planets) #a planet knows every other planet def draw(self): #fps stuff self.screen.fill(pygame.Color('black')) fps = self.font.render(str(int(self.clock.get_fps())), True, pygame.Color('white')) self.screen.blit(fps, (50, 50)) #---- for planet in self.planets: planet.draw(self.screen) def __init__(self): done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True self.draw() self.update() pygame.display.flip() self.clock.tick(60)
def test_02_planet(self): p = planet.Planet('vais_test_planet', num_seeds=5, width=20, height=15, wind=0.2, rain=0.20, sun=0.2, lava=0.5) self.assertEqual(len(str(p)) > 10, True)
def __init__(self): p = planet.Planet('SimpleAIWorld', 5, 20, 10, 0.2, 0.2, 0.2, 0.5) traits = character.CharacterCollection(os.getcwd() + os.sep + 'data') #self.a1 = traits.generate_random_character() self.a1 = agt.Agent('Jack') self.a2 = agt.Agent('Jill') #print('type(self.a1) = ', type(self.a1)) actions = ['walk', 'fight'] self.s = simulator.Simulator('Test of SimWorld', p, [self.a1, self.a2], actions) self.s.run() # with no params, it defaults to turn based mode
def test_02_large_planet(self): p2 = planet.Planet('Planet002', num_seeds=8, width=20, height=150, wind=0.5, rain=0.90, sun=0.6, lava=0.5) p2.evolve(years=1000000) self.assertEqual(str(p2)[0:24], '\n-- Welcome to Planet002')
def rebuild_planet_samples(): planets = [] with open(fldr + os.sep + 'planet_samples.csv') as f: hdr = f.readline() for line in f: print("Building ", line) name, num_seeds, width, height, wind, rain, sun, lava = parse_planet_row(line) p = planet.Planet(name, num_seeds, width, height, wind, rain, sun, lava) p.evolve(100) print(p) planets.append(p)
def test_propagate_planets1(): position1 = np.array([0., 0., 0.]) velocity1 = np.array([1., 0., 0.]) planet1 = planet.Planet(1E10, position1, velocity1, "Finera") position2 = np.array([1., 0., 0.]) velocity2 = np.array([-1., 0., 0.]) planet2 = planet.Planet(1E10, position2, velocity2, "Genobi") position3 = np.array([1., 0., 0.]) velocity3 = np.array([0., 0., 0.]) planet3 = planet.Planet(1E10, position3, velocity3, "Kalahan") sim = simulation.EulerLeapfrog([planet1, planet2, planet3], timesteps=1, delta_t=0.01) sim.propagate_bodies() assert np.allclose(planet1.position, np.array([0.01, 0., 0.])) assert np.allclose(planet2.position, np.array([1. - 1. * 0.01, 0., 0.])) assert np.allclose(planet3.position, np.array([1., 0., 0.]))
def test_01_create_planet(self): p = planet.Planet('Planet001', num_seeds=5, width=20, height=15, wind=0.1, rain=0.50, sun=0.4, lava=0.2) p.evolve(years=1000000) print(p) self.assertEqual(str(p)[0:24], '\n-- Welcome to Planet001')
def generate_planet(self): name = "" suffixes = [ " Prime", "", " B", "", " Alpha", "", ' Proxima', "", " IV", "", " V", "", " C", "", " VI", "", " VII", "", " VIII", "", " X", "", " IX", "", " D", "", "", "" ] syllables = random.randint(2, 4) for i in range(syllables): name += random.choice(self.planetparts[i]) name += random.choice(suffixes) faction = random.choice(self.factions) population = random.randint(0, 10000000000) return planet.Planet(name, faction, population)
def test_03_planet_evolve(self): """ NOTE - p.evolve() has errors as there is path in module """ p = planet.Planet('vais_test_planet', num_seeds=4, width=60, height=35, wind=0.4, rain=0.5, sun=0.5, lava=0.5) p.evolve(years=100000) self.assertTrue( os.path.exists(os.path.join(ref_folder, 'vais_test_planet.txt')))
def test_generateall(self): configp = ConfigParser() configp.readfp(StringIO("""[http://www.example.com/] name = Mary """)) my_planet = planet.Planet(configp) my_planet.run("Planet Name", "http://example.com", [], True) basedir = os.path.join(os.path.dirname(os.path.abspath(sys.modules[__name__].__file__)), 'data') os.mkdir(self.output_dir) t_file_names = ['simple', 'simple2'] self._remove_cached_templates(basedir, t_file_names) t_files = [os.path.join(basedir, t_file) + '.tmpl' for t_file in t_file_names] my_planet.generate_all_files(t_files, "Planet Name", 'http://example.com/', 'http://example.com/feed/', 'Mary', '*****@*****.**') for file_name in t_file_names: name = os.path.join(self.output_dir, file_name) content = file(name).read() self.assertEqual(content, 'Mary\n')
def test_21_sim_adventure_game(self): traits = character.CharacterCollection(ref_folder) a21 = mod_agt.Agent(name='a1', fldr=os.getcwd()) a21.characteristics = traits.generate_random_character() world = planet.Planet('SimWorld', num_seeds=5, width=20, height=15, wind=0.3, rain=0.10, sun=0.3, lava=0.4) actions = ['walk'] s = simulator.SimAdventureGame('Test of SimAdventureGame', world, [a21], actions) s.run() print(s) self.assertEqual(len(str(s)), 192)
def menu_start_game(filepath): """ Will start the game with the given file path """ is_levelcorrect, name, width, height, rover_cor, tiles = loader.load_level( filepath) if is_levelcorrect: plant = planet.Planet(name, width, height, tiles) rov = rover.Rover(rover_cor, plant) while not rov.isfinish: user_behavior = input("2") ##"Please choose what you want to do:\n1.SCAN <type>\n2.MOVE <direction> <sycles>\n3.WAIT <cycles>\n4.FINISH" # user_behavior="MOVE 10" input_elements = user_behavior.split(" ") if user_behavior.startswith("SCAN"): # input_elements=user_behavior.split(" ") if len(input_elements) == 2: rov.scan(input_elements[1]) else: print("Please input right command!") elif user_behavior.startswith("MOVE"): if len(input_elements) == 3: rov.move(input_elements[1], input_elements[2]) #rov.stats() else: print("Please input right command!") elif user_behavior.startswith("WAIT"): if len(input_elements) == 2: rov.wait(input_elements[1]) #rov.stats() else: print("Please input right command!") elif user_behavior.startswith("STATS"): if len(input_elements) == 1: rov.stats() else: print("Please input right command!") elif user_behavior.startswith("FINISH"): if len(input_elements) == 1: rov.finish() else: print("Please input right command!") else: print("Please input right command!")
def deviation(dvx, dvy, dist): #simulation of first half of the orbit global glob_pos #some global names to store variables global glob_vel unitmass = 1.0 ut = unit.Unit(np.array([1.0, 0.0, 0.0]), np.array([0.0 + dvx, 1.1 + dvy, 0.0]), unitmass) sp = space.Space() count = 0 planetmass = 1.0 / G pl = planet.Planet(planetmass) sp.planet = pl sp.unit = ut pos = ut.pos dt = 0.001 #simulation step E0 = ut.getEnergy(planetmass) A0 = ut.vectorLenc(planetmass) M0 = ut.getMomentum() while ((ut.pos[1] > ut.vel[1] * dt) or (ut.pos[0] > 0)): #Condition for one half of the orbit #while (ut.movetime(dt) < math.pi): #while (count < math.pi/dt): sp.step(dt, dist) count += 1 arrX.append(ut.pos[0]) arrY.append(ut.pos[1]) E = ut.getEnergy(planetmass) A = ut.vectorLenc(planetmass) M = ut.getMomentum() glob_vel = ut.vel glob_pos = ut.pos #delta = ((E - E0)**2) + vectors.squarelength(M - M0) + vectors.squarelength(A - A0) delta = ((E - E0)**2) + vectors.squarelength(A - A0) #print ('unit position: ',ut.pos) return delta
def deviation2(dvx, dvy, dist): # simulation of the second half sp = space.Space() count = 0 planetmass = 1.0 / G pl = planet.Planet(planetmass) sp.planet = pl unitmass = 1.0 pos = glob_pos vel = glob_vel dv = np.array([dvx, dvy, 0]) ut = unit.Unit(pos, (vel + dv), unitmass) sp.unit = ut #print ('start velocity', ut.vel) dt = 0.001 E0 = ut.getEnergy(planetmass) A0 = ut.vectorLenc(planetmass) M0 = ut.getMomentum() #while (ut.pos[1] < ut.vel[1] * dt) or (ut.pos[0] < 0 ): #Condition for second half of the orbit #while (ut.pos[1] <= 0): while (count < math.pi / dt): sp.step(dt, dist) count += 1 arrX.append(ut.pos[0]) arrY.append(ut.pos[1]) E = ut.getEnergy(planetmass) A = ut.vectorLenc(planetmass) M = ut.getMomentum() #delta = ((E - E0)**2) + vectors.squarelength(M - M0) + vectors.squarelength(A - A0) delta = ((E - E0)**2) + vectors.squarelength(A - A0) #print ('unit position: ', ut.pos , 'unit velocity: ', ut.vel) return delta
def deviation(dvx,dvy, dist): sp = space.Space() count = 0 planetmass = 1.0 / G pl = planet.Planet(planetmass) sp.planet = pl unitmass = 1.0 ut = unit.Unit(np.array([0.9,0.0,0.0]),np.array([0.0+dvx,1.0+dvy,0.0]), unitmass) sp.unit = ut t = 0 angle = 0 dt = 0.01 # simulation step pos0 = np.array([1,0.0,0.0]) pos = ut.pos E0 = ut.getEnergy(planetmass) A0 = ut.vectorLenc(planetmass) U0 = ut.getPotentialEnergy(planetmass) KO = ut.getKinectEnergy() #----------------Arrays of physical quantities ---------------- arrE = [] arrt = [] arrT = [] arrX = [] arrY = [] arrU = [] arrK = [] arrA = [] arrM = [] arrM_full = [] arrMx = [] arrMy = [] arrMz = [] arrAx = [] arrAy = [] arrAz = [] arrAngle = [] arrA_full = [] #------------------Simulation cycle----------------------------- n = 10 # number of circles while (t<(2*math.pi)*n): #one circle sp.step_rot(dt, dist, angle) count +=1 t+=dt angle+= math.degrees(0.001/57) E = ut.getEnergy(planetmass) U = ut.getPotentialEnergy(planetmass) K = ut.getKinectEnergy() A = ut.vectorLenc(planetmass) M = ut.getMomentum() Angle = math.atan2(ut.vectorLenc(planetmass)[0],ut.vectorLenc(planetmass)[1]) T = t / (2 * math.pi) # number of orbits done #-----------------Filling the arrays---------------------------- arrK.append(K) arrE.append(E) arrU.append(U) arrt.append(t) arrT.append(T) arrX.append(ut.pos[0]) arrY.append(ut.pos[1]) arrA.append(A) arrAx.append(A[0]) arrAy.append(A[1]) arrAz.append(A[2]) arrA_full.append(A[0]+A[1]+A[2]) arrMx.append(M[0]) arrMy.append(M[1]) arrMz.append(M[2]) arrM_full.append(M[0]+M[1]+M[2]) arrAngle.append(Angle) #-------------------------------------------------------------- #plt.plot(lnh, lnE) #------------------ graph plotting----------------------------- plt.figure(1) plt.xlabel('Number of circles') plt.ylabel('Potential Energy') plt.title('Potential Energy of the spacecraft') plt.axis([0, n, 0, 2]) plt.grid(True) plt.plot(arrT,arrU) #plt.plot(arrX,arrY) plt.figure(2) plt.xlabel('Number of circles') plt.ylabel('Angle') plt.grid(True) plt.plot(arrT, arrAngle) plt.figure(3) plt.xlabel('Number of circles') plt.ylabel('E') plt.title('Total Energy of the spacecraft') plt.axis([0, n, -0.7, -0.3]) plt.grid(True) plt.plot(arrT, arrE) plt.figure(4) plt.xlabel('x') plt.ylabel('y') plt.title('Orbit of the spacecraft') plt.axis([-1.5, 1.5, -1.5, 1.5]) plt.grid(True) plt.plot(arrX, arrY) plt.figure(5) plt.axis([0, n, -1, 2]) plt.grid(True) plt.plot(arrT, arrA_full) plt.xlabel('Number of circles') plt.ylabel('A') plt.title('Laplace–Runge–Lenz vector state ') plt.figure(6) plt.axis([0, n, -1, 2]) plt.grid(True) fig, ax = plt.subplots() ax.plot(arrT, arrAx, label ='x_component') ax.plot(arrT, arrAy, label ='y_component') ax.plot(arrT, arrAz, label ='z_component') plt.xlabel('Number of circles') plt.ylabel('A') plt.title('Laplace–Runge–Lenz vector components state ') legend = ax.legend(loc='upper right', shadow=True) frame = legend.get_frame() frame.set_facecolor('0.90') plt.figure(7) plt.axis([0, n, -1, 2]) plt.grid(True) fig, ay = plt.subplots() ay.plot(arrT, arrMx, label='x_component') ay.plot(arrT, arrMy, label='y_component') ay.plot(arrT, arrMz, label='z_component') plt.xlabel('Number of circles') plt.ylabel('A') plt.title('Angular momentum state ') legend = ay.legend(loc='upper right', shadow=True) frame = legend.get_frame() frame.set_facecolor('0.90') # Set the fontsize for label in legend.get_texts(): label.set_fontsize('large') for label in legend.get_lines(): label.set_linewidth(1.5) # the legend line width plt.show() #-------------------------------------------------------------- M = ut.getMomentum() #delta = ((E - E0)**2) + vectors.squarelength(M - M0) + vectors.squarelength(A - A0) delta = ((E - E0) ** 2) + vectors.squarelength(A - A0) return delta
def mainLoop(self): while True: ##THIS SECTION IS USED TO DRAW THE MAIN MENU## tColor = (255, 255, 0) while self.menu: title = self.titleFont.render("STEVEN LANDER", 1, tColor) names = self.mainFont.render("By: Hayden, Jack, and Dillon", 1, tColor) choiceEasy = self.mainFont.render("1. Easy", 1, tColor) choiceMid = self.mainFont.render("2. Hard", 1, tColor) choiceHard = self.mainFont.render("3. Impossible", 1, tColor) choiceQuit = self.mainFont.render("4. Quit", 1, tColor) self.window.blit(title, (250, 150)) self.window.blit(names, (250, 200)) self.window.blit(choiceEasy, (250, 250)) self.window.blit(choiceMid, (250, 300)) self.window.blit(choiceHard, (250, 350)) self.window.blit(choiceQuit, (250, 400)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.KEYUP: if (event.key == pygame.K_1): self.ship = ship.Ship(500) self.sprites.add(self.ship) self.spawnRate = 2 self.difficulty = 1 self.menu = False elif (event.key == pygame.K_2): self.ship = ship.Ship(200) self.sprites.add(self.ship) self.spawnRate = 5 self.difficulty = 5 self.menu = False elif (event.key == pygame.K_3): self.ship = ship.Ship(100) self.sprites.add(self.ship) self.spawnRate = 10 self.difficulty = 15 self.menu = False elif (event.key == pygame.K_4): pygame.quit() pygame.display.flip() self.window.blit(self.background, (0, 0)) ################################################## ##HANDLES DRAWING LABELS ON THE SCREEN## if (self.win and not self.died): self.enableInput = False winLab = self.titleFont.render("YOU WIN!", 1, tColor) resetLab = self.mainFont.render( "Press Space to return to menu", 1, tColor) self.window.blit(resetLab, (350, 100)) self.window.blit(winLab, (300, 50)) if (self.died and not self.win): self.enableInput = False deadLab = self.titleFont.render("YOU CRASHED!", 1, tColor) resetLab = self.mainFont.render( "Press Space to return to menu", 1, tColor) self.window.blit(resetLab, (350, 100)) self.window.blit(deadLab, (350, 50)) pygame.key.set_repeat(1, 50) self.background.fill((0, 0, 0)) if (self.ship.velMagnitude() > 0): self.score = round( self.ship.fuel / self.ship.velMagnitude() * self.difficulty, 2) scoreFile = open("score.txt", "r") self.highscore = float(scoreFile.readline()) scoreFile.close() fuelLab = self.mainFont.render("Fuel: " + str(self.ship.fuel), 1, tColor) velocityLab = self.mainFont.render( "Velocity: " + str(round(self.ship.velMagnitude(), 2)), 1, tColor) scoreLab = self.mainFont.render("Score: " + str(self.score), 1, tColor) hscoreLab = self.mainFont.render( "Highscore: " + str(self.highscore), 1, tColor) self.window.blit(fuelLab, (0, 50)) self.window.blit(velocityLab, (0, 100)) self.window.blit(scoreLab, (0, 150)) self.window.blit(hscoreLab, (0, 200)) ######################### #ASTEROID SPAWNING if (random.randrange(1, 500) <= self.spawnRate): ast = asteroid.Asteroid((770, random.randrange(0, 400))) self.asteroids.append(ast) self.sprites.add(ast) #FUEL SPAWNING if (random.randrange(1, 2000) <= self.spawnRate): fuelObj = fuelpod.FuelPod((770, random.randrange(0, 400))) self.fuelpods.append(fuelObj) self.sprites.add(fuelObj) #APPLIES A CONSTANT GRAVITY self.ship.accelerate((0, self.planet.gravity), "world") ##DRAWS THE TERRAIN self.terrain = pygame.draw.lines(self.window, (255, 255, 255), False, self.planet.nodes) self.platform = pygame.draw.line(self.window, (255, 0, 0), self.planet.plat[0], self.planet.plat[1], 10) pygame.draw.line(self.window, (255, 0, 0), self.planet.platStand[0], self.planet.platStand[1]) ######################### ##HANDLE POSITION UPDATES HERE## self.sprites.update() #Checks to make sure the ship is still on the screen if (self.ship.position[0] > self.width - self.ship.rect.width): self.ship.position = (self.width - self.ship.rect.width, self.ship.position[1]) self.ship.velocity = (0, self.ship.velocity[1]) if (self.ship.position[0] < self.ship.rect.width): self.ship.position = (self.ship.rect.width, self.ship.position[1]) self.ship.velocity = (0, self.ship.velocity[1]) if (self.ship.position[1] < 0): self.ship.position = (self.ship.position[0], 0) self.ship.velocity = (self.ship.velocity[0], 0) self.sprites.draw(self.window) ######################### ##CHECK FOR COLLISIONS## for i in self.asteroids: if (self.ship.rect.colliderect(i) and not self.win): self.died = True self.sprites.remove(self.ship) for i in self.fuelpods: if (self.ship.rect.colliderect(i)): self.ship.fuel += 50 self.sprites.remove(i) self.fuelpods.remove(i) del i if (self.ship.rect.colliderect(self.terrain) and not self.win): self.died = True self.ship.velocity = (0, 0) if (self.ship.rect.colliderect(self.platform)): if (self.ship.velMagnitude() > .7 and not self.win): self.died = True if (self.ship.rotation != 0 and not self.win): self.died = True elif (not self.died and not self.win): self.win = True self.checkHighscore() self.ship.velocity = (0, 0) ######################### #WAY TO HANDLE SEVERAL INPUTS HELD DOWN keys = pygame.key.get_pressed() #checking pressed keys if (self.enableInput ): #Makes sure the ship hasn't crashed or landed if keys[pygame.K_w]: self.ship.fuel -= 1 x = (self.ship.rotation / 90) if (self.ship.rotation != 0): y = 0 else: y = -1 if (self.ship.fuel > 0): self.ship.accelerate((x, y), "world") curSprite = random.choice(["yellow", "red"]) else: curSprite = "normal" else: curSprite = "normal" if keys[pygame.K_d]: self.ship.rotation = 90 #self.ship.image = customRotate(self.ship.image,-1) curSprite += "90" elif keys[pygame.K_a]: #self.ship.turn(-1) self.ship.rotation = -90 #self.ship.image = customRotate(self.ship.image,1) curSprite += "-90" else: self.ship.rotation = 0 #changes the ship sprite to the desired throttle state and rotation self.ship.image = pygame.image.load(curSprite + ".png").convert_alpha() ######################### ##NON GAMEPLAY INPUT## for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.KEYUP: if (event.key == pygame.K_SPACE): if (self.died or self.win): self.menu = True self.sprites.remove(self.ship) self.planet = planet.Planet(.1, 20) self.enableInput = True self.died = False self.win = False for i in self.asteroids: self.sprites.remove(i) for i in self.fuelpods: self.sprites.remove(i) self.fuelpods = [] self.asteroids = [] ######################### pygame.display.flip() self.window.blit(self.background, (0, 0)) self.clock.tick(50) pygame.quit()
usage_error("Missing expected entry ids") # Open the cache file directly to get the URL it represents try: db = dbhash.open(cache_file) url = db["url"] db.close() except dbhash.bsddb._db.DBError, e: print >> sys.stderr, cache_file + ":", e.args[1] sys.exit(1) except KeyError: print >> sys.stderr, cache_file + ": Probably not a cache file" sys.exit(1) # Now do it the right way :-) my_planet = planet.Planet(ConfigParser.ConfigParser()) my_planet.cache_directory = os.path.dirname(cache_file) channel = planet.Channel(my_planet, url) for item_id in ids: if not channel.has_item(item_id): print >> sys.stderr, item_id + ": Not in channel" sys.exit(1) # Do the user's bidding if command == "channel": print_keys(channel, "Channel Keys") elif command == "item": for item_id in ids: item = channel.get_item(item_id)