def output_json_map(options, the_world=None, skip_upload=False): from json_lib import mapper_j if the_world != None: cursor = the_world.cursor else: cursor = database.get_cursor() files = {} # create map #------------------------ the_map = mapper_j.JSON_map_maker() map_source = the_map.map_grid(cursor) # print(map_source) # exit() with open('%s/map/latest.json' % common.data['woa_folder'], 'w') as f: f.write(map_source) f.write(padding) with open('%s/map/turn_%d_normal.json' % (common.data['woa_folder'], common.current_turn()), 'w') as f: f.write(map_source) f.write(padding) # Save as files files['latest.json'] = '%s/map/latest.json' % common.data['woa_folder'] files['turn_%d_normal.json' % common.current_turn()] = '%s/map/turn_%d_normal.json' % (common.data['woa_folder'], common.current_turn()) if not skip_upload: upload("ftp.woarl.com", "*****@*****.**", ftp_pass['map'], files, options.delay, options.verbose) print(database.shell_text('[g]Json map uploaded[/g]'))
def major(): team_dict = the_world.teams() total_control = 0 team_count = 0 our_control = 0 for team_id, t in team_dict.items(): # if t.id == the_team.id: continue if t.ir: continue if not t.active: continue stat_f.check_team_stats(the_world.cursor, t, the_world) team_stats = t.get_stats(the_world.cursor) if common.current_turn() in team_stats: total_control += team_stats[common.current_turn()].land_controlled team_count += 1 if t.id == the_team.id: if common.current_turn() in team_stats: our_control = team_stats[common.current_turn()].land_controlled else: our_control = 0 average_control = total_control/float(team_count) if average_control <= our_control: info.append("<span class='pos'>Major:</span> You have above average land control of %s, average is %s" % (our_control, average_control)) return favour_rewards["major_pos"] else: info.append("<span class='neg'>Major:</span> You have below average land control of %s, average is %s" % (our_control, average_control)) return favour_rewards["major_neg"]
def test_negative(self): # Basic success w = dummy_world() t = w.teams()[0] t.stats[common.current_turn()] = stat.Stat({"city_count":10}) t.stats[common.current_turn()-1] = stat.Stat({"city_count":5}) deity_instance = deity_rules.Agashn(w) deity_instance.negative(t) try: self.assertEqual(deity_rules.favour_rewards['negative_pos'], deity_instance.favour) except Exception as e: print("\n") print(common.html_to_terminal("\n".join(deity_instance.info))) print("") raise # Basic failure w = dummy_world() t = w.teams()[0] t.stats[common.current_turn()] = stat.Stat({"city_count":3}) t.stats[common.current_turn()-1] = stat.Stat({"city_count":5}) deity_instance = deity_rules.Agashn(w) deity_instance.negative(t) try: self.assertEqual(deity_rules.favour_rewards['negative_neg'], deity_instance.favour) except Exception as e: print("\n") print(common.html_to_terminal("\n".join(deity_instance.info))) print("") raise
def test_major(self): # Basic success w = dummy_world() t = w.teams()[0] t.stats[common.current_turn()] = stat.Stat({"resources":"Materials:99"}) deity_instance = deity_rules.Laegus(w) deity_instance.major(t) try: self.assertEqual(deity_rules.favour_rewards['major_pos'], deity_instance.favour) except Exception as e: print("\n") print(common.html_to_terminal("\n".join(deity_instance.info))) print("") raise # Basic failure w = dummy_world() t = w.teams()[0] t.stats[common.current_turn()] = stat.Stat({"resources":"Materials:200"}) deity_instance = deity_rules.Laegus(w) deity_instance.major(t) try: self.assertEqual(deity_rules.favour_rewards['major_neg'], deity_instance.favour) except Exception as e: print("\n") print(common.html_to_terminal("\n".join(deity_instance.info))) print("") raise
def _players_that_moved_team(cursor): player_history = {} player_dict = player_q.get_all_players(cursor) # Get last two turns of data query = """SELECT * FROM player_history WHERE turn >= %d""" % (common.current_turn()-2) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) for row in cursor: if row['player'] not in player_dict: continue if player_dict[row['player']].last_posted <= common.current_turn()-6: continue if row['player'] not in player_history: player_history[row['player']] = {} player_history[row['player']][row['turn']] = row['team'] # import pprint # pprint.pprint(player_history) # Now find players that don't match up t1 = common.current_turn()-2 t2 = common.current_turn()-1 moved_players = [] for p, d in player_history.items(): if d.get(t1, 0) != d.get(t2, -1): # print("%s moved from %s to %s" % (player_dict[p].name, d.get(t1, 0), d.get(t2, -1))) moved_players.append(str(p)) return moved_players
def test_major(self): # Basic success w = dummy_world() for i, t in w.teams().items(): t.stats[common.current_turn()] = stat.Stat({"land_controlled":50}) t = w.teams()[0] t.stats[common.current_turn()] = stat.Stat({"land_controlled":100}) deity_instance = deity_rules.Agashn(w) deity_instance.major(t) try: self.assertEqual(deity_rules.favour_rewards['major_pos'], deity_instance.favour) except Exception as e: print("\n") print(common.html_to_terminal("\n".join(deity_instance.info))) print("") raise # Basic failure w = dummy_world() for i, t in w.teams().items(): t.stats[common.current_turn()] = stat.Stat({"land_controlled":50}) t = w.teams()[0] t.stats[common.current_turn()] = stat.Stat({"land_controlled":30}) deity_instance = deity_rules.Agashn(w) deity_instance.major(t) try: self.assertEqual(deity_rules.favour_rewards['major_neg'], deity_instance.favour) except Exception as e: print("\n") print(common.html_to_terminal("\n".join(deity_instance.info))) print("") raise
def capture_chance(the_world, op_id): # relations = the_world.relations()# [Host][Visitor] the_op = the_world.operatives()[op_id] op_dict = the_world.operatives() the_city = the_world.cities()[the_op.city] team_dict = the_world.teams() # Aliases covert_centre = the_world.buildings_lookup()['Covert centre'] covert_tech = the_world.techs_lookup()['Covert training'] operatives_in_city = the_world.operatives_in_city(the_city.id) allied_ops, hostile_ops = spy_report._op_lists_city(the_world, the_op.team, the_city.id) # Allied aid is the sum of their observation allied_score = 0 for o in allied_ops: age = 1 + math.sqrt(common.current_turn() - o.arrival) * 0.1 allied_score += o.observation * o.size * age # Hostile score is the sum of the squares of observation hostile_score = 0 for o in hostile_ops: age = 1 + math.sqrt(common.current_turn() - o.arrival) * 0.1 hostile_score += o.observation * o.size * age # Now we bring into account the operative in question diff = the_world.race_difference(the_op.team, the_city.team) diff = ((diff/10) - the_op.integration)/10# Can range from 1 to -0.5 diff = max(diff, -0.5) diff += 1# Now ranges from 2 to 0.5 hostile_score *= diff# Poor integration and a high physical difference means massive boost to hostile score # Covert centre? if covert_centre in the_city.buildings_amount and the_city.buildings_amount[covert_centre] > 0: hostile_score *= 1.3 age = 1 + math.sqrt(common.current_turn() - o.arrival) * 0.1 allied_score *= (the_op.stealth * age) allied_score *= ((team_dict[the_op.team].tech_levels.get(covert_tech, 0) * 0.03)+1) if allied_score > hostile_score: res = min_catch_chance else: if allied_score == 0: res = 1 else: res = (hostile_score/allied_score) # res *= (hostile_score-allied_score) res /= 100 res += min_catch_chance return res
def minor(): team_dict_c = data.team.get_teams_dict_c() deity_dict_n = data.deity.get_deity_dict_n() city_dict_c = city.get_city_dict_c() operatives_by_city = operative.get_operatives_by_city() operatives_dict_c = operative.get_operatives_dict_c() # First we want a list of all our cities # our_city_list = [c.id for c in city_dict_c.itervalues() if c.team == the_team.id and c.dead == False] our_city_list = [] their_city_list = [] failures = [] for city_id, the_city in city_dict_c.items(): if the_city.dead > 0: continue if common.current_turn() - the_city.founded <= 3: continue if the_city.team == the_team.id: our_city_list.append(city_id) else: # If they follow Soag chi then we can skip them if deity_dict_n['Soag chi'] in team_dict_c[the_city.team].get_deities(): continue their_city_list.append(city_id) # New we compare each with each for our_city_id in our_city_list: city_fails = False our_city = city_dict_c[our_city_id] for their_city_id in their_city_list: if city_fails: continue their_city = city_dict_c[their_city_id] # Is this city within range? distance = data.path.pythagoras((our_city.x, our_city.y), (their_city.x, their_city.y)) if distance <= 100: if common.current_turn() - their_city.founded > 2: city_fails = True failures.append(our_city.name) if len(failures) < 1: info.append("<span class='pos'>Minor:</span> All your cities are at least 100 units away from any city older than 2 years") return favour_rewards["minor_pos"] else: if len(failures) > 1: info.append("<span class='neg'>Minor:</span> The following cities are within 100 map units of one or more cities older than 2 years: %s and %s" % (", ".join(failures[0:-1]), failures[-1])) else: info.append("<span class='neg'>Minor:</span> The city of %s is within 100 map units of a city older than two years" % (failures[0])) return favour_rewards["minor_neg"]
def major(): # If this is in pre-orders then the stats won't exist # If it's mid-turn the stats are what we need if common.current_turn() in the_team.get_stats(the_world.cursor): team_stats = the_team.get_stats(the_world.cursor)[common.current_turn()] materials = res_dict.Res_dict(team_stats.resources).get("Materials") else: materials = res_dict.Res_dict(the_team.resources).get("Materials") if materials <= 100: info.append("<span class='pos'>Major:</span> You ended the year with fewer than 100 surplus materials") return favour_rewards["major_pos"] else: info.append("<span class='neg'>Major:</span> You ended the year with a surplus of over 100 materials (%s)" % materials) return favour_rewards["major_neg"]
def make_founding_query(team_id, name, city_location, is_port, is_nomadic, city_size, city_list): """Makes a set of queries for founding a new city""" if city_list == []: return [] queries = [] queries.append("""INSERT INTO cities (name, team, x, y, port, nomadic, population, founded, dead, secret) values ('%(name)s', %(team)s, %(x)s, %(y)s, %(port)s, %(nomadic)s, %(population)s, %(founded)s, 0, False);""".replace("\n", "") % { "name": database.escape(name), "team": team_id, "port": is_port, "nomadic": is_nomadic, "population": city_size, "x": city_location[0], "y": city_location[1], "founded": int(common.current_turn()), }) amount_per_city = math.ceil(city_size/len(city_list)) for c in city_list: queries.append("""UPDATE cities SET population = population-%d WHERE id = %d;""" % (amount_per_city, c)) return queries
def minor(): if campaign_f.team_campaign_count(the_world.cursor, the_team.id, common.current_turn()) >= 1: info.append("<span class='pos'>Minor:</span> You participated in at least three wars") return favour_rewards["minor_pos"] else: info.append("<span class='neg'>Minor:</span> You participated in fewer than 3 wars this year") return favour_rewards["minor_neg"]
def major(): team_dict_c = the_world.teams() city_dict_c = the_world.cities() operatives_dict_c = the_world.operatives() the_world.operatives_in_city(0) operatives_by_city = the_world._operatives_in_city # First we want a list of all our cities our_city_list = [] their_city_list = [] for city_id, the_city in city_dict_c.items(): if the_city.dead > 0: continue if the_city.team == the_team.id: our_city_list.append(city_id) elif common.current_turn() - the_city.founded > 2: their_city_list.append(city_id) nations_within_range = set() nations_infiltrated = set() # New we compare each with each for our_city_id in our_city_list: our_city = city_dict_c[our_city_id] for their_city_id in their_city_list: their_city = city_dict_c[their_city_id] # Is this city within range? distance = path_f.pythagoras((our_city.x, our_city.y), (their_city.x, their_city.y)) if distance <= 1000: nations_within_range.add(their_city.team) if their_city_id in operatives_by_city: city_has_op = False for o in operatives_by_city[their_city_id]: if operatives_dict_c[o].team == the_team.id and operatives_dict_c[o].died < 1: city_has_op = True if city_has_op: nations_infiltrated.add(their_city.team) # Now to find out what nations we fail at failures = [] for t in nations_within_range: if t not in nations_infiltrated: failures.append(team_dict_c[t].name) if len(failures) == 0: info.append("<span class='pos'>Major:</span> You have operatives within all nations within 1000 units of your cities" % (operative_percentage)) return favour_rewards["major_pos"] else: if len(failures) > 1: info.append("<span class='neg'>Major:</span> The following nations do not have operatives in them: %s and %s" % (", ".join(failures[0:-1]), failures[-1])) else: info.append("<span class='neg'>Major:</span> The nation of %s does not have an operative in it" % (failures[0])) return favour_rewards["major_neg"]
def pre_orders(options): start_time = time.time() cursor = database.get_cursor() the_world = spy_world.Spy_world(cursor) team_dict = the_world.active_teams() # Stats first, it's used for some favour stuff #------------------------ for team_id, the_team in team_dict.items(): stat_f.build_team_stats(the_world.cursor, the_team, the_world) # Now to assign the stats team_q.mass_get_team_stats(the_world.cursor, team_dict, common.current_turn()) # Pre orders - Teams #------------------------ cursor.execute("BEGIN") print(database.shell_text("Team pre-orders"), end="") for team_id, the_team in team_dict.items(): try: team_f.pre_orders(the_world, the_team) except Exception as e: cursor.execute("ROLLBACK") print(database.shell_text(" - [r]Failure[/r]")) print("Failure running pre-orders for %s" % the_team.name) print(database.shell_text("[r]Re run as 'rob3 start -l True[/r]'")) raise print(database.shell_text(" - [g]Done[/g]")) # Pre orders - System #------------------------ print(database.shell_text("System pre-orders"), end="") try: # Army history army_f.location_history(the_world) # Player history player_f.turn_history(the_world) # Power history power_f.turn_history(the_world) # Artefact history artefact_f.turn_history(the_world) # Operatives catching operative_f.catch_operatives(the_world) # Border history team_f.border_history(the_world) except Exception as e: cursor.execute("ROLLBACK") print(database.shell_text(" - [r]Failure[/r]")) print(database.shell_text("[r]Re run as 'rob3 start -l True[/r]'")) raise cursor.execute("COMMIT") print(database.shell_text("\nNow run [g]rob orders[/g]"))
def clear_out_old_team_caches(cursor, verbose): """Get rid of all caches older than 10 turns""" cutoff = common.current_turn()-10 queries = [] # TI cache queries.append("DELETE FROM ti_cache WHERE turn < %d" % cutoff) # Post cache queries.append("DELETE FROM post_cache WHERE turn < %d" % cutoff) # Orders cache # queries.append("DELETE FROM intorders WHERE id IN SELECT post_id FROM orders WHERE turn < %d" % cutoff) queries.append("DELETE FROM orders WHERE turn < %d" % cutoff) for q in queries: try: cursor.execute(q) except Exception as e: print("Query: %s\n" % q) raise e if verbose: print("teams_check.clear_out_old_team_caches() cleared out all cache info over 10 turns old")
def negative(): team_stats = the_team.get_stats(the_world.cursor) if (common.current_turn()-1) not in team_stats: cities_this_turn = 1 cities_last_turn = 0 else: cities_this_turn = team_stats[common.current_turn()].city_count cities_last_turn = team_stats[common.current_turn()-1].city_count if cities_this_turn >= cities_last_turn: info.append("<span class='pos'>Negative:</span> You have ended this year with at least as many cities as you ended last year with") return favour_rewards["negative_pos"] else: info.append("<span class='neg'>Negative:</span> You have ended this year with 1 or more fewer cities than last year") return favour_rewards["negative_neg"]
def build_turn(w, turn=-1): """Build a list of files to upload for the current turn based on campaigns etc""" if turn < 1: turn = common.current_turn() files = {} # Update topic update_topic_new(w) update_topic_old(w) # Save it with open('%s%d_overview.html' % (common.data['cache_path'], turn), 'w') as f: f.write(voi.headers.format(title = "Turn %d campaign overview" % turn)) f.write(get_page(w.cursor, "list_campaigns", turn = turn)) f.write(voi.footers) f.write(cli_f.padding) files['%s_%d_overview.html' % (tk, turn)] = '%s%d_overview.html' % (common.data['cache_path'], turn) # For each campaign for c in w.campaigns_from_turn(turn=turn): files = combine_dicts(files, _build_campaign(w, c)) return files
def turn_key(turn=-1): if turn < 1: turn = common.current_turn() m = md5() m.update("GM_turn_key".encode("utf-8")) m.update(str(turn).encode("utf-8")) return m.hexdigest()
def negative(): if campaign_f.team_campaign_count(the_world.cursor, the_team.id, common.current_turn()) > 1: info.append("<span class='neg'>Negative:</span> You participated in more than one war this year") return favour_rewards["negative_neg"] else: info.append("<span class='pos'>Negative:</span> You participated in one or fewer wars this year") return favour_rewards["negative_pos"]
def minor(): if campaign_f.team_campaign_count(the_world.cursor, the_team.id, common.current_turn()) > 0: info.append("<span class='pos'>Minor:</span> You participated in at least one war") return favour_rewards["minor_pos"] else: info.append("<span class='neg'>Minor:</span> You did not participate in any wars") return favour_rewards["minor_neg"]
def update_player_activity(player_dict): queries = [] for p, t in player_dict.items(): queries.append("UPDATE players SET last_posted = %d, team = %s WHERE id = %s;" % (common.current_turn(), t, p)) return queries
def main(cursor): team_id = int(common.get_val("team", 0)) turn = int(common.get_val("turn", -1)) if team_id < 1: return "<div style='padding: 5px;'>%s</div>" % common.select_team_form(cursor, "view_orders") if turn < 1: turn = common.current_turn() the_world = world.World(cursor) player_dict = the_world.players() the_team = team_q.get_one_team(cursor, team_id) the_orders = the_team.get_orders(cursor, the_world, "international", turn) # output = ["<div style='padding: 5px; font-size: 14px; line-height: 17px;'>"] output = ["<div style='padding: 5px;'>"] player_updates = {} for o in the_orders: player_updates[o.player] = o.team if o.content == "Orders placeholder": continue output.append( '<br /><hr />Post: <a href="http://woarl.com/board/viewtopic.php?p=%s#p%s">%s</a><br />' % (o.post_id, o.post_id, o.post_id) ) output.append( 'Poster: <a href="http://woarl.com/board/memberlist.php?mode=viewprofile&u=%d">%s</a> - ' % (o.player, player_dict[o.player].name) ) output.append('<a href="web.py?mode=edit_player&player=%d">Local edit</a><br />' % (o.player)) output.append(common.bbcode_to_html(o.content.replace('<span class="stitle">', '<hr /><span class="stitle">'))) output.append("</div>") # Update player activity if turn == common.current_turn(): database.query(cursor, player_f.update_player_activity(player_updates)) # print "<br />".join(output) page_data["Title"] = "%s International orders" % the_team.name return "".join(output)
def add_kill(killer, victim, turn=-1, battle=-1): if turn < 0: turn = common.current_turn() query = """INSERT INTO player_kills (killer, victim, turn, battle) values (%d, %d, %d, %d);""" % (killer, victim, turn, battle) return [query]
def backup(options): file_path = "%s/backup/turn_%s.sql" % (common.data['server_fpath'], common.current_turn()) args = "-h localhost -U postgres" os.system("pg_dump %s rob3 -f %s" % (args, file_path)) if options.verbose: print(database.shell_text("[g]Database backed up[/g]"))
def save_json(team, content): from pages import common turn = common.current_turn() return [ "DELETE FROM team_json_ti WHERE team = %d AND turn = %d" % (team, turn), "INSERT INTO team_json_ti (turn, team, content) values (%d, %d, '%s');" % (turn, team, database.escape(content)), ]
def _basic_observation(the_world, team_id, area, radius): your_ops, their_ops = _op_lists(the_world, team_id, area, radius) # Allied aid is the sum of their observation your_score = 0 for o in your_ops: age = 1 + math.sqrt(max(common.current_turn() - o.arrival, 1)) * 0.1 your_score += o.observation * math.sqrt(o.size) * age # Hostile score is the sum of the squares of observation their_score = 0 for o in their_ops: age = 1 + math.sqrt(max(common.current_turn() - o.arrival, 1)) * 0.2# Age counts for more when it's home ground their_score += math.sqrt(o.observation) * math.sqrt(o.size) * age your_score = sum([o.observation * math.sqrt(o.size) for o in your_ops]) + 1 their_score = sum([o.observation * math.sqrt(o.size) for o in their_ops]) + 1 return your_score/their_score
def check_operative_locations(cursor, verbose): """Finds operatives in dead cities and relocates them""" teams_dict = team_q.get_all_teams(cursor) operatives_dict = operative_q.get_all_operatives(cursor) city_dict = city_q.get_all_cities(cursor) # Get a list of the dead cities dead_city_list = [] for c_id, the_city in city_dict.items(): if the_city.dead > 0 or not teams_dict[the_city.team].active: dead_city_list.append(str(c_id)) # Find operatives in those cities query = """SELECT id FROM operatives WHERE city in (%s) and died < 1""" % ",".join(dead_city_list) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) move_op_list = {} for row in cursor: o = row['id'] t = operatives_dict[o].team if not teams_dict[t].active: continue if t not in move_op_list: move_op_list[t] = [] move_op_list[t].append(str(o)) # Find out which teams we need to get a city for teams_cities = {} for t in move_op_list.keys(): teams_cities[t] = -1 # Find cities for those teams if verbose: it = cli_f.progressbar(city_dict.items(), "ops_check.check_operative_locations: ", 40, with_eta = True) else: it = city_dict.items() for c_id, the_city in it: if the_city.team in teams_cities and not teams_dict[the_city.team].dead: teams_cities[the_city.team] = c_id # Now run the queries queries = [] for t, c in teams_cities.items(): query = "UPDATE operatives SET city = %d, arrival = %d WHERE id in (%s)" % ( c, common.current_turn(), ",".join(move_op_list[t]), ) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query))
def negative(): team_stats = the_team.get_stats(the_world.cursor) try: pop_this_turn = team_stats[common.current_turn()].population except Exception: pop_this_turn = 250 if (common.current_turn()-1) not in team_stats: pop_last_turn = 250 else: pop_last_turn = team_stats[common.current_turn()-1].population if pop_this_turn > pop_last_turn: info.append("<span class='pos'>Negative:</span> You have at least as many civilians as last turn") return favour_rewards["negative_pos"] else: info.append("<span class='neg'>Negative:</span> You have fewer civilians than you did last turn") return favour_rewards["negative_neg"]
def ir_player_activity(cursor, verbose): query = """UPDATE players SET last_posted = %d WHERE id in (%s);""" % ( common.current_turn()-5, ",".join((str(i) for i in ir_players))) try: cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query)) if verbose: print("players_check.ir_player_activity() updated all IR accounts")
def approve(self, team, title, content, turn=-1): if turn < 1: turn = common.current_turn() return ["""INSERT INTO interactive_orders (team, turn, title, content) values ({team}, {turn}, '{title}', '{content}');""".format( team = team, turn = turn, title = title, content = database.escape(content), )]
def major(): team_stats = the_team.get_stats(the_world.cursor) try: cities_this_turn = team_stats[common.current_turn()].city_count except Exception: cities_this_turn = 0 if (common.current_turn()-1) not in team_stats: cities_last_turn = 0 else: cities_last_turn = team_stats[common.current_turn()-1].city_count if cities_this_turn > cities_last_turn: info.append("<span class='pos'>Major:</span> You have at least 1 more city this turn than the last") return favour_rewards["major_pos"] else: info.append("<span class='neg'>Major:</span> You do not have at least 1 more city this turn than the last") return favour_rewards["major_neg"]