-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcommon_functions.py
More file actions
210 lines (186 loc) · 8.53 KB
/
Copy pathcommon_functions.py
File metadata and controls
210 lines (186 loc) · 8.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above
# copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
import re
import os
import defines
import pygame
import debug_functions
flags_dict = {}
tags_dict = {}
def return_ordinal_number(number: str) -> str:
# Converts a number to its ordinal form
ordinal_dict = {'1': "st", '2': "nd", '3': "rd"}
if number == "11" or number == "12" or number == "13":
return number + "th"
if number[-1] in ordinal_dict.keys():
return number + ordinal_dict[number[-1]]
return number + "th"
def break_up_large_numbers(number: str) -> str:
number = str(number)
# Adds a comma every three digits
new_text = ""
for i in range(len(number)):
new_text += number[i]
if (len(number) - (i + 1)) % 3 == 0 and i != len(number) - 1:
new_text += ","
return new_text
def is_created_nation(tag: str) -> bool:
# Returns True if the tag is dynamically generated (client state (K), colonial nation (C),
# trade city (T), federation (F), or custom nation (D)). False if it is anything else.
if re.fullmatch(r"([CDFKT])\d\d", tag) is not None:
return True
return False
def get_full_country_name(tag: str) -> str:
global tags_dict
# Takes a three-character tag and returns the full name
# Case-insensitive
# KER (Zia) has an incorrect number of spaces in its filename which is why I have to use .split('-')
name = None
try:
if len(tags_dict) == 0:
tags_countries_file = open(defines.PATH_TO_COUNTRIES_FILE, 'r')
tc_lines = tags_countries_file.readlines()
tags_countries_file.close()
for line in tc_lines:
if line[0] != '#' and line[0] != '\n':
try:
new_line = line.strip().split(" = ")[-1]
new_line = new_line.replace("\"", '')
new_line = new_line.split('/')[1]
new_line = new_line.split('.')[0]
tags_dict[line[:3]] = new_line
except:
continue
name = tags_dict[tag]
else:
if tag in tags_dict.keys():
name = tags_dict[tag]
if name is None: # Fallback
debug_functions.debug_out(
f"Unable to find full country name for tag {tag} in [{defines.PATH_TO_COUNTRIES_FILE}]. Using fallback source.",
event_type="WARN")
for files in os.walk(defines.PATH_TO_BACKUP_COUNTRIES_FOLDER):
for filename in files[-1]:
if filename[:3] == tag.upper():
name = filename[:-4].split('-')[1]
if name[0] == ' ':
return name[1:]
if name.lower() in defines.ALT_NAMES:
return defines.ALT_NAMES[name.lower()]
return name
else:
if name.lower() in defines.ALT_NAMES:
return defines.ALT_NAMES[name.lower()]
return name
except:
debug_functions.debug_out(f"Unable to find full country name at all for tag {tag}.", event_type="WARN")
return tag
return tag
def get_all_country_names(countries_folder=defines.PATH_TO_COUNTRIES_FILE[:-16]) -> list:
all_countries = []
for file in os.listdir(countries_folder):
if os.path.isfile(countries_folder + file):
try:
tags_countries_file = open(countries_folder + file, 'r')
debug_functions.debug_out(countries_folder + file)
tc_lines = tags_countries_file.readlines()
tags_countries_file.close()
for line in tc_lines:
if line[0] != '#' and line[0] != '\n':
try:
new_line = line.strip().split(" = ")[-1]
new_line = new_line.replace("\"", '')
new_line = new_line.split('/')[1]
new_line = new_line.split('.')[0]
if new_line.lower() in defines.ALT_NAMES:
new_line = defines.ALT_NAMES[new_line.lower()]
all_countries.append((line[:3], new_line))
except:
pass
except:
continue
if len(all_countries) == 0: # Fallback
debug_functions.debug_out(
f"Unable to compile countries names dict from [{countries_folder}]. Using fallback source.",
event_type="WARN")
for files in os.walk(defines.PATH_TO_BACKUP_COUNTRIES_FOLDER):
for filename in files[-1]:
if filename[:3] == filename[
:3].upper(): # Only filenames starting with three uppercase letters (or numbers)
tag = filename[:3]
name = filename[:-4].split('-')[1]
if name[0] == ' ':
name = name[1:]
if name.lower() in defines.ALT_NAMES:
name = defines.ALT_NAMES[name.lower()]
all_countries.append((tag, name))
return all_countries
def date_conversion(date: str) -> str:
# Takes a normally-formatted date string and turns it into
# DD Month YYYY
if date == "annexed" or date == "unknown":
return date
month_list = ["January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"]
date = date.split('.')
year = date[0]
month = month_list[int(date[1]) - 1]
day = date[2]
return day + " " + month + " " + year
def lookup_outcome(code) -> str:
# Returns a description of the war's outcome when given the outcome code
# OUTCOMES:
# 1 - draw
# 2 - victory for attackers
# 3 - victory for defenders
if code is not None:
outcome_list = ["White Peace", "Attacker Won", "Defender Won"]
return outcome_list[int(code) - 1]
return "Outcome Unknown"
def date_to_days(date: str) -> int:
if type(date) == type(None):
return 0
elif date == "annexed" or date == "unknown":
return 0
# Takes in a date (string) formatted like XXXX.XX.XX and converts it to an integer representing the number of
# days since January 1, AD 1
try:
months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30] # January-November, don't need to add December because it's the last month
date = date.split('.')
year, month, day = int(date[0]), int(date[1]), int(date[2])
return (year - 1) * 365 + sum(months[:month]) + day - 1
except:
return 0
def load_flag(tag: str, war):
global flags_dict
flag_tag = None
if tag in flags_dict.keys():
flag = pygame.image.load(flags_dict[tag])
else:
flag_tag = war.participants[tag].flag_tag
if flag_tag is not None and flag_tag in flags_dict.keys():
flag = pygame.image.load(flags_dict[flag_tag])
else:
try:
flag = pygame.image.load(war.participants[tag].flag_path)
except:
if is_created_nation(tag):
flag = pygame.image.load(defines.PATH_TO_BACKUP_FLAG)
pygame.draw.rect(flag, war.participants[tag].country_color, (0, 0, flag.get_width(), flag.get_height()))
else:
flag = pygame.image.load(defines.PATH_TO_BACKUP_FLAG)
debug_functions.debug_out(f"Failed to open flag for tag {tag}", event_type="WARN")
if flag_tag is not None:
colors = war.participants[tag].country_color
pygame.draw.rect(flag, colors, (int(flag.get_width() / 2), 0, int(flag.get_width() / 2), flag.get_height()))
return flag
def load_modded_flags(mod_folder) -> None:
global flags_dict
flag_directory = f"{mod_folder}/gfx/flags"
for files in os.walk(flag_directory):
for filename in files[-1]:
flags_dict[filename[:3]] = flag_directory + f"/{filename}"