def order(request): '''Starts building land army units When: Resources met Requirements met''' mum = getCurrentMother(request) # Python will HTTP 500 on invalid GET data costs = getCosts(mum, getRace(request), int(request.GET['what'])) if not (int(request.GET['what']) in range(0,MGID+1)): return HttpResponse('WHATINVALID') if int(request.GET['amount']) < 1: return HttpResponse('INVALIDAMOUNT') if costs[0]*int(request.GET['amount']) > getResourceIndex(request).stateUpdate(): return HttpResponse('COSTS') if not getRequirements(mum, getRace(request), int(request.GET['what'])): return HttpResponse('REQUIREMENTS') note(request, LM_LANDARMY_TRAINING, mid=mum.id, what=int(request.GET['what']), amount=int(request.GET['amount'])) orderProduce(mum, getRace(request), int(request.GET['what']), int(request.GET['amount'])) return HttpResponse('OK')
def order(request): '''Starts a technology research. When: Resources met Not researching any other technology worldwide Requirements met''' mum = getCurrentMother(request) costs = getCosts(mum.owner.technology, getRace(request), int(request.GET['what'])) if costs[0] > getResourceIndex(request).stateUpdate(): return HttpResponse('COSTS') if int(request.GET['what']) == 12: # supercomputer if getAccount(request).getPendingResearchesCount() > 0: return HttpResponse('QUEUE') else: if getAccount(request).getPendingResearchesCount() > mum.owner.technology.o_12: return HttpResponse('QUEUE') if not getRequirements(mum.owner.technology, getRace(request), int(request.GET['what'])).validate(mum): return HttpResponse('REQUIREMENTS') if not canAdvance(mum.owner.technology, getRace(request), int(request.GET['what'])): return HttpResponse('ADVANCE') note(request, LM_RESEARCH_ORDERED, mid=mum.id, what=int(request.GET['what']), levelfrom=mum.owner.technology.__dict__['o_'+request.GET['what']]) orderResearch(mum, int(request.GET['what']), costs) return HttpResponse('OK')
def provincepick(request, province): '''Returns a tuple in JSON: - garrison (HTML) - commands (HTML) - province's planet_count_number''' account = getAccount(request) # deem whether the user can access this try: province.presence # Must be inhabited except: return HttpResponse(dumps(None)) if province.presence.owner != account: # if not mine... try: reinf = province.presence.reinforcement_set.get(owner=account) except ObjectDoesNotExist: return HttpResponse(dumps(None)) # I don't have even reinforcements here # Get me outta here! # However if I have reinforcements here, then it's different garrison = reinf.garrison reinforcements = True else: # is mine garrison = province.presence.garrison reinforcements = False garr = p_garrison_prov_dx(request, garrison, getRace(request)) comms = p_commands(request, province.planet, province, reinforcements) x = dumps((garr, comms, province.planet_count_number)) return HttpResponse(x)
def process(request): mum = getCurrentMother(request) tech = getTechnology(request) try: mro, = MotherRelocationOrder.objects.filter(mother=mum) except: relocating = False mro = None else: relocating = True constructions = mum.getConstructions() researches = mum.getResearches() return render_to_response('mother/overview/overview.html', {'mother':mum, 'constructions':constructions, 'c_requirements':mother_construction.getRequirementsArray(mum, getRace(request)), 'c_costs':mother_construction.getCostsArray(mum, getRace(request)), 'technology':tech, 'researches':researches, 't_costs':technology.getCostsArray(tech, getRace(request)), 't_requirements':technology.getRequirementsArray(tech, getRace(request)), 'pgo':PrimaryGUIObject(request), 'relocating':relocating, 'mro':mro, 'race':getRace(request), })
def order(request, pp): mum = getCurrentMother(request) slot = int(request.GET['slot']) otype, olvl = pp.getPair(slot) if otype == 0: return HttpResponse('ZEROSLOT') # Cannot upgrade something that doesnt exist costs = getCosts(pp, getRace(request), olvl, otype) if pp.owner != getAccount(request): return HttpResponse('ACCOUNT') if costs[0] > getResourceIndex(request).stateUpdate(): return HttpResponse('COSTS') if pp.getPendingBuildingsCount() > 0: return HttpResponse('QUEUE') note(request, LP_BUILD_ORDERED, pid=pp.province.id, slot=slot, what=otype, levelfrom=olvl) orderBuild(pp, mum, otype, slot, costs) return HttpResponse('OK')
def land(request): mum = getCurrentMother(request) lpos = LandarmyProduceOrder.objects.filter(mother=mum.id).order_by('got__ordered_on') garn = {} for x in xrange(0, MGID+1): garn[x] = {} garn[x]['has'] = mum.garrison[x] garn[x]['creq'] = getRequirements(mum, getRace(request), x) garn[x]['req'] = garn[x]['creq'].validate(mum) garn[x]['cost'], garn[x]['time'] = getCosts(mum, getRace(request), x) return render_to_response('mother/garrison/land.html', {'mother':mum, 'garn':garn, 'lpos':lpos, 'pgo':PrimaryGUIObject(request, mum)})
def order(request): mum = getCurrentMother(request) costs = getCosts(mum, getRace(request), int(request.GET['what'])) if costs[0] > getResourceIndex(request).stateUpdate(): return HttpResponse('COSTS') if mum.getPendingConstructionsCount() > 0: return HttpResponse('QUEUE') if not getRequirements(mum, getRace(request), int(request.GET['what'])).validate(mum): return HttpResponse('REQUIREMENTS') note(request, LM_CONSTRUCTION_ORDERED, mid=mum.id, what=int(request.GET['what']), levelfrom=mum.__dict__['b_'+request.GET['what']]) orderConstruct(mum, int(request.GET['what']), costs) return HttpResponse('OK')
def scanner(request, p): '''Scans a target province in GET 'p' ''' mum = getCurrentMother(request) acc = getAccount(request) if getRace(request) != 1: return HttpResponse('RACE') if mum.isRelocating(): return HttpResponse('RELOCATION') if not p in mum.orbiting.province_set.all(): return HttpResponse('PROVINCE') doScan(acc, mum, p) return HttpResponse('OK')
def planetpick_planet(request, planet_id): '''We have picked a planet. That implies generating everything new. Returns a tuple in JSON: - PLM (HTML) - garrison (HTML) - commands (HTML) - new CurrentPlanetID - new SelectedProvince''' try: planet = Planet.objects.get(id=planet_id) except ObjectDoesNotExist: return HttpResponse(dumps(None)) account = getAccount(request) current_province = None current_garrison = None current_planet = planet allowDisplay = False limit_cmdr = False for province in planet.province_set.all(): try: province.presence except: continue if province.presence.owner == account: allowDisplay = True if current_province == None: current_province = province current_garrison = province.presence.garrison break try: reinf = province.presence.reinforcement_set.get(owner=account) except ObjectDoesNotExist: continue else: # We have reinforcements there allowDisplay = True current_province = province current_garrison = reinf.garrison limit_cmdr = True break if not allowDisplay: return HttpResponse('INVALIDPLANET') plm = p_plm(request, planet, highlight_preference=current_province) plg = p_garrison_prov_dx(request, current_garrison, getRace(request)) plc = p_commands(request, current_planet, current_province, limit_cmdr) repl = dumps((plm, plg, plc, current_planet.id, current_province.id)) return HttpResponse(repl)
def planetpick_mother(request): '''We have picked a mothership. That implies generating everything new. Returns a tuple in JSON: - PLM (HTML) - garrison (HTML) - commands (HTML) - new CurrentPlanetID''' mother = getCurrentMother(request) planet = mother.duePosition() plm = p_plm(request, planet) plg = p_garrison_prov_dx(request, mother.garrison, getRace(request)) plc = p_commands(request, mother.duePosition(), None) repl = dumps((plm, plg, plc, mother.duePosition().id)) return HttpResponse(repl)
def erect(request, pp): mum = getCurrentMother(request) slot = None for i in xrange(0, pp.province.slots): if pp.getPair(i)[0] == 0: slot = i break if slot == None: return HttpResponse('NOFREESLOTS') what = int(request.GET['what']) otype, olvl = pp.getPair(slot) if otype != 0: return HttpResponse('NONZEROSLOT') # Can't build in occupied space costs = getCosts(pp, getRace(request), 0, what) if pp.owner != getAccount(request): return HttpResponse('ACCOUNT') if costs[0] > getResourceIndex(request).stateUpdate(): return HttpResponse('COSTS') if pp.getPendingBuildingsCount() > 0: return HttpResponse('QUEUE') if (otype == 1) and (pp.province.titan_coef == 0): return HttpResponse('RSFAIL_TITAN') if (otype == 2) and (pp.province.pluton_coef == 0): return HttpResponse('RSFAIL_TITAN') if (otype == 3) and (pp.province.town_coef == 0): return HttpResponse('RSFAIL_TITAN') note(request, LP_BUILD_ORDERED, pid=pp.province.id, slot=slot, what=what, levelfrom=olvl) orderBuild(pp, mum, what, slot, costs) return HttpResponse('OK')
def process(request): mother = getCurrentMother(request) # The most basic issues account = getAccount(request) try: # Alliance issues alliance = AllianceMembership.objects.get(account=account) except ObjectDoesNotExist: alliance = None presences = ProvintionalPresence.objects.filter(owner=account) # Get all my provinces # Get all build orders on those province_builds = ProvinceBuildOrder.objects.filter(ppresence__in=presences) planets = [] # Get raw planets handle, will be useful in counting them provinces = [] # BTW, get province handles. for presence in presences: if not presence.province.planet in planets: planets.append(presence.province.planet) provinces.append(presence.province) # Provinces table is needed down there for some freaky shit concerning troops. # I'm quite sure those provinces thingy could be fixed by some annotation shit, but it would # utterly and terribly confuse me, and affect code readability # Get researches/builds on my mother researches = TechnologyResearchOrder.objects.filter(mother=mother) builds = MotherConstructionOrder.objects.filter(mother=mother) # Get troop building queues troop_training = LandarmyProduceOrder.objects.filter(mother=mother).order_by('-got__to_be_completed') # Calculate number of troops in training x = troop_training.aggregate(amount=Sum('amount'))['amount'] if x == None: queued_troop_count = 0 else: queued_troop_count = x # Rock'n'roll here! # Get my outbound salads outbound_salad = ResourceSendOrder.objects.filter(send_from=mother) inbound_salad = ResourceSendOrder.objects.filter(send_to=mother) my_outbounds = LandarmyProvintionalStrikeOrder.objects.filter(attacker=account) # Select movements TOWARDS MY PROVINCES [supplied by a province list] which are NOT MINE inbounds_concerning_me = LandarmyProvintionalStrikeOrder.objects.filter(dstprovince__in=provinces).exclude(attacker=account) my_strikes = LandarmyPlanetaryStrikeOrder.objects.filter(mother=mother) strikes_concerning_me = LandarmyPlanetaryStrikeOrder.objects.filter(province__in=provinces).exclude(mother__owner=account) evacs = LandarmyMotherPickupOrder.objects.filter(mother=mother) # Sorry sad statemento follows. # This view, by the virtue of it's existence, f***s the database without any contraception. # And she will be hurt. # I will get back to optimizing this some other time. # I promise. # TODO: Optimize this view allegiance_tab = {} for planet in planets: for province in planet.province_set.all(): # 0 - MINE, 1 - ENEMY, 2 - ALLIED, 3 - NOBODYS try: province.presence except: allegiance_tab[province.id] = 3 else: # get allegiance if province.presence.owner == getAccount(request): allegiance_tab[province.id] = 0 elif isAllied(getAccount(request), province.presence.owner): allegiance_tab[province.id] = 2 else: allegiance_tab[province.id] = 1 if alliance == None: # alliance is a presence object alliance_o = None else: alliance_o = alliance.alliance # true Alliance object try: # Get alliance ranking alliance_ranking = RankingAlliance.objects.get(alliance=alliance_o) except: alliance_ranking = None try: player_ranking = RankingNone.objects.get(account=getAccount(request)) except: player_ranking = None return render_to_response('stats/empire/empire.html',{'pgo':PrimaryGUIObject(request), 'alliance_m':alliance, 'alliance_ranking':alliance_ranking, 'player_ranking':player_ranking, 'alliance':alliance_o, 'race':getRace(request), 'mother':mother, 'account':account, 'province_count':presences.count(), 'planet_count':len(planets), 'queued_troop_count':queued_troop_count, 'troop_count':0, 'troops_training':troop_training, 'outbound_salad':outbound_salad, 'inbound_salad':inbound_salad, 'researches':researches, 'mother_builds':builds, 'prov_outbounds':my_outbounds, 'prov_inbounds':inbounds_concerning_me, 'prov_builds':province_builds, 'mother_inbounds':my_strikes, 'foreign_mother_inbounds':strikes_concerning_me, 'my_evacs':evacs, 'mother_name':mother.name, 'planets':planets, 'allegiance_tab':allegiance_tab, })
def plug_in(primaryguiobject): primaryguiobject.registerObject('race', getRace(primaryguiobject._request))
def dx_html(request, prov, mum=None): ## Uh, take a note that this still needs to limit displaying provinces we don't have a ship at if mum == None: mum = getCurrentMother(request) mother_evacs = LandarmyMotherPickupOrder.objects.filter(province=prov).filter(mother__owner=getAccount(request)) outgoing_units = LandarmyProvintionalStrikeOrder.objects.filter(srcprovince=prov) try: prov.presence except ObjectDoesNotExist: # MY drops incoming at THIS province mother_drops = LandarmyPlanetaryStrikeOrder.objects.filter(province=prov).filter(mother__owner=getAccount(request)) # MY attacks INCOMING at THIS province prov_target = LandarmyProvintionalStrikeOrder.objects.filter(dstprovince=prov).filter(attacker=getAccount(request)) return render_to_string('space/planetview/generator/unclaimed.html',{'pgo':PrimaryGUIObject(request), 'my_land_inbound':prov_target, 'my_drop_inbound':mother_drops, 'province':prov, 'race':getRace(request)}) if prov.presence.owner != getAccount(request): # MY drops incoming at THIS province mother_drops = LandarmyPlanetaryStrikeOrder.objects.filter(province=prov).filter(mother__owner=getAccount(request)) # MY moves INCOMING at THIS province prov_target = LandarmyProvintionalStrikeOrder.objects.filter(dstprovince=prov).filter(attacker=getAccount(request)) try: reif = Reinforcement.objects.filter(owner=getAccount(request)).get(presence=prov.presence) except: return render_to_string('space/planetview/generator/public.html',{'pgo':PrimaryGUIObject(request), 'my_land_inbound':prov_target, 'my_drop_inbound':mother_drops, 'race':getRace(request), 'province':prov}) else: return render_to_string('space/planetview/generator/reinforcer.html',{'pgo':PrimaryGUIObject(request), 'reinforcement':reif, 'my_land_inbound':prov_target, 'my_drop_inbound':mother_drops, 'province':prov, 'race':getRace(request)}) pbs = prov.presence.getPendingBuilds() d = {} for b in pbs: d[b.slot] = b firstclear = None costs = {} for i in xrange(0, prov.slots): otype, olvl = prov.presence.getPair(i) if otype == 0: if firstclear == None: firstclear = i else: costs[i] = getCosts(prov.presence, getRace(request), olvl, otype) gcosts = {} canerect = {} for i in xrange(1, MPBI+1): gcosts[i] = getCosts(prov.presence, getRace(request), 0, i) canerect[i] = True canerect[1] = (prov.titan_coef > 0) canerect[2] = (prov.pluton_coef > 0) canerect[3] = (prov.town_coef > 0) # ANY drops incoming at THIS province drops = LandarmyPlanetaryStrikeOrder.objects.filter(province=prov) # MY moves INCOMING at THIS province prov_target = LandarmyProvintionalStrikeOrder.objects.filter(dstprovince=prov) # MY moves OUTBOUND from THIS province outgoing_units = LandarmyProvintionalStrikeOrder.objects.filter(srcprovince=prov) # MY evacuations from THIS province evacs = LandarmyMotherPickupOrder.objects.filter(province=prov) return render_to_string('space/planetview/generator/private.html',{'pgo':PrimaryGUIObject(request), 'race':getRace(request), 'costs':costs, 'gcosts':gcosts, 'land_inbound':prov_target, 'drop_inbound':drops, 'evacs_bound':evacs, 'land_outbound':outgoing_units, 'province':prov, 'builds':d, 'canerect':canerect, 'account':getAccount(request), 'first_slot_clear':firstclear})
def process(request, planet_id, province_id=None): try: # check planet planet = Planet.objects.get(id=planet_id) except: return redirect('/') provinces = Province.objects.filter(planet=planet) provinces_postprocessed = {} prov = None try: # faciliates GET getting province to zoom onto if province_id != None: provgrabber = province_id else: provgrabber = int(request.GET['province']) except: provgrabber = None for province in provinces: # 0 - MINE, 1 - ENEMY, 2 - ALLIED, 3 - NOBODYS try: province.provintionalpresence except: pv = 'gray' else: if province.provintionalpresence.owner == getAccount(request): pv = 'green' elif isAllied(getAccount(request), province.provintionalpresence.owner): pv = 'blue' else: pv = 'red' provinces_postprocessed[province.id] = [pv, False] if province.id == provgrabber: prov = province try: if province.provintionalpresence.owner == getAccount(request): if prov == None: prov = province except: pass if prov == None: prov = provinces[0] provinces_postprocessed[prov.id][1] = True mum = getCurrentMother(request) sfx = dx_html(request, prov, mum).decode('utf8') # can relocate? can_relocate = False relocation_time = None if (planet != mum.duePosition()): # Different position than current can_relocate = mum.canRelocate() if can_relocate: relocation_time = getRelocationTime(mum, getRace(request), mum.orbiting, planet) # can scan? can_scan = False if getRace(request) == 1: if mum.isRelocating() == False: if mum.orbiting == planet: can_scan = True return render_to_response('space/planetview/planetview.html', {'htmldata':sfx, 'race':getRace(request), 'planet':planet, 'postprocessed':provinces_postprocessed, 'can_scan':can_scan, 'firstprovince':prov, 'can_relocate':can_relocate, 'relocation_time':relocation_time, 'wctg':lambda x: int((x+100.0)*(345.0/200.0)), 'pgo':PrimaryGUIObject(request)})
def dispatch(request, action, *args, **kwargs): try: cacid = getAccountId(request) except: pass if action == LM_DEPLOY_LAND_GROUND: p = ensure(kwargs['provinceid'], Province) insertFor(cacid, u'Wysłano na <a href="/space/planetview/'+unicode(p.planet.id)+'/?province='+unicode(p.id)+'">'+p.name+u'</a> wojsko') if action == LM_RESEARCH_ORDERED: insertFor(cacid, u'Nakazano rozwój <span>'+TECHNOLOGY_NAMES[kwargs['what']]+u'</span> na poziom <span>'+unicode(kwargs['levelfrom']+1)+'</span>') if action == LM_RESEARCH_CANCELLED: insertFor(cacid, u'Anulowano rozwój <span>'+TECHNOLOGY_NAMES[kwargs['what']]+u'</span> na poziom <span>'+unicode(kwargs['levelcurrent']+1)+'</span>') if action == LM_CONSTRUCTION_ORDERED: insertFor(cacid, u'Nakazano rozbudowę <span>'+CONSTRUCTION_NAMES[kwargs['what']]+u'</span> na poziom <span>'+unicode(kwargs['levelfrom']+1)+'</span>') if action == LM_CONSTRUCTION_CANCELLED: insertFor(cacid, u'Anulowano rozbudowę <span>'+CONSTRUCTION_NAMES[kwargs['what']]+u'</span> na poziom <span>'+unicode(kwargs['levelcurrent']+1)+'</span>') if action == LM_LANDARMY_TRAINING: insertFor(cacid, u'Rozpoczęto szkolenie <span>'+unicode(kwargs['amount'])+u'</span> jednostek <span>'+UNIT_NAMES[getRace(request)][kwargs['what']]+'</span>') if action == LM_RELOCATION: pl = ensure(kwargs['target'], Planet) insertFor(cacid, u'Wykonano skok nadprzestrzenny w kierunku <a href="/space/planetview/'+unicode(pl.id)+u'/">'+pl.name+u'</a>') if action == LM_SENT_RESOURCE: tplayer = ensure(kwargs['target'], Mother).owner rs = kwargs['resources'] insertFor(cacid, u'Wysłałeś <span>'+unicode(rs.titan)+u'</span> tytanu <span>'+unicode(rs.pluton)+u'</span> plutonu <span>'+unicode(rs.men)+u'</span> ludzi do <a href="/uprofile/view/'+unicode(tplayer.id)+'">'+escape(tplayer.empire)+'</a>') if action == LM_RCVD_RESOURCE: fplayer = ensure(kwargs['mfrom'], Mother).owner target = ensure(kwargs['target'], Mother).owner rs = kwargs['resources'] insertFor(target.id, u'Otrzymałeś <span>'+unicode(rs.titan)+u'</span> tytanu <span>'+unicode(rs.pluton)+u'</span> plutonu <span>'+unicode(rs.men)+u'</span> ludzi od <a href="/uprofile/view/'+unicode(fplayer.id)+'">'+escape(fplayer.empire)+'</a>')
def generate(request, mother=None, current_province=None, highlight=None): '''highlight is either None (highlight mother) or True (highlight province)''' account = getAccount(request) if mother == None: mother = getCurrentMother(request) # let's ascertain two variables that will be the basis of functioning of this script. # @current_planet is a bellum.space.models.Planet instance, and is the planet which map we are rendering # @current_province(parameter) is a bellum.province.models.Province instance, and is the province which is highlighted if current_province == None: # if none, then use mothership current_planet = mother.duePosition() # we do not need to highlight a province as it is mother hq we're operating on highlight_planet = False else: highlight_planet = True current_planet = current_province.planet if current_province.presence.owner != account: try: current_province.presence.reinforcement_set.get(owner=account) except ObjectDoesNotExist: return redirect('/') # You can't choose a province that's neither yours nor you have reinforcements on # -------------------------------- Construct planet list presences = ProvintionalPresence.objects.filter(owner=account) # Get all my provinces planets = [] provinces_per_planet = {} for presence in presences: if not presence.province.planet in planets: planets.append(presence.province.planet) try: provinces_per_planet[presence.province.planet.id] += 1 except KeyError: provinces_per_planet[presence.province.planet.id] = 1 reinfs = Reinforcement.objects.filter(owner=account) for reinf in reinfs: if not reinf.presence.province.planet in planets: planets.append(reinf.presence.province.planet) try: provinces_per_planet[reinf.presence.province.planet.id] += 1 except KeyError: provinces_per_planet[reinf.presence.province.planet.id] = 1 limit_cmdr = False # ---------------------------------- Construct garrison if current_province == None: garrison = mother.garrison else: if current_province.presence.owner == account: garrison = current_province.presence.garrison else: limit_cmdr = True garrison = current_province.presence.reinforcement_set.get(owner=account).garrison return render_to_response('space/troopmove/base.html', {'pgo':PrimaryGUIObject(request), 'planets':planets, 'mother':mother, 'highlight_planet':highlight_planet, 'current_planet':current_planet, 'current_province':current_province, 'provinces_per_planet':provinces_per_planet, 'fillin_pla':p_plm(request, current_planet, highlight_preference=current_province).decode('utf8'), 'fillin_garrison':p_garrison_prov_dx(request, garrison, getRace(request)).decode('utf8'), 'fillin_commands':p_commands(request, current_planet, current_province, limit_cmdr).decode('utf8')})
def submit(request): '''The great submit procedure. Accepts nearby anything, and has to resolve it to make sense. And BTW it has to send troops''' # MEMO: If an error occurs here, it kills the script, preventing it from doing anything. It's a GOOD thing, a DEFENSE against # the user. User won't notice, because this script handles AJAX, and AJAX is processed by my JavaScript, not by browser # Quite a show off code it is, isn't it? # -------------------------------------- grab designation, and substitute it for valid in-game code designation = int(request.GET['designation']) if not (designation in (0,1,2)): return HttpResponse('HACK') # Prevent invalid designations dmap = {0:2, 1:1, 2:3} # true code for JS 0 is 2 ("Attack") # true code for JS 1 is 1 ("Attack if not allied on arrival, else Reinforce") # true code for JS 2 is 3 ("Fallback if not allied on arrival, else Reinforce") # there are also other designations(0 - I'm falling back, 4 - Reinforce, 5 - Fallback on arrival) # there are either old or debug designation = dmap[designation] # -------------------------------------- Try to ascertain what we are actually doing. And there's lotta of possibilities source = request.GET['source'] target = request.GET['target'] if (source == 'null') and (target == 'null'): raise Exception # Situation where mother is both source and target are right out if source == 'null': # We are dropping stuff from mothership mother = getCurrentMother(request) # Get our mother object target = Province.objects.get(id=int(target)) # In that case we are dropping unto a province if target.planet != mother.duePosition(): return HttpResponse('HQNT') # Mother cannot drop to a province - she's not there if mother.isRelocating(): return HttpResponse('RELOC') # Mother can't drop during a relocation # Ok, I see no reasons why we shoudn't perform the action for now. order = 'DROP' src_garrison = mother.garrison # Store mother garrison for further checking and reference elif target == 'null': # We are evacuating mother = getCurrentMother(request) # Get our mother object source = Province.objects.get(id=int(source)) # Get our province object if source.planet != mother.duePosition(): return HttpResponse('HQNT') # Mother cannot evac from a province - she's not there if mother.isRelocating(): return HttpResponse('RELOC') # Mother can't evac during a relocation if source.presence.owner != getAccount(request): # If province is not ours (if it's unoccupied, error happens) reinf = source.presence.reinforcement_set.get(owner=getAccount(request)) # If we don't have any reinforcements, error happens order = 'EVAC-REINF' # Ok, we can evacuate our reinforcements src_garrison = reinf.garrison # Store reinforcement garrison for further checking and reference else: order = 'EVAC' # Evacuate our units src_garrison = source.presence.garrison # Store provintional garrison for further checking and reference else: # We are doing a province-to-province transfer source = Province.objects.get(id=int(source)) target = Province.objects.get(id=int(target)) if source.planet != target.planet: raise Exception # Obviously, you can't make interplanetary transfers here :D if source.presence.owner != getAccount(request): return HttpResponse('HACK') # Can't comandeer a province that's not mine. Unoccupied - error if not (target in source.getNeighbours()): return HttpResponse('HACK') # Must be a neighbouring province # Ok, no reasons why we shouldn't do it order = 'ATTACK' src_garrison = source.presence.garrison # Store provintional garrison for further checking and reference # -------------------------------------- Reconstruct a garrison object from that JavaScript GET babble garrison = Garrison() for i in xrange(0, MGI+1): # Do that for every possible troop type try: gv = int(request.GET['st'+str(i)]) # Try to get troop number of troop type "i" from JavaScript GET except: # If it's not there... gv = 0 # Ignore the error. There might be more units ahead to read. garrison[i] = gv # Store the value unto garrison i += 1 # Increase i # ------------------------------------- Check whether we can send that many troops if garrison.isZero(): return HttpResponse('ZERO') # You want to send 0 units? How could it be... if not (garrison in src_garrison): return HttpResponse('HACK') # ------------------------------------- Being outfitted with knowledge of what to do, and with that to do that, let's do that ;) # In each case, we will list variables that are already ready to use. if order == 'EVAC': # Process evacuation request orderMotherPickup(source.presence, garrison, mother, race=getRace(request)) # Order the evacuation note(request, LP_MOTHER_PICKUP_LAND, pid=source.id, garrison=garrison, mid=mother.id) # Store info about evacuation to last-done-stuff(LARF, ie. Last Actions Reporting Format) elif order == 'EVAC-REINF': # Process reinforcement evacuation request orderReinforcementsPickup(source.presence, garrison, mother, reinf, race=getRace(request)) note(request, LP_MOTHER_PICKUP_LAND, pid=source.id, garrison=garrison, mid=mother.id) # Save info about pickup into LARF elif order == 'DROP': # Process drop request orderPlanetaryStrike(garrison, mother, target, designation, 0, race=getRace(request)) # order the drop # Last zero parameter is a placeholder to additional commands # if these were to be implemented at some point in-game note(request, LM_DEPLOY_LAND_GROUND, mid=mother.id, garrison=garrison, provinceid=target.id, designation=designation, orders=0) # Save info into LARF elif order == 'ATTACK': # Process province-to-province transfers orderProvintionalStrike(garrison, source, target, designation, 0, race=getRace(request)) # Order the strike note(request, LP_DEPLOY_LAND_GROUND, pid=source.id, garrison=garrison, target=target, designation=designation, orders=0) # Store info about the deployment into LARF else: # Something terrible, terrible has happened. We are processing unknown order, or our code took an exceptionally wrong codepath. # It's so terrible it's disgusting. And it's totally my fault. If something like that happens, I should fix it ASAP. raise Exception return HttpResponse('OK') # Signal that stuff went just OK