1 """
2 The documentation for python-tdl. A Pythonic port of
3 U{libtcod<http://doryen.eptalys.net/libtcod/>}.
4
5 You can find the project page on Google Code
6 U{here<http://code.google.com/p/python-tdl/>}.
7
8 Report any bugs or issues to the Google Code issue tracker
9 U{here<https://code.google.com/p/python-tdl/issues/list>}.
10
11 Getting Started
12 ===============
13 Once the library is imported you can load the font you want to use with
14 L{tdl.setFont}.
15 This is optional and when skipped will use a decent default font.
16
17 After that you call L{tdl.init} to set the size of the window and get the
18 root console in return.
19 This console is the canvas to what will appear on the screen.
20
21 Indexing Consoles
22 =================
23 For most methods taking a position you can use Python-style negative
24 indexes to refer to the opposite side of a console with (-1, -1)
25 starting at the bottom right.
26 You can also check if a point is part of a console using containment
27 logic i.e. ((x, y) in console).
28
29 Drawing
30 =======
31 Once you have the root console from L{tdl.init} you can start drawing on
32 it using a method such as L{Console.drawChar}.
33 When using this method you can have the char parameter be an integer or a
34 single character string.
35 The fgcolor and bgcolor parameters expect a three item list
36 [red, green, blue] with integers in the 0-255 range with [0, 0, 0] being
37 black and [255, 255, 255] being white.
38 Or instead you can use None for any of the three parameters to tell the
39 library to not overwrite colors.
40 After the drawing functions are called a call to L{tdl.flush} will update
41 the screen.
42 """
43
44 import sys
45 import os
46
47 import ctypes
48 import weakref
49 import array
50 import itertools
51 import textwrap
52 import struct
53 import re
54 import warnings
55
56 from . import event, map, noise
57 from .__tcod import _lib, _Color, _unpackfile
58
59 _IS_PYTHON3 = (sys.version_info[0] == 3)
60
61 if _IS_PYTHON3:
62 _INTTYPES = (int,)
63 _NUMTYPES = (int, float)
64 _STRTYPES = (str, bytes)
65 else:
66 _INTTYPES = (int, long)
67 _NUMTYPES = (int, long, float)
68 _STRTYPES = (str,)
71 "changes string into bytes if running in python 3, for sending to ctypes"
72 if _IS_PYTHON3 and isinstance(string, str):
73 return string.encode()
74 return string
75
93
94 _fontinitialized = False
95 _rootinitialized = False
96 _rootConsoleRef = None
97
98 _setchar = _lib.TCOD_console_set_char
99 _setfore = _lib.TCOD_console_set_char_foreground
100 _setback = _lib.TCOD_console_set_char_background
101 _setcharEX = _lib.TCOD_console_put_char_ex
103 """Used internally.
104 Raise an assertion error if the parameters can not be converted into colors.
105 """
106 for color in colors:
107 assert _iscolor(color), 'a color must be a 3 item tuple, web format, or None, received %s' % repr(color)
108 return True
109
111 """Used internally.
112 A debug function to see if an object can be used as a TCOD color struct.
113 None counts as a parameter to keep the current colors instead.
114
115 This function is often part of an inner-loop and can slow a program down.
116 It has been made to work with assert and can be skipped with the -O flag.
117 Still it's called often and must be optimized.
118 """
119 if color is None:
120 return True
121 if isinstance(color, (tuple, list, _Color)):
122 return len(color) == 3
123 if isinstance(color, _INTTYPES):
124 return True
125 return False
126
155
157 """Try to get the width and height of a bmp of png image file"""
158 file = open(filename, 'rb')
159 if file.read(8) == b'\x89PNG\r\n\x1a\n':
160 while 1:
161 length, = struct.unpack('>i', file.read(4))
162 chunkID = file.read(4)
163 if chunkID == '':
164 return None
165 if chunkID == b'IHDR':
166
167 return struct.unpack('>ii', file.read(8))
168 file.seek(4 + length, 1)
169 file.seek(0)
170 if file.read(8) == b'BM':
171 file.seek(18, 0)
172
173 return struct.unpack('<ii', file.read(8))
174
177 """
178 The catch all for most TDL specific errors.
179 """
180
433
484
534
591
608
615
625
653 def getCover(x, length):
654 """return the (x, width) ranges of what is covered and uncovered"""
655 cover = (0, length)
656 uncover = None
657 if x > 0:
658 cover = (x, length - x)
659 uncover = (0, x)
660 elif x < 0:
661 x = abs(x)
662 cover = (0, length - x)
663 uncover = (length - x, x)
664 return cover, uncover
665
666 width, height = self.getSize()
667 if abs(x) >= width or abs(y) >= height:
668 return self.clear()
669
670
671 coverX, uncoverX = getCover(x, width)
672 coverY, uncoverY = getCover(y, height)
673
674
675
676
677
678
679
680 x, width, srcx = getSlide(x, width)
681 y, height, srcy = getSlide(y, height)
682 self.blit(self, x, y, width, height, srcx, srcy)
683
684 if uncoverX:
685 self.drawRect(uncoverX[0], coverY[0], uncoverX[1], coverY[1], 0x20, 0x000000, 0x000000)
686 if uncoverY:
687 self.drawRect(coverX[0], uncoverY[0], coverX[1], uncoverY[1], 0x20, 0x000000, 0x000000)
688 if uncoverX and uncoverY:
689 self.drawRect(uncoverX[0], uncoverY[0], uncoverX[1], uncoverY[1], 0x20, 0x000000, 0x000000)
690
703
709
711 """Contains character and color data and can be drawn to.
712
713 The console created by the L{tdl.init} function is the root console and is the
714 console that is rendered to the screen with L{flush}.
715
716 Any console created from the Console class is an off-screen console that
717 can be drawn on before being L{blit} to the root console.
718 """
719
720 __slots__ = ('_as_parameter_', '_typewriter')
721
738
739
740 @classmethod
751
765
767
768 clone = self.__class__(self.width, self.height)
769 clone.blit(self)
770 return clone
771
777
785
800
802 """Convertion x and y to their position on the root Console for this Window
803
804 Because this is a Console instead of a Window we return the paramaters
805 untouched"""
806 return x, y
807
808 - def clear(self, fgcolor=(0, 0, 0), bgcolor=(0, 0, 0)):
809 """Clears the entire Console.
810
811 @type fgcolor: (r, g, b)
812 @param fgcolor: Foreground color.
813
814 Must be a 3-item list with integers that range 0-255.
815
816 Unlike most other operations you cannot use None here.
817 @type bgcolor: (r, g, b)
818 @param bgcolor: Background color. See fgcolor.
819 """
820 assert _verify_colors(fgcolor, bgcolor)
821 assert fgcolor and bgcolor, 'Can not use None with clear'
822 self._typewriter = None
823 _lib.TCOD_console_set_default_background(self, _formatColor(bgcolor))
824 _lib.TCOD_console_set_default_foreground(self, _formatColor(fgcolor))
825 _lib.TCOD_console_clear(self)
826
827 - def _setChar(self, x, y, char, fgcolor=None, bgcolor=None, bgblend=1):
828 """
829 Sets a character.
830 This is called often and is designed to be as fast as possible.
831
832 Because of the need for speed this function will do NO TYPE CHECKING
833 AT ALL, it's up to the drawing functions to use the functions:
834 _formatChar and _formatColor before passing to this."""
835
836 console = self._as_parameter_
837
838 if char is not None and fgcolor is not None and bgcolor is not None:
839 _setcharEX(console, x, y, char, fgcolor, bgcolor)
840 return
841 if char is not None:
842 _setchar(console, x, y, char)
843 if fgcolor is not None:
844 _setfore(console, x, y, fgcolor)
845 if bgcolor is not None:
846 _setback(console, x, y, bgcolor, bgblend)
847
848 - def _setCharBatch(self, batch, fgcolor, bgcolor, bgblend=1, nullChar=False):
849 """
850 Try to perform a batch operation otherwise fall back to _setChar.
851 If fgcolor and bgcolor are defined then this is faster but not by very
852 much.
853
854 batch is a iterable of [(x, y), ch] items
855 """
856 if fgcolor and not nullChar:
857
858 self._typewriter = None
859 console = self._as_parameter_
860 bgblend = ctypes.c_int(bgblend)
861
862 if not bgcolor:
863 bgblend = 0
864 else:
865 _lib.TCOD_console_set_default_background(console, bgcolor)
866 _lib.TCOD_console_set_default_foreground(console, fgcolor)
867 _putChar = _lib.TCOD_console_put_char
868 for (x, y), char in batch:
869 _putChar(console, x, y, char, bgblend)
870 else:
871 for (x, y), char in batch:
872 self._setChar(x, y, char, fgcolor, bgcolor, bgblend)
873
875
876 x, y = self._normalizePoint(x, y)
877 char = _lib.TCOD_console_get_char(self, x, y)
878 bgcolor = _lib.TCOD_console_get_char_background_wrapper(self, x, y)
879 fgcolor = _lib.TCOD_console_get_char_foreground_wrapper(self, x, y)
880 return char, tuple(fgcolor), tuple(bgcolor)
881
883 return "<Console (Width=%i Height=%i)>" % (self.width, self.height)
884
885
886 -class Window(_MetaConsole):
887 """A Window contains a small isolated part of a Console.
888
889 Drawing on the Window draws on the Console.
890
891 Making a Window and setting its width or height to None will extend it to
892 the edge of the console.
893 """
894
895 __slots__ = ('parent', 'x', 'y')
896
897 - def __init__(self, console, x, y, width, height):
898 """Isolate part of a L{Console} or L{Window} instance.
899
900 @type console: L{Console} or L{Window}
901 @param console: The parent object which can be a L{Console} or another
902 L{Window} instance.
903
904 @type x: int
905 @param x: X coordinate to place the Window.
906
907 This follows the normal rules for indexing so you can use a
908 negative integer to place the Window relative to the bottom
909 right of the parent Console instance.
910 @type y: int
911 @param y: Y coordinate to place the Window.
912
913 See x.
914
915 @type width: int or None
916 @param width: Width of the Window.
917
918 Can be None to extend as far as possible to the
919 bottom right corner of the parent Console or can be a
920 negative number to be sized reltive to the Consoles total
921 size.
922 @type height: int or None
923 @param height: Height of the Window.
924
925 See width.
926 """
927 _MetaConsole.__init__(self)
928 assert isinstance(console, (Console, Window)), 'console parameter must be a Console or Window instance, got %s' % repr(console)
929 self.parent = console
930 self.x, self.y, self.width, self.height = console._normalizeRect(x, y, width, height)
931 if isinstance(console, Console):
932 self.console = console
933 else:
934 self.console = self.parent.console
935
937 """Convertion x and y to their position on the root Console"""
938
939 return self.parent._translate((x + self.x), (y + self.y))
940
941 - def clear(self, fgcolor=(0, 0, 0), bgcolor=(0, 0, 0)):
942 """Clears the entire Window.
943
944 @type fgcolor: (r, g, b)
945 @param fgcolor: Foreground color.
946
947 Must be a 3-item list with integers that range 0-255.
948
949 Unlike most other operations you can not use None here.
950 @type bgcolor: (r, g, b)
951 @param bgcolor: Background color. See fgcolor.
952 """
953 assert _verify_colors(fgcolor, bgcolor)
954 assert fgcolor and bgcolor, 'Can not use None with clear'
955 self.drawRect(0, 0, None, None, 0x20, fgcolor, bgcolor)
956
957 - def _setChar(self, x, y, char=None, fgcolor=None, bgcolor=None, bgblend=1):
958 self.parent._setChar((x + self.x), (y + self.y), char, fgcolor, bgcolor, bgblend)
959
961 myX = self.x
962 myY = self.y
963 self.parent._setCharBatch((((x + myX, y + myY), ch) for ((x, y), ch) in batch),
964 fgcolor, bgcolor, bgblend)
965
966
967 - def drawChar(self, x, y, char, fgcolor=(255, 255, 255), bgcolor=(0, 0, 0)):
971
972 - def drawRect(self, x, y, width, height, string, fgcolor=(255, 255, 255), bgcolor=(0, 0, 0)):
973
974 x, y, width, height = self._normalizeRect(x, y, width, height)
975 self.parent.drawRect(x + self.x, y + self.y, width, height, string, fgcolor, bgcolor)
976
977 - def drawFrame(self, x, y, width, height, string, fgcolor=(255, 255, 255), bgcolor=(0, 0, 0)):
978
979 x, y, width, height = self._normalizeRect(x, y, width, height)
980 self.parent.drawFrame(x + self.x, y + self.y, width, height, string, fgcolor, bgcolor)
981
986
988 return "<Window(X=%i Y=%i Width=%i Height=%i)>" % (self.x, self.y,
989 self.width,
990 self.height)
991
994 """Converts a console into a scrolling text log that respects special
995 characters.
996
997 This class works best on a L{Window} or off-screen L{Console} instance.
998 In a L{Window} for example the scrolling text is limited to the L{Window}'s
999 isolated area.
1000 """
1001
1003 """Add a virtual cursor to a L{Console} or L{Window} instance.
1004
1005 @type console: L{Console} or L{Window}
1006 """
1007 warnings.warn("Typewriter is no longer needed, use Console or Window objects", DeprecationWarning)
1008 assert isinstance(console, (Console, Window)), 'console parameter must be a Console or Window instance, got %s' % repr(console)
1009 self.parent = console
1010 if isinstance(self.parent, Console):
1011 self.console = self.parent
1012 else:
1013 self.console = self.parent.console
1014 self._cursor = (0, 0)
1015 self.scrollMode = 'scroll'
1016 self.fgcolor = _formatColor((255, 255, 255))
1017 self.bgcolor = _formatColor((0, 0, 0))
1018 self._bgblend = 1
1019
1021 """return the normalized the cursor position."""
1022 width, height = self.parent.getSize()
1023 while x >= width:
1024 x -= width
1025 y += 1
1026 while y >= height:
1027 if self.scrollMode == 'scroll':
1028 y -= 1
1029 self.parent.scroll(0, -1)
1030 elif self.scrollMode == 'error':
1031
1032 self._cursor = (0, 0)
1033 raise TDLError('Typewriter cursor has reached the end of the console')
1034 return (x, y)
1035
1037 """Return the virtual cursor position.
1038
1039 @rtype: (int, int)
1040 @return: Returns (x, y) a 2-integer tuple containing where the next
1041 L{addChar} or L{addStr} will start at.
1042
1043 This can be changed with the L{move} method."""
1044 x, y = self._cursor
1045 width, height = self.parent.getSize()
1046 while x >= width:
1047 x -= width
1048 y += 1
1049 if y >= height and self.scrollMode == 'scroll':
1050 y = height - 1
1051 return x, y
1052
1053 - def move(self, x, y):
1054 """Move the virtual cursor.
1055
1056 @type x: int
1057 @param x: X position to place the cursor.
1058 @type y: int
1059 @param y: Y position to place the cursor.
1060 """
1061 self._cursor = self.parent._normalizePoint(x, y)
1062
1063 - def setFG(self, color):
1064 """Change the foreground color"""
1065 assert _iscolor(color)
1066 assert color is not None
1067 self.fgcolor = _formatColor(color)
1068 if self.console._colorLock is self:
1069 _lib.TCOD_console_set_default_foreground(self.console, self.fgcolor)
1070
1071 - def setBG(self, color):
1072 """Change the background color"""
1073 assert _iscolor(color)
1074 assert color is not None
1075 self.bgcolor = _formatColor(color)
1076 if self.console._colorLock is self:
1077 _lib.TCOD_console_set_default_background(self.console, self.bgcolor)
1078
1080 """Make sure the colors on a console match the Typewriter instance"""
1081 if self.console._colorLock is not self:
1082 self.console._colorLock = self
1083
1084 _lib.TCOD_console_set_default_background(self.console, self.bgcolor)
1085 _lib.TCOD_console_set_default_foreground(self.console, self.fgcolor)
1086
1087
1089 """Draw a single character at the cursor."""
1090 if char == '\n':
1091 x = 0
1092 y += 1
1093 return
1094 if char == '\r':
1095 x = 0
1096 return
1097 x, y = self._normalize(*self.cursor)
1098 self._cursor = [x + 1, y]
1099 self._updateConsole()
1100 x, y = self.parent._translate(x, y)
1101 _lib.TCOD_console_put_char(self.console._as_parameter_, x, y, _formatChar(char), self._bgblend)
1102
1103
1105 """Write a string at the cursor. Handles special characters such as newlines.
1106
1107 @type string: string
1108 @param string:
1109 """
1110 x, y = self._cursor
1111 for char in string:
1112 if char == '\n':
1113 x = 0
1114 y += 1
1115 continue
1116 if char == '\r':
1117 x = 0
1118 continue
1119 x, y = self._normalize(x, y)
1120 self.parent.drawChar(x, y, char, self.fgcolor, self.bgcolor)
1121 x += 1
1122 self._cursor = (x, y)
1123
1124 - def write(self, string):
1125 """This method mimics basic file-like behaviour.
1126
1127 Because of this method you can replace sys.stdout or sys.stderr with
1128 a L{Typewriter} instance.
1129
1130 @type string: string
1131 """
1132
1133
1134
1135 x, y = self._normalize(*self._cursor)
1136 width, height = self.parent.getSize()
1137 wrapper = textwrap.TextWrapper(initial_indent=(' '*x), width=width)
1138 writeLines = []
1139 for line in string.split('\n'):
1140 if line:
1141 writeLines += wrapper.wrap(line)
1142 wrapper.initial_indent = ''
1143 else:
1144 writeLines.append([])
1145
1146 for line in writeLines:
1147 x, y = self._normalize(x, y)
1148 self.parent.drawStr(x, y, line[x:], self.fgcolor, self.bgcolor)
1149 y += 1
1150 x = 0
1151 y -= 1
1152 self._cursor = (x, y)
1153
1154
1155 -def init(width, height, title=None, fullscreen=False, renderer='OPENGL'):
1156 """Start the main console with the given width and height and return the
1157 root console.
1158
1159 Call the consoles drawing functions. Then remember to use L{tdl.flush} to
1160 make what's drawn visible on the console.
1161
1162 @type width: int
1163 @param width: width of the root console (in tiles)
1164
1165 @type height: int
1166 @param height: height of the root console (in tiles)
1167
1168 @type title: string
1169 @param title: Text to display as the window title.
1170
1171 If left None it defaults to the running scripts filename.
1172
1173 @type fullscreen: boolean
1174 @param fullscreen: Can be set to True to start in fullscreen mode.
1175
1176 @type renderer: string
1177 @param renderer: Can be one of 'GLSL', 'OPENGL', or 'SDL'.
1178
1179 Due to way Python works you're unlikely to see much of an
1180 improvement by using 'GLSL' or 'OPENGL' as most of the
1181 time Python is slow interacting with the console and the
1182 rendering itself is pretty fast even on 'SDL'.
1183
1184 @rtype: L{Console}
1185 @return: The root console. Only what is drawn on the root console is
1186 what's visible after a call to L{tdl.flush}.
1187 After the root console is garbage collected, the window made by
1188 this function will close.
1189 """
1190 RENDERERS = {'GLSL': 0, 'OPENGL': 1, 'SDL': 2}
1191 global _rootinitialized, _rootConsoleRef
1192 if not _fontinitialized:
1193 setFont(_unpackfile('terminal8x8.png'), None, None, True, True)
1194
1195 if renderer.upper() not in RENDERERS:
1196 raise TDLError('No such render type "%s", expected one of "%s"' % (renderer, '", "'.join(RENDERERS)))
1197 renderer = RENDERERS[renderer.upper()]
1198
1199
1200 if _rootConsoleRef and _rootConsoleRef():
1201 oldroot = _rootConsoleRef()
1202 rootreplacement = Console(oldroot.width, oldroot.height)
1203 rootreplacement.blit(oldroot)
1204 oldroot._replace(rootreplacement)
1205 del rootreplacement
1206
1207 if title is None:
1208 if sys.argv:
1209
1210 title = os.path.basename(sys.argv[0])
1211 else:
1212 title = 'python-tdl'
1213
1214 _lib.TCOD_console_init_root(width, height, _encodeString(title), fullscreen, renderer)
1215
1216
1217
1218
1219 event._eventsflushed = False
1220 _rootinitialized = True
1221 rootconsole = Console._newConsole(ctypes.c_void_p())
1222 _rootConsoleRef = weakref.ref(rootconsole)
1223
1224 return rootconsole
1225
1227 """Make all changes visible and update the screen.
1228
1229 Remember to call this function after drawing operations.
1230 Calls to flush will enfore the frame rate limit set by L{tdl.setFPS}.
1231
1232 This function can only be called after L{tdl.init}
1233 """
1234 if not _rootinitialized:
1235 raise TDLError('Cannot flush without first initializing with tdl.init')
1236
1237 _lib.TCOD_console_flush()
1238
1239 -def setFont(path, columns=None, rows=None, columnFirst=False,
1240 greyscale=False, altLayout=False):
1241 """Changes the font to be used for this session.
1242 This should be called before L{tdl.init}
1243
1244 If the font specifies its size in its filename (i.e. font_NxN.png) then this
1245 function can auto-detect the tileset formatting and the parameters columns
1246 and rows can be left None.
1247
1248 While it's possible you can change the font mid program it can sometimes
1249 break in rare circumstances. So use caution when doing this.
1250
1251 @type path: string
1252 @param path: Must be a string filepath where a bmp or png file is found.
1253
1254 @type columns: int
1255 @param columns: Number of columns in the tileset.
1256
1257 Can be left None for auto-detection.
1258
1259 @type rows: int
1260 @param rows: Number of rows in the tileset.
1261
1262 Can be left None for auto-detection.
1263
1264 @type columnFirst: boolean
1265 @param columnFirst: Defines if the characer order goes along the rows or
1266 colomns.
1267 It should be True if the charater codes 0-15 are in the
1268 first column.
1269 And should be False if the characters 0-15
1270 are in the first row.
1271
1272 @type greyscale: boolean
1273 @param greyscale: Creates an anti-aliased font from a greyscale bitmap.
1274 Otherwise it uses the alpha channel for anti-aliasing.
1275
1276 Unless you actually need anti-aliasing from a font you
1277 know uses a smooth greyscale channel you should leave
1278 this on False.
1279
1280 @type altLayout: boolean
1281 @param altLayout: An alternative layout with space in the upper left
1282 corner.
1283 The colomn parameter is ignored if this is True,
1284 find examples of this layout in the font/libtcod/
1285 directory included with the python-tdl source.
1286
1287 @raise TDLError: Will be raised if no file is found at path or if auto-
1288 detection fails.
1289
1290 @note: A png file that's been optimized can fail to load correctly on
1291 MAC OS X creating a garbled mess when rendering.
1292 Don't use a program like optipng or just use bmp files instead if
1293 you want your program to work on macs.
1294 """
1295
1296 FONT_LAYOUT_ASCII_INCOL = 1
1297 FONT_LAYOUT_ASCII_INROW = 2
1298 FONT_TYPE_GREYSCALE = 4
1299 FONT_LAYOUT_TCOD = 8
1300 global _fontinitialized
1301 _fontinitialized = True
1302 flags = 0
1303 if altLayout:
1304 flags |= FONT_LAYOUT_TCOD
1305 elif columnFirst:
1306 flags |= FONT_LAYOUT_ASCII_INCOL
1307 else:
1308 flags |= FONT_LAYOUT_ASCII_INROW
1309 if greyscale:
1310 flags |= FONT_TYPE_GREYSCALE
1311 if not os.path.exists(path):
1312 raise TDLError('no file exists at: "%s"' % path)
1313 path = os.path.abspath(path)
1314
1315
1316 imgSize = _getImageSize(path)
1317 if imgSize:
1318 imgWidth, imgHeight = imgSize
1319
1320 match = re.match('.*?([0-9]+)[xX]([0-9]+)', os.path.basename(path))
1321 if match:
1322 fontWidth, fontHeight = match.groups()
1323 fontWidth, fontHeight = int(fontWidth), int(fontHeight)
1324
1325
1326 estColumns, remC = divmod(imgWidth, fontWidth)
1327 estRows, remR = divmod(imgHeight, fontHeight)
1328 if remC or remR:
1329 warnings.warn("Font may be incorrectly formatted.")
1330
1331 if not columns:
1332 columns = estColumns
1333 if not rows:
1334 rows = estRows
1335 else:
1336
1337 if not (columns and rows):
1338
1339 raise TDLError('%s has no font size in filename' % os.path.basename(path))
1340
1341 if columns and rows:
1342
1343 if (fontWidth * columns != imgWidth or
1344 fontHeight * rows != imgHeight):
1345 warnings.warn("setFont parameters are set as if the image size is (%d, %d) when the detected size is actually (%i, %i)"
1346 % (fontWidth * columns, fontHeight * rows,
1347 imgWidth, imgHeight))
1348 else:
1349 warnings.warn("%s is probably not an image." % os.path.basename(path))
1350
1351 if not (columns and rows):
1352
1353 raise TDLError('Can not auto-detect the tileset of %s' % os.path.basename(path))
1354
1355 _lib.TCOD_console_set_custom_font(_encodeString(path), flags, columns, rows)
1356
1358 """Returns True if program is fullscreen.
1359
1360 @rtype: boolean
1361 @return: Returns True if the window is in fullscreen mode.
1362 Otherwise returns False.
1363 """
1364 if not _rootinitialized:
1365 raise TDLError('Initialize first with tdl.init')
1366 return _lib.TCOD_console_is_fullscreen()
1367
1369 """Changes the fullscreen state.
1370
1371 @type fullscreen: boolean
1372 """
1373 if not _rootinitialized:
1374 raise TDLError('Initialize first with tdl.init')
1375 _lib.TCOD_console_set_fullscreen(fullscreen)
1376
1378 """Change the window title.
1379
1380 @type title: string
1381 """
1382 if not _rootinitialized:
1383 raise TDLError('Not initilized. Set title with tdl.init')
1384 _lib.TCOD_console_set_window_title(_encodeString(title))
1385
1387 """Capture the screen and save it as a png file
1388
1389 @type path: string
1390 @param path: The filepath to save the screenshot.
1391
1392 If path is None then the image will be placed in the current
1393 folder with the names:
1394 screenshot001.png, screenshot002.png, ...
1395 """
1396 if not _rootinitialized:
1397 raise TDLError('Initialize first with tdl.init')
1398 if isinstance(path, str):
1399 _lib.TCOD_sys_save_screenshot(_encodeString(path))
1400 elif path is None:
1401 filelist = os.listdir('.')
1402 n = 1
1403 filename = 'screenshot%.3i.png' % n
1404 while filename in filelist:
1405 n += 1
1406 filename = 'screenshot%.3i.png' % n
1407 _lib.TCOD_sys_save_screenshot(_encodeString(filename))
1408 else:
1409
1410 tmpname = os.tempnam()
1411 _lib.TCOD_sys_save_screenshot(_encodeString(tmpname))
1412 with tmpname as tmpfile:
1413 path.write(tmpfile.read())
1414 os.remove(tmpname)
1415
1416
1417
1418 -def setFPS(frameRate):
1419 """Set the maximum frame rate.
1420
1421 @type frameRate: int
1422 @param frameRate: Further calls to L{tdl.flush} will limit the speed of
1423 the program to run at <frameRate> frames per second. Can
1424 also be set to 0 to run without a limit.
1425
1426 Defaults to None.
1427 """
1428 if frameRate is None:
1429 frameRate = 0
1430 assert isinstance(frameRate, _INTTYPES), 'frameRate must be an integer or None, got: %s' % repr(frameRate)
1431 _lib.TCOD_sys_set_fps(frameRate)
1432
1434 """Return the current frames per second of the running program set by
1435 L{setFPS}
1436
1437 @rtype: int
1438 @return: Returns the frameRate set by setFPS.
1439 If set to no limit, this will return 0.
1440 """
1441 return _lib.TCOD_sys_get_fps()
1442
1444 """Change the fullscreen resoulution
1445
1446 @type width: int
1447 @type height: int
1448 """
1449 _lib.TCOD_sys_force_fullscreen_resolution(width, height)
1450
1451 __all__ = [_var for _var in locals().keys() if _var[0] != '_' and _var not in
1452 ['sys', 'os', 'ctypes', 'array', 'weakref', 'itertools', 'textwrap',
1453 'struct', 're', 'warnings']]
1454 __all__ += ['_MetaConsole']
1455 __all__.remove('Typewriter')
1456
1457 __license__ = "New BSD License"
1458 __email__ = "4b796c65+pythonTDL@gmail.com"
1459