def radar(request, pp): '''needs a presence in 'pp' ''' if pp.owner != getAccount(request): return HttpResponse('ACCOUNT') radarlevel = 0 for i in xrange(0, pp.province.slots): otype, olvl = pp.getPair(i) if otype == 4: if olvl > radarlevel: radarlevel = olvl if radarlevel == 0: return HttpResponse('NORADAR') ms = Mother.objects.filter(orbiting=pp.province.planet) mros_i = MotherRelocationOrder.objects.filter(loc_to=pp.province.planet) mros_o = MotherRelocationOrder.objects.filter(loc_from=pp.province.planet) sms = filter(lambda x: (not x in mros_i) and (not x in mros_o), ms) srl = RadarReportv01(pp.province, radarlevel) if radarlevel >= 1: # radar lv 1 for mum in sms: srl.appendStationary(mum) if radarlevel >= 2: # radar lv 2 for mum in mros_i: srl.appendInbound(mum) if radarlevel >= 3: # radar lv 3 for mum in mros_o: srl.appendOutbound(mum) rp = makeReport(srl) sendTo(rp, getAccount(request), u'Raport radaru z '+pp.province.name) 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 process(request, membership): if (getAccount(request) == membership.alliance.leader): return HttpResponse('LEADERCANTLEAVE') else: note(request, LA_LEAVE_ALLIANCE, name=membership.alliance.name, shname=membership.alliance.shname, aid=membership.alliance.id, accid=getAccountId(request)) membership.alliance.members -= 1 membership.alliance.save() bootFromAlliance(membership.alliance, getAccount(request)) membership.delete() 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 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 rank(request, membership, target_membership_id): # supply new rank via GET:rank target_membership_id = int(target_membership_id) try: tm = AllianceMembership.objects.get(id=target_membership_id) except ObjectDoesNotExist: return HttpResponse('INVALID MEMBERSHIP') if tm.alliance != membership.alliance: return HttpResponse(escape(tm.rank)) if (tm.account == membership.alliance.leader): # if you change leader rank if not (getAccount(request) == membership.alliance.leader): # you must be the leader return HttpResponse(escape(tm.rank)) if not membership.hasPrivilege(AM_PRIVILEGE): return HttpResponse(escape(tm.rank)) tm.rank = request.GET['rank'] try: tm.save() except: pass return HttpResponse(escape(tm.rank))
def process(request, rankingtype, page): if not (rankingtype in ('all', 'mother', 'army', 'allied')): return redirect('/') rt = {'all':RankingNone, 'army':RankingArmy, 'mother':RankingMother, 'allied':RankingAlliance} if page == None: # caveats pass else: page = int(page) ranking = rt[rankingtype].objects.filter(id__gt=RPP*(page-1)).filter(id__lt=(RPP*page)+1) acc = getAccount(request) total_objects_count = rt[rankingtype].objects.count() pages = int(ceil(total_objects_count / RPP)) pagination = [] if (pages < 8): # special case - static pagination = range(1, pages+1) elif (page > 3) and (page < pages-2): # no special cases apply pagination = [page-3, page-2, page-1, page, page+1, page+2, page+3] elif (page < 4): # less than 3 entries left pagination = range(1, page+1) + [page+1, page+2, page+3] elif (page > pages-4): # less than 3 entries right pagination = [page-3, page-2, page-1, page] + range(page+1, pages+1) return render_to_response('stats/ranking/'+rankingtype+'.html',{'pgo':PrimaryGUIObject(request), 'account':acc, 'page':page, 'pagecount':pages, 'pages':pagination, 'ranking':ranking})
def cancel_strike(request): '''cancels a provintional strike of ID given as GET id''' try: lpso = LandarmyProvintionalStrikeOrder.objects.get(id=int(request.GET['id'])) except: return HttpResponse('FAIL') if lpso.designation == 0: return HttpResponse('FAIL') if lpso.attacker != getAccount(request): return HttpResponse('FAIL') lpso.directiveFallback() return HttpResponse('OKAY')
def cancel_drop(request): '''cancels a drop of drop ID given as GET id''' try: lpso = LandarmyPlanetaryStrikeOrder.objects.get(id=int(request.GET['id'])) except: return HttpResponse('FAIL') if lpso.designation == 0: return HttpResponse('FAIL') if lpso.mother.owner != getAccount(request): return HttpResponse('FAIL') lpso.fallback() return HttpResponse('OKAY')
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 process(request): try: aap = AllianceApplication.objects.get(applicant=getAccount(request)) except ObjectDoesNotExist: pass else: return render_to_response('alliance/apply/applying.html', {'pgo':PrimaryGUIObject(request), 'application':aap, 'alliance':aap.alliance}) if request.method == 'POST': af = NewAllianceForm(request.POST) if af.is_valid(): group_id, board_id = createAlliance(af.cleaned_data['name'], getAccount(request)) af.instance.name = af.cleaned_data['name'] af.instance.shname = af.cleaned_data['shname'] af.instance.leader = getAccount(request) af.instance.mainpage = u'Do ustawienia' af.instance.members = 1 af.instance.smf_board_id = board_id af.instance.smf_group_id = group_id af.instance.save() amb = AllianceMembership(None, af.instance.leader.id, af.instance.id, 255, u'Szef') amb.save() note(request, LA_CREATE_ALLIANCE, name=af.instance.name, shname=af.instance.shname, aid=af.instance.id) return redirect('/alliance/view/own/') try: af except: af = NewAllianceForm() return render_to_response('alliance/new/newform.html', {'form':af, 'pgo':PrimaryGUIObject(request)})
def p_plm(request, planet, highlight_preference=None): '''Generate planet map highlight preference is a province instance''' allegiance_tab = {} for province in planet.province_set.all(): # 0 - MINE, 1 - ENEMY, 2 - ALLIED, 3 - NOBODYS try: province.provintionalpresence except: allegiance_tab[province.id] = 'gray' else: if province.provintionalpresence.owner == getAccount(request): allegiance_tab[province.id] = 'green' elif isAllied(getAccount(request), province.provintionalpresence.owner): allegiance_tab[province.id] = 'blue' else: allegiance_tab[province.id] = 'red' x = render_to_string('space/troopmove/generator/pla.html', {'planet':planet, 'wctg':lambda x: int((x+100.0)*(345.0/200.0)), 'allegiance_strings':allegiance_tab, 'highlight_preference':highlight_preference}) return x
def retr(request, pvmsg_id): # retrieve a message/report acc = getAccount(request) try: pmsg = LCDMessage.objects.get(id=pvmsg_id) except ObjectDoesNotExist: return HttpResponse(dumps(None)) if pmsg.recipient != acc: return HttpResponse('NOT YOURS HACKER') msg_cont = pmsg.mapRef() # extract reference - a Report object in this case if pmsg.msgtype != LCDMT_PRIVATE: # this is not a private message, this is a REPORT try: am = AllianceMembership.objects.get(account=getAccount(request)) except: am = None if isinstance(msg_cont.data, WarfareReport): f = render_to_string('stats/reports/WarfareReport/report.html', {'r':msg_cont.data, 'membership':am}) if isinstance(msg_cont.data, ScanReportv01): f = render_to_string('stats/reports/ScanReportv01/report.html', {'r':msg_cont.data, 'membership':am}) if isinstance(msg_cont.data, RadarReportv01): f = render_to_string('stats/reports/RadarReportv01/report.html', {'r':msg_cont.data, 'membership':am}) if pmsg.relayed != None: rp = (pmsg.id, pmsg.msgtype, f, msg_cont.title, True, pmsg.relayed.id, pmsg.relayed.empire) else: rp = (pmsg.id, pmsg.msgtype, f, msg_cont.title, False) else: # this is a private message rp = (pmsg.id, pmsg.msgtype, escape(msg_cont.text).replace('\n', '<br>'), pmsg.author.id, pmsg.author.empire) cacheContactAcc(request, pmsg.author) if pmsg.readed == 0: pmsg.readed = 1 pmsg.save() return HttpResponse(dumps(rp))
def process(request): acc = getAccount(request) ll = fileFor(acc.id) a = [] tmp = [] for x in ll.readlines(): tmp += [x] if len(tmp) == 2: # should be appended a.append(tmp) tmp = [] return render_to_response('stats/larf/larf.html',{'pgo':PrimaryGUIObject(request), 'entries':a})
def cancel(request, pp): slot = int(request.GET['slot']) if pp.owner != getAccount(request): return HttpResponse('ACCOUNT') otype, olvl = pp.getPair(slot) # if we are cancelling an erection, otype == 0 ... try: otype = cancelBuild(pp, slot) # ... therefore this except: return HttpResponse('UNEXISTANT') note(request, LP_BUILD_CANCELLED, what=otype, pid=pp.province.id, levelcurrent=olvl) return HttpResponse('OK')
def process(request, membership): if not (getAccount(request) == membership.alliance.leader): return HttpResponse('NOT LEADER') alliance = membership.alliance note(request, LA_DISBAND_ALLIANCE, aid=alliance.id, name=alliance.name, shname=alliance.shname) AllianceApplication.objects.filter(alliance=alliance).delete() for ams in AllianceMembership.objects.filter(alliance=membership.alliance): bootFromAlliance(alliance, ams.account) ams.delete() destroyAlliance(alliance) membership.alliance.delete() return HttpResponse('OK')
def convr(request): '''Long-term report library''' acc = getAccount(request) for dmsg in LCDMessage.objects.filter(recipient=acc).filter(senton__lt=datetime.now()-timedelta(14)): dmsg.delete() rmsgs = LCDMessage.objects.filter(recipient=acc).exclude(msgtype=LCDMT_PRIVATE).order_by('-senton') msga = [] for rmsg in rmsgs: if rmsg.relayed == None: msga.append((rmsg.id, rmsg.mapRef().title, rmsg.senton.strftime('%H:%M %d.%m.%Y'), False)) else: msga.append((rmsg.id, rmsg.mapRef().title, rmsg.senton.strftime('%H:%M %d.%m.%Y'), True, rmsg.relayed.id, rmsg.relayed.empire)) return HttpResponse(dumps(msga))
def process(request, acc_id): try: acc = Account.objects.get(id=acc_id) except: return redirect('/') try: tmum = Mother.objects.get(owner=acc) except: # unregistered return redirect('/stats/empire/') rtt = getResourceTravelTime(getCurrentMother(request), tmum) return render_to_response('uprofile/view/view.html', {'account':acc, 'rtt':rtt, 'same': getAccount(request) == acc, 'pgo':PrimaryGUIObject(request)})
def convp(request, acc_id): '''Long-term conversation with a Particular player''' acc = getAccount(request) try: target = Account.objects.get(id=acc_id) except: return HttpResponse(dumps(None)) for dmsg in LCDMessage.objects.filter((Q(author=acc) & Q(recipient=target)) | (Q(author=target) & Q(recipient=acc))).filter(msgtype=LCDMT_PRIVATE).filter(senton__lt=datetime.now()-timedelta(14)): dmsg.delete() pmsgs = LCDMessage.objects.filter((Q(author=acc) & Q(recipient=target)) | (Q(author=target) & Q(recipient=acc))).filter(msgtype=LCDMT_PRIVATE).order_by('-senton') msga = [] for msg in pmsgs: x = (msg.author != target, escape(msg.mapRef().text).replace('\n', '<br>'), msg.senton.strftime('%H:%M %d.%m.%Y')) msga.append(x) return HttpResponse(dumps((target.empire, msga)))
def push(request): # send a private message to target player. Target's ID is in POST try: target = Account.objects.get(id=int(request.POST['target'])) except: return HttpResponse(dumps(None)) m = PrivateMessage(text=request.POST['content'], references=1) try: m.save() except: pass pm = LCDMessage(recipient=target, author=getAccount(request), msgtype=LCDMT_PRIVATE, message_ref=m.id) pm.save() cacheContactAcc(request, target) return HttpResponse(dumps(True))
def process(request): acc = getAccount(request) # cash_data: dict{planet_id => list( ... (province_id, province_name, cash) ... ) } # planetary_map: dict(planet_id => planet_name) # sumup_data: dict(planet_id => sum_of_incomes) # ppres: set of analyzed presences cash_data = {} planetary_map = {} ppres = ProvintionalPresence.objects.filter(owner=acc) sumup_data = {} for pp in ppres: try: # Cache in mapping planetary_map[pp.province.planet_id] except: planetary_map[pp.province.planet_id] = pp.province.planet.name try: # Ensure a cash_data slot exists cash_data[pp.province.planet_id] except: cash_data[pp.province.planet_id] = [] try: # Ensure a sumup_data slot exists sumup_data[pp.province.planet_id] except: sumup_data[pp.province.planet_id] = ResourceIndex() cp = calculate_presence(pp) cash_data[pp.province.planet_id].append((pp.province_id, pp.province.name, cp)) sumup_data[pp.province.planet_id].addRatio(cp) mother = Mother.objects.get(owner=acc) mum = calculate_mother(mother) return render_to_response('stats/income/income.html',{'pgo':PrimaryGUIObject(request), 'account':acc, 'provinces':cash_data, 'planet_sums':sumup_data, 'planet_id_to_name':planetary_map, 'mother':mum, 'zero':zero, 'mother_name':mother.name})
def query(request): '''Get list of unreaded messages''' acc = getAccount(request) msgs = LCDMessage.objects.filter(recipient=acc).filter(readed=0) tab = [] for msg in msgs: if msg.msgtype == LCDMT_PRIVATE: tab.append((msg.id, LCDMT_PRIVATE, msg.author.id, msg.author.empire)) elif msg.msgtype in (LCDMT_UR, LCDMT_SR): tab.append((msg.id, msg.msgtype)) f = [] for id, empire in request.session['ChatCache'].iteritems(): f.append((id, empire)) return HttpResponse(dumps((tab, f)))
def process(request): try: titan = int(request.GET['titan']) except: titan = 0 try: pluton = int(request.GET['pluton']) except: pluton = 0 try: manpower = int(request.GET['men']) except: manpower = 0 try: target = Account.objects.get(id=int(request.GET['target'])) except: return HttpResponse('FAIL') my_mum = getCurrentMother(request) acc = getAccount(request) if acc == target: return HttpResponse('SELF') rindex = getResourceIndex(request) rindex.stateUpdate() sending_res = ResourceIndex(titan=titan, pluton=pluton, men=manpower) if (sending_res == 0): return HttpResponse('NULL') if (sending_res > rindex): return HttpResponse('TOOMUCH') tg_mother = Mother.objects.get(owner=target) note(request, LM_SENT_RESOURCE, mid=my_mum.id, target=tg_mother.id, resources=sending_res) orderResourceSend(my_mum, tg_mother, sending_res.titan, sending_res.pluton, sending_res.men) return HttpResponse('OK')
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 relay(request, msg_id, acc_id): '''relay a message to specified account. Must be a report''' acc = getAccount(request) try: target = Account.objects.get(id=acc_id) except: return HttpResponse(dumps(None)) try: rmsg = LCDMessage.objects.get(id=msg_id) except ObjectDoesNotExist: return HttpResponse(dumps(None)) if rmsg.msgtype == LCDMT_PRIVATE: return HttpResponse(dumps(None)) # it's a private message rmsg.mapRef().link() newmsg = LCDMessage(recipient=target, author=rmsg.author, msgtype=rmsg.msgtype, \ senton=rmsg.senton, message_ref=rmsg.message_ref, relayed=acc) newmsg.save() return HttpResponse('OK')
def process(request, path): from bellum.portal.models import Page try: this = Page.objects.get(path=path) except: this = Page.objects.get(path=r'/') try: account = getAccount(request) mother = getCurrentMother(request) except: account = None mother = None # construct backway routing: br = [] br_i = this try: while True: br.append(br_i) br_i = br_i.getParent() except: pass # construct alongside-peerlist: ap = [] for i in br: ap.append(i.getPeers()) # construct rendering tree: rt_p = zip(br, ap) # rendering tree, proto # wait, does this element have children? try: if this.getChildren().count > 0: rt_p = [(None, this.getChildren())] + rt_p except: pass rtext = u'' # render outmost layer b_counter = len(rt_p) for elem, peers in rt_p: x = u'' for peer in peers: if peer.path[:8] == u'special:': x += u'<h'+str(b_counter)+' onclick="window.location=\''+peer.path[8:]+'\'"' else: x += u'<h'+str(b_counter)+' onclick="window.location=\'/portal/'+peer.path+'\'"' if peer == elem: x += ' style="color: white"' x += u'>'+peer.title+'</h'+str(b_counter)+'>' if peer == elem: x += rtext rtext = '<div id="container_h'+str(b_counter)+'">'+x+'</div>' b_counter -= 1 content = Template(this.content).render_unicode(this=this, account=account, mother=mother) css = Template(this.head).render_unicode(this=this, account=account, mother=mother) return render_to_response('portal.html', {'menu':rtext, 'content':content, 'head':css, 'this':this, 'account':account, 'mother':mother})
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 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