diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..e9314d8 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +# https://EditorConfig.org + +root = true + +[*] +charset = utf-8 +#insert_final_newline = true +#trim_trailing_whitespace = true + +[*.{py,pyx}] +indent_style = tab +indent_size = 4 diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..748dba3 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,71 @@ +name: Test Deployment + +on: + push: + pull_request: + +jobs: + bundle: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-18.04, macos-10.15, windows-2019] + fail-fast: false + steps: + # Must checkout with v1 so that git describe will work correctly. + # https://github.com/actions/checkout/issues/290 + - uses: actions/checkout@v1 + with: + fetch-depth: 0 + - uses: actions/setup-python@v2 + with: + # Python 3.8 is the last version with Windows 7 support. + python-version: "3.8" + - name: Install APT dependencies + # python-tcod needs libsdl2-dev to build on Linux. + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install libsdl2-dev + - name: Get pip cache dir + id: pip-cache + run: | + echo "::set-output name=dir::$(pip cache dir)" + - name: pip cache + uses: actions/cache@v2 + with: + path: ${{ steps.pip-cache.outputs.dir }} + key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }} + restore-keys: | + ${{ runner.os }}-pip- + - name: Install Pip packages + run: | + python -m pip install -U pip wheel + pip install -r requirements.txt + - name: Compile Cython modules + run: | + python compile_cython_modules.py build_ext --inplace + - name: Run PyInstaller + env: + PYTHONOPTIMIZE: 1 # Enable optimizations as if the -O flag is given. + PYTHONHASHSEED: 42 # Try to ensure deterministic results. + run: | + pyinstaller build.spec + - name: List files + shell: bash + run: | + find dist + - name: Tar files + if: runner.os != 'Windows' + run: | + tar --format=ustar -czvf ${{matrix.os}}.tar.gz dist/reactor-3 + - name: Archive files + if: runner.os == 'Windows' + run: | + Compress-Archive dist/reactor-3 ${{matrix.os}}.zip + - name: 'Upload Artifact' + uses: actions/upload-artifact@v2 + with: + name: dist + path: ${{matrix.os}}.* + retention-days: 30 diff --git a/.gitignore b/.gitignore index 0388d0b..80f8691 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ *.pyd *.pyc +*.pyo *.c *.so *.sh diff --git a/alife/__init__.py b/alife/__init__.py index 2327227..e0091e7 100644 --- a/alife/__init__.py +++ b/alife/__init__.py @@ -6,4 +6,7 @@ # Ended: Probably not for a while # ################################### +# The use of star imports is causing hidden imports of submodules. +# Changing __all__ will break distributions unless the spec file is updated as well. + __all__ = ['action', 'snapshots', 'judgement', 'chunks', 'brain', 'speech', 'stances', 'jobs', 'groups', 'factions', 'camps', 'sight', 'rawparse', 'noise', 'planner'] diff --git a/alife/action.py b/alife/action.py index 2794584..f874dd2 100644 --- a/alife/action.py +++ b/alife/action.py @@ -2,10 +2,10 @@ import life as lfe -import judgement -import movement -import rawparse -import goals +from . import judgement +from . import movement +from . import rawparse +from . import goals import logging @@ -17,7 +17,7 @@ def retrieve(match, **kwargs): if 'list' in match: return match['list'] - print 'Match returned nothing!'*25 + print('Match returned nothing!'*25) #if 'criteria_id' in kwargs: # _criteria = goals.get_criteria(life, ) @@ -112,7 +112,7 @@ def _execute(action): if 'add_to' in _struct: if not _struct['list'][0] in _struct['list']: _struct['add_to'].append(_struct['list'][0]) - print 'LOOK OUT!' * 55, _struct['add_to'] + print('LOOK OUT!' * 55, _struct['add_to']) return True @@ -138,7 +138,7 @@ def _execute(action): if 'filter' in action['args']: _ret_list = [] - for key in _arguments.keys(): + for key in list(_arguments.keys()): if not key in action['kwargs']['arguments']['kwargs']: if 'include' in action['kwargs']['arguments']['kwargs'] and key in action['kwargs']['arguments']['kwargs']['include']: continue @@ -154,11 +154,11 @@ def _execute(action): for entry in _ret_list: _struct['list'].remove(entry) - print 'filter function',_struct['list'] + print('filter function',_struct['list']) return _struct['list'] if 'get_known_alife' in action['args']: - return _struct['life']['know'].keys() + return list(_struct['life']['know'].keys()) if 'track_alife' in action['args']: if not _struct['list']: @@ -167,11 +167,11 @@ def _execute(action): if movement._find_alife(_struct['life'], target=_struct['list'][0]): if not _struct['list'][0] in _struct['add_to']: _struct['add_to'].append(_struct['list'][0]) - print 'FOUND HIM!!!!!!!!!!!' * 50 + print('FOUND HIM!!!!!!!!!!!' * 50) lfe.focus_on(_struct['life']) - print _struct['life']['name'],'Tracking',LIFE[_struct['list'][0]]['name'] - print judgement.can_trust(_struct['life'], _struct['list'][0]) + print(_struct['life']['name'],'Tracking',LIFE[_struct['list'][0]]['name']) + print(judgement.can_trust(_struct['life'], _struct['list'][0])) return True diff --git a/alife/alife_combat.py b/alife/alife_combat.py index b747ff7..dad7eac 100644 --- a/alife/alife_combat.py +++ b/alife/alife_combat.py @@ -3,16 +3,16 @@ import graphics as gfx import life as lfe -import judgement +from . import judgement import bad_numbers -import combat -import speech -import sight -import camps -import brain -import stats +from . import combat +from . import speech +from . import sight +from . import camps +from . import brain +from . import stats import logic -import jobs +from . import jobs import logging diff --git a/alife/alife_cover.py b/alife/alife_cover.py index 73b0a44..ccb5b70 100644 --- a/alife/alife_cover.py +++ b/alife/alife_cover.py @@ -2,11 +2,11 @@ import life as lfe -import judgement -import movement +from . import judgement +from . import movement import bad_numbers -import sight -import brain +from . import sight +from . import brain import logging diff --git a/alife/alife_discover.py b/alife/alife_discover.py index 873124d..e40d429 100644 --- a/alife/alife_discover.py +++ b/alife/alife_discover.py @@ -2,11 +2,11 @@ import life as lfe -import judgement -import survival -import chunks -import sight -import brain +from . import judgement +from . import survival +from . import chunks +from . import sight +from . import brain import smp import logging diff --git a/alife/alife_escape.py b/alife/alife_escape.py index 735c08d..cb1d8a3 100644 --- a/alife/alife_escape.py +++ b/alife/alife_escape.py @@ -2,10 +2,10 @@ import life as lfe -import judgement -import movement -import sight -import brain +from . import judgement +from . import movement +from . import sight +from . import brain import logging diff --git a/alife/alife_explore.py b/alife/alife_explore.py index 08305b0..21a031a 100644 --- a/alife/alife_explore.py +++ b/alife/alife_explore.py @@ -4,11 +4,11 @@ import life as lfe -import judgement -import survival -import chunks -import sight -import brain +from . import judgement +from . import survival +from . import chunks +from . import sight +from . import brain import logging diff --git a/alife/alife_follow.py b/alife/alife_follow.py index 79d69fe..d600dff 100644 --- a/alife/alife_follow.py +++ b/alife/alife_follow.py @@ -2,9 +2,9 @@ import life as lfe -import judgement -import movement -import sight +from . import judgement +from . import movement +from . import sight def tick(life): diff --git a/alife/alife_group.py b/alife/alife_group.py index b0abd4f..555fa0d 100644 --- a/alife/alife_group.py +++ b/alife/alife_group.py @@ -2,15 +2,15 @@ import life as lfe -import judgement -import movement -import groups -import speech -import action +from . import judgement +from . import movement +from . import groups +from . import speech +from . import action import events -import brain -import stats -import jobs +from . import brain +from . import stats +from . import jobs def setup(life): diff --git a/alife/alife_guard.py b/alife/alife_guard.py index 0298d2e..e3a9935 100644 --- a/alife/alife_guard.py +++ b/alife/alife_guard.py @@ -2,9 +2,9 @@ import life as lfe -import judgement -import movement -import brain +from . import judgement +from . import movement +from . import brain import logging diff --git a/alife/alife_hidden.py b/alife/alife_hidden.py index 431c61c..fa99e8d 100644 --- a/alife/alife_hidden.py +++ b/alife/alife_hidden.py @@ -4,9 +4,9 @@ import life as lfe -import judgement -import movement -import combat +from . import judgement +from . import movement +from . import combat import logging diff --git a/alife/alife_manage_items.py b/alife/alife_manage_items.py index d9a3b8d..e4d3809 100644 --- a/alife/alife_manage_items.py +++ b/alife/alife_manage_items.py @@ -2,8 +2,8 @@ import life as lfe -import judgement -import survival +from . import judgement +from . import survival import logging diff --git a/alife/alife_manage_targets.py b/alife/alife_manage_targets.py index b54faa2..4ea762d 100644 --- a/alife/alife_manage_targets.py +++ b/alife/alife_manage_targets.py @@ -2,7 +2,7 @@ import life as lfe import alife -import raids +from . import raids TIER = TIER_PASSIVE diff --git a/alife/alife_needs.py b/alife/alife_needs.py index baa073c..7405292 100644 --- a/alife/alife_needs.py +++ b/alife/alife_needs.py @@ -2,10 +2,10 @@ import life as lfe -import judgement -import movement -import survival -import brain +from . import judgement +from . import movement +from . import survival +from . import brain def setup(life): @@ -13,7 +13,7 @@ def setup(life): _needs_to_satisfy = [] _needs_unmet = [] - for need in life['needs'].values(): + for need in list(life['needs'].values()): if not survival.needs_to_satisfy(life, need): continue diff --git a/alife/alife_search.py b/alife/alife_search.py index e29678f..e9b4b52 100644 --- a/alife/alife_search.py +++ b/alife/alife_search.py @@ -2,13 +2,13 @@ import life as lfe -import judgement -import movement +from . import judgement +from . import movement import bad_numbers -import speech -import camps -import brain -import jobs +from . import speech +from . import camps +from . import brain +from . import jobs import logging @@ -27,7 +27,7 @@ def conditions(life, alife_seen, alife_not_seen, targets_seen, targets_not_seen, if not _lost_targets: return False else: - print life['name'], _lost_targets + print(life['name'], _lost_targets) return RETURN_VALUE diff --git a/alife/alife_shelter.py b/alife/alife_shelter.py index 70e8371..e3d8e58 100644 --- a/alife/alife_shelter.py +++ b/alife/alife_shelter.py @@ -2,10 +2,10 @@ import life as lfe -import references -import judgement -import chunks -import goals +from . import references +from . import judgement +from . import chunks +from . import goals import maps import random diff --git a/alife/alife_surrender.py b/alife/alife_surrender.py index a516965..1a65651 100644 --- a/alife/alife_surrender.py +++ b/alife/alife_surrender.py @@ -2,11 +2,11 @@ import life as lfe -import judgement +from . import judgement import bad_numbers -import speech -import brain -import stats +from . import speech +from . import brain +from . import stats import logging diff --git a/alife/alife_talk.py b/alife/alife_talk.py index f9dd25b..d8cb408 100644 --- a/alife/alife_talk.py +++ b/alife/alife_talk.py @@ -1,18 +1,18 @@ from globals import * import life as lfe -import judgement -import movement +from . import judgement +from . import movement import bad_numbers import dialog -import speech -import groups -import memory -import stats -import raids -import brain -import camps -import jobs +from . import speech +from . import groups +from . import memory +from . import stats +from . import raids +from . import brain +from . import camps +from . import jobs import logging import random diff --git a/alife/alife_work.py b/alife/alife_work.py index b70db53..683a35c 100644 --- a/alife/alife_work.py +++ b/alife/alife_work.py @@ -7,4 +7,4 @@ def tick(life): if life['missions']: - missions.do_mission(life, life['missions'].keys()[0]) + missions.do_mission(life, list(life['missions'].keys())[0]) diff --git a/alife/brain.py b/alife/brain.py index 0141faa..b0d28bd 100644 --- a/alife/brain.py +++ b/alife/brain.py @@ -2,24 +2,24 @@ import life as lfe -import alife_group -import alife_needs -import alife_talk - -import snapshots -import judgement -import survival -import movement -import factions -import planner +from . import alife_group +from . import alife_needs +from . import alife_talk + +from . import snapshots +from . import judgement +from . import survival +from . import movement +from . import factions +from . import planner import bad_numbers -import memory -import speech -import combat -import stats +from . import memory +from . import speech +from . import combat +from . import stats import logic -import sight -import sound +from . import sight +from . import sound import logging import time @@ -99,7 +99,7 @@ def flag_item(life, item, flag, value=True): remember_item(life, item) if not flag in life['know_items'][item['uid']]['flags']: - print life['know_items'][item['uid']] + print(life['know_items'][item['uid']]) life['know_items'][item['uid']]['flags'][flag] = value logging.debug('%s flagged item %s with %s' % (' '.join(life['name']),item['uid'],flag)) @@ -242,7 +242,7 @@ def get_matching_remembered_items(life, matches, no_owner=False, active=True, on if 'type' in matches and matches['type'] in life['known_items_type_cache']: _remembered_items = [life['know_items'][i] for i in life['known_items_type_cache'][matches['type']]] else: - _remembered_items = life['know_items'].values() + _remembered_items = list(life['know_items'].values()) for item in _remembered_items: _item = ITEMS[item['item']] diff --git a/alife/camps.py b/alife/camps.py index 1e7343a..72f331a 100644 --- a/alife/camps.py +++ b/alife/camps.py @@ -2,18 +2,18 @@ import life as lfe -import references -import judgement +from . import references +from . import judgement import language -import survival -import movement +from . import survival +from . import movement import bad_numbers -import speech -import chunks -import groups -import brain -import stats -import jobs +from . import speech +from . import chunks +from . import groups +from . import brain +from . import stats +from . import jobs import logging import random @@ -68,7 +68,7 @@ def _get_nearest_known_camp(life): for camp in [life['known_camps'][i] for i in life['known_camps']]: _key = references.find_nearest_key_in_reference(life, get_camp(camp['id'])['reference']) - _center = [int(val)+(WORLD_INFO['chunk_size']/2) for val in _key.split(',')] + _center = [int(val)+(WORLD_INFO['chunk_size']//2) for val in _key.split(',')] _distance = bad_numbers.distance(life['pos'], _center) @@ -85,7 +85,7 @@ def get_distance_to_nearest_known_camp(life): return _get_nearest_known_camp(life)['score'] def get_camp_via_reference(reference): - for camp in CAMPS.values(): + for camp in list(CAMPS.values()): if camp['reference'] == reference: return camp['id'] @@ -107,7 +107,7 @@ def get_controlling_groups(camp_id): def get_controlling_group_global(camp_id): _groups = get_controlling_groups(camp_id) - _groups_controlling = [_grp['id'] for _grp in _groups.values() if _grp['score'] == max([_grp['score'] for _grp in _groups.values()])] + _groups_controlling = [_grp['id'] for _grp in list(_groups.values()) if _grp['score'] == max([_grp['score'] for _grp in list(_groups.values())])] if _groups_controlling: return _groups_controlling[0] @@ -125,13 +125,13 @@ def get_controlling_group_according_to(life, camp_id): return _best_group['group'] def get_all_alife_in_camp(camp_id): - return [life['id'] for life in LIFE.values() if is_in_camp(life, WORLD_INFO['camps'][camp_id])] + return [life['id'] for life in list(LIFE.values()) if is_in_camp(life, WORLD_INFO['camps'][camp_id])] def is_in_camp(life, camp): return references.life_is_in_reference(life, camp['reference']) def is_in_any_camp(position): - for camp in WORLD_INFO['camps'].values(): + for camp in list(WORLD_INFO['camps'].values()): if references.is_in_reference(position, camp['reference']): return camp['id'] @@ -164,9 +164,9 @@ def debug_camps(): if not _group: continue - print camp_id, 'is controlled by', _group + print(camp_id, 'is controlled by', _group) _actual_group = groups.get_group(life, _group) - print '\t%s member(s)' % len(_actual_group['members']) + print('\t%s member(s)' % len(_actual_group['members'])) #def get_camp_jobs(camp_id): # _jobs = [] diff --git a/alife/chunks.py b/alife/chunks.py index ee7c64d..805b459 100644 --- a/alife/chunks.py +++ b/alife/chunks.py @@ -1,10 +1,10 @@ from globals import * import life as lfe -import references -import judgement +from . import references +from . import judgement import logic -import sight +from . import sight import maps import logging @@ -45,22 +45,22 @@ def get_chunk(chunk_key): return maps.get_chunk(chunk_key) def get_chunk_from_cache(pos): - _chunk_key = '%s,%s' % ((pos[0]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], (pos[1]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']) + _chunk_key = '%s,%s' % ((pos[0]//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], (pos[1]//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']) return WORLD_INFO['chunk_map'][_chunk_key] def get_chunk_pos(chunk_id, center=False): if center: - return [int(val)+(map_gen['chunk_size']/2) for val in chunk_id.split(',')] + return [int(val)+(map_gen['chunk_size']//2) for val in chunk_id.split(',')] return [int(val) for val in chunk_id.split(',')] def get_chunks_in_range(x_mod_min, x_mod_max, y_mod_min, y_mod_max, x_buffer=0, y_buffer=0): _chunk_keys = [] - print int(round(MAP_SIZE[1]*y_mod_min))+y_buffer, int(round(MAP_SIZE[1]*y_mod_max))-y_buffer - print range(int(round(MAP_SIZE[1]*y_mod_min))+y_buffer, int(round(MAP_SIZE[1]*y_mod_max))-y_buffer, WORLD_INFO['chunk_size']) - print range(int(round(MAP_SIZE[0]*x_mod_min))+x_buffer, int(round(MAP_SIZE[0]*x_mod_max))-x_buffer, WORLD_INFO['chunk_size']) + print(int(round(MAP_SIZE[1]*y_mod_min))+y_buffer, int(round(MAP_SIZE[1]*y_mod_max))-y_buffer) + print(list(range(int(round(MAP_SIZE[1]*y_mod_min))+y_buffer, int(round(MAP_SIZE[1]*y_mod_max))-y_buffer, WORLD_INFO['chunk_size']))) + print(list(range(int(round(MAP_SIZE[0]*x_mod_min))+x_buffer, int(round(MAP_SIZE[0]*x_mod_max))-x_buffer, WORLD_INFO['chunk_size']))) for y in range(int(round(MAP_SIZE[1]*y_mod_min))+y_buffer, int(round(MAP_SIZE[1]*y_mod_max))-y_buffer, WORLD_INFO['chunk_size']): for x in range(int(round(MAP_SIZE[0]*x_mod_min))+x_buffer, int(round(MAP_SIZE[0]*x_mod_max))-x_buffer, WORLD_INFO['chunk_size']): @@ -72,7 +72,7 @@ def get_visible_chunks_from(pos, vision, center=True): _center_chunk_key = get_chunk_key_at(pos) if center: - _pos = [int(i)+WORLD_INFO['chunk_size']/2 for i in _center_chunk_key.split(',')] + _pos = [int(i)+WORLD_INFO['chunk_size']//2 for i in _center_chunk_key.split(',')] _pos.append(pos[2]) pos = _pos[:] @@ -89,7 +89,7 @@ def get_visible_chunks_from(pos, vision, center=True): return _chunk_keys def get_chunk_key_at(pos): - return '%s,%s' % ((pos[0]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], (pos[1]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']) + return '%s,%s' % ((pos[0]//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], (pos[1]//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']) def find_best_chunk(life, ignore_starting=False, ignore_time=False, lost_method=None, only_unvisted=False, only_unseen=False, only_recent=False): _interesting_chunks = {} @@ -123,7 +123,7 @@ def find_best_chunk(life, ignore_starting=False, ignore_time=False, lost_method= if only_recent: _recent = -1 - for chunk_key in _interesting_chunks.keys(): + for chunk_key in list(_interesting_chunks.keys()): chunk = _interesting_chunks[chunk_key] if chunk['discovered_at']>_recent: @@ -139,7 +139,7 @@ def find_best_chunk(life, ignore_starting=False, ignore_time=False, lost_method= continue if lost_method == 'furthest': - chunk_center = [int(val)+(WORLD_INFO['chunk_size']/2) for val in chunk_key.split(',')] + chunk_center = [int(val)+(WORLD_INFO['chunk_size']//2) for val in chunk_key.split(',')] _score = bad_numbers.distance(life['pos'], chunk_center) if ignore_starting and chunk_key == lfe.get_current_chunk_id(life): @@ -160,7 +160,7 @@ def find_best_chunk(life, ignore_starting=False, ignore_time=False, lost_method= # if chunk_key in life['known_chunks']: # continue # -# chunk_center = [int(val)+(WORLD_INFO['chunk_size']/2) for val in chunk_key.split(',')] +# chunk_center = [int(val)+(WORLD_INFO['chunk_size']//2) for val in chunk_key.split(',')] # _distance = bad_numbers.distance(life['pos'], chunk_center) # # if not _nearest['key'] or _distance<_nearest['distance']: @@ -226,7 +226,7 @@ def _get_nearest_chunk_in_list(pos, chunks, check_these_chunks_first=[]): if not chunk_key in chunks: continue - chunk_center = [int(val)+(WORLD_INFO['chunk_size']/2) for val in chunk_key.split(',')] + chunk_center = [int(val)+(WORLD_INFO['chunk_size']//2) for val in chunk_key.split(',')] _dist = bad_numbers.distance(pos, chunk_center) if not _nearest_chunk['chunk_key'] or _dist < _nearest_chunk['distance']: @@ -237,7 +237,7 @@ def _get_nearest_chunk_in_list(pos, chunks, check_these_chunks_first=[]): return _nearest_chunk for chunk_key in chunks: - chunk_center = [int(val)+(WORLD_INFO['chunk_size']/2) for val in chunk_key.split(',')] + chunk_center = [int(val)+(WORLD_INFO['chunk_size']//2) for val in chunk_key.split(',')] _dist = bad_numbers.distance(pos, chunk_center) if not _nearest_chunk['chunk_key'] or _dist < _nearest_chunk['distance']: @@ -283,8 +283,8 @@ def can_see_chunk(life, chunk_key, distance=True, center_chunk=False): _pos = life['pos'][:] if center_chunk: - _pos[0] = ((_pos[0]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'])+WORLD_INFO['chunk_size']/2 - _pos[1] = ((_pos[1]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'])+WORLD_INFO['chunk_size']/2 + _pos[0] = ((_pos[0]//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'])+WORLD_INFO['chunk_size']//2 + _pos[1] = ((_pos[1]//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'])+WORLD_INFO['chunk_size']//2 return can_see_chunk_from_pos(_pos, chunk_key, distance=distance, vision=sight.get_vision(life)) diff --git a/alife/combat.py b/alife/combat.py index c3ba793..f3fe6eb 100644 --- a/alife/combat.py +++ b/alife/combat.py @@ -2,17 +2,17 @@ import life as lfe -import judgement -import movement +from . import judgement +from . import movement import weapons -import speech +from . import speech import melee import zones import items -import sight -import stats -import brain -import jobs +from . import sight +from . import stats +from . import brain +from . import jobs import bad_numbers import logging @@ -25,7 +25,7 @@ def get_engage_distance(life): if _weapons: return bad_numbers.clip(int(round(ITEMS[_weapons[0]]['accuracy']*29)), 3, sight.get_vision(life)) else: - return sight.get_vision(life)/2 + return sight.get_vision(life)//2 def weapon_is_working(life, item_uid): _weapon = ITEMS[item_uid] @@ -104,9 +104,9 @@ def load_feed(life, weapon_uid, feed_uid): def _get_feed(life, weapon): _feeds = lfe.get_all_inventory_items(life, matches=[{'type': weapon['feed'], 'ammotype': weapon['ammotype']}], ignore_actions=False) - _highest_feed = {'rounds': -1, 'feed': None} + _highest_feed = {'rounds': [], 'feed': None} for feed in [lfe.get_inventory_item(life, _feed['uid']) for _feed in _feeds]: - if feed['rounds']>_highest_feed['rounds']: + if len(feed['rounds']) > len(_highest_feed['rounds']): _highest_feed['rounds'] = feed['rounds'] _highest_feed['feed'] = feed @@ -140,7 +140,7 @@ def _refill_feed(life, feed): _rounds = len(feed['rounds']) if _rounds>=feed['maxrounds'] or (not _bullets_in_inventory and _rounds): - print 'Full?' + print('Full?') return True _ammo_count = len(lfe.get_all_inventory_items(life,matches=[{'type': 'bullet', 'ammotype': feed['ammotype']}])) @@ -168,13 +168,13 @@ def _equip_weapon(life, weapon_uid, feed_uid): if _refill_feed(life, _feed): load_feed(life, _weapon['uid'], _feed['uid']) else: - print 'should be equippan?' + print('should be equippan?') lfe.add_action(life,{'action': 'equipitem', 'item': weapon_uid}, 300, delay=0) - print 'Loaded!' + print('Loaded!') return True return True diff --git a/alife/goals.py b/alife/goals.py index b6256e3..0ff3472 100644 --- a/alife/goals.py +++ b/alife/goals.py @@ -2,19 +2,19 @@ import life as lfe -import action +from . import action import traceback import logging import sys def has_goal(life, name): - return [g for g in life['goals'].values() if g['name'] == name] + return [g for g in list(life['goals'].values()) if g['name'] == name] def get_active_goals(life): _active = [] - for goal in [g for g in life['goals'].values() if not g['complete']]: + for goal in [g for g in list(life['goals'].values()) if not g['complete']]: if perform_goal(life, goal['id'], only_required=True): _active.append(goal['id']) @@ -140,21 +140,21 @@ def check_for_goal_finish(life, goal_id, passed=False): for question in _goal['complete_on_answer']: if lfe.get_memory_via_id(life, question)['answered']: - print 'DELETED GOAL!' * 100 + print('DELETED GOAL!' * 100) _goal['complete'] = True break if passed: - print 'DELETED GOAL!' * 100 + print('DELETED GOAL!' * 100) _goal['complete'] = True - print 'FINISHED GOAL' * 50 + print('FINISHED GOAL' * 50) def perform_goal(life, goal_id, only_required=False): _goal = get_goal_via_id(life, goal_id) _passed = True - for criteria in _goal['criteria'].values(): + for criteria in list(_goal['criteria'].values()): if only_required and not criteria['required']: continue @@ -171,7 +171,7 @@ def perform_goal(life, goal_id, only_required=False): criteria['result'] = _process if not criteria['result']: - print 'Goal not met', life['name'], criteria + print('Goal not met', life['name'], criteria) _passed = False continue else: @@ -217,9 +217,9 @@ def process_criteria(life, goal_id, criteria_id, result): _criteria['result'] = action.execute(sub_criteria['filter_action']) if _criteria['result']: - print 'Sub-criteria passed:', sub_criteria + print('Sub-criteria passed:', sub_criteria) else: - print 'Sub-criteria failed:', sub_criteria + print('Sub-criteria failed:', sub_criteria) break return _criteria['result'] diff --git a/alife/groups.py b/alife/groups.py index c5f9496..ee427e3 100644 --- a/alife/groups.py +++ b/alife/groups.py @@ -3,25 +3,25 @@ import graphics as gfx import life as lfe -import references -import judgement -import movement -import survival -import factions +from . import references +from . import judgement +from . import movement +from . import survival +from . import factions import bad_numbers -import memory -import action -import combat -import speech +from . import memory +from . import action +from . import combat +from . import speech import events -import chunks +from . import chunks import logic -import sight -import camps -import brain -import stats -import raids -import jobs +from . import sight +from . import camps +from . import brain +from . import stats +from . import raids +from . import jobs import logging import random @@ -215,7 +215,7 @@ def get_event(life, group_id, event_id): def process_events(life, group_id): _group = get_group(life, group_id) - for event in _group['events'].values(): + for event in list(_group['events'].values()): events.process_event(event) def announce(life, _group_id, gist, message='', order=False, consider_motive=False, filter_if=None, **kwargs): @@ -225,7 +225,7 @@ def announce(life, _group_id, gist, message='', order=False, consider_motive=Fal if _group['claimed_motive'] == 'wealth': _announce_to = [] - for life_id in LIFE.keys(): + for life_id in list(LIFE.keys()): if life_id == life['id']: continue @@ -241,7 +241,7 @@ def announce(life, _group_id, gist, message='', order=False, consider_motive=Fal elif _group['claimed_motive'] == 'survival': _announce_to = [] - for life_id in LIFE.keys(): + for life_id in list(LIFE.keys()): if life_id == life['id']: continue @@ -460,9 +460,9 @@ def get_jobs(life, group_id): _lowest['group'] = group_id - print 'RAID', _lowest + print('RAID', _lowest) else: - print 'ony one' + print('ony one') return _jobs @@ -554,7 +554,7 @@ def manage_territory(life, group_id): _distance = chunks.get_distance_to_nearest_chunk_in_list(WORLD_INFO['chunk_map'][_shelter_chunk]['pos'], factions.get_territory(_opposing_shelter)['chunk_keys']) if _distance<=30: - print '2 CLOSE 2 HANDLE' + print('2 CLOSE 2 HANDLE') def manage_raid(life, group_id): if not get_stage(life, group_id) in [STAGE_RAIDING, STAGE_ATTACKING]: @@ -569,7 +569,7 @@ def manage_raid(life, group_id): flag(life, group_id, 'announced_raid_location', _raid_chunk_key) lfe.memory(life, 'focus_on_chunk', chunk_key=_raid_chunk_key) - print 'RAID LOCATION SET' * 100 + print('RAID LOCATION SET' * 100) def manage_combat(life, group_id): if has_flag(life, group_id, 'confident'): @@ -773,7 +773,7 @@ def get_possible_group_location(life, group_id): _most_recent['time'] = _target['last_seen_time'] if not _most_recent['shelter']: - print 'STILL DO NOT HAVE TARGET GROUP LOCATION' + print('STILL DO NOT HAVE TARGET GROUP LOCATION') return _most_recent['shelter'] diff --git a/alife/jobs.py b/alife/jobs.py index 13ea88e..9dbe3dd 100644 --- a/alife/jobs.py +++ b/alife/jobs.py @@ -7,7 +7,7 @@ #import dialog #import speech #import brain -import action +from . import action import logging @@ -82,7 +82,7 @@ def reset_job(job_id): _job['workers'] = [] _job['completed'] = False - for task in _job['tasks'].values(): + for task in list(_job['tasks'].values()): task['completed'] = False task['requires'] = _task['_required'][:] diff --git a/alife/judgement.py b/alife/judgement.py index 1dff03a..f7646c0 100644 --- a/alife/judgement.py +++ b/alife/judgement.py @@ -2,20 +2,20 @@ import life as lfe -import references -import factions +from . import references +from . import factions import weapons -import chunks -import combat -import groups +from . import chunks +from . import combat +from . import groups import zones -import stats -import brain -import raids -import sight -import camps +from . import stats +from . import brain +from . import raids +from . import sight +from . import camps import logic -import jobs +from . import jobs import logging import bad_numbers @@ -98,7 +98,7 @@ def get_ranged_combat_ready_score(life, consider_target_id=None): if consider_target_id: _target = brain.knows_alife_by_id(life, consider_target_id) #TODO: Judge proper distance based on weapon equip time - if bad_numbers.distance(life['pos'], _target['last_seen_at']) combat.get_engage_distance(target): - _score += item['accuracy']/2 + _score += item['accuracy']//2 else: _score += item['accuracy'] @@ -303,7 +303,7 @@ def is_scared(life): continue if _knows['alignment'] == 'scared' and not _knows['asleep'] and not _knows['dead']: - print life['name'], 'is scared' + print(life['name'], 'is scared') return True return False @@ -311,7 +311,7 @@ def is_scared(life): def get_trusted(life, visible=True, only_recent=False): _trusted = [] - for target in life['know'].values(): + for target in list(life['know'].values()): if can_trust(life, target['life']['id']): if only_recent and target['last_seen_time']>=150: continue @@ -404,7 +404,7 @@ def get_threats(life, escaped_only=False, ignore_lost=True, ignore_escaped=True, return _target_filter(life, brain.retrieve_from_memory(life, 'threats'), escaped_only, ignore_escaped, ignore_lost=ignore_lost, recent_only=recent_only, limit_distance=limit_distance, filter_func=filter_func) def get_target_to_follow(life): - _highest = {'id': None, 'score': 0} + _highest = {'id': 0, 'score': 0} for target_id in get_trusted(life, visible=False, only_recent=False): if not lfe.execute_raw(life, 'follow', 'follow_target_if', life_id=target_id): @@ -437,10 +437,10 @@ def get_target_to_guard(life): return target_id - return None + return 0 def get_nearest_threat(life): - _target = {'target': None, 'score': 9999} + _target = {'target': 0, 'score': 9999} #_combat_targets = brain.retrieve_from_memory(life, 'combat_targets') #if not _combat_targets: @@ -550,7 +550,7 @@ def judge_life(life, target_id): # print '%s danger in %s: %s -> %s' % (' '.join(life['name']), ' '.join(target['life']['name']), _old_danger, target['danger']) if not _old_trust == target['trust']: - print '%s trust in %s: %s -> %s' % (' '.join(life['name']), ' '.join(target['life']['name']), _old_trust, target['trust']) + print('%s trust in %s: %s -> %s' % (' '.join(life['name']), ' '.join(target['life']['name']), _old_trust, target['trust'])) def judge_search_pos(life, pos): return lfe.execute_raw(life, 'search', 'judge', break_on_true=True, pos1=life['pos'], pos2=pos) @@ -645,7 +645,7 @@ def judge_chunk(life, chunk_id, visited=False, seen=False, checked=True, investi _known_chunk['last_checked'] = WORLD_INFO['ticks'] _trusted = 0 - for _target in life['know'].values(): + for _target in list(life['know'].values()): if not _target['last_seen_at']: continue @@ -730,8 +730,8 @@ def judge_reference(life, reference_id, known_penalty=False): _count += 1 _chunk = maps.get_chunk(key) - _chunk_center = (_chunk['pos'][0]+(WORLD_INFO['chunk_size']/2), - _chunk['pos'][1]+(WORLD_INFO['chunk_size']/2)) + _chunk_center = (_chunk['pos'][0]+(WORLD_INFO['chunk_size']//2), + _chunk['pos'][1]+(WORLD_INFO['chunk_size']//2)) _distance = bad_numbers.distance(life['pos'], _chunk_center) if not _closest_chunk_key['key'] or _distance<_closest_chunk_key['distance']: @@ -752,16 +752,16 @@ def judge_reference(life, reference_id, known_penalty=False): #How long since we've been here? #if key in life['known_chunks']: - # _last_visit = bad_numbers.clip(abs((life['known_chunks'][key]['last_visited']-WORLD_INFO['ticks'])/FPS), 2, 99999) + # _last_visit = bad_numbers.clip(abs((life['known_chunks'][key]['last_visited']-WORLD_INFO['ticks'])//FPS), 2, 99999) # _score += _last_visit #else: - # _score += WORLD_INFO['ticks']/FPS + # _score += WORLD_INFO['ticks']//FPS #Take length into account _score += _count #Subtract distance in chunks - _score -= _closest_chunk_key['distance']/WORLD_INFO['chunk_size'] + _score -= _closest_chunk_key['distance']//WORLD_INFO['chunk_size'] #TODO: Average time since last visit (check every key in reference) #TODO: For tracking last visit use world ticks @@ -788,12 +788,12 @@ def judge_camp(life, camp, for_founding=False): #to other camps. This is hardcoded (can't think of a reason why the ALife would want this) if for_founding: - for _known_camp in [c['reference'] for c in life['known_camps'].values()]: + for _known_camp in [c['reference'] for c in list(life['known_camps'].values())]: for _pos1 in _known_camp: pos1 = [int(i) for i in _pos1.split(',')] for _pos2 in camp: pos2 = [int(i) for i in _pos2.split(',')] - _dist = bad_numbers.distance(pos1, pos2) / WORLD_INFO['chunk_size'] + _dist = bad_numbers.distance(pos1, pos2) // WORLD_INFO['chunk_size'] if _dist <= 15: return 0 @@ -802,7 +802,7 @@ def judge_camp(life, camp, for_founding=False): _current_population = 0 _current_trust = 0 - for _target in life['know'].values(): + for _target in list(life['know'].values()): if not references.is_in_reference(_target['last_seen_at'], camp): continue @@ -821,7 +821,7 @@ def judge_camp(life, camp, for_founding=False): _score += judge_group(life, camps.get_controlling_group(_camp)) if stats.desires_to_create_camp(life): - _score += len(groups.get_group(life, life['group'])['members'])/2<=len(_known_chunks_of_camp) + _score += len(groups.get_group(life, life['group'])['members'])//2<=len(_known_chunks_of_camp) #TODO: Why does this cause a crash? #return int(round(_percent_known*10)) @@ -986,19 +986,19 @@ def get_best_shelter(life): if _shelter: _nearest_chunk_key = references.find_nearest_key_in_reference(life, _shelter) - _shelter_center = [int(val)+(WORLD_INFO['chunk_size']/2) for val in _nearest_chunk_key.split(',')] + _shelter_center = [int(val)+(WORLD_INFO['chunk_size']//2) for val in _nearest_chunk_key.split(',')] _dist = bad_numbers.distance(life['pos'], _shelter_center) judge_chunk(life, _nearest_chunk_key) if _dist <= logic.time_until_midnight()*life['speed_max']: - print life['name'],'can get to shelter in time' + print(life['name'],'can get to shelter in time') return _nearest_chunk_key else: - print life['name'],'cant get to shelter in time' + print(life['name'],'cant get to shelter in time') for chunk_key in [chunk_id for chunk_id in life['known_chunks'] if chunks.get_flag(life, chunk_id, 'shelter')]: - chunk_center = [int(val)+(WORLD_INFO['chunk_size']/2) for val in chunk_key.split(',')] + chunk_center = [int(val)+(WORLD_INFO['chunk_size']//2) for val in chunk_key.split(',')] _score = bad_numbers.distance(life['pos'], chunk_center) if not _best_shelter['shelter'] or _score<_best_shelter['distance']: @@ -1008,15 +1008,15 @@ def get_best_shelter(life): return _best_shelter['shelter'] def update_camps(life): - for camp in life['known_camps'].values(): + for camp in list(life['known_camps'].values()): camp['snapshot']['life'] = [] camp['snapshot']['groups'] = {} - for _target in life['know'].values(): + for _target in list(life['know'].values()): if not _target['last_seen_at']: continue - for camp in life['known_camps'].values(): + for camp in list(life['known_camps'].values()): if not camps.position_is_in_camp(_target['last_seen_at'], camp['id']): continue diff --git a/alife/memory.py b/alife/memory.py index ee9afa2..73580ea 100644 --- a/alife/memory.py +++ b/alife/memory.py @@ -2,12 +2,12 @@ import life as lfe -import judgement -import rawparse -import action -import speech -import brain -import jobs +from . import judgement +from . import rawparse +from . import action +from . import speech +from . import brain +from . import jobs import logging @@ -43,11 +43,11 @@ def create_order(life, life_id, order, message, **kwargs): logging.critical('%s does not know %s but is giving orders to them.' % (' '.join(life['name']), ' '.join(LIFE[life_id]['name']))) return False - if _order in _target['orders'].values(): + if _order in list(_target['orders'].values()): return False _order['active'] = False - if _order in _target['orders'].values(): + if _order in list(_target['orders'].values()): return False _order['active'] = True @@ -63,7 +63,7 @@ def get_questions_for_target(life, life_id): def get_orders_for_target(life, life_id, active_only=True): _active_orders = [] - for order in brain.knows_alife_by_id(life, life_id)['orders'].values(): + for order in list(brain.knows_alife_by_id(life, life_id)['orders'].values()): if active_only and not order['active']: continue @@ -107,7 +107,7 @@ def reject_order(life, life_id): def give_target_order_message(life, life_id): _orders = get_orders_for_target(life, life_id) - print life['name'], LIFE[life_id]['name'], 'ORDER MESSAGE', _orders[0]['message'] + print(life['name'], LIFE[life_id]['name'], 'ORDER MESSAGE', _orders[0]['message']) return _orders[0]['message'] def rescore_history(life): diff --git a/alife/movement.py b/alife/movement.py index 188cd10..13c4e25 100644 --- a/alife/movement.py +++ b/alife/movement.py @@ -2,20 +2,20 @@ import life as lfe -import references +from . import references import weapons import bad_numbers -import combat -import speech -import chunks -import memory +from . import combat +from . import speech +from . import chunks +from . import memory import logic import alife import zones -import sight -import brain +from . import sight +from . import brain import maps -import jobs +from . import jobs import fov import random @@ -59,7 +59,7 @@ def position_to_attack(life, target, engage_distance): lfe.add_action(life, {'action': 'dijkstra_move', 'rolldown': True, - 'goals': [list(p) for p in random.sample(_attack_positions, len(_attack_positions)/2)], + 'goals': [list(p) for p in random.sample(_attack_positions, len(_attack_positions)//2)], 'orig_goals': list(_attack_positions), 'avoid_positions': list(_avoid_positions), 'reason': 'positioning for attack'}, @@ -132,7 +132,7 @@ def travel_to_position(life, pos, stop_on_sight=False, force=False): def travel_to_chunk(life, chunk_key): _chunk_pos = maps.get_chunk(chunk_key)['pos'] - return travel_to_position(life, [_chunk_pos[0]+WORLD_INFO['chunk_size']/2, _chunk_pos[1]+WORLD_INFO['chunk_size']/2, 2]) + return travel_to_position(life, [_chunk_pos[0]+WORLD_INFO['chunk_size']//2, _chunk_pos[1]+WORLD_INFO['chunk_size']//2, 2]) def guard_chunk(life, chunk_key): if 'guard_time' in life['state_flags'] and life['state_flags']['guard_time']: @@ -195,8 +195,8 @@ def search_for_target(life, target_id): return False _lowest = {'score': -1, 'pos': None} - _x_top_left = bad_numbers.clip(_know['last_seen_at'][0]-(_size/2), 0, MAP_SIZE[0]) - _y_top_left = bad_numbers.clip(_know['last_seen_at'][1]-(_size/2), 0, MAP_SIZE[1]) + _x_top_left = bad_numbers.clip(_know['last_seen_at'][0]-(_size//2), 0, MAP_SIZE[0]) + _y_top_left = bad_numbers.clip(_know['last_seen_at'][1]-(_size//2), 0, MAP_SIZE[1]) for x in range(0, _size): _x = _x_top_left+x @@ -297,7 +297,7 @@ def hide(life, targets): if not pos in _avoid_positions: _avoid_positions.append(pos) else: - print 'Something went wrong' + print('Something went wrong') return False @@ -358,7 +358,7 @@ def collect_nearby_wanted_items(life, only_visible=True, matches={'type': 'gun'} _empty_hand = lfe.get_open_hands(life) if not _empty_hand: - print 'No open hands, managing....' + print('No open hands, managing....') for item_uid in lfe.get_held_items(life): _container = lfe.can_put_item_in_storage(life, item_uid) diff --git a/alife/noise.py b/alife/noise.py index 6173509..66604eb 100644 --- a/alife/noise.py +++ b/alife/noise.py @@ -8,10 +8,10 @@ import graphics as gfx import language -import judgement +from . import judgement import bad_numbers -import sight -import brain +from . import sight +from . import brain import logging import random @@ -32,7 +32,7 @@ def update_targets_around_noise(life, noise): if 'target' in noise and not life['id'] == noise['target']: _visiblity = bad_numbers.clip(sight.get_stealth_coverage(LIFE[noise['target']]), 0.0, 1.0) - _visiblity = bad_numbers.clip(_visiblity+(bad_numbers.distance(life['pos'], LIFE[noise['target']]['pos']))/(sight.get_vision(life)/2), 0, 1.0) + _visiblity = bad_numbers.clip(_visiblity+(bad_numbers.distance(life['pos'], LIFE[noise['target']]['pos']))//(sight.get_vision(life)//2), 0, 1.0) if _visiblity >= sight.get_visiblity_of_position(life, LIFE[noise['target']]['pos']): brain.meet_alife(life, LIFE[noise['target']]) @@ -41,7 +41,7 @@ def update_targets_around_noise(life, noise): life['know'][noise['target']]['last_seen_at'] = noise['pos'][:] life['know'][noise['target']]['last_seen_time'] = 0 - for target in life['know'].values(): + for target in list(life['know'].values()): if not target['escaped'] or not target['last_seen_at'] or target['dead']: continue @@ -61,7 +61,7 @@ def update_targets_around_noise(life, noise): logging.debug('%s heard a noise, attributing it to %s.' % (' '.join(life['name']), ' '.join(_most_likely_target['target']['life']['name']))) def _spread(noise): - for alife in LIFE.values(): + for alife in list(LIFE.values()): if alife['dead']: continue @@ -82,7 +82,7 @@ def _spread(noise): #TODO: Check walls between positions #TODO: Add memory if not _can_see or not noise['skip_on_visual']: - if _dist >=noise['volume']/2: + if _dist >=noise['volume']//2: if 'player' in alife: gfx.message(random.choice(FAR_TEXT).replace('@t', noise['text'][1]).replace('@d', _direction_string), style='sound') else: diff --git a/alife/planner.py b/alife/planner.py index 0fbd30c..97f9f37 100644 --- a/alife/planner.py +++ b/alife/planner.py @@ -131,7 +131,7 @@ def find_actions_that_satisfy(life, desires, debug=False): continue else: if debug: - print 'action %s failed to meet the desires of %s' % (action, _desire) + print('action %s failed to meet the desires of %s' % (action, _desire)) _break = True break @@ -151,12 +151,12 @@ def find_actions_that_satisfy(life, desires, debug=False): if not FUNCTION_MAP[_requirement](life) == _true: if debug: - print '\tFailed at:%s' % _requirement + print('\tFailed at:%s' % _requirement) _break = True break elif debug: - print '\tPassed:%s' % _requirement + print('\tPassed:%s' % _requirement) if _break: continue @@ -224,7 +224,7 @@ def execute(life, func): break if func == 'set_raid_location': - print 'CHECKS OUT' * 100 + print('CHECKS OUT' * 100) if _self_call: if FUNCTION_MAP[func]() == _true: return True @@ -249,14 +249,14 @@ def execute_plan(life, plan): # raise Exception('Invalid function in life type \'%s\' for action \'%s\': %s' % (life['species'], action, life['goap_actions'][action]['execute'])) def get_next_goal(life, debug=False): - _next_goal = {'highest': None, 'goal': None, 'plan': None} + _next_goal = {'highest': float("-inf"), 'goal': None, 'plan': None} for goal in life['goap_goals']: _break = False if debug == goal: - print - print goal + print() + print(goal) if len(life['goap_goals'][goal]['require'][0]): for requirement in life['goap_goals'][goal]['require']: @@ -279,12 +279,12 @@ def get_next_goal(life, debug=False): _func = FUNCTION_MAP[_requirement](life) if not _func == _true: if debug == goal: - print '\tFailed at:%s' % _requirement + print('\tFailed at:%s' % _requirement) _break = True break elif debug == goal: - print '\tPassed:%s' % _requirement + print('\tPassed:%s' % _requirement) #elif SETTINGS['following'] == life['id']: # print '[state_%s] Requirement passed: %s (wanted %s)' % (goal, _requirement, _true) # print FUNCTION_MAP[_requirement](life) diff --git a/alife/raids.py b/alife/raids.py index 691d718..05ab750 100644 --- a/alife/raids.py +++ b/alife/raids.py @@ -2,8 +2,8 @@ import life as lfe -import camps -import brain +from . import camps +from . import brain import logging diff --git a/alife/rawparse.py b/alife/rawparse.py index 8942bb6..6d12cfe 100644 --- a/alife/rawparse.py +++ b/alife/rawparse.py @@ -2,36 +2,36 @@ import life as lfe -import alife_manage_items -import alife_discover -import alife_shelter -import alife_escape -import alife_search -import alife_combat -import alife_follow -import alife_cover -import alife_needs -import alife_work +from . import alife_manage_items +from . import alife_discover +from . import alife_shelter +from . import alife_escape +from . import alife_search +from . import alife_combat +from . import alife_follow +from . import alife_cover +from . import alife_needs +from . import alife_work -import references -import judgement +from . import references +from . import judgement import missions -import survival -import movement -import factions +from . import survival +from . import movement +from . import factions import bad_numbers -import memory -import groups -import combat -import chunks -import speech +from . import memory +from . import groups +from . import combat +from . import chunks +from . import speech import dialog -import brain +from . import brain import items -import stats +from . import stats import logic -import sight -import jobs +from . import sight +from . import jobs import logging import re @@ -397,10 +397,10 @@ def raw_section_has_identifier(life, section, identifier): return False def get_raw_sections(life): - return life['raw']['sections'].keys() + return list(life['raw']['sections'].keys()) def get_raw_identifiers(life, section): - return life['raw']['sections'][section].keys() + return list(life['raw']['sections'][section].keys()) def get_arguments(life, section, identifier): return life['raw']['sections'][section][identifier] diff --git a/alife/references.py b/alife/references.py index 714ebd5..168370e 100644 --- a/alife/references.py +++ b/alife/references.py @@ -2,9 +2,9 @@ import life as lfe -import judgement +from . import judgement import mapgen -import chunks +from . import chunks import alife import maps @@ -31,7 +31,7 @@ def _find_nearest_reference(life, ref_type, skip_current=False, skip_known=False if skip_unknown and not _nearest_key in life['known_chunks']: continue - _center = [int(val)+(WORLD_INFO['chunk_size']/2) for val in _nearest_key.split(',')] + _center = [int(val)+(WORLD_INFO['chunk_size']//2) for val in _nearest_key.split(',')] _distance = bad_numbers.distance(life['pos'], _center) if not _lowest['chunk_key'] or _distance<_lowest['distance']: @@ -49,7 +49,7 @@ def _find_nearest_reference_exact(position, ref_type=None): continue for reference in WORLD_INFO['reference_map'][_r_type]: - _center = [int(val)+(WORLD_INFO['chunk_size']/2) for val in _nearest_key.split(',')] + _center = [int(val)+(WORLD_INFO['chunk_size']//2) for val in _nearest_key.split(',')] _distance = bad_numbers.distance(position, _center) _nearest_key = find_nearest_key_in_reference_exact(position, reference) @@ -65,7 +65,7 @@ def _find_nearest_reference_type_exact(position, ref_type=None): for chunk_keys in WORLD_INFO['refs'][ref_type]: _nearest_chunk_key = chunks.get_nearest_chunk_in_list(position, chunk_keys) - _center = [int(val)+(WORLD_INFO['chunk_size']/2) for val in _nearest_chunk_key.split(',')] + _center = [int(val)+(WORLD_INFO['chunk_size']//2) for val in _nearest_chunk_key.split(',')] _distance = bad_numbers.distance(position, _center) if not _lowest['chunk_key'] or _distance<_lowest['distance']: @@ -86,7 +86,7 @@ def _find_best_unknown_reference(life, ref_type): _chunk_key = find_nearest_key_in_reference(life, reference) - if bad_numbers.distance(life['pos'], maps.get_chunk(_chunk_key)['pos'])/WORLD_INFO['chunk_size']>10: + if bad_numbers.distance(life['pos'], maps.get_chunk(_chunk_key)['pos'])//WORLD_INFO['chunk_size']>10: continue if not _best_reference['reference'] or _score>_best_reference['score']: @@ -117,13 +117,13 @@ def find_nearest_key_in_reference(life, reference_id, unknown=False, ignore_curr continue if ignore_current and lfe.get_current_chunk_id(life) == _key: - print 'ignoring current' + print('ignoring current') continue if not maps.get_chunk(_key)['ground']: continue - _center = [int(val)+(WORLD_INFO['chunk_size']/2) for val in _key.split(',')] + _center = [int(val)+(WORLD_INFO['chunk_size']//2) for val in _key.split(',')] _distance = bad_numbers.distance(life['pos'], _center) if not _lowest['chunk_key'] or _distance<_lowest['distance']: @@ -142,7 +142,7 @@ def find_nearest_key_in_reference_exact(position, reference): if not maps.get_chunk(_key)['ground']: continue - _center = [int(val)+(WORLD_INFO['chunk_size']/2) for val in _key.split(',')] + _center = [int(val)+(WORLD_INFO['chunk_size']//2) for val in _key.split(',')] _distance = bad_numbers.distance(position, _center) if not _lowest['chunk_key'] or _distance<_lowest['distance']: @@ -181,9 +181,9 @@ def path_along_reference(life, ref_type): if maps.get_chunk(neighbor_key) == lfe.get_current_chunk(life): continue - _neighbor_pos = [int(val)+(WORLD_INFO['chunk_size']/2) for val in neighbor_key.split(',')] - _cent = (lfe.get_current_chunk(life)['pos'][0]+(WORLD_INFO['chunk_size']/2), - lfe.get_current_chunk(life)['pos'][1]+(WORLD_INFO['chunk_size']/2)) + _neighbor_pos = [int(val)+(WORLD_INFO['chunk_size']//2) for val in neighbor_key.split(',')] + _cent = (lfe.get_current_chunk(life)['pos'][0]+(WORLD_INFO['chunk_size']//2), + lfe.get_current_chunk(life)['pos'][1]+(WORLD_INFO['chunk_size']//2)) _neighbor_direction = bad_numbers.direction_to(_cent, _neighbor_pos) _directions[_neighbor_direction] = {'key': neighbor_key, 'score': 9999} @@ -200,7 +200,7 @@ def path_along_reference(life, ref_type): if _directions[_new_dir]['key'] in life['known_chunks']: continue - _score += (180-(abs(_new_dir-life['discover_direction'])))/45 + _score += (180-(abs(_new_dir-life['discover_direction'])))//45 _score += life['discover_direction_history'].count(_new_dir) if _score>=_best_dir['score']: diff --git a/alife/sight.py b/alife/sight.py index 6dd7973..369fa92 100644 --- a/alife/sight.py +++ b/alife/sight.py @@ -5,12 +5,12 @@ import life as lfe from overwatch import core -import judgement +from . import judgement import weather -import groups -import chunks -import combat -import brain +from . import groups +from . import chunks +from . import combat +from . import brain import logic import items import maps @@ -59,7 +59,7 @@ def look(life): #This is for optimizing. Be careful if you mess with this... _nearby_alife = {} - for alife in LIFE.values(): + for alife in list(LIFE.values()): if alife['id'] == life['id']: continue @@ -180,10 +180,10 @@ def quick_look(life): _items = [] _current_chunk = lfe.get_current_chunk_id(life) _current_chunk_pos = chunks.get_chunk(_current_chunk)['pos'] - _x_chunk_min = bad_numbers.clip(_current_chunk_pos[0]-((get_vision(life)/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']), 0, MAP_SIZE[0]-WORLD_INFO['chunk_size']) - _y_chunk_min = bad_numbers.clip(_current_chunk_pos[1]-((get_vision(life)/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']), 0, MAP_SIZE[1]-WORLD_INFO['chunk_size']) - _x_chunk_max = bad_numbers.clip(_current_chunk_pos[0]+((get_vision(life)/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']), 0, MAP_SIZE[0]-WORLD_INFO['chunk_size']) - _y_chunk_max = bad_numbers.clip(_current_chunk_pos[1]+((get_vision(life)/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']), 0, MAP_SIZE[1]-WORLD_INFO['chunk_size']) + _x_chunk_min = bad_numbers.clip(_current_chunk_pos[0]-((get_vision(life)//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']), 0, MAP_SIZE[0]-WORLD_INFO['chunk_size']) + _y_chunk_min = bad_numbers.clip(_current_chunk_pos[1]-((get_vision(life)//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']), 0, MAP_SIZE[1]-WORLD_INFO['chunk_size']) + _x_chunk_max = bad_numbers.clip(_current_chunk_pos[0]+((get_vision(life)//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']), 0, MAP_SIZE[0]-WORLD_INFO['chunk_size']) + _y_chunk_max = bad_numbers.clip(_current_chunk_pos[1]+((get_vision(life)//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']), 0, MAP_SIZE[1]-WORLD_INFO['chunk_size']) _has_ready_weapon = combat.has_ready_weapon(life) for y in range(_y_chunk_min, _y_chunk_max, WORLD_INFO['chunk_size']): @@ -347,13 +347,13 @@ def is_in_fov(life, pos, view_size=MAP_WINDOW_SIZE): if not isinstance(life['fov'], np.ndarray): return False - _min_los_x = ((life['fov'].shape[0]/2)-view_size[0]/2) + _min_los_x = ((life['fov'].shape[0]//2)-view_size[0]//2) _max_los_x = life['fov'].shape[0] - _min_los_y = ((life['fov'].shape[1]/2)-view_size[1]/2) + _min_los_y = ((life['fov'].shape[1]//2)-view_size[1]//2) _max_los_y = life['fov'].shape[1] - _x = pos[0]-(life['pos'][0]-life['fov'].shape[0])-life['fov'].shape[0]/2 - _y = pos[1]-(life['pos'][1]-life['fov'].shape[1])-life['fov'].shape[0]/2 + _x = pos[0]-(life['pos'][0]-life['fov'].shape[0])-life['fov'].shape[0]//2 + _y = pos[1]-(life['pos'][1]-life['fov'].shape[1])-life['fov'].shape[0]//2 if _x<_min_los_x or _x>=_max_los_x or _y<_min_los_y or _y>=_max_los_y: return False @@ -448,8 +448,8 @@ def generate_los(life, target, at, source_map, score_callback, invert=False, ign _stime = time.time() _cover = {'pos': None,'score': 9000} - _x = bad_numbers.clip(at[0]-(SETTINGS['los']/2),0,MAP_SIZE[0]-(SETTINGS['los']/2)) - _y = bad_numbers.clip(at[1]-(SETTINGS['los']/2),0,MAP_SIZE[1]-(SETTINGS['los']/2)) + _x = bad_numbers.clip(at[0]-(SETTINGS['los']//2),0,MAP_SIZE[0]-(SETTINGS['los']//2)) + _y = bad_numbers.clip(at[1]-(SETTINGS['los']//2),0,MAP_SIZE[1]-(SETTINGS['los']//2)) _top_left = (_x,_y,at[2]) target_los = render_fast_los.render_fast_los(at, @@ -486,7 +486,7 @@ def generate_los(life, target, at, source_map, score_callback, invert=False, ign #print time.time()-_stime if not _cover['pos']: - print 'Nowhere to hide', target['life']['name'], _top_left + print('Nowhere to hide', target['life']['name'], _top_left) return False @@ -497,8 +497,8 @@ def _generate_los(life,target,at,source_map,score_callback,invert=False,ignore_s _cover = {'pos': None,'score': 9000} #TODO: Unchecked Cython flag - _x = bad_numbers.clip(at[0]-(MAP_WINDOW_SIZE[0]/2),0,MAP_SIZE[0]) - _y = bad_numbers.clip(at[1]-(MAP_WINDOW_SIZE[1]/2),0,MAP_SIZE[1]) + _x = bad_numbers.clip(at[0]-(MAP_WINDOW_SIZE[0]//2),0,MAP_SIZE[0]) + _y = bad_numbers.clip(at[1]-(MAP_WINDOW_SIZE[1]//2),0,MAP_SIZE[1]) _top_left = (_x,_y,at[2]) target_los = render_los.render_los(source_map,at,top_left=_top_left,no_edge=False) @@ -531,13 +531,13 @@ def _generate_los(life,target,at,source_map,score_callback,invert=False,ignore_s _cover['pos'] = list(pos) if not _cover['pos']: - print 'Nowhere to hide' + print('Nowhere to hide') return False return _cover def find_visible_items(life): - return [item for item in life['know_items'].values() if not item['last_seen_time'] and not 'parent_id' in item['item']] + return [item for item in list(life['know_items'].values()) if not item['last_seen_time'] and not 'parent_id' in item['item']] def find_known_items(life, matches={}, only_visible=True): _match = [] @@ -556,13 +556,13 @@ def find_known_items(life, matches={}, only_visible=True): def _scan_surroundings(center_chunk_key, chunk_size, vision, ignore_chunks=[], chunk_map=WORLD_INFO['chunk_map']): _center_chunk_pos = maps.get_chunk(center_chunk_key)['pos'] - #_center_chunk_pos[0] = ((_center_chunk_pos[0]/chunk_size)*chunk_size)+(chunk_size/2) - #_center_chunk_pos[1] = ((_center_chunk_pos[1]/chunk_size)*chunk_size)+(chunk_size/2) + #_center_chunk_pos[0] = ((_center_chunk_pos[0]//chunk_size)*chunk_size)+(chunk_size//2) + #_center_chunk_pos[1] = ((_center_chunk_pos[1]//chunk_size)*chunk_size)+(chunk_size//2) _chunks = set() _chunk_map = set(chunk_map.keys()) - for _x_mod, _y_mod in render_los.draw_circle(0, 0, ((vision*2)/chunk_size)): - x_mod = _center_chunk_pos[0]+(_x_mod*chunk_size) #(_x_mod/chunk_size)*chunk_size + for _x_mod, _y_mod in render_los.draw_circle(0, 0, ((vision*2)//chunk_size)): + x_mod = _center_chunk_pos[0]+(_x_mod*chunk_size) #(_x_mod//chunk_size)*chunk_size y_mod = _center_chunk_pos[1]+(_y_mod*chunk_size) #print x_mod, y_mod, _center_chunk_pos diff --git a/alife/sound.py b/alife/sound.py index e4f66ee..bfc1e27 100644 --- a/alife/sound.py +++ b/alife/sound.py @@ -3,22 +3,22 @@ import graphics as gfx import life as lfe -import judgement +from . import judgement import dialog -import action -import groups -import chunks -import speech -import combat +from . import action +from . import groups +from . import chunks +from . import speech +from . import combat import events import logic -import sight -import raids -import brain -import camps -import stats +from . import sight +from . import raids +from . import brain +from . import camps +from . import stats import maps -import jobs +from . import jobs import logging @@ -41,9 +41,9 @@ def listen(life): pass elif event['gist'] == 'camp_raid': - print '*' * 10 - print 'RAID IN EFFECT!!!!!!!!!!' - print '*' * 10 + print('*' * 10) + print('RAID IN EFFECT!!!!!!!!!!') + print('*' * 10) _knows = brain.knows_alife(life, event['from']) _raid = raids.defend_camp(event['camp']['id'], life['id']) @@ -53,7 +53,7 @@ def listen(life): speech.announce(life, 'raid_score', raid_score=_raid_score) elif event['gist'] == 'raid_score': - print life['name'],'Got friendly raid score:', event['raid_score'] + print(life['name'],'Got friendly raid score:', event['raid_score']) elif event['gist'] == 'share_item_info': if event['item'] in ITEMS: @@ -69,7 +69,7 @@ def listen(life): target=event['founder'], founder=event['founder']) - print 'Thanks for the camp founder info!' + print('Thanks for the camp founder info!') elif event['gist'] == 'under_attack': _knows_attacker = True @@ -77,7 +77,7 @@ def listen(life): if life['id'] == event['attacker']: pass else: - print life['name'], 'HEARD CALL FOR HELP FROM', event['from']['name'] + print(life['name'], 'HEARD CALL FOR HELP FROM', event['from']['name']) if not brain.knows_alife_by_id(life, event['attacker']): brain.meet_alife(life, LIFE[event['attacker']]) _knows_attacker = False @@ -135,7 +135,7 @@ def listen(life): target=event['target']) elif event['gist'] == 'threw_an_item': - print 'CHECK THIS HERE' * 100 + print('CHECK THIS HERE' * 100) pass elif event['gist'] == '_group_leader_state_change': diff --git a/alife/speech.py b/alife/speech.py index 11e9316..b394caa 100644 --- a/alife/speech.py +++ b/alife/speech.py @@ -3,15 +3,15 @@ import graphics as gfx import life as lfe -import judgement +from . import judgement import language import dialog -import groups -import memory -import brain +from . import groups +from . import memory +from . import brain import menus -import sight -import stats +from . import sight +from . import stats import logging import random @@ -371,7 +371,7 @@ def update_location_of_target_from_target(life, life_id, target_id): logging.debug('%s updated location of %s: %s' % (' '.join(life['name']), ' '.join(LIFE[target_id]['name']), _known['last_seen_at'])) else: - print 'Got out of date info!' * 20 + print('Got out of date info!' * 20) def change_alignment(life, life_id, alignment): _alignment = '%s_to_%s' % (brain.knows_alife_by_id(life, life_id)['alignment'], alignment) diff --git a/alife/stances.py b/alife/stances.py index 132e933..fa867d3 100644 --- a/alife/stances.py +++ b/alife/stances.py @@ -1,6 +1,6 @@ -import brain +from . import brain -import judgement +from . import judgement import logging diff --git a/alife/stats.py b/alife/stats.py index 6b06fbd..8cf229f 100644 --- a/alife/stats.py +++ b/alife/stats.py @@ -3,14 +3,14 @@ import life as lfe import historygen -import judgement -import survival -import speech -import groups -import combat -import camps -import sight -import brain +from . import judgement +from . import survival +from . import speech +from . import groups +from . import combat +from . import camps +from . import sight +from . import brain import zones import bad_numbers @@ -155,7 +155,7 @@ def desires_to_join_camp(life, camp_id): return False if life['camp']: - print life['name'],'already has camp',camps.knows_founder(life, life['camp']) + print(life['name'],'already has camp',camps.knows_founder(life, life['camp'])) return False if life['stats']['lone_wolf']: @@ -166,7 +166,7 @@ def desires_to_join_camp(life, camp_id): _memory = _memories.pop() if not judgement.can_trust(life, _memory['founder']): - print life['name'],'Cant trust founder' * 10 + print(life['name'],'Cant trust founder' * 10) return False if lfe.get_memory(life, matches={'text': 'ask_to_join_camp', 'camp': camp_id}): @@ -299,14 +299,14 @@ def can_scratch(life): _melee_limbs = lfe.get_melee_limbs(life) if not _melee_limbs: - print life['name'],'no melee limbs' + print(life['name'],'no melee limbs') return False for limb in _melee_limbs: if 'SHARP' in lfe.get_limb(life, limb)['flags']: return limb - print life['name'],'cant scratch' + print(life['name'],'cant scratch') return None @@ -316,7 +316,7 @@ def is_nervous(life, life_id): _dist = bad_numbers.distance(life['pos'], LIFE[life_id]['pos']) - if _dist <= sight.get_vision(LIFE[life_id])/2: + if _dist <= sight.get_vision(LIFE[life_id])//2: return True return False @@ -490,14 +490,14 @@ def is_parent_of(life, life_id): return False def has_parent(life): - for life_id in life['know'].keys(): + for life_id in list(life['know'].keys()): if is_child_of(life, life_id): return True return False def has_child(life): - for life_id in life['know'].keys(): + for life_id in list(life['know'].keys()): if is_parent_of(life, life_id): return True diff --git a/alife/survival.py b/alife/survival.py index 4174c77..6fcfb05 100644 --- a/alife/survival.py +++ b/alife/survival.py @@ -1,19 +1,19 @@ from globals import * import life as lfe -import references -import judgement -import movement -import rawparse +from . import references +from . import judgement +from . import movement +from . import rawparse import weapons -import action -import chunks -import speech -import combat -import brain +from . import action +from . import chunks +from . import speech +from . import combat +from . import brain import items -import sight -import stats +from . import sight +from . import stats import maps import logging @@ -50,7 +50,7 @@ def delete_needed_item(life, need_id): logging.debug('Remove item need: %s' % need_id) def remove_item_from_needs(life, item_uid): - for need in life['needs'].values(): + for need in list(life['needs'].values()): if item_uid in need['meet_with']: need['meet_with'].remove(item_uid) @@ -59,7 +59,7 @@ def remove_item_from_needs(life, item_uid): #@profile def process(life): - for need in life['needs'].values(): + for need in list(life['needs'].values()): if need['type'] == 'item': _has_items = [] _potential_items = [] @@ -418,7 +418,7 @@ def explore_unknown_chunks(life): _walkable_area = chunks.get_walkable_areas(_chunk_key) if not _walkable_area: - print 'no walkable area' + print('no walkable area') return False _closest_pos = {'pos': None, 'distance': -1} diff --git a/artifacts.py b/artifacts.py index 313a025..bf15a92 100644 --- a/artifacts.py +++ b/artifacts.py @@ -44,7 +44,7 @@ def create_field(y_min=0): return _territory_key def get_active_fields(): - return [t for t in WORLD_INFO['territories'].values() if t['danger']] + return [t for t in list(WORLD_INFO['territories'].values()) if t['danger']] def tick_fields(): for territory in get_active_fields(): @@ -83,4 +83,4 @@ def create_burner(chunk_key): effects.create_fire(_pos, intensity=8) effects.create_explosion(_pos, 4) - print 'MAN CHECK THIS OUT!!!!!', chunk_key \ No newline at end of file + print('MAN CHECK THIS OUT!!!!!', chunk_key) \ No newline at end of file diff --git a/bad_numbers.py b/bad_numbers.py index f048ec6..e48bec5 100644 --- a/bad_numbers.py +++ b/bad_numbers.py @@ -14,7 +14,7 @@ def clip(number,start,end): return max(start, min(number, end)) def roll(dice, sides): - return sum([random.choice(range(sides))+1 for d in range(dice)]) + return sum([random.choice(list(range(sides)))+1 for d in range(dice)]) def lerp(n1, n2, t): return n1 + (n2-n1) * t @@ -155,7 +155,7 @@ def _create_dijkstra_map(center,source_map,targets,size=(50,50),flee=False,**kva calculate_dijkstra_map(_dijkstra) logging.info('Dijkstra map took: %s, size %s,%s' % (str(time.time()-_stime),(_max_x-_min_x),(_max_y-_min_y))) - print 'Dijkstra map took: %s, size %s,%s, %s' % (str(time.time()-_stime),(_max_x-_min_x),(_max_y-_min_y),0) + print('Dijkstra map took: %s, size %s,%s, %s' % (str(time.time()-_stime),(_max_x-_min_x),(_max_y-_min_y),0)) return _dijkstra @@ -181,9 +181,9 @@ def draw_dijkstra(dijkstra,path): _score = '. ' #_score = _score - print '%s' % _score, + print('%s' % _score, end=' ') - print + print() def create_dijkstra_map(center,source_map,targets,flee=False): _farthest_distance = 0 diff --git a/build.spec b/build.spec new file mode 100644 index 0000000..18d3b87 --- /dev/null +++ b/build.spec @@ -0,0 +1,66 @@ +# -*- mode: python ; coding: utf-8 -*- + +import os.path +import subprocess +import tempfile + +# Create a temporary file with version info. +version_file = os.path.join(tempfile.gettempdir(), "git-version.txt") +with open(version_file, "w") as f: + f.write(subprocess.check_output(["git", "describe", "--tags"], text=True).strip()) + +block_cipher = None + +a = Analysis( + ["reactor-3.py"], + binaries=[], + datas=[("readme.md", "."), ("license.txt", "."), (version_file, ".")], + hiddenimports=[ + "alife.action", + "alife.snapshots", + "alife.judgement", + "alife.chunks", + "alife.brain", + "alife.speech", + "alife.stances", + "alife.jobs", + "alife.groups", + "alife.factions", + "alife.camps", + "alife.sight", + "alife.rawparse", + "alife.noise", + "alife.planner", + ], + hookspath=[], + runtime_hooks=[], + excludes=[], + win_no_prefer_redirects=False, + win_private_assemblies=False, + cipher=block_cipher, + noarchive=False, +) +pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) +exe = EXE( + pyz, + a.scripts, + [], + exclude_binaries=True, + name="reactor-3", + debug=False, + bootloader_ignore_signals=False, + strip=False, + upx=True, + console=True, +) +coll = COLLECT( + exe, + a.binaries, + a.zipfiles, + a.datas, + Tree("data", prefix="data", excludes=["maps"]), # Include data directory. + strip=False, + upx=True, + upx_exclude=[], + name="reactor-3", +) diff --git a/build_life.py b/build_life.py index 7a80c1f..eb6dc52 100644 --- a/build_life.py +++ b/build_life.py @@ -110,12 +110,12 @@ def get_children_of_tag(taglist): return _limbs def build(file): - print 'Reading file \'%s\'...' % file + print('Reading file \'%s\'...' % file) try: _data = read_xml_file(file) - except Exception, e: - print 'Failed to read file:',e + except Exception as e: + print('Failed to read file:',e) return False life = {} @@ -126,21 +126,21 @@ def build(file): life['vars'] = get_value(_data, 'vars') life['icon'] = get_value(_data, 'icon') - print 'Creating new life: %s' % life['species'] - print 'Parsing and connecting limbs...', + print('Creating new life: %s' % life['species']) + print('Parsing and connecting limbs...', end=' ') life['body'] = get_tag(_data,'body') - print 'Done!' - print 'Offloading to disk...', + print('Done!') + print('Offloading to disk...', end=' ') save_json_file('%s.json' % life['species'],life) - print 'Done!' + print('Done!') return True -print '*'*10 -print 'Build Life' -print '*'*10 +print('*'*10) +print('Build Life') +print('*'*10) if len(sys.argv) == 1: for (dirpath, dirname, filenames) in os.walk(LIFE_DIR): diff --git a/buildinggen.py b/buildinggen.py index d791ae8..842f2c8 100644 --- a/buildinggen.py +++ b/buildinggen.py @@ -89,7 +89,7 @@ def connect_to_chunks(connect_to, existing_connections, steps, building_chunks): _common_neighbors = {} _highest = 0 - for layer in _connect_layers.values(): + for layer in list(_connect_layers.values()): for chunk_key in layer['neighbors']: if chunk_key in _common_neighbors: _common_neighbors[chunk_key] += 1 @@ -99,7 +99,7 @@ def connect_to_chunks(connect_to, existing_connections, steps, building_chunks): if _common_neighbors[chunk_key]>_highest: _highest = _common_neighbors[chunk_key] - for chunk_key in _common_neighbors.keys(): + for chunk_key in list(_common_neighbors.keys()): if _common_neighbors[chunk_key]<_highest: del _common_neighbors[chunk_key] @@ -109,7 +109,7 @@ def connect_to_chunks(connect_to, existing_connections, steps, building_chunks): if _highest'): _text = '> '+_text - _n_x = MAP_WINDOW_SIZE[0]/2-len(_text)/2 + _n_x = MAP_WINDOW_SIZE[0]//2-len(_text)//2 if _n_x < _x: _x = _n_x diff --git a/dijkstra.py b/dijkstra.py index 129e25b..3f9a065 100644 --- a/dijkstra.py +++ b/dijkstra.py @@ -13,7 +13,7 @@ def create_dijkstra_map(center,source_map,targets): #Calculate the maximum size of the of the map by testing distances to all targets _farthest_distance = 10#bad_numbers.distance(center,targets[0]['position']) - print _farthest_distance + print(_farthest_distance) _min_x = clip(center[0]-(_farthest_distance),0,MAP_SIZE[0]) _max_x = clip(center[0]+(_farthest_distance),0,MAP_SIZE[0]) @@ -140,25 +140,25 @@ def draw_dijkstra(dijkstra,path=None): if not path: if (_x,_y) in dijkstra['ignore']: - print '# ', + print('# ', end=' ') continue #else: # print '.', _n = str(bad_numbers.clip(abs(int(dijkstra['map'][y,x])),0,41)) if len(_n)==1: - print '%s ' % _n, + print('%s ' % _n, end=' ') else: - print _n, + print(_n, end=' ') else: #print path if (_x,_y,0) in path: - print 'o', + print('o', end=' ') elif (_x,_y) in dijkstra['ignore']: - print '#', + print('#', end=' ') else: - print ' ', - print + print(' ', end=' ') + print() def _main(): _targets = [{'position': (40,30),'score': 50}] @@ -167,7 +167,7 @@ def _main(): _stime = time.time() generate_dijkstra_map(_a) invert_dijkstra_map(_a) - print time.time()-_stime + print(time.time()-_stime) draw_dijkstra(_a) _path = pathfinding.path_from_dijkstra((43,30,2),_a,downhill=False) diff --git a/drawing.py b/drawing.py index 2022644..8597986 100644 --- a/drawing.py +++ b/drawing.py @@ -197,7 +197,7 @@ def draw_circle(at, size): for j in range(width+1): Circle = (((i-CenterY)*(i-CenterY))/((float(height)/2)*(float(height)/2)))+((((j-CenterX)*(j-CenterX))/((float(width)/2)*(float(width)/2)))); if Circle>0 and Circle<1.1: - circle.append((at[0]+(j-(width/2)),at[1]+(i-(height/2)))) + circle.append((at[0]+(j-(width//2)),at[1]+(i-(height//2)))) if not at in circle: circle.append(at) diff --git a/effects.py b/effects.py index ba51308..6b3777b 100644 --- a/effects.py +++ b/effects.py @@ -332,7 +332,7 @@ def draw_vapor(pos, vapor): def calculate_all_effects(): _remove_lights = [] - for effect in EFFECTS.values(): + for effect in list(EFFECTS.values()): effect['callback'](effect) for light in WORLD_INFO['lights']: diff --git a/fast_dijkstra.pyx b/fast_dijkstra.pyx index 4f6c5f4..b001d9c 100644 --- a/fast_dijkstra.pyx +++ b/fast_dijkstra.pyx @@ -3,7 +3,7 @@ from libc.stdlib cimport malloc, free import zones as zon -import numbers +import bad_numbers as numbers import time import copy @@ -156,7 +156,7 @@ def dijkstra_map(start_pos, goals, zones, max_chunk_distance=5, rolldown=True, a raise Exception('Crash.') - _chunk_key = '%s,%s' % ((x/_chunk_size)*_chunk_size, (y/_chunk_size)*_chunk_size) + _chunk_key = '%s,%s' % ((x//_chunk_size)*_chunk_size, (y//_chunk_size)*_chunk_size) if avoid_chunks and _chunk_key in avoid_chunks: _avoid_goals.append((x, y)) @@ -167,10 +167,10 @@ def dijkstra_map(start_pos, goals, zones, max_chunk_distance=5, rolldown=True, a _pass = False for i in range(0, _number_of_goals): - _goal_chunk_key = '%s,%s' % ((_goals_x[i]/_chunk_size)*_chunk_size, (_goals_y[i]/_chunk_size)*_chunk_size) + _goal_chunk_key = '%s,%s' % ((_goals_x[i]//_chunk_size)*_chunk_size, (_goals_y[i]//_chunk_size)*_chunk_size) _goal_chunk = WORLD_INFO['chunk_map'][_goal_chunk_key] - if distance(_chunk['pos'], _goal_chunk['pos'])/_chunk_size<=max_chunk_distance: + if distance(_chunk['pos'], _goal_chunk['pos'])//_chunk_size<=max_chunk_distance: _pass = True break diff --git a/fast_scan_surroundings.pyx b/fast_scan_surroundings.pyx index 41030c8..8b1c74b 100644 --- a/fast_scan_surroundings.pyx +++ b/fast_scan_surroundings.pyx @@ -38,7 +38,7 @@ def scan_surroundings(life, initial=False, _chunks=[], ignore_chunks=[], judge=T chunk_key = _chunks[i] _current_chunk = maps.get_chunk(chunk_key) - _dist = numbers.distance(life['pos'], (_current_chunk['pos'][0]+CHUNK_SIZE/2, _current_chunk['pos'][1]+CHUNK_SIZE/2)) + _dist = numbers.distance(life['pos'], (_current_chunk['pos'][0]+CHUNK_SIZE//2, _current_chunk['pos'][1]+CHUNK_SIZE//2)) if _dist>_outline_chunks['distance']+CHUNK_SIZE: _outline_chunks['distance'] = _dist @@ -52,7 +52,7 @@ def scan_surroundings(life, initial=False, _chunks=[], ignore_chunks=[], judge=T _outline_chunk = WORLD_INFO['chunk_map'][outline_chunk_key] if _outline_chunk['max_z'] <= life['pos'][2]: - _can_see = drawing.diag_line(life['pos'], (_outline_chunk['pos'][0]+CHUNK_SIZE/2, _outline_chunk['pos'][1]+CHUNK_SIZE/2)) + _can_see = drawing.diag_line(life['pos'], (_outline_chunk['pos'][0]+CHUNK_SIZE//2, _outline_chunk['pos'][1]+CHUNK_SIZE//2)) else: _can_see = alife.chunks.can_see_chunk(life, outline_chunk_key) diff --git a/fov.pyx b/fov.pyx index 8df80bb..c058de6 100644 --- a/fov.pyx +++ b/fov.pyx @@ -10,7 +10,7 @@ import alife import items import maps -import cPickle +import pickle as cPickle import cython import numpy import time @@ -76,7 +76,7 @@ def light(los_map, world_pos, size, row, _start_slope, _end_slope, xx, xy, yx, y callback((_a_x, _a_y)) if not _solid: - _chunk_key = '%s,%s' % ((_a_x/5)*5, (_a_y/5)*5) + _chunk_key = '%s,%s' % ((_a_x//5)*5, (_a_y//5)*5) _chunk = chunk_map[_chunk_key] for item_uid in _chunk['items'][:]: @@ -125,7 +125,7 @@ def fov(start_position, distance, get_chunks=False, life_id=None, callback=None) if x<0 or x>=MAP_SIZE[0]-1 or y<0 or y>=MAP_SIZE[1]-1: continue - _chunk_key = '%s,%s' % ((x/5)*5, (y/5)*5) + _chunk_key = '%s,%s' % ((x//5)*5, (y//5)*5) for item_uid in maps.get_chunk(_chunk_key)['items']: if items.is_blocking(item_uid) and ITEMS[item_uid]['pos'][:2] == [x, y]: @@ -173,7 +173,7 @@ def fov(start_position, distance, get_chunks=False, life_id=None, callback=None) _map, _keys = light(_los, start_position, _distance, 1, 1.0, 0.0, MULT[0][i], MULT[1][i], MULT[2][i], MULT[3][i], WORLD_INFO['map'], MAP_SIZE, WORLD_INFO['chunk_map'], callback=callback) - _los[_los.shape[0]/2,_los.shape[1]/2] = 1 + _los[_los.shape[0]//2,_los.shape[1]//2] = 1 if get_chunks: return False diff --git a/globals.py b/globals.py index c11c083..59deb16 100644 --- a/globals.py +++ b/globals.py @@ -5,7 +5,7 @@ WINDOW_TITLE = 'Reactor 3 - %s' % VERSION WINDOW_SIZE = [100, 60] MAP_SIZE = [250, 250, 5] -MAP_WINDOW_SIZE = [WINDOW_SIZE[0]/2, WINDOW_SIZE[1]-10] +MAP_WINDOW_SIZE = [WINDOW_SIZE[0]//2, WINDOW_SIZE[1]-10] ITEM_WINDOW_SIZE = (40,1) CONSOLE_WINDOW_SIZE = (40,30) MESSAGE_WINDOW_SIZE = (100,10) @@ -13,7 +13,7 @@ X_CUTOUT_WINDOW_SIZE = (15,15) Y_CUTOUT_WINDOW_SIZE = (15,15) PREFAB_WINDOW_OFFSET = (MAP_WINDOW_SIZE[0]+26,1) -CURSOR_POS = [WINDOW_SIZE[0]/2, WINDOW_SIZE[1]/2, 2] +CURSOR_POS = [WINDOW_SIZE[0]//2, WINDOW_SIZE[1]//2, 2] MAP_CURSOR = [0,0] PREFAB_CURSOR = [0,0] PREFABS = {} diff --git a/graphics.py b/graphics.py index 6f2a809..5ac1323 100644 --- a/graphics.py +++ b/graphics.py @@ -49,7 +49,6 @@ def init_libtcod(terraform=False, window_size=WINDOW_SIZE, map_view_size=MAP_WIN Y_CUTOUT_CHAR_BUFFER[0] = numpy.zeros((Y_CUTOUT_WINDOW_SIZE[1], Y_CUTOUT_WINDOW_SIZE[0]), dtype=numpy.int8) Y_CUTOUT_CHAR_BUFFER[1] = numpy.zeros((Y_CUTOUT_WINDOW_SIZE[1], Y_CUTOUT_WINDOW_SIZE[0]), dtype=numpy.int8) - tcod.console_set_keyboard_repeat(200, 0) tcod.sys_set_fps(FPS) for i in range(3): @@ -61,7 +60,7 @@ def init_libtcod(terraform=False, window_size=WINDOW_SIZE, map_view_size=MAP_WIN Y_CUTOUT_RGB_BACK_BUFFER[i] = numpy.zeros((Y_CUTOUT_WINDOW_SIZE[1], Y_CUTOUT_WINDOW_SIZE[0]), dtype=numpy.int8) Y_CUTOUT_RGB_FORE_BUFFER[i] = numpy.zeros((Y_CUTOUT_WINDOW_SIZE[1], Y_CUTOUT_WINDOW_SIZE[0]), dtype=numpy.int8) - SETTINGS['light mesh grid'] = numpy.meshgrid(range(map_view_size[0]), range(map_view_size[1])) + SETTINGS['light mesh grid'] = numpy.meshgrid(list(range(map_view_size[0])), list(range(map_view_size[1]))) def create_view(x, y, w, h, dw, dh, alpha, name, lighting=False, layer=0, fore_opacity=1, back_opacity=1, transparent=False, require_refresh=False): if get_view_by_name(name): @@ -122,7 +121,7 @@ def clear_view(view_name, color=tcod.black): col_buffer[2] = col_buffer[2].clip(color.b) def clear_views(): - for key in VIEWS.keys(): + for key in list(VIEWS.keys()): del VIEWS[key] logging.debug('Cleared views.') @@ -134,7 +133,7 @@ def clear_views(): SETTINGS['active_view'] = None def clear_scene(): - for key in VIEW_SCENE.keys(): + for key in list(VIEW_SCENE.keys()): del VIEW_SCENE[key] for entry in VIEW_SCENE_CACHE.copy(): @@ -262,12 +261,12 @@ def draw_view(view_name): _draw_view(_view) def draw_scene(): - for layer in VIEW_SCENE.values(): + for layer in list(VIEW_SCENE.values()): for view in layer: _draw_view(view) def render_scene(): - for layer in VIEW_SCENE.values(): + for layer in list(VIEW_SCENE.values()): for view in layer: tcod.console_blit(view['console'], 0, @@ -613,7 +612,7 @@ def draw_status_line(): 'map') if SETTINGS['glitch_text']: - _max_glitch_progress = SETTINGS['glitch_text_time_max']/2 + _max_glitch_progress = SETTINGS['glitch_text_time_max']//2 _glitch_progress = SETTINGS['glitch_text_time']/float(_max_glitch_progress) _i = 0 @@ -650,9 +649,9 @@ def draw_selected_tile_in_item_window(pos): def draw_all_tiles(): for tile in TILES: - tcod.console_set_char_foreground(ITEM_WINDOW, TILES.keys().index(tile), 0, TILES[tile]['color'][0]) - tcod.console_set_char_background(ITEM_WINDOW, TILES.keys().index(tile), 0, TILES[tile]['color'][1]) - tcod.console_set_char(ITEM_WINDOW, TILES.keys().index(tile), 0, TILES[tile]['icon']) + tcod.console_set_char_foreground(ITEM_WINDOW, list(TILES.keys()).index(tile), 0, TILES[tile]['color'][0]) + tcod.console_set_char_background(ITEM_WINDOW, list(TILES.keys()).index(tile), 0, TILES[tile]['color'][1]) + tcod.console_set_char(ITEM_WINDOW, list(TILES.keys()).index(tile), 0, TILES[tile]['icon']) def draw_dijkstra_heatmap(): if not SETTINGS['heatmap']: @@ -672,7 +671,7 @@ def draw_dijkstra_heatmap(): if y=MAP_WINDOW_SIZE[1]: continue - _score = abs(SETTINGS['heatmap']['map'][_x][_y])/8 + _score = abs(SETTINGS['heatmap']['map'][_x][_y])//8 _light = bad_numbers.clip(_score,0,150) lighten_tile(x,y,_light) @@ -696,12 +695,12 @@ def draw_chunk_map(): else: _fore_color = tcod.white - if MAP_CURSOR[0]/WORLD_INFO['chunk_size'] == x/WORLD_INFO['chunk_size'] and MAP_CURSOR[1]/WORLD_INFO['chunk_size'] == y/WORLD_INFO['chunk_size']: + if MAP_CURSOR[0]//WORLD_INFO['chunk_size'] == x//WORLD_INFO['chunk_size'] and MAP_CURSOR[1]//WORLD_INFO['chunk_size'] == y//WORLD_INFO['chunk_size']: _fore_color = tcod.white _tile = 'x' - blit_char(x/WORLD_INFO['chunk_size'], - y/WORLD_INFO['chunk_size'], + blit_char(x//WORLD_INFO['chunk_size'], + y//WORLD_INFO['chunk_size'], _tile, char_buffer=MAP_CHAR_BUFFER, fore_color=_fore_color, @@ -751,8 +750,8 @@ def title(text, padding=2, text_color=tcod.white, background_color=tcod.black): if not SETTINGS['running']: return False - _center_x = (WINDOW_SIZE[0]/2)-len(text)/2 - _center_y = WINDOW_SIZE[1]/2 + _center_x = (WINDOW_SIZE[0]//2)-len(text)//2 + _center_y = WINDOW_SIZE[1]//2 tcod.console_set_default_background(0, background_color) tcod.console_set_default_foreground(0, text_color) tcod.console_print_frame(0, @@ -775,8 +774,8 @@ def glitch_text(text, change_text_only=False): if SETTINGS['glitch_text_fade']: SETTINGS['glitch_text_fade'] = False - if SETTINGS['glitch_text_time'] > SETTINGS['glitch_text_time_max']/2: - SETTINGS['glitch_text_time'] = SETTINGS['glitch_text_time_max']/2 + if SETTINGS['glitch_text_time'] > SETTINGS['glitch_text_time_max']//2: + SETTINGS['glitch_text_time'] = SETTINGS['glitch_text_time_max']//2 if SETTINGS['glitch_text_time']: return True diff --git a/inputs.py b/inputs.py index 89723b4..e531862 100644 --- a/inputs.py +++ b/inputs.py @@ -1,4 +1,4 @@ -from cStringIO import StringIO +from io import StringIO from globals import * from debug import * @@ -21,6 +21,23 @@ def get_input(): get_keyboard_input() get_mouse_input() +VK_MAPPINGS = { + tcod.KEY_RIGHT: "right", + tcod.KEY_LEFT: "left", + tcod.KEY_DOWN: "down", + tcod.KEY_UP: "up", + tcod.KEY_KP0: "0", + tcod.KEY_KP1: "1", + tcod.KEY_KP2: "2", + tcod.KEY_KP3: "3", + tcod.KEY_KP4: "4", + tcod.KEY_KP5: "5", + tcod.KEY_KP6: "6", + tcod.KEY_KP7: "7", + tcod.KEY_KP8: "8", + tcod.KEY_KP9: "9", +} + def get_keyboard_input(): global KEYBOARD_STRING @@ -29,16 +46,13 @@ def get_keyboard_input(): if KEY.c: _key = chr(KEY.c) + if KEY.shift: + _key = _key.upper() + if _key == "/": + _key = "?" else: - if KEY.pressed: - if KEY.vk == tcod.KEY_RIGHT: - INPUT['right'] = True - elif KEY.vk == tcod.KEY_LEFT: - INPUT['left'] = True - elif KEY.vk == tcod.KEY_DOWN: - INPUT['down'] = True - elif KEY.vk == tcod.KEY_UP: - INPUT['up'] = True + if KEY.pressed and KEY.vk in VK_MAPPINGS: + INPUT[VK_MAPPINGS[KEY.vk]] = True return True @@ -63,7 +77,7 @@ def get_keyboard_input(): if _item and KEY.pressed: _item['values'][0] += _key - if not INPUT.has_key(_key): + if _key not in INPUT: INPUT[_key] = False if not INPUT[_key] and KEY.pressed: diff --git a/items.py b/items.py index 43e11e0..218021d 100644 --- a/items.py +++ b/items.py @@ -29,7 +29,7 @@ def load_item(item): try: logging.debug('Caching item: %s' % item) return json.loads(''.join(e.readlines())) - except ValueError,e: + except ValueError as e: raise Exception('Failed to load item: %s' % e) def initiate_all_items(): @@ -147,12 +147,12 @@ def initiate_item(name): item['marked_for_reint'] = _marked_for_reint.copy() #Unicode isn't handled all that well on Windows for some reason... - for key in item: + for key in list(item): _value = item[key] del item[key] item[str(key)] = _value - if isinstance(item[key],unicode): + if isinstance(item[key],str): item[key] = str(item[key]) ITEM_TYPES[item['name']] = item @@ -247,7 +247,7 @@ def remove_from_chunk(item): return False def clean_item_for_save(item): - if isinstance(item['icon'], unicode) or isinstance(item['icon'], str): + if isinstance(item['icon'], str) or isinstance(item['icon'], str): item['icon'] = ord(item['icon'][0]) _fore = None @@ -262,11 +262,11 @@ def clean_item_for_save(item): item['color'] = (_fore, _back) def save_all_items(): - for item in ITEMS.values(): + for item in list(ITEMS.values()): clean_item_for_save(item) def reload_all_items(): - for item in ITEMS.values(): + for item in list(ITEMS.values()): if isinstance(item['icon'], int): item['icon'] = chr(item['icon']) @@ -378,13 +378,13 @@ def move(item, direction, speed, friction=0.05, _velocity=0): def is_item_owned(item_uid): _item = get_item_from_uid(item_uid) - if _item.has_key('parent_id'): + if 'parent_id' in _item: return True - if _item.has_key('parent'): + if 'parent' in _item: return True - if _item.has_key('stored_in'): + if 'stored_in' in _item: return True return False @@ -460,7 +460,7 @@ def can_store_item_in(item_uid, container_uid): def store_item_in(item_uid, container_uid): if not can_store_item_in(item_uid, container_uid): - print 'cannot store in' + print('cannot store in') raise Exception('Cant store item %s in container %s: %s is full.' % (item_uid, container_uid, ITEMS[container_uid]['name'])) _item = get_item_from_uid(item_uid) @@ -539,7 +539,7 @@ def explode(item): #TODO: Dirty hack for life_id in LIFE: - _limbs = LIFE[life_id]['body'].keys() + _limbs = list(LIFE[life_id]['body'].keys()) if not _limbs: continue @@ -553,7 +553,7 @@ def explode(item): _direction = bad_numbers.direction_to(item['pos'], LIFE[life_id]['pos']) #TODO: Intelligent(?) limb groups? - _distance = bad_numbers.distance(LIFE[life_id]['pos'], item['pos'])/2 + _distance = bad_numbers.distance(LIFE[life_id]['pos'], item['pos'])//2 for i in range(_force-_distance): _limb = random.choice(_limbs) @@ -601,9 +601,9 @@ def explode(item): if not random.randint(0, 4): effects.create_fire((pos[0], pos[1], item['pos'][2]), - intensity=item['damage']['fire']/2) + intensity=item['damage']['fire']//2) - _dist = bad_numbers.distance(item['pos'], pos)/2 + _dist = bad_numbers.distance(item['pos'], pos)//2 if not random.randint(0, _dist) or not _dist: effects.create_ash(pos) @@ -628,7 +628,7 @@ def collision_with_solid(item, pos): item['realpos'][0] = float(pos[0])+_x_diff item['realpos'][1] = float(pos[1])+_y_diff - print '*** STOP ***' + print('*** STOP ***') process_event(item, 'stop') @@ -705,7 +705,7 @@ def create_effects(item, pos, real_z_pos, z_min): if 'SMOKING' in item['flags']: if random.randint(0, 50)<=25: effects.create_smoke_streamer([pos[0]+random.randint(-item['size'], item['size']), pos[1]+random.randint(-item['size'], item['size']), _z_level], - item['size']/2, + item['size']//2, random.randint(item['size']*2, (item['size']*2)+5)) if 'BURNING' in item['flags']: if random.randint(0, 50)<=25: @@ -713,7 +713,7 @@ def create_effects(item, pos, real_z_pos, z_min): random.randint(item['size'], (item['size'])+3), color=tcod.light_crimson) if 'max_speed' in item and is_moving(item): - effects.create_vapor(item['pos'], 5, bad_numbers.clip(item['speed']/20, 0, 1)) + effects.create_vapor(item['pos'], 5, bad_numbers.clip(item['speed']//20, 0, 1)) def get_min_max_velocity(item): if item['velocity'][0]>0: @@ -897,14 +897,14 @@ def tick_item(item): def tick_all_items(): if not WORLD_INFO['ticks'] % 16 or not ACTIVE_ITEMS: if SETTINGS['controlling']: - for item in ITEMS.values(): + for item in list(ITEMS.values()): if bad_numbers.distance(item['pos'], LIFE[SETTINGS['controlling']]['pos'])>=OFFLINE_ALIFE_DISTANCE: if item['uid'] in ACTIVE_ITEMS: ACTIVE_ITEMS.remove(item['uid']) elif not item['uid'] in ACTIVE_ITEMS: ACTIVE_ITEMS.add(item['uid']) elif not ACTIVE_ITEMS: - ACTIVE_ITEMS.update(ITEMS.keys()) + ACTIVE_ITEMS.update(list(ITEMS.keys())) for item in ACTIVE_ITEMS.copy(): if is_moving(ITEMS[item]): diff --git a/language.py b/language.py index 222472a..e502607 100644 --- a/language.py +++ b/language.py @@ -139,11 +139,8 @@ def _load_strings(a, directory, filenames): def load_strings(): #TODO: Use better walk, like one in profiles.py - try: - os.path.walk(TEXT_DIR, _load_strings, None) - load_dialog() - except Exception, e: - raise Exception(e) + for directory, _, filenames in os.walk("."): + _load_strings(None, directory, filenames) def load_dialog(): with open(os.path.join(TEXT_DIR, 'dialog.txt')) as f: @@ -202,11 +199,11 @@ def format_injury(injury): return 'nothing in particular.' def generate_memory_phrase(memory): - _details = [key for key in memory.keys() if not key == 'text'] + _details = [key for key in list(memory.keys()) if not key == 'text'] _memory_age = WORLD_INFO['ticks']-memory['time_created'] _topic = memory['text'] if _topic == 'friendly': return '%s seems like a good guy.' % (' '.join(LIFE[memory['target']]['name'])) else: - print 'DIDNT HAVE A PHRASE FOR',_topic + print('DIDNT HAVE A PHRASE FOR',_topic) diff --git a/libtcodpy.py b/libtcodpy.py deleted file mode 100644 index 91d2e86..0000000 --- a/libtcodpy.py +++ /dev/null @@ -1,1957 +0,0 @@ -# -# libtcod 1.5.1 python wrapper -# Copyright (c) 2008,2009,2010 Jice & Mingos -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# * The name of Jice or Mingos may not be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL JICE OR MINGOS BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -import sys -import ctypes -import struct -from ctypes import * - -if not hasattr(ctypes, "c_bool"): # for Python < 2.6 - c_bool = c_uint8 - -try: #import NumPy if available - import numpy - numpy_available = True -except ImportError: - numpy_available = False - -LINUX=False -MAC=False -MINGW=False -MSVC=False -if sys.platform.find('linux') != -1: - _lib = ctypes.cdll['./libtcod.so'] - LINUX=True -elif sys.platform.find('darwin') != -1: - _lib = ctypes.cdll['./libtcod.dylib'] - MAC = True -elif sys.platform.find('haiku') != -1: - _lib = ctypes.cdll['./libtcod.so'] - HAIKU = True -else: - try: - _lib = ctypes.cdll['./libtcod-mingw.dll'] - MINGW=True - except WindowsError: - _lib = ctypes.cdll['./libtcod-VS.dll'] - MSVC=True - # On Windows, ctypes doesn't work well with function returning structs, - # so we have to user the _wrapper functions instead - _lib.TCOD_color_multiply = _lib.TCOD_color_multiply_wrapper - _lib.TCOD_color_add = _lib.TCOD_color_add_wrapper - _lib.TCOD_color_multiply_scalar = _lib.TCOD_color_multiply_scalar_wrapper - _lib.TCOD_color_subtract = _lib.TCOD_color_subtract_wrapper - _lib.TCOD_color_lerp = _lib.TCOD_color_lerp_wrapper - _lib.TCOD_console_get_default_background = _lib.TCOD_console_get_default_background_wrapper - _lib.TCOD_console_get_default_foreground = _lib.TCOD_console_get_default_foreground_wrapper - _lib.TCOD_console_get_char_background = _lib.TCOD_console_get_char_background_wrapper - _lib.TCOD_console_get_char_foreground = _lib.TCOD_console_get_char_foreground_wrapper - _lib.TCOD_console_get_fading_color = _lib.TCOD_console_get_fading_color_wrapper - _lib.TCOD_image_get_pixel = _lib.TCOD_image_get_pixel_wrapper - _lib.TCOD_image_get_mipmap_pixel = _lib.TCOD_image_get_mipmap_pixel_wrapper - _lib.TCOD_parser_get_color_property = _lib.TCOD_parser_get_color_property_wrapper - -HEXVERSION = 0x010501 -STRVERSION = "1.5.1" -TECHVERSION = 0x01050103 - -############################ -# color module -############################ -class Color(Structure): - _fields_ = [('r', c_uint8), - ('g', c_uint8), - ('b', c_uint8), - ] - - def __eq__(self, c): - return _lib.TCOD_color_equals(self, c) - - def __mul__(self, c): - if isinstance(c,Color): - return _lib.TCOD_color_multiply(self, c) - else: - return _lib.TCOD_color_multiply_scalar(self, c_float(c)) - - def __add__(self, c): - return _lib.TCOD_color_add(self, c) - - def __sub__(self, c): - return _lib.TCOD_color_subtract(self, c) - - def __repr__(self): - return "Color(%d,%d,%d)" % (self.r, self.g, self.b) - - def __getitem__(self, i): - if type(i) == str: - return getattr(self, i) - else: - return getattr(self, "rgb"[i]) - - def __setitem__(self, i, c): - if type(i) == str: - setattr(self, i, c) - else: - setattr(self, "rgb"[i], c) - - def __iter__(self): - yield self.r - yield self.g - yield self.b - -# Should be valid on any platform, check it! Has to be done after Color is defined. -if MAC: - from cprotos import setup_protos - setup_protos(_lib) - -_lib.TCOD_color_equals.restype = c_bool -_lib.TCOD_color_multiply.restype = Color -_lib.TCOD_color_multiply_scalar.restype = Color -_lib.TCOD_color_add.restype = Color -_lib.TCOD_color_subtract.restype = Color - -# default colors -# grey levels -black=Color(0,0,0) -darkest_grey=Color(31,31,31) -darker_grey=Color(63,63,63) -dark_grey=Color(95,95,95) -grey=Color(127,127,127) -light_grey=Color(159,159,159) -lighter_grey=Color(191,191,191) -lightest_grey=Color(223,223,223) -darkest_gray=Color(31,31,31) -darker_gray=Color(63,63,63) -dark_gray=Color(95,95,95) -gray=Color(127,127,127) -light_gray=Color(159,159,159) -lighter_gray=Color(191,191,191) -lightest_gray=Color(223,223,223) -white=Color(255,255,255) - -# sepia -darkest_sepia=Color(31,24,15) -darker_sepia=Color(63,50,31) -dark_sepia=Color(94,75,47) -sepia=Color(127,101,63) -light_sepia=Color(158,134,100) -lighter_sepia=Color(191,171,143) -lightest_sepia=Color(222,211,195) - -#standard colors -red=Color(255,0,0) -flame=Color(255,63,0) -orange=Color(255,127,0) -amber=Color(255,191,0) -yellow=Color(255,255,0) -lime=Color(191,255,0) -chartreuse=Color(127,255,0) -green=Color(0,255,0) -sea=Color(0,255,127) -turquoise=Color(0,255,191) -cyan=Color(0,255,255) -sky=Color(0,191,255) -azure=Color(0,127,255) -blue=Color(0,0,255) -han=Color(63,0,255) -violet=Color(127,0,255) -purple=Color(191,0,255) -fuchsia=Color(255,0,255) -magenta=Color(255,0,191) -pink=Color(255,0,127) -crimson=Color(255,0,63) - -# dark colors -dark_red=Color(191,0,0) -dark_flame=Color(191,47,0) -dark_orange=Color(191,95,0) -dark_amber=Color(191,143,0) -dark_yellow=Color(191,191,0) -dark_lime=Color(143,191,0) -dark_chartreuse=Color(95,191,0) -dark_green=Color(0,191,0) -dark_sea=Color(0,191,95) -dark_turquoise=Color(0,191,143) -dark_cyan=Color(0,191,191) -dark_sky=Color(0,143,191) -dark_azure=Color(0,95,191) -dark_blue=Color(0,0,191) -dark_han=Color(47,0,191) -dark_violet=Color(95,0,191) -dark_purple=Color(143,0,191) -dark_fuchsia=Color(191,0,191) -dark_magenta=Color(191,0,143) -dark_pink=Color(191,0,95) -dark_crimson=Color(191,0,47) - -# darker colors -darker_red=Color(127,0,0) -darker_flame=Color(127,31,0) -darker_orange=Color(127,63,0) -darker_amber=Color(127,95,0) -darker_yellow=Color(127,127,0) -darker_lime=Color(95,127,0) -darker_chartreuse=Color(63,127,0) -darker_green=Color(0,127,0) -darker_sea=Color(0,127,63) -darker_turquoise=Color(0,127,95) -darker_cyan=Color(0,127,127) -darker_sky=Color(0,95,127) -darker_azure=Color(0,63,127) -darker_blue=Color(0,0,127) -darker_han=Color(31,0,127) -darker_violet=Color(63,0,127) -darker_purple=Color(95,0,127) -darker_fuchsia=Color(127,0,127) -darker_magenta=Color(127,0,95) -darker_pink=Color(127,0,63) -darker_crimson=Color(127,0,31) - -# darkest colors -darkest_red=Color(63,0,0) -darkest_flame=Color(63,15,0) -darkest_orange=Color(63,31,0) -darkest_amber=Color(63,47,0) -darkest_yellow=Color(63,63,0) -darkest_lime=Color(47,63,0) -darkest_chartreuse=Color(31,63,0) -darkest_green=Color(0,63,0) -darkest_sea=Color(0,63,31) -darkest_turquoise=Color(0,63,47) -darkest_cyan=Color(0,63,63) -darkest_sky=Color(0,47,63) -darkest_azure=Color(0,31,63) -darkest_blue=Color(0,0,63) -darkest_han=Color(15,0,63) -darkest_violet=Color(31,0,63) -darkest_purple=Color(47,0,63) -darkest_fuchsia=Color(63,0,63) -darkest_magenta=Color(63,0,47) -darkest_pink=Color(63,0,31) -darkest_crimson=Color(63,0,15) - -# light colors -light_red=Color(255,114,114) -light_flame=Color(255,149,114) -light_orange=Color(255,184,114) -light_amber=Color(255,219,114) -light_yellow=Color(255,255,114) -light_lime=Color(219,255,114) -light_chartreuse=Color(184,255,114) -light_green=Color(114,255,114) -light_sea=Color(114,255,184) -light_turquoise=Color(114,255,219) -light_cyan=Color(114,255,255) -light_sky=Color(114,219,255) -light_azure=Color(114,184,255) -light_blue=Color(114,114,255) -light_han=Color(149,114,255) -light_violet=Color(184,114,255) -light_purple=Color(219,114,255) -light_fuchsia=Color(255,114,255) -light_magenta=Color(255,114,219) -light_pink=Color(255,114,184) -light_crimson=Color(255,114,149) - -#lighter colors -lighter_red=Color(255,165,165) -lighter_flame=Color(255,188,165) -lighter_orange=Color(255,210,165) -lighter_amber=Color(255,232,165) -lighter_yellow=Color(255,255,165) -lighter_lime=Color(232,255,165) -lighter_chartreuse=Color(210,255,165) -lighter_green=Color(165,255,165) -lighter_sea=Color(165,255,210) -lighter_turquoise=Color(165,255,232) -lighter_cyan=Color(165,255,255) -lighter_sky=Color(165,232,255) -lighter_azure=Color(165,210,255) -lighter_blue=Color(165,165,255) -lighter_han=Color(188,165,255) -lighter_violet=Color(210,165,255) -lighter_purple=Color(232,165,255) -lighter_fuchsia=Color(255,165,255) -lighter_magenta=Color(255,165,232) -lighter_pink=Color(255,165,210) -lighter_crimson=Color(255,165,188) - -# lightest colors -lightest_red=Color(255,191,191) -lightest_flame=Color(255,207,191) -lightest_orange=Color(255,223,191) -lightest_amber=Color(255,239,191) -lightest_yellow=Color(255,255,191) -lightest_lime=Color(239,255,191) -lightest_chartreuse=Color(223,255,191) -lightest_green=Color(191,255,191) -lightest_sea=Color(191,255,223) -lightest_turquoise=Color(191,255,239) -lightest_cyan=Color(191,255,255) -lightest_sky=Color(191,239,255) -lightest_azure=Color(191,223,255) -lightest_blue=Color(191,191,255) -lightest_han=Color(207,191,255) -lightest_violet=Color(223,191,255) -lightest_purple=Color(239,191,255) -lightest_fuchsia=Color(255,191,255) -lightest_magenta=Color(255,191,239) -lightest_pink=Color(255,191,223) -lightest_crimson=Color(255,191,207) - -# desaturated colors -desaturated_red=Color(127,63,63) -desaturated_flame=Color(127,79,63) -desaturated_orange=Color(127,95,63) -desaturated_amber=Color(127,111,63) -desaturated_yellow=Color(127,127,63) -desaturated_lime=Color(111,127,63) -desaturated_chartreuse=Color(95,127,63) -desaturated_green=Color(63,127,63) -desaturated_sea=Color(63,127,95) -desaturated_turquoise=Color(63,127,111) -desaturated_cyan=Color(63,127,127) -desaturated_sky=Color(63,111,127) -desaturated_azure=Color(63,95,127) -desaturated_blue=Color(63,63,127) -desaturated_han=Color(79,63,127) -desaturated_violet=Color(95,63,127) -desaturated_purple=Color(111,63,127) -desaturated_fuchsia=Color(127,63,127) -desaturated_magenta=Color(127,63,111) -desaturated_pink=Color(127,63,95) -desaturated_crimson=Color(127,63,79) - -# metallic -brass=Color(191,151,96) -copper=Color(197,136,124) -gold=Color(229,191,0) -silver=Color(203,203,203) - -# miscellaneous -celadon=Color(172,255,175) -peach=Color(255,159,127) - -# color functions -_lib.TCOD_color_lerp.restype = Color -def color_lerp(c1, c2, a): - return _lib.TCOD_color_lerp(c1, c2, c_float(a)) - -def color_set_hsv(c, h, s, v): - _lib.TCOD_color_set_HSV(byref(c), c_float(h), c_float(s), c_float(v)) - -def color_get_hsv(c): - h = c_float() - s = c_float() - v = c_float() - _lib.TCOD_color_get_HSV(c, byref(h), byref(s), byref(v)) - return h.value, s.value, v.value - -def color_scale_HSV(c, scoef, vcoef) : - _lib.TCOD_color_scale_HSV(byref(c),c_float(scoef),c_float(vcoef)) - -def color_gen_map(colors, indexes): - ccolors = (Color * len(colors))(*colors) - cindexes = (c_int * len(indexes))(*indexes) - cres = (Color * (max(indexes) + 1))() - _lib.TCOD_color_gen_map(cres, len(colors), ccolors, cindexes) - return cres - -############################ -# console module -############################ -class Key(Structure): - _fields_=[('vk', c_int), - ('c', c_uint8), - ('pressed', c_bool), - ('lalt', c_bool), - ('lctrl', c_bool), - ('ralt', c_bool), - ('rctrl', c_bool), - ('shift', c_bool), - ] - -class ConsoleBuffer: - # simple console that allows direct (fast) access to cells. simplifies - # use of the "fill" functions. - def __init__(self, width, height, back_r=0, back_g=0, back_b=0, fore_r=0, fore_g=0, fore_b=0, char=' '): - # initialize with given width and height. values to fill the buffer - # are optional, defaults to black with no characters. - n = width * height - self.width = width - self.height = height - self.clear(back_r, back_g, back_b, fore_r, fore_g, fore_b, char) - - def clear(self, back_r=0, back_g=0, back_b=0, fore_r=0, fore_g=0, fore_b=0, char=' '): - # clears the console. values to fill it with are optional, defaults - # to black with no characters. - n = self.width * self.height - self.back_r = [back_r] * n - self.back_g = [back_g] * n - self.back_b = [back_b] * n - self.fore_r = [fore_r] * n - self.fore_g = [fore_g] * n - self.fore_b = [fore_b] * n - self.char = [ord(char)] * n - - def copy(self): - # returns a copy of this ConsoleBuffer. - other = ConsoleBuffer(0, 0) - other.width = self.width - other.height = self.height - other.back_r = list(self.back_r) # make explicit copies of all lists - other.back_g = list(self.back_g) - other.back_b = list(self.back_b) - other.fore_r = list(self.fore_r) - other.fore_g = list(self.fore_g) - other.fore_b = list(self.fore_b) - other.char = list(self.char) - return other - - def set_fore(self, x, y, r, g, b, char): - # set the character and foreground color of one cell. - i = self.width * y + x - self.fore_r[i] = r - self.fore_g[i] = g - self.fore_b[i] = b - self.char[i] = ord(char) - - def set_back(self, x, y, r, g, b): - # set the background color of one cell. - i = self.width * y + x - self.back_r[i] = r - self.back_g[i] = g - self.back_b[i] = b - - def set(self, x, y, back_r, back_g, back_b, fore_r, fore_g, fore_b, char): - # set the background color, foreground color and character of one cell. - i = self.width * y + x - self.back_r[i] = back_r - self.back_g[i] = back_g - self.back_b[i] = back_b - self.fore_r[i] = fore_r - self.fore_g[i] = fore_g - self.fore_b[i] = fore_b - self.char[i] = ord(char) - - def blit(self, dest, fill_fore=True, fill_back=True): - # use libtcod's "fill" functions to write the buffer to a console. - if (console_get_width(dest) != self.width or - console_get_height(dest) != self.height): - raise ValueError('ConsoleBuffer.blit: Destination console has an incorrect size.') - - s = struct.Struct('%di' % len(self.back_r)) - - if fill_back: - _lib.TCOD_console_fill_background(dest, (c_int * len(self.back_r))(*self.back_r), (c_int * len(self.back_g))(*self.back_g), (c_int * len(self.back_b))(*self.back_b)) - - if fill_fore: - _lib.TCOD_console_fill_foreground(dest, (c_int * len(self.fore_r))(*self.fore_r), (c_int * len(self.fore_g))(*self.fore_g), (c_int * len(self.fore_b))(*self.fore_b)) - _lib.TCOD_console_fill_char(dest, (c_int * len(self.char))(*self.char)) - -_lib.TCOD_console_credits_render.restype = c_bool -_lib.TCOD_console_is_fullscreen.restype = c_bool -_lib.TCOD_console_is_window_closed.restype = c_bool -_lib.TCOD_console_get_default_background.restype = Color -_lib.TCOD_console_get_default_foreground.restype = Color -_lib.TCOD_console_get_char_background.restype = Color -_lib.TCOD_console_get_char_foreground.restype = Color -_lib.TCOD_console_get_fading_color.restype = Color -_lib.TCOD_console_is_key_pressed.restype = c_bool - -# background rendering modes -BKGND_NONE = 0 -BKGND_SET = 1 -BKGND_MULTIPLY = 2 -BKGND_LIGHTEN = 3 -BKGND_DARKEN = 4 -BKGND_SCREEN = 5 -BKGND_COLOR_DODGE = 6 -BKGND_COLOR_BURN = 7 -BKGND_ADD = 8 -BKGND_ADDA = 9 -BKGND_BURN = 10 -BKGND_OVERLAY = 11 -BKGND_ALPH = 12 -BKGND_DEFAULT=13 - -def BKGND_ALPHA(a): - return BKGND_ALPH | (int(a * 255) << 8) - -def BKGND_ADDALPHA(a): - return BKGND_ADDA | (int(a * 255) << 8) - -# non blocking key events types -KEY_PRESSED = 1 -KEY_RELEASED = 2 -# key codes -KEY_NONE = 0 -KEY_ESCAPE = 1 -KEY_BACKSPACE = 2 -KEY_TAB = 3 -KEY_ENTER = 4 -KEY_SHIFT = 5 -KEY_CONTROL = 6 -KEY_ALT = 7 -KEY_PAUSE = 8 -KEY_CAPSLOCK = 9 -KEY_PAGEUP = 10 -KEY_PAGEDOWN = 11 -KEY_END = 12 -KEY_HOME = 13 -KEY_UP = 14 -KEY_LEFT = 15 -KEY_RIGHT = 16 -KEY_DOWN = 17 -KEY_PRINTSCREEN = 18 -KEY_INSERT = 19 -KEY_DELETE = 20 -KEY_LWIN = 21 -KEY_RWIN = 22 -KEY_APPS = 23 -KEY_0 = 24 -KEY_1 = 25 -KEY_2 = 26 -KEY_3 = 27 -KEY_4 = 28 -KEY_5 = 29 -KEY_6 = 30 -KEY_7 = 31 -KEY_8 = 32 -KEY_9 = 33 -KEY_KP0 = 34 -KEY_KP1 = 35 -KEY_KP2 = 36 -KEY_KP3 = 37 -KEY_KP4 = 38 -KEY_KP5 = 39 -KEY_KP6 = 40 -KEY_KP7 = 41 -KEY_KP8 = 42 -KEY_KP9 = 43 -KEY_KPADD = 44 -KEY_KPSUB = 45 -KEY_KPDIV = 46 -KEY_KPMUL = 47 -KEY_KPDEC = 48 -KEY_KPENTER = 49 -KEY_F1 = 50 -KEY_F2 = 51 -KEY_F3 = 52 -KEY_F4 = 53 -KEY_F5 = 54 -KEY_F6 = 55 -KEY_F7 = 56 -KEY_F8 = 57 -KEY_F9 = 58 -KEY_F10 = 59 -KEY_F11 = 60 -KEY_F12 = 61 -KEY_NUMLOCK = 62 -KEY_SCROLLLOCK = 63 -KEY_SPACE = 64 -KEY_CHAR = 65 -# special chars -# single walls -CHAR_HLINE = 196 -CHAR_VLINE = 179 -CHAR_NE = 191 -CHAR_NW = 218 -CHAR_SE = 217 -CHAR_SW = 192 -CHAR_TEEW = 180 -CHAR_TEEE = 195 -CHAR_TEEN = 193 -CHAR_TEES = 194 -CHAR_CROSS = 197 -# double walls -CHAR_DHLINE = 205 -CHAR_DVLINE = 186 -CHAR_DNE = 187 -CHAR_DNW = 201 -CHAR_DSE = 188 -CHAR_DSW = 200 -CHAR_DTEEW = 185 -CHAR_DTEEE = 204 -CHAR_DTEEN = 202 -CHAR_DTEES = 203 -CHAR_DCROSS = 206 -# blocks -CHAR_BLOCK1 = 176 -CHAR_BLOCK2 = 177 -CHAR_BLOCK3 = 178 -# arrows -CHAR_ARROW_N = 24 -CHAR_ARROW_S = 25 -CHAR_ARROW_E = 26 -CHAR_ARROW_W = 27 -# arrows without tail -CHAR_ARROW2_N = 30 -CHAR_ARROW2_S = 31 -CHAR_ARROW2_E = 16 -CHAR_ARROW2_W = 17 -# double arrows -CHAR_DARROW_H = 29 -CHAR_DARROW_V = 18 -# GUI stuff -CHAR_CHECKBOX_UNSET = 224 -CHAR_CHECKBOX_SET = 225 -CHAR_RADIO_UNSET = 9 -CHAR_RADIO_SET = 10 -# sub-pixel resolution kit -CHAR_SUBP_NW = 226 -CHAR_SUBP_NE = 227 -CHAR_SUBP_N = 228 -CHAR_SUBP_SE = 229 -CHAR_SUBP_DIAG = 230 -CHAR_SUBP_E = 231 -CHAR_SUBP_SW = 232 -# misc characters -CHAR_BULLET = 7 -CHAR_BULLET_INV = 8 -CHAR_BULLET_SQUARE = 254 -CHAR_CENT = 189 -CHAR_CLUB = 5 -CHAR_COPYRIGHT = 184 -CHAR_CURRENCY = 207 -CHAR_DIAMOND = 4 -CHAR_DIVISION = 246 -CHAR_EXCLAM_DOUBLE = 19 -CHAR_FEMALE = 12 -CHAR_FUNCTION = 159 -CHAR_GRADE = 248 -CHAR_HALF = 171 -CHAR_HEART = 3 -CHAR_LIGHT = 15 -CHAR_MALE = 11 -CHAR_MULTIPLICATION = 158 -CHAR_NOTE = 13 -CHAR_NOTE_DOUBLE = 14 -CHAR_ONE_QUARTER = 172 -CHAR_PILCROW = 20 -CHAR_POUND = 156 -CHAR_POW1 = 251 -CHAR_POW2 = 253 -CHAR_POW3 = 252 -CHAR_RESERVED = 169 -CHAR_SECTION = 21 -CHAR_SMILIE = 1 -CHAR_SMILIE_INV = 2 -CHAR_SPADE = 6 -CHAR_THREE_QUARTERS = 243 -CHAR_UMLAUT = 249 -CHAR_YEN = 190 -# font flags -FONT_LAYOUT_ASCII_INCOL = 1 -FONT_LAYOUT_ASCII_INROW = 2 -FONT_TYPE_GREYSCALE = 4 -FONT_TYPE_GRAYSCALE = 4 -FONT_LAYOUT_TCOD = 8 -# color control codes -COLCTRL_1=1 -COLCTRL_2=2 -COLCTRL_3=3 -COLCTRL_4=4 -COLCTRL_5=5 -COLCTRL_NUMBER=5 -COLCTRL_FORE_RGB=6 -COLCTRL_BACK_RGB=7 -COLCTRL_STOP=8 -# renderers -RENDERER_GLSL=0 -RENDERER_OPENGL=1 -RENDERER_SDL=2 -NB_RENDERERS=3 -# alignment -LEFT=0 -RIGHT=1 -CENTER=2 -# initializing the console -def console_init_root(w, h, title, fullscreen=False, renderer=RENDERER_SDL): - _lib.TCOD_console_init_root(w, h, c_char_p(title), fullscreen, renderer) - -def console_get_width(con): - return _lib.TCOD_console_get_width(con) - -def console_get_height(con): - return _lib.TCOD_console_get_height(con) - -def console_set_custom_font(fontFile, flags=FONT_LAYOUT_ASCII_INCOL, nb_char_horiz=0, nb_char_vertic=0): - _lib.TCOD_console_set_custom_font(c_char_p(fontFile), flags, nb_char_horiz, nb_char_vertic) - -def console_map_ascii_code_to_font(asciiCode, fontCharX, fontCharY): - if type(asciiCode) == str or type(asciiCode) == bytes: - _lib.TCOD_console_map_ascii_code_to_font(ord(asciiCode), fontCharX, - fontCharY) - else: - _lib.TCOD_console_map_ascii_code_to_font(asciiCode, fontCharX, - fontCharY) - -def console_map_ascii_codes_to_font(firstAsciiCode, nbCodes, fontCharX, - fontCharY): - if type(firstAsciiCode) == str or type(asciiCode) == bytes: - _lib.TCOD_console_map_ascii_codes_to_font(ord(firstAsciiCode), nbCodes, - fontCharX, fontCharY) - else: - _lib.TCOD_console_map_ascii_codes_to_font(firstAsciiCode, nbCodes, - fontCharX, fontCharY) - -def console_map_string_to_font(s, fontCharX, fontCharY): - if type(s) == bytes: - _lib.TCOD_console_map_string_to_font(s, fontCharX, fontCharY) - else: - _lib.TCOD_console_map_string_to_font_utf(s, fontCharX, fontCharY) - -def console_is_fullscreen(): - return _lib.TCOD_console_is_fullscreen() - -def console_set_fullscreen(fullscreen): - _lib.TCOD_console_set_fullscreen(c_int(fullscreen)) - -def console_is_window_closed(): - return _lib.TCOD_console_is_window_closed() - -def console_set_window_title(title): - _lib.TCOD_console_set_window_title(c_char_p(title)) - -def console_credits(): - _lib.TCOD_console_credits() - -def console_credits_reset(): - _lib.TCOD_console_credits_reset() - -def console_credits_render(x, y, alpha): - return _lib.TCOD_console_credits_render(x, y, c_int(alpha)) - -def console_flush(): - _lib.TCOD_console_flush() - -# drawing on a console -def console_set_default_background(con, col): - _lib.TCOD_console_set_default_background(con, col) - -def console_set_default_foreground(con, col): - _lib.TCOD_console_set_default_foreground(con, col) - -def console_clear(con): - return _lib.TCOD_console_clear(con) - -def console_put_char(con, x, y, c, flag=BKGND_DEFAULT): - if type(c) == str or type(c) == bytes: - _lib.TCOD_console_put_char(con, x, y, ord(c), flag) - else: - _lib.TCOD_console_put_char(con, x, y, c, flag) - -def console_put_char_ex(con, x, y, c, fore, back): - if type(c) == str or type(c) == bytes: - _lib.TCOD_console_put_char_ex(con, x, y, ord(c), fore, back) - else: - _lib.TCOD_console_put_char_ex(con, x, y, c, fore, back) - -def console_set_char_background(con, x, y, col, flag=BKGND_SET): - _lib.TCOD_console_set_char_background(con, x, y, col, flag) - -def console_set_char_foreground(con, x, y, col): - _lib.TCOD_console_set_char_foreground(con, x, y, col) - -def console_set_char(con, x, y, c): - if type(c) == str or type(c) == bytes: - _lib.TCOD_console_set_char(con, x, y, ord(c)) - else: - _lib.TCOD_console_set_char(con, x, y, c) - -def console_set_background_flag(con, flag): - _lib.TCOD_console_set_background_flag(con, c_int(flag)) - -def console_get_background_flag(con): - return _lib.TCOD_console_get_background_flag(con) - -def console_set_alignment(con, alignment): - _lib.TCOD_console_set_alignment(con, c_int(alignment)) - -def console_get_alignment(con): - return _lib.TCOD_console_get_alignment(con) - -def console_print(con, x, y, fmt): - if type(fmt) == bytes: - _lib.TCOD_console_print(c_void_p(con), x, y, c_char_p(fmt)) - else: - _lib.TCOD_console_print_utf(c_void_p(con), x, y, fmt) - -def console_print_ex(con, x, y, flag, alignment, fmt): - if type(fmt) == bytes: - _lib.TCOD_console_print_ex(c_void_p(con), x, y, flag, alignment, c_char_p(fmt)) - else: - _lib.TCOD_console_print_ex_utf(c_void_p(con), x, y, flag, alignment, fmt) - -def console_print_rect(con, x, y, w, h, fmt): - if type(fmt) == bytes: - return _lib.TCOD_console_print_rect(c_void_p(con), x, y, w, h, c_char_p(fmt)) - else: - return _lib.TCOD_console_print_rect_utf(c_void_p(con), x, y, w, h, fmt) - -def console_print_rect_ex(con, x, y, w, h, flag, alignment, fmt): - if type(fmt) == bytes: - return _lib.TCOD_console_print_rect_ex(c_void_p(con), x, y, w, h, flag, alignment, c_char_p(fmt)) - else: - return _lib.TCOD_console_print_rect_ex_utf(c_void_p(con), x, y, w, h, flag, alignment, fmt) - -def console_get_height_rect(con, x, y, w, h, fmt): - if type(fmt) == bytes: - return _lib.TCOD_console_get_height_rect(c_void_p(con), x, y, w, h, c_char_p(fmt)) - else: - return _lib.TCOD_console_get_height_rect_utf(c_void_p(con), x, y, w, h, fmt) - -def console_rect(con, x, y, w, h, clr, flag=BKGND_DEFAULT): - _lib.TCOD_console_rect(con, x, y, w, h, c_int(clr), flag) - -def console_hline(con, x, y, l, flag=BKGND_DEFAULT): - _lib.TCOD_console_hline( con, x, y, l, flag) - -def console_vline(con, x, y, l, flag=BKGND_DEFAULT): - _lib.TCOD_console_vline( con, x, y, l, flag) - -def console_print_frame(con, x, y, w, h, clear=True, flag=BKGND_DEFAULT, fmt=0): - _lib.TCOD_console_print_frame(c_void_p(con), x, y, w, h, c_int(clear), flag, c_char_p(fmt)) - -def console_set_color_control(con,fore,back) : - _lib.TCOD_console_set_color_control(con,fore,back) - -def console_get_default_background(con): - return _lib.TCOD_console_get_default_background(con) - -def console_get_default_foreground(con): - return _lib.TCOD_console_get_default_foreground(con) - -def console_get_char_background(con, x, y): - return _lib.TCOD_console_get_char_background(con, x, y) - -def console_get_char_foreground(con, x, y): - return _lib.TCOD_console_get_char_foreground(con, x, y) - -def console_get_char(con, x, y): - return _lib.TCOD_console_get_char(con, x, y) - -def console_set_fade(fade, fadingColor): - _lib.TCOD_console_set_fade(fade, fadingColor) - ##_lib.TCOD_console_set_fade_wrapper(fade, fadingColor) - -def console_get_fade(): - return _lib.TCOD_console_get_fade().value - -def console_get_fading_color(): - return _lib.TCOD_console_get_fading_color() - -# handling keyboard input -def console_wait_for_keypress(flush): - k=Key() - _lib.TCOD_console_wait_for_keypress_wrapper(byref(k),c_bool(flush)) - return k - -def console_check_for_keypress(flags=KEY_RELEASED): - k=Key() - _lib.TCOD_console_check_for_keypress_wrapper(byref(k),c_int(flags)) - return k - -def console_is_key_pressed(key): - return _lib.TCOD_console_is_key_pressed(key) - -def console_set_keyboard_repeat(initial_delay, interval): - _lib.TCOD_console_set_keyboard_repeat(initial_delay, interval) - -def console_disable_keyboard_repeat(): - _lib.TCOD_console_disable_keyboard_repeat() - -# using offscreen consoles -def console_new(w, h): - return _lib.TCOD_console_new(w, h) -def console_from_file(filename): - return _lib.TCOD_console_from_file(filename) -def console_get_width(con): - return _lib.TCOD_console_get_width(con) - -def console_get_height(con): - return _lib.TCOD_console_get_height(con) - -def console_blit(src, x, y, w, h, dst, xdst, ydst, ffade=1.0,bfade=1.0): - _lib.TCOD_console_blit(src, x, y, w, h, dst, xdst, ydst, c_float(ffade), c_float(bfade)) - -def console_set_key_color(con, col): - _lib.TCOD_console_set_key_color(con, col) - -def console_delete(con): - _lib.TCOD_console_delete(con) - -# fast color filling -def console_fill_foreground(con,r,g,b) : - if len(r) != len(g) or len(r) != len(b): - raise TypeError('R, G and B must all have the same size.') - - if (numpy_available and isinstance(r, numpy.ndarray) and - isinstance(g, numpy.ndarray) and isinstance(b, numpy.ndarray)): - #numpy arrays, use numpy's ctypes functions - r = numpy.ascontiguousarray(r, dtype=numpy.int32) - g = numpy.ascontiguousarray(g, dtype=numpy.int32) - b = numpy.ascontiguousarray(b, dtype=numpy.int32) - cr = r.ctypes.data_as(POINTER(c_int)) - cg = g.ctypes.data_as(POINTER(c_int)) - cb = b.ctypes.data_as(POINTER(c_int)) - else: - # otherwise convert using ctypes arrays - cr = (c_int * len(r))(*r) - cg = (c_int * len(g))(*g) - cb = (c_int * len(b))(*b) - - _lib.TCOD_console_fill_foreground(con, cr, cg, cb) - -def console_fill_background(con,r,g,b) : - if len(r) != len(g) or len(r) != len(b): - raise TypeError('R, G and B must all have the same size.') - - if (numpy_available and isinstance(r, numpy.ndarray) and - isinstance(g, numpy.ndarray) and isinstance(b, numpy.ndarray)): - #numpy arrays, use numpy's ctypes functions - r = numpy.ascontiguousarray(r, dtype=numpy.int32) - g = numpy.ascontiguousarray(g, dtype=numpy.int32) - b = numpy.ascontiguousarray(b, dtype=numpy.int32) - cr = r.ctypes.data_as(POINTER(c_int)) - cg = g.ctypes.data_as(POINTER(c_int)) - cb = b.ctypes.data_as(POINTER(c_int)) - else: - # otherwise convert using ctypes arrays - cr = (c_int * len(r))(*r) - cg = (c_int * len(g))(*g) - cb = (c_int * len(b))(*b) - - _lib.TCOD_console_fill_background(con, cr, cg, cb) - -def console_fill_char(con,arr) : - if (numpy_available and isinstance(arr, numpy.ndarray) ): - #numpy arrays, use numpy's ctypes functions - arr = numpy.ascontiguousarray(arr, dtype=numpy.int32) - carr = arr.ctypes.data_as(POINTER(c_int)) - else: - #otherwise convert using the struct module - carr = struct.pack('%di' % len(arr), *arr) - - _lib.TCOD_console_fill_char(con, carr) - -def console_load_asc(con, filename) : - _lib.TCOD_console_load_asc(con,filename) -def console_save_asc(con, filename) : - _lib.TCOD_console_save_asc(con,filename) -def console_load_apf(con, filename) : - _lib.TCOD_console_load_apf(con,filename) -def console_save_apf(con, filename) : - _lib.TCOD_console_save_apf(con,filename) - -############################ -# sys module -############################ -_lib.TCOD_sys_get_last_frame_length.restype = c_float -_lib.TCOD_sys_elapsed_seconds.restype = c_float - -# high precision time functions -def sys_set_fps(fps): - _lib.TCOD_sys_set_fps(fps) - -def sys_get_fps(): - return _lib.TCOD_sys_get_fps() - -def sys_get_last_frame_length(): - return _lib.TCOD_sys_get_last_frame_length() - -def sys_sleep_milli(val): - _lib.TCOD_sys_sleep_milli(c_uint(val)) - -def sys_elapsed_milli(): - return _lib.TCOD_sys_elapsed_milli() - -def sys_elapsed_seconds(): - return _lib.TCOD_sys_elapsed_seconds() - -def sys_set_renderer(renderer): - _lib.TCOD_sys_set_renderer(renderer) - -def sys_get_renderer(): - return _lib.TCOD_sys_get_renderer() - -# easy screenshots -def sys_save_screenshot(name=0): - _lib.TCOD_sys_save_screenshot(c_char_p(name)) - -# custom fullscreen resolution -def sys_force_fullscreen_resolution(width, height): - _lib.TCOD_sys_force_fullscreen_resolution(width, height) - -def sys_get_current_resolution(): - w = c_int() - h = c_int() - _lib.TCOD_sys_get_current_resolution(byref(w), byref(h)) - return w.value, h.value - -def sys_get_char_size(): - w = c_int() - h = c_int() - _lib.TCOD_sys_get_char_size(byref(w), byref(h)) - return w.value, h.value - -# update font bitmap -def sys_update_char(asciiCode, fontx, fonty, img, x, y) : - _lib.TCOD_sys_update_char(c_int(asciiCode),c_int(fontx),c_int(fonty),img,c_int(x),c_int(y)) - -# custom SDL post renderer -SDL_RENDERER_FUNC = CFUNCTYPE(None, c_void_p) -def sys_register_SDL_renderer(callback): - global sdl_renderer_func - sdl_renderer_func = SDL_RENDERER_FUNC(callback) - _lib.TCOD_sys_register_SDL_renderer(sdl_renderer_func) - -# events -EVENT_KEY_PRESS=1 -EVENT_KEY_RELEASE=2 -EVENT_KEY=EVENT_KEY_PRESS|EVENT_KEY_RELEASE -EVENT_MOUSE_MOVE=4 -EVENT_MOUSE_PRESS=8 -EVENT_MOUSE_RELEASE=16 -EVENT_MOUSE=EVENT_MOUSE_MOVE|EVENT_MOUSE_PRESS|EVENT_MOUSE_RELEASE -EVENT_ANY=EVENT_KEY|EVENT_MOUSE -def sys_check_for_event(mask,k,m) : - return _lib.TCOD_sys_check_for_event(c_int(mask),byref(k),byref(m)) - -def sys_wait_for_event(mask,k,m,flush) : - return _lib.TCOD_sys_wait_for_event(c_int(mask),byref(k),byref(m),c_bool(flush)) - -############################ -# line module -############################ -_lib.TCOD_line_step.restype = c_bool -_lib.TCOD_line.restype=c_bool -_lib.TCOD_line_step_mt.restype = c_bool - -def line_init(xo, yo, xd, yd): - _lib.TCOD_line_init(xo, yo, xd, yd) - -def line_step(): - x = c_int() - y = c_int() - ret = _lib.TCOD_line_step(byref(x), byref(y)) - if not ret: - return x.value, y.value - return None,None - -def line(xo,yo,xd,yd,py_callback) : - LINE_CBK_FUNC=CFUNCTYPE(c_bool,c_int,c_int) - c_callback=LINE_CBK_FUNC(py_callback) - return _lib.TCOD_line(xo,yo,xd,yd,c_callback) - -def line_iter(xo, yo, xd, yd): - data = (c_int * 9)() # struct TCOD_bresenham_data_t - _lib.TCOD_line_init_mt(xo, yo, xd, yd, data) - x = c_int(xo) - y = c_int(yo) - done = False - while not done: - yield x.value, y.value - done = _lib.TCOD_line_step_mt(byref(x), byref(y), data) - -############################ -# image module -############################ -_lib.TCOD_image_is_pixel_transparent.restype = c_bool -_lib.TCOD_image_get_pixel.restype = Color -_lib.TCOD_image_get_mipmap_pixel.restype = Color - -def image_new(width, height): - return _lib.TCOD_image_new(width, height) - -def image_clear(image,col) : - _lib.TCOD_image_clear(image,col) - -def image_invert(image) : - _lib.TCOD_image_invert(image) - -def image_hflip(image) : - _lib.TCOD_image_hflip(image) - -def image_rotate90(image, num=1) : - _lib.TCOD_image_rotate90(image,num) - -def image_vflip(image) : - _lib.TCOD_image_vflip(image) - -def image_scale(image, neww, newh) : - _lib.TCOD_image_scale(image,c_int(neww),c_int(newh)) - -def image_set_key_color(image,col) : - _lib.TCOD_image_set_key_color(image,col) - -def image_get_alpha(image,x,y) : - return _lib.TCOD_image_get_alpha(image,c_int(x),c_int(y)) - -def image_is_pixel_transparent(image,x,y) : - return _lib.TCOD_image_is_pixel_transparent(image,c_int(x),c_int(y)) - -def image_load(filename): - return _lib.TCOD_image_load(c_char_p(filename)) - -def image_from_console(console): - return _lib.TCOD_image_from_console(console) - -def image_refresh_console(image, console): - _lib.TCOD_image_refresh_console(image, console) - -def image_get_size(image): - w=c_int() - h=c_int() - _lib.TCOD_image_get_size(image, byref(w), byref(h)) - return w.value, h.value - -def image_get_pixel(image, x, y): - return _lib.TCOD_image_get_pixel(image, x, y) - -def image_get_mipmap_pixel(image, x0, y0, x1, y1): - return _lib.TCOD_image_get_mipmap_pixel(image, c_float(x0), c_float(y0), - c_float(x1), c_float(y1)) -def image_put_pixel(image, x, y, col): - _lib.TCOD_image_put_pixel(image, x, y, col) - ##_lib.TCOD_image_put_pixel_wrapper(image, x, y, col) - -def image_blit(image, console, x, y, bkgnd_flag, scalex, scaley, angle): - _lib.TCOD_image_blit(image, console, c_float(x), c_float(y), bkgnd_flag, - c_float(scalex), c_float(scaley), c_float(angle)) - -def image_blit_rect(image, console, x, y, w, h, bkgnd_flag): - _lib.TCOD_image_blit_rect(image, console, x, y, w, h, bkgnd_flag) - -def image_blit_2x(image, console, dx, dy, sx=0, sy=0, w=-1, h=-1): - _lib.TCOD_image_blit_2x(image, console, dx,dy,sx,sy,w,h) - -def image_save(image, filename): - _lib.TCOD_image_save(image, c_char_p(filename)) - -def image_delete(image): - _lib.TCOD_image_delete(image) - -############################ -# mouse module -############################ -class Mouse(Structure): - _fields_=[('x', c_int), - ('y', c_int), - ('dx', c_int), - ('dy', c_int), - ('cx', c_int), - ('cy', c_int), - ('dcx', c_int), - ('dcy', c_int), - ('lbutton', c_bool), - ('rbutton', c_bool), - ('mbutton', c_bool), - ('lbutton_pressed', c_bool), - ('rbutton_pressed', c_bool), - ('mbutton_pressed', c_bool), - ('wheel_up', c_bool), - ('wheel_down', c_bool), - ] - -_lib.TCOD_mouse_is_cursor_visible.restype = c_bool - -def mouse_show_cursor(visible): - _lib.TCOD_mouse_show_cursor(c_int(visible)) - -def mouse_is_cursor_visible(): - return _lib.TCOD_mouse_is_cursor_visible() - -def mouse_move(x, y): - _lib.TCOD_mouse_move(x, y) - -def mouse_get_status(): - mouse=Mouse() - _lib.TCOD_mouse_get_status_wrapper(byref(mouse)) - return mouse - -############################ -# parser module -############################ -_lib.TCOD_struct_get_name.restype = c_char_p -_lib.TCOD_struct_is_mandatory.restype = c_bool -_lib.TCOD_parser_get_bool_property.restype = c_bool -_lib.TCOD_parser_get_float_property.restype = c_float -_lib.TCOD_parser_get_string_property.restype = c_char_p -_lib.TCOD_parser_get_color_property.restype = Color - -class Dice(Structure): - _fields_=[('nb_dices', c_int), - ('nb_faces', c_int), - ('multiplier', c_float), - ('addsub', c_float), - ] - - def __repr__(self): - return "Dice(%d, %d, %s, %s)" % (self.nb_dices, self.nb_faces, - self.multiplier, self.addsub) - -class _CValue(Union): - _fields_=[('c',c_uint8), - ('i',c_int), - ('f',c_float), - ('s',c_char_p), - # JBR03192012 See http://bugs.python.org/issue14354 for why these are not defined as their actual types - ('col',c_uint8 * 3), - ('dice',c_int * 4), - ('custom',c_void_p), - ] - -_CFUNC_NEW_STRUCT = CFUNCTYPE(c_uint, c_void_p, c_char_p) -_CFUNC_NEW_FLAG = CFUNCTYPE(c_uint, c_char_p) -_CFUNC_NEW_PROPERTY = CFUNCTYPE(c_uint, c_char_p, c_int, _CValue) - -class _CParserListener(Structure): - _fields_=[('new_struct', _CFUNC_NEW_STRUCT), - ('new_flag',_CFUNC_NEW_FLAG), - ('new_property',_CFUNC_NEW_PROPERTY), - ('end_struct',_CFUNC_NEW_STRUCT), - ('error',_CFUNC_NEW_FLAG), - ] - -# property types -TYPE_NONE = 0 -TYPE_BOOL = 1 -TYPE_CHAR = 2 -TYPE_INT = 3 -TYPE_FLOAT = 4 -TYPE_STRING = 5 -TYPE_COLOR = 6 -TYPE_DICE = 7 -TYPE_VALUELIST00 = 8 -TYPE_VALUELIST01 = 9 -TYPE_VALUELIST02 = 10 -TYPE_VALUELIST03 = 11 -TYPE_VALUELIST04 = 12 -TYPE_VALUELIST05 = 13 -TYPE_VALUELIST06 = 14 -TYPE_VALUELIST07 = 15 -TYPE_VALUELIST08 = 16 -TYPE_VALUELIST09 = 17 -TYPE_VALUELIST10 = 18 -TYPE_VALUELIST11 = 19 -TYPE_VALUELIST12 = 20 -TYPE_VALUELIST13 = 21 -TYPE_VALUELIST14 = 22 -TYPE_VALUELIST15 = 23 -TYPE_LIST = 1024 - -def _convert_TCODList(clist, typ): - res = list() - for i in range(_lib.TCOD_list_size(clist)): - elt = _lib.TCOD_list_get(clist, i) - elt = cast(elt, c_void_p) - if typ == TYPE_BOOL: - elt = c_bool.from_buffer(elt).value - elif typ == TYPE_CHAR: - elt = c_char.from_buffer(elt).value - elif typ == TYPE_INT: - elt = c_int.from_buffer(elt).value - elif typ == TYPE_FLOAT: - elt = c_float.from_buffer(elt).value - elif typ == TYPE_STRING or TYPE_VALUELIST15 >= typ >= TYPE_VALUELIST00: - elt = cast(elt, c_char_p).value - elif typ == TYPE_COLOR: - elt = Color.from_buffer_copy(elt) - elif typ == TYPE_DICE: - # doesn't work - elt = Dice.from_buffer_copy(elt) - res.append(elt) - return res - -def parser_new(): - return _lib.TCOD_parser_new() - -def parser_new_struct(parser, name): - return _lib.TCOD_parser_new_struct(parser, name) - -def struct_add_flag(struct, name): - _lib.TCOD_struct_add_flag(struct, name) - -def struct_add_property(struct, name, typ, mandatory): - _lib.TCOD_struct_add_property(struct, name, typ, c_bool(mandatory)) - -def struct_add_value_list(struct, name, value_list, mandatory): - CARRAY = c_char_p * (len(value_list) + 1) - cvalue_list = CARRAY() - for i in range(len(value_list)): - cvalue_list[i] = cast(value_list[i], c_char_p) - cvalue_list[len(value_list)] = 0 - _lib.TCOD_struct_add_value_list(struct, name, cvalue_list, c_bool(mandatory)) - -def struct_add_list_property(struct, name, typ, mandatory): - _lib.TCOD_struct_add_list_property(struct, name, typ, c_bool(mandatory)) - -def struct_add_structure(struct, sub_struct): - _lib.TCOD_struct_add_structure(struct, sub_struct) - -def struct_get_name(struct): - return _lib.TCOD_struct_get_name(struct) - -def struct_is_mandatory(struct, name): - return _lib.TCOD_struct_is_mandatory(struct, name) - -def struct_get_type(struct, name): - return _lib.TCOD_struct_get_type(struct, name) - -def parser_run(parser, filename, listener=0): - if listener != 0: - clistener=_CParserListener() - def value_converter(name, typ, value): - if typ == TYPE_BOOL: - return listener.new_property(name, typ, value.c == 1) - elif typ == TYPE_CHAR: - return listener.new_property(name, typ, '%c' % (value.c & 0xFF)) - elif typ == TYPE_INT: - return listener.new_property(name, typ, value.i) - elif typ == TYPE_FLOAT: - return listener.new_property(name, typ, value.f) - elif typ == TYPE_STRING or \ - TYPE_VALUELIST15 >= typ >= TYPE_VALUELIST00: - return listener.new_property(name, typ, value.s) - elif typ == TYPE_COLOR: - col = cast(value.col, POINTER(Color)).contents - return listener.new_property(name, typ, col) - elif typ == TYPE_DICE: - dice = cast(value.dice, POINTER(Dice)).contents - return listener.new_property(name, typ, dice) - elif typ & TYPE_LIST: - return listener.new_property(name, typ, - _convert_TCODList(value.custom, typ & 0xFF)) - return True - clistener.new_struct = _CFUNC_NEW_STRUCT(listener.new_struct) - clistener.new_flag = _CFUNC_NEW_FLAG(listener.new_flag) - clistener.new_property = _CFUNC_NEW_PROPERTY(value_converter) - clistener.end_struct = _CFUNC_NEW_STRUCT(listener.end_struct) - clistener.error = _CFUNC_NEW_FLAG(listener.error) - _lib.TCOD_parser_run(parser, c_char_p(filename), byref(clistener)) - else: - _lib.TCOD_parser_run(parser, c_char_p(filename), 0) - -def parser_delete(parser): - _lib.TCOD_parser_delete(parser) - -def parser_get_bool_property(parser, name): - return _lib.TCOD_parser_get_bool_property(parser, c_char_p(name)) - -def parser_get_int_property(parser, name): - return _lib.TCOD_parser_get_int_property(parser, c_char_p(name)) - -def parser_get_char_property(parser, name): - return '%c' % _lib.TCOD_parser_get_char_property(parser, c_char_p(name)) - -def parser_get_float_property(parser, name): - return _lib.TCOD_parser_get_float_property(parser, c_char_p(name)) - -def parser_get_string_property(parser, name): - return _lib.TCOD_parser_get_string_property(parser, c_char_p(name)) - -def parser_get_color_property(parser, name): - return _lib.TCOD_parser_get_color_property(parser, c_char_p(name)) - -def parser_get_dice_property(parser, name): - d = Dice() - _lib.TCOD_parser_get_dice_property_py(c_void_p(parser), c_char_p(name), byref(d)) - return d - -def parser_get_list_property(parser, name, typ): - clist = _lib.TCOD_parser_get_list_property(parser, c_char_p(name), c_int(typ)) - return _convert_TCODList(clist, typ) - -############################ -# random module -############################ -_lib.TCOD_random_get_float.restype = c_float -_lib.TCOD_random_get_double.restype = c_double - -RNG_MT = 0 -RNG_CMWC = 1 - -DISTRIBUTION_LINEAR = 0 -DISTRIBUTION_GAUSSIAN = 1 -DISTRIBUTION_GAUSSIAN_RANGE = 2 -DISTRIBUTION_GAUSSIAN_INVERSE = 3 -DISTRIBUTION_GAUSSIAN_RANGE_INVERSE = 4 - -def random_get_instance(): - return _lib.TCOD_random_get_instance() - -def random_new(algo=RNG_CMWC): - return _lib.TCOD_random_new(algo) - -def random_new_from_seed(seed, algo=RNG_CMWC): - return _lib.TCOD_random_new_from_seed(algo,c_uint(seed)) - -def random_set_distribution(rnd, dist) : - _lib.TCOD_random_set_distribution(rnd, dist) - -def random_get_int(rnd, mi, ma): - return _lib.TCOD_random_get_int(rnd, mi, ma) - -def random_get_float(rnd, mi, ma): - return _lib.TCOD_random_get_float(rnd, c_float(mi), c_float(ma)) - -def random_get_double(rnd, mi, ma): - return _lib.TCOD_random_get_double(rnd, c_double(mi), c_double(ma)) - -def random_get_int_mean(rnd, mi, ma, mean): - return _lib.TCOD_random_get_int_mean(rnd, mi, ma, mean) - -def random_get_float_mean(rnd, mi, ma, mean): - return _lib.TCOD_random_get_float_mean(rnd, c_float(mi), c_float(ma), c_float(mean)) - -def random_get_double_mean(rnd, mi, ma, mean): - return _lib.TCOD_random_get_double_mean(rnd, c_double(mi), c_double(ma), c_double(mean)) - -def random_save(rnd): - return _lib.TCOD_random_save(rnd) - -def random_restore(rnd, backup): - _lib.TCOD_random_restore(rnd, backup) - -def random_delete(rnd): - _lib.TCOD_random_delete(rnd) - -############################ -# noise module -############################ -_lib.TCOD_noise_get.restype = c_float -_lib.TCOD_noise_get_ex.restype = c_float -_lib.TCOD_noise_get_fbm.restype = c_float -_lib.TCOD_noise_get_fbm_ex.restype = c_float -_lib.TCOD_noise_get_turbulence.restype = c_float -_lib.TCOD_noise_get_turbulence_ex.restype = c_float - -NOISE_DEFAULT_HURST = 0.5 -NOISE_DEFAULT_LACUNARITY = 2.0 - -NOISE_DEFAULT = 0 -NOISE_PERLIN = 1 -NOISE_SIMPLEX = 2 -NOISE_WAVELET = 4 - -_NOISE_PACKER_FUNC = (None, - (c_float * 1), - (c_float * 2), - (c_float * 3), - (c_float * 4), - ) - -def noise_new(dim, h=NOISE_DEFAULT_HURST, l=NOISE_DEFAULT_LACUNARITY, random=0): - return _lib.TCOD_noise_new(dim, c_float(h), c_float(l), random) - -def noise_set_type(n, typ) : - _lib.TCOD_noise_set_type(n,typ) - -def noise_get(n, f, typ=NOISE_DEFAULT): - return _lib.TCOD_noise_get_ex(n, _NOISE_PACKER_FUNC[len(f)](*f), typ) - -def noise_get_fbm(n, f, oc, typ=NOISE_DEFAULT): - return _lib.TCOD_noise_get_fbm_ex(n, _NOISE_PACKER_FUNC[len(f)](*f), c_float(oc), typ) - -def noise_get_turbulence(n, f, oc, typ=NOISE_DEFAULT): - return _lib.TCOD_noise_get_turbulence_ex(n, _NOISE_PACKER_FUNC[len(f)](*f), c_float(oc), typ) - -def noise_delete(n): - _lib.TCOD_noise_delete(n) - -############################ -# fov module -############################ -_lib.TCOD_map_is_in_fov.restype = c_bool -_lib.TCOD_map_is_transparent.restype = c_bool -_lib.TCOD_map_is_walkable.restype = c_bool - -FOV_BASIC = 0 -FOV_DIAMOND = 1 -FOV_SHADOW = 2 -FOV_PERMISSIVE_0 = 3 -FOV_PERMISSIVE_1 = 4 -FOV_PERMISSIVE_2 = 5 -FOV_PERMISSIVE_3 = 6 -FOV_PERMISSIVE_4 = 7 -FOV_PERMISSIVE_5 = 8 -FOV_PERMISSIVE_6 = 9 -FOV_PERMISSIVE_7 = 10 -FOV_PERMISSIVE_8 = 11 -FOV_RESTRICTIVE = 12 -NB_FOV_ALGORITHMS = 13 - -def FOV_PERMISSIVE(p) : - return FOV_PERMISSIVE_0+p - -def map_new(w, h): - return _lib.TCOD_map_new(w, h) - -def map_copy(source, dest): - return _lib.TCOD_map_copy(source, dest) - -def map_set_properties(m, x, y, isTrans, isWalk): - _lib.TCOD_map_set_properties(m, x, y, c_int(isTrans), c_int(isWalk)) - -def map_clear(m,walkable=False,transparent=False): - _lib.TCOD_map_clear(m,c_int(walkable),c_int(transparent)) - -def map_compute_fov(m, x, y, radius=0, light_walls=True, algo=FOV_RESTRICTIVE ): - _lib.TCOD_map_compute_fov(m, x, y, c_int(radius), c_bool(light_walls), c_int(algo)) - -def map_is_in_fov(m, x, y): - return _lib.TCOD_map_is_in_fov(m, x, y) - -def map_is_transparent(m, x, y): - return _lib.TCOD_map_is_transparent(m, x, y) - -def map_is_walkable(m, x, y): - return _lib.TCOD_map_is_walkable(m, x, y) - -def map_delete(m): - return _lib.TCOD_map_delete(m) - -def map_get_width(map): - return _lib.TCOD_map_get_width(map) - -def map_get_height(map): - return _lib.TCOD_map_get_height(map) - -############################ -# pathfinding module -############################ -_lib.TCOD_path_compute.restype = c_bool -_lib.TCOD_path_is_empty.restype = c_bool -_lib.TCOD_path_walk.restype = c_bool - -PATH_CBK_FUNC = CFUNCTYPE(c_float, c_int, c_int, c_int, c_int, py_object) - -def path_new_using_map(m, dcost=1.41): - return (_lib.TCOD_path_new_using_map(c_void_p(m), c_float(dcost)), None) - -def path_new_using_function(w, h, func, userdata=0, dcost=1.41): - cbk_func = PATH_CBK_FUNC(func) - return (_lib.TCOD_path_new_using_function(w, h, cbk_func, - py_object(userdata), c_float(dcost)), cbk_func) - -def path_compute(p, ox, oy, dx, dy): - return _lib.TCOD_path_compute(p[0], ox, oy, dx, dy) - -def path_get_origin(p): - x = c_int() - y = c_int() - _lib.TCOD_path_get_origin(p[0], byref(x), byref(y)) - return x.value, y.value - -def path_get_destination(p): - x = c_int() - y = c_int() - _lib.TCOD_path_get_destination(p[0], byref(x), byref(y)) - return x.value, y.value - -def path_size(p): - return _lib.TCOD_path_size(p[0]) - -def path_reverse(p): - _lib.TCOD_path_reverse(p[0]) - -def path_get(p, idx): - x = c_int() - y = c_int() - _lib.TCOD_path_get(p[0], idx, byref(x), byref(y)) - return x.value, y.value - -def path_is_empty(p): - return _lib.TCOD_path_is_empty(p[0]) - -def path_walk(p, recompute): - x = c_int() - y = c_int() - if _lib.TCOD_path_walk(p[0], byref(x), byref(y), c_int(recompute)): - return x.value, y.value - return None,None - -def path_delete(p): - _lib.TCOD_path_delete(p[0]) - -_lib.TCOD_dijkstra_path_set.restype = c_bool -_lib.TCOD_dijkstra_is_empty.restype = c_bool -_lib.TCOD_dijkstra_path_walk.restype = c_bool -_lib.TCOD_dijkstra_get_distance.restype = c_float - -def dijkstra_new(m, dcost=1.41): - return (_lib.TCOD_dijkstra_new(c_void_p(m), c_float(dcost)), None) - -def dijkstra_new_using_function(w, h, func, userdata=0, dcost=1.41): - cbk_func = PATH_CBK_FUNC(func) - return (_lib.TCOD_path_dijkstra_using_function(w, h, cbk_func, - py_object(userdata), c_float(dcost)), cbk_func) - -def dijkstra_compute(p, ox, oy): - _lib.TCOD_dijkstra_compute(p[0], c_int(ox), c_int(oy)) - -def dijkstra_path_set(p, x, y): - return _lib.TCOD_dijkstra_path_set(p[0], c_int(x), c_int(y)) - -def dijkstra_get_distance(p, x, y): - return _lib.TCOD_dijkstra_get_distance(p[0], c_int(x), c_int(y)) - -def dijkstra_size(p): - return _lib.TCOD_dijkstra_size(p[0]) - -def dijkstra_reverse(p): - _lib.TCOD_dijkstra_reverse(p[0]) - -def dijkstra_get(p, idx): - x = c_int() - y = c_int() - _lib.TCOD_dijkstra_get(p[0], c_int(idx), byref(x), byref(y)) - return x.value, y.value - -def dijkstra_is_empty(p): - return _lib.TCOD_dijkstra_is_empty(p[0]) - -def dijkstra_path_walk(p): - x = c_int() - y = c_int() - if _lib.TCOD_dijkstra_path_walk(p[0], byref(x), byref(y)): - return x.value, y.value - return None,None - -def dijkstra_delete(p): - _lib.TCOD_dijkstra_delete(p[0]) - -############################ -# bsp module -############################ -class _CBsp(Structure): - _fields_ = [('next', c_void_p), - ('father', c_void_p), - ('son', c_void_p), - ('x', c_int), - ('y', c_int), - ('w', c_int), - ('h', c_int), - ('position', c_int), - ('level', c_uint8), - ('horizontal', c_bool), - ] - -_lib.TCOD_bsp_new_with_size.restype = POINTER(_CBsp) -_lib.TCOD_bsp_left.restype = POINTER(_CBsp) -_lib.TCOD_bsp_right.restype = POINTER(_CBsp) -_lib.TCOD_bsp_father.restype = POINTER(_CBsp) -_lib.TCOD_bsp_is_leaf.restype = c_bool -_lib.TCOD_bsp_contains.restype = c_bool -_lib.TCOD_bsp_find_node.restype = POINTER(_CBsp) - -BSP_CBK_FUNC = CFUNCTYPE(c_int, c_void_p, c_void_p) - -# python class encapsulating the _CBsp pointer -class Bsp(object): - def __init__(self, cnode): - pcbsp = cast(cnode, POINTER(_CBsp)) - self.p = pcbsp - - def getx(self): - return self.p.contents.x - def setx(self, value): - self.p.contents.x = value - x = property(getx, setx) - - def gety(self): - return self.p.contents.y - def sety(self, value): - self.p.contents.y = value - y = property(gety, sety) - - def getw(self): - return self.p.contents.w - def setw(self, value): - self.p.contents.w = value - w = property(getw, setw) - - def geth(self): - return self.p.contents.h - def seth(self, value): - self.p.contents.h = value - h = property(geth, seth) - - def getpos(self): - return self.p.contents.position - def setpos(self, value): - self.p.contents.position = value - position = property(getpos, setpos) - - def gethor(self): - return self.p.contents.horizontal - def sethor(self,value): - self.p.contents.horizontal = value - horizontal = property(gethor, sethor) - - def getlev(self): - return self.p.contents.level - def setlev(self,value): - self.p.contents.level = value - level = property(getlev, setlev) - - -def bsp_new_with_size(x, y, w, h): - return Bsp(_lib.TCOD_bsp_new_with_size(x, y, w, h)) - -def bsp_split_once(node, horizontal, position): - _lib.TCOD_bsp_split_once(node.p, c_int(horizontal), position) - -def bsp_split_recursive(node, randomizer, nb, minHSize, minVSize, maxHRatio, - maxVRatio): - _lib.TCOD_bsp_split_recursive(node.p, randomizer, nb, minHSize, minVSize, - c_float(maxHRatio), c_float(maxVRatio)) - -def bsp_resize(node, x, y, w, h): - _lib.TCOD_bsp_resize(node.p, x, y, w, h) - -def bsp_left(node): - return Bsp(_lib.TCOD_bsp_left(node.p)) - -def bsp_right(node): - return Bsp(_lib.TCOD_bsp_right(node.p)) - -def bsp_father(node): - return Bsp(_lib.TCOD_bsp_father(node.p)) - -def bsp_is_leaf(node): - return _lib.TCOD_bsp_is_leaf(node.p) - -def bsp_contains(node, cx, cy): - return _lib.TCOD_bsp_contains(node.p, cx, cy) - -def bsp_find_node(node, cx, cy): - return Bsp(_lib.TCOD_bsp_find_node(node.p, cx, cy)) - -def _bsp_traverse(node, callback, userData, func): - # convert the c node into a python node - #before passing it to the actual callback - def node_converter(cnode, data): - node = Bsp(cnode) - return callback(node, data) - cbk_func = BSP_CBK_FUNC(node_converter) - func(node.p, cbk_func, userData) - -def bsp_traverse_pre_order(node, callback, userData=0): - _bsp_traverse(node, callback, userData, _lib.TCOD_bsp_traverse_pre_order) - -def bsp_traverse_in_order(node, callback, userData=0): - _bsp_traverse(node, callback, userData, _lib.TCOD_bsp_traverse_in_order) - -def bsp_traverse_post_order(node, callback, userData=0): - _bsp_traverse(node, callback, userData, _lib.TCOD_bsp_traverse_post_order) - -def bsp_traverse_level_order(node, callback, userData=0): - _bsp_traverse(node, callback, userData, _lib.TCOD_bsp_traverse_level_order) - -def bsp_traverse_inverted_level_order(node, callback, userData=0): - _bsp_traverse(node, callback, userData, - _lib.TCOD_bsp_traverse_inverted_level_order) - -def bsp_remove_sons(node): - _lib.TCOD_bsp_remove_sons(node.p) - -def bsp_delete(node): - _lib.TCOD_bsp_delete(node.p) - -############################ -# heightmap module -############################ -class _CHeightMap(Structure): - _fields_=[('w', c_int), - ('h', c_int), - ('values', POINTER(c_float)), - ] - -_lib.TCOD_heightmap_new.restype = POINTER(_CHeightMap) -_lib.TCOD_heightmap_get_value.restype = c_float -_lib.TCOD_heightmap_has_land_on_border.restype = c_bool - -class HeightMap(object): - def __init__(self, chm): - pchm = cast(chm, POINTER(_CHeightMap)) - self.p = pchm - - def getw(self): - return self.p.contents.w - def setw(self, value): - self.p.contents.w = value - w = property(getw, setw) - - def geth(self): - return self.p.contents.h - def seth(self, value): - self.p.contents.h = value - h = property(geth, seth) - -def heightmap_new(w, h): - phm = _lib.TCOD_heightmap_new(w, h) - return HeightMap(phm) - -def heightmap_set_value(hm, x, y, value): - _lib.TCOD_heightmap_set_value(hm.p, x, y, c_float(value)) - -def heightmap_add(hm, value): - _lib.TCOD_heightmap_add(hm.p, c_float(value)) - -def heightmap_scale(hm, value): - _lib.TCOD_heightmap_scale(hm.p, c_float(value)) - -def heightmap_clear(hm): - _lib.TCOD_heightmap_clear(hm.p) - -def heightmap_clamp(hm, mi, ma): - _lib.TCOD_heightmap_clamp(hm.p, c_float(mi),c_float(ma)) - -def heightmap_copy(hm1, hm2): - _lib.TCOD_heightmap_copy(hm1.p, hm2.p) - -def heightmap_normalize(hm, mi=0.0, ma=1.0): - _lib.TCOD_heightmap_normalize(hm.p, c_float(mi), c_float(ma)) - -def heightmap_lerp_hm(hm1, hm2, hm3, coef): - _lib.TCOD_heightmap_lerp_hm(hm1.p, hm2.p, hm3.p, c_float(coef)) - -def heightmap_add_hm(hm1, hm2, hm3): - _lib.TCOD_heightmap_add_hm(hm1.p, hm2.p, hm3.p) - -def heightmap_multiply_hm(hm1, hm2, hm3): - _lib.TCOD_heightmap_multiply_hm(hm1.p, hm2.p, hm3.p) - -def heightmap_add_hill(hm, x, y, radius, height): - _lib.TCOD_heightmap_add_hill(hm.p, c_float( x), c_float( y), - c_float( radius), c_float( height)) - -def heightmap_dig_hill(hm, x, y, radius, height): - _lib.TCOD_heightmap_dig_hill(hm.p, c_float( x), c_float( y), - c_float( radius), c_float( height)) - -def heightmap_rain_erosion(hm, nbDrops, erosionCoef, sedimentationCoef, rnd=0): - _lib.TCOD_heightmap_rain_erosion(hm.p, nbDrops, c_float( erosionCoef), - c_float( sedimentationCoef), rnd) - -def heightmap_kernel_transform(hm, kernelsize, dx, dy, weight, minLevel, - maxLevel): - FARRAY = c_float * kernelsize - IARRAY = c_int * kernelsize - cdx = IARRAY(*dx) - cdy = IARRAY(*dy) - cweight = FARRAY(*weight) - _lib.TCOD_heightmap_kernel_transform(hm.p, kernelsize, cdx, cdy, cweight, - c_float(minLevel), c_float(maxLevel)) - -def heightmap_add_voronoi(hm, nbPoints, nbCoef, coef, rnd=0): - FARRAY = c_float * nbCoef - ccoef = FARRAY(*coef) - _lib.TCOD_heightmap_add_voronoi(hm.p, nbPoints, nbCoef, ccoef, rnd) - -def heightmap_add_fbm(hm, noise, mulx, muly, addx, addy, octaves, delta, scale): - _lib.TCOD_heightmap_add_fbm(hm.p, noise, c_float(mulx), c_float(muly), - c_float(addx), c_float(addy), - c_float(octaves), c_float(delta), - c_float(scale)) -def heightmap_scale_fbm(hm, noise, mulx, muly, addx, addy, octaves, delta, - scale): - _lib.TCOD_heightmap_scale_fbm(hm.p, noise, c_float(mulx), c_float(muly), - c_float(addx), c_float(addy), - c_float(octaves), c_float(delta), - c_float(scale)) -def heightmap_dig_bezier(hm, px, py, startRadius, startDepth, endRadius, - endDepth): - IARRAY = c_int * 4 - cpx = IARRAY(*px) - cpy = IARRAY(*py) - _lib.TCOD_heightmap_dig_bezier(hm.p, cpx, cpy, c_float(startRadius), - c_float(startDepth), c_float(endRadius), - c_float(endDepth)) - -def heightmap_get_value(hm, x, y): - return _lib.TCOD_heightmap_get_value(hm.p, x, y) - -def heightmap_get_interpolated_value(hm, x, y): - return _lib.TCOD_heightmap_get_interpolated_value(hm.p, c_float(x), - c_float(y)) - -def heightmap_get_slope(hm, x, y): - return _lib.TCOD_heightmap_get_slope(hm.p, x, y) - -def heightmap_get_normal(hm, x, y, waterLevel): - FARRAY = c_float * 3 - cn = FARRAY() - _lib.TCOD_heightmap_get_normal(hm.p, c_float(x), c_float(y), cn, - c_float(waterLevel)) - return cn[0], cn[1], cn[2] - -def heightmap_count_cells(hm, mi, ma): - return _lib.TCOD_heightmap_count_cells(hm.p, c_float(mi), c_float(ma)) - -def heightmap_has_land_on_border(hm, waterlevel): - return _lib.TCOD_heightmap_has_land_on_border(hm.p, c_float(waterlevel)) - -def heightmap_get_minmax(hm): - mi = c_float() - ma = c_float() - _lib.TCOD_heightmap_get_minmax(hm.p, byref(mi), byref(ma)) - return mi.value, ma.value - -def heightmap_delete(hm): - _lib.TCOD_heightmap_delete(hm.p) - - -############################ -# name generator module -############################ -_lib.TCOD_namegen_generate.restype = c_char_p -_lib.TCOD_namegen_generate_custom.restype = c_char_p - -def namegen_parse(filename,random=0) : - _lib.TCOD_namegen_parse(filename,random) - -def namegen_generate(name) : - return _lib.TCOD_namegen_generate(name, 0) - -def namegen_generate_custom(name, rule) : - return _lib.TCOD_namegen_generate(name, rule, 0) - -def namegen_get_sets(): - nb=_lib.TCOD_namegen_get_nb_sets_wrapper() - SARRAY = c_char_p * nb; - setsa = SARRAY() - _lib.TCOD_namegen_get_sets_wrapper(setsa) - return list(setsa) - -def namegen_destroy() : - _lib.TCOD_namegen_destroy() - - diff --git a/life.py b/life.py index 45bb22f..4a2fb07 100644 --- a/life.py +++ b/life.py @@ -169,7 +169,7 @@ def initiate_life(name): #except: # print 'FIXME: Exception on no .dat for life' - print 'MOVE GOAP INIT. HERE' * 50 + print('MOVE GOAP INIT. HERE' * 50) if not 'icon' in life: logging.warning('No icon set for life type \'%s\'. Using default (%s).' % (name,DEFAULT_LIFE_ICON)) @@ -179,7 +179,7 @@ def initiate_life(name): logging.error('No flags set for life type \'%s\'. Errors may occur.' % name) for key in life: - if isinstance(life[key],unicode): + if isinstance(life[key],str): life[key] = str(life[key]) life.update(calculate_base_stats(life)) @@ -192,7 +192,7 @@ def initiate_limbs(life): """Creates skeleton of a character and all related variables. Returns nothing.""" body = life['body'] - for limb in body: + for limb in list(body): #Unicode fix: _val = body[limb].copy() del body[limb] @@ -250,7 +250,7 @@ def execute_raw(life, section, identifier, break_on_true=False, break_on_false=T _broke_on_false = 0 if debug and not dialog: - print 'Grabbing raw: %s, %s' % (section, identifier) + print('Grabbing raw: %s, %s' % (section, identifier)) if dialog: _raw = dialog @@ -262,7 +262,7 @@ def execute_raw(life, section, identifier, break_on_true=False, break_on_false=T for rule_group in _raw: if debug: - print 'Function group:', rule_group + print('Function group:', rule_group) for rule in rule_group: if rule['string']: @@ -288,14 +288,14 @@ def execute_raw(life, section, identifier, break_on_true=False, break_on_false=T _func = rule['function'](life, **kwargs) except Exception as e: logging.critical('Function \'%s\' got invalid argument.' % rule['function']) - print rule + print(rule) import traceback traceback.print_exc() sys.exit(1) if debug: - print 'Function:', _func - print 'Function arguments:', _func_args + print('Function:', _func) + print('Function arguments:', _func_args) if rule['true'] == '*' or _func == rule['true']: for value in rule['values']: @@ -508,7 +508,7 @@ def sanitize_heard(life): del life['heard'] def sanitize_know(life): - for entry in life['know'].values(): + for entry in list(life['know'].values()): entry['life'] = entry['life']['id'] if alife.brain.alife_has_flag(life, entry['life'], 'search_map'): @@ -519,7 +519,7 @@ def prepare_for_save(life): _sanitize_keys = {'heard': sanitize_heard, 'know': sanitize_know} - for key in life.keys():#_delete_keys: + for key in list(life.keys()):#_delete_keys: if key in _sanitize_keys: _sanitize_keys[key](life) elif key in _delete_keys: @@ -534,7 +534,7 @@ def post_save(life): life['dialogs'] = [] life['fov'] = fov.fov(life['pos'], sight.get_vision(life)) - for entry in life['know'].values(): + for entry in list(life['know'].values()): entry['life'] = LIFE[entry['life']] #NOTE: This section is for updating life entities after keys have been added @@ -542,35 +542,35 @@ def post_save(life): initiate_raw(life) def load_all_life(): - for life in LIFE.values(): + for life in list(LIFE.values()): post_save(life) def save_all_life(): - for life in LIFE.values(): + for life in list(LIFE.values()): prepare_for_save(life) - for key in life.keys(): + for key in list(life.keys()): try: json.dumps(life[key]) except: - print life[key] + print(life[key]) logging.critical('Life key cannot be offloaded: %s' % key) raise Exception(key) _life = json.dumps(LIFE) - for life in LIFE.values(): + for life in list(LIFE.values()): post_save(life) return _life def show_debug_info(life): - print ' '.join(life['name']) - print '*'*10 - print 'Dumping memory' - print '*'*10 + print(' '.join(life['name'])) + print('*'*10) + print('Dumping memory') + print('*'*10) for memory in life['memory']: - print memory['target'], memory['text'] + print(memory['target'], memory['text']) def get_engage_distance(life): return 0 @@ -646,7 +646,7 @@ def get_current_known_chunk(life): return False def get_current_known_chunk_id(life): - _chunk_key = '%s,%s' % ((life['pos'][0]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], (life['pos'][1]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']) + _chunk_key = '%s,%s' % ((life['pos'][0]//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], (life['pos'][1]//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']) if _chunk_key in life['known_chunks']: return _chunk_key @@ -659,7 +659,7 @@ def get_current_chunk(life): return maps.get_chunk(_chunk_id) def get_current_chunk_id(life): - return '%s,%s' % ((life['pos'][0]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], (life['pos'][1]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']) + return '%s,%s' % ((life['pos'][0]//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], (life['pos'][1]//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']) def get_known_life(life, id): if id in life['know']: @@ -926,7 +926,7 @@ def crouch(life): else: _delay = melee.get_stance_score(life, 'crouching') - set_animation(life, ['n', '@'], speed=_delay/2) + set_animation(life, ['n', '@'], speed=_delay//2) add_action(life,{'action': 'crouch'}, 200, delay=_delay) @@ -939,7 +939,7 @@ def stand(life): else: _delay = melee.get_stance_score(life, 'standing') - set_animation(life, ['^', '@'], speed=_delay/2) + set_animation(life, ['^', '@'], speed=_delay//2) add_action(life,{'action': 'stand'}, 200, delay=_delay) @@ -957,7 +957,7 @@ def crawl(life, force=False): else: _delay = melee.get_stance_score(life, 'crawling') - set_animation(life, ['v', '@'], speed=_delay/2) + set_animation(life, ['v', '@'], speed=_delay//2) add_action(life,{'action': 'crawl'}, 200, delay=_delay) @@ -1174,7 +1174,7 @@ def perform_collisions(life): if not life['gravity']: life['falling_startzpos'] = life['pos'][2] - if life.has_key('player'): + if 'player' in life: gfx.message('You begin to fall...') life['gravity'] = WORLD_INFO['world_gravity'] @@ -1252,14 +1252,14 @@ def add_action(life, action, score, delay=0): _tmp_action = {'action': action,'score': score} if _tmp_action in life['actions']: - print 'Action already exists in queue for %s: %s' % (' '.join(life['name']), action['action']) + print('Action already exists in queue for %s: %s' % (' '.join(life['name']), action['action'])) return False _tmp_action['delay'] = delay _tmp_action['delay_max'] = delay if _tmp_action in life['actions']: - print 'Action already exists in queue for %s: %s' % (' '.join(life['name']), action['action']) + print('Action already exists in queue for %s: %s' % (' '.join(life['name']), action['action'])) return False _index = 0 @@ -1356,7 +1356,7 @@ def perform_action(life): if 'debug' in _action and _action['debug']: SETTINGS['print dijkstra maps'] = False - print _path + print(_path) if not 'failed_dijkstra' in life['state_flags'] and walk(life, path=_path): delete_action(life, action) @@ -1455,8 +1455,8 @@ def perform_action(life): delete_action(life, action) set_animation(life, [',', 'x'], speed=6) - if life.has_key('player'): - if _action.has_key('container'): + if 'player' in life: + if 'container' in _action: _item = items.get_item_from_uid(_action['item']) _container = items.get_item_from_uid(_action['container']) gfx.message('You store %s in %s.' @@ -1489,12 +1489,12 @@ def perform_action(life): if _stored: _item = get_inventory_item(life,_action['item']) - if life.has_key('player'): + if 'player' in life: gfx.message('You remove %s from %s.' % (_name,_stored['name'])) else: say(life,'@n takes off %s.' % _name,action=True) - if life.has_key('player'): + if 'player' in life: gfx.message('You drop %s.' % _name) else: say(life,'@n drops %s.' % _name,action=True) @@ -1548,7 +1548,7 @@ def perform_action(life): remove_item_from_inventory(life,_action['item']) direct_add_item_to_inventory(life,_action['item'],container=_action['container']) - if life.has_key('player'): + if 'player' in life: gfx.message('You put %s into %s.' % (_item_to_store_name,_container_name)) else: say(life,'@n stores %s in %s.' % (_item_to_store_name,_container_name), action=True, event=False) @@ -1568,7 +1568,7 @@ def perform_action(life): elif _action['action'] == 'pickupequipitem': if not can_wear_item(life,_action['item']): - if life.has_key('player'): + if 'player' in life: gfx.message('You can\'t equip this item!') delete_action(life,action) @@ -1577,7 +1577,7 @@ def perform_action(life): item = items.get_item_from_uid(_action['item']) - if life.has_key('player'): + if 'player' in life: gfx.message('You equip %s from the ground.' % items.get_name(item)) else: say(life,'@n puts on %s from the ground.' % _name,action=True) @@ -1603,7 +1603,7 @@ def perform_action(life): _item['owner'] = None if _hand['holding']: - if life.has_key('player'): + if 'player' in life: gfx.message('You\'re already holding something in your %s!' % _action['hand']) delete_action(life, action) @@ -1656,7 +1656,7 @@ def perform_action(life): _ammo = remove_item_from_inventory(life, _action['ammo']['uid']) _action['ammo']['parent'] = _action['weapon']['uid'] - if life.has_key('player'): + if 'player' in life: gfx.message('You load a new %s into your %s.' % (_action['weapon']['feed'],_action['weapon']['name'])) else: say(life, '@n reloads %s.' % items.get_name(_action['weapon']), action=True, event=False) @@ -1692,7 +1692,7 @@ def perform_action(life): _action['round']['parent'] = _action['ammo']['uid'] _round = remove_item_from_inventory(life, _action['round']['uid']) - if life.has_key('player') and len(_action['ammo']['rounds'])>=_action['ammo']['maxrounds']: + if 'player' in life and len(_action['ammo']['rounds'])>=_action['ammo']['maxrounds']: gfx.message('The magazine is full.') delete_action(life,action) @@ -1739,7 +1739,7 @@ def perform_action(life): return True def kill(life, injury): - if isinstance(injury, str) or isinstance(injury, unicode): + if isinstance(injury, str) or isinstance(injury, str): life['cause_of_death'] = injury if 'player' in life: @@ -1900,7 +1900,7 @@ def tick_all_life(setup=False): brain.sight.look(life) brain.sound.listen(life) - for mission_id in life['missions'].keys(): + for mission_id in list(life['missions'].keys()): missions.do_mission(life, mission_id) perform_action(life) @@ -1974,11 +1974,11 @@ def throw_item(life, item_uid, target): _distance = bad_numbers.distance(_item['pos'], target) #TODO: TOSS OVER WALL? THROW FASTER? - #_z_velocity = _distance/_distance*(1-_item['gravity']) + #_z_velocity = _distance//_distance*(1-_item['gravity']) _z_velocity = 0 #TODO: The following works: - #_speed = _distance/_distance*(1-_drag) + #_speed = _distance//_distance*(1-_drag) _speed = 2 items.move(_item, _direction, _speed, _velocity=_z_velocity) @@ -2024,7 +2024,7 @@ def add_item_to_storage(life, item_uid, container=None): container = can_put_item_in_storage(life, item_uid) if not container: - print 'cannot store',_item['name'] + print('cannot store',_item['name']) return False #_container = items.get_item_from_uid(container) @@ -2039,7 +2039,7 @@ def remove_item_in_storage(life, item_uid): if 'stored_in' in items.get_item_from_uid(item_uid): items.remove_item_from_any_storage(item_uid) else: - print 'incorrect: item not stored' + print('incorrect: item not stored') #for _container in [items.get_item_from_uid(_container) for _container in life['inventory']]: # if not 'max_capacity' in _container: @@ -2166,7 +2166,7 @@ def get_all_equipped_items(life, check_hands=True, matches=[]): def get_all_known_camps(life, matches={}): _camps = [] - for camp in life['known_camps'].values(): + for camp in list(life['known_camps'].values()): for key in matches: if not key in camp or not camp[key] == matches[key]: break @@ -2180,7 +2180,7 @@ def get_item_access_time(life, item_uid): _size = _item['size'] if 'attaches_to' in _item: - _size = _size/len(_item['attaches_to']) + _size = _size//len(_item['attaches_to']) _size = bad_numbers.clip(_size, 0, 6) @@ -2221,7 +2221,7 @@ def direct_add_item_to_inventory(life, item_uid, container=None): """ #Warning: Only use this if you know what you're doing! - if not isinstance(item_uid, str) and not isinstance(item_uid, unicode): + if not isinstance(item_uid, str) and not isinstance(item_uid, str): raise Exception('Deprecated: String not passed as item UID') item = items.get_item_from_uid(item_uid) @@ -2259,7 +2259,7 @@ def direct_add_item_to_inventory(life, item_uid, container=None): def add_item_to_inventory(life, item_uid, equip=False): """Helper function. Adds item to inventory. Returns inventory ID.""" - if not isinstance(item_uid, str) and not isinstance(item_uid, unicode): + if not isinstance(item_uid, str) and not isinstance(item_uid, str): raise Exception('Deprecated: String not passed as item UID') item = items.get_item_from_uid(item_uid) @@ -2323,7 +2323,7 @@ def remove_item_from_inventory(life, item_id): item['pos'] = life['pos'][:] remove_item_in_storage(life, item_id) elif not item_is_stored(life, item_id): - print 'item is NOT stored' + print('item is NOT stored') if 'max_capacity' in item: logging.debug('Dropping container storing:') @@ -2900,10 +2900,10 @@ def draw_visual_inventory(life): if _limbs[limb]['holding']: _item = get_inventory_item(life,_limbs[limb]['holding'][0]) console_set_default_foreground(0,white) - console_print(0,MAP_WINDOW_SIZE[0]+1,_limbs.keys().index(limb)+1,'%s: %s' % (limb,_item['name'])) + console_print(0,MAP_WINDOW_SIZE[0]+1,list(_limbs.keys()).index(limb)+1,'%s: %s' % (limb,_item['name'])) else: console_set_default_foreground(0,Color(125,125,125)) - console_print(0,MAP_WINDOW_SIZE[0]+1,_limbs.keys().index(limb)+1,'%s: None' % limb) + console_print(0,MAP_WINDOW_SIZE[0]+1,list(_limbs.keys()).index(limb)+1,'%s: None' % limb) console_set_default_foreground(0,white) @@ -3204,7 +3204,7 @@ def collapse(life): def get_damage(life): _damage = 0 - for limb in life['body'].values(): + for limb in list(life['body'].values()): _damage += limb['cut'] _damage += limb['bleeding'] @@ -3341,7 +3341,7 @@ def calculate_blood(life): if life['blood']<=0: return 0 - for limb in life['body'].values(): + for limb in list(life['body'].values()): if not limb['bleeding']: continue @@ -3360,7 +3360,7 @@ def calculate_blood(life): return life['blood'] def calculate_max_blood(life): - return sum([l['size']*10 for l in life['body'].values()]) + return sum([l['size']*10 for l in list(life['body'].values())]) def get_bleeding_limbs(life): """Returns list of bleeding limbs.""" @@ -3577,9 +3577,9 @@ def burn(life, intensity): if life['stance'] == 'standing' and intensity>=3: _limbs.extend(get_legs(life)) elif life['stance'] == 'crouching' and intensity>=3: - _limbs.extend(life['body'].keys()) + _limbs.extend(list(life['body'].keys())) elif life['stance'] == 'crawling': - _limbs.extend(life['body'].keys()) + _limbs.extend(list(life['body'].keys())) else: return False @@ -3743,7 +3743,7 @@ def difficulty_of_hitting_limb(life, limb, item_uid): return 9999 _scatter = weapons.get_bullet_scatter_to(life, life['pos'], item_uid) - _scatter *= 1+((10-bad_numbers.clip(get_limb(life, limb)['size'], 1, 10))/10) + _scatter *= 1+((10-bad_numbers.clip(get_limb(life, limb)['size'], 1, 10))//10) return _scatter @@ -3753,9 +3753,9 @@ def damage_from_item(life, item): if item['aim_at_limb'] and item['accuracy']>=difficulty_of_hitting_limb(life, item['aim_at_limb'], item['uid']): _rand_limb = [item['aim_at_limb'] for i in range(item['accuracy'])] - _rand_limb.append(random.choice(life['body'].keys())) + _rand_limb.append(random.choice(list(life['body'].keys()))) else: - _rand_limb = [random.choice(life['body'].keys())] + _rand_limb = [random.choice(list(life['body'].keys()))] _poss_limbs = _rand_limb _shot_by_alife = LIFE[item['shot_by']] @@ -3830,29 +3830,29 @@ def generate_life_info(life): for key in _stats_for: if isinstance(life[key], list): - print '\n',key,'\t-', + print('\n',key,'\t-', end=' ') for value in life[key]: if isinstance(value, dict): - print '\n' + print('\n') for _key in value: - print '\t',_key,'\t' * (2-(len(_key)/8)),value[_key] + print('\t',_key,'\t' * (2-(len(_key)//8)),value[_key]) else: - print value, - print '\t\t', + print(value, end=' ') + print('\t\t', end=' ') elif isinstance(life[key], dict): for _key in life[key]: - print '\t',_key,'\t' * (2-(len(_key)/8)),life[key][_key] + print('\t',_key,'\t' * (2-(len(_key)//8)),life[key][_key]) else: - print '\n',key,'\t-',life[key], + print('\n',key,'\t-',life[key], end=' ') return _lines def print_life_table(): - print '%' * 16 - print '^ Life (Table) ^' - print '%' * 16,'\n' + print('%' * 16) + print('^ Life (Table) ^') + print('%' * 16,'\n') for life in [LIFE[i] for i in LIFE]: generate_life_info(life) - print '\n','%' * 16,'\n' + print('\n','%' * 16,'\n') diff --git a/locks.py b/locks.py index 065487b..6377379 100644 --- a/locks.py +++ b/locks.py @@ -22,10 +22,10 @@ def lock(lock_name, reason=''): get_lock(lock_name)['locked'] = True if reason: - print '%s: %s' % (lock_name, reason) + print('%s: %s' % (lock_name, reason)) def unlock(lock_name, reason=''): get_lock(lock_name)['locked'] = False if reason: - print '%s: %s' % (lock_name, reason) + print('%s: %s' % (lock_name, reason)) diff --git a/logic.py b/logic.py index d0d497d..1bed133 100644 --- a/logic.py +++ b/logic.py @@ -183,8 +183,8 @@ def draw_event(): _i = 0 for line in _lines: - _half = len(line)/2 - _x = bad_numbers.clip((MAP_WINDOW_SIZE[0]/2)-_half, 0, MAP_WINDOW_SIZE[0]-len(line)-1) + _half = len(line)//2 + _x = bad_numbers.clip((MAP_WINDOW_SIZE[0]//2)-_half, 0, MAP_WINDOW_SIZE[0]-len(line)-1) gfx.blit_string(_x, 10+_i, diff --git a/mainmenu.py b/mainmenu.py index 0dffba4..402da8f 100644 --- a/mainmenu.py +++ b/mainmenu.py @@ -11,6 +11,7 @@ import random import time +import sys INTRO = 'flagsdev presents' SUB_LINE = 'Reactor 3' @@ -56,7 +57,7 @@ def draw_intro(): _mod = int(round(255*bad_numbers.clip(time.time()-_title_time, 0, 1))) console_set_default_foreground(0, Color(_mod, _mod, _mod)) - console_print(0, (WINDOW_SIZE[0]/2)-len(_text)/2, (WINDOW_SIZE[1]/2)-2, _text) + console_print(0, (WINDOW_SIZE[0]//2)-len(_text)//2, (WINDOW_SIZE[1]//2)-2, _text) if time.time()-_stime>=1: if not _warning_time: @@ -64,7 +65,7 @@ def draw_intro(): _mod = int(round(255*bad_numbers.clip(time.time()-_warning_time, 0, 1))) - console_set_default_foreground(0, Color(_mod/2, _mod/2, _mod/2)) + console_set_default_foreground(0, Color(_mod//2, _mod//2, _mod//2)) console_print(0, 0, WINDOW_SIZE[1]-1, _warning_message) if time.time()-_stime>=1.2: @@ -73,7 +74,7 @@ def draw_intro(): _c_mod = _char_alpha[c] _mod = bad_numbers.clip(time.time()-_warning_time, 0, 1) console_set_default_foreground(0, Color(int(round((200*_mod)*_c_mod)), 0, 0)) - console_print(0, _i+(WINDOW_SIZE[0]/2)-len(SUB_LINE)/2, (WINDOW_SIZE[1]/2), c) + console_print(0, _i+(WINDOW_SIZE[0]//2)-len(SUB_LINE)//2, (WINDOW_SIZE[1]//2), c) _char_alpha[c] = bad_numbers.clip(_char_alpha[c]*1.015, 0, 1) _i += 1 diff --git a/mapgen.py b/mapgen.py index ad630bc..a48df06 100644 --- a/mapgen.py +++ b/mapgen.py @@ -145,7 +145,7 @@ def generate_map(size=(400, 1000, 10), detail=5, towns=2, factories=1, forests=1 return map_gen -def create_path_map(): +def create_path_map(map_gen): WORLD_INFO['path_map'] = {} for slice_id in WORLD_INFO['slices']: @@ -204,7 +204,7 @@ def get_neighboring_tiles(map_gen, pos, tiles, vert_only=False, horiz_only=False return _neighbor_tiles def building_test(map_gen, building_type): - while not generate_building(map_gen, '45,30', building_type, map_gen['chunk_map'].keys()): + while not generate_building(map_gen, '45,30', building_type, list(map_gen['chunk_map'].keys())): continue def create_buildings(): @@ -1254,7 +1254,7 @@ def generate_building(map_gen, chunk_key, building_type, possible_building_chunk if not _building: return False - if not sum([len(r['chunk_keys']) for r in _building['rooms'].values()])==sum([r['chunks'] for r in BUILDINGS[building_type]['chunks'].values()]): + if not sum([len(r['chunk_keys']) for r in list(_building['rooms'].values())])==sum([r['chunks'] for r in list(BUILDINGS[building_type]['chunks'].values())]): return False for room_name in _building['rooms']: @@ -1451,15 +1451,15 @@ def generate_building(map_gen, chunk_key, building_type, possible_building_chunk create_tile(map_gen, _x, _y, 2, random.choice(_building['flags']['yard']['tiles'])) - _max_chunk_distance = _closest_fence_chunk['distance']/3 + _max_chunk_distance = _closest_fence_chunk['distance']//3 if 'fence' in _building['flags']['yard']: for x in range(_top_left[0], _bot_right[0]+WORLD_INFO['chunk_size']+1): if x >= MAP_SIZE[0]-1: continue - _chunk_key_1 = [(x/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], _top_left[1]] - _chunk_key_2 = [(x/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], _bot_right[1]] + _chunk_key_1 = [(x//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], _top_left[1]] + _chunk_key_2 = [(x//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], _bot_right[1]] _pos_1_open = map_gen['map'][x][_top_left[1]][2]['id'] in [t['id'] for t in tiles.GRASS_TILES] or \ map_gen['map'][x][_top_left[1]][2]['id'] in [t['id'] for t in _building['flags']['yard']['splatter_tiles']] or \ map_gen['map'][x][_top_left[1]][2]['id'] in [t['id'] for t in _building['flags']['yard']['tiles']] @@ -1481,8 +1481,8 @@ def generate_building(map_gen, chunk_key, building_type, possible_building_chunk if y >= MAP_SIZE[1]-1: continue - _chunk_key_1 = [_top_left[0], (y/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']] - _chunk_key_2 = [_bot_right[0], (y/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']] + _chunk_key_1 = [_top_left[0], (y//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']] + _chunk_key_2 = [_bot_right[0], (y//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']] _pos_1_open = map_gen['map'][_top_left[0]][y][2]['id'] in [t['id'] for t in tiles.GRASS_TILES] or \ map_gen['map'][_top_left[0]][y][2]['id'] in [t['id'] for t in _building['flags']['yard']['splatter_tiles']] or \ map_gen['map'][_top_left[0]][y][2]['id'] in [t['id'] for t in _building['flags']['yard']['tiles']] @@ -1591,8 +1591,8 @@ def create_tile(map_gen, x, y, z, tile): _chunk['max_z'] = z def generate_chunk_map(map_gen): - for y1 in xrange(0, map_gen['size'][1], map_gen['chunk_size']): - for x1 in xrange(0, map_gen['size'][0], map_gen['chunk_size']): + for y1 in range(0, map_gen['size'][1], map_gen['chunk_size']): + for x1 in range(0, map_gen['size'][0], map_gen['chunk_size']): _chunk_key = '%s,%s' % (x1, y1) map_gen['chunk_map'][_chunk_key] = {'pos': (x1, y1), @@ -1952,8 +1952,8 @@ def generate_noise_map(map_gen): if not empty_cell_1 in _cell_2['neighbors']: _cell_2['neighbors'].append(empty_cell_1) - for empty_cell in _empty_cells.keys(): - if not empty_cell in _empty_cells.keys(): + for empty_cell in list(_empty_cells.keys()): + if not empty_cell in list(_empty_cells.keys()): continue _cell = _empty_cells[empty_cell] @@ -2021,7 +2021,7 @@ def generate_noise_map(map_gen): del _empty_cells[empty_cell] del _empty_cells[neighbor] - for __cell in _empty_cells.values(): + for __cell in list(_empty_cells.values()): if empty_cell in __cell['neighbors']: __cell['neighbors'].remove(empty_cell) @@ -2114,8 +2114,8 @@ def generate_field(map_gen, cell): for chunk_key in cell['chunk_keys']: map_gen['chunk_map'][chunk_key]['type'] = 'field' - _x = map_gen['chunk_map'][chunk_key]['pos'][0]+(map_gen['chunk_size']/2) - _y = map_gen['chunk_map'][chunk_key]['pos'][1]+(map_gen['chunk_size']/2) + _x = map_gen['chunk_map'][chunk_key]['pos'][0]+(map_gen['chunk_size']//2) + _y = map_gen['chunk_map'][chunk_key]['pos'][1]+(map_gen['chunk_size']//2) if _x<0 or _x>=MAP_SIZE[0] or _y<0 or _y>=MAP_SIZE[1]: continue @@ -2165,8 +2165,8 @@ def generate_farm(map_gen, cell): _yard_chunks.append(neighbor_chunk_key) _center_pos = list(map_gen['chunk_map'][neighbor_chunk_key]['pos'][:2]) - _center_pos[0] += map_gen['chunk_size']/2 - _center_pos[1] += map_gen['chunk_size']/2 + _center_pos[0] += map_gen['chunk_size']//2 + _center_pos[1] += map_gen['chunk_size']//2 for pos in drawing.draw_circle(_center_pos, random.randint(6, 8)): if pos[0]<0 or pos[0]>=MAP_SIZE[0] or pos[1]<0 or pos[1]>=MAP_SIZE[1]: @@ -2208,7 +2208,7 @@ def generate_farm(map_gen, cell): _x = x-_top_left[0] if not _x or not _y or x == _bot_right[0] or y == _bot_right[1]: - create_tile(map_gen, x+map_gen['chunk_size']/2, y+map_gen['chunk_size']/2, 2, random.choice(tiles.WOOD_TILES)) + create_tile(map_gen, x+map_gen['chunk_size']//2, y+map_gen['chunk_size']//2, 2, random.choice(tiles.WOOD_TILES)) #Silos _potential_silo_chunks = [] @@ -2253,7 +2253,7 @@ def generate_farm(map_gen, cell): create_tile(map_gen, x, y, 2, random.choice(tiles.CONCRETE_FLOOR_TILES)) _breaks = [] - _center = (_silo_chunk['pos'][0]+map_gen['chunk_size']/2, _silo_chunk['pos'][1]+map_gen['chunk_size']/2) + _center = (_silo_chunk['pos'][0]+map_gen['chunk_size']//2, _silo_chunk['pos'][1]+map_gen['chunk_size']//2) for z in range(1, 4): for pos in drawing.draw_circle(_center, 10): if pos[0]<0 or pos[0]>=MAP_SIZE[0] or pos[1]<0 or pos[1]>=MAP_SIZE[1]: @@ -2267,7 +2267,7 @@ def generate_farm(map_gen, cell): 'direction': bad_numbers.direction_to(_center, pos)}) for break_pos in _breaks: - _velocity = bad_numbers.velocity(break_pos['direction'], bad_numbers.clip(break_pos['distance']/5, 0.5, 1)) + _velocity = bad_numbers.velocity(break_pos['direction'], bad_numbers.clip(break_pos['distance']//5, 0.5, 1)) _velocity[0] = break_pos['pos'][0]+_velocity[0] _velocity[1] = break_pos['pos'][1]+_velocity[1] @@ -2490,8 +2490,8 @@ def generate_town(map_gen, cell, road_scale=1, road_type='paved'): def create_splotch(map_gen, position, size, tiles, avoid_tiles=[], z=2, only_tiles=[], avoid_chunks=[], avoid_positions=[], pos_is_chunk_key=False): if pos_is_chunk_key: position = list(position) - position[0] += map_gen['chunk_size']/2 - position[1] += map_gen['chunk_size']/2 + position[0] += map_gen['chunk_size']//2 + position[1] += map_gen['chunk_size']//2 for pos in drawing.draw_circle(position, size): if pos[0]<0 or pos[0]>=MAP_SIZE[0] or pos[1]<0 or pos[1]>=MAP_SIZE[1]: @@ -2557,11 +2557,11 @@ def place_road(map_gen, length=(15, 25), start_pos=None, next_dir=None, turnoffs else: _max_turns = turns - _road_segments = range(random.randint(length[0], length[1])) + _road_segments = list(range(random.randint(length[0], length[1]))) _town_segments = [] for i in range(turnoffs): if i: - _segment = len(_road_segments)/(turnoffs-i) + _segment = len(_road_segments)//(turnoffs-i) _segment -= 10 else: _segment = first_segment @@ -2573,26 +2573,26 @@ def place_road(map_gen, length=(15, 25), start_pos=None, next_dir=None, turnoffs _next_dir = next_dir if start_pos: - _chunk_key = '%s,%s' % ((start_pos[0]/map_gen['chunk_size'])*map_gen['chunk_size'], - (start_pos[1]/map_gen['chunk_size'])*map_gen['chunk_size']) + _chunk_key = '%s,%s' % ((start_pos[0]//map_gen['chunk_size'])*map_gen['chunk_size'], + (start_pos[1]//map_gen['chunk_size'])*map_gen['chunk_size']) if not _pos: _prev_dir = _next_dir if not _start_edge: - _pos = [random.randint(0, map_gen['size'][0])/map_gen['chunk_size'], 0] + _pos = [random.randint(0, map_gen['size'][0])//map_gen['chunk_size'], 0] _prev_dir = (0, -1) _next_dir = (0, 1) elif _start_edge == 1: - _pos = [map_gen['size'][0]/map_gen['chunk_size'], random.randint(0, map_gen['size'][1])/map_gen['chunk_size']] + _pos = [map_gen['size'][0]//map_gen['chunk_size'], random.randint(0, map_gen['size'][1])//map_gen['chunk_size']] _prev_dir = (1, 0) _next_dir = (-1, 0) elif _start_edge == 2: - _pos = [random.randint(10*map_gen['chunk_size'], (map_gen['size'][0])/map_gen['chunk_size'])-(6*map_gen['chunk_size']), map_gen['size'][1]/map_gen['chunk_size']] + _pos = [random.randint(10*map_gen['chunk_size'], (map_gen['size'][0])//map_gen['chunk_size'])-(6*map_gen['chunk_size']), map_gen['size'][1]//map_gen['chunk_size']] _prev_dir = (0, 1) _next_dir = (0, -1) elif _start_edge == 3: - _pos = [-1, random.randint(0, map_gen['size'][1])/map_gen['chunk_size']] + _pos = [-1, random.randint(0, map_gen['size'][1])//map_gen['chunk_size']] _prev_dir = (-1, 0) _next_dir = (1, 0) @@ -2601,10 +2601,10 @@ def place_road(map_gen, length=(15, 25), start_pos=None, next_dir=None, turnoffs _pos[0] += _next_dir[0] _pos[1] += _next_dir[1] - if _pos[0] >= map_gen['size'][0]/map_gen['chunk_size']: + if _pos[0] >= map_gen['size'][0]//map_gen['chunk_size']: return False - if _pos[1] >= map_gen['size'][1]/map_gen['chunk_size']: + if _pos[1] >= map_gen['size'][1]//map_gen['chunk_size']: return False if _pos[0] < 0: @@ -2650,13 +2650,13 @@ def place_road(map_gen, length=(15, 25), start_pos=None, next_dir=None, turnoffs if _max_turns: _possible_next_dirs = [] - if _pos[0]+len(_road_segments)+10: _possible_next_dirs.append((-1, 0)) - if _pos[1]+len(_road_segments)+10: @@ -2714,7 +2714,7 @@ def create_tree(map_gen, position, height): continue _dist = _size-bad_numbers.clip(bad_numbers.distance(position, pos), 1, height-map_gen['size'][2]) - for _z in range(_dist/2, _dist): + for _z in range(_dist//2, _dist): if map_gen['map'][pos[0]][pos[1]][2+_z]: continue @@ -2975,4 +2975,4 @@ def decorate_world(map_gen): else: generate_map(size=(400, 1000, 10), skip_zoning=(not '--zone' in sys.argv), skip_chunking=(not '--chunk' in sys.argv)) - print 'Total mapgen time:', time.time()-_t \ No newline at end of file + print('Total mapgen time:', time.time()-_t) \ No newline at end of file diff --git a/maps.py b/maps.py index a45e436..79c2bc6 100644 --- a/maps.py +++ b/maps.py @@ -30,7 +30,7 @@ CYTHON_ENABLED = True -except ImportError, e: +except ImportError as e: CYTHON_ENABLED = False logging.warning('[Cython] ImportError with module: %s' % e) @@ -57,7 +57,7 @@ def create_map(size=MAP_SIZE, blank=False): return _map def reload_slices(): - for _slice in WORLD_INFO['slices'].values(): + for _slice in list(WORLD_INFO['slices'].values()): #logging.debug('Loading slice: %s' % _slice['id']) _size = [_slice['bot_right'][0]-_slice['top_left'][0], _slice['bot_right'][1]-_slice['top_left'][1]] @@ -114,7 +114,7 @@ def save_map(map_name, base_dir=MAP_DIR, only_cached=True): _map_file.write('world_info:%s\n' % json.dumps(WORLD_INFO)) - for _slice in _slices.keys(): + for _slice in list(_slices.keys()): if '_map' in _slices[_slice]: del _slices[_slice]['_map'] @@ -266,8 +266,8 @@ def load_cluster_at_position_if_needed(position): _chunk_cluster_size = WORLD_INFO['chunk_size']*10 - _cluster_key = '%s,%s' % ((position[0]/_chunk_cluster_size)*_chunk_cluster_size, - (position[1]/_chunk_cluster_size)*_chunk_cluster_size) + _cluster_key = '%s,%s' % ((position[0]//_chunk_cluster_size)*_chunk_cluster_size, + (position[1]//_chunk_cluster_size)*_chunk_cluster_size) if _cluster_key in LOADED_CHUNKS: return False @@ -368,8 +368,8 @@ def render_lights(size=MAP_WINDOW_SIZE, show_weather=True): _render_x = light['pos'][0]-CAMERA_POS[0] _render_y = light['pos'][1]-CAMERA_POS[1] - _x = bad_numbers.clip(light['pos'][0]-(size[0]/2),0,MAP_SIZE[0]) - _y = bad_numbers.clip(light['pos'][1]-(size[1]/2),0,MAP_SIZE[1]) + _x = bad_numbers.clip(light['pos'][0]-(size[0]//2),0,MAP_SIZE[0]) + _y = bad_numbers.clip(light['pos'][1]-(size[1]//2),0,MAP_SIZE[1]) _top_left = (_x,_y,light['pos'][2]) #TODO: Render only on move @@ -406,7 +406,7 @@ def render_lights(size=MAP_WINDOW_SIZE, show_weather=True): brightness *= los #brightness *= LOS_BUFFER[0] - #_mod = (abs((WORLD_INFO['length_of_day']/2)-WORLD_INFO['real_time_of_day'])/float(WORLD_INFO['length_of_day']))*5.0 + #_mod = (abs((WORLD_INFO['length_of_day']//2)-WORLD_INFO['real_time_of_day'])/float(WORLD_INFO['length_of_day']))*5.0 #_mod = bad_numbers.clip(_mod-1, 0, 1) #(255*_mod, 165*_mod, 0*_mod) #print brightness @@ -452,7 +452,7 @@ def _render_los(map, pos, size, cython=False, life=None): _start_time = time.time() _fov = fov.fov(pos, size) - print time.time()-_start_time + print(time.time()-_start_time) return _fov @@ -609,8 +609,8 @@ def create_position_maps(): def create_search_map(life, pos, size): _map = numpy.ones((size, size)) - _x_top_left = bad_numbers.clip(pos[0]-(size/2), 0, MAP_SIZE[0]) - _y_top_left = bad_numbers.clip(pos[1]-(size/2), 0, MAP_SIZE[1]) + _x_top_left = bad_numbers.clip(pos[0]-(size//2), 0, MAP_SIZE[0]) + _y_top_left = bad_numbers.clip(pos[1]-(size//2), 0, MAP_SIZE[1]) for x in range(0, size): _x = _x_top_left+x @@ -696,10 +696,10 @@ def update_chunk_map(): logging.info('Chunk map updated in %.2f seconds.' % (time.time()-_stime)) def draw_chunk_map(life=None, show_faction_ownership=False): - _x_min = bad_numbers.clip(CAMERA_POS[0]/WORLD_INFO['chunk_size'], 0, MAP_SIZE[0]/WORLD_INFO['chunk_size']) - _y_min = bad_numbers.clip(CAMERA_POS[1]/WORLD_INFO['chunk_size'], 0, MAP_SIZE[1]/WORLD_INFO['chunk_size']) - _x_max = bad_numbers.clip(_x_min+WINDOW_SIZE[0], 0, MAP_SIZE[0]/WORLD_INFO['chunk_size']) - _y_max = bad_numbers.clip(_y_min+WINDOW_SIZE[1], 0, MAP_SIZE[1]/WORLD_INFO['chunk_size']) + _x_min = bad_numbers.clip(CAMERA_POS[0]//WORLD_INFO['chunk_size'], 0, MAP_SIZE[0]//WORLD_INFO['chunk_size']) + _y_min = bad_numbers.clip(CAMERA_POS[1]//WORLD_INFO['chunk_size'], 0, MAP_SIZE[1]//WORLD_INFO['chunk_size']) + _x_max = bad_numbers.clip(_x_min+WINDOW_SIZE[0], 0, MAP_SIZE[0]//WORLD_INFO['chunk_size']) + _y_max = bad_numbers.clip(_y_min+WINDOW_SIZE[1], 0, MAP_SIZE[1]//WORLD_INFO['chunk_size']) _life_chunk_key = None @@ -707,13 +707,13 @@ def draw_chunk_map(life=None, show_faction_ownership=False): _life_chunk_key = lfe.get_current_chunk_id(life) for x in range(_x_min, _x_max): - _d_x = x-(CAMERA_POS[0]/WORLD_INFO['chunk_size']) + _d_x = x-(CAMERA_POS[0]//WORLD_INFO['chunk_size']) if 0>_d_x >= WINDOW_SIZE[0]: continue for y in range(_y_min, _y_max): - _d_y = y-(CAMERA_POS[1]/WORLD_INFO['chunk_size']) + _d_y = y-(CAMERA_POS[1]//WORLD_INFO['chunk_size']) _draw = True _fore_color = tcod.darker_gray _back_color = tcod.darkest_gray diff --git a/maputils.py b/maputils.py index fe9e70d..2270fde 100644 --- a/maputils.py +++ b/maputils.py @@ -15,7 +15,7 @@ def resize_map(map,size): _old_size = get_map_size(map) if _old_size[0]>size[0] or _old_size[1]>size[1] or _old_size[2]>size[2]: - print 'Warning: Attempting to shink the map! Data will be lost.' + print('Warning: Attempting to shink the map! Data will be lost.') _new_map = copy.deepcopy(map) @@ -89,4 +89,4 @@ def resize_map(map,size): maps.save_map('temp_map') - print 'Created map: temp_map.dat' \ No newline at end of file + print('Created map: temp_map.dat') \ No newline at end of file diff --git a/melee.py b/melee.py index d60eb8a..7e6b67d 100644 --- a/melee.py +++ b/melee.py @@ -27,7 +27,7 @@ def assume_stance(p, stance, towards=None): if not p['next_stance']['delay']: p['next_stance']['forced'] = False else: - print p['name'], 'cannot move (forced)' + print(p['name'], 'cannot move (forced)') return False p['next_stance']['delay'] = get_stance_score(p, stance) @@ -39,7 +39,7 @@ def assume_stance(p, stance, towards=None): gfx.message('You start to %s.' % stance) elif 'player' in LIFE[towards]: gfx.message('%s begins to %s.' % (' '.join(p['name']), stance)) - print p['name'], 'begins', p['next_stance']['stance'], '(%s' % p['next_stance']['delay']+')' + print(p['name'], 'begins', p['next_stance']['stance'], '(%s' % p['next_stance']['delay']+')') return True def force_stance(p, target_id, stance): @@ -56,7 +56,7 @@ def force_stance(p, target_id, stance): p['next_stance']['stance'] = 'standing' p['next_stance']['forced'] = True - print p['name'], 'forced into', p['stance'], '(%s' % p['next_stance']['delay']+')' + print(p['name'], 'forced into', p['stance'], '(%s' % p['next_stance']['delay']+')') def examine_possible_moves(p, targets): #TODO: Cancel move? @@ -98,9 +98,9 @@ def examine_possible_moves(p, targets): return True if 'player' in p: - _moves[_target]['moves'].extend(p['moves'].keys()) + _moves[_target]['moves'].extend(list(p['moves'].keys())) else: - assume_stance(p, random.choice(p['moves'].keys()), towards=_target) + assume_stance(p, random.choice(list(p['moves'].keys())), towards=_target) return True #if _next_stance and _next_stance in p['moves'] and not p['stance'] in p['moves'][_next_stance]['counters']: @@ -141,11 +141,11 @@ def tick(p): p['next_stance']['delay'] -= 1 if p['next_stance']['delay']: - print p['name'], 'waiting:', p['next_stance']['stance'], '(%s' % p['next_stance']['delay']+')' + print(p['name'], 'waiting:', p['next_stance']['stance'], '(%s' % p['next_stance']['delay']+')') return False if p['next_stance']['stance']: - print p['name'], p['stance'], '->', p['next_stance']['stance'] + print(p['name'], p['stance'], '->', p['next_stance']['stance']) p['stance'] = p['next_stance']['stance'] p['next_stance']['stance'] = None @@ -167,7 +167,7 @@ def react_to_attack(life, target_id, stance): elif life['stances'][life['stance']]<=life['stances']['crouching']: force_stance(life, target_id, 'off-balance') - lfe.add_wound(life, random.choice(life['body'].keys()), pain=_attack['damage']['force']) + lfe.add_wound(life, random.choice(list(life['body'].keys())), pain=_attack['damage']['force']) def perform_moves(people): for life_id in people: @@ -184,7 +184,7 @@ def perform_moves(people): elif 'player' in _life: gfx.message('%s counters your %s.' % (' '.join(_target['name']), _life['stance']), style='player_combat_bad') - print '%s counters %s\'s %s!' % (_target['name'], _life['name'], _life['stance']) + print('%s counters %s\'s %s!' % (_target['name'], _life['name'], _life['stance'])) #react_to_attack(_life, _target['id'], _target['stance']) else: @@ -197,7 +197,7 @@ def perform_moves(people): elif 'player' in _target: gfx.message('%s lands a %s.' % (' '.join(_life['name']), _life['stance']), style='player_combat_bad') - print '%s\'s %s hits %s!' % (_life['name'], _life['stance'], _target['name']) + print('%s\'s %s hits %s!' % (_life['name'], _life['stance'], _target['name'])) react_to_attack(_target, _life['id'], _life['stance']) _life['next_stance']['towards'] = None @@ -219,7 +219,7 @@ def fight(life, target): def process_fights(): _fighters = [] - for life in LIFE.values(): + for life in list(LIFE.values()): if life['next_stance']['stance']: if sum([abs(i) for i in life['velocity']]): continue diff --git a/missions.py b/missions.py index 2af5e10..b69eb77 100644 --- a/missions.py +++ b/missions.py @@ -145,7 +145,7 @@ def get_active_task(life, mission_id): return [t for t in _mission['tasks'] if not _mission['tasks'][t]['completed']][0] def has_mission_with_name(life, mission_name): - for mission in life['missions'].values(): + for mission in list(life['missions'].values()): if mission['name'] == mission_name: return True diff --git a/network.py b/network.py index f2e1a82..687a91b 100644 --- a/network.py +++ b/network.py @@ -18,8 +18,8 @@ def parse_packet(packet): if _packet['type'] == 'get': if _packet['what'] == 'stats': - _stats = {'total_memories': sum([len(l['memory']) for l in LIFE.values()]), - 'active_life': len([l for l in LIFE.values() if not l['dead']])} + _stats = {'total_memories': sum([len(l['memory']) for l in list(LIFE.values())]), + 'active_life': len([l for l in list(LIFE.values()) if not l['dead']])} return json.dumps(_stats) elif _packet['what'] == 'groups': @@ -28,7 +28,7 @@ def parse_packet(packet): _life = LIFE[_packet['value']] _knows = {} - for entry in _life['know'].values(): + for entry in list(_life['know'].values()): _knows[entry['life']['id']] = {} for key in entry: if key == 'heard': @@ -68,9 +68,9 @@ def parse_packet(packet): return json.dumps(_memory) elif _packet['what'] == 'life_list': - return json.dumps(LIFE.keys()) + return json.dumps(list(LIFE.keys())) elif _packet['what'] == 'camp_list': - return json.dumps(CAMPS.keys()) + return json.dumps(list(CAMPS.keys())) elif _packet['what'] == 'camp': if not _packet['value'] in CAMPS: return json.dumps({}) diff --git a/overwatch/core.py b/overwatch/core.py index 19b8013..ce9b315 100644 --- a/overwatch/core.py +++ b/overwatch/core.py @@ -16,9 +16,9 @@ def get_player_situation(): _situation = {} _situation['armed'] = alife.combat.has_potentially_usable_weapon(_life) - _situation['friends'] = len([l for l in _life['know'].values() if l['alignment'] in ['trust', 'feign_trust']]) + _situation['friends'] = len([l for l in list(_life['know'].values()) if l['alignment'] in ['trust', 'feign_trust']]) _situation['group'] = _life['group'] - _situation['online_alife'] = [l for l in LIFE.values() if l['online'] and not l['dead'] and not l['id'] == _life['id']] + _situation['online_alife'] = [l for l in list(LIFE.values()) if l['online'] and not l['dead'] and not l['id'] == _life['id']] _situation['trusted_online_alife'] = [l for l in _situation['online_alife'] if alife.judgement.can_trust(_life, l['id'])] _situation['has_radio'] = len(lfe.get_all_inventory_items(_life, matches=[{'type': 'radio'}]))>0 _situation['weapons'] = alife.combat.get_weapons(_life) @@ -41,7 +41,7 @@ def get_player_situation(): return _situation def get_group_leader_with_motive(group_motive, online=False): - for life in LIFE.values(): + for life in list(LIFE.values()): if not (life['online'] or not online) or not life['group'] or not alife.groups.is_leader(life, life['group'], life['id']) or SETTINGS['controlling'] == life['id']: continue diff --git a/overwatch/events.py b/overwatch/events.py index cac6ecc..56bec31 100644 --- a/overwatch/events.py +++ b/overwatch/events.py @@ -12,7 +12,7 @@ import items import alife import maps -import core +from . import core import logging import random diff --git a/overwatch/situations.py b/overwatch/situations.py index 4efe15a..f520312 100644 --- a/overwatch/situations.py +++ b/overwatch/situations.py @@ -8,19 +8,19 @@ import drawing import bad_numbers import effects -import events +from . import events import spawns import alife import items import maps -import core +from . import core import logging import random def form_scheme(force=False): - print WORLD_INFO['next_scheme_timer'] + print(WORLD_INFO['next_scheme_timer']) if WORLD_INFO['next_scheme_timer']: WORLD_INFO['next_scheme_timer'] -= 1 @@ -53,7 +53,7 @@ def form_scheme(force=False): _event_name = random.choice(_event_names) - print _event_name + print(_event_name) if _event_name == 'attract': if _player_situation['enemy_factions'] and not _player_situation['friendly_factions']: diff --git a/pathfinding.py b/pathfinding.py index f451fd6..5fbf500 100644 --- a/pathfinding.py +++ b/pathfinding.py @@ -35,8 +35,8 @@ def astar(life, start, end, zones, chunk_mode=False, terraform=None, avoid_tiles maps.load_cluster_at_position_if_needed(end) if chunk_mode: - _path['start'] = (_path['start'][0]/WORLD_INFO['chunk_size'], _path['start'][1]/WORLD_INFO['chunk_size']) - _path['end'] = (_path['end'][0]/WORLD_INFO['chunk_size'], _path['end'][1]/WORLD_INFO['chunk_size']) + _path['start'] = (_path['start'][0]//WORLD_INFO['chunk_size'], _path['start'][1]//WORLD_INFO['chunk_size']) + _path['end'] = (_path['end'][0]//WORLD_INFO['chunk_size'], _path['end'][1]//WORLD_INFO['chunk_size']) _path['olist'][0] = (_path['start'][0], _path['start'][1]) _path['fmap'] = numpy.zeros((_path['map_size'][1], _path['map_size'][0]), dtype=numpy.int16) @@ -56,10 +56,10 @@ def astar(life, start, end, zones, chunk_mode=False, terraform=None, avoid_tiles #1: Walkable if terraform: - _start_chunk_key = '%s,%s' % ((start[0]/terraform['chunk_size'])*terraform['chunk_size'], - (start[1]/terraform['chunk_size'])*terraform['chunk_size']) - _end_chunk_key = '%s,%s' % ((end[0]/terraform['chunk_size'])*terraform['chunk_size'], - (end[1]/terraform['chunk_size'])*terraform['chunk_size']) + _start_chunk_key = '%s,%s' % ((start[0]//terraform['chunk_size'])*terraform['chunk_size'], + (start[1]//terraform['chunk_size'])*terraform['chunk_size']) + _end_chunk_key = '%s,%s' % ((end[0]//terraform['chunk_size'])*terraform['chunk_size'], + (end[1]//terraform['chunk_size'])*terraform['chunk_size']) if chunk_mode: _increment = terraform['chunk_size'] @@ -69,14 +69,14 @@ def astar(life, start, end, zones, chunk_mode=False, terraform=None, avoid_tiles for y in range(0, terraform['size'][1], _increment): for x in range(0, terraform['size'][0], _increment): if chunk_mode: - _chunk_key = '%s,%s' % ((x/terraform['chunk_size'])*terraform['chunk_size'], - (y/terraform['chunk_size'])*terraform['chunk_size']) + _chunk_key = '%s,%s' % ((x//terraform['chunk_size'])*terraform['chunk_size'], + (y//terraform['chunk_size'])*terraform['chunk_size']) if not _chunk_key in [_start_chunk_key, _end_chunk_key]: if terraform['chunk_map'][_chunk_key]['type'] in avoid_chunk_types: continue - _path['map'][y/terraform['chunk_size'], x/terraform['chunk_size']] = 1 + _path['map'][y//terraform['chunk_size'], x//terraform['chunk_size']] = 1 else: _map_pos = terraform['map'][x][y][2] @@ -88,8 +88,8 @@ def astar(life, start, end, zones, chunk_mode=False, terraform=None, avoid_tiles else: if chunk_mode: - for y in range(MAP_SIZE[1]/WORLD_INFO['chunk_size']): - for x in range(MAP_SIZE[0]/WORLD_INFO['chunk_size']): + for y in range(MAP_SIZE[1]//WORLD_INFO['chunk_size']): + for x in range(MAP_SIZE[0]//WORLD_INFO['chunk_size']): _chunk_key = '%s,%s' % (x*WORLD_INFO['chunk_size'], y*WORLD_INFO['chunk_size']) @@ -221,7 +221,7 @@ def short_path(life, start, end): return _line def chunk_path(life, start, end, zones): - return astar(life, start, end, zones, map_size=(MAP_SIZE[0]/WORLD_INFO['chunk_size'], MAP_SIZE[1]/WORLD_INFO['chunk_size']), chunk_mode=True) + return astar(life, start, end, zones, map_size=(MAP_SIZE[0]//WORLD_INFO['chunk_size'], MAP_SIZE[1]//WORLD_INFO['chunk_size']), chunk_mode=True) def walk_chunk_path(life): _existing_chunk_path = alife.brain.get_flag(life, 'chunk_path') diff --git a/player.py b/player.py index ddb0ab4..7f9f73c 100644 --- a/player.py +++ b/player.py @@ -420,7 +420,7 @@ def handle_input(): _player = LIFE[SETTINGS['controlling']] _menu_items = [] - for mission in _player['missions'].values(): + for mission in list(_player['missions'].values()): if not mission['tasks']: continue @@ -646,10 +646,10 @@ def handle_input(): if INPUT['s']: if LIFE[SETTINGS['controlling']]['strafing']: LIFE[SETTINGS['controlling']]['strafing'] = False - print 'Not strafing' + print('Not strafing') else: LIFE[SETTINGS['controlling']]['strafing'] = True - print 'Strafing' + print('Strafing') if INPUT['S']: #if not LIFE[SETTINGS['controlling']]['encounters']: @@ -735,9 +735,9 @@ def handle_input(): menus.delete_menu(menus.get_menu_by_name('Debug (Developer)')) return False - _online_alife = len([l['id'] for l in LIFE.values() if l['online'] and not l['dead'] and l['think_rate_max']<30]) - _online_alife_in_passive = len([l['id'] for l in LIFE.values() if l['online'] and not l['dead'] and l['think_rate_max']>=30]) - _offline_alife = len([l['id'] for l in LIFE.values() if not l['online'] and not l['dead']]) + _online_alife = len([l['id'] for l in list(LIFE.values()) if l['online'] and not l['dead'] and l['think_rate_max']<30]) + _online_alife_in_passive = len([l['id'] for l in list(LIFE.values()) if l['online'] and not l['dead'] and l['think_rate_max']>=30]) + _offline_alife = len([l['id'] for l in list(LIFE.values()) if not l['online'] and not l['dead']]) _options = [] _options.append(menus.create_item('title', 'Testing', None)) @@ -751,7 +751,7 @@ def handle_input(): _options.append(menus.create_item('single', 'Update chunk map', 'Generates chunk map')) _options.append(menus.create_item('title', 'World Info', None)) _options.append(menus.create_item('single', 'ALife (%s)' % len(LIFE), 'Online: %s (%s), Offline: %s' % (_online_alife, _online_alife_in_passive, _offline_alife))) - _options.append(menus.create_item('single', 'ALife memories', sum([len(l['memory']) for l in LIFE.values() if not l['dead']]))) + _options.append(menus.create_item('single', 'ALife memories', sum([len(l['memory']) for l in list(LIFE.values()) if not l['dead']]))) _options.append(menus.create_item('single', 'Groups', len(WORLD_INFO['groups']))) _options.append(menus.create_item('single', 'Seed', WORLD_INFO['seed'])) @@ -827,7 +827,7 @@ def handle_input(): LIFE[SETTINGS['controlling']]['pos'][1]-5, LIFE[SETTINGS['controlling']]['pos'][2]-5), [zones.get_zone_at_coords(LIFE[SETTINGS['controlling']]['pos'])]): - print pos + print(pos) SELECTED_TILES[0].append((pos[0], pos[1], 2)) #if INPUT['N']: @@ -1351,13 +1351,13 @@ def create_look_list(): return False _menu_items = [] - for item in [l for l in ITEMS.values() if sight.can_see_position(LIFE[SETTINGS['controlling']], l['pos']) and not l == LIFE[SETTINGS['controlling']]]: + for item in [l for l in list(ITEMS.values()) if sight.can_see_position(LIFE[SETTINGS['controlling']], l['pos']) and not l == LIFE[SETTINGS['controlling']]]: if items.is_item_owned(item['uid']): continue _menu_items.append(menus.create_item('single', item['name'], None, item=item['uid'], icon=item['icon'])) - for target in [l for l in LIFE.values() if sight.can_see_position(LIFE[SETTINGS['controlling']], l['pos']) and not l == LIFE[SETTINGS['controlling']]]: + for target in [l for l in list(LIFE.values()) if sight.can_see_position(LIFE[SETTINGS['controlling']], l['pos']) and not l == LIFE[SETTINGS['controlling']]]: _menu_items.append(menus.create_item('single', ' '.join(target['name']), None, target=target['id'], icon=target['icon'])) if not _menu_items: @@ -1819,7 +1819,7 @@ def create_tasks_menu(): _life = LIFE[SETTINGS['controlling']] _tasks = [] - for task_id in jobs.get_job(_life['job'])['tasks'].keys(): + for task_id in list(jobs.get_job(_life['job'])['tasks'].keys()): task = jobs.get_task(_life['job'], task_id) _tasks.append(menus.create_item('single', @@ -1844,7 +1844,7 @@ def create_tasks_menu(): def announce_to(entry): if entry['who'] == 'public': - _announce_to = LIFE.keys() + _announce_to = list(LIFE.keys()) _announce_to.remove(SETTINGS['controlling']) elif entry['who'] == 'trusted': _announce_to = judgement.get_trusted(LIFE[SETTINGS['controlling']], visible=False) @@ -1881,7 +1881,7 @@ def create_announce_group_menu(**kwargs): def handle_create_job(entry): for entry in entry['workers']: _assigned = entry['values'][entry['value']]=='Assigned' - print entry['key'], _assigned + print(entry['key'], _assigned) def handle_select_workers(entry): job = entry['key'] @@ -2188,7 +2188,7 @@ def create_wound_menu(target): _has_wound = False _entries = [] - for limb in LIFE[target]['body'].values(): + for limb in list(LIFE[target]['body'].values()): _title = False for wound in limb['wounds']: diff --git a/prefabs.py b/prefabs.py index b05fe60..3c33ed9 100644 --- a/prefabs.py +++ b/prefabs.py @@ -125,7 +125,7 @@ def draw_prefab_thumbnail(entry): if not _prefab['map'][x][y][z]: continue - print _prefab['map'][x][y][z] + print(_prefab['map'][x][y][z]) #tcod.console_put_char_(0, PREFAB_TOP_VIEW_POS[0]+x, PREFAB_TOP_VIEW_POS[1]+y, def prefab_selected(entry): @@ -135,7 +135,7 @@ def create_prefab_list(): tcod.console_clear(0) tcod.console_clear(MAP_WINDOW) _prefabs = [] - for prefab in PREFABS.values(): + for prefab in list(PREFABS.values()): _prefabs.append(menus.create_item('single', prefab['name'], None)) return menus.create_menu(title='Prefabs', diff --git a/pyfov.py b/pyfov.py index a485961..9bd2485 100644 --- a/pyfov.py +++ b/pyfov.py @@ -44,7 +44,7 @@ def old_light(los_map, world_pos, size, row, start_slope, end_slope, xx, xy, yx, los_map[_sax+size, _say+size] = 1 if not _solid: - _chunk_key = '%s,%s' % ((_a_x/5)*5, (_a_y/5)*5) + _chunk_key = '%s,%s' % ((_a_x//5)*5, (_a_y//5)*5) if not _chunk_key in _return_chunks: _return_chunks.add(_chunk_key) diff --git a/reactor-3.py b/reactor-3.py index d2a1ceb..1d61681 100644 --- a/reactor-3.py +++ b/reactor-3.py @@ -108,8 +108,8 @@ def move_camera(pos, scroll=False): brain.unflag(_life, 'camera_lean') brain.unflag(_life, 'camera_lean_time') - CAMERA_POS[0] = int(round(bad_numbers.clip(pos[0]-(MAP_WINDOW_SIZE[0]/2), 0, MAP_SIZE[0]-MAP_WINDOW_SIZE[0]))) - CAMERA_POS[1] = int(round(bad_numbers.clip(pos[1]-(MAP_WINDOW_SIZE[1]/2), 0, MAP_SIZE[1]-MAP_WINDOW_SIZE[1]))) + CAMERA_POS[0] = int(round(bad_numbers.clip(pos[0]-(MAP_WINDOW_SIZE[0]//2), 0, MAP_SIZE[0]-MAP_WINDOW_SIZE[0]))) + CAMERA_POS[1] = int(round(bad_numbers.clip(pos[1]-(MAP_WINDOW_SIZE[1]//2), 0, MAP_SIZE[1]-MAP_WINDOW_SIZE[1]))) CAMERA_POS[2] = int(round(pos[2])) if not _orig_pos == CAMERA_POS: @@ -153,22 +153,22 @@ def death(): gfx.fade_to_black(1) - gfx.blit_string((MAP_WINDOW_SIZE[0]/2)-len(_string)/2, - MAP_WINDOW_SIZE[1]/2, + gfx.blit_string((MAP_WINDOW_SIZE[0]//2)-len(_string)//2, + MAP_WINDOW_SIZE[1]//2, _string, 'map', fore_color=tcod.Color(_col, 0, 0), back_color=tcod.Color(0, 0, 0)) - gfx.blit_string((MAP_WINDOW_SIZE[0]/2)-len(_sub_string)/2, - (MAP_WINDOW_SIZE[1]/2)+2, + gfx.blit_string((MAP_WINDOW_SIZE[0]//2)-len(_sub_string)//2, + (MAP_WINDOW_SIZE[1]//2)+2, _sub_string, 'map', fore_color=tcod.Color(int(round(_col*.75)), int(round(_col*.75)), int(round(_col*.75))), back_color=tcod.Color(0, 0, 0)) - gfx.blit_string((MAP_WINDOW_SIZE[0]/2)-len(_sub_sub_string)/2, - (MAP_WINDOW_SIZE[1]/2)+4, + gfx.blit_string((MAP_WINDOW_SIZE[0]//2)-len(_sub_sub_string)//2, + (MAP_WINDOW_SIZE[1]//2)+4, _sub_sub_string, 'map', fore_color=tcod.Color(int(round(_col*.75)), int(round(_col*.75)), int(round(_col*.75))), @@ -229,8 +229,8 @@ def main(): _visible_chunks = sight.scan_surroundings(LIFE[SETTINGS['following']], judge=False, get_chunks=True) alife.brain.flag(LIFE[SETTINGS['following']], 'visible_chunks', value=_visible_chunks) - _cam_x = bad_numbers.clip(LIFE[SETTINGS['following']]['pos'][0]-MAP_WINDOW_SIZE[0]/2, 0, MAP_SIZE[0]-MAP_WINDOW_SIZE[0]/2) - _cam_y = bad_numbers.clip(LIFE[SETTINGS['following']]['pos'][1]-MAP_WINDOW_SIZE[1]/2, 0, MAP_SIZE[1]-MAP_WINDOW_SIZE[1]/2) + _cam_x = bad_numbers.clip(LIFE[SETTINGS['following']]['pos'][0]-MAP_WINDOW_SIZE[0]//2, 0, MAP_SIZE[0]-MAP_WINDOW_SIZE[0]//2) + _cam_y = bad_numbers.clip(LIFE[SETTINGS['following']]['pos'][1]-MAP_WINDOW_SIZE[1]//2, 0, MAP_SIZE[1]-MAP_WINDOW_SIZE[1]//2) else: _visible_chunks = sight.scan_surroundings(LIFE[SETTINGS['controlling']], judge=False, get_chunks=True) @@ -238,8 +238,8 @@ def main(): SETTINGS['last_camera_pos'] = SETTINGS['camera_track'][:] - _cam_x = bad_numbers.clip(LIFE[SETTINGS['controlling']]['pos'][0]-MAP_WINDOW_SIZE[0]/2, 0, MAP_SIZE[0]-MAP_WINDOW_SIZE[0]/2) - _cam_y = bad_numbers.clip(LIFE[SETTINGS['controlling']]['pos'][1]-MAP_WINDOW_SIZE[1]/2, 0, MAP_SIZE[1]-MAP_WINDOW_SIZE[1]/2) + _cam_x = bad_numbers.clip(LIFE[SETTINGS['controlling']]['pos'][0]-MAP_WINDOW_SIZE[0]//2, 0, MAP_SIZE[0]-MAP_WINDOW_SIZE[0]//2) + _cam_y = bad_numbers.clip(LIFE[SETTINGS['controlling']]['pos'][1]-MAP_WINDOW_SIZE[1]//2, 0, MAP_SIZE[1]-MAP_WINDOW_SIZE[1]//2) maps.render_lights() @@ -269,7 +269,7 @@ def main(): gfx.end_of_frame() if '--fps' in sys.argv: - print tcod.sys_get_fps() + print(tcod.sys_get_fps()) if (SETTINGS['recording'] and _player_moved and not EVENTS and not MENUS) or '--worldmap' in sys.argv: gfx.screenshot() @@ -309,7 +309,7 @@ def loop(): logging.error('[Cython] Run \'python compile_cython_modules.py build_ext --inplace\'') sys.exit(1) - except ImportError, e: + except ImportError as e: CYTHON_ENABLED = False logging.warning('[Cython] ImportError with module: %s' % e) logging.warning('[Cython] Certain functions can run faster if compiled with Cython.') @@ -326,6 +326,7 @@ def loop(): tiles.create_all_tiles() language.load_strings() + language.load_dialog() missions.load_all_missions() alife.rawparse.create_function_map() locks.create_lock('camera_free', locked=True) @@ -374,7 +375,7 @@ def loop(): except KeyboardInterrupt: SETTINGS['running'] = False traceback.print_exc() - except Exception, e: + except Exception as e: traceback.print_exc() SETTINGS['running'] = False diff --git a/readme.md b/readme.md index 555cc48..c7bfd92 100644 --- a/readme.md +++ b/readme.md @@ -34,13 +34,12 @@ Join a faction and take over the Zone, or simply exist on your own. Installing ========== -Reactor 3 requires Python 2.7, Cython, Numpy, and [libtcod](http://doryen.eptalys.net/libtcod/download/). +Reactor 3 requires Python 3.6+ on a platform which can compile Python extensions. git clone https://github.com/flags/Reactor-3.git cd Reactor-3 + python -m pip install -r requirements.txt python compile_cython_modules.py build_ext --inplace - -Next, download the libtcod library and move the `.so` (Windows: `.dll`) files from the archive to the Reactor 3 directory. Run `python reactor-3.py` to play. diff --git a/render_fast_los.pyx b/render_fast_los.pyx index 37e756e..e6221f4 100644 --- a/render_fast_los.pyx +++ b/render_fast_los.pyx @@ -27,13 +27,13 @@ def check_dirs(at, sight, source_map, los, intensity=45, already_checked={}, sca cdef int Y_MAP_SIZE = MAP_SIZE[1] _check_dirs = already_checked - _checked_quads = [deg/90 for deg in already_checked] + _checked_quads = [deg//90 for deg in already_checked] start_point[0] = at[0] start_point[1] = at[1] start_point[2] = at[2] for deg in range(scan[0], scan[1], intensity): - if quad_check and deg/90 in _checked_quads: + if quad_check and deg//90 in _checked_quads: continue _end_x,_end_y = velocity(deg, sight)[:2] @@ -42,8 +42,8 @@ def check_dirs(at, sight, source_map, los, intensity=45, already_checked={}, sca _line = render_los.draw_line(start_point[0], start_point[1], end_point[0], end_point[1]) _i = 0 _wall = 0 - __x = clip(start_point[0]-(los.shape[1]/2),0,X_MAP_SIZE-(los.shape[1]/2)) - __y = clip(start_point[1]-(los.shape[0]/2),0,Y_MAP_SIZE-(los.shape[0]/2)) + __x = clip(start_point[0]-(los.shape[1]//2),0,X_MAP_SIZE-(los.shape[1]//2)) + __y = clip(start_point[1]-(los.shape[0]//2),0,Y_MAP_SIZE-(los.shape[0]//2)) for pos in _line: _x,_y = pos @@ -81,11 +81,11 @@ def render_fast_los(at, sight_length, source_map, no_edge=False): _check_dirs = check_dirs(at, sight, source_map, los, intensity=intensity, already_checked=_check_dirs, no_edge=no_edge) quads_to_check = [] - for deg in [entry/90 for entry in _check_dirs if _check_dirs[entry]]: + for deg in [entry//90 for entry in _check_dirs if _check_dirs[entry]]: if not deg in quads_to_check: quads_to_check.append(deg) - intensity /= 2 + intensity //= 2 if intensity<=6: break diff --git a/render_los.pyx b/render_los.pyx index fe98a6b..df14ab4 100644 --- a/render_los.pyx +++ b/render_los.pyx @@ -28,7 +28,7 @@ def draw_circle(x,y,size): for j in range(width+1): circle = (((i-center_y)*(i-center_y))/((float(height)/2)*(float(height)/2)))+((((j-center_x)*(j-center_x))/((float(width)/2)*(float(width)/2)))); if circle>0 and circle<1.1: - _circle.append((x+(j-(width/2)),y+(i-(height/2)))) + _circle.append((x+(j-(width//2)),y+(i-(height//2)))) if not (x, y) in _circle: _circle.append((x, y)) @@ -120,8 +120,8 @@ def render_los(position, size, view_size=MAP_WINDOW_SIZE, top_left=CAMERA_POS, n for _pos in draw_circle(POS_X, POS_Y, size): _dark = 0 - _chunk_key = '%s,%s' % ((_pos[0]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], - (_pos[1]/WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']) + _chunk_key = '%s,%s' % ((_pos[0]//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size'], + (_pos[1]//WORLD_INFO['chunk_size'])*WORLD_INFO['chunk_size']) #if _chunk_key in HIDDEN_CHUNKS: # continue diff --git a/render_map.pyx b/render_map.pyx index 69b994e..f69a037 100644 --- a/render_map.pyx +++ b/render_map.pyx @@ -49,12 +49,12 @@ def render_map(map, force_camera_pos=None, view_size=MAP_WINDOW_SIZE, **kwargs): _cam_pos = SETTINGS['camera_track'][:] if not CAMERA_POS[0]: - _x_mod = SETTINGS['camera_track'][0]-view_size[0]/2 + _x_mod = SETTINGS['camera_track'][0]-view_size[0]//2 elif CAMERA_POS[0]+view_size[0]>=MAP_SIZE[0]: _x_mod = 0 if not CAMERA_POS[1]: - _y_mod = SETTINGS['camera_track'][1]-view_size[1]/2 + _y_mod = SETTINGS['camera_track'][1]-view_size[1]//2 elif CAMERA_POS[1]+view_size[1]>=MAP_SIZE[1]: _y_mod = 0 @@ -64,9 +64,9 @@ def render_map(map, force_camera_pos=None, view_size=MAP_WINDOW_SIZE, **kwargs): los = None if 'los' in kwargs: los = kwargs['los'] - _min_los_x = (los.shape[0]/2)-view_size[0]/2-_x_mod+_camera_x_offset + _min_los_x = (los.shape[0]//2)-view_size[0]//2-_x_mod+_camera_x_offset _max_los_x = los.shape[0] - _min_los_y = (los.shape[1]/2)-view_size[1]/2-_y_mod+_camera_y_offset + _min_los_y = (los.shape[1]//2)-view_size[1]//2-_y_mod+_camera_y_offset _max_los_y = los.shape[1] _view = get_view_by_name('map') diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..1c7b515 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +Cython +numpy +tcod>=12.6.1 +pyinstaller==4.3 diff --git a/terraform.py b/terraform.py index 0caaff7..fbaf596 100644 --- a/terraform.py +++ b/terraform.py @@ -1,6 +1,7 @@ """Terraform - World editor for Reactor 3""" import logging +import importlib logger = logging.getLogger() logger.setLevel(logging.DEBUG) @@ -46,7 +47,7 @@ logging.warning('[Cython] render_map is out of date!') logging.warning('[Cython] Run \'python compile_cython_modules.py build_ext --inplace\'') -except ImportError, e: +except ImportError as e: CYTHON_ENABLED = False logging.warning('[Cython] ImportError with module: %s' % e) logging.warning('[Cython] Certain functions can run faster if compiled with Cython.') @@ -57,7 +58,7 @@ def pre_setup_world(): create_all_tiles() WORLD_INFO['lights'] = [] - for key in ITEMS.keys(): + for key in list(ITEMS.keys()): del ITEMS[key] def post_setup_world(): @@ -65,12 +66,12 @@ def post_setup_world(): weather.change_weather() maps.create_position_maps() - WORLD_INFO['real_time_of_day'] = WORLD_INFO['length_of_day']/2 + WORLD_INFO['real_time_of_day'] = WORLD_INFO['length_of_day']//2 def regenerate_world(build_test=False): gfx.title('Generating...') - reload(mapgen) + importlib.reload(mapgen) if build_test: mapgen.create_buildings() @@ -100,8 +101,8 @@ def regenerate_world(build_test=False): def move_camera(pos, scroll=False): _orig_pos = CAMERA_POS[:] - CAMERA_POS[0] = bad_numbers.clip(pos[0]-(WINDOW_SIZE[0]/2),0,MAP_SIZE[0]-WINDOW_SIZE[0]) - CAMERA_POS[1] = bad_numbers.clip(pos[1]-(WINDOW_SIZE[1]/2),0,MAP_SIZE[1]-WINDOW_SIZE[1]) + CAMERA_POS[0] = bad_numbers.clip(pos[0]-(WINDOW_SIZE[0]//2),0,MAP_SIZE[0]-WINDOW_SIZE[0]) + CAMERA_POS[1] = bad_numbers.clip(pos[1]-(WINDOW_SIZE[1]//2),0,MAP_SIZE[1]-WINDOW_SIZE[1]) CAMERA_POS[2] = pos[2] if not _orig_pos == CAMERA_POS: @@ -180,8 +181,8 @@ def handle_input(): pass elif INPUT['c']: - CURSOR_POS[0] = MAP_SIZE[0]/2 - CURSOR_POS[1] = MAP_SIZE[1]/2 + CURSOR_POS[0] = MAP_SIZE[0]//2 + CURSOR_POS[1] = MAP_SIZE[1]//2 elif INPUT['m']: if SETTINGS['running'] == 2: @@ -377,7 +378,6 @@ def main(): gfx.log(WINDOW_TITLE) sys_set_fps(FPS_TERRAFORM) - console_set_keyboard_repeat(200, 30) mapgen.create_buildings() diff --git a/tests/M01_data_structure.py b/tests/M01_data_structure.py index 2013b69..7151145 100644 --- a/tests/M01_data_structure.py +++ b/tests/M01_data_structure.py @@ -36,7 +36,7 @@ def get_raw_tile(tile): MAP.append(_y) -print MAP[3][3],get_raw_tile(MAP[3][3])['cost'] +print(MAP[3][3],get_raw_tile(MAP[3][3])['cost']) import sys -print 'Map size (bytes):',sys.getsizeof(MAP) \ No newline at end of file +print('Map size (bytes):',sys.getsizeof(MAP)) \ No newline at end of file diff --git a/tests/M01_data_structure_3d.py b/tests/M01_data_structure_3d.py index f09594e..f69cd5c 100644 --- a/tests/M01_data_structure_3d.py +++ b/tests/M01_data_structure_3d.py @@ -59,7 +59,7 @@ def get_raw_tile(tile): _y.append(_z) MAP.append(_y) -print 'Printing map' +print('Printing map') for x in range(MAP_SIZE[0]): for y in range(MAP_SIZE[1]): _top_tile = None @@ -67,11 +67,11 @@ def get_raw_tile(tile): if MAP[x][y][z]: _top_tile = MAP[x][y][z] - print get_raw_tile(_top_tile)['icon'], + print(get_raw_tile(_top_tile)['icon'], end=' ') - print + print() -print 'Timing map fetching' +print('Timing map fetching') import time _stime = time.time() for x in range(MAP_SIZE[0]): @@ -79,6 +79,6 @@ def get_raw_tile(tile): for z in range(MAP_SIZE[2]): if MAP[x][y][z]: get_raw_tile(MAP[x][y][z]) -print time.time()-_stime +print(time.time()-_stime) -print MAP[3][3] \ No newline at end of file +print(MAP[3][3]) \ No newline at end of file diff --git a/tests/M01_data_visualization.py b/tests/M01_data_visualization.py index d9b9855..ffe0120 100644 --- a/tests/M01_data_visualization.py +++ b/tests/M01_data_visualization.py @@ -99,7 +99,7 @@ def get_input(): def handle_input(): if MOUSE_1_DOWN: - print MOUSE_POS + print(MOUSE_POS) MAP[MOUSE_POS[0]][MOUSE_POS[1]][2] = create_tile(WALL_TILE) diff --git a/tests/M01_map_editor.py b/tests/M01_map_editor.py index ba0bfce..3bc1ebd 100644 --- a/tests/M01_map_editor.py +++ b/tests/M01_map_editor.py @@ -89,7 +89,7 @@ def get_mouse_input(): else: MOUSE_1_DOWN = False - MOUSE_POS = MOUSE.x/16,MOUSE.y/16 + MOUSE_POS = MOUSE.x//16,MOUSE.y//16 def get_input(): global KEY,MOUSE,CURSOR_POS @@ -114,7 +114,7 @@ def get_input(): def handle_input(): global MOUSE_POS if MOUSE_1_DOWN: - print MOUSE_POS + print(MOUSE_POS) MAP[MOUSE_POS[0]][MOUSE_POS[1]][2] = create_tile(WALL_TILE) TIME_OF_DAY = 6 diff --git a/tests/M05_gas_mode.py b/tests/M05_gas_mode.py index ebc11a8..62d98d7 100644 --- a/tests/M05_gas_mode.py +++ b/tests/M05_gas_mode.py @@ -3,7 +3,7 @@ import sys if not len(sys.argv)==3: - print 'Expects: python gas_mode.py ' + print('Expects: python gas_mode.py ') sys.exit(1) X_SIZE = int(sys.argv[1]) @@ -50,7 +50,7 @@ def simulate(MAP): draw_map(NEXT_MAP) if numpy.array_equal(MAP,NEXT_MAP): - print 'Took: ',_i + print('Took: ',_i) return NEXT_MAP MAP = NEXT_MAP.copy() @@ -69,11 +69,11 @@ def draw_map(MAP): NEIGHBOR_COUNT = 0 LARGEST_SCORE = 0 if MAP[MOD_X,MOD_Y] == -1: - print 'x', + print('x', end=' ') else: - print MAP[MOD_X,MOD_Y], + print(MAP[MOD_X,MOD_Y], end=' ') - print '' + print('') SOURCE_MAP[5,5]=8 @@ -87,6 +87,6 @@ def draw_map(MAP): START_TIME = time.time() SOURCE_MAP = simulate(SOURCE_MAP) -print time.time()-START_TIME +print(time.time()-START_TIME) draw_map(SOURCE_MAP) diff --git a/tests/M06_Melee.py b/tests/M06_Melee.py index 034c21c..af4bb66 100644 --- a/tests/M06_Melee.py +++ b/tests/M06_Melee.py @@ -44,7 +44,7 @@ def assume_stance(p, stance, towards=None): p['next_stance']['towards'] = towards p['next_stance']['forced'] = False - print p['name'], 'begins', p['next_stance']['stance'], '(%s' % p['next_stance']['delay']+')' + print(p['name'], 'begins', p['next_stance']['stance'], '(%s' % p['next_stance']['delay']+')') return True def force_stance(p, stance): @@ -56,7 +56,7 @@ def force_stance(p, stance): p['next_stance']['forced'] = True - print p['name'], 'forced into', p['stance'], '(%s' % p['next_stance']['delay']+')' + print(p['name'], 'forced into', p['stance'], '(%s' % p['next_stance']['delay']+')') def examine_possible_moves(p, targets): #TODO: Cancel move? @@ -72,7 +72,7 @@ def examine_possible_moves(p, targets): assume_stance(p, COMBAT_MOVES[_next_stance]['counters'][0], towards=target) return False elif not _next_stance or not target['stance'] in COMBAT_MOVES: - assume_stance(p, random.choice(COMBAT_MOVES.keys()), towards=target) + assume_stance(p, random.choice(list(COMBAT_MOVES.keys())), towards=target) return True def tick(p): @@ -80,11 +80,11 @@ def tick(p): p['next_stance']['delay'] -= 1 if p['next_stance']['delay']: - print p['name'], 'waiting:', p['next_stance']['stance'], '(%s' % p['next_stance']['delay']+')' + print(p['name'], 'waiting:', p['next_stance']['stance'], '(%s' % p['next_stance']['delay']+')') return False if p['next_stance']['stance']: - print p['name'], p['stance'], '->', p['next_stance']['stance'] + print(p['name'], p['stance'], '->', p['next_stance']['stance']) p['stance'] = p['next_stance']['stance'] p['next_stance']['stance'] = None @@ -100,18 +100,18 @@ def perform_moves(people): _target = life['next_stance']['towards'] if life['stance'] in COMBAT_MOVES and _target['stance'] in COMBAT_MOVES[life['stance']]['counters']: - print '%s counters %s\'s %s!' % (_target['name'], life['name'], life['stance']) + print('%s counters %s\'s %s!' % (_target['name'], life['name'], life['stance'])) force_stance(life, 'off-balance') else: if _target['stance'] in 'off-balance': force_stance(_target, 'prone') - print '%s\'s %s hits %s!' % (life['name'], life['stance'], _target['name']) + print('%s\'s %s hits %s!' % (life['name'], life['stance'], _target['name'])) life['next_stance']['towards'] = None else: - print '%s\'s %s does nothing!' % (life['name'], life['stance']) + print('%s\'s %s does nothing!' % (life['name'], life['stance'])) #TODO: React... #life['stance'] = 'stand' diff --git a/tests/M06_fov.py b/tests/M06_fov.py index 2af0f71..731adcd 100644 --- a/tests/M06_fov.py +++ b/tests/M06_fov.py @@ -47,7 +47,7 @@ def draw(los_map): else: _x+=' ' - print _x + print(_x) def light(los_map, world_pos, size, row, start_slope, end_slope, xx, xy, yx, yy): if start_slope < end_slope: @@ -132,6 +132,6 @@ def los(start_position, distance): _start_time = time.time() _los = los((20, 20), 20) -print time.time()-_start_time +print(time.time()-_start_time) draw(_los) \ No newline at end of file diff --git a/tests/M06_zonepath.py b/tests/M06_zonepath.py index 733e3ff..49e3430 100644 --- a/tests/M06_zonepath.py +++ b/tests/M06_zonepath.py @@ -44,37 +44,37 @@ def draw_map(source_map, z): for x in range(MAP_SIZE[0]): for y in range(MAP_SIZE[1]): if source_map[x][y][z]: - print '#', + print('#', end=' ') else: - print '.', - print + print('.', end=' ') + print() def draw_slice(slice_map): for x in range(MAP_SIZE[0]): for y in range(MAP_SIZE[1]): if slice_map[x][y] == -1: - print '^', + print('^', end=' ') elif slice_map[x][y] == -2: - print '#', + print('#', end=' ') elif slice_map[x][y] == -3: - print ' ' + print(' ') elif not slice_map[x][y]: - print '.', + print('.', end=' ') else: - print slice_map[x][y], + print(slice_map[x][y], end=' ') - print + print() def draw_ramps(ramps): _ramps = [r[:2] for r in ramps] for x in range(MAP_SIZE[0]): for y in range(MAP_SIZE[1]): if (x, y) in _ramps: - print '^', + print('^', end=' ') else: - print '.', + print('.', end=' ') - print + print() def get_unzoned(slice_map, z): for x in range(MAP_SIZE[0]): @@ -91,7 +91,7 @@ def get_unzoned(slice_map, z): return None def process_slice(z): - print 'Processing:',z + print('Processing:',z) _runs = 0 _slice = create_map_array(flat=True) @@ -108,7 +108,7 @@ def process_slice(z): if 'map' in sys.argv: draw_map(MAP, z) - print '\tRuns:',_runs,'Time:', + print('\tRuns:',_runs,'Time:', end=' ') break _slice[_start_pos[0]][_start_pos[1]] = _z_id @@ -155,10 +155,10 @@ def process_slice(z): if 'ramp' in sys.argv: draw_ramps(_ramps) - print + print() def get_slices_at_z(z): - return [s for s in WORLD_INFO['slices'].values() if s['z'] == z] + return [s for s in list(WORLD_INFO['slices'].values()) if s['z'] == z] def can_path_to_zone(z1, z2): if z1 == z2: @@ -175,7 +175,7 @@ def can_path_to_zone(z1, z2): if z2 in _to_check: _checked.append(z2) - print _checked + print(_checked) return True return False @@ -184,7 +184,7 @@ def create_zone_map(): for z in range(MAP_SIZE[2]): _stime = time.time() process_slice(z) - print time.time()-_stime + print(time.time()-_stime) def connect_ramps(): for _slice in WORLD_INFO['slices']: @@ -197,17 +197,17 @@ def connect_ramps(): WORLD_INFO['slices'][_slice]['neighbors'][_matched_slice['map'][x][y]].append((x, y)) for _slice in WORLD_INFO['slices']: - print 'Zone %s' % _slice, '@ z-level',WORLD_INFO['slices'][_slice]['z'] + print('Zone %s' % _slice, '@ z-level',WORLD_INFO['slices'][_slice]['z']) for neighbor in WORLD_INFO['slices'][_slice]['neighbors']: - print '\tNeighbor:', neighbor, '(%s ramps)' % len(WORLD_INFO['slices'][_slice]['neighbors'][neighbor]) + print('\tNeighbor:', neighbor, '(%s ramps)' % len(WORLD_INFO['slices'][_slice]['neighbors'][neighbor])) #print WORLD_INFO['slices'][_slice]['neighbors'].keys() if not WORLD_INFO['slices'][_slice]['neighbors']: - print '\tNo neighbors.' + print('\tNo neighbors.') if __name__ == '__main__': create_zone_map() - print + print() connect_ramps() - print can_path_to_zone(1, 1) \ No newline at end of file + print(can_path_to_zone(1, 1)) \ No newline at end of file diff --git a/tests/M07_buildings.py b/tests/M07_buildings.py index e965f4c..c9f1395 100644 --- a/tests/M07_buildings.py +++ b/tests/M07_buildings.py @@ -26,7 +26,7 @@ def walker(chunk_key, steps, add_first=False, chunk_keys=True, avoid_chunk_keys= _valid_directions.append(mod[:]) if not _valid_directions: - print 'Take a break...' + print('Take a break...') break @@ -75,7 +75,7 @@ def connect_to_chunks(connect_to, existing_connections, steps): _common_neighbors = {} _highest = 0 - for layer in _connect_layers.values(): + for layer in list(_connect_layers.values()): for chunk_key in layer['neighbors']: if chunk_key in _common_neighbors: _common_neighbors[chunk_key] += 1 @@ -85,7 +85,7 @@ def connect_to_chunks(connect_to, existing_connections, steps): if _common_neighbors[chunk_key]>_highest: _highest = _common_neighbors[chunk_key] - for chunk_key in _common_neighbors.keys(): + for chunk_key in list(_common_neighbors.keys()): if _common_neighbors[chunk_key]<_highest: del _common_neighbors[chunk_key] @@ -95,7 +95,7 @@ def connect_to_chunks(connect_to, existing_connections, steps): if _highest', stance, _time + print(life['name'], '->', stance, _time) def stun(life, force=0): _current_stance = get_current_stance(life) @@ -121,7 +121,7 @@ def stun(life, force=0): return enter_stance(life, _next_stance, forced=True) def attack(life, target_id, stance): - print life['name'], 'hit', LIFE[target_id]['name']+':', stance + print(life['name'], 'hit', LIFE[target_id]['name']+':', stance) _attack = get_stance(life, stance)['attack'] @@ -132,7 +132,7 @@ def attack(life, target_id, stance): life['score'] += 1 stun(LIFE[target_id], force=_attack['force']) else: - print LIFE[target_id]['name'], 'blocked', life['name'] + print(LIFE[target_id]['name'], 'blocked', life['name']) stun(life) def think(life): @@ -156,7 +156,7 @@ def think(life): _incoming.append({'target_id': life_id, 'time': _target['stance_ticks']}) elif not 'defend' in _current_target_stance or not random.randint(0, life['stats']['melee']): if 'defend' in _current_target_stance: - print life['name'], 'tries to break', LIFE[life_id]['name'] + print(life['name'], 'tries to break', LIFE[life_id]['name']) _targets.append({'target_id': life_id}) @@ -172,14 +172,14 @@ def think(life): _has_counter_attack = get_quickest_attack(life, incoming_attack['target_id'], limit=incoming_attack['time']) if _has_counter_attack: - print life['name'], 'is countering', LIFE[incoming_attack['target_id']]['name'] + print(life['name'], 'is countering', LIFE[incoming_attack['target_id']]['name']) return enter_stance(life, _has_counter_attack, target_id=incoming_attack['target_id']) else: _has_defend = get_quickest_defend(life, limit=incoming_attack['time']) if _has_defend: if not 'defend' in get_current_stance(life) and not (life['next_stance'] and 'defend' in get_stance(life, life['next_stance'])): - print life['name'], 'is defending against', LIFE[incoming_attack['target_id']]['name'] + print(life['name'], 'is defending against', LIFE[incoming_attack['target_id']]['name']) return enter_stance(life, _has_defend, target_id=incoming_attack['target_id']) if life['next_stance']: @@ -194,7 +194,7 @@ def think(life): life['stance'] = life['next_stance'] life['next_stance'] = None - print life['name'], '=', life['stance'], life['stance_flags'] + print(life['name'], '=', life['stance'], life['stance_flags']) _stance = get_current_stance(life) _flags = life['stance_flags'].copy() @@ -211,7 +211,7 @@ def think(life): _stance = get_current_stance(life) if 'defend' in _stance and random.randint(0, life['stats']['melee']): - print life['name'], 'holds' + print(life['name'], 'holds') return True #Stand back up @@ -225,5 +225,5 @@ def think(life): think(p1) think(p2) -print p1['score'] -print p2['score'] \ No newline at end of file +print(p1['score']) +print(p2['score']) \ No newline at end of file diff --git a/tests/M07_recoil.py b/tests/M07_recoil.py index dd6008e..4dec68c 100644 --- a/tests/M07_recoil.py +++ b/tests/M07_recoil.py @@ -79,13 +79,13 @@ def simulate(firearms_skill, recoil=0.0): _accuracies = [] for i in range(1, 10+1): - print 'Skill: %s\t' % i + print('Skill: %s\t' % i) for r in range(0, 5): recoil = r/5.0 _accuracy, _deviations = simulate(i, recoil=recoil) _accuracies.append(_accuracy) - print '\trecoil=%0.4f, accuracy=%0.4f, avg. deviation=%0.4f' % (recoil, _accuracy, sum(_deviations)/float(len(_deviations))) + print('\trecoil=%0.4f, accuracy=%0.4f, avg. deviation=%0.4f' % (recoil, _accuracy, sum(_deviations)/float(len(_deviations)))) -print _weapon['name'], 'accuracy:', sum(_accuracies)/float(len(_accuracies)) +print(_weapon['name'], 'accuracy:', sum(_accuracies)/float(len(_accuracies))) diff --git a/tests/fast_render_simple_numpy.py b/tests/fast_render_simple_numpy.py index abfec57..f38b4d9 100644 --- a/tests/fast_render_simple_numpy.py +++ b/tests/fast_render_simple_numpy.py @@ -17,14 +17,14 @@ SCREEN_W = 80 SCREEN_H = 50 -HALF_W = SCREEN_W / 2 -HALF_H = SCREEN_H / 2 +HALF_W = SCREEN_W // 2 +HALF_H = SCREEN_H // 2 libtcod.console_set_custom_font(os.path.join('arial10x10.png'), libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD) libtcod.console_init_root(SCREEN_W, SCREEN_H, 'libtcod sample', False) -(x, y) = meshgrid(range(SCREEN_W), range(SCREEN_H)) +(x, y) = meshgrid(list(range(SCREEN_W)), list(range(SCREEN_H))) lights = [] lights.append({'x': 40,'y': 20,'brightness': 4.0}) @@ -67,6 +67,6 @@ libtcod.console_fill_background(0, _R, _G, _B) libtcod.console_fill_foreground(0, _R, _G, _B) - print libtcod.sys_get_fps() + print(libtcod.sys_get_fps()) libtcod.console_flush() diff --git a/threads.py b/threads.py index 145455a..fbb7f9c 100644 --- a/threads.py +++ b/threads.py @@ -24,7 +24,7 @@ def check_chunks(self, force=False): self.last_checked = WORLD_INFO['ticks'] - for life in [l for l in LIFE.values() if l['online']]: + for life in [l for l in list(LIFE.values()) if l['online']]: _x_min = bad_numbers.clip(life['pos'][0]-MAP_WINDOW_SIZE[0], 0, MAP_SIZE[0]-1-MAP_WINDOW_SIZE[0]) _y_min = bad_numbers.clip(life['pos'][1]-MAP_WINDOW_SIZE[1], 0, MAP_SIZE[1]-1-MAP_WINDOW_SIZE[1]) _x_max = bad_numbers.clip(life['pos'][0]+MAP_WINDOW_SIZE[0], 0, MAP_SIZE[0]-1) diff --git a/tools/ReactorWatch.py b/tools/ReactorWatch.py index 303f3ee..8c4f339 100644 --- a/tools/ReactorWatch.py +++ b/tools/ReactorWatch.py @@ -27,7 +27,7 @@ def memory(life_id): @app.route('/life/') def life(life_id): life = request('life', value=int(life_id)) - knows = life['know'].values() + knows = list(life['know'].values()) return render_template('life.html', life=life, knows=knows) diff --git a/tools/guntest.py b/tools/guntest.py index ac1fb38..eb8e40a 100644 --- a/tools/guntest.py +++ b/tools/guntest.py @@ -84,13 +84,13 @@ def simulate(firearms_skill, recoil=0.0): _accuracies = [] for i in range(1, 10+1): - print 'Skill: %s\t' % i + print('Skill: %s\t' % i) for r in range(0, 5): recoil = r/5.0 _accuracy, _deviations = simulate(i, recoil=recoil) _accuracies.append(_accuracy) - print '\trecoil=%0.4f, accuracy=%0.4f, avg. deviation=%0.4f' % (recoil, _accuracy, sum(_deviations)/float(len(_deviations))) + print('\trecoil=%0.4f, accuracy=%0.4f, avg. deviation=%0.4f' % (recoil, _accuracy, sum(_deviations)/float(len(_deviations)))) -print _weapon['name'], 'accuracy:', sum(_accuracies)/float(len(_accuracies)) +print(_weapon['name'], 'accuracy:', sum(_accuracies)/float(len(_accuracies))) diff --git a/tools/life_dump.py b/tools/life_dump.py index 281f76c..01a13b2 100644 --- a/tools/life_dump.py +++ b/tools/life_dump.py @@ -7,7 +7,7 @@ def dump(filename): with open(filename, 'r') as e: _life = json.loads(''.join(e.readlines())) - print json.dumps(_life, indent=3) + print(json.dumps(_life, indent=3)) if __name__ == '__main__': if len(sys.argv)>1: diff --git a/weapons.py b/weapons.py index 9a024c1..768ceba 100644 --- a/weapons.py +++ b/weapons.py @@ -191,7 +191,7 @@ def fire(life, target, limb=None): _bullet['accuracy'] = int(round(get_accuracy(life, weapon['uid'], limb=_aim_with_limb))) - print 'ACCURACY', _bullet['accuracy'] + print('ACCURACY', _bullet['accuracy']) del _bullet['parent'] items.move(_bullet, _bullet_direction, _bullet['max_speed']) diff --git a/weather.py b/weather.py index 06b9f5f..cb708ab 100644 --- a/weather.py +++ b/weather.py @@ -29,7 +29,7 @@ def change_weather(): _indexes = [] _i = 0 for light_type in _weather['light_types']: - _weather['color_indexes'].append((WORLD_INFO['length_of_day']/_weather['events'])*_i) + _weather['color_indexes'].append((WORLD_INFO['length_of_day']//_weather['events'])*_i) _i += 1 if 'dark_night' in light_type: @@ -63,7 +63,7 @@ def change_weather(): WORLD_INFO['weather'].update(_weather) def get_current_weather(): - _current_weather = WORLD_INFO['real_time_of_day']/(WORLD_INFO['length_of_day']/len(WORLD_INFO['weather']['colors'])) + _current_weather = WORLD_INFO['real_time_of_day']//(WORLD_INFO['length_of_day']//len(WORLD_INFO['weather']['colors'])) _current_weather = bad_numbers.clip(_current_weather, 0, len(WORLD_INFO['weather']['colors'])-1) return WORLD_INFO['weather']['colors'][_current_weather] @@ -83,7 +83,7 @@ def get_weather_status(): return get_current_weather()['name'] def generate_effects(size): - _current_weather = WORLD_INFO['real_time_of_day']/(WORLD_INFO['length_of_day']/len(WORLD_INFO['weather']['colors'])) + _current_weather = WORLD_INFO['real_time_of_day']//(WORLD_INFO['length_of_day']//len(WORLD_INFO['weather']['colors'])) _current_weather = bad_numbers.clip(_current_weather, 0, len(WORLD_INFO['weather']['colors'])-1) if 'raining' in WORLD_INFO['weather']['colors'][_current_weather]['effects']: diff --git a/worldgen.py b/worldgen.py index 29fb612..fff0ce9 100644 --- a/worldgen.py +++ b/worldgen.py @@ -161,7 +161,7 @@ def load_world(world): SETTINGS['controlling'] = None SETTINGS['following'] = None - for life in LIFE.values(): + for life in list(LIFE.values()): if life['dead']: continue diff --git a/zones.py b/zones.py index 9fd9300..9f0461c 100644 --- a/zones.py +++ b/zones.py @@ -14,9 +14,11 @@ import copy import time +logger = logging.getLogger(__name__) + def cache_zones(): for z in range(0, MAP_SIZE[2]): - ZONE_CACHE[z] = [s for s in WORLD_INFO['slices'].values() if s['z'] == z] + ZONE_CACHE[z] = [s for s in list(WORLD_INFO['slices'].values()) if s['z'] == z] def create_map_array(val=0, size=MAP_SIZE): _map = numpy.zeros((size[0], size[1])) @@ -165,8 +167,12 @@ def process_slice(z, world_info=None, start_id=0, map_size=MAP_SIZE): WORLD_INFO['slices'][_z_id] = {'z': z, 'top_left': _top_left, 'bot_right': _bot_right, 'id': _z_id, 'ramps': list(_ramps), 'neighbors': {}} def get_zone_at_coords(pos): - _map_pos = WORLD_INFO['map'][pos[0]][pos[1]][pos[2]] - + try: + _map_pos = WORLD_INFO['map'][pos[0]][pos[1]][pos[2]] + except IndexError: + logger.exception("Attempted to go out-of-bounds.", stack_info=True) + return None + if not _map_pos or not 'z_id' in _map_pos: return None @@ -228,14 +234,14 @@ def create_zone_map(): if SETTINGS['running']: tcod.console_print(0, 0, 0, ' ') - print 'Zone gen took',time.time()-_t + print('Zone gen took',time.time()-_t) def connect_ramps(): _i = 1 for _slice in WORLD_INFO['slices']: #print 'Connecting:','Zone %s' % _slice, '@ z-level',WORLD_INFO['slices'][_slice]['z'], '(%s ramp(s))' % len(WORLD_INFO['slices'][_slice]['ramps']) - gfx.title('Connecting: %s\%s' % (_i, len(WORLD_INFO['slices'].keys()))) + gfx.title('Connecting: %s\%s' % (_i, len(list(WORLD_INFO['slices'].keys())))) _i += 1 @@ -268,7 +274,7 @@ def dijkstra_map(start_pos, goals, zones, max_chunk_distance=5, rolldown=True, a 'return_score_in_range': return_score_in_range} _map_string = '' - for key in _map.keys(): + for key in list(_map.keys()): _map_string += '%s:%s' % (key, _map[key]) if _map_string in DIJKSTRA_CACHE: