def spawn(self, game, player, shipId=None): Scenario.spawn(self, game, player, shipId) player.race = game.stats.R_HUMAN shipStats = game.stats.HUMAN_CARGO (x, y) = (self.orbitalbase.xp + 50, self.orbitalbase.yp + 60) flagship = FlagShip(player, shipStats, AiCaptain(player), x, y, 0, 0, 0.0, 0.0, 0.0, 0) flagship.ore = 0 flagship.energy = 0 flagship.ori = 7 / 8 * pi + pi / 2 flagship.turrets[1].buildInstall(game.stats.T_MASS_SR_0) flagship.turrets[0].buildInstall(game.stats.T_MASS_MR_0) player.flagship = flagship game.objects.append(flagship) for i in xrange(3): harvester = HarvesterShip(player, player.race.defaultHarvester, AiPilotHarvester(flagship), 0, 0, 0, 4, 0.0, 0.0, 0.0, 0) flagship.shipyards[harvester.stats.img].docked.append(harvester) player.needToUpdateRelations = True
def create_network(self, controller=Controller): """ Adds a switch, a Kali container, and several mininet hosts to the network created in the base class. TODO: An __init__ parameter should be used to allow overriding prefixlen and host count """ Scenario.create_network(self, controller) # Add switch switch = self.net.addSwitch('s1') # Create a random subnet to add hosts to self.prefixlen = random.randint(24, 27) self.subnet = subnet.generate(self.prefixlen) hosts = list(self.subnet.hosts()) # Add kali self.kali = self.net.addDocker('kali', cls=Kali, ip="%s/%s" % (hosts.pop(), self.prefixlen)) self.net.addLink(switch, self.kali) for i in range(0, random.randint(10, 25)): # If the host list is empty, exit if not hosts: break # Get a random IP from the list of hosts ip = hosts.pop(random.randrange(len(hosts))) # Add a host host = self.net.addHost('h' + str(i), ip="%s/%s" % (ip, self.prefixlen)) # Link host to switch self.net.addLink(switch, host)
def create_network(self, controller=None): """Adds a switch, Kali, vsftpd, and some hosts to the network.""" Scenario.create_network(self, controller) self.add_switch() # Create a random subnet to add hosts to prefixlen = random.randint(27, 29) hosts = list(subnet.generate(prefixlen).hosts()) # Add kali self.kali = self.net.addDocker('kali', cls=Kali, ip="%s/%s" % (hosts.pop(), prefixlen)) self.kali.install_package(*self.packages) self.net.addLink(self.switch, self.kali) # Add ftpd self.ftpd = self.net.addDocker('ftp', cls=Vsftpd, ip="%s/%s" % (hosts.pop(), prefixlen)) self.net.addLink(self.switch, self.ftpd) # Add ftp client for i in range(random.randrange(1, 5)): ftpc = self.net.addHost('ftpc'+str(i), ip="%s/%s" % (hosts.pop(), prefixlen)) self.net.addLink(self.switch, ftpc) self.ftp_clients.append(ftpc)
def createNewScenario(self): scenario = Scenario(self, "New Scenario") self.root = self.tree.AddRoot(scenario.getName()) self.tree.SetPyData(self.root, scenario) self.tree.SetItemImage(self.root, self.fldridx, wx.TreeItemIcon_Normal) self.tree.SetItemImage(self.root, self.fldropenidx, wx.TreeItemIcon_Expanded)
def __init__( self, game, nSystems=3, nPlanets=12, nAsteroidFields=9 ): self.nSystems = nSystems self.nPlanets = nPlanets self.nAsteroidFields = nAsteroidFields self.distBetweenSuns = 30000 self.distBetweenSunsMod = 4000 self.planetDistFromSun = 9000 # also asteroids self.planetDistFromSunMod = 5000 # also asteroids self.minDistBetweenPlanets = 1000 self.player = None self.harvestersAtSpawn = 4 self.wantedBadGuys = 0 Scenario.__init__(self, game ) self.suns = [] self.planets = [] game.astres = [] self.ennemyShips = [] self.generate( game )
def generate_task(self, doc): Scenario.generate_task(self, doc) doc.add_paragraph("In this scenario you have access to two Kali machines in seperate VLANs in the same network. " "The VLANs are somewhere in the range 1-10. ") doc.add_paragraph( "The tool arp-scan is able to find which VLAN you are a part of by specifying a VLAN to scan.") doc.add_paragraph( "The vconfig tool can be used to add a VLAN tag to an interface.") doc.add_paragraph("Answer the following questions: ")
def generate_task(self, doc=Document()): Scenario.generate_task(self, doc) doc.add_paragraph( "DHCP servers assign IP addresses within a set range for a set amount of time. " "This makes them vulnerable to 'starvation' attacks, where a malicious device requests every IP by pretending to be many devices simultaneously." ) doc.add_paragraph( "In this task you'll be performing a starvation attack. To do this you'll need to use Yersinia. NOTE: Do NOT run dhclient until told." ) doc.add_paragraph("Answer the following questions:")
def generate_task(self, doc): Scenario.generate_task(self, doc) doc.add_paragraph( 'In this scenario your kali machine is connected to a switch capable of learning connected MAC adresses, ' 'this means that traffic will be delivered to the correct device once it\'s location has been learned.') doc.add_paragraph( 'This task requires you to use ettercap/arpspoof to trick devices into sending traffic to you instead of the intended recipient, ' 'then Wireshark/tcpdump can be used to analyse packets.') doc.add_paragraph( 'Answer the following questions:')
def __init__(self, game): Scenario.__init__(self, game) self.harvestersAtSpawn = 4 self.wantedBadGuys = 10 self.sol = Sun(game.stats.S_SOL, 0, 0) self.mercury = Planet(game.stats.P_MERCURY, -4100, 1400) # 4332 self.venus = Planet(game.stats.P_VENUS, 5000, 2200) # 5462 self.earth = Planet(game.stats.P_EARTH, -3100, 6700) # 7382 self.mars = Planet(game.stats.P_MARS_1, -7800, -2200) # 8104 self.moon = Planet(game.stats.P_MOON, -3900, 6400) self.jupiter = Planet(game.stats.P_JUPITER, -12000, -4800) # 12924 self.saturn = Planet(game.stats.P_SATURN, 13000, 2500) # 13238 self.neptune = Planet(game.stats.P_NEPTUNE, 15000, 7000) # 16552 self.moon.zp = -50 self.moon.yi = 0.1 self.moon.orbiting = self.earth self.blackHole = BlackHole(game.stats.BH_0, 10000, -10000) for i in xrange(10): # civilians around self.earth dist = randint(100, 800) angle = 2 * pi * random() (x, y) = (self.earth.xp + dist * cos(angle), self.earth.yp + dist * sin(angle)) s = Ship(game.stats.CIVILIAN_0, AiCivilian(), x, y, -20) game.objects.append(s) for i in range(60): # asteroids between self.saturn and self.neptune dist = 15000 angle = (1 - 2 * random()) * pi / 10 + pi / 7 asteroid = Asteroid(game, self.sol.xp + dist * cos(angle), self.sol.yp + dist * sin(angle), 300) game.harvestables.append(asteroid) for i in range(50): # asteroids outer self.mars dist = 9000 angle = (1 - 2 * random()) * pi / 8 + pi * 9 / 8 # 2*random()*pi # asteroid = Asteroid(game, self.sol.xp + dist * cos(angle), self.sol.yp + dist * sin(angle), 200) game.harvestables.append(asteroid) game.astres = [ self.sol, self.mercury, self.venus, self.earth, self.moon, self.mars, self.jupiter, self.saturn, self.neptune, self.moon, self.blackHole ] for i in xrange(self.wantedBadGuys): self.addRandomNpc(game)
def spawn(self, game, player, shipId): # if not player.flagship and player.points >= game.stats.PlayableShips[ shipId ].points: player.race = game.stats.PlayableShips[shipId].race shipStats = game.stats.PlayableShips[shipId].stats dist = randint(10, self.gamma[1].stats.maxRadius) angle = 2 * pi * random() (x, y) = (self.gamma[1].xp + dist * cos(angle), self.gamma[1].yp + dist * sin(angle)) flagship = FlagShip(player, shipStats, AiCaptain(player), x, y, 0, 0, 0.0, 0.0, 0.0, 0) flagship.ore = flagship.stats.maxOre / 2 flagship.energy = flagship.stats.maxEnergy / 2 flagship.ori = 2 * pi * random() if player.race == game.stats.R_EVOLVED: smallTurret = game.stats.T_BURST_LASER_0 mediumTurret = game.stats.T_SUBSPACE_WAVE_0 elif player.race == game.stats.R_NOMAD: smallTurret = game.stats.T_REPEATER_1 mediumTurret = game.stats.T_NOMAD_CANNON_0 elif player.race == game.stats.R_AI: smallTurret = game.stats.T_AI_FLAK_1 mediumTurret = game.stats.T_AI_OMNI_LASER_0 else: smallTurret = game.stats.T_MASS_SR_0 mediumTurret = game.stats.T_MASS_MR_0 for t in flagship.turrets[:2]: t.buildInstall(mediumTurret) for t in flagship.turrets[-2:]: t.buildInstall(smallTurret) player.flagship = flagship game.objects.append(flagship) for i in range(self.harvestersAtSpawn): harvester = HarvesterShip(player, player.race.defaultHarvester, AiPilotHarvester(flagship), 0, 0, 0, 4, 0.0, 0.0, 0.0, 0) flagship.shipyards[harvester.stats.img].docked.append(harvester) Scenario.spawn(self, game, player, shipId=shipId) for i in xrange(0, 3): frigate = Frigate(player, player.race.defaults[ids.B_FRIGATE], AiEscortFrigate(player), x + 100, y + 100) game.objects.append(frigate)
def run_network(self): """Runs `netcat` on hosts in the network to provide open ports to scan""" Scenario.run_network(self) # Open random top ports for scanning for host in self.net.hosts: if host.name == 'kali': continue host.taskPorts = [] for port in range(0, random.randint(0, 4)): host.taskPorts.append(random.choice(top_100_ports)) for port in host.taskPorts: host.cmd('nc', '-l', '-d', '-p', port, '&') if self.developer: self.kali.cmd('ip a') self.kali.cmd('nmap -v %s/%s' % (self.kali.defaultIntf().IP(), self.prefixlen))
def spawn( self, game, player, shipId ): player.race = game.stats.PlayableShips[ shipId ].race shipStats = game.stats.PlayableShips[ shipId ].stats planet = choice( self.planets ) dist = randint( 10, planet.stats.maxRadius ) angle = 2*pi*random() (x,y) = ( planet.xp+dist*cos(angle), planet.yp+dist*sin(angle) ) flagship = FlagShip( player, shipStats, AiCaptain( player ),x,y,0, 0, 0.0,0.0,0.0, 0) flagship.ore = flagship.stats.maxOre/2 flagship.energy = flagship.stats.maxEnergy / 2 flagship.ori = 2*pi*random() if player.race == game.stats.R_EVOLVED: smallTurret = game.stats.T_ESPHERE_0 mediumTurret = game.stats.T_SUBSPACE_WAVE_0 elif player.race == game.stats.R_NOMAD: smallTurret = game.stats.T_REPEATER_1 mediumTurret = game.stats.T_NOMAD_CANNON_0 elif player.race == game.stats.R_AI: smallTurret = game.stats.T_AI_FLAK_1 mediumTurret = game.stats.T_AI_OMNI_LASER_0 else: smallTurret = game.stats.T_MASS_SR_0 mediumTurret = game.stats.T_MASS_MR_0 for t in flagship.turrets[:2]: t.buildInstall( mediumTurret ) for t in flagship.turrets[-2:]: t.buildInstall( smallTurret ) player.flagship = flagship game.objects.append( flagship ) for i in range(self.harvestersAtSpawn): harvester = HarvesterShip(player, player.race.defaultHarvester, AiPilotHarvester(flagship), 0,0,0, 4, 0.0,0.0,0.0, 0) flagship.shipyards[ harvester.stats.img ].docked.append( harvester ) Scenario.spawn( self, game, player, shipId=shipId ) for i in xrange( 0, 3 ): frigate = Frigate( player, player.race.defaults[ ids.B_FRIGATE ], AiEscortFrigate( player ), x+100, y+100 ) game.objects.append( frigate )
def __init__(self, game): Scenario.__init__(self, game ) self.harvestersAtSpawn = 4 self.wantedBadGuys = 10 self.sol = Sun( game.stats.S_SOL, 0, 0 ) self.mercury = Planet( game.stats.P_MERCURY, -4100, 1400 ) # 4332 self.venus = Planet( game.stats.P_VENUS, 5000, 2200 ) # 5462 self.earth = Planet( game.stats.P_EARTH, -3100, 6700 ) # 7382 self.mars = Planet( game.stats.P_MARS_1, -7800, -2200 ) # 8104 self.moon = Planet( game.stats.P_MOON, -3900, 6400 ) self.jupiter = Planet( game.stats.P_JUPITER, -12000, -4800 ) # 12924 self.saturn = Planet( game.stats.P_SATURN, 13000, 2500 ) # 13238 self.neptune = Planet( game.stats.P_NEPTUNE, 15000, 7000 ) # 16552 self.moon.zp = -50 self.moon.yi = 0.1 self.moon.orbiting = self.earth self.blackHole = BlackHole( game.stats.BH_0, 10000, -10000 ) for i in xrange( 10 ): # civilians around self.earth dist = randint( 100, 800 ) angle = 2*pi*random() (x,y) = (self.earth.xp+dist*cos(angle), self.earth.yp+dist*sin(angle)) s = Ship( game.stats.CIVILIAN_0, AiCivilian(), x, y, -20 ) game.objects.append( s ) for i in range( 60 ): # asteroids between self.saturn and self.neptune dist = 15000 angle = (1-2*random())*pi/10+pi/7 asteroid = Asteroid( game, self.sol.xp+dist*cos(angle), self.sol.yp+dist*sin(angle), 300 ) game.harvestables.append( asteroid ) for i in range( 50 ): # asteroids outer self.mars dist = 9000 angle = (1-2*random())*pi/8+pi*9/8 # 2*random()*pi # asteroid = Asteroid( game, self.sol.xp+dist*cos(angle), self.sol.yp+dist*sin(angle), 200 ) game.harvestables.append( asteroid ) game.astres = [self.sol, self.mercury, self.venus, self.earth, self.moon, self.mars, self.jupiter, self.saturn, self.neptune, self.moon, self.blackHole ] for i in xrange( self.wantedBadGuys ): self.addRandomNpc( game )
def testScenario(self): from scenarios import Scenario, scenario_config s = [] for sc in scenario_config: s.append(Scenario(**sc)) self.assertEqual(12, s[0].N_Months) self.assertEqual(1000, s[0].honeycomb_size_in_hive)
def spawn( self, game, player, shipId=None ): Scenario.spawn( self, game, player, shipId ) player.race = game.stats.R_HUMAN shipStats = game.stats.HUMAN_SCOUT (x,y) = self.startingPoint flagship = FlagShip( player, shipStats, AiCaptain( player ),x,y,0, 0, 0.0,0.0,0.0, 0) flagship.ore = flagship.stats.maxOre flagship.energy = 0 flagship.ori = 7/8*pi+pi/2 player.flagship = flagship game.objects.append( flagship ) player.needToUpdateRelations = True
def spawn(self, game, player, shipId=None): Scenario.spawn(self, game, player, shipId) player.race = game.stats.R_HUMAN shipStats = game.stats.HUMAN_SCOUT (x, y) = self.startingPoint flagship = FlagShip(player, shipStats, AiCaptain(player), x, y, 0, 0, 0.0, 0.0, 0.0, 0) flagship.ore = flagship.stats.maxOre flagship.energy = 0 flagship.ori = 7 / 8 * pi + pi / 2 player.flagship = flagship game.objects.append(flagship) player.needToUpdateRelations = True
def generate_task(self, doc): Scenario.generate_task(self, doc) doc.add_paragraph( 'In this scenario your kali machine is connected to a switch capable of learning connected MAC adresses, ' 'this means that traffic will be delivered to the correct device rather than all devices after seeing the device\'s MAC send a packet. ' ) doc.add_paragraph( 'MAC Addresses in this scenario are learned by storing them in a Content Addressable Memory (CAM) table, a dictionary of MACs to Ports. ' ) doc.add_paragraph( 'CAM tables such as this one are vulnerable to an attack known as flooding, where by filling the CAM table the switch is forced to relearn the MAC. ' 'Until the MAC address is relearned any packets sent to it are flooded on all of the switches ports, and visable to devices connected to those ports. ' ) doc.add_paragraph( 'This task requires you to use the \'macof\' to peform CAM Table flooding, then Wireshark/tcpdump can be used to analyse packets. ' ) doc.add_paragraph( 'NOTE: The macof tool generates a large amount of traffic that slow the network to a crawl like a DOS attack. If you aren\'t succesful in capturing traffic, pause your attack for a bit' ) doc.add_paragraph('Answer the following questions:')
def __init__(self, game, steps=None, name=None, description=None, year=0): stats = Stats() # stats.R_HUMAN.turrets = [ stats.T_SOLAR_0 ] # stats.R_HUMAN.missiles = [] # stats.R_HUMAN.ships = [] stats.PlayableShips = {} steps = [] for i in xrange(8): steps.append( Step(goal=lambda self, game: not filter( lambda ship: ship.alive, self.ennemyShips), onBegin=lambda self, game, stepNbr=i + 1: self. stepFunction(game, stepNbr), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts=[(1, "Clear the area.")])) Scenario.__init__(self, game, steps=steps, stats=stats) self.sol = Sun(game.stats.S_SOL, 4000, 0) for i in range(75): # asteroids asteroid = Asteroid(game, -2000, 0, 800) game.harvestables.append(asteroid) game.astres = [self.sol] self.player = None self.startingPoint = (-1000, 0) self.ennemyPosition = (-2000, 0) self.ennemy = Faction(game.stats.R_EXTRA, "Unknown") game.addPlayer(self.ennemy) self.infestedAsteroid = Asteroid(game, self.ennemyPosition[0], self.ennemyPosition[1], 0) game.harvestables.append(self.infestedAsteroid) self.ennemyShips = []
def spawn( self, game, player, shipId=None ): print "spawning" player.race = game.stats.R_HUMAN shipStats = game.stats.HUMAN_FS_0 (x,y) = self.startingPoint flagship = FlagShip( player, shipStats, AiCaptain( player ),x,y,0, 0, 0.0,0.0,0.0, 0) flagship.ore = flagship.stats.maxOre flagship.energy = 1000 flagship.ori = 7/8*pi+pi/2 for turret in flagship.turrets[2:4]: turret.buildInstall( game.stats.T_MASS_SR_1 ) player.flagship = flagship game.objects.append( flagship ) # self.player = player Scenario.spawn( self, game, player, shipId )
def spawn(self, game, player, shipId=None): print "spawning" player.race = game.stats.R_HUMAN shipStats = game.stats.HUMAN_FS_0 (x, y) = self.startingPoint flagship = FlagShip(player, shipStats, AiCaptain(player), x, y, 0, 0, 0.0, 0.0, 0.0, 0) flagship.ore = flagship.stats.maxOre flagship.energy = 1000 flagship.ori = 7 / 8 * pi + pi / 2 for turret in flagship.turrets[2:4]: turret.buildInstall(game.stats.T_MASS_SR_1) player.flagship = flagship game.objects.append(flagship) # self.player = player Scenario.spawn(self, game, player, shipId)
def __init__(self, game, steps=None, name=None, description=None, year=0): stats = Stats() # stats.R_HUMAN.turrets = [ stats.T_SOLAR_0 ] # stats.R_HUMAN.missiles = [] # stats.R_HUMAN.ships = [] stats.PlayableShips = {} steps = [] for i in xrange( 8 ): steps.append( Step( goal=lambda self, game: not filter( lambda ship: ship.alive, self.ennemyShips ), onBegin=lambda self, game, stepNbr=i+1: self.stepFunction( game, stepNbr ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (1,"Clear the area.")] ) ) Scenario.__init__(self, game, steps=steps, stats=stats ) self.sol = Sun( game.stats.S_SOL, 4000, 0 ) for i in range( 75 ): # asteroids asteroid = Asteroid( game, -2000, 0, 800 ) game.harvestables.append( asteroid ) game.astres = [ self.sol ] self.player = None self.startingPoint = ( -1000, 0 ) self.ennemyPosition = ( -2000, 0 ) self.ennemy = Faction( game.stats.R_EXTRA, "Unknown" ) game.addPlayer( self.ennemy ) self.infestedAsteroid = Asteroid( game, self.ennemyPosition[0], self.ennemyPosition[1], 0 ) game.harvestables.append( self.infestedAsteroid ) self.ennemyShips = []
def spawn( self, game, player, shipId=None ): player.race = game.stats.R_HUMAN shipStats = game.stats.HUMAN_BASE_MINING (x,y) = ( self.earth.xp-320, self.earth.yp+380 ) flagship = OrbitalBase( player, shipStats, AiGovernor( player ),x,y,0, 0, 0.0,0.0,0.0, 0) flagship.ore = 5000 flagship.energy = 1000 flagship.ri = -0.01 flagship.turrets[3].buildInstall( game.stats.T_MASS_MR_0 ) flagship.turrets[1].buildInstall( game.stats.T_MASS_MR_0 ) player.flagship = flagship game.objects.append( flagship ) for i in xrange( 6 ): harvester = HarvesterShip(player, player.race.defaultHarvester, AiPilotHarvester(flagship), 0,0,0, 4, 0.0,0.0,0.0, 0) flagship.shipyards[ harvester.stats.img ].docked.append( harvester ) player.needToUpdateRelations = True Scenario.spawn( self, game, player, shipId )
def spawn( self, game, player, shipId=None ): Scenario.spawn( self, game, player, shipId ) player.race = game.stats.R_HUMAN shipStats = game.stats.HUMAN_CARGO (x,y) = ( self.orbitalbase.xp+50, self.orbitalbase.yp+60 ) flagship = FlagShip( player, shipStats, AiCaptain( player ),x,y,0, 0, 0.0,0.0,0.0, 0) flagship.ore = 0 flagship.energy = 0 flagship.ori = 7/8*pi+pi/2 flagship.turrets[1].buildInstall( game.stats.T_MASS_SR_0 ) flagship.turrets[0].buildInstall( game.stats.T_MASS_MR_0 ) player.flagship = flagship game.objects.append( flagship ) for i in xrange( 3 ): harvester = HarvesterShip(player, player.race.defaultHarvester, AiPilotHarvester(flagship), 0,0,0, 4, 0.0,0.0,0.0, 0) flagship.shipyards[ harvester.stats.img ].docked.append( harvester ) player.needToUpdateRelations = True
def __init__(self, game, steps=None, name=None, description=None, year=0): stats = Stats() stats.R_HUMAN.turrets = [ stats.T_SOLAR_0 ] stats.R_HUMAN.missiles = [] stats.R_HUMAN.ships = [] stats.PlayableShips = {} steps = [ Step( goal=lambda self, game: game.tick-9*config.fps>=self.lastStepAt and self.player.inputs.xc and not utils.distLowerThan( (self.player.inputs.xc+self.player.inputs.wc/2, self.player.inputs.yc+self.player.inputs.hc/2 ), self.player.flagship.pos, 200 ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0,_("Look around your ship a bit.")), (config.fps*3, _("To move the camera, either use the arrow keys...")), (config.fps*6, _("or click on the radar in the upper left corner."))] ), Step( goal=lambda self, game: game.tick-6*config.fps>=self.lastStepAt and utils.distLowerThan( (self.player.inputs.xc+self.player.inputs.wc/2, self.player.inputs.yc+self.player.inputs.hc/2 ), self.player.flagship.pos, 2 ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0,_("Good, now stick the camera to your ship.")), (config.fps*3, _("To do so, click on the center of the radar.")),] ), Step( goal=lambda self, game: game.tick-9*config.fps>=self.lastStepAt and not utils.distLowerThan( self.startingPoint, self.player.flagship.pos, 100 ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0,_("Now move away from the orbital station.")), (3*config.fps, _("To move the ship, left-click on the destination and your crew will manoeuver towards there.") ), (6*config.fps, _("To give the order to stop, left-click on the ship.") ) ] ), Step( goal=lambda self, game: filter( lambda turret: turret.building==stats.T_SOLAR_0, self.player.flagship.turrets ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0,_("Let's prepare ourselves before going out to explore.")), (3*config.fps, _("Jumping uses a lot of energy, so first build 2 solar arrays on your ship.") ), (6*config.fps, _("To do so, left-click on one of the black circle at the right of the screen.") ), (9*config.fps, _("Then select the solar array from the list.") ) ] ), Step( goal=lambda self, game: filter( lambda turret: turret.install and turret.install.stats==stats.T_SOLAR_0, self.player.flagship.turrets ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0,_("Well done, it will take a little while for it to be completed.")), (3*config.fps, _("Begin building the second one right away.") ), (9*config.fps, _("Notice the green bar in the top right corner...") ), (12*config.fps, _("it indicates the proportion of energy in your battery.") ), (15*config.fps, _("The quantity is indicated in green text next to it..") ) ] ), Step( goal=lambda self, game: len(filter( lambda turret: turret.install and turret.install.stats==stats.T_SOLAR_0, self.player.flagship.turrets ) ) >= 2 and game.tick-6*config.fps>=self.lastStepAt, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0,_("Every ship benefits from solar energy the closer they are to a sun.") ), (3*config.fps,_("A solar array will capture even more solar energy but will consume a little when in deep space.") ) ] ), Step( goal=lambda self, game: self.player.flagship.jumping, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0,_("We still need to fill the battery before jumping.")), (3*config.fps, _("Use the long-range sensor in fullscreen mode to see our destination.") ), (6*config.fps, _("Left-click on the Radar button in the upper-left corner.") ), (12*config.fps, _("Notice your poition over Earth. It will be useful to come back.") ), (15*config.fps, _("Mars is the 4th planet from the sun.") ), (18*config.fps, _("You can see it on the right of the asteroid field down left from you.")), (21*config.fps, _("To execute the jump, left-click on the blue button at the top of the screen") ), (24*config.fps, _("the left-click on the destination, the planet Mars.") ), ] ), Step( goal=lambda self, game: not self.player.flagship.jumping, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, onBegin=lambda self, game: self.addEnnemyShip( game, self.ennemyPosition ), texts = [ ( 0, _("Know that you can change the destination of the jump while it charges.") ), (3*config.fps, _("Go back to normal view by clicking on the radar button again.") ), ] ), Step( goal=lambda self, game: utils.distLowerThan( self.ennemyPosition, self.player.flagship.pos, 500 ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ ( config.fps, _("Now head for the asteroid field.") ), ( 4*config.fps, _("Reports are that there is a anormal rotating asteroid towards the bottom of the field.") ), ( 7*config.fps, _("Investigate it.") ) ] ), Step( goal=lambda self, game: utils.distLowerThan( self.ennemyPosition, self.player.flagship.pos, 200 ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ ( 0, _("It may be dangerous but get closer to gather data.") ) ] ), Step( goal=lambda self, game: self.player.flagship.jumping, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ ( 0, _("What ever it is. It is hostile!") ), ( 1*config.fps, _("Enough data collected.") ), ( 2*config.fps, _("Jump away now!") ) ] ), Step( goal=lambda self, game: not self.player.flagship.jumping, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ ( 0, _("Don't worry, your shield and hull should be able to handle the hits for a little longer.") ) ] ), Step( goal=lambda self, game: utils.distLowerThanObjects( self.player.flagship, self.orbitalbase, 2000 ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ ( 1, _("Head back to Earth.") ) ] ), Step( goal=lambda self, game: utils.distLowerThanObjects( self.player.flagship, self.orbitalbase, 100 ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0, _("Return to the orbital station.")), ( 3*config.fps, _("Collected data will be useful if they ever try to get closer to Earth.") ) ] ), ] Scenario.__init__(self, game, steps=steps, stats=stats ) ### redefining stats, dangerous self.sol = Sun( game.stats.S_SOL, 0, 0 ) self.mercury = Planet( game.stats.P_MERCURY, -4100, 1400 ) self.venus = Planet( game.stats.P_VENUS, 5000, 2300 ) self.earth = Planet( game.stats.P_EARTH, -3100, 6700 ) self.mars = Planet( game.stats.P_MARS_1, -7800, -2300 ) self.moon = Planet( game.stats.P_MOON, -3900, 6400 ) self.jupiter = Planet( game.stats.P_JUPITER, -13000, -4800 ) self.saturn = Planet( game.stats.P_SATURN, 13000, 2500 ) self.neptune = Planet( game.stats.P_NEPTUNE, 15000, 7000 ) self.moon.zp = -50 self.moon.yi = 0.1 self.moon.orbiting = self.earth for i in range( 50 ): # asteroids outer self.mars dist = 9000 angle = (1-2*random())*pi/8+pi*9/8 asteroid = Asteroid( game, self.sol.xp+dist*cos(angle), self.sol.yp+dist*sin(angle), 300 ) game.harvestables.append( asteroid ) for i in range( 60 ): # asteroids between self.saturn and self.neptune dist = 15000 angle = (1-2*random())*pi/10+pi/7 asteroid = Asteroid( game, self.sol.xp+dist*cos(angle), self.sol.yp+dist*sin(angle), 300 ) game.harvestables.append( asteroid ) game.astres = [self.sol, self.mercury, self.venus, self.earth, self.moon, self.mars, self.jupiter, self.saturn, self.neptune, self.moon ] dist = self.earth.stats.maxRadius*1.5 angle = 5*pi/8 self.orbitalbase = OrbitalBase( None, game.stats.HUMAN_BASE_MINING, None, self.earth.xp+dist*cos(angle),self.earth.yp+dist*sin(angle)) self.orbitalbase.ri = -0.013 game.objects.append( self.orbitalbase ) self.player = None self.startingPoint = ( self.orbitalbase.xp+50, self.orbitalbase.yp+60 ) dist = 9000 angle = pi*9/8+pi/8*2/3 self.ennemyPosition = ( self.sol.xp+dist*cos(angle), self.sol.yp+dist*sin(angle) )
counts[input_type] = { 'ref_count': ref_count, 'alt_count': alt_count, 'vaf': vaf } # row_dest either points to the output_rows or expected_rows OrderedDicts row_dest = None scenario_name = None try: # Construct VAF quad out of counts (pull vaf value out) vaf_quad = {} for input_type in input_mafs.keys(): vaf_quad[input_type] = counts[input_type]['vaf'] scenario = Scenario(vaf_quad, scenarios_config_file_path) row_dest = output_rows scenario_name = scenario.name except Scenario.NoScenarioException as e: if not args.total_output: continue else: row_dest = expected_rows row_dest['scenario'].append(scenario_name) for output_column in output_maf_map: input_column = output_maf_map[output_column] row_dest[output_column].append(row[input_column]) for maf_type in maf_types: ref_output_column = '%s_%s' % (ref_count_column_prefix,
def run_network(self): """Runs the network. Adds an OpenFlow rule the the network switch for flood packets on all ports.""" Scenario.run_network(self) self.add_ftp() # Add a rule to the switch to flood packets self.switch.dpctl("add-flow", "action=flood")
def __init__(self, game): self.player = None self.harvestersAtSpawn = 4 self.wantedBadGuys = 9 steps = [ Step(goal=lambda self, game: not filter(lambda ship: ship.alive, self.ennemyShips), onBegin=lambda self, game: self.addExtrasInFields( game, count=self.wantedBadGuys), failure=lambda self, game: False, texts=[(config.fps * 10, "You are at the Human outpost over Gamma 1."), (config.fps * 20, "There is hostile life forms in the system."), (config.fps * 30, "Clear the asteroids fields above the star Gamma.")]), Step(goal=lambda self, game: not filter(lambda ship: ship.alive, self.ennemyShips), onBegin=lambda self, game: self.addAttackingExtras( game, count=self.wantedBadGuys), failure=lambda self, game: False, texts=[ (0, "The human outpost above Gamma 1 is under attack!"), (config.fps * 10, "Jump to their help in 10s..."), (config.fps * 17, "3s"), (config.fps * 18, "2s"), (config.fps * 19, "1s"), (config.fps * 20, "Jump!") ]), Step(goal=lambda self, game: game.tick - 20 * config.fps >= self. lastStepAt, onBegin=lambda self, game: False, failure=lambda self, game: False, texts=[ (0, "The alien's attack has been succesfully repelled!"), (config.fps * 10, "Congratulations ;)") ]) ] Scenario.__init__(self, game, steps=steps) self.ennemyShips = [] self.gamma = [ Sun(game.stats.S_SOL, 1000, 4000), Planet(game.stats.P_MERCURY_1, 0, -2200), Planet(game.stats.P_X_1, -1000, 11500) ] for i in range(20): # asteroids around self.gamma[1] dist = 750 angle = 2 * pi * random() asteroid = Asteroid(game, self.gamma[1].xp + dist * cos(angle), self.gamma[1].yp + dist * sin(angle), 80) game.harvestables.append(asteroid) for i in range(100): # asteroids around self.gamma area = choice([(7000, 300, 5 * pi / 8, pi / 9), (10000, 400, 6 * pi / 8, pi / 8), (12000, 500, 5 * pi / 8, pi / 11)]) # , 3000 dist = area[0] #randint( area[0]-area[1], area[0]+area[1] ) angle = area[2] + area[3] * (1 - 2 * random()) asteroid = Asteroid(game, self.gamma[0].xp + dist * cos(angle), self.gamma[0].yp + dist * sin(angle), area[1]) game.harvestables.append(asteroid) for i in xrange(10): # civilians around self.gamma[1] dist = randint(100, 800) angle = 2 * pi * random() (x, y) = (self.gamma[1].xp + dist * cos(angle), self.gamma[1].yp + dist * sin(angle)) s = Ship(game.stats.CIVILIAN_0, AiCivilian(), x, y, -20) game.objects.append(s) game.astres = self.gamma # for i in range( 5 ): # self.addExtrasInFields( game ) spots = [] for o in game.astres: if isinstance(o, Planet) and not isinstance(o, Sun): spots.append(o) for i in xrange(30): # random civilians spot = choice(spots) dist = randint(100, 800) angle = 2 * pi * random() (x, y) = (spot.xp + dist * cos(angle), spot.yp + dist * sin(angle)) s = Ship(game.stats.CIVILIAN_0, AiCivilian(), x, y, -20) game.objects.append(s) self.humanDefense = Faction(game.stats.R_HUMAN, "Human Defenses") nbrBases = 3 for i in xrange(nbrBases): dist = self.gamma[1].stats.maxRadius * 1.8 #(1.8+0.4*random()) angle = pi * i * 2 / nbrBases obase = OrbitalBase(self.humanDefense, game.stats.HUMAN_BASE, AiGovernor(self.humanDefense), self.gamma[1].xp + dist * cos(angle), self.gamma[1].yp + dist * sin(angle), 0, 0, 0.0, 0.0, 0.0, 0) for t in obase.turrets: if i % 2 == 0: t.install = TurretInstall(game.stats.T_MASS_SR_1) t.weapon = MassWeaponTurret(game.stats.W_MASS_SR_1) else: t.install = TurretInstall(game.stats.T_MASS_MR_1) t.weapon = MassWeaponTurret(game.stats.W_MASS_MR) t.ai = AiWeaponTurret() obase.ori = angle + pi / 2 obase.orbiting = self.gamma[1] obase.xi = cos(obase.ori) obase.yi = sin(obase.ori) obase.ore = obase.stats.maxOre obase.ri = -0.008 game.objects.append(obase) self.humanDefense.bases.append(obase) for i in xrange(10): radius = self.gamma[1].stats.maxRadius * (2.5) dist = self.gamma[1].stats.maxRadius * (1.5 + 1 * random()) angle = 2 * pi * random() # AiPilotDefense fighter = ShipSingleWeapon(self.humanDefense, game.stats.HUMAN_FIGHTER, AiPilotPolice(self.gamma[1], radius), self.gamma[1].xp + dist * cos(angle), self.gamma[1].yp + dist * sin(angle), 0, 4, 0.0, 0.0, 0.0, 0) game.objects.append(fighter) self.humanDefense.ships.append(fighter) # self.humanDefense.bases.append( obase ) game.addPlayer(self.humanDefense) ## Extra self.extraRock0 = Faction(game.stats.R_EXTRA, "Rocks") game.addPlayer(self.extraRock0)
def train_mine_policy(scenario: Scenario, horizon: int, batch_size: int, epochs: int, ntrvs: int, mine_class: nn.Module, mine_params, q_net: nn.Module, pi_net: nn.Module, tradeoff: float, lr: float, tag: str = None, save_every: int = 100, log_video_every: Union[int, None] = None, minibatch_size=0, opt_iters=1, lowest_mi=np.inf, cutoff=np.inf, device=pt.device('cpu')): q_net.to(device=device) pi_net.to(device=device) opt = pt.optim.Adam(list(pi_net.parameters()) + list(q_net.parameters()), lr=lr) mine = [mine_class().to(device=device) for t in range(horizon)] last_time = time.time() mi = pt.zeros(horizon).to(device=device) scenario.device = pt.device('cpu') prev_best_value = np.inf current_value = np.inf if minibatch_size == 0: minibatch_size = batch_size if tag is not None: writer = SummaryWriter(f'runs/{tag}', flush_secs=1) for epoch in range(epochs): #if epoch % save_every == 0 or epoch == epochs - 1: start_epoch_event = pt.cuda.Event(enable_timing=True) end_epoch_event = pt.cuda.Event(enable_timing=True) end_rollout_event = pt.cuda.Event(enable_timing=True) start_epoch_event.record() pi_log_probs = pt.zeros((horizon, minibatch_size), device=device) q_log_probs = pt.zeros((horizon, minibatch_size), device=device) q_net.cpu() pi_net.cpu() states, outputs, samples, trvs, inputs, costs = rollout( pi_net, q_net, ntrvs, scenario, horizon, batch_size, pt.device('cpu')) end_rollout_event.record() pt.cuda.synchronize() elapsed_rollout_time = start_epoch_event.elapsed_time( end_rollout_event) / 1000 print(f'Rollout Time: {elapsed_rollout_time:.3f}') print( f'Mean Abs. Displacement: {pt.abs(states[0, -1, :] - states[1, -1, :]).mean().detach().item()}' ) states = states.to(device) outputs = outputs.to(device) samples = samples.to(device) trvs = trvs.to(device) inputs = inputs.to(device) costs = costs.to(device) q_net.to(device) pi_net.to(device) for s in range(batch_size): trv = pt.zeros(ntrvs, device=device) for t in range(horizon): trvs[:, t, s] = q_net(outputs[:, t, s], trv, t, samples[:, t, s])[0] trv = trvs[:, t, s] value = costs.sum(axis=0).mean().item() if tradeoff > -1: states_mi = states.detach().cuda() trvs_mi = trvs.detach().cuda() for t in range(horizon): mine[t].cuda() if epoch == 0: values = train_mine_network( mine[t], (states_mi[:, t, :], trvs_mi[:, t, :]), epochs=100 * mine_params['epochs']) else: train_mine_network(mine[t], (states_mi[:, t, :], trvs_mi[:, t, :]), epochs=mine_params['epochs']) for t in range(horizon): num_datapts = states.shape[2] batch_size = num_datapts joint_batch_idx = np.random.choice(range(num_datapts), size=num_datapts, replace=False) marginal_batch_idx1 = np.random.choice(range(num_datapts), size=num_datapts, replace=False) marginal_batch_idx2 = np.random.choice(range(num_datapts), size=num_datapts, replace=False) joint_batch = pt.cat( (states[:, t, joint_batch_idx], trvs[:, t, joint_batch_idx]), axis=0).t() marginal_batch = pt.cat((states[:, t, marginal_batch_idx1], trvs[:, t, marginal_batch_idx2]), axis=0).t() j_T = mine[t](joint_batch) m_T = mine[t](marginal_batch) mi[t] = j_T.mean() - pt.log(pt.mean(pt.exp(m_T))) mi_sum = mi.sum() baseline = costs.sum(axis=0).mean() current_value = value + tradeoff * mi_sum.detach() if value < cutoff and mi_sum < lowest_mi: print('Saving Model...') lowest_mi = mi_sum.item() pt.save( { 'pi_net_state_dict': pi_net.state_dict(), 'q_net_state_dict': q_net.state_dict() }, f'models/{tag}_epoch_{epoch}_mi_{lowest_mi:.3f}') else: print(f'Current Best: {prev_best_value}') for iter in range(opt_iters): print(f'Computing Iteration {iter}') minibatch_idx = np.random.choice(range(batch_size), size=minibatch_size, replace=False) outputs_minibatch = outputs[:, :, minibatch_idx] trvs_minibatch = trvs[:, :, minibatch_idx] inputs_minibatch = inputs[:, :, minibatch_idx] costs_minibatch = costs[:, minibatch_idx] for s in range(minibatch_size): trv = pt.zeros(ntrvs, device=device) for t in range(horizon): q_log_probs[t, s] = q_net.log_prob(trvs[:, t, s].detach(), outputs_minibatch[:, t, s], trv.detach(), t) pi_log_probs[t, s] = pi_net.log_prob( inputs_minibatch[:, t, s].detach(), trvs_minibatch[:, t, s].detach(), t) trv = trvs_minibatch[:, t, s] opt.zero_grad() loss = pt.mul(pi_log_probs.sum(axis=0), costs_minibatch.sum(axis=0) - baseline).mean() + \ pt.mul(q_log_probs.sum(axis=0), costs_minibatch.sum(axis=0) - baseline).mean() + \ tradeoff * mi_sum loss.backward() opt.step() pi_log_probs = pi_log_probs.detach() q_log_probs = pi_log_probs.detach() if tag is not None: writer.add_scalar('Loss/Total', value + tradeoff * mi.sum().item(), epoch) writer.add_scalar('Loss/MI', mi_sum, epoch) writer.add_scalar('Loss/Cost', value, epoch) writer.add_histogram('Loss/Cost Dist', costs.sum(axis=0), epoch) if log_video_every is not None and epoch % log_video_every == 0: print('Saving Video...') best_traj_idx = pt.argmin(costs.sum(axis=0)) worst_traj_idx = pt.argmax(costs.sum(axis=0)) best_traj_vid = pt.stack([ pt.stack([ outputs[:, t, best_traj_idx].view(3, 64, 64) for t in range(horizon) ]) ]) worst_traj_vid = pt.stack([ pt.stack([ outputs[:, t, worst_traj_idx].view(3, 64, 64) for t in range(horizon) ]) ]) writer.add_video('Loss/Worst Traj', worst_traj_vid, epoch) writer.add_video('Loss/Best Traj', best_traj_vid, epoch) mi = mi.detach() end_epoch_event.record() pt.cuda.synchronize() elapsed_epoch_time = start_epoch_event.elapsed_time( end_epoch_event) / 1000 print( f'[{tradeoff}.{epoch}: {elapsed_epoch_time:.3f}]\t\tAvg. Cost: {value:.3f}\t\tEst. MI: {mi_sum.item():.5f}\t\tTotal: {value + tradeoff * mi_sum.item():.3f}\t\t Lowest MI: {lowest_mi:.3f}' ) if epoch == epochs - 1: return lowest_mi
def __init__( self, game ): self.player = None self.harvestersAtSpawn = 4 self.wantedBadGuys = 9 steps = [ Step( goal=lambda self, game: not filter( lambda ship: ship.alive, self.ennemyShips ), onBegin=lambda self, game: self.addExtrasInFields( game, count=self.wantedBadGuys ), failure=lambda self, game: False, texts = [ (config.fps*10,"You are at the Human outpost over Gamma 1."), (config.fps*20,"There is hostile life forms in the system."), (config.fps*30,"Clear the asteroids fields above the star Gamma.") ] ), Step( goal=lambda self, game: not filter( lambda ship: ship.alive, self.ennemyShips ), onBegin=lambda self, game: self.addAttackingExtras( game, count=self.wantedBadGuys ), failure=lambda self, game: False, texts = [ (0,"The human outpost above Gamma 1 is under attack!"), (config.fps*10,"Jump to their help in 10s..."), (config.fps*17,"3s"), (config.fps*18,"2s"), (config.fps*19,"1s"), (config.fps*20,"Jump!") ] ), Step( goal=lambda self, game: game.tick - 20*config.fps >= self.lastStepAt, onBegin=lambda self, game: False, failure=lambda self, game: False, texts = [ (0,"The alien's attack has been succesfully repelled!"), (config.fps*10,"Congratulations ;)") ] ) ] Scenario.__init__(self, game, steps=steps ) self.ennemyShips = [] self.gamma = [Sun( game.stats.S_SOL, 1000, 4000 ), Planet( game.stats.P_MERCURY_1, 0, -2200 ), Planet( game.stats.P_X_1, -1000, 11500 ) ] for i in range( 20 ): # asteroids around self.gamma[1] dist = 750 angle = 2*pi*random() asteroid = Asteroid( game, self.gamma[1].xp+dist*cos(angle), self.gamma[1].yp+dist*sin(angle), 80 ) game.harvestables.append( asteroid ) for i in range( 100 ): # asteroids around self.gamma area = choice( [(7000, 300, 5*pi/8, pi/9), (10000, 400, 6*pi/8, pi/8), (12000, 500, 5*pi/8, pi/11) ] ) # , 3000 dist = area[0] #randint( area[0]-area[1], area[0]+area[1] ) angle = area[2]+area[3]*(1-2*random()) asteroid = Asteroid( game, self.gamma[0].xp+dist*cos(angle), self.gamma[0].yp+dist*sin(angle), area[1] ) game.harvestables.append( asteroid ) for i in xrange( 10 ): # civilians around self.gamma[1] dist = randint( 100, 800 ) angle = 2*pi*random() (x,y) = (self.gamma[1].xp+dist*cos(angle), self.gamma[1].yp+dist*sin(angle)) s = Ship( game.stats.CIVILIAN_0, AiCivilian(), x, y, -20 ) game.objects.append( s ) game.astres = self.gamma # for i in range( 5 ): # self.addExtrasInFields( game ) spots = [] for o in game.astres: if isinstance( o, Planet ) and not isinstance( o, Sun ): spots.append( o ) for i in xrange( 30 ): # random civilians spot = choice( spots ) dist = randint( 100, 800 ) angle = 2*pi*random() (x,y) = (spot.xp+dist*cos(angle), spot.yp+dist*sin(angle)) s = Ship( game.stats.CIVILIAN_0, AiCivilian(), x, y, -20 ) game.objects.append( s ) self.humanDefense = Faction( game.stats.R_HUMAN, "Human Defenses" ) nbrBases = 3 for i in xrange( nbrBases ): dist = self.gamma[1].stats.maxRadius*1.8 #(1.8+0.4*random()) angle = pi*i*2/nbrBases obase = OrbitalBase( self.humanDefense, game.stats.HUMAN_BASE, AiGovernor( self.humanDefense ),self.gamma[1].xp+dist*cos(angle),self.gamma[1].yp+dist*sin(angle),0, 0, 0.0,0.0,0.0, 0) for t in obase.turrets: if i%2==0: t.install = TurretInstall( game.stats.T_MASS_SR_1 ) t.weapon = MassWeaponTurret( game.stats.W_MASS_SR_1 ) else: t.install = TurretInstall( game.stats.T_MASS_MR_1 ) t.weapon = MassWeaponTurret( game.stats.W_MASS_MR ) t.ai = AiWeaponTurret() obase.ori = angle+pi/2 obase.orbiting = self.gamma[1] obase.xi = cos( obase.ori) obase.yi = sin( obase.ori) obase.ore = obase.stats.maxOre obase.ri = -0.008 game.objects.append( obase ) self.humanDefense.bases.append( obase ) for i in xrange( 10 ): radius = self.gamma[1].stats.maxRadius*(2.5) dist = self.gamma[1].stats.maxRadius*(1.5+1*random()) angle = 2*pi*random() # AiPilotDefense fighter = ShipSingleWeapon(self.humanDefense, game.stats.HUMAN_FIGHTER, AiPilotPolice(self.gamma[1],radius),self.gamma[1].xp+dist*cos(angle),self.gamma[1].yp+dist*sin(angle),0, 4, 0.0,0.0,0.0, 0) game.objects.append( fighter ) self.humanDefense.ships.append( fighter ) # self.humanDefense.bases.append( obase ) game.addPlayer( self.humanDefense ) ## Extra self.extraRock0 = Faction( game.stats.R_EXTRA, "Rocks" ) game.addPlayer( self.extraRock0 )
def generate_task(self, doc): Scenario.generate_task(self, doc) doc.add_paragraph("Template")
def doTurn(self, game): Scenario.doTurn(self, game)
def start_game(self) -> None: scenario = Scenario() scenario.start()
def __init__(self, game, steps=None, name=None, description=None, year=0): stats = Stats() stats.R_HUMAN.turrets = [stats.T_SOLAR_0] stats.R_HUMAN.missiles = [] stats.R_HUMAN.ships = [] stats.PlayableShips = {} steps = [ Step(goal=lambda self, game: game.tick - 9 * config.fps >= self. lastStepAt and self.player.inputs.xc and not utils. distLowerThan((self.player.inputs.xc + self.player.inputs.wc / 2, self.player.inputs.yc + self.player.inputs. hc / 2), self.player.flagship.pos, 200), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts=[ (0, _("Look around your ship a bit.")), (config.fps * 3, _("To move the camera, either use the arrow keys...")), (config.fps * 6, _("or click on the radar in the upper left corner.")) ]), Step(goal=lambda self, game: game.tick - 6 * config.fps >= self. lastStepAt and utils.distLowerThan( (self.player.inputs.xc + self.player.inputs.wc / 2, self. player.inputs.yc + self.player.inputs.hc / 2), self. player.flagship.pos, 2), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts=[ (0, _("Good, now stick the camera to your ship.")), (config.fps * 3, _("To do so, click on the center of the radar.")), ]), Step( goal=lambda self, game: game.tick - 9 * config.fps >= self. lastStepAt and not utils.distLowerThan( self.startingPoint, self.player.flagship.pos, 100), failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, texts= [(0, _("Now move away from the orbital station.")), (3 * config.fps, _("To move the ship, left-click on the destination and your crew will manoeuver towards there." )), (6 * config.fps, _("To give the order to stop, left-click on the ship."))]), Step( goal=lambda self, game: filter( lambda turret: turret.building == stats.T_SOLAR_0, self. player.flagship.turrets), failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, texts= [(0, _("Let's prepare ourselves before going out to explore.")), (3 * config.fps, _("Jumping uses a lot of energy, so first build 2 solar arrays on your ship." )), (6 * config.fps, _("To do so, left-click on one of the black circle at the right of the screen." )), (9 * config.fps, _("Then select the solar array from the list."))]), Step( goal=lambda self, game: filter( lambda turret: turret.install and turret.install.stats == stats.T_SOLAR_0, self.player.flagship.turrets), failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, texts= [(0, _("Well done, it will take a little while for it to be completed." )), (3 * config.fps, _("Begin building the second one right away.")), (9 * config.fps, _("Notice the green bar in the top right corner...")), (12 * config.fps, _("it indicates the proportion of energy in your battery.")), (15 * config.fps, _("The quantity is indicated in green text next to it.."))]), Step( goal=lambda self, game: len( filter( lambda turret: turret.install and turret.install.stats == stats.T_SOLAR_0, self.player.flagship.turrets) ) >= 2 and game.tick - 6 * config.fps >= self.lastStepAt, failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, texts= [(0, _("Every ship benefits from solar energy the closer they are to a sun." )), (3 * config.fps, _("A solar array will capture even more solar energy but will consume a little when in deep space." ))]), Step( goal=lambda self, game: self.player.flagship.jumping, failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, texts=[ (0, _("We still need to fill the battery before jumping.")), (3 * config.fps, _("Use the long-range sensor in fullscreen mode to see our destination." )), (6 * config.fps, _("Left-click on the Radar button in the upper-left corner." )), (12 * config.fps, _("Notice your poition over Earth. It will be useful to come back." )), (15 * config.fps, _("Mars is the 4th planet from the sun.")), (18 * config.fps, _("You can see it on the right of the asteroid field down left from you." )), (21 * config.fps, _("To execute the jump, left-click on the blue button at the top of the screen" )), (24 * config.fps, _("the left-click on the destination, the planet Mars.")), ]), Step( goal=lambda self, game: not self.player.flagship.jumping, failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, onBegin=lambda self, game: self.addEnnemyShip( game, self.ennemyPosition), texts=[ (0, _("Know that you can change the destination of the jump while it charges." )), (3 * config.fps, _("Go back to normal view by clicking on the radar button again." )), ]), Step( goal=lambda self, game: utils.distLowerThan( self.ennemyPosition, self.player.flagship.pos, 500), failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, texts= [(config.fps, _("Now head for the asteroid field.")), (4 * config.fps, _("Reports are that there is a anormal rotating asteroid towards the bottom of the field." )), (7 * config.fps, _("Investigate it."))]), Step(goal=lambda self, game: utils.distLowerThan( self.ennemyPosition, self.player.flagship.pos, 200), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts=[ (0, _("It may be dangerous but get closer to gather data.")) ]), Step(goal=lambda self, game: self.player.flagship.jumping, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts=[(0, _("What ever it is. It is hostile!")), (1 * config.fps, _("Enough data collected.")), (2 * config.fps, _("Jump away now!"))]), Step( goal=lambda self, game: not self.player.flagship.jumping, failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, texts= [(0, _("Don't worry, your shield and hull should be able to handle the hits for a little longer." ))]), Step(goal=lambda self, game: utils.distLowerThanObjects( self.player.flagship, self.orbitalbase, 2000), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts=[(1, _("Head back to Earth."))]), Step( goal=lambda self, game: utils.distLowerThanObjects( self.player.flagship, self.orbitalbase, 100), failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, texts= [(0, _("Return to the orbital station.")), (3 * config.fps, _("Collected data will be useful if they ever try to get closer to Earth." ))]), ] Scenario.__init__(self, game, steps=steps, stats=stats) ### redefining stats, dangerous self.sol = Sun(game.stats.S_SOL, 0, 0) self.mercury = Planet(game.stats.P_MERCURY, -4100, 1400) self.venus = Planet(game.stats.P_VENUS, 5000, 2300) self.earth = Planet(game.stats.P_EARTH, -3100, 6700) self.mars = Planet(game.stats.P_MARS_1, -7800, -2300) self.moon = Planet(game.stats.P_MOON, -3900, 6400) self.jupiter = Planet(game.stats.P_JUPITER, -13000, -4800) self.saturn = Planet(game.stats.P_SATURN, 13000, 2500) self.neptune = Planet(game.stats.P_NEPTUNE, 15000, 7000) self.moon.zp = -50 self.moon.yi = 0.1 self.moon.orbiting = self.earth for i in range(50): # asteroids outer self.mars dist = 9000 angle = (1 - 2 * random()) * pi / 8 + pi * 9 / 8 asteroid = Asteroid(game, self.sol.xp + dist * cos(angle), self.sol.yp + dist * sin(angle), 300) game.harvestables.append(asteroid) for i in range(60): # asteroids between self.saturn and self.neptune dist = 15000 angle = (1 - 2 * random()) * pi / 10 + pi / 7 asteroid = Asteroid(game, self.sol.xp + dist * cos(angle), self.sol.yp + dist * sin(angle), 300) game.harvestables.append(asteroid) game.astres = [ self.sol, self.mercury, self.venus, self.earth, self.moon, self.mars, self.jupiter, self.saturn, self.neptune, self.moon ] dist = self.earth.stats.maxRadius * 1.5 angle = 5 * pi / 8 self.orbitalbase = OrbitalBase(None, game.stats.HUMAN_BASE_MINING, None, self.earth.xp + dist * cos(angle), self.earth.yp + dist * sin(angle)) self.orbitalbase.ri = -0.013 game.objects.append(self.orbitalbase) self.player = None self.startingPoint = (self.orbitalbase.xp + 50, self.orbitalbase.yp + 60) dist = 9000 angle = pi * 9 / 8 + pi / 8 * 2 / 3 self.ennemyPosition = (self.sol.xp + dist * cos(angle), self.sol.yp + dist * sin(angle))
#!/usr/bin/python import sys import os from scenarios.Scenario import * from Plotter.plotter import * import subprocess import time if len(sys.argv) < 2: print "USAGE:python runscen.py path_to_scenario_file collection_path(*optional) policy_name(*optional)" else: scenario = Scenario(sys.argv[1],0) scenario.run() if len(sys.argv) > 3 : print "Collecting results..." if("autoCollect" in sys.argv): time.sleep(5) else: raw_input("Press any key to start collection") print "collect_path:"+sys.argv[2] print "policy_name:"+sys.argv[3] collectPath = sys.argv[2] scenario.policyName = sys.argv[3] plotpath = "./out/plots/"+scenario.pStartDate scenfile = sys.argv[1][sys.argv[1].rfind("/")+1:] scenfile = scenfile[:scenfile.rfind(".")]
def __init__( self, game ): Scenario.__init__(self, game ) self.harvestersAtSpawn = 4 self.wantedBadGuys = 5 sol = Sun( game.stats.S_SOL, 0, 0 ) mercury = Planet( game.stats.P_MERCURY, -4100, 1400 ) venus = Planet( game.stats.P_VENUS, 5000, 2200 ) self.earth = Planet( game.stats.P_EARTH, -3100, 6700 ) self.mars = Planet( game.stats.P_MARS, -7800, -2200 ) moon = Planet( game.stats.P_MOON, -3900, 6400 ) jupiter = Planet( game.stats.P_JUPITER, -12000, -4800 ) saturn = Planet( game.stats.P_SATURN, 13000, 2500 ) neptune = Planet( game.stats.P_NEPTUNE, 15000, 7000 ) moon.zp = -50 moon.yi = 0.1 moon.orbiting = self.earth for i in xrange( 20 ): # civilians around self.earth dist = randint( 100, 800 ) angle = 2*pi*random() (x,y) = (self.earth.xp+dist*cos(angle), self.earth.yp+dist*sin(angle)) s = Ship( game.stats.CIVILIAN_0, AiCivilian(), x, y, -20 ) game.objects.append( s ) for i in range( 60 ): # asteroids between saturn and neptune dist = 15000 angle = (1-2*random())*pi/10+pi/7 asteroid = Asteroid( game, sol.xp+dist*cos(angle), sol.yp+dist*sin(angle), 300 ) game.harvestables.append( asteroid ) for i in range( 30 ): # asteroids outer self.mars dist = 9000 angle = (1-2*random())*pi/8+pi*9/8 asteroid = Asteroid( game, sol.xp+dist*cos(angle), sol.yp+dist*sin(angle), 200 ) game.harvestables.append( asteroid ) nebula = Nebula( game.stats.A_NEBULA, 4800, 500 ) for i in range( 15 ): # asteroids in nebula asteroid = Asteroid( game, 4800, 800, 800 ) game.harvestables.append( asteroid ) self.alphaCentaury = [ Sun( game.stats.S_SOL, -32000, 16000 ), Planet( game.stats.P_MARS_2, -28300, 12000 ), Planet( game.stats.P_SATURN_1, -39000, 8000 ) ] for i in range( 40 ): # asteroids around self.alphaCentaury dist = 4600 #angle = 2*pi*i/50 angle = (1-2*random())*pi/4-pi/8 asteroid = Asteroid( game, self.alphaCentaury[0].xp+dist*cos(angle), self.alphaCentaury[0].yp+dist*sin(angle), 200 ) game.harvestables.append( asteroid ) self.beta = [ Sun( game.stats.S_SOL, 8000, -24000 ), Planet( game.stats.P_MARS_1, 12000, -22000 ), Planet( game.stats.P_X, 500, -21000 ) , Planet( game.stats.P_JUPITER_1, 17000, -24700 )] for i in range( 20 ): # asteroids around self.beta[1] dist = 600 angle = 2*pi*random() asteroid = Asteroid( game, self.beta[1].xp+dist*cos(angle), self.beta[1].yp+dist*sin(angle), 80 ) game.harvestables.append( asteroid ) self.gamma = [Sun( game.stats.S_SOL, 40000, 4000 ), Planet( game.stats.P_MERCURY_1, 39000, -2200 ), Planet( game.stats.P_X_1, 38000, 11500 ) ] for i in range( 20 ): # asteroids around self.gamma[1] dist = 750 angle = 2*pi*random() asteroid = Asteroid( game, self.gamma[1].xp+dist*cos(angle), self.gamma[1].yp+dist*sin(angle), 80 ) game.harvestables.append( asteroid ) for i in range( 100 ): # asteroids around self.gamma area = choice( [(7000, 300, 5*pi/8, pi/9), (10000, 400, 6*pi/8, pi/8), (12000, 500, 5*pi/8, pi/11) ] ) # , 3000 dist = area[0] #randint( area[0]-area[1], area[0]+area[1] ) angle = area[2]+area[3]*(1-2*random()) asteroid = Asteroid( game, self.gamma[0].xp+dist*cos(angle), self.gamma[0].yp+dist*sin(angle), area[1] ) game.harvestables.append( asteroid ) nebula2 = Nebula( game.stats.A_NEBULA, 8000, -16000 ) blackHole0 = BlackHole( game.stats.BH_0, -30000, -20000 ) # for i in range( 15 ): # asteroid = Asteroid( game, -7000, -3200, 800 ) # game.objects.append( asteroid ) # for i in range( 15 ): # asteroid = Asteroid( game, 8500, 6800, 800 ) # game.objects.append( asteroid ) self.sol = [sol, mercury, venus, self.earth, moon, self.mars, jupiter, saturn, neptune, nebula, nebula2 ] game.astres = [sol, mercury, venus, self.earth, moon, self.mars, jupiter, saturn, neptune, nebula, nebula2, blackHole0 ] + self.alphaCentaury + self.beta + self.gamma # game.objects = game.objects # + [sol, mercury, venus, self.earth, moon, self.mars, jupiter, saturn, neptune, nebula, nebula2 ] + self.alphaCentaury + self.beta for i in range( 5 ): self.addRandomNpc( game ) spots = [] for o in game.astres: if isinstance( o, Planet ) and not isinstance( o, Sun ): spots.append( o ) for i in xrange( 30 ): # random civilians spot = choice( spots ) dist = randint( 100, 800 ) angle = 2*pi*random() (x,y) = (spot.xp+dist*cos(angle), spot.yp+dist*sin(angle)) s = Ship( game.stats.CIVILIAN_0, AiCivilian(), x, y, -20 ) game.objects.append( s ) self.marsDefense = Faction( game.stats.R_HUMAN, "Mars Defenses" ) obase = OrbitalBase( self.marsDefense, game.stats.HUMAN_BASE, AiGovernor( self.marsDefense ),self.mars.xp+self.mars.stats.maxRadius*1.5,self.mars.yp+self.mars.stats.maxRadius*1.5,0, 0, 0.0,0.0,0.0, 0) for t in obase.turrets: t.install = TurretInstall( game.stats.T_MASS_SR_0 ) t.weapon = MassWeaponTurret( game.stats.W_MASS_SR_0 ) t.ai = AiWeaponTurret() obase.orbiting = self.mars obase.yi = 1 obase.ore = obase.stats.maxOre obase.ri = -0.008 game.objects.append( obase ) for i in xrange( 20 ): radius = self.mars.stats.maxRadius*(2.5) dist = self.mars.stats.maxRadius*(1.5+1*random()) angle = 2*pi*random() # AiPilotDefense fighter = ShipSingleWeapon(self.marsDefense, game.stats.HUMAN_FIGHTER, AiPilotDefense(self.mars,radius),self.mars.xp+dist*cos(angle),self.mars.yp+dist*sin(angle),0, 4, 0.0,0.0,0.0, 0) game.objects.append( fighter ) self.marsDefense.ships.append( fighter ) self.marsDefense.bases.append( obase ) game.addPlayer( self.marsDefense ) self.earthDefense = Faction( game.stats.R_HUMAN, "Earth Defenses" ) nbrBases = 3 for i in xrange( nbrBases ): dist = self.earth.stats.maxRadius*1.8 #(1.8+0.4*random()) angle = pi*i*2/nbrBases obase = OrbitalBase( self.earthDefense, game.stats.HUMAN_BASE, AiGovernor( self.earthDefense ),self.earth.xp+dist*cos(angle),self.earth.yp+dist*sin(angle),0, 0, 0.0,0.0,0.0, 0) for t in obase.turrets: t.install = TurretInstall( game.stats.T_MASS_MR_0 ) t.weapon = MassWeaponTurret( game.stats.W_MASS_MR ) t.ai = AiWeaponTurret() obase.ori = angle+pi/2 obase.orbiting = self.earth obase.xi = cos( obase.ori) obase.yi = sin( obase.ori) obase.ore = obase.stats.maxOre obase.ri = -0.008 game.objects.append( obase ) self.earthDefense.bases.append( obase ) for i in xrange( 20 ): radius = self.earth.stats.maxRadius*(2.5) dist = self.earth.stats.maxRadius*(1.5+1*random()) angle = 2*pi*random() # AiPilotDefense fighter = ShipSingleWeapon(self.earthDefense, game.stats.HUMAN_FIGHTER, AiPilotPolice(self.earth,radius),self.earth.xp+dist*cos(angle),self.earth.yp+dist*sin(angle),0, 4, 0.0,0.0,0.0, 0) game.objects.append( fighter ) self.earthDefense.ships.append( fighter ) # self.earthDefense.bases.append( obase ) game.addPlayer( self.earthDefense ) ## ai forces self.addAiBase( game, "Neptune base", neptune ) self.addAiBase( game, "Saturn base", saturn ) self.addAiBase( game, "Jupiter base", jupiter, 2 ) ## Evolved self.evolvedSwarm0 = Faction( game.stats.R_EVOLVED, "First Swarm", territories=[Territory((self.alphaCentaury[ 1 ].xp, self.alphaCentaury[ 1 ].yp), 500), Territory((self.alphaCentaury[ 1 ].xp-1000, self.alphaCentaury[ 1 ].yp-500), 500)] ) (x,y) = self.alphaCentaury[ 1 ].xp-self.alphaCentaury[ 1 ].stats.maxRadius*1.5,self.alphaCentaury[ 1 ].yp+self.alphaCentaury[ 1 ].stats.maxRadius*1.5 flagship = FlagShip( self.evolvedSwarm0, game.stats.EVOLVED_FS_1, AiCaptain( self.evolvedSwarm0 ),x,y,0, 0, 0.0,0.0,0.0, 0) flagship.ore = flagship.stats.maxOre for t in flagship.turrets[:-2]: t.install = TurretInstall( game.stats.T_MASS_MR_0 ) t.weapon = MassWeaponTurret( game.stats.W_MASS_MR ) t.ai = AiWeaponTurret() for t in flagship.turrets[-2:]: t.install = TurretInstall( game.stats.T_LASER_SR_0 ) t.weapon = LaserWeaponTurret( game.stats.W_LASER_SR ) t.ai = AiWeaponTurret() for i in range(4): harvester = HarvesterShip(self.evolvedSwarm0, self.evolvedSwarm0.race.defaultHarvester, AiPilotHarvester(flagship), 0,0,0, 4, 0.0,0.0,0.0, 0) flagship.shipyards[ harvester.stats.img ].docked.append( harvester ) for i in xrange( 5 ): if i>=3: fighter = ShipSingleWeapon(self.evolvedSwarm0, game.stats.EVOLVED_BOMBER, AiPilotFighter(flagship),0,0,0, 4, 0.0,0.0,0.0, 0) else: fighter = ShipSingleWeapon(self.evolvedSwarm0, game.stats.EVOLVED_FIGHTER, AiPilotFighter(flagship),0,0,0, 4, 0.0,0.0,0.0, 0) for i in xrange( 10 ): fighter = ShipSingleWeapon(self.evolvedSwarm0, game.stats.EVOLVED_FIGHTER, AiPilotDefense(flagship, 500),0,0,0, 4, 0.0,0.0,0.0, 0) (fighter.xp,fighter.yp) = (flagship.xp,flagship.yp) game.objects.append( fighter ) self.evolvedSwarm0.ships.append( fighter ) # flagship.shipyards[ fighter.stats.img ].docked.append( fighter ) game.objects.append( flagship ) self.evolvedSwarm0.flagships.append( flagship ) game.addPlayer( self.evolvedSwarm0 ) ## Extra TODO remove section self.extraRock0 = Faction( game.stats.R_EXTRA, "Rocks" ) for i in xrange( 0 ): # 4 ): angle = 2*pi*random() dist = 750 # self.gamma[ 1 ].stats.maxRadius* (x,y) = self.gamma[ 1 ].xp-dist*cos(angle),self.gamma[ 1 ].yp+dist*sin(angle) if i%4==0: flagship = FlagShip( self.extraRock0, game.stats.EXTRA_BASE, AiCaptain( self.extraRock0 ),x,y,0, 0, 0.0,0.0,0.0, 0) for k,t in enumerate(flagship.turrets): t.install = TurretInstall( game.stats.T_ROCK_THROWER_1 ) t.weapon = MassWeaponTurret( game.stats.W_ROCK_THROWER_1 ) t.ai = AiWeaponTurret() elif i%4==1: flagship = FlagShip( self.extraRock0, game.stats.EXTRA_FS_1, AiCaptain( self.extraRock0 ),x,y,0, 0, 0.0,0.0,0.0, 0) for k,t in enumerate(flagship.turrets): t.install = TurretInstall( game.stats.T_DRAGON_0 ) t.weapon = MassWeaponTurret( game.stats.W_DRAGON_0 ) t.ai = AiWeaponTurret() elif i%4==2: flagship = FlagShip( self.extraRock0, game.stats.EXTRA_BASE, AiCaptain( self.extraRock0 ),x,y,0, 0, 0.0,0.0,0.0, 0) for k,t in enumerate(flagship.turrets): t.install = TurretInstall( game.stats.T_LARVA_0 ) t.weapon = MissileWeaponTurret( game.stats.W_LARVA_0 ) t.ai = AiWeaponTurret() else: flagship = FlagShip( self.extraRock0, game.stats.EXTRA_FS_2, AiCaptain( self.extraRock0 ),x,y,0, 0, 0.0,0.0,0.0, 0) for i in xrange( 8 ): fighter = ShipSingleWeapon(self.extraRock0, game.stats.EXTRA_FIGHTER, AiPilotFighter(flagship),0,0,0, 4, 0.0,0.0,0.0, 0) flagship.shipyards[ fighter.stats.img ].docked.append( fighter ) flagship.ore = flagship.stats.maxOre game.objects.append( flagship ) self.extraRock0.flagships.append( flagship ) flagship.missiles[ ids.M_LARVA ].amount = 100 for i in xrange( 16 ): self.addRandomExtra( game )
def __init__(self, game): Scenario.__init__(self, game) self.harvestersAtSpawn = 4 self.wantedBadGuys = 5 sol = Sun(game.stats.S_SOL, 0, 0) mercury = Planet(game.stats.P_MERCURY, -4100, 1400) venus = Planet(game.stats.P_VENUS, 5000, 2200) self.earth = Planet(game.stats.P_EARTH, -3100, 6700) self.mars = Planet(game.stats.P_MARS, -7800, -2200) moon = Planet(game.stats.P_MOON, -3900, 6400) jupiter = Planet(game.stats.P_JUPITER, -12000, -4800) saturn = Planet(game.stats.P_SATURN, 13000, 2500) neptune = Planet(game.stats.P_NEPTUNE, 15000, 7000) moon.zp = -50 moon.yi = 0.1 moon.orbiting = self.earth for i in xrange(20): # civilians around self.earth dist = randint(100, 800) angle = 2 * pi * random() (x, y) = (self.earth.xp + dist * cos(angle), self.earth.yp + dist * sin(angle)) s = Ship(game.stats.CIVILIAN_0, AiCivilian(), x, y, -20) game.objects.append(s) for i in range(60): # asteroids between saturn and neptune dist = 15000 angle = (1 - 2 * random()) * pi / 10 + pi / 7 asteroid = Asteroid(game, sol.xp + dist * cos(angle), sol.yp + dist * sin(angle), 300) game.harvestables.append(asteroid) for i in range(30): # asteroids outer self.mars dist = 9000 angle = (1 - 2 * random()) * pi / 8 + pi * 9 / 8 asteroid = Asteroid(game, sol.xp + dist * cos(angle), sol.yp + dist * sin(angle), 200) game.harvestables.append(asteroid) nebula = Nebula(game.stats.A_NEBULA, 4800, 500) for i in range(15): # asteroids in nebula asteroid = Asteroid(game, 4800, 800, 800) game.harvestables.append(asteroid) self.alphaCentaury = [ Sun(game.stats.S_SOL, -32000, 16000), Planet(game.stats.P_MARS_2, -28300, 12000), Planet(game.stats.P_SATURN_1, -39000, 8000) ] for i in range(40): # asteroids around self.alphaCentaury dist = 4600 #angle = 2*pi*i/50 angle = (1 - 2 * random()) * pi / 4 - pi / 8 asteroid = Asteroid(game, self.alphaCentaury[0].xp + dist * cos(angle), self.alphaCentaury[0].yp + dist * sin(angle), 200) game.harvestables.append(asteroid) self.beta = [ Sun(game.stats.S_SOL, 8000, -24000), Planet(game.stats.P_MARS_1, 12000, -22000), Planet(game.stats.P_X, 500, -21000), Planet(game.stats.P_JUPITER_1, 17000, -24700) ] for i in range(20): # asteroids around self.beta[1] dist = 600 angle = 2 * pi * random() asteroid = Asteroid(game, self.beta[1].xp + dist * cos(angle), self.beta[1].yp + dist * sin(angle), 80) game.harvestables.append(asteroid) self.gamma = [ Sun(game.stats.S_SOL, 40000, 4000), Planet(game.stats.P_MERCURY_1, 39000, -2200), Planet(game.stats.P_X_1, 38000, 11500) ] for i in range(20): # asteroids around self.gamma[1] dist = 750 angle = 2 * pi * random() asteroid = Asteroid(game, self.gamma[1].xp + dist * cos(angle), self.gamma[1].yp + dist * sin(angle), 80) game.harvestables.append(asteroid) for i in range(100): # asteroids around self.gamma area = choice([(7000, 300, 5 * pi / 8, pi / 9), (10000, 400, 6 * pi / 8, pi / 8), (12000, 500, 5 * pi / 8, pi / 11)]) # , 3000 dist = area[0] #randint( area[0]-area[1], area[0]+area[1] ) angle = area[2] + area[3] * (1 - 2 * random()) asteroid = Asteroid(game, self.gamma[0].xp + dist * cos(angle), self.gamma[0].yp + dist * sin(angle), area[1]) game.harvestables.append(asteroid) nebula2 = Nebula(game.stats.A_NEBULA, 8000, -16000) blackHole0 = BlackHole(game.stats.BH_0, -30000, -20000) # for i in range( 15 ): # asteroid = Asteroid( game, -7000, -3200, 800 ) # game.objects.append( asteroid ) # for i in range( 15 ): # asteroid = Asteroid( game, 8500, 6800, 800 ) # game.objects.append( asteroid ) self.sol = [ sol, mercury, venus, self.earth, moon, self.mars, jupiter, saturn, neptune, nebula, nebula2 ] game.astres = [ sol, mercury, venus, self.earth, moon, self.mars, jupiter, saturn, neptune, nebula, nebula2, blackHole0 ] + self.alphaCentaury + self.beta + self.gamma # game.objects = game.objects # + [sol, mercury, venus, self.earth, moon, self.mars, jupiter, saturn, neptune, nebula, nebula2 ] + self.alphaCentaury + self.beta for i in range(5): self.addRandomNpc(game) spots = [] for o in game.astres: if isinstance(o, Planet) and not isinstance(o, Sun): spots.append(o) for i in xrange(30): # random civilians spot = choice(spots) dist = randint(100, 800) angle = 2 * pi * random() (x, y) = (spot.xp + dist * cos(angle), spot.yp + dist * sin(angle)) s = Ship(game.stats.CIVILIAN_0, AiCivilian(), x, y, -20) game.objects.append(s) self.marsDefense = Faction(game.stats.R_HUMAN, "Mars Defenses") obase = OrbitalBase(self.marsDefense, game.stats.HUMAN_BASE, AiGovernor(self.marsDefense), self.mars.xp + self.mars.stats.maxRadius * 1.5, self.mars.yp + self.mars.stats.maxRadius * 1.5, 0, 0, 0.0, 0.0, 0.0, 0) for t in obase.turrets: t.install = TurretInstall(game.stats.T_MASS_SR_0) t.weapon = MassWeaponTurret(game.stats.W_MASS_SR_0) t.ai = AiWeaponTurret() obase.orbiting = self.mars obase.yi = 1 obase.ore = obase.stats.maxOre obase.ri = -0.008 game.objects.append(obase) for i in xrange(20): radius = self.mars.stats.maxRadius * (2.5) dist = self.mars.stats.maxRadius * (1.5 + 1 * random()) angle = 2 * pi * random() # AiPilotDefense fighter = ShipSingleWeapon(self.marsDefense, game.stats.HUMAN_FIGHTER, AiPilotDefense(self.mars, radius), self.mars.xp + dist * cos(angle), self.mars.yp + dist * sin(angle), 0, 4, 0.0, 0.0, 0.0, 0) game.objects.append(fighter) self.marsDefense.ships.append(fighter) self.marsDefense.bases.append(obase) game.addPlayer(self.marsDefense) self.earthDefense = Faction(game.stats.R_HUMAN, "Earth Defenses") nbrBases = 3 for i in xrange(nbrBases): dist = self.earth.stats.maxRadius * 1.8 #(1.8+0.4*random()) angle = pi * i * 2 / nbrBases obase = OrbitalBase(self.earthDefense, game.stats.HUMAN_BASE, AiGovernor(self.earthDefense), self.earth.xp + dist * cos(angle), self.earth.yp + dist * sin(angle), 0, 0, 0.0, 0.0, 0.0, 0) for t in obase.turrets: t.install = TurretInstall(game.stats.T_MASS_MR_0) t.weapon = MassWeaponTurret(game.stats.W_MASS_MR) t.ai = AiWeaponTurret() obase.ori = angle + pi / 2 obase.orbiting = self.earth obase.xi = cos(obase.ori) obase.yi = sin(obase.ori) obase.ore = obase.stats.maxOre obase.ri = -0.008 game.objects.append(obase) self.earthDefense.bases.append(obase) for i in xrange(20): radius = self.earth.stats.maxRadius * (2.5) dist = self.earth.stats.maxRadius * (1.5 + 1 * random()) angle = 2 * pi * random() # AiPilotDefense fighter = ShipSingleWeapon(self.earthDefense, game.stats.HUMAN_FIGHTER, AiPilotPolice(self.earth, radius), self.earth.xp + dist * cos(angle), self.earth.yp + dist * sin(angle), 0, 4, 0.0, 0.0, 0.0, 0) game.objects.append(fighter) self.earthDefense.ships.append(fighter) # self.earthDefense.bases.append( obase ) game.addPlayer(self.earthDefense) ## ai forces self.addAiBase(game, "Neptune base", neptune) self.addAiBase(game, "Saturn base", saturn) self.addAiBase(game, "Jupiter base", jupiter, 2) ## Evolved self.evolvedSwarm0 = Faction( game.stats.R_EVOLVED, "First Swarm", territories=[ Territory((self.alphaCentaury[1].xp, self.alphaCentaury[1].yp), 500), Territory((self.alphaCentaury[1].xp - 1000, self.alphaCentaury[1].yp - 500), 500) ]) (x, y) = self.alphaCentaury[1].xp - self.alphaCentaury[ 1].stats.maxRadius * 1.5, self.alphaCentaury[ 1].yp + self.alphaCentaury[1].stats.maxRadius * 1.5 flagship = FlagShip(self.evolvedSwarm0, game.stats.EVOLVED_FS_1, AiCaptain(self.evolvedSwarm0), x, y, 0, 0, 0.0, 0.0, 0.0, 0) flagship.ore = flagship.stats.maxOre for t in flagship.turrets[:-2]: t.install = TurretInstall(game.stats.T_MASS_MR_0) t.weapon = MassWeaponTurret(game.stats.W_MASS_MR) t.ai = AiWeaponTurret() for t in flagship.turrets[-2:]: t.install = TurretInstall(game.stats.T_LASER_SR_0) t.weapon = LaserWeaponTurret(game.stats.W_LASER_SR) t.ai = AiWeaponTurret() for i in range(4): harvester = HarvesterShip(self.evolvedSwarm0, self.evolvedSwarm0.race.defaultHarvester, AiPilotHarvester(flagship), 0, 0, 0, 4, 0.0, 0.0, 0.0, 0) flagship.shipyards[harvester.stats.img].docked.append(harvester) for i in xrange(5): if i >= 3: fighter = ShipSingleWeapon(self.evolvedSwarm0, game.stats.EVOLVED_BOMBER, AiPilotFighter(flagship), 0, 0, 0, 4, 0.0, 0.0, 0.0, 0) else: fighter = ShipSingleWeapon(self.evolvedSwarm0, game.stats.EVOLVED_FIGHTER, AiPilotFighter(flagship), 0, 0, 0, 4, 0.0, 0.0, 0.0, 0) for i in xrange(10): fighter = ShipSingleWeapon(self.evolvedSwarm0, game.stats.EVOLVED_FIGHTER, AiPilotDefense(flagship, 500), 0, 0, 0, 4, 0.0, 0.0, 0.0, 0) (fighter.xp, fighter.yp) = (flagship.xp, flagship.yp) game.objects.append(fighter) self.evolvedSwarm0.ships.append(fighter) # flagship.shipyards[ fighter.stats.img ].docked.append( fighter ) game.objects.append(flagship) self.evolvedSwarm0.flagships.append(flagship) game.addPlayer(self.evolvedSwarm0) ## Extra TODO remove section self.extraRock0 = Faction(game.stats.R_EXTRA, "Rocks") for i in xrange(0): # 4 ): angle = 2 * pi * random() dist = 750 # self.gamma[ 1 ].stats.maxRadius* (x, y) = self.gamma[1].xp - dist * cos( angle), self.gamma[1].yp + dist * sin(angle) if i % 4 == 0: flagship = FlagShip(self.extraRock0, game.stats.EXTRA_BASE, AiCaptain(self.extraRock0), x, y, 0, 0, 0.0, 0.0, 0.0, 0) for k, t in enumerate(flagship.turrets): t.install = TurretInstall(game.stats.T_ROCK_THROWER_1) t.weapon = MassWeaponTurret(game.stats.W_ROCK_THROWER_1) t.ai = AiWeaponTurret() elif i % 4 == 1: flagship = FlagShip(self.extraRock0, game.stats.EXTRA_FS_1, AiCaptain(self.extraRock0), x, y, 0, 0, 0.0, 0.0, 0.0, 0) for k, t in enumerate(flagship.turrets): t.install = TurretInstall(game.stats.T_DRAGON_0) t.weapon = MassWeaponTurret(game.stats.W_DRAGON_0) t.ai = AiWeaponTurret() elif i % 4 == 2: flagship = FlagShip(self.extraRock0, game.stats.EXTRA_BASE, AiCaptain(self.extraRock0), x, y, 0, 0, 0.0, 0.0, 0.0, 0) for k, t in enumerate(flagship.turrets): t.install = TurretInstall(game.stats.T_LARVA_0) t.weapon = MissileWeaponTurret(game.stats.W_LARVA_0) t.ai = AiWeaponTurret() else: flagship = FlagShip(self.extraRock0, game.stats.EXTRA_FS_2, AiCaptain(self.extraRock0), x, y, 0, 0, 0.0, 0.0, 0.0, 0) for i in xrange(8): fighter = ShipSingleWeapon(self.extraRock0, game.stats.EXTRA_FIGHTER, AiPilotFighter(flagship), 0, 0, 0, 4, 0.0, 0.0, 0.0, 0) flagship.shipyards[fighter.stats.img].docked.append( fighter) flagship.ore = flagship.stats.maxOre game.objects.append(flagship) self.extraRock0.flagships.append(flagship) flagship.missiles[ids.M_LARVA].amount = 100 for i in xrange(16): self.addRandomExtra(game)
def __init__(self): self._dao = DataAccess() self._scenarios = Scenario() self._host = "nathan@sf1-1-pc1" self._robot = Factory.getCurrentRobot()
def doTurn( self, game ): Scenario.doTurn( self, game )
class RobotCommands(object): exposed = True def __init__(self): self._dao = DataAccess() self._scenarios = Scenario() self._host = "nathan@sf1-1-pc1" self._robot = Factory.getCurrentRobot() def POST(self, *args, **kwargs): request = json.loads(cherrypy.request.body.read()) # Send the robot to certain location (The behaviour depends on the scenario) if request.has_key('location'): if request['scenario'] == 1: if request['scenarioType'] == 'HallDoorbell': self._scenarios.ScenarioDoorbell1(request, self._host) else: self._scenarios.Scenario1(request, self._host) elif request['scenario'] == 2: if request['scenarioType'] == 'HallDoorbell': self._scenarios.ScenarioDoorbell2(request, self._host) elif request['scenarioType'] == 'LivingDrink': self._scenarios.Scenario2(request, self._host) else: self._scenarios.Scenario1(request, self._host) elif request['scenario'] == 3: if request['scenarioType'] == 'HallDoorbell': self._scenarios.ScenarioDoorbell1(request, self._host) else: self._scenarios.Scenario3(request, self._host) # Send voice command to the robot (espeak software required) elif request.has_key( 'speech') and self._dao.getActiveQuestion()['repeated'] == 0: #Block other interfaces to repeat the message self._dao.setResponse(request['messageId'], None, 1) self._preferences = self._dao.users.getUserPreferences() if request['scenario'] == 3 or request[ 'messageId'] == 'doorbellAssistLowPro': time.sleep(0.5) #Including delay to help transition elif request['scenario'] == 1 or request['scenario'] == 2: time.sleep(7) #Time to wait for the body movement to finish if self._preferences[0]['voice'] == 1: self._robot.setComponentState('head', 'front') #Compose speech if request['scenario'] == 1 or request['scenario'] == 2: message = request['speech'].replace( "User,", request['username'] + ",") else: message = request['speech'].replace("User, ", "") message = message.replace("<br/>", "") #Remove end of line if exists #subprocess.call(['C:\\Program Files (x86)\\eSpeak\\command_line\\espeak.exe', request['speech']]) #Windows #subprocess.call(['espeak', message]) #Linux subprocess.Popen( ["ssh", "%s" % self._host, "espeak -s 135 '%s'" % message], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) #Remote Linux if request['scenario'] == 1 or request['scenario'] == 2: self._robot.setComponentState('head', 'front_bend_left') time.sleep(0.150) self._robot.setComponentState('head', 'front_bend_right') time.sleep(0.150) self._robot.setComponentState('head', 'front') else: time.sleep(1) ## Determine the speech time wait = 0.3 * (len(message.split()) - 1) time.sleep(wait) #It means the robot has already spoken and the dialog can be shown self._dao.setResponse(request['messageId'], None, 2) # Open Tray if self._robot.getComponentState('tray')[0] == 'lowered': self._robot.setComponentState('tray', 'raised') #Finish Action self._robot.setComponentState('head', 'back') self._robot.setLight(eval(self._preferences[0]['light'])) # Open Tray (Sometimes the first attempt is failing) if self._robot.getComponentState('tray')[0] != 'raised': self._robot.setComponentState('tray', 'raised') else: raise cherrypy.HTTPError(400)
def __init__(self, game, steps=None, name=None, description=None, year=0): stats = Stats() stats.R_HUMAN.turrets = [ stats.T_LASER_SR_1, stats.T_LASER_SR_0, stats.T_MASS_SR_1, stats.T_MASS_SR_0, stats.T_MASS_MR_0 ] stats.R_HUMAN.missiles = [] stats.R_HUMAN.ships = [ stats.HARVESTER ] stats.PlayableShips = {} steps = [ Step( goal=lambda self, game: utils.distLowerThanObjects( self.player.flagship, self.asteroid, 300 ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, # onBegin=lambda self, game: self.player.flagship.ore = 500, texts = [ (0, "We need some materials."), (4*config.fps, "There is an asteroid close to the Moon."), (8*config.fps, "Get close to it.") ] ), Step( goal=lambda self, game: self.player.flagship.ai.launching[ self.player.race.defaultHarvester.img ], failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0, "Begin collecting raw ore."), (4*config.fps, "To do so, launch your harvester by pressing the blue arrow button at the bottom of the screen.") ] ), Step( goal=lambda self, game: self.player.flagship.oreProcess, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0, "Now wait for them to bring back the ore."), (6*config.fps, "Don't worry about the ships following you around."), (10*config.fps, "They are civilian and while they are under your protection they speed up building processes.") ] ), Step( goal=lambda self, game: self.player.flagship.ore >= 100, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0, "They have now added the raw ore to the processing queue."), (4*config.fps, "Wait a little while and it will be transformed into usable materials."), (8*config.fps, "Keep harvesting and processing the ore until you reach 100 material."), (12*config.fps, "Notice the moving bars at the bottom right corner of the screen..."), (14*config.fps, "they represents the ore being processed."), (18*config.fps, "once they reach the right, they are usable!"), (22*config.fps, "They will then be added to the ore stock indicated by the blue gage in the bottom right corner."), ] ), Step( goal=lambda self, game: self.player.flagship.shipyards[ self.player.race.defaultHarvester.img ].getCount() >= 4, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0, "You now have enough material to build a new harvester and speed it up!"), (2*config.fps, "To do so, click on the icon of the harvester at the bottom of the screen, under the launch button.") ] ), Step( goal=lambda self, game: self.player.flagship.ore >= 300, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0, "Keep harvesting and processing ore util you reach 300 material."), (4*config.fps, "It will follow the orders the others already received."), (8*config.fps, "Notice the blue bar in the upper right corner and the green one in the bottm right..."), (12*config.fps, "the blue one represents your shield and the green one your hull.") ] ), Step( goal=lambda self, game: len( filter( lambda turret: turret.install, self.player.flagship.turrets ) ) >= 3, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0, "There are rumors of pirates in the area."), (4*config.fps, "Build one more mass cannon turret on your ship."), (8*config.fps, "To do so, click on an empty slot on the right of the screen and select an affordable turret."), ] ), Step( goal=lambda self, game: not self.ennemyShip.alive, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, onBegin=lambda self, game: (self.addAttackingEnnemy( game, (self.moon.xp-1500,self.moon.yp-800), self.player.flagship, "Pirate lambda" ), game.setRelationBetween( self.player, self.ennemy, 1 )), texts = [ (0, "Defend yourself from the incoming pirate ship."), (4*config.fps, "To attack it, simply left-click on it once."), (8*config.fps, "Your crew will aim and fire the turrets."), (12*config.fps, "You can still help them by manoeuvering the ship so that the ennemy is in range of the turrets.") ] ), Step( goal=lambda self, game: utils.distLowerThanObjects( self.player.flagship, self.orbitalbase, 100 ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [ (0, "Well done!"), (2*config.fps, "Recall your harvester and return to the orbital base.") ] ), ] Scenario.__init__(self, game, steps=steps, stats=stats ) ### redefining stats, dangerous self.sol = Sun( game.stats.S_SOL, 0, 0 ) self.mercury = Planet( game.stats.P_MERCURY, -4100, 1400 ) self.venus = Planet( game.stats.P_VENUS, 5000, 2300 ) self.earth = Planet( game.stats.P_EARTH, -3100, 6700 ) self.mars = Planet( game.stats.P_MARS_1, -7800, -2300 ) self.moon = Planet( game.stats.P_MOON, -3900, 6400 ) self.jupiter = Planet( game.stats.P_JUPITER, -13000, -4800 ) self.saturn = Planet( game.stats.P_SATURN, 13000, 2500 ) self.neptune = Planet( game.stats.P_NEPTUNE, 15000, 7000 ) self.moon.zp = -50 self.moon.yi = 0.1 self.moon.orbiting = self.earth # asteroids over the moon, vital to scenario for i in xrange( 1 ): self.asteroid = Asteroid( game, self.moon.xp-200, self.moon.yp+150, 10 ) game.harvestables.append( self.asteroid ) for i in xrange( 3 ): # civilians around self.earth dist = randint( 100, 800 ) angle = 2*pi*random() (x,y) = (self.earth.xp+dist*cos(angle), self.earth.yp+dist*sin(angle)) s = Ship( game.stats.CIVILIAN_0, AiCivilian(), x, y, -20 ) game.objects.append( s ) for i in range( 50 ): # asteroids outer self.mars dist = 9000 angle = (1-2*random())*pi/8+pi*9/8 asteroid = Asteroid( game, self.sol.xp+dist*cos(angle), self.sol.yp+dist*sin(angle), 300 ) game.harvestables.append( asteroid ) game.astres = [self.sol, self.mercury, self.venus, self.earth, self.moon, self.mars, self.jupiter, self.saturn, self.neptune, self.moon ] dist = self.earth.stats.maxRadius*1.5 angle = 5*pi/8 self.orbitalbase = OrbitalBase( None, game.stats.HUMAN_BASE_MINING, None, self.earth.xp+dist*cos(angle),self.earth.yp+dist*sin(angle)) self.orbitalbase.ri = -0.013 game.objects.append( self.orbitalbase ) self.player = None
def run_network(self): Scenario.run_network(self) self.add_ftp()
def __init__(self, game, steps=None, name=None, description=None, year=0): stats = Stats() stats.R_HUMAN.turrets = [ stats.T_LASER_SR_1, stats.T_LASER_SR_0, stats.T_MASS_SR_1, stats.T_MASS_SR_0, stats.T_MASS_MR_0 ] stats.R_HUMAN.missiles = [] stats.R_HUMAN.ships = [stats.HARVESTER] stats.PlayableShips = {} steps = [ Step( goal=lambda self, game: utils.distLowerThanObjects( self.player.flagship, self.asteroid, 300), failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, # onBegin=lambda self, game: self.player.flagship.ore = 500, texts=[(0, "We need some materials."), (4 * config.fps, "There is an asteroid close to the Moon."), (8 * config.fps, "Get close to it.")]), Step( goal=lambda self, game: self.player.flagship.ai.launching[ self.player.race.defaultHarvester.img], failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, texts= [(0, "Begin collecting raw ore."), (4 * config.fps, "To do so, launch your harvester by pressing the blue arrow button at the bottom of the screen." )]), Step( goal=lambda self, game: self.player.flagship.oreProcess, failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, texts= [(0, "Now wait for them to bring back the ore."), (6 * config.fps, "Don't worry about the ships following you around."), (10 * config.fps, "They are civilian and while they are under your protection they speed up building processes." )]), Step( goal=lambda self, game: self.player.flagship.ore >= 100, failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, texts=[ (0, "They have now added the raw ore to the processing queue." ), (4 * config.fps, "Wait a little while and it will be transformed into usable materials." ), (8 * config.fps, "Keep harvesting and processing the ore until you reach 100 material." ), (12 * config.fps, "Notice the moving bars at the bottom right corner of the screen..." ), (14 * config.fps, "they represents the ore being processed."), (18 * config.fps, "once they reach the right, they are usable!"), (22 * config.fps, "They will then be added to the ore stock indicated by the blue gage in the bottom right corner." ), ]), Step( goal=lambda self, game: self.player.flagship.shipyards[ self.player.race.defaultHarvester.img].getCount() >= 4, failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, texts= [(0, "You now have enough material to build a new harvester and speed it up!" ), (2 * config.fps, "To do so, click on the icon of the harvester at the bottom of the screen, under the launch button." )]), Step( goal=lambda self, game: self.player.flagship.ore >= 300, failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, texts= [(0, "Keep harvesting and processing ore util you reach 300 material." ), (4 * config.fps, "It will follow the orders the others already received."), (8 * config.fps, "Notice the blue bar in the upper right corner and the green one in the bottm right..." ), (12 * config.fps, "the blue one represents your shield and the green one your hull." )]), Step( goal=lambda self, game: len( filter(lambda turret: turret.install, self.player.flagship. turrets)) >= 3, failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, texts=[ (0, "There are rumors of pirates in the area."), (4 * config.fps, "Build one more mass cannon turret on your ship."), (8 * config.fps, "To do so, click on an empty slot on the right of the screen and select an affordable turret." ), ]), Step( goal=lambda self, game: not self.ennemyShip.alive, failure=lambda self, game: not self.player.flagship or not self .player.flagship.alive, onBegin=lambda self, game: (self.addAttackingEnnemy( game, (self.moon.xp - 1500, self.moon.yp - 800), self.player.flagship, "Pirate lambda" ), game.setRelationBetween(self.player, self.ennemy, 1)), texts= [(0, "Defend yourself from the incoming pirate ship."), (4 * config.fps, "To attack it, simply left-click on it once."), (8 * config.fps, "Your crew will aim and fire the turrets."), (12 * config.fps, "You can still help them by manoeuvering the ship so that the ennemy is in range of the turrets." )]), Step(goal=lambda self, game: utils.distLowerThanObjects( self.player.flagship, self.orbitalbase, 100), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts=[ (0, "Well done!"), (2 * config.fps, "Recall your harvester and return to the orbital base.") ]), ] Scenario.__init__(self, game, steps=steps, stats=stats) ### redefining stats, dangerous self.sol = Sun(game.stats.S_SOL, 0, 0) self.mercury = Planet(game.stats.P_MERCURY, -4100, 1400) self.venus = Planet(game.stats.P_VENUS, 5000, 2300) self.earth = Planet(game.stats.P_EARTH, -3100, 6700) self.mars = Planet(game.stats.P_MARS_1, -7800, -2300) self.moon = Planet(game.stats.P_MOON, -3900, 6400) self.jupiter = Planet(game.stats.P_JUPITER, -13000, -4800) self.saturn = Planet(game.stats.P_SATURN, 13000, 2500) self.neptune = Planet(game.stats.P_NEPTUNE, 15000, 7000) self.moon.zp = -50 self.moon.yi = 0.1 self.moon.orbiting = self.earth # asteroids over the moon, vital to scenario for i in xrange(1): self.asteroid = Asteroid(game, self.moon.xp - 200, self.moon.yp + 150, 10) game.harvestables.append(self.asteroid) for i in xrange(3): # civilians around self.earth dist = randint(100, 800) angle = 2 * pi * random() (x, y) = (self.earth.xp + dist * cos(angle), self.earth.yp + dist * sin(angle)) s = Ship(game.stats.CIVILIAN_0, AiCivilian(), x, y, -20) game.objects.append(s) for i in range(50): # asteroids outer self.mars dist = 9000 angle = (1 - 2 * random()) * pi / 8 + pi * 9 / 8 asteroid = Asteroid(game, self.sol.xp + dist * cos(angle), self.sol.yp + dist * sin(angle), 300) game.harvestables.append(asteroid) game.astres = [ self.sol, self.mercury, self.venus, self.earth, self.moon, self.mars, self.jupiter, self.saturn, self.neptune, self.moon ] dist = self.earth.stats.maxRadius * 1.5 angle = 5 * pi / 8 self.orbitalbase = OrbitalBase(None, game.stats.HUMAN_BASE_MINING, None, self.earth.xp + dist * cos(angle), self.earth.yp + dist * sin(angle)) self.orbitalbase.ri = -0.013 game.objects.append(self.orbitalbase) self.player = None
def __init__(self, game, steps=None, name=None, description=None, year=0): stats = Stats() stats.R_HUMAN.turrets = [ stats.T_LASER_SR_1, stats.T_LASER_SR_0, stats.T_LASER_MR_0, stats.T_MASS_SR_1, stats.T_MASS_SR_0, stats.T_MASS_LR, stats.T_MASS_MR_0, stats.T_MISSILE_1, stats.T_MISSILE_0, stats.T_PULSE, stats.T_MINER, stats.T_SOLAR_0, ] stats.R_HUMAN.missiles = [ids.M_NORMAL, ids.M_PULSE, ids.M_MINER] stats.R_HUMAN.ships = [ stats.HARVESTER, stats.HUMAN_FIGHTER ] stats.PlayableShips = {} steps = [] ### missiles steps.append( Step( goal=lambda self, game: filter( lambda turret: turret.install and turret.install.stats==stats.T_MISSILE_0, self.player.flagship.turrets ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, onBegin=lambda self, game: self.addEnnemyShip( game, (self.player.flagship.xp+stats.T_MASS_MR_0.weapon.maxRange+100, self.player.flagship.yp), None ), texts = [(0,"There's an ennemy ship on the other side of Earth, directly to your right."), (config.fps*4, "It is too far away to reach with your current weapons."), (config.fps*8, "Select an empty turret, on the right of the screen, and build a missile launcher."), (config.fps*16, "It would also be a good idea to begin harvesting the asteroid close by."), (config.fps*20, "Build more harvester if you feel that it's necessary." )] ) ) steps.append( Step( goal=lambda self, game: self.player.flagship.missiles[ids.M_NORMAL].amount >= 10, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [(0,"Now that the launcher is ready you will need some missiles!"), (config.fps*4, "Click on the missile icon at the botom of the screen to start building them."), (config.fps*8, "10 should be enough to initiate the combat.") ] ) ) steps.append( Step( goal=lambda self, game: not self.ennemyShip.alive, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, onBegin=lambda self, game: (game.setRelationBetween( self.player, self.ennemy, 1 ), game.setRelationBetween( self.ennemy, self.player, 1 )), texts = [(0,"Now attack it!"), (config.fps*4, "It is the blue dot on the radar screen, left-click on it to begin the attack." ) ] ) ) ### mass turret / upgrading steps.append( Step( goal=lambda self, game: filter( lambda turret: turret.install and turret.install.stats==stats.T_MASS_LR, self.player.flagship.turrets ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, onBegin=lambda self, game: self.addEnnemyShip( game, (self.player.flagship.xp+stats.T_MASS_LR.weapon.maxRange-400, self.player.flagship.yp), None ), texts = [(0,"One appeared even further away!"), (config.fps*4, "Upgrade at least one of your mass cannon to a mass driver turret." ) ] ) ) steps.append( Step( goal=lambda self, game: not self.ennemyShip.alive, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, onBegin=lambda self, game: (game.setRelationBetween( self.player, self.ennemy, 1 ), game.setRelationBetween( self.ennemy, self.player, 1 )), text = "Now that you can reach it, attack it!" ) ) ### fighters steps.append( Step( goal=lambda self, game: self.player.flagship.shipyards[ ids.S_HUMAN_FIGHTER ].getCount() >= 5, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, onBegin=lambda self, game: self.addEnnemyShips( game, (self.player.flagship.xp+stats.T_MASS_LR.weapon.maxRange+1000, self.player.flagship.yp), 200, count=2 ), texts = [(0,"There's another one too far away for your turrets."), (config.fps*4, "You need to build at leats 5 fighters."), (config.fps*8, "To do so, click on the fighter icon, at the bottom of the screen next to the harvester." )] ) ) steps.append( Step( goal=lambda self, game: self.player.flagship.ai.launching[ ids.S_HUMAN_FIGHTER ], failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [(0,"Launch your fighters."), (config.fps*4, "To do so, press the blue arrow button at the bottom of the screen." )] ) ) steps.append( Step( goal=lambda self, game: not self.ennemy.flagships, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, onBegin=lambda self, game: (game.setRelationBetween( self.player, self.ennemy, 1 ), game.setRelationBetween( self.ennemy, self.player, 1 )), text = "Now order your fighters to attack it by left-clicking on it." ) ) ### mines steps.append( Step( goal=lambda self, game: filter( lambda turret: turret.install and turret.install.stats==stats.T_MINER, self.player.flagship.turrets ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [(0, "The pirates always come from the same direction."), (config.fps*4, "Let's think ahead and build a mine field."), (config.fps*8, "First, build a mine layer turret."), (config.fps*12, "It would be a good idea to recall your fighters before laying the mine field."), (config.fps*16, "To do so, press onthe green arrow over the fighter icon." )] ) ) steps.append( Step( goal=lambda self, game: self.player.flagship.missiles[ids.M_MINER].amount >= 1, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, text = "Build 8 or more miner missiles.\nThe button appeared next to the missile button." ) ) steps.append( Step( goal=lambda self, game: filter( lambda obj: isinstance( obj, MinerMissile ), game.objects.objects ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, text = "A missile is ready.\nShoot it by clicking on the red targetting button over its icon.", texts= [ (config.fps*4,"Then click on the target, in this case target at a little distance to the right of the station."), (config.fps*8,"You can always cancel the launch of a missile by right clicking on the screen when targetting.") ] ) ) steps.append( Step( goal=lambda self, game: len( filter( lambda obj: isinstance( obj, Mine ), game.objects.objects ) ) >= stats.T_MINER.specialValue[1]*8, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, text = "Build and deploy a total of at least 8 missiles." ) ) ### pulse steps.append( Step( goal=lambda self, game: filter( lambda turret: turret.install and turret.install.stats==stats.T_PULSE, self.player.flagship.turrets ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, onBegin=lambda self, game: self.addEnnemyShips( game, (self.player.flagship.xp+stats.T_MASS_LR.weapon.maxRange+200, self.player.flagship.yp), 200, count=4 ), texts = [(0, "A group of pirates can now be seen far away."), (config.fps*4, "To trap them and give us a head start let's hit them with an EMP weapon first!"), (config.fps*8, "Build a pulse launcher.") ] ) ) steps.append( Step( goal=lambda self, game: self.player.flagship.missiles[ids.M_PULSE].amount >= 1, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, text = "Build at least one pulse missile." ) ) steps.append( Step( goal=lambda self, game: filter( lambda obj: isinstance( obj, PulseMissile ), game.objects.objects ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, text = "A missile is ready.\nShoot it in the middle of the pirates." ) ) steps.append( Step( goal=lambda self, game: not filter( lambda obj: isinstance( obj, PulseMissile ), game.objects.objects ), failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, onBegin=lambda self, game: (game.setRelationBetween( self.player, self.ennemy, 1 ), game.setRelationBetween( self.ennemy, self.player, 1 )), texts = [(0,"Wait for them to get hit."), (config.fps*4, "Every ship caught in the explosion will have its engines disabled for a few seconds..."), (config.fps*8, "its shield will also be badly hit.")] ) ) steps.append( Step( goal=lambda self, game: not self.ennemy.flagships, failure=lambda self, game: not self.player.flagship or not self.player.flagship.alive, texts = [(0,"Wait for them to recover from the EMP and to get caught in the mine field!"), (config.fps*4, "Then finish them.")] ) ) Scenario.__init__(self, game, steps=steps, stats=stats ) self.sol = Sun( game.stats.S_SOL, 0, 0 ) self.mercury = Planet( game.stats.P_MERCURY, -4100, 1400 ) self.venus = Planet( game.stats.P_VENUS, 5000, 2300 ) self.earth = Planet( game.stats.P_EARTH, -3100, 6700 ) self.mars = Planet( game.stats.P_MARS_1, -7800, -2300 ) self.moon = Planet( game.stats.P_MOON, -3900, 6400 ) self.jupiter = Planet( game.stats.P_JUPITER, -13000, -4800 ) self.saturn = Planet( game.stats.P_SATURN, 13000, 2500 ) self.neptune = Planet( game.stats.P_NEPTUNE, 15000, 7000 ) self.moon.zp = -50 self.moon.yi = 0.1 self.moon.orbiting = self.earth # asteroids near the station for i in xrange( 1 ): asteroid = Asteroid( game, self.moon.xp+200, self.moon.yp+430, 0 ) game.harvestables.append( asteroid ) for i in xrange( 10 ): # civilians around self.earth dist = randint( 100, 800 ) angle = 2*pi*random() (x,y) = (self.earth.xp+dist*cos(angle), self.earth.yp+dist*sin(angle)) s = Ship( game.stats.CIVILIAN_0, AiCivilian(), x, y, -20 ) game.objects.append( s ) for i in range( 50 ): # asteroids outer self.mars dist = 9000 angle = (1-2*random())*pi/8+pi*9/8 asteroid = Asteroid( game, self.sol.xp+dist*cos(angle), self.sol.yp+dist*sin(angle), 300 ) game.harvestables.append( asteroid ) game.astres = [self.sol, self.mercury, self.venus, self.earth, self.moon, self.mars, self.jupiter, self.saturn, self.neptune, self.moon ] # dist = self.earth.stats.maxRadius*1.2 # angle = 7/8*pi # self.orbitalbase = OrbitalBase( None, game.stats.HUMAN_BASE, None, self.earth.xp+dist*cos(angle),self.earth.yp+dist*sin(angle)) # self.orbitalbase.ri = -0.013 # game.objects.append( self.orbitalbase ) self.player = None