Python 3 everywhere, PEP8 (#42559)

* Ported Python scripts with 2to3, appeased PEP8

* Removed unused function, UTF-8 is default in Python 3

* Removing more Python 2 specific syntax

* Fixing docs

* Replacing python executable with python3
This commit is contained in:
Serhiy Zahoriya
2020-08-03 10:21:11 +03:00
committed by GitHub
parent c9ba17182c
commit 5cc59e134e
34 changed files with 411 additions and 374 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import biplist
import os.path
+5 -3
View File
@@ -10,16 +10,18 @@ with open(blacklist_filename) as blacklist_file:
mods_to_keep = []
def add_mods(mods):
for mod in mods:
if not mod in all_mod_dependencies:
if mod not in all_mod_dependencies:
# Either an invalid mod id, or blacklisted.
return False
for mod in mods:
if not mod in mods_to_keep:
if mod not in mods_to_keep:
mods_to_keep.append(mod)
return True
all_mod_dependencies = {}
for info in glob.glob('data/mods/*/modinfo.json'):
@@ -31,7 +33,7 @@ for info in glob.glob('data/mods/*/modinfo.json'):
all_mod_dependencies[ident] = e.get("dependencies", [])
for mod in all_mod_dependencies:
if not mod in mods_to_keep:
if mod not in mods_to_keep:
if add_mods(all_mod_dependencies[mod]):
mods_to_keep.append(mod)
+1 -1
View File
@@ -1 +1 @@
find . -name "*json" -type f -exec python -m json.tool {} >/dev/null \;
find . -name "*json" -type f -exec python3 -m json.tool {} >/dev/null \;
+1 -1
View File
@@ -538,7 +538,7 @@ Pass the ``--help`` flag to list options.
### dmg distribution
You can build a nice dmg distribution file with the `dmgdist` target. You will need a tool called [dmgbuild](https://pypi.python.org/pypi/dmgbuild). To install this tool, you will need Python first. If you are on Mac OS X >= 10.8, Python 2.7 is pre-installed with the OS. If you are on an older version of OS X, you can download Python [on their official website](https://www.python.org/downloads/) or install it with homebrew `brew install python`. Once you have Python, you should be able to install `dmgbuild` by running:
You can build a nice dmg distribution file with the `dmgdist` target. You will need a tool called [dmgbuild](https://pypi.python.org/pypi/dmgbuild). To install this tool, you may need to install Python first. You can download Python [on their official website](https://www.python.org/downloads/) or install it with homebrew `brew install python`. Once you have Python, you should be able to install `dmgbuild` by running:
# This install pip. It might not be required if it is already installed.
curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | sudo python
+4 -5
View File
@@ -141,8 +141,8 @@ lit -v build/tools/clang-tidy-plugin/test
To build llvm on Windows, you'll first need to get some tools installed.
- Cmake
- Python 3 (Python 2 may not work for building llvm, but it's still required to run
the lit test, which will be discussed in the next section.)
- Python 3 (Python 2 may be still required to run the lit test,
which will be discussed in the next section.)
- MinGW-w64 (other compilers may or may not work. Clang itself does not seem to be
building llvm on Windows correctly.)
- A shell environment
@@ -202,8 +202,7 @@ After building clang-tidy as a library from the llvm source, the next step is to
build clang-tidy as an executable, with the custom checks from the CDDA source.
In this step, the following tools are required.
- Python 2 (used to run the lit test for the custom checks)
- Python 3 (used to run other python scripts)
- Python 3 (Python 2 may still be required to run the lit test for the custom checks)
- CMake
- MinGW-w64
- FileCheck (built from the llvm source)
@@ -272,7 +271,7 @@ index 4ab6e913a7..d1a4418ba6 100644
The next step is to run CMake to generate the compilation database. The compilation
database contains compiler flags that clang-tidy uses to check the source files.
Make sure Python 2, Python 3, CMake, MinGW-w64, and FileCheck are on the path.
Make sure Python 3 (and Python 2 if it's still required), CMake, MinGW-w64, and FileCheck are on the path.
Note that two `bin` directories of MinGW-w64 should be on the path: `<mingw-w64-root>/bin`,
and `<mingw-w64-root>/x86_64-w64-mingw32/bin`. FileCheck's path is `<llvm-source-root>/build/bin`,
if you built it with the instructions in the previous section. Python 2 should
+1 -1
View File
@@ -19,7 +19,7 @@ defined, and all defined topics are referenced in a response or an NPC's chat, i
There is a python script in `tools/dialogue_validator.py` that will map all topics to responses
and vice versa. Invoke it with
```sh
python tools/dialogue_validator.py data/json/npcs/* data/json/npcs/Backgrounds/* data/json/npcs/refugee_center/*
python3 tools/dialogue_validator.py data/json/npcs/* data/json/npcs/Backgrounds/* data/json/npcs/refugee_center/*
```
If you are writing a mod with dialogue, you can add the paths to the mod's dialogue files.
+1 -1
View File
@@ -12,7 +12,7 @@ This is a Python script that will convert a legacy tileset into a compositing ti
It requires pyvips to do the image processing.
It takes a single mandatory argument, which is the path to the tileset directory. For example:
`python tools/gfx_tools/decompose.py gfx/ChestHole16Tileset` will convert the legacy ChestHole16 tileset to a compositing tileset.
`python3 tools/gfx_tools/decompose.py gfx/ChestHole16Tileset` will convert the legacy ChestHole16 tileset to a compositing tileset.
decompose.py creates a sufficient directory hierarchy and file names for a tileset to be compositing, but it is machine generated and badly organized. New compositing tilesets should use more sensible file names and a better organization.
+1 -1
View File
@@ -18,7 +18,7 @@ MESSAGE("\n")
add_custom_target (
extract_string
COMMAND python lang/extract_json_strings.py
COMMAND python3 lang/extract_json_strings.py
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
+95 -52
View File
@@ -15,6 +15,7 @@ parser = OptionParser()
parser.add_option("-v", "--verbose", dest="verbose", help="be verbose")
(options, args) = parser.parse_args()
# Exceptions
class WrongJSONItem(Exception):
def __init__(self, msg, item):
@@ -24,6 +25,7 @@ class WrongJSONItem(Exception):
def __str__(self):
return ("---\nJSON error\n{0}\n--- JSON Item:\n{1}\n---".format(self.msg, self.item))
# there may be some non-json files in data/raw
not_json = {os.path.normpath(i) for i in {
"sokoban.txt",
@@ -47,12 +49,14 @@ warning_suppressed_list = {os.path.normpath(i) for i in {
"data/mods/Tanks/monsters.json"
}}
def warning_supressed(filename):
for i in warning_suppressed_list:
if filename.startswith(i):
return True
return False
# these files will not be parsed. Full related path.
ignore_files = {os.path.normpath(i) for i in {
"data/json/anatomy.json",
@@ -205,6 +209,7 @@ use_format_strings = {
# For handling grammatical gender
all_genders = ["f", "m", "n"]
def gender_options(subject):
return [subject + ":" + g for g in all_genders]
@@ -221,6 +226,7 @@ def extract_achievement(a):
if "description" in req:
writestr(outfile, req["description"])
def extract_bodypart(item):
outfile = get_outfile("bodypart")
# See comments in `body_part_struct::load` of bodypart.cpp about why xxx and xxx_multiple are not inside a single translation object.
@@ -236,22 +242,26 @@ def extract_bodypart(item):
if "hp_bar_ui_text" in item:
writestr(outfile, item["hp_bar_ui_text"])
def extract_clothing_mod(item):
outfile = get_outfile("clothing_mod")
writestr(outfile, item["implement_prompt"])
writestr(outfile, item["destroy_prompt"])
def extract_construction(item):
outfile = get_outfile("construction")
writestr(outfile, item["description"])
if "pre_note" in item:
writestr(outfile, item["pre_note"])
def extract_harvest(item):
outfile = get_outfile("harvest")
if "message" in item:
writestr(outfile, item["message"])
def extract_material(item):
outfile = get_outfile("material")
writestr(outfile, item["name"])
@@ -268,9 +278,10 @@ def extract_material(item):
writestr(outfile, item["dmg_adj"][2])
writestr(outfile, item["dmg_adj"][3])
wrote = True
if not wrote and not "copy-from" in item :
if not wrote and "copy-from" not in item:
print("WARNING: {}: no mandatory field in item: {}".format("/data/json/materials.json", item))
def extract_martial_art(item):
outfile = get_outfile("martial_art")
if "name" in item:
@@ -300,11 +311,12 @@ def extract_martial_art(item):
for buff in buffs:
writestr(outfile, buff["name"])
if buff["name"] == item["name"]:
c="Description of buff for martial art '{}'".format(name)
c = "Description of buff for martial art '{}'".format(name)
else:
c="Description of buff '{}' for martial art '{}'".format(buff["name"], name)
c = "Description of buff '{}' for martial art '{}'".format(buff["name"], name)
writestr(outfile, buff["description"], comment=c)
def extract_move_mode(item):
outfile = get_outfile("move_modes")
# Move mode name
@@ -326,18 +338,19 @@ def extract_move_mode(item):
change_good_mech = item["change_good_mech"]
writestr(outfile, change_good_mech, comment="Successfully switch to this move mode, mech steed")
if "change_bad_none" in item:
# Failed change message
# Failed change message
change_bad_none = item["change_bad_none"]
writestr(outfile, change_bad_none, comment="Failure to switch to this move mode, no steed")
if "change_bad_animal" in item:
# Failed change message (animal steed)
# Failed change message (animal steed)
change_bad_animal = item["change_bad_animal"]
writestr(outfile, change_bad_animal, comment="Failure to switch to this move mode, animal steed")
if "change_bad_mech" in item:
# Failed change message (mech steed)
# Failed change message (mech steed)
change_bad_mech = item["change_bad_mech"]
writestr(outfile, change_bad_mech, comment="Failure to switch to this move mode, mech steed")
def extract_effect_type(item):
# writestr will not write string if it is None.
outfile = get_outfile("effects")
@@ -415,10 +428,12 @@ def extract_effect_type(item):
writestr(outfile, msg, context="memorial_male")
writestr(outfile, msg, context="memorial_female")
else:
writestr(outfile, msg, context="memorial_male",
comment="Male memorial remove log for effect(s) '{}'.".format(', '.join(name)))
writestr(outfile, msg, context="memorial_female",
comment="Female memorial remove log for effect(s) '{}'.".format(', '.join(name)))
writestr(
outfile, msg, context="memorial_male",
comment="Male memorial remove log for effect(s) '{}'.".format(', '.join(name)))
writestr(
outfile, msg, context="memorial_female",
comment="Female memorial remove log for effect(s) '{}'.".format(', '.join(name)))
def extract_gun(item):
@@ -491,6 +506,7 @@ def extract_professions(item):
writestr(outfile, item["description"], context="prof_desc_female",
comment="Profession (female {}) description".format(nm))
def extract_scenarios(item):
outfile = get_outfile("scenario")
# writestr will not write string if it is None.
@@ -525,6 +541,7 @@ def extract_scenarios(item):
found = item.get(f, None)
writestr(outfile, found)
def extract_mapgen(item):
outfile = get_outfile("mapgen")
# writestr will not write string if it is None.
@@ -549,6 +566,7 @@ def extract_mapgen(item):
writestr(outfile, v.get("access_denied"),
comment="Computer access denied warning")
def extract_monster_attack(item):
outfile = get_outfile("monster_attack")
if "hit_dmg_u" in item:
@@ -579,6 +597,7 @@ def extract_recipe_group(item):
for i in item.get("recipes"):
writestr(outfile, i.get("description"))
def extract_gendered_dynamic_line_optional(line, outfile):
if "gendered_line" in line:
msg = line["gendered_line"]
@@ -588,12 +607,14 @@ def extract_gendered_dynamic_line_optional(line, outfile):
context = " ".join(context_list)
writestr(outfile, msg, context=context)
def extract_dynamic_line_optional(line, member, outfile):
if member in line:
extract_dynamic_line(line[member], outfile)
dynamic_line_string_keys = [
# from `simple_string_conds` in `condition.h`
# from `simple_string_conds` in `condition.h`
"u_male", "u_female", "npc_male", "npc_female",
"has_no_assigned_mission", "has_assigned_mission", "has_many_assigned_missions",
"has_no_available_mission", "has_available_mission", "has_many_available_missions",
@@ -604,10 +625,11 @@ dynamic_line_string_keys = [
"u_can_stow_weapon", "npc_can_stow_weapon", "u_has_weapon", "npc_has_weapon",
"u_driving", "npc_driving",
"has_pickup_list", "is_by_radio", "has_reason",
# yes/no strings for complex conditions, 'and' list
# yes/no strings for complex conditions, 'and' list
"yes", "no", "and"
]
def extract_dynamic_line(line, outfile):
if type(line) == list:
for l in line:
@@ -619,6 +641,7 @@ def extract_dynamic_line(line, outfile):
elif type(line) == str:
writestr(outfile, line)
def extract_talk_effects(effects, outfile):
if type(effects) != list:
effects = [effects]
@@ -627,6 +650,7 @@ def extract_talk_effects(effects, outfile):
if "u_buy_monster" in eff and "name" in eff:
writestr(outfile, eff["name"], comment="Nickname for creature '{}'".format(eff["u_buy_monster"]))
def extract_talk_response(response, outfile):
if "text" in response:
writestr(outfile, response["text"])
@@ -647,6 +671,7 @@ def extract_talk_response(response, outfile):
if "effect" in response:
extract_talk_effects(response["effect"], outfile)
def extract_talk_topic(item):
outfile = get_outfile("talk_topic")
if "dynamic_line" in item:
@@ -657,12 +682,14 @@ def extract_talk_topic(item):
if "effect" in item:
extract_talk_effects(item["effect"], outfile)
def extract_trap(item):
outfile = get_outfile("trap")
writestr(outfile, item["name"])
if "vehicle_data" in item and "sound" in item["vehicle_data"]:
writestr(outfile, item["vehicle_data"]["sound"], comment="Trap-vehicle collision message for trap '{}'".format(item["name"]))
def extract_missiondef(item):
outfile = get_outfile("mission_def")
item_name = item.get("name")
@@ -698,6 +725,7 @@ def extract_missiondef(item):
if "fail" in item and "effect" in item["fail"]:
extract_talk_effects(item["fail"]["effect"], outfile)
def extract_mutation(item):
outfile = get_outfile("mutation")
@@ -710,7 +738,7 @@ def extract_mutation(item):
else:
writestr(outfile, found)
simple_fields = [ "description" ]
simple_fields = ["description"]
for f in simple_fields:
found = item.get(f)
@@ -735,6 +763,7 @@ def extract_mutation(item):
if "spawn_item" in item:
writestr(outfile, item.get("spawn_item").get("message"))
def extract_mutation_category(item):
outfile = get_outfile("mutation_category")
@@ -743,12 +772,12 @@ def extract_mutation_category(item):
raise WrongJSONItem("JSON item don't contain 'name' field", item)
writestr(outfile, found, comment="Mutation class name")
simple_fields = [ "mutagen_message",
"iv_message",
"iv_sleep_message",
"iv_sound_message",
"junkie_message"
]
simple_fields = ["mutagen_message",
"iv_message",
"iv_sleep_message",
"iv_sound_message",
"junkie_message"
]
for f in simple_fields:
found = item.get(f)
@@ -773,6 +802,7 @@ def extract_vehspawn(item):
for st in found:
writestr(outfile, st.get("description"), comment="Vehicle Spawn Description")
def extract_recipe_category(item):
outfile = get_outfile("recipe_category")
@@ -794,6 +824,7 @@ def extract_recipe_category(item):
writestr(outfile, subcat_name,
comment="Crafting recipes subcategory of '{}' category".format(cat_name))
def extract_gate(item):
outfile = get_outfile("gates")
messages = item.get("messages", {})
@@ -802,22 +833,26 @@ def extract_gate(item):
writestr(outfile, v,
comment="'{}' action message of some gate object.".format(k))
def extract_field_type(item):
outfile = get_outfile("field_type")
for fd in item.get("intensity_levels"):
if "name" in fd:
writestr(outfile,fd.get("name"))
if "name" in fd:
writestr(outfile, fd.get("name"))
def extract_ter_furn_transform_messages(item):
outfile = get_outfile("ter_furn_transform_messages")
writestr(outfile,item.get("fail_message"))
for terrain in item.get("terrain"):
writestr(outfile,terrain.get("message"))
outfile = get_outfile("ter_furn_transform_messages")
writestr(outfile, item.get("fail_message"))
for terrain in item.get("terrain"):
writestr(outfile, terrain.get("message"))
def extract_skill_display_type(item):
outfile = get_outfile("skill_display_type")
writestr(outfile, item["display_string"], comment="display string for skill display type '{}'".format(item["id"]))
def extract_fault(item):
outfile = get_outfile("fault")
writestr(outfile, item["name"])
@@ -830,17 +865,19 @@ def extract_fault(item):
if "success_msg" in method:
writestr(outfile, method["success_msg"], format_strings=True, comment="success message for mending method '{}' of fault '{}'".format(method["name"], item["name"]))
def extract_snippets(item):
outfile = get_outfile("snippet")
text = item["text"];
text = item["text"]
if type(text) is not list:
text = [text];
text = [text]
for snip in text:
if type(snip) is str:
writestr(outfile, snip)
else:
writestr(outfile, snip["text"])
# these objects need to have their strings specially extracted
extract_specials = {
"achievement": extract_achievement,
@@ -903,7 +940,8 @@ if not os.path.exists(to_dir):
# clean any old extracted strings, it will all be redone
for filename in os.listdir(to_dir):
if not filename.endswith(".py"): continue
if not filename.endswith(".py"):
continue
f = os.path.join(to_dir, filename)
os.remove(f)
@@ -917,6 +955,7 @@ def tlcomment(fs, string):
for line in string.splitlines():
fs.write("#~ {}\n".format(line))
def gettextify(string, context=None, plural=None):
"Put the string in a fake gettext call, and add a newline."
if context:
@@ -930,6 +969,7 @@ def gettextify(string, context=None, plural=None):
else:
return "_(%r)\n" % string
def writestr(filename, string, context=None, format_strings=False, comment=None, pl_fmt=False):
"Wrap the string and write to the file."
if type(string) is list:
@@ -942,7 +982,7 @@ def writestr(filename, string, context=None, format_strings=False, comment=None,
comment = string["//~"]
else:
comment = "{}\n{}".format(comment, string["//~"])
context = string.get( "ctxt" )
context = string.get("ctxt")
str_pl = None
if pl_fmt:
if "str_pl" in string:
@@ -971,7 +1011,7 @@ def writestr(filename, string, context=None, format_strings=False, comment=None,
else:
str_pl = None
elif string is None:
return;
return
else:
raise WrongJSONItem("ERROR: value is not a string, dict, list, or None", string)
@@ -983,11 +1023,13 @@ def writestr(filename, string, context=None, format_strings=False, comment=None,
# we must tell xgettext this explicitly
if not format_strings and ("%" in str_singular or (str_pl is not None and "%" in str_pl)):
fs.write("# xgettext:no-python-format\n")
fs.write(gettextify(str_singular,context=context,plural=str_pl))
fs.write(gettextify(str_singular, context=context, plural=str_pl))
def get_outfile(json_object_type):
return os.path.join(to_dir, json_object_type + "_from_json.py")
use_action_msgs = {
"activate_msg",
"deactive_msg",
@@ -1023,13 +1065,15 @@ use_action_msgs = {
"gerund"
}
def extract_use_action_msgs(outfile, use_action, it_name, kwargs):
"""Extract messages for iuse_actor objects. """
for f in sorted(use_action_msgs):
if type(use_action) is dict and f in use_action:
if it_name:
writestr(outfile, use_action[f],
comment="Use action {} for {}.".format(f, it_name), **kwargs)
writestr(
outfile, use_action[f],
comment="Use action {} for {}.".format(f, it_name), **kwargs)
# Recursively check sub objects as they may contain more messages.
if type(use_action) is list:
for i in use_action:
@@ -1038,14 +1082,16 @@ def extract_use_action_msgs(outfile, use_action, it_name, kwargs):
for (k, v) in sorted(use_action.items(), key=lambda x: x[0]):
extract_use_action_msgs(outfile, v, it_name, kwargs)
found_types = set();
found_types = set()
known_types = ignorable | use_format_strings | extract_specials.keys() | automatically_convertible
# extract commonly translatable data from json to fake-python
def extract(item, infilename):
"""Find any extractable strings in the given json object,
and write them to the appropriate file."""
if not "type" in item:
if "type" not in item:
return
object_type = item["type"]
found_types.add(object_type)
@@ -1063,7 +1109,7 @@ def extract(item, infilename):
if object_type not in known_types:
print("WARNING: known_types does not contain object type '{}'".format(object_type))
wrote = False
name = item.get("name") # Used in gettext comments below.
name = item.get("name") # Used in gettext comments below.
# Don't extract any record with name = "none".
if name and name == "none":
return
@@ -1140,7 +1186,7 @@ def extract(item, infilename):
wrote = True
if "message" in item:
writestr(outfile, item["message"], format_strings=True,
comment="Message for {} '{}'".format(object_type, name), **kwargs )
comment="Message for {} '{}'".format(object_type, name), **kwargs)
wrote = True
if "messages" in item:
for message in item["messages"]:
@@ -1151,12 +1197,12 @@ def extract(item, infilename):
writestr(outfile, mod_loc[0], **kwargs)
wrote = True
if "info" in item:
c = "Please leave anything in <angle brackets> unchanged."
writestr(outfile, item["info"], comment=c, **kwargs)
wrote = True
c = "Please leave anything in <angle brackets> unchanged."
writestr(outfile, item["info"], comment=c, **kwargs)
wrote = True
if "verb" in item:
writestr(outfile, item["verb"], **kwargs)
wrote = True
writestr(outfile, item["verb"], **kwargs)
wrote = True
if "special_attacks" in item:
special_attacks = item["special_attacks"]
for special_attack in special_attacks:
@@ -1169,17 +1215,12 @@ def extract(item, infilename):
.format(name, special_attack.get("spell_id")), **kwargs)
wrote = True
if "footsteps" in item:
writestr(outfile, item["footsteps"], **kwargs)
wrote = True
if not wrote and not "copy-from" in item:
writestr(outfile, item["footsteps"], **kwargs)
wrote = True
if not wrote and "copy-from" not in item:
if not warning_supressed(infilename):
print("WARNING: {}: nothing translatable found in item: {}".format(infilename, item))
def is_official_mod(full_path):
for i in official_mods:
if full_path.find(i) != -1:
return True
return False
def extract_all_from_dir(json_dir):
"""Extract strings from every json file in the specified directory,
@@ -1187,7 +1228,7 @@ def extract_all_from_dir(json_dir):
allfiles = os.listdir(json_dir)
allfiles.sort()
dirs = []
skiplist = [ os.path.normpath(".gitkeep") ]
skiplist = [os.path.normpath(".gitkeep")]
for f in allfiles:
full_name = os.path.join(json_dir, f)
if os.path.isdir(full_name):
@@ -1208,6 +1249,7 @@ def extract_all_from_dir(json_dir):
for d in dirs:
extract_all_from_dir(os.path.join(json_dir, d))
def extract_all_from_file(json_file):
"Extract translatable strings from every object in the specified file."
if options.verbose:
@@ -1227,9 +1269,10 @@ def extract_all_from_file(json_file):
print(E)
exit(1)
def prepare_git_file_list():
command_str = "git ls-files"
res = None;
res = None
if platform == "win32":
res = subprocess.Popen(command_str, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
+9 -4
View File
@@ -8,6 +8,7 @@ import os
usage = "USAGE: strip_line_numbers.py <filename> [<filename> ...]"
def strip_pot_file(filename):
# Check pot file
if not os.path.isfile(filename):
@@ -18,7 +19,7 @@ def strip_pot_file(filename):
except IOError as read_exc:
print(read_exc)
sys.exit(1)
assert(len(to_write) > 1) # Wrong .pot file
assert(len(to_write) > 1) # Wrong .pot file
to_write = strip_line_numbers(to_write)
to_write = strip_repeated_comments(to_write)
@@ -30,13 +31,14 @@ def strip_pot_file(filename):
print(write_exc)
sys.exit(1)
def strip_repeated_comments(lines):
to_remove = []
ln_length = len(lines)
for i in range(ln_length):
line = lines[i]
if i < (ln_length - 1):
next_line = lines[i+1]
next_line = lines[i + 1]
else:
next_line = None
# only act on line-comments
@@ -52,6 +54,7 @@ def strip_repeated_comments(lines):
return lines
def strip_line_numbers(lines):
"Strip line numbers from the specified list of strings."
@@ -59,7 +62,8 @@ def strip_line_numbers(lines):
for i in range(len(lines)):
line = lines[i]
# only act on line-comments
if not line.startswith("#:"): continue
if not line.startswith("#:"):
continue
# line comments are of the format: "#: <file>:<line> <file>:<line>"
items = line.split()
newitems = ["#:"]
@@ -67,7 +71,7 @@ def strip_line_numbers(lines):
# and checking for duplicates
for item in items[1:]:
newname = item.split(':')[0]
if not newname in newitems:
if newname not in newitems:
newitems.append(newname)
# replace the old line with the new
newline = ' '.join(newitems) + '\n'
@@ -75,6 +79,7 @@ def strip_line_numbers(lines):
return lines
if __name__ == "__main__":
# get filename(s) from sys.argv and strip
if len(sys.argv) < 2:
+3
View File
@@ -2,6 +2,7 @@
from __future__ import print_function
import sys
def print_encode_error(unicode_err, counter):
chunk = unicode_err.object
err_line = counter + chunk.count(b'\n', 0, unicode_err.start)
@@ -14,6 +15,7 @@ def print_encode_error(unicode_err, counter):
x_start = unicode_err.start - line_start + 2
print("{0:>{1}}".format("^" * x_num, x_start))
def check(f):
count = 1
try:
@@ -28,6 +30,7 @@ def check(f):
return True
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Usage: {} [FILENAME]".format(sys.argv[0]))
+18 -17
View File
@@ -5,23 +5,24 @@ import argparse
IGNORE_MISMATCH = ["id", "abstract"]
def get_data(argsDict, resource_name):
resource = []
resource_sources = argsDict.get(resource_name, [])
if not isinstance(resource_sources, list):
resource_sources = [resource_sources]
for resource_filename in resource_sources:
if resource_filename.endswith(".json"):
try:
with open(resource_filename) as resource_file:
resource += json.load(resource_file)
except FileNotFoundError:
exit("Failed: could not find {}".format(resource_filename))
else:
print("Invalid filename {}".format(resource_filename))
if not resource:
resource = []
resource_sources = argsDict.get(resource_name, [])
if not isinstance(resource_sources, list):
resource_sources = [resource_sources]
for resource_filename in resource_sources:
if resource_filename.endswith(".json"):
try:
with open(resource_filename) as resource_file:
resource += json.load(resource_file)
except FileNotFoundError:
exit("Failed: could not find {}".format(resource_filename))
else:
print(("Invalid filename {}".format(resource_filename)))
if not resource:
exit("Failed: {} was empty".format(resource_filename))
return resource
return resource
args = argparse.ArgumentParser(description="Make items use copy-from.")
@@ -45,9 +46,9 @@ for item in items:
del_keys = []
for key in item:
if key == "type":
continue
continue
if item[key] == base_item.get(key):
del_keys.append(key)
del_keys.append(key)
can_copy = True
for key in base_item:
if key in del_keys:
+22 -20
View File
@@ -22,6 +22,7 @@ args.add_argument("dialogue_json", nargs="+", action="store",
"to validate the dialogue in the vanilla game.")
argsDict = vars(args.parse_args())
def get_dialogue_from_json():
dialogue = []
@@ -29,14 +30,14 @@ def get_dialogue_from_json():
if arg_path.endswith("/"):
arg_path = arg_path[:-1]
for subdir_path, dirnames, filenames in os.walk(arg_path):
for filename in filenames:
path = subdir_path + "/" + filename
if path == "data/json/npcs/TALK_TEST.json":
continue
if path.endswith(".json"):
with open(path) as dialogue_file:
dialogue += json.load(dialogue_file)
for filename in filenames:
path = subdir_path + "/" + filename
if path == "data/json/npcs/TALK_TEST.json":
continue
if path.endswith(".json"):
with open(path) as dialogue_file:
dialogue += json.load(dialogue_file)
return dialogue
@@ -88,7 +89,7 @@ def parse_response(topics, response, topic_branches=None, this_ids=None):
failure_r = response.get("failure", {})
add_topic_by_response(topics, failure_r, topic_branches, this_ids)
def validate(dialogue):
topics = {}
topic_branches = {
@@ -97,25 +98,25 @@ def validate(dialogue):
"TALK_SEDATED": {"responses": ["TALK_DONE"], "ends": True, "parent": None},
}
# defined in src/npctalk.cpp
defined_ids = [ "TALK_NONE", "TALK_DONE", "TALK_TRAIN", "TALK_HOW_MUCH_FURTHER",
"TALK_SEDATED" ]
defined_ids = ["TALK_NONE", "TALK_DONE", "TALK_TRAIN", "TALK_HOW_MUCH_FURTHER",
"TALK_SEDATED"]
for topic_id in defined_ids:
add_topic_by_id(topics, topic_id)
# referenced in src/npctalk.cpp
refered_ids = [ "TALK_WAKE_UP", "TALK_RADIO", "TALK_MISSION_DESCRIBE_URGENT",
"TALK_MISSION_DESCRIBE", "TALK_SHELTER", "TALK_SIZE_UP", "TALK_LOOK_AT",
"TALK_OPINION", "TALK_SHOUT", "TALK_STRANGER_AGGRESSIVE", "TALK_LEADER",
"TALK_TRAIN_START", "TALK_STOLE_ITEM", "TALK_SEDATED" ]
refered_ids = ["TALK_WAKE_UP", "TALK_RADIO", "TALK_MISSION_DESCRIBE_URGENT",
"TALK_MISSION_DESCRIBE", "TALK_SHELTER", "TALK_SIZE_UP", "TALK_LOOK_AT",
"TALK_OPINION", "TALK_SHOUT", "TALK_STRANGER_AGGRESSIVE", "TALK_LEADER",
"TALK_TRAIN_START", "TALK_STOLE_ITEM", "TALK_SEDATED"]
for topic_id in refered_ids:
add_topic_by_chat(topics, topic_id)
# TALK_TRAIN_START is technically not a start id
start_topics = [ "TALK_RADIO", "TALK_LEADER", "TALK_FRIEND", "TALK_STOLE_ITEM",
"TALK_MISSION_DESCRIBE_URGENT", "TALK_SEDATED", "TALK_WAKE_UP",
"TALK_MUG", "TALK_STRANGER_AGGRESSIVE", "TALK_STRANGER_SCARED",
"TALK_STRANGER_WARY", "TALK_STRANGER_FRIENDLY", "TALK_STRANGER_NEUTRAL",
"TALK_SHELTER", "TALK_CAMP_OVERSEER" ]
start_topics = ["TALK_RADIO", "TALK_LEADER", "TALK_FRIEND", "TALK_STOLE_ITEM",
"TALK_MISSION_DESCRIBE_URGENT", "TALK_SEDATED", "TALK_WAKE_UP",
"TALK_MUG", "TALK_STRANGER_AGGRESSIVE", "TALK_STRANGER_SCARED",
"TALK_STRANGER_WARY", "TALK_STRANGER_FRIENDLY", "TALK_STRANGER_NEUTRAL",
"TALK_SHELTER", "TALK_CAMP_OVERSEER"]
for talk_topic in dialogue:
if not isinstance(talk_topic, dict):
continue
@@ -212,4 +213,5 @@ def validate(dialogue):
if not branch_record["parent"] in start_topics:
print("no path from a start topic to {}".format(topic_id))
validate(get_dialogue_from_json())
+2 -2
View File
@@ -13,7 +13,7 @@ starts_with_drive_letter = re.compile("^/(\w)/(.*)$")
data = None
with open(compile_db, 'r', encoding="utf-8") as fs:
data = json.load( fs )
data = json.load(fs)
for j in range(len(data)):
directory = data[j]["directory"]
@@ -24,7 +24,7 @@ with open(compile_db, 'r', encoding="utf-8") as fs:
rsp_path = os.path.join(directory, command[i][1:])
with open(rsp_path, 'r', encoding="utf-8") as rsp:
newflags = shlex.split(rsp.read())
command = command[:i] + newflags + command[i+1:]
command = command[:i] + newflags + command[i + 1:]
i = i + len(newflags)
else:
match_result = starts_with_drive_letter.match(command[i])
+4 -2
View File
@@ -22,7 +22,8 @@ from datetime import time as dtime, date, datetime, timedelta
log = logging.getLogger('generate_changelog')
class MissingCommitException(Exception): pass
class MissingCommitException(Exception):
pass
class JenkinsBuild:
@@ -134,7 +135,7 @@ class SummaryType:
class CDDAPullRequest(PullRequest):
"""A Pull Request with logic specific to CDDA Repository and their "Summary" descriptions"""
SUMMARY_REGEX = re.compile( r'^`*(?i:SUMMARY):\s+(?P<pr_type>\w+)\s*(?:"(?P<pr_desc>.+)")?', re.MULTILINE )
SUMMARY_REGEX = re.compile(r'^`*(?i:SUMMARY):\s+(?P<pr_type>\w+)\s*(?:"(?P<pr_desc>.+)")?', re.MULTILINE)
VALID_SUMMARY_CATEGORIES = (
'Content',
@@ -206,6 +207,7 @@ class JenkinsBuildFactory:
return JenkinsBuild(number, last_hash, branch, build_dttm, is_building,
build_result, block_ms, wait_ms, build_ms)
class CommitFactory:
"""Abstraction for instantiation of new Commit objects"""
+25 -27
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# compose.py
# Split a gfx directory made of 1000s of little images and files into a set of tilesheets
@@ -22,34 +22,31 @@ FALLBACK = {
"file": "fallback.png",
"tiles": [],
"ascii": [
{ "offset": 0, "bold": False, "color": "BLACK" },
{ "offset": 256, "bold": True, "color": "WHITE" },
{ "offset": 512, "bold": False, "color": "WHITE" },
{ "offset": 768, "bold": True, "color": "BLACK" },
{ "offset": 1024, "bold": False, "color": "RED" },
{ "offset": 1280, "bold": False, "color": "GREEN" },
{ "offset": 1536, "bold": False, "color": "BLUE" },
{ "offset": 1792, "bold": False, "color": "CYAN" },
{ "offset": 2048, "bold": False, "color": "MAGENTA" },
{ "offset": 2304, "bold": False, "color": "YELLOW" },
{ "offset": 2560, "bold": True, "color": "RED" },
{ "offset": 2816, "bold": True, "color": "GREEN" },
{ "offset": 3072, "bold": True, "color": "BLUE" },
{ "offset": 3328, "bold": True, "color": "CYAN" },
{ "offset": 3584, "bold": True, "color": "MAGENTA" },
{ "offset": 3840, "bold": True, "color": "YELLOW" }
{"offset": 0, "bold": False, "color": "BLACK"},
{"offset": 256, "bold": True, "color": "WHITE"},
{"offset": 512, "bold": False, "color": "WHITE"},
{"offset": 768, "bold": True, "color": "BLACK"},
{"offset": 1024, "bold": False, "color": "RED"},
{"offset": 1280, "bold": False, "color": "GREEN"},
{"offset": 1536, "bold": False, "color": "BLUE"},
{"offset": 1792, "bold": False, "color": "CYAN"},
{"offset": 2048, "bold": False, "color": "MAGENTA"},
{"offset": 2304, "bold": False, "color": "YELLOW"},
{"offset": 2560, "bold": True, "color": "RED"},
{"offset": 2816, "bold": True, "color": "GREEN"},
{"offset": 3072, "bold": True, "color": "BLUE"},
{"offset": 3328, "bold": True, "color": "CYAN"},
{"offset": 3584, "bold": True, "color": "MAGENTA"},
{"offset": 3840, "bold": True, "color": "YELLOW"}
]
}
error_logged = False
# stupid stinking Python 2 versus Python 3 syntax
def write_to_json(pathname, data):
with open(pathname, "w") as fp:
try:
json.dump(data, fp)
except ValueError:
fp.write(json.dumps(data))
json.dump(data, fp)
json_formatter = "./tools/format/json_formatter.cgi"
if os.path.isfile(json_formatter):
@@ -67,9 +64,9 @@ def find_or_make_dir(pathname):
class PngRefs(object):
def __init__(self, tileset_dirname):
# dict of pngnames to png numbers; used to control uniqueness
self.pngname_to_pngnum = { "null_image": 0 }
self.pngname_to_pngnum = {"null_image": 0}
# dict of png absolute numbers to png names
self.pngnum_to_pngname = { 0: "null_image" }
self.pngnum_to_pngname = {0: "null_image"}
self.pngnum = 0
self.referenced_pngnames = []
self.tileset_pathname = tileset_dirname
@@ -206,7 +203,7 @@ class TilesheetData(object):
self.null_image = Vips.Image.grey(self.width, self.height)
self.row_pngs = ["null_image"]
self.filler = False
self.fallback = False;
self.fallback = False
if self.ts_specs.get("fallback"):
self.fallback = True
return
@@ -229,7 +226,7 @@ class TilesheetData(object):
refs.pngnum += spacer
in_list = []
for png_pathname in self.row_pngs:
if png_pathname == "null_image":
in_list.append(self.null_image)
@@ -303,6 +300,7 @@ class TilesheetData(object):
out_image = Vips.Image.arrayjoin(merge_pngs, across=16)
out_image.pngsave(self.ts_path)
args = argparse.ArgumentParser(description="Merge all the individal tile_entries and pngs in a tileset's directory into a tile_config.json and 1 or more tilesheet pngs.")
args.add_argument("tileset_dir", action="store",
help="local name of the tileset directory")
@@ -351,7 +349,7 @@ for subdir_index in range(1, len(refs.tileset_info)):
#print("pngnum to pngname {}".format(json.dumps(refs.pngnum_to_pngname, sort_keys=True, indent=2)))
tiles_new = []
for ts_data in all_ts_data:
if ts_data.fallback:
fallback_name = ts_data.ts_name
+10 -11
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# decompose.py
# Split a gfx tile_config.json into 1000s of little directories, each with their own config
@@ -9,6 +9,7 @@ import json
import math
import os
import subprocess
import sys
try:
import pyvips
@@ -18,13 +19,10 @@ except ImportError:
gi.require_version('Vips', '8.0')
from gi.repository import Vips
# stupid stinking Python 2 versus Python 3 syntax
def write_to_json(pathname, data, prettify=False):
with open(pathname, "w") as fp:
try:
json.dump(data, fp)
except ValueError:
fp.write(json.dumps(data))
json.dump(data, fp)
json_formatter = "./tools/format/json_formatter.cgi"
if prettify and os.path.isfile(json_formatter):
@@ -214,6 +212,7 @@ class TileSheetData(object):
#print("{}: {}".format(self.ts_filename, json.dumps(ts_tile_info, indent=2)))
tile_info.append({self.ts_filename: ts_tile_info})
class ExtractionData(object):
def __init__(self, ts_filename, refs):
self.ts_data = refs.ts_data.get(ts_filename)
@@ -225,7 +224,7 @@ class ExtractionData(object):
ts_base = ts_filename.split(".png")[0]
geometry_dim = "{}x{}".format(self.ts_data.sprite_width, self.ts_data.sprite_height)
pngs_dir = "/pngs_" + ts_base + "_{}".format(geometry_dim)
pngs_dir = "/pngs_" + ts_base + "_{}".format(geometry_dim)
self.ts_dir_pathname = refs.tileset_pathname + pngs_dir
find_or_make_dir(self.ts_dir_pathname)
self.tilenum_in_dir = 256
@@ -261,7 +260,7 @@ class ExtractionData(object):
self.increment_dir()
tile_data = refs.ts_data[ts_filename]
file_index = png_index - tile_data.pngnum_min
y_index = math.floor( file_index / tile_data.ts_tiles_per_row )
y_index = math.floor(file_index / tile_data.ts_tiles_per_row)
x_index = file_index - y_index * tile_data.ts_tiles_per_row
tile_off_x = max(0, tile_data.sprite_width * x_index)
tile_off_y = max(0, tile_data.sprite_height * y_index)
@@ -304,7 +303,7 @@ class PngRefs(object):
os.stat(self.tileset_pathname)
except KeyError:
print("cannot find a directory {}".format(self.tileset_pathname))
exit -1
sys.exit(-1)
tileset_confname = refs.tileset_pathname + "/" + "tile_config.json"
@@ -312,7 +311,7 @@ class PngRefs(object):
os.stat(tileset_confname)
except KeyError:
print("cannot find a directory {}".format(tileset_confname))
exit -1
sys.exit(-1)
if delete_pathname:
with open(delete_pathname) as del_file:
@@ -328,7 +327,7 @@ class PngRefs(object):
self.delete_pngnums.append(i)
with open(tileset_confname) as conf_file:
return(json.load(conf_file))
return(json.load(conf_file))
def add_pngnum_to_tsfilepath(self, pngnum):
if not isinstance(pngnum, int):
+5 -9
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# png_update.py
# Rename a png and update all references to it.
@@ -8,13 +8,10 @@ import json
import os
import subprocess
# stupid stinking Python 2 versus Python 3 syntax
def write_to_json(pathname, data):
with open(pathname, "w") as fp:
try:
json.dump(data, fp)
except ValueError:
fp.write(json.dumps(data))
json.dump(data, fp)
json_formatter = "./tools/format/json_formatter.cgi"
if os.path.isfile(json_formatter):
@@ -84,7 +81,7 @@ def convert_tile_entry(tile_entry, old_name, new_name):
changed |= add_changed
if new_tile_entrys:
tile_entry["additional_tiles"] = new_tile_entrys
return tile_entry, changed
return tile_entry, changed
def convert_tile_entry_file(file_path, old_name, new_name):
@@ -104,6 +101,7 @@ def convert_tile_entry_file(file_path, old_name, new_name):
new_tile_data = new_tile_data[0]
write_to_json(file_path, new_tile_data)
args = argparse.ArgumentParser(description="Rename a png file, its associated tile_entry.json, and update all other tile_entry.json in the tileset dir to reflect the new name.")
args.add_argument("tileset_dir", action="store",
help="local name of the tileset directory under gfx/")
@@ -150,5 +148,3 @@ for png_dirname in os.listdir(tileset_dirname):
elif filename == old_name_json:
new_path = subdir_fpath + "/" + new_name_json
os.rename(old_path, new_path)
+1 -1
View File
@@ -26,7 +26,7 @@ for root, directories, filenames in os.walk(args_dict["dir"]):
path = os.path.join(root, filename)
if path.endswith(".json"):
new = gen_new(path)
if new != None:
if new is not None:
with open(path, "w") as jf:
json.dump(new, jf, ensure_ascii=False)
os.system(f"./tools/format/json_formatter.cgi {path}")
+12 -8
View File
@@ -10,16 +10,18 @@ TOP_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, "..", ".."))
JSON_DIR = os.path.join(TOP_DIR, "data")
TAGS_FILE = os.path.join(TOP_DIR, "tags")
def make_tags_line(id_key, id, filename):
pattern = '/"{id_key}": "{id}"/'.format(id_key=id_key, id=id)
return '\t'.join((id, filename, pattern)).encode('utf-8')
def is_json_tag_line(line):
return b'.json\t' in line
def main(args):
parser = argparse.ArgumentParser(description=
"""\
parser = argparse.ArgumentParser(description="""
Update a tags file with locations of the definitions of CDDA json entities.
If you already have a tags file with some data in, this will only replace tags
@@ -41,15 +43,15 @@ e.g. ctags.""")
json_data = json.load(file)
except Exception as err:
sys.stderr.write(
"Problem reading file %s, reason: %s" %
(filename, err))
"Problem reading file %s, reason: %s" %
(filename, err))
continue
if type(json_data) == dict:
json_data = [json_data]
elif type(json_data) != list:
sys.stderr.write(
"Problem parsing data from file %s, reason: "
"expected a list." % filename)
"Problem parsing data from file %s, reason: "
"expected a list." % filename)
continue
for obj in json_data:
@@ -67,13 +69,15 @@ e.g. ctags.""")
except FileNotFoundError:
pass
existing_tags_lines = [l.rstrip(b'\n') for l in existing_tags_lines if
not is_json_tag_line(l)]
existing_tags_lines = [
l.rstrip(b'\n') for l in existing_tags_lines if
not is_json_tag_line(l)]
all_tags_lines = sorted(json_tags_lines + existing_tags_lines)
with open(TAGS_FILE, 'wb') as tags_file:
tags_file.write(b'\n'.join(all_tags_lines))
if __name__ == '__main__':
main(sys.argv[1:])
+14 -14
View File
@@ -1,14 +1,12 @@
#!/usr/bin/env python2
#!/usr/bin/env python3
"""Run this script with -h for usage info and docs.
"""
from __future__ import print_function
import sys
import json
import argparse
from util import import_data, key_counter, ui_counts_to_columns,\
WhereAction
WhereAction
parser = argparse.ArgumentParser(description="""Count the number of times a specific key occurs.
@@ -20,16 +18,18 @@ Example usages:
# List keys on JSON objects of type "bionic", output in JSON.
%(prog)s type=bionic
""", formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--fnmatch",
default="*.json",
help="override with glob expression to select a smaller fileset.")
parser.add_argument("--human",
action="store_true",
help="if set, makes output human readable. default is to return output in JSON.")
parser.add_argument("where",
action=WhereAction, nargs='*', type=str,
help="where exclusions of the form 'where_key=where_val', no quotes.")
parser.add_argument(
"--fnmatch",
default="*.json",
help="override with glob expression to select a smaller fileset.")
parser.add_argument(
"--human",
action="store_true",
help="if set, makes output human readable. default is to return output in JSON.")
parser.add_argument(
"where",
action=WhereAction, nargs='*', type=str,
help="where exclusions of the form 'where_key=where_val', no quotes.")
if __name__ == "__main__":
+6 -8
View File
@@ -1,9 +1,7 @@
#!/usr/bin/env python2
#!/usr/bin/env python3
"""Run this script with -h for usage info and docs.
"""
from __future__ import print_function
import argparse
import os
import stat
@@ -24,10 +22,10 @@ Example usages:
values.py -k material | %(prog)s
""", formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--human",
action="store_true",
help="if set, makes output human readable. default is to return output in JSON.")
parser.add_argument(
"--human",
action="store_true",
help="if set, makes output human readable. default is to return output in JSON.")
if __name__ == "__main__":
@@ -56,7 +54,7 @@ if __name__ == "__main__":
keys = set()
for item in json_data:
# We assume only dictionaries here
keys.update(item.keys())
keys.update(list(item.keys()))
keys = sorted(list(keys))
+14 -14
View File
@@ -1,9 +1,7 @@
#!/usr/bin/env python2
#!/usr/bin/env python3
"""Run this script with -h for usage info and docs.
"""
from __future__ import print_function
import sys
import argparse
from util import import_data, matches_all_wheres, CDDAJSONWriter, WhereAction
@@ -16,16 +14,18 @@ Example usages:
%(prog)s material=plastic material=steel
""", formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--fnmatch",
default="*.json",
help="override with glob expression to select a smaller fileset.")
parser.add_argument("--all",
action="store_true",
help="if set, includes all matches. if not set, includes first match in the stream.")
parser.add_argument("where",
action=WhereAction, nargs='+', type=str,
help="where exclusions of the form 'where_key=where_val', no quotes.")
parser.add_argument(
"--fnmatch",
default="*.json",
help="override with glob expression to select a smaller fileset.")
parser.add_argument(
"--all",
action="store_true",
help="if set, includes all matches. if not set, includes first match in the stream.")
parser.add_argument(
"where",
action=WhereAction, nargs='+', type=str,
help="where exclusions of the form 'where_key=where_val', no quotes.")
if __name__ == "__main__":
@@ -58,6 +58,6 @@ if __name__ == "__main__":
# TODO: get rid of ugh
print("[")
for i, p in enumerate(plucked):
eol = ",\n" if i < len(plucked)-1 else "\n"
eol = ",\n" if i < len(plucked) - 1 else "\n"
print(CDDAJSONWriter(p, 1).dumps(), end=eol)
print("]")
+1
View File
@@ -10,6 +10,7 @@ args_dict = vars(args.parse_args())
inheriting_item_ids = []
def gen_new(path):
change = False
with open(path, "r") as json_file:
+11 -12
View File
@@ -1,9 +1,7 @@
#!/usr/bin/env python2
#!/usr/bin/env python3
"""Run this script with -h for usage info and docs.
"""
from __future__ import print_function
import sys
import argparse
from util import import_data, matches_all_wheres, CDDAJSONWriter, WhereAction
@@ -18,13 +16,14 @@ Example usages:
# everything else goes to stderr
%(prog)s --fnmatch=dreams.json type=dream strength=2 1>matched.json 2>not_matched.json
""", formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--fnmatch",
default="*.json",
help="override with glob expression to select a smaller fileset.")
parser.add_argument("where",
action=WhereAction, nargs='+', type=str,
help="where exclusions of the form 'where_key=where_val', no quotes.")
parser.add_argument(
"--fnmatch",
default="*.json",
help="override with glob expression to select a smaller fileset.")
parser.add_argument(
"where",
action=WhereAction, nargs='+', type=str,
help="where exclusions of the form 'where_key=where_val', no quotes.")
if __name__ == "__main__":
@@ -53,13 +52,13 @@ if __name__ == "__main__":
# matched first
print("[")
for i, p in enumerate(matched):
eol = ",\n" if i < len(matched)-1 else "\n"
eol = ",\n" if i < len(matched) - 1 else "\n"
print(CDDAJSONWriter(p, 1).dumps(), end=eol)
print("]")
# not_matched second
print("[", file=sys.stderr)
for i, p in enumerate(not_matched):
eol = ",\n" if i < len(not_matched)-1 else "\n"
eol = ",\n" if i < len(not_matched) - 1 else "\n"
print(CDDAJSONWriter(p, 1).dumps(), end=eol, file=sys.stderr)
print("]", file=sys.stderr)
+3 -11
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python2
#!/usr/bin/env python3
"""Print a Markdown or CSV table of JSON values from the given keys.
Run this script with -h for full usage information.
@@ -16,15 +16,8 @@ Examples with nested attributes:
"""
import argparse
import codecs
import sys
import util
# Avoid (most) unicode frustrations
# https://pythonhosted.org/kitchen/unicode-frustrations.html
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
# Command-line arguments
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
@@ -61,7 +54,7 @@ def safe_value(value, format):
"""
if format == 'md':
return value.replace('|', '\|')
return value.replace('|', '\\|')
elif format == 'csv':
if ',' in value or '"' in value:
@@ -153,7 +146,7 @@ def item_values(item, fields):
# Make dict presentable
if isinstance(it, dict):
values.append("%s" % it.items())
values.append("%s" % list(it.items()))
# Separate lists with slashes
elif isinstance(it, list):
values.append(" / ".join("%s" % i for i in it))
@@ -179,4 +172,3 @@ if __name__ == "__main__":
continue
print_row(item_values(item, args.columns), args.format)
+15 -25
View File
@@ -1,23 +1,19 @@
"""Utility stuff for json tools.
"""
from __future__ import print_function
import argparse
from collections import Counter, OrderedDict
from fnmatch import fnmatch
import json
import re
import os
from StringIO import StringIO
from io import StringIO
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
JSON_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, "..", "..", "data", "json"))
JSON_FNMATCH = "*.json"
def import_data(json_dir=JSON_DIR, json_fmatch=JSON_FNMATCH):
"""Use a UNIX like file match expression to weed out the JSON files.
@@ -47,13 +43,12 @@ def import_data(json_dir=JSON_DIR, json_fmatch=JSON_FNMATCH):
return (data, errors)
def match_primitive_values(item_value, where_value):
"""Perform any odd logic on item matching.
"""
# Matching interpolation for keyboard constrained input.
if type(item_value) == str or type(item_value) == unicode:
# Direct match, and don't convert unicode in Python 2.
if type(item_value) == str:
# Direct match
return bool(re.match(where_value, item_value))
elif type(item_value) == int or type(item_value) == float:
# match after string conversion
@@ -65,7 +60,6 @@ def match_primitive_values(item_value, where_value):
return False
def matches_where(item, where_key, where_value):
"""True if:
where_key exists AND
@@ -102,7 +96,6 @@ def matches_where(item, where_key, where_value):
return match_primitive_values(item_value, where_value)
def matches_all_wheres(item, where_fn_list):
"""Takes a list of where functions and attempts to match against them.
@@ -122,7 +115,6 @@ def matches_all_wheres(item, where_fn_list):
return True
class WhereAction(argparse.Action):
"""An argparse action callback.
@@ -157,7 +149,6 @@ class WhereAction(argparse.Action):
raise ValueError("Where options are strict. Must be in the form of 'where_key=where_value'")
def key_counter(data, where_fn_list):
"""Count occurences of keys found in data {list of dicts}
that also match each where_fn_list {list of fns}.
@@ -200,14 +191,14 @@ def item_value_counter(_value):
"""
stats = Counter()
# String or unicode
if isinstance(_value, basestring):
if isinstance(_value, str):
stats[_value] += 1
# Cast numbers to strings
elif type(_value) == int or type(_value) == float:
stats[str(_value)] += 1
# Pull all values from objects
elif type(_value) == OrderedDict:
stats += list_value_counter(_value.values())
stats += list_value_counter(list(_value.values()))
# Pull values from list of objects or strings
elif type(_value) == list:
stats += list_value_counter(_value)
@@ -216,6 +207,7 @@ def item_value_counter(_value):
(_value, type(_value)))
return stats
def list_value_counter(_list):
"""Return a Counter tallying all values in the given {list of dicts}
or {list of strs}, recursing into nested dicts and lists.
@@ -225,6 +217,7 @@ def list_value_counter(_list):
stats += item_value_counter(elem)
return stats
def value_counter(data, search_key, where_fn_list):
"""Takes a search_key {str}, and for values found in data {list of dicts}
that also match each where_fn_list {list of fns} with those keys,
@@ -246,7 +239,7 @@ def value_counter(data, search_key, where_fn_list):
parent_key = search_key
child_key = None
else:
raise ArgumentError("Only one '.' allowed in search key")
raise argparse.ArgumentError("Only one '.' allowed in search key")
for item in matching_data:
if parent_key not in item:
@@ -261,7 +254,7 @@ def value_counter(data, search_key, where_fn_list):
# If this value is a list of objects, pull parent_key.child_key
# values from all of them to include in stats
if type(parent_val) == list and all(type(e) == OrderedDict
for e in parent_val):
for e in parent_val):
for od in parent_val:
if child_key in od:
stat_vals.append(od[child_key])
@@ -281,12 +274,11 @@ def value_counter(data, search_key, where_fn_list):
return stats, len(matching_data)
def ui_values_to_columns(values, screen_width=80):
"""Take a list of strings and output in fixed width columns.
"""
max_val_len = len(max(values, key=len))+1
cols = screen_width/max_val_len
max_val_len = len(max(values, key=len)) + 1
cols = screen_width / max_val_len
iters = 0
for v in values:
print(v.ljust(max_val_len), end=' ')
@@ -296,20 +288,18 @@ def ui_values_to_columns(values, screen_width=80):
print("")
def ui_counts_to_columns(counts):
"""Take a Counter instance and display in single fixed width key:value
column.
"""
# Values in left column, counts in right, left column as wide as longest string length.
key_vals = counts.most_common()
key_field_len = len(max(list(counts.keys()), key=len))+1
key_field_len = len(max(list(counts.keys()), key=len)) + 1
output_template = "%%-%ds: %%s" % key_field_len
for k_v in key_vals:
print(output_template % k_v)
class CDDAJSONWriter(object):
"""Essentially a one-off class used to write CDDA formatted JSON output.
@@ -330,7 +320,7 @@ class CDDAJSONWriter(object):
# buf is initialized on a call to dumps
def indented_write(self, s):
self.buf.write(self.indent*self.indent_multiplier + s)
self.buf.write(self.indent * self.indent_multiplier + s)
def write_key(self, k):
self.indented_write("\"%s\": " % k)
@@ -361,7 +351,7 @@ class CDDAJSONWriter(object):
self.buf.write(",\n")
else:
self.buf.write("\n")
self.indent_multiplier -=1
self.indent_multiplier -= 1
self.indented_write("]")
def dumps(self):
@@ -372,7 +362,7 @@ class CDDAJSONWriter(object):
self.buf = None
self.buf = StringIO()
items = self.d.items()
items = list(self.d.items())
global indent_multiplier
self.indented_write("{\n")
self.indent_multiplier += 1
+18 -16
View File
@@ -1,14 +1,12 @@
#!/usr/bin/env python2
#!/usr/bin/env python3
"""Run this script with -h for usage info and docs.
"""
from __future__ import print_function
import argparse
import sys
import json
from util import import_data, value_counter, ui_counts_to_columns,\
WhereAction
WhereAction
parser = argparse.ArgumentParser(description="""Count the number of
times a specific values occurs for a specific key. The key may be a
@@ -26,18 +24,22 @@ Example usages:
# What cost values are in bionics that are active?
%(prog)s --key=cost type=bionic active=true
""", formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--fnmatch",
default="*.json",
help="override with glob expression to select a smaller fileset.")
parser.add_argument("--human",
action="store_true",
help="if set, makes output human readable. default is to return output in JSON dictionary.")
parser.add_argument("-k", "--key",
required=True, type=str,
help="key on JSON objects from which to count values")
parser.add_argument("where",
action=WhereAction, nargs='*', type=str,
help="where exclusions of the form 'where_key=where_val', no quotes.")
parser.add_argument(
"--fnmatch",
default="*.json",
help="override with glob expression to select a smaller fileset.")
parser.add_argument(
"--human",
action="store_true",
help="if set, makes output human readable. default is to return output in JSON dictionary.")
parser.add_argument(
"-k", "--key",
required=True, type=str,
help="key on JSON objects from which to count values")
parser.add_argument(
"where",
action=WhereAction, nargs='*', type=str,
help="where exclusions of the form 'where_key=where_val', no quotes.")
if __name__ == "__main__":
+24 -25
View File
@@ -36,26 +36,25 @@ def x_y_sub(x, y, is_north):
(y - MIN_Y - 1) % STRIDE_Y)
def x_y_simple(x, y):
return "{}__{}".format(x, y)
def get_data(argsDict, resource_name):
resource = []
resource_sources = argsDict.get(resource_name, [])
if not isinstance(resource_sources, list):
resource_sources = [resource_sources]
for resource_filename in resource_sources:
if resource_filename.endswith(".json"):
try:
with open(resource_filename) as resource_file:
resource += json.load(resource_file)
except FileNotFoundError:
exit("Failed: could not find {}".format(resource_filename))
else:
print("Invalid filename {}".format(resource_filename))
return resource
resource = []
resource_sources = argsDict.get(resource_name, [])
if not isinstance(resource_sources, list):
resource_sources = [resource_sources]
for resource_filename in resource_sources:
if resource_filename.endswith(".json"):
try:
with open(resource_filename) as resource_file:
resource += json.load(resource_file)
except FileNotFoundError:
exit("Failed: could not find {}".format(resource_filename))
else:
print(("Invalid filename {}".format(resource_filename)))
return resource
def adjacent_to_set(x, y, coord_set):
@@ -87,7 +86,7 @@ def validate_old_map(old_map, entry):
if entry["weight"] and old_map.get("weight") and entry["weight"] != old_map.get("weight"):
return False
if entry["object"].get("fill_ter") and old_obj.get("fill_ter") and \
entry["object"]["fill_ter"] != old_obj.get("fill_ter"):
entry["object"]["fill_ter"] != old_obj.get("fill_ter"):
return False
new_palettes = entry.get("palettes", {})
@@ -106,7 +105,7 @@ def validate_old_map(old_map, entry):
keysets[key_term] = new_keyset
elif new_keyset != {}:
return False
if not entry["weight"]:
entry["weight"] = old_map.get("weight", 0)
if not entry["object"].get("fill_ter"):
@@ -124,10 +123,10 @@ def adjust_place(term, old_obj, offset_x, offset_y):
def adjust_coord(x_or_y, new_entry, old_entry, offset):
val = old_entry.get(x_or_y, "False")
if val == "False":
return False
return False
if isinstance(val, list):
val[0] += offset
val[1] += offset
val[0] += offset
val[1] += offset
else:
val += offset
new_entry[x_or_y] = val
@@ -242,7 +241,7 @@ for z, zlevel in merge_sets.items():
for x_y, mapset in zlevel.items():
# first, split the mergeset into chunks with common KEYED_TERMS using a weird floodfill
chunks = []
chunks = [{ "maps": [], "entry": copy.deepcopy(basic_entry)}]
chunks = [{"maps": [], "entry": copy.deepcopy(basic_entry)}]
for y in range(0, STRIDE_Y):
for x in range(0, STRIDE_X):
om_id = mapset.get(x_y_simple(x, y), "")
@@ -260,10 +259,10 @@ for z, zlevel in merge_sets.items():
# check that this map's keyed terms match the other keyed terms in this chunk
if validate_old_map(old_map, chunk_data["entry"]):
chunk_data["maps"].append({"x": x, "y": y})
validated = True
validated = True
if not validated:
new_entry = copy.deepcopy(basic_entry)
chunks.append({ "maps": [{"x": x, "y": y}], "entry": new_entry })
chunks.append({"maps": [{"x": x, "y": y}], "entry": new_entry})
# then split up any irregular shapes that made it past the screen
# T and L shapes are possible because every map is adjacent, for instance
@@ -278,7 +277,7 @@ for z, zlevel in merge_sets.items():
min_x = maps[0]["x"]
maps.sort(key=itemgetter("y"))
max_y = maps[-1]["y"]
min_y = maps[0]["y"]
min_y = maps[0]["y"]
# if this is a line, square, or rectangle, it's continguous
if len(maps) == ((max_x - min_x + 1) * (max_y - min_y + 1)):
final_chunks.append(chunk_data)
@@ -303,7 +302,7 @@ for z, zlevel in merge_sets.items():
if not maps:
continue
first_x = maps[0]["x"]
first_y = maps[0]["y"]
first_y = maps[0]["y"]
for coords in maps:
x = coords["x"]
y = coords["y"]
+12 -13
View File
@@ -4,6 +4,7 @@ import json
import argparse
import copy
def hash_key(key):
if isinstance(key, list):
return "list_" + "".join(key)
@@ -22,8 +23,8 @@ def parse_furnter(om_objs, palette, conflicts):
map_hash = hash_key(map_val)
pal_hash = hash_key(pal_val)
conflicts.setdefault(map_key, {})
conflicts[map_key].setdefault(map_hash, { "val": map_val, "count": 0 })
conflicts[map_key].setdefault(pal_hash, { "val": pal_val, "count": 0 })
conflicts[map_key].setdefault(map_hash, {"val": map_val, "count": 0})
conflicts[map_key].setdefault(pal_hash, {"val": pal_val, "count": 0})
conflicts[map_key][map_hash]["count"] += 1
conflicts[map_key][pal_hash]["count"] += 1
@@ -66,13 +67,13 @@ mapgen_source = argsDict.get("mapgen_source", "")
palette_name = argsDict.get("palette_name", "")
palette_source = argsDict.get("palette_path", "") + "/" + palette_name + ".json"
if mapgen_source.endswith(".json"):
try:
with open(mapgen_source) as mapgen_file:
mapgen += json.load(mapgen_file)
except FileNotFoundError:
exit("Failed: could not find {}".format(mapgen_source))
try:
with open(mapgen_source) as mapgen_file:
mapgen += json.load(mapgen_file)
except FileNotFoundError:
exit("Failed: could not find {}".format(mapgen_source))
else:
exit("Failed: invalid mapgen file name {}".format(mapgen_source))
exit("Failed: invalid mapgen file name {}".format(mapgen_source))
furn_pal = {}
furn_conflicts = {}
@@ -116,12 +117,12 @@ for om_tile in mapgen:
if om_ter_final:
om_object["terrain"] = om_ter_final
else:
del om_object["terrain"]
del om_object["terrain"]
else:
del om_object["terrain"]
with open(mapgen_source, 'w') as mapgen_file:
mapgen_file.write(json.dumps(mapgen, indent=2))
mapgen_file.write(json.dumps(mapgen, indent=2))
palette_json = [
{
@@ -133,9 +134,7 @@ palette_json = [
]
with open(palette_source, 'w') as palette_file:
palette_file.write(json.dumps(palette_json, indent=2))
palette_file.write(json.dumps(palette_json, indent=2))
#print("furniture palette {}".format(json.dumps(furn_pal, indent=2)))
#print("terrain palette {}".format(json.dumps(ter_pal, indent=2)))
+9 -6
View File
@@ -7,6 +7,7 @@ import re
import subprocess
import sys
def print_help():
print("\n"
"Update faction camp blueprints with autocalculated requirements from unit test log.\n"
@@ -18,6 +19,7 @@ def print_help():
" update: update with suggested requirements (default)\n"
" suppress: suppress inconsistency warnings\n")
def main(argv):
try:
opts, args = getopt.getopt(argv, "", ["help", "logfile=", "action="])
@@ -39,7 +41,7 @@ def main(argv):
elif arg == "suppress":
suppress = True
else:
print_help();
print_help()
return
if not test_log:
print_help()
@@ -49,7 +51,7 @@ def main(argv):
"data/core",
"data/json",
"data/mods",
};
}
auto_update_blueprint = re.compile("~~~ auto-update-blueprint: (.+)")
auto_update_blueprint_end = re.compile("~~~ end-auto-update")
@@ -78,7 +80,7 @@ def main(argv):
else:
reqs += line
if complete:
update_blueprints[ident] = json.loads(reqs);
update_blueprints[ident] = json.loads(reqs)
print("{} needs updating".format(ident))
if len(update_blueprints) == 0:
@@ -98,10 +100,10 @@ def main(argv):
if type(content) is list:
for obj in content:
if not (type(obj) is dict
and "type" in obj and obj["type"] == "recipe"
and ("result" in obj or "abstract" in obj)):
and "type" in obj and obj["type"] == "recipe"
and ("result" in obj or "abstract" in obj)):
continue
ident = None;
ident = None
if "abstract" in obj:
ident = obj["abstract"]
else:
@@ -121,5 +123,6 @@ def main(argv):
json.dump(content, fs, indent=2)
subprocess.run(["tools/format/json_formatter", json_path], stdout=subprocess.DEVNULL)
if __name__ == "__main__":
main(sys.argv[1:])
+6 -6
View File
@@ -7,8 +7,8 @@ import re
import os
args = argparse.ArgumentParser(
description=
"Generate a json definition for a vehicle in a Cataclysm DDA save file.")
description="Generate a json definition for a vehicle "
"in a Cataclysm DDA save file.")
args.add_argument(
"save", action="store", help="specify save file containing vehicle")
args.add_argument(
@@ -33,7 +33,7 @@ def getVehicleTemplates():
allTemplates = []
for vehicle in vehicles:
vehicleDef = buildVehicleDef(vehicle)
if not vehicleDef in allTemplates:
if vehicleDef not in allTemplates:
allTemplates.append(vehicleDef)
return allTemplates
@@ -45,7 +45,7 @@ def getVehicleInstances(mapPath):
mapData = json.load(mapFile)
for i in range(0, len(mapData)):
for vehicle in mapData[i]["vehicles"]:
if argsDict["vehicle"] != None:
if argsDict["vehicle"] is not None:
if argsDict["vehicle"] == vehicle["name"]:
vehicles.append(vehicle)
print(f"Found \"{vehicle['name']}\"")
@@ -76,11 +76,11 @@ def buildVehicleDef(vehicle):
frames = [
p for p in partsDef
if re.match(r'(xl|hd|folding_)?frame', p["part"]) != None
if re.match(r'(xl|hd|folding_)?frame', p["part"]) is not None
]
everythingElse = [
p for p in partsDef
if re.match(r'(xl|hd|folding_)?frame', p["part"]) == None
if re.match(r'(xl|hd|folding_)?frame', p["part"]) is None
]
frames = sortFrames(frames)
+2 -4
View File
@@ -1,12 +1,10 @@
#!/usr/bin/env python
#!/usr/bin/env python3
'''Tool to combine ascii map cells with json templates.
Original design and implementation: acidia (https://github.com/acidia)
Current design and implementation: wormingdead (https://github.com/wormingdead)
'''
from __future__ import division
import argparse
import copy
import json
@@ -267,6 +265,6 @@ def main(parser):
file_name=json_template.name,
json_err=str(val_err)))
if __name__ == "__main__":
main(cli_interface())
+55 -53
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# pylint: disable=C0103
# pylint: disable=C0301
@@ -13,7 +13,7 @@ import math
# offset=0 will align the bottom of the sprite with the bottom (southwest corner) of the square
# offset<1 will be a fraction of the isometric tile height
# offset>=1 will be an absolute number of pixels
SPRITE_OFFSET_FROM_BOTTOM = 1.0/8
SPRITE_OFFSET_FROM_BOTTOM = 1.0 / 8
parser = argparse.ArgumentParser(description='Convert a Cataclysm-DDA tileset to isometric view.')
@@ -23,19 +23,21 @@ parser.add_argument('-f', dest='floodfill', action='store_true')
args = parser.parse_args()
def iso_ize(tile_num, new_tile_num=-1, initial_rotation=0, override=False):
if override or (tile_num,initial_rotation) not in converted_tile_ids:
print " iso-izing " + str(tile_num)
if override or (tile_num, initial_rotation) not in converted_tile_ids:
print(" iso-izing " + str(tile_num))
if new_tile_num == -1:
new_tile_num = tile_num
converted_tile_ids[(tile_num,initial_rotation)] = True
command = ('convert -background transparent ' + new_tileset_name + '/tiles/tile-' + "{:0>6d}".format(tile_num) + '.png ' +
converted_tile_ids[(tile_num, initial_rotation)] = True
command = (
'convert -background transparent ' + new_tileset_name + '/tiles/tile-' + "{:0>6d}".format(tile_num) + '.png ' +
'-rotate ' + str(initial_rotation) + ' ' +
'-rotate -45 +repage -resize 100%x50% ' +
'-crop ' + str(nwidth) + 'x' + str(int(nwidth/2)) + '+2+1 ' + #TODO: get correct offsets
'+repage -extent ' + str(nwidth) + 'x' + str(nheight) + '+0-' + str(nheight-int(nwidth/2)) + ' ' +
'-crop ' + str(nwidth) + 'x' + str(int(nwidth / 2)) + '+2+1 ' + # TODO: get correct offsets
'+repage -extent ' + str(nwidth) + 'x' + str(nheight) + '+0-' + str(nheight - int(nwidth / 2)) + ' ' +
new_tileset_name + '/tiles/to_merge/tile-' + "{:0>6d}".format(new_tile_num) + '.png')
print command
print(command)
if os.system(command):
raise
return True
@@ -45,7 +47,7 @@ def iso_ize(tile_num, new_tile_num=-1, initial_rotation=0, override=False):
# convert one old tile definition to one new tile definition
# recursive for additional-tiles
def tile_convert(otile, main_id, new_tile_number):
print 'tile_convert ' + main_id + ' ' + str(new_tile_number)
print('tile_convert ' + main_id + ' ' + str(new_tile_number))
ntile = dict()
ntile['id'] = otile['id']
ntile['ntn'] = int(new_tile_number)
@@ -58,7 +60,7 @@ def tile_convert(otile, main_id, new_tile_number):
if 'multitile' in otile:
ntile['multitile'] = otile['multitile']
for g in ('fg','bg'):
for g in ('fg', 'bg'):
if g not in otile:
continue
if type(otile[g]) == int:
@@ -81,11 +83,11 @@ def tile_convert(otile, main_id, new_tile_number):
# iso-ize?
if (
(
(main_id[0:2] == 't_' or main_id[0:9] == 'lighting_') and # terrain and lighting
(g == 'bg' or 'bg' not in otile) # rotate bg, fg iff there's no bg
(main_id[0:2] == 't_' or main_id[0:9] == 'lighting_') and # terrain and lighting
(g == 'bg' or 'bg' not in otile) # rotate bg, fg iff there's no bg
) or
(main_id[0:2] == 'f_' and g == 'bg' and 'fg' in otile) or
main_id[0:3] == 'vp_' or main_id[0:3] == 'fd_' or # vehicle parts and fields
main_id[0:3] == 'vp_' or main_id[0:3] == 'fd_' or # vehicle parts and fields
# additional_tiles:
otile['id'] == 'broken' or
otile['id'] == 'open' or
@@ -95,40 +97,40 @@ def tile_convert(otile, main_id, new_tile_number):
otile['id'] == 'edge' or
otile['id'] == 'end_piece' or
otile['id'] == 't_connection' or
('rotates' in otile and otile['rotates'] == True) or
('rotates' in otile and otile['rotates'] is True) or
otile['id'] != main_id
):
):
# iso-ize this tile
iso_ize(otile[g][0], override=True)
if ('rotates' in otile or
otile['id'] == 'broken' or
otile['id'] == 'open' or
otile['id'] == 'unconnected' or
otile['id'] == 'center' or
otile['id'] == 'corner' or
otile['id'] == 'edge' or
otile['id'] == 'end_piece' or
otile['id'] == 't_connection'):
print " and rotating " + str(otile[g][0])
otile['id'] == 'broken' or
otile['id'] == 'open' or
otile['id'] == 'unconnected' or
otile['id'] == 'center' or
otile['id'] == 'corner' or
otile['id'] == 'edge' or
otile['id'] == 'end_piece' or
otile['id'] == 't_connection'):
print(" and rotating " + str(otile[g][0]))
# create 3 new iso-ized tiles, as well
for rot in (270,180,90):
for rot in (270, 180, 90):
if iso_ize(otile[g][0], ntile['ntn'], rot):
ntile[g].append(ntile['ntn'])
ntile['ntn'] += 1
print "next tile number now " + str(ntile['ntn'])
print("next tile number now " + str(ntile['ntn']))
else:
if (ntile[g][0],0) not in converted_tile_ids:
print" offsetting " + str(ntile[g][0])
converted_tile_ids[(ntile[g][0],0)] = True
if (ntile[g][0], 0) not in converted_tile_ids:
print(" offsetting " + str(ntile[g][0]))
converted_tile_ids[(ntile[g][0], 0)] = True
# offset this flat tile
command = (
'convert -background transparent ' + new_tileset_name + '/tiles/tile-' + "{:0>6d}".format(otile[g][0]) + '.png' +
(' -fill transparent -draw "color 0,0 floodfill"' if args.floodfill else '') +
' -extent ' + str(nwidth) + 'x' + str(nheight) +
'-' + str(int((nwidth-owidth)/2)) + '-' + str(int((nheight-oheight)-flat_sprite_offset)) + ' ' +
'-' + str(int((nwidth - owidth) / 2)) + '-' + str(int((nheight - oheight) - flat_sprite_offset)) + ' ' +
'+repage ' +
new_tileset_name + '/tiles/to_merge/tile-' + '{:0>6d}'.format(otile[g][0]) + '.png')
print command
print(command)
if os.system(command):
raise
else:
@@ -140,13 +142,13 @@ def tile_convert(otile, main_id, new_tile_number):
if 'additional_tiles' in otile:
nta = ntile['additional_tiles'] = list()
for otile in otile['additional_tiles']:
print ' handling additional_tile ' + otile['id']
print(' handling additional_tile ' + otile['id'])
tile = tile_convert(otile, main_id, ntile['ntn'])
ntile['ntn'] = tile['ntn']
del tile['ntn']
nta.append(tile)
print "returning tile, next tile number now " + str(ntile['ntn'])
print("returning tile, next tile number now " + str(ntile['ntn']))
return ntile
@@ -165,14 +167,14 @@ try:
except:
pass
os.system('rm -rf '+new_tileset_name+'/tiles/*')
os.system('rm -rf ' + new_tileset_name + '/tiles/*')
try:
os.mkdir(new_tileset_name + '/tiles/to_merge')
except:
pass
print 'reading ' + old_tileset_name + '/tile_config.json'
print('reading ' + old_tileset_name + '/tile_config.json')
with open(old_tileset_name + '/tile_config.json') as old_tile_config_json_file:
otc = json.load(old_tile_config_json_file)
@@ -180,13 +182,13 @@ oheight = otc['tile_info'][0]['height']
owidth = otc['tile_info'][0]['width']
# iso tile width is enough to hold a 45 degree rotated original tile
nwidth = int(owidth * math.sqrt(2)/2)*2
nwidth = int(owidth * math.sqrt(2) / 2) * 2
# iso tile height is enough to hold a vertical offset 2d tile
if SPRITE_OFFSET_FROM_BOTTOM < 1:
flat_sprite_offset = int(nwidth * SPRITE_OFFSET_FROM_BOTTOM / 2)
else:
flat_sprite_offset = int(SPRITE_OFFSET_FROM_BOTTOM / 2)
print "flat sprite offset " + str(flat_sprite_offset)
print("flat sprite offset " + str(flat_sprite_offset))
nheight = flat_sprite_offset + oheight
# struct that will become the new tileset_config.json
@@ -202,43 +204,44 @@ ntc['tiles-new'] = list()
tile_count = 0
new_tiles = list()
print 'processing tiles-new'
print('processing tiles-new')
for otn in otc['tiles-new']:
# need to add support for fallback tiles
if os.path.basename(otn['file']).find('fallback') > -1:
continue
converted_tile_ids = dict()
if first_filename == '':
first_filename = os.path.basename(otn['file']) # remember this for tileset.txt
first_filename = os.path.basename(otn['file']) # remember this for tileset.txt
ntc['tiles-new'].append(dict())
ntn = ntc['tiles-new'][-1]
ntn['file'] = 'gfx/' + new_tileset_name + '/' + os.path.basename(otn['file'])
ntn['tiles'] = list()
print ' splitting ../'+otn['file']
print(' splitting ../' + otn['file'])
# split tile image sheet into individual tile images
command = 'convert -crop '+str(oheight)+'x'+str(owidth)+' ../'+otn['file']+' +repage '+new_tileset_name+'/tiles/tile-%06d.png'
print command
command = 'convert -crop ' + str(oheight) + 'x' + str(owidth) + ' ../' + otn['file'] + ' +repage ' + new_tileset_name + '/tiles/tile-%06d.png'
print(command)
if os.system(command):
raise
os.system('cp '+new_tileset_name+'/tiles/tile-*.png '+new_tileset_name+'/tiles/to_merge')
os.system('cp ' + new_tileset_name + '/tiles/tile-*.png ' + new_tileset_name + '/tiles/to_merge')
# path joining version for other paths
TILEDIR = new_tileset_name+'/tiles'
TILEDIR = new_tileset_name + '/tiles'
tile_count = len([name for name in os.listdir(TILEDIR) if os.path.isfile(os.path.join(TILEDIR, name))])
new_tile_number = tile_count
for otile in otn['tiles']:
print ' handling ' + otile['id']
tile = tile_convert(otile,otile['id'],new_tile_number)
print(' handling ' + otile['id'])
tile = tile_convert(otile, otile['id'], new_tile_number)
new_tile_number = tile['ntn']
del tile['ntn']
ntn['tiles'].append(tile)
print 'Merging tiles to single image'
command = ('montage -background transparent "' + new_tileset_name + '/tiles/to_merge/tile-*.png" -tile 16x -geometry +0+0 ' +
new_tileset_name + '/' + os.path.basename(otn['file']))
print command
print('Merging tiles to single image')
command = (
'montage -background transparent "' + new_tileset_name + '/tiles/to_merge/tile-*.png" -tile 16x -geometry +0+0 ' +
new_tileset_name + '/' + os.path.basename(otn['file']))
print(command)
if os.system(command):
raise
@@ -258,5 +261,4 @@ with open(new_tileset_name + '/tileset.txt', 'w') as new_tileset_txt_file:
'JSON: ' + new_tileset_name + '/tile_config.json\n' +
'#Tileset Path - Default of gfx/tinytile.png\n' +
'TILESET: ' + new_tileset_name + '/tiles.png\n'
)
)