def test_is_enemy(self): c2 = country.Country() c3 = country.Country() self.c.add_area([(0, 0), (100, 0), (100, 100)]) self.assertFalse(self.c.is_enemy(c2)) c2.add_area([(0, 0), (100, 0), (100, -100)]) self.assertFalse(self.c.is_enemy(c2)) c3.add_area([(20, 50), (70, 30), (60, 100)]) self.assertTrue(self.c.is_enemy(c3))
def test_where_do_i_live(self): country1 = country.Country() country1.add_area([(0, 0), (100, 0), (100, 100)]) country2 = country.Country() country2.add_area([(0, 0), (100, 0), (100, -100)]) self.assertIsNone(self.c.where_do_i_live()) country1.area.add_resident(self.c) self.assertEqual(self.c.where_do_i_live(), country1) country2.area.add_resident(self.c) self.assertEqual(self.c.where_do_i_live(), country2)
def test_parse(self): country1 = country.Country([[1, 1], [10, 1], [10, 10], [1, 10]]) country2 = country.Country([[5, 5], [12, 5], [12, 12], [5, 12]]) country3 = country.Country([[100, 100], [100, 200], [200, 200], [200, 100]]) country4 = country.Country([[200, 200], [300, 200], [300, 300], [200, 300]]) graph = country.Graph([country1, country2, country3, country4]) string = parse.save(graph) graph2 = parse.load(string.splitlines()) self.assertEqual(graph, graph2)
def test_travel(self): country1 = country.Country() country1.add_area([(0, 0), (100, 0), (100, 100)]) country2 = country.Country() country2.add_area([(0, 0), (100, 0), (100, -100)]) country3 = country.Country() country3.add_area([(200, 0), (500, 0), (200, 200)]) country1.area.add_resident(self.c) self.c.travel(country2) self.assertEqual(self.c.where_do_i_live(), country2) self.c.travel(country3) self.assertEqual(self.c.where_do_i_live(), country2)
def test_country_neigh(self): country1 = country.Country([[1, 1], [10, 1], [10, 10], [1, 10]]) country12 = country.Country([[1, 1], [10, 1], [10, 10], [1, 10]]) country2 = country.Country([[5, 5], [12, 5], [12, 12], [5, 12]]) country3 = country.Country([[100, 100], [100, 200], [200, 200], [200, 100]]) country4 = country.Country([[200, 200], [300, 200], [300, 300], [200, 300]]) self.assertTrue(country1 in country2) self.assertEqual(country1, country12) g = country.Graph([country1, country2, country3, country4]) self.assertEqual( list(g.get_neighbours([country4, None]))[0][0], country3)
def __init__(self, data_file, continent_file): #construct class super().__init__(self) #call base class constructor data_file = open(data_file) #open file continent_file = open(continent_file) data_list = data_file.readlines() #read file and create list of countries continent_list = continent_file.readlines() country_data = [] country_continent = [] countryCat = {} cDictionary = {} for country_name in data_list[1:]: #split each country's data in list of countries and get rid of header country_list = country_name.strip().split('|') country_data.append(country_list) for country_name in continent_list[1:]: #split each (country, continent) in list of countries and get rid of header country_list = country_name.strip().split(',') country_continent.append(country_list) for country_name in country_continent: #fill Dictionary cDictionary[country_name[0]] = country_name[1] for country_name in country_data: #fill Catalogue country_object = country.Country(country_name) pop = country_object.setPopulation(int(country_name[1].replace(',', ''))) area = country_object.setArea(float(country_name[2].replace(',', ''))) continent = country_object.setContinent(cDictionary[country_name[0]]) countryCat[country_name[0]] = {'Population': country_object.getPopulation(), 'Area': country_object.getArea(), 'Continent': country_object.getContinent()} self.countryCat = countryCat self.cDictionary = cDictionary
def findMostPopulousContinent(self): #function to return the name and population of the continent with the most people living in it africa_list = [] asia_list = [] europe_list = [] north_america_list = [] south_america_list = [] for country_name in self.countryCat: #create list of country populations for each continent country_object = country.Country(country_name) if self.cDictionary[country_name] == 'Africa': pop = country_object.setPopulation(self.countryCat[country_name]['Population']) africa_list.append(country_object.getPopulation()) if self.cDictionary[country_name] == 'Asia': pop = country_object.setPopulation(self.countryCat[country_name]['Population']) asia_list.append(country_object.getPopulation()) if self.cDictionary[country_name] == 'Europe': pop = country_object.setPopulation(self.countryCat[country_name]['Population']) europe_list.append(country_object.getPopulation()) if self.cDictionary[country_name] == 'North America': pop = country_object.setPopulation(self.countryCat[country_name]['Population']) north_america_list.append(country_object.getPopulation()) if self.cDictionary[country_name] == 'South America': pop = country_object.setPopulation(self.countryCat[country_name]['Population']) south_america_list.append(country_object.getPopulation()) africa = ('Africa', sum(africa_list)) #sum country populations for each continent asia = ('Asia', sum(asia_list)) europe = ('Europe', sum(europe_list)) north_america = ('North America', sum(north_america_list)) south_america = ('South America', sum(south_america_list)) list = [africa, asia, europe, north_america, south_america] def getKey(item): return item[1] return max(list, key=getKey) #return continent with highest population
def printCountryCatalogue(self): #function to print catalogue for country_name in self.countryCat: country_object = country.Country(country_name) country_object.setPopulation(self.countryCat[country_name]['Population']) country_object.setArea(self.countryCat[country_name]['Area']) country_object.setContinent(self.countryCat[country_name]['Continent']) print(country_object) #print string representation for each country's objects
def getCountriesByContinent(self, continent): #function to return a list of countries in a continent list = [] for country_name in self.countryCat: if self.cDictionary[country_name] == continent: country_object = country.Country(country_name) list.append(country_object.getName()) return list
def __init__(self, redis, features={}): NPC.__init__(self, redis, features, 'npc') self.logger = logging.getLogger(__name__) self.generate_features('leader') #generates self.scope = "country" self.generate_features('leader' + self.scope) # generate self.kind from scope; scope.kind = absolutemonarchy self.generate_features('leader' + self.kind) # generate self.leader from leaderabsolutemonarchy_leader # generate leader.description from leaderabsolutemonarchy_leader_description if self.scope == 'country': self.location = country.Country(self.redis, {'leader': self}) elif self.scope == 'city': self.location = city.City(self.redis, {'leader': self}) elif self.scope == 'organization': self.location = organization.Organization(self.redis, {'leader': self}) else: self.location = organization.Organization(self.redis, {'leader': self}) self.scope = 'organization' self.name.title = self.leader_description[self.sex['name']] #re-render the name with the title. self.name.render()
def __getCountries(self): '''Find the countries and check that data are present ''' import os print 'Creating countries...' aptcnt = 0 apscnt = 0 navcnt = 0 countries = [] for entry in os.listdir(self.path): if os.path.isfile(os.path.join(self.path, entry)): split = entry.split('_') if split[1] == 'airports': aptcnt += 1 countries.append( ctr.Country(self.path, split[2], split[3][:-4])) elif split[1] == 'airspace': apscnt += 1 elif split[1] == 'navaid': navcnt += 1 else: raise RuntimeError('Unrecognized type of openAIP file: ' + entry + '!\n') if (aptcnt == apscnt and apscnt == navcnt): return countries else: raise RuntimeError( 'Some data files are missing, counted {0} airports, {1} airspaces, and {2} navaids files!\n' .format(aptcnt, apscnt, navcnt))
def getCountryStats(): allCountryData = getAPIdata(countryAPIParams)["countryitems"][0] if(allCountryData["stat"] == "ok"): # Why the hell is "stat" buried beneath "countryitems" ?!?!?! tmpCountryDict = {} for key in allCountryData: # See what I mean?!?! Now I have to manually exclude stat!!! if(key != "stat"): # Then to boot, the key is a useless arbitrary number tmpData = allCountryData[key] # Now we are at country-level cCode = tmpData["code"] cName = tmpData["title"] totCases = tmpData["total_cases"] totRec = tmpData["total_recovered"] totUnr = tmpData["total_unresolved"] totDeaths = tmpData["total_deaths"] ndCase = tmpData["total_new_cases_today"] ndDeath = tmpData["total_new_deaths_today"] totAct = tmpData["total_active_cases"] totSer = tmpData["total_serious_cases"] # print("Fetching timeline data for : " + cCode) tLine = getTimelineStats(cCode) # Pass the country code for timeline tmpCountry = country.Country(cCode, cName, totCases, totRec, totUnr, totDeaths, ndCase, ndDeath, totAct, totSer, tLine) tmpCountryDict[cName] = tmpCountry # Now the key is country name return tmpCountryDict else: return "API ERROR! " + allCountryData["stat"]
def __init__(self, N, R, width): ################################### # SET UP INFRASTRUCTURE ################################## self.running = True self.schedule = RandomActivation(self) self.grid = MultiGrid(width, width, True) self.positions = list(product([x for x in range(width)],repeat = 2)) ########################################## # SET UP AGENTS - Resources and Countries ######################################### for i in range(N): a = c.Country(i, self) self.schedule.add(a) pos = self.get_position() self.grid.place_agent(a, pos) self.area_owned = R for i in range(R): res = r.Resource(i, self, random.randint(1,6), "") pos = self.get_position() self.grid.place_agent(res,pos) ########################################## # SET UP DATA COLLECTOR ########################################### self.datacollector = DataCollector(agent_reporters = {"Scaling A": "scaling_a" ,\ "Scaling B" : "scaling_b", \ "Capacity": "capacity", \ "Land Owned": "land_owned", \ "Conquered": "conquered"})
def setPopulationOfCountry(self, country_name, pop): #function to set population if country_name in self.countryCat: country_object = country.Country(country_name) country_object.setPopulation(int(pop)) self.countryCat[country_name]['Population'] = country_object.getPopulation() return True else: #return false if country not in catalogue return False
def setAreaOfCountry(self, country_name, area): #function to set area if country_name in self.countryCat: country_object = country.Country(country_name) country_object.setArea(float(area)) self.countryCat[country_name]['Area'] = country_object.getArea() return True else: #return false if country not in catalogue return False
def findCountry(self, country_name): #function to look up country if country_name in self.countryCat: country_object = country.Country(country_name) country_object.setPopulation(self.countryCat[country_name]['Population']) country_object.setArea(self.countryCat[country_name]['Area']) country_object.setContinent(self.countryCat[country_name]['Continent']) return country_object #return the string representation of the country object else: #return null if country not in catalogue return None
def test_fight(self): self.c.add_area([(0, 0), (100, 0), (100, 100)]) friendly_creature = creature.Creature() self.c.area.add_resident(friendly_creature) non_enemy_country = country.Country() non_enemy_country.add_area([(0, 0), (100, 0), (100, -100)]) non_enemy_creature = creature.Creature() non_enemy_country.area.add_resident(non_enemy_creature) # Can't fight non-enemy countries self.assertIsNone(self.c.fight(non_enemy_country)) enemy_country = country.Country() enemy_country.add_area([(20, 50), (70, 30), (60, 100)]) enemy_creature = creature.Creature() enemy_creature.strength -= 2 enemy_country.area.add_resident(enemy_creature) self.assertEqual(self.c.fight(enemy_country), self.c) self.assertEqual(self.c.strength(), 2)
def getCountriesByArea(self, continent=''): #function to return a list of countries with its area in a continent def getKey(item): return item[1] list = [] if continent == '': #return list of all countries if continent name is empty string for country_name in self.countryCat: country_object = country.Country(country_name) area = country_object.setArea(self.countryCat[country_name]['Area']) list.append((country_object.getName(), country_object.getArea())) return sorted(list, reverse=True, key=getKey) elif continent in self.cDictionary.values(): for country_name in self.countryCat: if self.cDictionary[country_name] == continent: country_object = country.Country(country_name) area = country_object.setArea(self.countryCat[country_name]['Area']) list.append((country_object.getName(), country_object.getArea())) return sorted(list, reverse=True, key=getKey) else: #return blank list if continent does not exist and is not empty return list
def countries_init(screen_width, screen_height, border_width, number_of_stages): cntrs = [] info_file = open("countries.info") lines = info_file.readlines() width = int(lines[0].split(':')[0]) height = int(lines[0].split(':')[1]) for line in lines[1:]: split = line.split(':') name = split[0] population = int(split[1]) position = [ int((split[2].split(',')[0][1:])), int(split[2].split(',')[1][1:-1]) ] position[0] = int(position[0] / width * screen_width + border_width) position[1] = int(position[1] / height * screen_height + border_width) points = [] i = 1 point = [] for ch in split[3][1:-2].split(): if i > 0: point.append(int(ch[1:-1])) else: point.append(int(ch[:-2])) point[0] = int(point[0] / width * screen_width + border_width) point[1] = int(point[1] / height * screen_height + border_width) points.append(tuple(point)) point = [] i *= -1 cnt = country.Country(name) cnt.population = population cnt.set_position(tuple(position)) cnt.set_polygon(points) base = int(pow(population, 1.0 / number_of_stages)) stage = [] while population > 0: stage.append(population) population //= base stage.reverse() cnt.stage = stage cntrs.append(cnt) return cntrs
def get_country(line): """ Retorna un objeto del tipo País, tomando como parámetro una línea de datos. """ line = line.split(',') confederation = int(line[0]) name = line[1] points = int(line[2]) wins = int(line[3]) return country.Country(confederation, name, points, wins)
def filterCountriesByPopDensity(self, lower, upper): #function to return list of populationi densities within range list = [] for country_name in self.countryCat: #calculate pop density for each country country_object = country.Country(country_name) pop = country_object.setPopulation(self.countryCat[country_name]['Population']) area = country_object.setArea(self.countryCat[country_name]['Area']) pop_density = country_object.getPopDensity(pop, area) if lower < pop_density < upper: #create list of pop densities in range list.append((country_name, pop_density)) def getKey(item): return item[1] return sorted(list, reverse=True, key=getKey) #return sorted list
def addCountry(self, country_name, pop, area, continent): #function to add country to dictionary and catalogue if country_name in self.countryCat and self.cDictionary: #return false if country already in dictionary and catalogue return False else: if country_name not in self.countryCat: country_object = country.Country(country_name) country_object.setPopulation(int(pop)) country_object.setArea(float(area)) country_object.setContinent(continent) self.countryCat[country_name] = {'Population': country_object.getPopulation(), 'Area': country_object.getArea(), 'Continent': country_object.getContinent()} if country_name not in self.cDictionary: self.cDictionary[country_name] = continent return True
def saveCountryCatalogue(self, output_file): #fuction to save catalogue information to a file try: output_file = open(output_file, 'w') #open file to write output_file.write('Name|Continent|Population|Area|Population Density\n') for country_name in sorted(self.countryCat): #sort countries alphabetically and write information for each country to file country_object = country.Country(country_name) continent = country_object.setContinent(self.countryCat[country_name]['Continent']) pop = country_object.setPopulation(self.countryCat[country_name]['Population']) area = country_object.setArea(self.countryCat[country_name]['Area']) pop_density = country_object.getPopDensity(pop, area) output_file.write('%s|%s|%d|%.2f|%.2f\n' % (country_name, country_object.getContinent(), country_object.getPopulation(), country_object.getArea(), pop_density)) output_file.close() return len(self.countryCat) #return number of items written except: return -1 #return -1 if operation unsuccessful
def _parse_country(self, element, dictionary, parent): name = element.attributes.getNamedItem('name').nodeValue c = country.Country() c['name'] = name c['file'] = element.attributes.getNamedItem('file').nodeValue c['image'] = Theme.loadImage(c['file']) c['continent'] = parent['name'] c['offset'] = (int(element.attributes.getNamedItem('pos_x').nodeValue), int(element.attributes.getNamedItem('pos_y').nodeValue)) try: c['army_offset'] = ( int(element.attributes.getNamedItem('army_x').nodeValue), int(element.attributes.getNamedItem('army_y').nodeValue)) except AttributeError, e: c['army_offset'] = (0, 0)
def __init__(self, users=[ player1, player2, player3, player4, player5, player6, player7 ], nations=DipConts.Countries, locs=DipConts.Locations, supcents=DipConts.SupplyCenters, adjLocs=DipConts.AdjacentLocations): self.countries = [] for i in range(countries): self.countries.append( country.Country(nations[i]["Locations"], nations[i]["SupplyCenters"], nations[i]["Name"], users[i])) self.locs = locs self.supcents = supcents self.adjLocs = adjLocs
def load_country(): for i in range(len(name)): temp = c.Country() #basic info print("-" * 20) print("loading country:{}".format(name[i])) print("-" * 20) config = np.loadtxt('country/{}.txt'.format(name[i]), dtype=str) temp.name = re.search('name=(.*)', config[0]).group(1) temp.eco_type = int(re.search('type=(.*)', config[1]).group(1)) #pop initial print("loading population") temp.undereducated = int( re.search('undereducated=(.*)', config[2]).group(1)) temp.worker = int(re.search('worker=(.*)', config[3]).group(1)) temp.educated = int(re.search('educated=(.*)', config[4]).group(1)) temp.elite = int(re.search('elite=(.*)', config[5]).group(1)) #fact initial print("loading factories") temp.mine_coal = int(re.search('mine_coal=(.*)', config[6]).group(1)) temp.mine_oil = int(re.search('mine_oil=(.*)', config[7]).group(1)) temp.mine_material = int( re.search('mine_material=(.*)', config[8]).group(1)) temp.mine_U235 = int(re.search('mine_U235=(.*)', config[9]).group(1)) temp.farm = int(re.search('farm=(.*)', config[10]).group(1)) temp.factory = int(re.search('factory=(.*)', config[11]).group(1)) temp.high_tech = int(re.search('high_tech=(.*)', config[12]).group(1)) temp.bank = int(re.search('bank=(.*)', config[13]).group(1)) temp.power = int(re.search('power=(.*)', config[14]).group(1)) #national capital print("loading capital") temp.c_liquid = float(re.search('c_liquid=(.*)', config[15]).group(1)) temp.c_solid = float(re.search('c_solid=(.*)', config[16]).group(1)) temp.c_bank = float(re.search('c_bank=(.*)', config[17]).group(1)) #private capital temp.p_liquid = float(re.search('p_liquid=(.*)', config[18]).group(1)) temp.p_solid = float(re.search('p_solid=(.*)', config[19]).group(1)) temp.p_bank = float(re.search('p_bank=(.*)', config[20]).group(1)) #political power in this country print("loading political power") temp.undereducated_pp = int( re.search('undereducated_pp=(.*)', config[21]).group(1)) temp.worker_pp = int(re.search('worker_pp=(.*)', config[22]).group(1)) temp.educated_pp = int( re.search('educated_pp=(.*)', config[23]).group(1)) temp.elite_pp = int(re.search('elite_pp=(.*)', config[24]).group(1)) #stockpile print("loading stockpile") temp.food = float(re.search('food=(.*)', config[25]).group(1)) temp.material = float(re.search('material=(.*)', config[26]).group(1)) temp.industrial = float( re.search('industrial=(.*)', config[27]).group(1)) temp.high_tech = float( re.search('high_tech=(.*)', config[28]).group(1)) temp.oil = float(re.search('oil=(.*)', config[29]).group(1)) temp.energy = float(re.search('energy=(.*)', config[30]).group(1)) temp.coal = float(re.search('coal=(.*)', config[31]).group(1)) temp.U235 = float(re.search('U235=(.*)', config[32]).group(1)) temp.nuclear = float(re.search('nuclear=(.*)', config[33]).group(1)) #school print("loading school") temp.high_school = int( re.search('high_school=(.*)', config[34]).group(1)) temp.public_university = int( re.search('public_university=(.*)', config[35]).group(1)) temp.private_universty = int( re.search('private_university=(.*)', config[36]).group(1)) country.append(temp) print("-" * 20) print("loading complete") print("-" * 20)
def setUp(self): self.c = country.Country()
def test_is_larger_true(self): canada = country.Country("Canada", 36290000, 9985000) denmark = country.Country("Denmark", 5603000, 42933) actual = canada.is_larger(denmark) expected = True self.assertEqual(actual, expected)
def test_is_larger_same_population(self): canada = country.Country("Canada", 36290000, 9985000) denmark = country.Country("Denmark", 5603000, 9985000) actual = canada.is_larger(denmark) expected = False self.assertEqual(actual, expected)
def test_is_larger_false(self): canada = country.Country("Canada", 36290000, 9985000) denmark = country.Country("Denmark", 5603000, 42933) actual = denmark.is_larger(canada) expected = False self.assertEqual(actual, expected)