Skip to content

Commit daaf3e8

Browse files
committed
privatized internal libraries
1 parent 1d17a04 commit daaf3e8

File tree

4 files changed

+74
-79
lines changed

4 files changed

+74
-79
lines changed

tdl/__init__.py

Lines changed: 41 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -48,22 +48,21 @@
4848
the screen.
4949
"""
5050

51-
import sys
52-
import os
53-
54-
import ctypes
55-
import weakref
56-
import array
57-
import itertools
58-
import textwrap
59-
import struct
60-
import re
61-
import warnings
51+
import sys as _sys
52+
import os as _os
53+
54+
import ctypes as _ctypes
55+
import weakref as _weakref
56+
import itertools as _itertools
57+
import textwrap as _textwrap
58+
import struct as _struct
59+
import re as _re
60+
import warnings as _warnings
6261

6362
from . import event, map, noise
6463
from .__tcod import _lib, _Color, _unpackfile
6564

66-
_IS_PYTHON3 = (sys.version_info[0] == 3)
65+
_IS_PYTHON3 = (_sys.version_info[0] == 3)
6766

6867
if _IS_PYTHON3: # some type lists to use with isinstance
6968
_INTTYPES = (int,)
@@ -155,19 +154,19 @@ def _getImageSize(filename):
155154
file = open(filename, 'rb')
156155
if file.read(8) == b'\x89PNG\r\n\x1a\n': # PNG
157156
while 1:
158-
length, = struct.unpack('>i', file.read(4))
157+
length, = _struct.unpack('>i', file.read(4))
159158
chunkID = file.read(4)
160159
if chunkID == '': # EOF
161160
return None
162161
if chunkID == b'IHDR':
163162
# return width, height
164-
return struct.unpack('>ii', file.read(8))
163+
return _struct.unpack('>ii', file.read(8))
165164
file.seek(4 + length, 1)
166165
file.seek(0)
167166
if file.read(8) == b'BM': # Bitmap
168167
file.seek(18, 0) # skip to size data
169168
# return width, height
170-
return struct.unpack('<ii', file.read(8))
169+
return _struct.unpack('<ii', file.read(8))
171170
# return None on error, unknown file
172171

173172
class TDLError(Exception):
@@ -344,7 +343,7 @@ def write(self, string):
344343
# help much.
345344
x, y = self._normalizeCursor(*self._cursor)
346345
width, height = self.getSize()
347-
wrapper = textwrap.TextWrapper(initial_indent=(' '*x), width=width)
346+
wrapper = _textwrap.TextWrapper(initial_indent=(' '*x), width=width)
348347
writeLines = []
349348
for line in string.split('\n'):
350349
if line:
@@ -391,7 +390,7 @@ def drawChar(self, x, y, char, fgcolor=(255, 255, 255), bgcolor=(0, 0, 0)):
391390

392391
assert _verify_colors(fgcolor, bgcolor)
393392
x, y = self._normalizePoint(x, y)
394-
x, y = ctypes.c_int(x), ctypes.c_int(y)
393+
x, y = _ctypes.c_int(x), _ctypes.c_int(y)
395394
self._setChar(x, y, _formatChar(char),
396395
_formatColor(fgcolor), _formatColor(bgcolor))
397396

@@ -503,10 +502,10 @@ def drawRect(self, x, y, width, height, string, fgcolor=(255, 255, 255), bgcolor
503502
char = _formatChar(string)
504503
# use itertools to make an x,y grid
505504
# using ctypes here reduces type converstions later
506-
grid = itertools.product((ctypes.c_int(x) for x in range(x, x + width)),
507-
(ctypes.c_int(y) for y in range(y, y + height)))
505+
grid = _itertools.product((_ctypes.c_int(x) for x in range(x, x + width)),
506+
(_ctypes.c_int(y) for y in range(y, y + height)))
508507
# zip the single character in a batch variable
509-
batch = zip(grid, itertools.repeat(char, width * height))
508+
batch = zip(grid, _itertools.repeat(char, width * height))
510509
self._setCharBatch(batch, fgcolor, bgcolor, nullChar=(char is None))
511510

512511
def drawFrame(self, x, y, width, height, string, fgcolor=(255, 255, 255), bgcolor=(0, 0, 0)):
@@ -647,7 +646,7 @@ def __iter__(self):
647646
slow process, especially for Python, and should be minimized.
648647
@rtype: iter((x, y), ...)
649648
"""
650-
return itertools.product(range(self.width), range(self.height))
649+
return _itertools.product(range(self.width), range(self.height))
651650

652651
def move(self, x, y):
653652
"""Move the virtual cursor.
@@ -793,7 +792,7 @@ def __del__(self):
793792
"""
794793
global _rootinitialized, _rootConsoleRef
795794
# check of see if the pointer is to the special root console
796-
if isinstance(self._as_parameter_, ctypes.c_void_p):
795+
if isinstance(self._as_parameter_, _ctypes.c_void_p):
797796
# do we recognise this root console?
798797
if(_rootConsoleRef and _rootConsoleRef is self):
799798
_rootinitialized = False
@@ -813,15 +812,15 @@ def __copy__(self):
813812
def __getstate__(self):
814813
# save data from getChar
815814
data = [self.getChar(x, y) for x,y in
816-
itertools.product(range(self.width), range(self.height))]
815+
_itertools.product(range(self.width), range(self.height))]
817816
return self.width, self.height, data
818817

819818
def __setstate__(self, state):
820819
# make console from __init__ and unpack a getChar array
821820
width, height, data = state
822821
self.__init__(width, height)
823-
for (x, y), graphic in zip(itertools.product(range(width),
824-
range(height)), data):
822+
for (x, y), graphic in zip(_itertools.product(range(width),
823+
range(height)), data):
825824
self.drawChar(x, y, *graphic)
826825

827826
def _replace(self, console):
@@ -898,7 +897,7 @@ def _setCharBatch(self, batch, fgcolor, bgcolor, bgblend=1, nullChar=False):
898897
# buffer values as ctypes objects
899898
self._typewriter = None # clear the typewriter as colors will be set
900899
console = self._as_parameter_
901-
bgblend = ctypes.c_int(bgblend)
900+
bgblend = _ctypes.c_int(bgblend)
902901

903902
if not bgcolor:
904903
bgblend = 0
@@ -1084,9 +1083,9 @@ def init(width, height, title=None, fullscreen=False, renderer='OPENGL'):
10841083
del rootreplacement
10851084

10861085
if title is None: # use a default title
1087-
if sys.argv:
1086+
if _sys.argv:
10881087
# Use the script filename as the title.
1089-
title = os.path.basename(sys.argv[0])
1088+
title = _os.path.basename(_sys.argv[0])
10901089
else:
10911090
title = 'python-tdl'
10921091

@@ -1097,8 +1096,8 @@ def init(width, height, title=None, fullscreen=False, renderer='OPENGL'):
10971096

10981097
event._eventsflushed = False
10991098
_rootinitialized = True
1100-
rootconsole = Console._newConsole(ctypes.c_void_p())
1101-
_rootConsoleRef = weakref.ref(rootconsole)
1099+
rootconsole = Console._newConsole(_ctypes.c_void_p())
1100+
_rootConsoleRef = _weakref.ref(rootconsole)
11021101

11031102
return rootconsole
11041103

@@ -1188,16 +1187,16 @@ def setFont(path, columns=None, rows=None, columnFirst=False,
11881187
flags |= FONT_LAYOUT_ASCII_INROW
11891188
if greyscale:
11901189
flags |= FONT_TYPE_GREYSCALE
1191-
if not os.path.exists(path):
1190+
if not _os.path.exists(path):
11921191
raise TDLError('no file exists at: "%s"' % path)
1193-
path = os.path.abspath(path)
1192+
path = _os.path.abspath(path)
11941193

11951194
# and the rest is the auto-detect script
11961195
imgSize = _getImageSize(path) # try to find image size
11971196
if imgSize:
11981197
imgWidth, imgHeight = imgSize
11991198
# try to get font size from filename
1200-
match = re.match('.*?([0-9]+)[xX]([0-9]+)', os.path.basename(path))
1199+
match = _re.match('.*?([0-9]+)[xX]([0-9]+)', _os.path.basename(path))
12011200
if match:
12021201
fontWidth, fontHeight = match.groups()
12031202
fontWidth, fontHeight = int(fontWidth), int(fontHeight)
@@ -1206,7 +1205,7 @@ def setFont(path, columns=None, rows=None, columnFirst=False,
12061205
estColumns, remC = divmod(imgWidth, fontWidth)
12071206
estRows, remR = divmod(imgHeight, fontHeight)
12081207
if remC or remR:
1209-
warnings.warn("Font may be incorrectly formatted.")
1208+
_warnings.warn("Font may be incorrectly formatted.")
12101209

12111210
if not columns:
12121211
columns = estColumns
@@ -1216,21 +1215,21 @@ def setFont(path, columns=None, rows=None, columnFirst=False,
12161215
# the font name excluded the fonts size
12171216
if not (columns and rows):
12181217
# no matched font size and no tileset is given
1219-
raise TDLError('%s has no font size in filename' % os.path.basename(path))
1218+
raise TDLError('%s has no font size in filename' % _os.path.basename(path))
12201219

12211220
if columns and rows:
12221221
# confirm user set options
12231222
if (fontWidth * columns != imgWidth or
12241223
fontHeight * rows != imgHeight):
1225-
warnings.warn("setFont parameters are set as if the image size is (%d, %d) when the detected size is actually (%i, %i)"
1224+
_warnings.warn("setFont parameters are set as if the image size is (%d, %d) when the detected size is actually (%i, %i)"
12261225
% (fontWidth * columns, fontHeight * rows,
12271226
imgWidth, imgHeight))
12281227
else:
1229-
warnings.warn("%s is probably not an image." % os.path.basename(path))
1228+
_warnings.warn("%s is probably not an image." % _os.path.basename(path))
12301229

12311230
if not (columns and rows):
12321231
# didn't auto-detect
1233-
raise TDLError('Can not auto-detect the tileset of %s' % os.path.basename(path))
1232+
raise TDLError('Can not auto-detect the tileset of %s' % _os.path.basename(path))
12341233

12351234
_lib.TCOD_console_set_custom_font(_encodeString(path), flags, columns, rows)
12361235

@@ -1278,7 +1277,7 @@ def screenshot(path=None):
12781277
if isinstance(path, str):
12791278
_lib.TCOD_sys_save_screenshot(_encodeString(path))
12801279
elif path is None: # save to screenshot001.png, screenshot002.png, ...
1281-
filelist = os.listdir('.')
1280+
filelist = _os.listdir('.')
12821281
n = 1
12831282
filename = 'screenshot%.3i.png' % n
12841283
while filename in filelist:
@@ -1287,11 +1286,11 @@ def screenshot(path=None):
12871286
_lib.TCOD_sys_save_screenshot(_encodeString(filename))
12881287
else: # assume file like obj
12891288
#save to temp file and copy to file-like obj
1290-
tmpname = os.tempnam()
1289+
tmpname = _os.tempnam()
12911290
_lib.TCOD_sys_save_screenshot(_encodeString(tmpname))
12921291
with tmpname as tmpfile:
12931292
path.write(tmpfile.read())
1294-
os.remove(tmpname)
1293+
_os.remove(tmpname)
12951294
#else:
12961295
# raise TypeError('path is an invalid type: %s' % type(path))
12971296

@@ -1328,9 +1327,7 @@ def forceResolution(width, height):
13281327
"""
13291328
_lib.TCOD_sys_force_fullscreen_resolution(width, height)
13301329

1331-
__all__ = [_var for _var in locals().keys() if _var[0] != '_' and _var not in
1332-
['sys', 'os', 'ctypes', 'array', 'weakref', 'itertools', 'textwrap',
1333-
'struct', 're', 'warnings']] # remove modules from __all__
1330+
__all__ = [_var for _var in locals().keys() if _var[0] != '_'] # remove modules from __all__
13341331
__all__ += ['_MetaConsole'] # keep this object public to show the documentation in epydoc
13351332

13361333
__license__ = "New BSD License"

tdl/event.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,7 @@
3030
'NUMLOCK', 'SCROLLLOCK', 'SPACE', 'CHAR'
3131
"""
3232

33-
import time
34-
import ctypes
33+
import time as _time
3534

3635
from .__tcod import _lib, _Mouse, _Key
3736
from . import __tcod as _tcod
@@ -295,7 +294,7 @@ def runOnce(self):
295294
them is a decent way to create a state machine.
296295
"""
297296
if not hasattr(self, '_App__prevTime'):
298-
self.__prevTime = time.clock() # initiate __prevTime
297+
self.__prevTime = _time.clock() # initiate __prevTime
299298
for event in get():
300299
if event.type: # exclude custom events with a blank type variable
301300
# call the ev_* methods
@@ -306,7 +305,7 @@ def runOnce(self):
306305
method = 'key_%s' % event.key # key_KEYNAME
307306
if hasattr(self, method): # silently exclude undefined methods
308307
getattr(self, method)(event)
309-
newTime = time.clock()
308+
newTime = _time.clock()
310309
self.update(newTime - self.__prevTime)
311310
self.__prevTime = newTime
312311
#_tdl.flush()
@@ -414,7 +413,7 @@ def keyWait():
414413
if event.type == 'QUIT':
415414
# convert QUIT into alt+F4
416415
return KeyDown('F4', '', True, False, True, False, False)
417-
time.sleep(.001)
416+
_time.sleep(.001)
418417

419418
def setKeyRepeat(delay=500, interval=0):
420419
"""Change or disable key repeat.
@@ -439,4 +438,4 @@ def isWindowClosed():
439438
"""
440439
return _lib.TCOD_console_is_window_closed()
441440

442-
__all__ = [_var for _var in locals().keys() if _var[0] != '_' and _var not in ['time', 'ctypes']]
441+
__all__ = [_var for _var in locals().keys() if _var[0] != '_']

tdl/map.py

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@
22
Rogue-like map utilitys such as line-of-sight, field-of-view, and path-finding.
33
44
"""
5-
import array
6-
import ctypes
7-
import itertools
8-
import math
5+
import ctypes as _ctypes
6+
import itertools as _itertools
7+
import math as _math
98

10-
import tdl
9+
import tdl as _tdl
1110
from .__tcod import _lib, _PATHCALL
1211

1312
_FOVTYPES = {'BASIC' : 0, 'DIAMOND': 1, 'SHADOW': 2, 'RESTRICTIVE': 12, 'PERMISSIVE': 11}
@@ -20,7 +19,7 @@ def _getFOVType(fov):
2019
return _FOVTYPES[fov]
2120
if fov[:10] == 'PERMISSIVE' and fov[10].isdigit() and fov[10] != '9':
2221
return 4 + int(fov[10])
23-
raise tdl.TDLError('No such fov option as %s' % oldFOV)
22+
raise _tdl.TDLError('No such fov option as %s' % oldFOV)
2423

2524
class AStar(object):
2625
"""A* pathfinder
@@ -31,7 +30,7 @@ class AStar(object):
3130
__slots__ = ('_as_parameter_', '_callback', '__weakref__')
3231

3332
def __init__(self, width, height, callback,
34-
diagnalCost=math.sqrt(2), advanced=False):
33+
diagnalCost=_math.sqrt(2), advanced=False):
3534
"""Create an A* pathfinder using a callback.
3635
3736
Before crating this instance you should make one of two types of
@@ -106,9 +105,9 @@ def getPath(self, origX, origY, destX, destY):
106105
found = _lib.TCOD_path_compute(self, origX, origY, destX, destY)
107106
if not found:
108107
return [] # path not found
109-
x, y = ctypes.c_int(), ctypes.c_int()
110-
xRef, yRef = ctypes.byref(x), ctypes.byref(y)
111-
recalculate = ctypes.c_bool(True)
108+
x, y = _ctypes.c_int(), _ctypes.c_int()
109+
xRef, yRef = _ctypes.byref(x), _ctypes.byref(y)
110+
recalculate = _ctypes.c_bool(True)
112111
path = []
113112
while _lib.TCOD_path_walk(self, xRef, yRef, recalculate):
114113
path.append((x.value, y.value))
@@ -159,20 +158,20 @@ def quickFOV(x, y, callback, fov='PERMISSIVE', radius=7.5, lightWalls=True, sphe
159158
@return: Returns a set of (x, y) points that are within the field-of-view.
160159
"""
161160
trueRadius = radius
162-
radius = int(math.ceil(radius))
161+
radius = int(_math.ceil(radius))
163162
mapSize = radius * 2 + 1
164163
fov = _getFOVType(fov)
165164

166165
setProp = _lib.TCOD_map_set_properties # make local
167166
inFOV = _lib.TCOD_map_is_in_fov
168167

169-
cTrue = ctypes.c_bool(1)
170-
cFalse = ctypes.c_bool(False)
168+
cTrue = _ctypes.c_bool(1)
169+
cFalse = _ctypes.c_bool(False)
171170
tcodMap = _lib.TCOD_map_new(mapSize, mapSize)
172171
try:
173172
# pass one, write callback data to the tcodMap
174-
for (x_, cX), (y_, cY) in itertools.product(((i, ctypes.c_int(i)) for i in range(mapSize)),
175-
((i, ctypes.c_int(i)) for i in range(mapSize))):
173+
for (x_, cX), (y_, cY) in _itertools.product(((i, _ctypes.c_int(i)) for i in range(mapSize)),
174+
((i, _ctypes.c_int(i)) for i in range(mapSize))):
176175

177176
pos = (x_ + x - radius,
178177
y_ + y - radius)
@@ -182,9 +181,9 @@ def quickFOV(x, y, callback, fov='PERMISSIVE', radius=7.5, lightWalls=True, sphe
182181
# pass two, compute fov and build a list of points
183182
_lib.TCOD_map_compute_fov(tcodMap, radius, radius, radius, lightWalls, fov)
184183
touched = set() # points touched by field of view
185-
for (x_, cX),(y_, cY) in itertools.product(((i, ctypes.c_int(i)) for i in range(mapSize)),
186-
((i, ctypes.c_int(i)) for i in range(mapSize))):
187-
if sphere and math.hypot(x_ - radius, y_ - radius) > trueRadius:
184+
for (x_, cX),(y_, cY) in _itertools.product(((i, _ctypes.c_int(i)) for i in range(mapSize)),
185+
((i, _ctypes.c_int(i)) for i in range(mapSize))):
186+
if sphere and _math.hypot(x_ - radius, y_ - radius) > trueRadius:
188187
continue
189188
if inFOV(tcodMap, cX, cY):
190189
touched.add((x_ + x - radius, y_ + y - radius))

0 commit comments

Comments
 (0)