id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
9,100
|
jazzband/inflect
|
inflect.py
|
engine.compare_adjs
|
def compare_adjs(self, word1, word2):
"""
compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as adjectives
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise
"""
return self._plequal(word1, word2, self.plural_adj)
|
python
|
def compare_adjs(self, word1, word2):
"""
compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as adjectives
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise
"""
return self._plequal(word1, word2, self.plural_adj)
|
[
"def",
"compare_adjs",
"(",
"self",
",",
"word1",
",",
"word2",
")",
":",
"return",
"self",
".",
"_plequal",
"(",
"word1",
",",
"word2",
",",
"self",
".",
"plural_adj",
")"
] |
compare word1 and word2 for equality regardless of plurality
word1 and word2 are to be treated as adjectives
return values:
eq - the strings are equal
p:s - word1 is the plural of word2
s:p - word2 is the plural of word1
p:p - word1 and word2 are two different plural forms of the one word
False - otherwise
|
[
"compare",
"word1",
"and",
"word2",
"for",
"equality",
"regardless",
"of",
"plurality",
"word1",
"and",
"word2",
"are",
"to",
"be",
"treated",
"as",
"adjectives"
] |
c2a3df74725990c195a5d7f37199de56873962e9
|
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2350-L2363
|
9,101
|
jazzband/inflect
|
inflect.py
|
engine.singular_noun
|
def singular_noun(self, text, count=None, gender=None):
"""
Return the singular of text, where text is a plural noun.
If count supplied, then return the singular if count is one of:
1, a, an, one, each, every, this, that or if count is None
otherwise return text unchanged.
Whitespace at the start and end is preserved.
"""
pre, word, post = self.partition_word(text)
if not word:
return text
sing = self._sinoun(word, count=count, gender=gender)
if sing is not False:
plural = self.postprocess(
word, self._sinoun(word, count=count, gender=gender)
)
return "{}{}{}".format(pre, plural, post)
return False
|
python
|
def singular_noun(self, text, count=None, gender=None):
"""
Return the singular of text, where text is a plural noun.
If count supplied, then return the singular if count is one of:
1, a, an, one, each, every, this, that or if count is None
otherwise return text unchanged.
Whitespace at the start and end is preserved.
"""
pre, word, post = self.partition_word(text)
if not word:
return text
sing = self._sinoun(word, count=count, gender=gender)
if sing is not False:
plural = self.postprocess(
word, self._sinoun(word, count=count, gender=gender)
)
return "{}{}{}".format(pre, plural, post)
return False
|
[
"def",
"singular_noun",
"(",
"self",
",",
"text",
",",
"count",
"=",
"None",
",",
"gender",
"=",
"None",
")",
":",
"pre",
",",
"word",
",",
"post",
"=",
"self",
".",
"partition_word",
"(",
"text",
")",
"if",
"not",
"word",
":",
"return",
"text",
"sing",
"=",
"self",
".",
"_sinoun",
"(",
"word",
",",
"count",
"=",
"count",
",",
"gender",
"=",
"gender",
")",
"if",
"sing",
"is",
"not",
"False",
":",
"plural",
"=",
"self",
".",
"postprocess",
"(",
"word",
",",
"self",
".",
"_sinoun",
"(",
"word",
",",
"count",
"=",
"count",
",",
"gender",
"=",
"gender",
")",
")",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"pre",
",",
"plural",
",",
"post",
")",
"return",
"False"
] |
Return the singular of text, where text is a plural noun.
If count supplied, then return the singular if count is one of:
1, a, an, one, each, every, this, that or if count is None
otherwise return text unchanged.
Whitespace at the start and end is preserved.
|
[
"Return",
"the",
"singular",
"of",
"text",
"where",
"text",
"is",
"a",
"plural",
"noun",
"."
] |
c2a3df74725990c195a5d7f37199de56873962e9
|
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L2365-L2385
|
9,102
|
jazzband/inflect
|
inflect.py
|
engine.a
|
def a(self, text, count=1):
"""
Return the appropriate indefinite article followed by text.
The indefinite article is either 'a' or 'an'.
If count is not one, then return count followed by text
instead of 'a' or 'an'.
Whitespace at the start and end is preserved.
"""
mo = re.search(r"\A(\s*)(?:an?\s+)?(.+?)(\s*)\Z", text, re.IGNORECASE)
if mo:
word = mo.group(2)
if not word:
return text
pre = mo.group(1)
post = mo.group(3)
result = self._indef_article(word, count)
return "{}{}{}".format(pre, result, post)
return ""
|
python
|
def a(self, text, count=1):
"""
Return the appropriate indefinite article followed by text.
The indefinite article is either 'a' or 'an'.
If count is not one, then return count followed by text
instead of 'a' or 'an'.
Whitespace at the start and end is preserved.
"""
mo = re.search(r"\A(\s*)(?:an?\s+)?(.+?)(\s*)\Z", text, re.IGNORECASE)
if mo:
word = mo.group(2)
if not word:
return text
pre = mo.group(1)
post = mo.group(3)
result = self._indef_article(word, count)
return "{}{}{}".format(pre, result, post)
return ""
|
[
"def",
"a",
"(",
"self",
",",
"text",
",",
"count",
"=",
"1",
")",
":",
"mo",
"=",
"re",
".",
"search",
"(",
"r\"\\A(\\s*)(?:an?\\s+)?(.+?)(\\s*)\\Z\"",
",",
"text",
",",
"re",
".",
"IGNORECASE",
")",
"if",
"mo",
":",
"word",
"=",
"mo",
".",
"group",
"(",
"2",
")",
"if",
"not",
"word",
":",
"return",
"text",
"pre",
"=",
"mo",
".",
"group",
"(",
"1",
")",
"post",
"=",
"mo",
".",
"group",
"(",
"3",
")",
"result",
"=",
"self",
".",
"_indef_article",
"(",
"word",
",",
"count",
")",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"pre",
",",
"result",
",",
"post",
")",
"return",
"\"\""
] |
Return the appropriate indefinite article followed by text.
The indefinite article is either 'a' or 'an'.
If count is not one, then return count followed by text
instead of 'a' or 'an'.
Whitespace at the start and end is preserved.
|
[
"Return",
"the",
"appropriate",
"indefinite",
"article",
"followed",
"by",
"text",
"."
] |
c2a3df74725990c195a5d7f37199de56873962e9
|
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L3259-L3280
|
9,103
|
jazzband/inflect
|
inflect.py
|
engine.no
|
def no(self, text, count=None):
"""
If count is 0, no, zero or nil, return 'no' followed by the plural
of text.
If count is one of:
1, a, an, one, each, every, this, that
return count followed by text.
Otherwise return count follow by the plural of text.
In the return value count is always followed by a space.
Whitespace at the start and end is preserved.
"""
if count is None and self.persistent_count is not None:
count = self.persistent_count
if count is None:
count = 0
mo = re.search(r"\A(\s*)(.+?)(\s*)\Z", text)
pre = mo.group(1)
word = mo.group(2)
post = mo.group(3)
if str(count).lower() in pl_count_zero:
return "{}no {}{}".format(pre, self.plural(word, 0), post)
else:
return "{}{} {}{}".format(pre, count, self.plural(word, count), post)
|
python
|
def no(self, text, count=None):
"""
If count is 0, no, zero or nil, return 'no' followed by the plural
of text.
If count is one of:
1, a, an, one, each, every, this, that
return count followed by text.
Otherwise return count follow by the plural of text.
In the return value count is always followed by a space.
Whitespace at the start and end is preserved.
"""
if count is None and self.persistent_count is not None:
count = self.persistent_count
if count is None:
count = 0
mo = re.search(r"\A(\s*)(.+?)(\s*)\Z", text)
pre = mo.group(1)
word = mo.group(2)
post = mo.group(3)
if str(count).lower() in pl_count_zero:
return "{}no {}{}".format(pre, self.plural(word, 0), post)
else:
return "{}{} {}{}".format(pre, count, self.plural(word, count), post)
|
[
"def",
"no",
"(",
"self",
",",
"text",
",",
"count",
"=",
"None",
")",
":",
"if",
"count",
"is",
"None",
"and",
"self",
".",
"persistent_count",
"is",
"not",
"None",
":",
"count",
"=",
"self",
".",
"persistent_count",
"if",
"count",
"is",
"None",
":",
"count",
"=",
"0",
"mo",
"=",
"re",
".",
"search",
"(",
"r\"\\A(\\s*)(.+?)(\\s*)\\Z\"",
",",
"text",
")",
"pre",
"=",
"mo",
".",
"group",
"(",
"1",
")",
"word",
"=",
"mo",
".",
"group",
"(",
"2",
")",
"post",
"=",
"mo",
".",
"group",
"(",
"3",
")",
"if",
"str",
"(",
"count",
")",
".",
"lower",
"(",
")",
"in",
"pl_count_zero",
":",
"return",
"\"{}no {}{}\"",
".",
"format",
"(",
"pre",
",",
"self",
".",
"plural",
"(",
"word",
",",
"0",
")",
",",
"post",
")",
"else",
":",
"return",
"\"{}{} {}{}\"",
".",
"format",
"(",
"pre",
",",
"count",
",",
"self",
".",
"plural",
"(",
"word",
",",
"count",
")",
",",
"post",
")"
] |
If count is 0, no, zero or nil, return 'no' followed by the plural
of text.
If count is one of:
1, a, an, one, each, every, this, that
return count followed by text.
Otherwise return count follow by the plural of text.
In the return value count is always followed by a space.
Whitespace at the start and end is preserved.
|
[
"If",
"count",
"is",
"0",
"no",
"zero",
"or",
"nil",
"return",
"no",
"followed",
"by",
"the",
"plural",
"of",
"text",
"."
] |
c2a3df74725990c195a5d7f37199de56873962e9
|
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L3369-L3398
|
9,104
|
jazzband/inflect
|
inflect.py
|
engine.present_participle
|
def present_participle(self, word):
"""
Return the present participle for word.
word is the 3rd person singular verb.
"""
plv = self.plural_verb(word, 2)
for pat, repl in (
(r"ie$", r"y"),
(r"ue$", r"u"), # TODO: isn't ue$ -> u encompassed in the following rule?
(r"([auy])e$", r"\g<1>"),
(r"ski$", r"ski"),
(r"[^b]i$", r""),
(r"^(are|were)$", r"be"),
(r"^(had)$", r"hav"),
(r"^(hoe)$", r"\g<1>"),
(r"([^e])e$", r"\g<1>"),
(r"er$", r"er"),
(r"([^aeiou][aeiouy]([bdgmnprst]))$", r"\g<1>\g<2>"),
):
(ans, num) = re.subn(pat, repl, plv)
if num:
return "%sing" % ans
return "%sing" % ans
|
python
|
def present_participle(self, word):
"""
Return the present participle for word.
word is the 3rd person singular verb.
"""
plv = self.plural_verb(word, 2)
for pat, repl in (
(r"ie$", r"y"),
(r"ue$", r"u"), # TODO: isn't ue$ -> u encompassed in the following rule?
(r"([auy])e$", r"\g<1>"),
(r"ski$", r"ski"),
(r"[^b]i$", r""),
(r"^(are|were)$", r"be"),
(r"^(had)$", r"hav"),
(r"^(hoe)$", r"\g<1>"),
(r"([^e])e$", r"\g<1>"),
(r"er$", r"er"),
(r"([^aeiou][aeiouy]([bdgmnprst]))$", r"\g<1>\g<2>"),
):
(ans, num) = re.subn(pat, repl, plv)
if num:
return "%sing" % ans
return "%sing" % ans
|
[
"def",
"present_participle",
"(",
"self",
",",
"word",
")",
":",
"plv",
"=",
"self",
".",
"plural_verb",
"(",
"word",
",",
"2",
")",
"for",
"pat",
",",
"repl",
"in",
"(",
"(",
"r\"ie$\"",
",",
"r\"y\"",
")",
",",
"(",
"r\"ue$\"",
",",
"r\"u\"",
")",
",",
"# TODO: isn't ue$ -> u encompassed in the following rule?",
"(",
"r\"([auy])e$\"",
",",
"r\"\\g<1>\"",
")",
",",
"(",
"r\"ski$\"",
",",
"r\"ski\"",
")",
",",
"(",
"r\"[^b]i$\"",
",",
"r\"\"",
")",
",",
"(",
"r\"^(are|were)$\"",
",",
"r\"be\"",
")",
",",
"(",
"r\"^(had)$\"",
",",
"r\"hav\"",
")",
",",
"(",
"r\"^(hoe)$\"",
",",
"r\"\\g<1>\"",
")",
",",
"(",
"r\"([^e])e$\"",
",",
"r\"\\g<1>\"",
")",
",",
"(",
"r\"er$\"",
",",
"r\"er\"",
")",
",",
"(",
"r\"([^aeiou][aeiouy]([bdgmnprst]))$\"",
",",
"r\"\\g<1>\\g<2>\"",
")",
",",
")",
":",
"(",
"ans",
",",
"num",
")",
"=",
"re",
".",
"subn",
"(",
"pat",
",",
"repl",
",",
"plv",
")",
"if",
"num",
":",
"return",
"\"%sing\"",
"%",
"ans",
"return",
"\"%sing\"",
"%",
"ans"
] |
Return the present participle for word.
word is the 3rd person singular verb.
|
[
"Return",
"the",
"present",
"participle",
"for",
"word",
"."
] |
c2a3df74725990c195a5d7f37199de56873962e9
|
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L3402-L3427
|
9,105
|
jazzband/inflect
|
inflect.py
|
engine.ordinal
|
def ordinal(self, num):
"""
Return the ordinal of num.
num can be an integer or text
e.g. ordinal(1) returns '1st'
ordinal('one') returns 'first'
"""
if re.match(r"\d", str(num)):
try:
num % 2
n = num
except TypeError:
if "." in str(num):
try:
# numbers after decimal,
# so only need last one for ordinal
n = int(num[-1])
except ValueError: # ends with '.', so need to use whole string
n = int(num[:-1])
else:
n = int(num)
try:
post = nth[n % 100]
except KeyError:
post = nth[n % 10]
return "{}{}".format(num, post)
else:
mo = re.search(r"(%s)\Z" % ordinal_suff, num)
try:
post = ordinal[mo.group(1)]
return re.sub(r"(%s)\Z" % ordinal_suff, post, num)
except AttributeError:
return "%sth" % num
|
python
|
def ordinal(self, num):
"""
Return the ordinal of num.
num can be an integer or text
e.g. ordinal(1) returns '1st'
ordinal('one') returns 'first'
"""
if re.match(r"\d", str(num)):
try:
num % 2
n = num
except TypeError:
if "." in str(num):
try:
# numbers after decimal,
# so only need last one for ordinal
n = int(num[-1])
except ValueError: # ends with '.', so need to use whole string
n = int(num[:-1])
else:
n = int(num)
try:
post = nth[n % 100]
except KeyError:
post = nth[n % 10]
return "{}{}".format(num, post)
else:
mo = re.search(r"(%s)\Z" % ordinal_suff, num)
try:
post = ordinal[mo.group(1)]
return re.sub(r"(%s)\Z" % ordinal_suff, post, num)
except AttributeError:
return "%sth" % num
|
[
"def",
"ordinal",
"(",
"self",
",",
"num",
")",
":",
"if",
"re",
".",
"match",
"(",
"r\"\\d\"",
",",
"str",
"(",
"num",
")",
")",
":",
"try",
":",
"num",
"%",
"2",
"n",
"=",
"num",
"except",
"TypeError",
":",
"if",
"\".\"",
"in",
"str",
"(",
"num",
")",
":",
"try",
":",
"# numbers after decimal,",
"# so only need last one for ordinal",
"n",
"=",
"int",
"(",
"num",
"[",
"-",
"1",
"]",
")",
"except",
"ValueError",
":",
"# ends with '.', so need to use whole string",
"n",
"=",
"int",
"(",
"num",
"[",
":",
"-",
"1",
"]",
")",
"else",
":",
"n",
"=",
"int",
"(",
"num",
")",
"try",
":",
"post",
"=",
"nth",
"[",
"n",
"%",
"100",
"]",
"except",
"KeyError",
":",
"post",
"=",
"nth",
"[",
"n",
"%",
"10",
"]",
"return",
"\"{}{}\"",
".",
"format",
"(",
"num",
",",
"post",
")",
"else",
":",
"mo",
"=",
"re",
".",
"search",
"(",
"r\"(%s)\\Z\"",
"%",
"ordinal_suff",
",",
"num",
")",
"try",
":",
"post",
"=",
"ordinal",
"[",
"mo",
".",
"group",
"(",
"1",
")",
"]",
"return",
"re",
".",
"sub",
"(",
"r\"(%s)\\Z\"",
"%",
"ordinal_suff",
",",
"post",
",",
"num",
")",
"except",
"AttributeError",
":",
"return",
"\"%sth\"",
"%",
"num"
] |
Return the ordinal of num.
num can be an integer or text
e.g. ordinal(1) returns '1st'
ordinal('one') returns 'first'
|
[
"Return",
"the",
"ordinal",
"of",
"num",
"."
] |
c2a3df74725990c195a5d7f37199de56873962e9
|
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L3431-L3467
|
9,106
|
jazzband/inflect
|
inflect.py
|
engine.join
|
def join(
self,
words,
sep=None,
sep_spaced=True,
final_sep=None,
conj="and",
conj_spaced=True,
):
"""
Join words into a list.
e.g. join(['ant', 'bee', 'fly']) returns 'ant, bee, and fly'
options:
conj: replacement for 'and'
sep: separator. default ',', unless ',' is in the list then ';'
final_sep: final separator. default ',', unless ',' is in the list then ';'
conj_spaced: boolean. Should conj have spaces around it
"""
if not words:
return ""
if len(words) == 1:
return words[0]
if conj_spaced:
if conj == "":
conj = " "
else:
conj = " %s " % conj
if len(words) == 2:
return "{}{}{}".format(words[0], conj, words[1])
if sep is None:
if "," in "".join(words):
sep = ";"
else:
sep = ","
if final_sep is None:
final_sep = sep
final_sep = "{}{}".format(final_sep, conj)
if sep_spaced:
sep += " "
return "{}{}{}".format(sep.join(words[0:-1]), final_sep, words[-1])
|
python
|
def join(
self,
words,
sep=None,
sep_spaced=True,
final_sep=None,
conj="and",
conj_spaced=True,
):
"""
Join words into a list.
e.g. join(['ant', 'bee', 'fly']) returns 'ant, bee, and fly'
options:
conj: replacement for 'and'
sep: separator. default ',', unless ',' is in the list then ';'
final_sep: final separator. default ',', unless ',' is in the list then ';'
conj_spaced: boolean. Should conj have spaces around it
"""
if not words:
return ""
if len(words) == 1:
return words[0]
if conj_spaced:
if conj == "":
conj = " "
else:
conj = " %s " % conj
if len(words) == 2:
return "{}{}{}".format(words[0], conj, words[1])
if sep is None:
if "," in "".join(words):
sep = ";"
else:
sep = ","
if final_sep is None:
final_sep = sep
final_sep = "{}{}".format(final_sep, conj)
if sep_spaced:
sep += " "
return "{}{}{}".format(sep.join(words[0:-1]), final_sep, words[-1])
|
[
"def",
"join",
"(",
"self",
",",
"words",
",",
"sep",
"=",
"None",
",",
"sep_spaced",
"=",
"True",
",",
"final_sep",
"=",
"None",
",",
"conj",
"=",
"\"and\"",
",",
"conj_spaced",
"=",
"True",
",",
")",
":",
"if",
"not",
"words",
":",
"return",
"\"\"",
"if",
"len",
"(",
"words",
")",
"==",
"1",
":",
"return",
"words",
"[",
"0",
"]",
"if",
"conj_spaced",
":",
"if",
"conj",
"==",
"\"\"",
":",
"conj",
"=",
"\" \"",
"else",
":",
"conj",
"=",
"\" %s \"",
"%",
"conj",
"if",
"len",
"(",
"words",
")",
"==",
"2",
":",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"words",
"[",
"0",
"]",
",",
"conj",
",",
"words",
"[",
"1",
"]",
")",
"if",
"sep",
"is",
"None",
":",
"if",
"\",\"",
"in",
"\"\"",
".",
"join",
"(",
"words",
")",
":",
"sep",
"=",
"\";\"",
"else",
":",
"sep",
"=",
"\",\"",
"if",
"final_sep",
"is",
"None",
":",
"final_sep",
"=",
"sep",
"final_sep",
"=",
"\"{}{}\"",
".",
"format",
"(",
"final_sep",
",",
"conj",
")",
"if",
"sep_spaced",
":",
"sep",
"+=",
"\" \"",
"return",
"\"{}{}{}\"",
".",
"format",
"(",
"sep",
".",
"join",
"(",
"words",
"[",
"0",
":",
"-",
"1",
"]",
")",
",",
"final_sep",
",",
"words",
"[",
"-",
"1",
"]",
")"
] |
Join words into a list.
e.g. join(['ant', 'bee', 'fly']) returns 'ant, bee, and fly'
options:
conj: replacement for 'and'
sep: separator. default ',', unless ',' is in the list then ';'
final_sep: final separator. default ',', unless ',' is in the list then ';'
conj_spaced: boolean. Should conj have spaces around it
|
[
"Join",
"words",
"into",
"a",
"list",
"."
] |
c2a3df74725990c195a5d7f37199de56873962e9
|
https://github.com/jazzband/inflect/blob/c2a3df74725990c195a5d7f37199de56873962e9/inflect.py#L3756-L3804
|
9,107
|
libtcod/python-tcod
|
tcod/tcod.py
|
_int
|
def _int(int_or_str: Any) -> int:
"return an integer where a single character string may be expected"
if isinstance(int_or_str, str):
return ord(int_or_str)
if isinstance(int_or_str, bytes):
return int_or_str[0]
return int(int_or_str)
|
python
|
def _int(int_or_str: Any) -> int:
"return an integer where a single character string may be expected"
if isinstance(int_or_str, str):
return ord(int_or_str)
if isinstance(int_or_str, bytes):
return int_or_str[0]
return int(int_or_str)
|
[
"def",
"_int",
"(",
"int_or_str",
":",
"Any",
")",
"->",
"int",
":",
"if",
"isinstance",
"(",
"int_or_str",
",",
"str",
")",
":",
"return",
"ord",
"(",
"int_or_str",
")",
"if",
"isinstance",
"(",
"int_or_str",
",",
"bytes",
")",
":",
"return",
"int_or_str",
"[",
"0",
"]",
"return",
"int",
"(",
"int_or_str",
")"
] |
return an integer where a single character string may be expected
|
[
"return",
"an",
"integer",
"where",
"a",
"single",
"character",
"string",
"may",
"be",
"expected"
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/tcod.py#L15-L21
|
9,108
|
libtcod/python-tcod
|
tcod/tcod.py
|
_console
|
def _console(console: Any) -> Any:
"""Return a cffi console."""
try:
return console.console_c
except AttributeError:
warnings.warn(
(
"Falsy console parameters are deprecated, "
"always use the root console instance returned by "
"console_init_root."
),
DeprecationWarning,
stacklevel=3,
)
return ffi.NULL
|
python
|
def _console(console: Any) -> Any:
"""Return a cffi console."""
try:
return console.console_c
except AttributeError:
warnings.warn(
(
"Falsy console parameters are deprecated, "
"always use the root console instance returned by "
"console_init_root."
),
DeprecationWarning,
stacklevel=3,
)
return ffi.NULL
|
[
"def",
"_console",
"(",
"console",
":",
"Any",
")",
"->",
"Any",
":",
"try",
":",
"return",
"console",
".",
"console_c",
"except",
"AttributeError",
":",
"warnings",
".",
"warn",
"(",
"(",
"\"Falsy console parameters are deprecated, \"",
"\"always use the root console instance returned by \"",
"\"console_init_root.\"",
")",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"3",
",",
")",
"return",
"ffi",
".",
"NULL"
] |
Return a cffi console.
|
[
"Return",
"a",
"cffi",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/tcod.py#L139-L153
|
9,109
|
libtcod/python-tcod
|
tcod/color.py
|
Color._new_from_cdata
|
def _new_from_cdata(cls, cdata: Any) -> "Color":
"""new in libtcod-cffi"""
return cls(cdata.r, cdata.g, cdata.b)
|
python
|
def _new_from_cdata(cls, cdata: Any) -> "Color":
"""new in libtcod-cffi"""
return cls(cdata.r, cdata.g, cdata.b)
|
[
"def",
"_new_from_cdata",
"(",
"cls",
",",
"cdata",
":",
"Any",
")",
"->",
"\"Color\"",
":",
"return",
"cls",
"(",
"cdata",
".",
"r",
",",
"cdata",
".",
"g",
",",
"cdata",
".",
"b",
")"
] |
new in libtcod-cffi
|
[
"new",
"in",
"libtcod",
"-",
"cffi"
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/color.py#L66-L68
|
9,110
|
libtcod/python-tcod
|
tcod/event.py
|
_describe_bitmask
|
def _describe_bitmask(
bits: int, table: Dict[Any, str], default: str = "0"
) -> str:
"""Returns a bitmask in human readable form.
This is a private function, used internally.
Args:
bits (int): The bitmask to be represented.
table (Dict[Any,str]): A reverse lookup table.
default (Any): A default return value when bits is 0.
Returns: str: A printable version of the bits variable.
"""
result = []
for bit, name in table.items():
if bit & bits:
result.append(name)
if not result:
return default
return "|".join(result)
|
python
|
def _describe_bitmask(
bits: int, table: Dict[Any, str], default: str = "0"
) -> str:
"""Returns a bitmask in human readable form.
This is a private function, used internally.
Args:
bits (int): The bitmask to be represented.
table (Dict[Any,str]): A reverse lookup table.
default (Any): A default return value when bits is 0.
Returns: str: A printable version of the bits variable.
"""
result = []
for bit, name in table.items():
if bit & bits:
result.append(name)
if not result:
return default
return "|".join(result)
|
[
"def",
"_describe_bitmask",
"(",
"bits",
":",
"int",
",",
"table",
":",
"Dict",
"[",
"Any",
",",
"str",
"]",
",",
"default",
":",
"str",
"=",
"\"0\"",
")",
"->",
"str",
":",
"result",
"=",
"[",
"]",
"for",
"bit",
",",
"name",
"in",
"table",
".",
"items",
"(",
")",
":",
"if",
"bit",
"&",
"bits",
":",
"result",
".",
"append",
"(",
"name",
")",
"if",
"not",
"result",
":",
"return",
"default",
"return",
"\"|\"",
".",
"join",
"(",
"result",
")"
] |
Returns a bitmask in human readable form.
This is a private function, used internally.
Args:
bits (int): The bitmask to be represented.
table (Dict[Any,str]): A reverse lookup table.
default (Any): A default return value when bits is 0.
Returns: str: A printable version of the bits variable.
|
[
"Returns",
"a",
"bitmask",
"in",
"human",
"readable",
"form",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/event.py#L25-L45
|
9,111
|
libtcod/python-tcod
|
tcod/event.py
|
_pixel_to_tile
|
def _pixel_to_tile(x: float, y: float) -> Tuple[float, float]:
"""Convert pixel coordinates to tile coordinates."""
xy = tcod.ffi.new("double[2]", (x, y))
tcod.lib.TCOD_sys_pixel_to_tile(xy, xy + 1)
return xy[0], xy[1]
|
python
|
def _pixel_to_tile(x: float, y: float) -> Tuple[float, float]:
"""Convert pixel coordinates to tile coordinates."""
xy = tcod.ffi.new("double[2]", (x, y))
tcod.lib.TCOD_sys_pixel_to_tile(xy, xy + 1)
return xy[0], xy[1]
|
[
"def",
"_pixel_to_tile",
"(",
"x",
":",
"float",
",",
"y",
":",
"float",
")",
"->",
"Tuple",
"[",
"float",
",",
"float",
"]",
":",
"xy",
"=",
"tcod",
".",
"ffi",
".",
"new",
"(",
"\"double[2]\"",
",",
"(",
"x",
",",
"y",
")",
")",
"tcod",
".",
"lib",
".",
"TCOD_sys_pixel_to_tile",
"(",
"xy",
",",
"xy",
"+",
"1",
")",
"return",
"xy",
"[",
"0",
"]",
",",
"xy",
"[",
"1",
"]"
] |
Convert pixel coordinates to tile coordinates.
|
[
"Convert",
"pixel",
"coordinates",
"to",
"tile",
"coordinates",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/event.py#L48-L52
|
9,112
|
libtcod/python-tcod
|
tcod/event.py
|
get
|
def get() -> Iterator[Any]:
"""Return an iterator for all pending events.
Events are processed as the iterator is consumed. Breaking out of, or
discarding the iterator will leave the remaining events on the event queue.
Example::
for event in tcod.event.get():
if event.type == "QUIT":
print(event)
raise SystemExit()
elif event.type == "KEYDOWN":
print(event)
elif event.type == "MOUSEBUTTONDOWN":
print(event)
elif event.type == "MOUSEMOTION":
print(event)
else:
print(event)
"""
sdl_event = tcod.ffi.new("SDL_Event*")
while tcod.lib.SDL_PollEvent(sdl_event):
if sdl_event.type in _SDL_TO_CLASS_TABLE:
yield _SDL_TO_CLASS_TABLE[sdl_event.type].from_sdl_event(sdl_event)
else:
yield Undefined.from_sdl_event(sdl_event)
|
python
|
def get() -> Iterator[Any]:
"""Return an iterator for all pending events.
Events are processed as the iterator is consumed. Breaking out of, or
discarding the iterator will leave the remaining events on the event queue.
Example::
for event in tcod.event.get():
if event.type == "QUIT":
print(event)
raise SystemExit()
elif event.type == "KEYDOWN":
print(event)
elif event.type == "MOUSEBUTTONDOWN":
print(event)
elif event.type == "MOUSEMOTION":
print(event)
else:
print(event)
"""
sdl_event = tcod.ffi.new("SDL_Event*")
while tcod.lib.SDL_PollEvent(sdl_event):
if sdl_event.type in _SDL_TO_CLASS_TABLE:
yield _SDL_TO_CLASS_TABLE[sdl_event.type].from_sdl_event(sdl_event)
else:
yield Undefined.from_sdl_event(sdl_event)
|
[
"def",
"get",
"(",
")",
"->",
"Iterator",
"[",
"Any",
"]",
":",
"sdl_event",
"=",
"tcod",
".",
"ffi",
".",
"new",
"(",
"\"SDL_Event*\"",
")",
"while",
"tcod",
".",
"lib",
".",
"SDL_PollEvent",
"(",
"sdl_event",
")",
":",
"if",
"sdl_event",
".",
"type",
"in",
"_SDL_TO_CLASS_TABLE",
":",
"yield",
"_SDL_TO_CLASS_TABLE",
"[",
"sdl_event",
".",
"type",
"]",
".",
"from_sdl_event",
"(",
"sdl_event",
")",
"else",
":",
"yield",
"Undefined",
".",
"from_sdl_event",
"(",
"sdl_event",
")"
] |
Return an iterator for all pending events.
Events are processed as the iterator is consumed. Breaking out of, or
discarding the iterator will leave the remaining events on the event queue.
Example::
for event in tcod.event.get():
if event.type == "QUIT":
print(event)
raise SystemExit()
elif event.type == "KEYDOWN":
print(event)
elif event.type == "MOUSEBUTTONDOWN":
print(event)
elif event.type == "MOUSEMOTION":
print(event)
else:
print(event)
|
[
"Return",
"an",
"iterator",
"for",
"all",
"pending",
"events",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/event.py#L564-L590
|
9,113
|
libtcod/python-tcod
|
tcod/event.py
|
wait
|
def wait(timeout: Optional[float] = None) -> Iterator[Any]:
"""Block until events exist, then return an event iterator.
`timeout` is the maximum number of seconds to wait as a floating point
number with millisecond precision, or it can be None to wait forever.
Returns the same iterator as a call to :any:`tcod.event.get`.
Example::
for event in tcod.event.wait():
if event.type == "QUIT":
print(event)
raise SystemExit()
elif event.type == "KEYDOWN":
print(event)
elif event.type == "MOUSEBUTTONDOWN":
print(event)
elif event.type == "MOUSEMOTION":
print(event)
else:
print(event)
"""
if timeout is not None:
tcod.lib.SDL_WaitEventTimeout(tcod.ffi.NULL, int(timeout * 1000))
else:
tcod.lib.SDL_WaitEvent(tcod.ffi.NULL)
return get()
|
python
|
def wait(timeout: Optional[float] = None) -> Iterator[Any]:
"""Block until events exist, then return an event iterator.
`timeout` is the maximum number of seconds to wait as a floating point
number with millisecond precision, or it can be None to wait forever.
Returns the same iterator as a call to :any:`tcod.event.get`.
Example::
for event in tcod.event.wait():
if event.type == "QUIT":
print(event)
raise SystemExit()
elif event.type == "KEYDOWN":
print(event)
elif event.type == "MOUSEBUTTONDOWN":
print(event)
elif event.type == "MOUSEMOTION":
print(event)
else:
print(event)
"""
if timeout is not None:
tcod.lib.SDL_WaitEventTimeout(tcod.ffi.NULL, int(timeout * 1000))
else:
tcod.lib.SDL_WaitEvent(tcod.ffi.NULL)
return get()
|
[
"def",
"wait",
"(",
"timeout",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
")",
"->",
"Iterator",
"[",
"Any",
"]",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"tcod",
".",
"lib",
".",
"SDL_WaitEventTimeout",
"(",
"tcod",
".",
"ffi",
".",
"NULL",
",",
"int",
"(",
"timeout",
"*",
"1000",
")",
")",
"else",
":",
"tcod",
".",
"lib",
".",
"SDL_WaitEvent",
"(",
"tcod",
".",
"ffi",
".",
"NULL",
")",
"return",
"get",
"(",
")"
] |
Block until events exist, then return an event iterator.
`timeout` is the maximum number of seconds to wait as a floating point
number with millisecond precision, or it can be None to wait forever.
Returns the same iterator as a call to :any:`tcod.event.get`.
Example::
for event in tcod.event.wait():
if event.type == "QUIT":
print(event)
raise SystemExit()
elif event.type == "KEYDOWN":
print(event)
elif event.type == "MOUSEBUTTONDOWN":
print(event)
elif event.type == "MOUSEMOTION":
print(event)
else:
print(event)
|
[
"Block",
"until",
"events",
"exist",
"then",
"return",
"an",
"event",
"iterator",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/event.py#L593-L620
|
9,114
|
libtcod/python-tcod
|
tcod/event.py
|
get_mouse_state
|
def get_mouse_state() -> MouseState:
"""Return the current state of the mouse.
.. addedversion:: 9.3
"""
xy = tcod.ffi.new("int[2]")
buttons = tcod.lib.SDL_GetMouseState(xy, xy + 1)
x, y = _pixel_to_tile(*xy)
return MouseState((xy[0], xy[1]), (int(x), int(y)), buttons)
|
python
|
def get_mouse_state() -> MouseState:
"""Return the current state of the mouse.
.. addedversion:: 9.3
"""
xy = tcod.ffi.new("int[2]")
buttons = tcod.lib.SDL_GetMouseState(xy, xy + 1)
x, y = _pixel_to_tile(*xy)
return MouseState((xy[0], xy[1]), (int(x), int(y)), buttons)
|
[
"def",
"get_mouse_state",
"(",
")",
"->",
"MouseState",
":",
"xy",
"=",
"tcod",
".",
"ffi",
".",
"new",
"(",
"\"int[2]\"",
")",
"buttons",
"=",
"tcod",
".",
"lib",
".",
"SDL_GetMouseState",
"(",
"xy",
",",
"xy",
"+",
"1",
")",
"x",
",",
"y",
"=",
"_pixel_to_tile",
"(",
"*",
"xy",
")",
"return",
"MouseState",
"(",
"(",
"xy",
"[",
"0",
"]",
",",
"xy",
"[",
"1",
"]",
")",
",",
"(",
"int",
"(",
"x",
")",
",",
"int",
"(",
"y",
")",
")",
",",
"buttons",
")"
] |
Return the current state of the mouse.
.. addedversion:: 9.3
|
[
"Return",
"the",
"current",
"state",
"of",
"the",
"mouse",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/event.py#L749-L757
|
9,115
|
libtcod/python-tcod
|
tcod/_internal.py
|
deprecate
|
def deprecate(
message: str, category: Any = DeprecationWarning, stacklevel: int = 0
) -> Callable[[F], F]:
"""Return a decorator which adds a warning to functions."""
def decorator(func: F) -> F:
if not __debug__:
return func
@functools.wraps(func)
def wrapper(*args, **kargs): # type: ignore
warnings.warn(message, category, stacklevel=stacklevel + 2)
return func(*args, **kargs)
return cast(F, wrapper)
return decorator
|
python
|
def deprecate(
message: str, category: Any = DeprecationWarning, stacklevel: int = 0
) -> Callable[[F], F]:
"""Return a decorator which adds a warning to functions."""
def decorator(func: F) -> F:
if not __debug__:
return func
@functools.wraps(func)
def wrapper(*args, **kargs): # type: ignore
warnings.warn(message, category, stacklevel=stacklevel + 2)
return func(*args, **kargs)
return cast(F, wrapper)
return decorator
|
[
"def",
"deprecate",
"(",
"message",
":",
"str",
",",
"category",
":",
"Any",
"=",
"DeprecationWarning",
",",
"stacklevel",
":",
"int",
"=",
"0",
")",
"->",
"Callable",
"[",
"[",
"F",
"]",
",",
"F",
"]",
":",
"def",
"decorator",
"(",
"func",
":",
"F",
")",
"->",
"F",
":",
"if",
"not",
"__debug__",
":",
"return",
"func",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"# type: ignore",
"warnings",
".",
"warn",
"(",
"message",
",",
"category",
",",
"stacklevel",
"=",
"stacklevel",
"+",
"2",
")",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
"return",
"cast",
"(",
"F",
",",
"wrapper",
")",
"return",
"decorator"
] |
Return a decorator which adds a warning to functions.
|
[
"Return",
"a",
"decorator",
"which",
"adds",
"a",
"warning",
"to",
"functions",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/_internal.py#L9-L25
|
9,116
|
libtcod/python-tcod
|
tcod/_internal.py
|
pending_deprecate
|
def pending_deprecate(
message: str = "This function may be deprecated in the future."
" Consider raising an issue on GitHub if you need this feature.",
category: Any = PendingDeprecationWarning,
stacklevel: int = 0,
) -> Callable[[F], F]:
"""Like deprecate, but the default parameters are filled out for a generic
pending deprecation warning."""
return deprecate(message, category, stacklevel)
|
python
|
def pending_deprecate(
message: str = "This function may be deprecated in the future."
" Consider raising an issue on GitHub if you need this feature.",
category: Any = PendingDeprecationWarning,
stacklevel: int = 0,
) -> Callable[[F], F]:
"""Like deprecate, but the default parameters are filled out for a generic
pending deprecation warning."""
return deprecate(message, category, stacklevel)
|
[
"def",
"pending_deprecate",
"(",
"message",
":",
"str",
"=",
"\"This function may be deprecated in the future.\"",
"\" Consider raising an issue on GitHub if you need this feature.\"",
",",
"category",
":",
"Any",
"=",
"PendingDeprecationWarning",
",",
"stacklevel",
":",
"int",
"=",
"0",
",",
")",
"->",
"Callable",
"[",
"[",
"F",
"]",
",",
"F",
"]",
":",
"return",
"deprecate",
"(",
"message",
",",
"category",
",",
"stacklevel",
")"
] |
Like deprecate, but the default parameters are filled out for a generic
pending deprecation warning.
|
[
"Like",
"deprecate",
"but",
"the",
"default",
"parameters",
"are",
"filled",
"out",
"for",
"a",
"generic",
"pending",
"deprecation",
"warning",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/_internal.py#L28-L36
|
9,117
|
libtcod/python-tcod
|
tdl/__init__.py
|
_format_char
|
def _format_char(char):
"""Prepares a single character for passing to ctypes calls, needs to return
an integer but can also pass None which will keep the current character
instead of overwriting it.
This is called often and needs to be optimized whenever possible.
"""
if char is None:
return -1
if isinstance(char, _STRTYPES) and len(char) == 1:
return ord(char)
try:
return int(char) # allow all int-like objects
except:
raise TypeError('char single character string, integer, or None\nReceived: ' + repr(char))
|
python
|
def _format_char(char):
"""Prepares a single character for passing to ctypes calls, needs to return
an integer but can also pass None which will keep the current character
instead of overwriting it.
This is called often and needs to be optimized whenever possible.
"""
if char is None:
return -1
if isinstance(char, _STRTYPES) and len(char) == 1:
return ord(char)
try:
return int(char) # allow all int-like objects
except:
raise TypeError('char single character string, integer, or None\nReceived: ' + repr(char))
|
[
"def",
"_format_char",
"(",
"char",
")",
":",
"if",
"char",
"is",
"None",
":",
"return",
"-",
"1",
"if",
"isinstance",
"(",
"char",
",",
"_STRTYPES",
")",
"and",
"len",
"(",
"char",
")",
"==",
"1",
":",
"return",
"ord",
"(",
"char",
")",
"try",
":",
"return",
"int",
"(",
"char",
")",
"# allow all int-like objects",
"except",
":",
"raise",
"TypeError",
"(",
"'char single character string, integer, or None\\nReceived: '",
"+",
"repr",
"(",
"char",
")",
")"
] |
Prepares a single character for passing to ctypes calls, needs to return
an integer but can also pass None which will keep the current character
instead of overwriting it.
This is called often and needs to be optimized whenever possible.
|
[
"Prepares",
"a",
"single",
"character",
"for",
"passing",
"to",
"ctypes",
"calls",
"needs",
"to",
"return",
"an",
"integer",
"but",
"can",
"also",
"pass",
"None",
"which",
"will",
"keep",
"the",
"current",
"character",
"instead",
"of",
"overwriting",
"it",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L101-L115
|
9,118
|
libtcod/python-tcod
|
tdl/__init__.py
|
_format_str
|
def _format_str(string):
"""Attempt fast string handing by decoding directly into an array."""
if isinstance(string, _STRTYPES):
if _IS_PYTHON3:
array = _array.array('I')
array.frombytes(string.encode(_utf32_codec))
else: # Python 2
if isinstance(string, unicode):
array = _array.array(b'I')
array.fromstring(string.encode(_utf32_codec))
else:
array = _array.array(b'B')
array.fromstring(string)
return array
return string
|
python
|
def _format_str(string):
"""Attempt fast string handing by decoding directly into an array."""
if isinstance(string, _STRTYPES):
if _IS_PYTHON3:
array = _array.array('I')
array.frombytes(string.encode(_utf32_codec))
else: # Python 2
if isinstance(string, unicode):
array = _array.array(b'I')
array.fromstring(string.encode(_utf32_codec))
else:
array = _array.array(b'B')
array.fromstring(string)
return array
return string
|
[
"def",
"_format_str",
"(",
"string",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"_STRTYPES",
")",
":",
"if",
"_IS_PYTHON3",
":",
"array",
"=",
"_array",
".",
"array",
"(",
"'I'",
")",
"array",
".",
"frombytes",
"(",
"string",
".",
"encode",
"(",
"_utf32_codec",
")",
")",
"else",
":",
"# Python 2",
"if",
"isinstance",
"(",
"string",
",",
"unicode",
")",
":",
"array",
"=",
"_array",
".",
"array",
"(",
"b'I'",
")",
"array",
".",
"fromstring",
"(",
"string",
".",
"encode",
"(",
"_utf32_codec",
")",
")",
"else",
":",
"array",
"=",
"_array",
".",
"array",
"(",
"b'B'",
")",
"array",
".",
"fromstring",
"(",
"string",
")",
"return",
"array",
"return",
"string"
] |
Attempt fast string handing by decoding directly into an array.
|
[
"Attempt",
"fast",
"string",
"handing",
"by",
"decoding",
"directly",
"into",
"an",
"array",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L119-L133
|
9,119
|
libtcod/python-tcod
|
tdl/__init__.py
|
_getImageSize
|
def _getImageSize(filename):
"""Try to get the width and height of a bmp of png image file"""
result = None
file = open(filename, 'rb')
if file.read(8) == b'\x89PNG\r\n\x1a\n': # PNG
while 1:
length, = _struct.unpack('>i', file.read(4))
chunkID = file.read(4)
if chunkID == '': # EOF
break
if chunkID == b'IHDR':
# return width, height
result = _struct.unpack('>ii', file.read(8))
break
file.seek(4 + length, 1)
file.close()
return result
file.seek(0)
if file.read(8) == b'BM': # Bitmap
file.seek(18, 0) # skip to size data
result = _struct.unpack('<ii', file.read(8))
file.close()
return result
|
python
|
def _getImageSize(filename):
"""Try to get the width and height of a bmp of png image file"""
result = None
file = open(filename, 'rb')
if file.read(8) == b'\x89PNG\r\n\x1a\n': # PNG
while 1:
length, = _struct.unpack('>i', file.read(4))
chunkID = file.read(4)
if chunkID == '': # EOF
break
if chunkID == b'IHDR':
# return width, height
result = _struct.unpack('>ii', file.read(8))
break
file.seek(4 + length, 1)
file.close()
return result
file.seek(0)
if file.read(8) == b'BM': # Bitmap
file.seek(18, 0) # skip to size data
result = _struct.unpack('<ii', file.read(8))
file.close()
return result
|
[
"def",
"_getImageSize",
"(",
"filename",
")",
":",
"result",
"=",
"None",
"file",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"if",
"file",
".",
"read",
"(",
"8",
")",
"==",
"b'\\x89PNG\\r\\n\\x1a\\n'",
":",
"# PNG",
"while",
"1",
":",
"length",
",",
"=",
"_struct",
".",
"unpack",
"(",
"'>i'",
",",
"file",
".",
"read",
"(",
"4",
")",
")",
"chunkID",
"=",
"file",
".",
"read",
"(",
"4",
")",
"if",
"chunkID",
"==",
"''",
":",
"# EOF",
"break",
"if",
"chunkID",
"==",
"b'IHDR'",
":",
"# return width, height",
"result",
"=",
"_struct",
".",
"unpack",
"(",
"'>ii'",
",",
"file",
".",
"read",
"(",
"8",
")",
")",
"break",
"file",
".",
"seek",
"(",
"4",
"+",
"length",
",",
"1",
")",
"file",
".",
"close",
"(",
")",
"return",
"result",
"file",
".",
"seek",
"(",
"0",
")",
"if",
"file",
".",
"read",
"(",
"8",
")",
"==",
"b'BM'",
":",
"# Bitmap",
"file",
".",
"seek",
"(",
"18",
",",
"0",
")",
"# skip to size data",
"result",
"=",
"_struct",
".",
"unpack",
"(",
"'<ii'",
",",
"file",
".",
"read",
"(",
"8",
")",
")",
"file",
".",
"close",
"(",
")",
"return",
"result"
] |
Try to get the width and height of a bmp of png image file
|
[
"Try",
"to",
"get",
"the",
"width",
"and",
"height",
"of",
"a",
"bmp",
"of",
"png",
"image",
"file"
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L165-L187
|
9,120
|
libtcod/python-tcod
|
tdl/__init__.py
|
init
|
def init(width, height, title=None, fullscreen=False, renderer='SDL'):
"""Start the main console with the given width and height and return the
root console.
Call the consoles drawing functions. Then remember to use L{tdl.flush} to
make what's drawn visible on the console.
Args:
width (int): width of the root console (in tiles)
height (int): height of the root console (in tiles)
title (Optiona[Text]):
Text to display as the window title.
If left None it defaults to the running scripts filename.
fullscreen (bool): Can be set to True to start in fullscreen mode.
renderer (Text): Can be one of 'GLSL', 'OPENGL', or 'SDL'.
Due to way Python works you're unlikely to see much of an
improvement by using 'GLSL' over 'OPENGL' as most of the
time Python is slow interacting with the console and the
rendering itself is pretty fast even on 'SDL'.
Returns:
tdl.Console: The root console.
Only what is drawn on the root console is
what's visible after a call to :any:`tdl.flush`.
After the root console is garbage collected, the window made by
this function will close.
.. seealso::
:any:`Console` :any:`set_font`
"""
RENDERERS = {'GLSL': 0, 'OPENGL': 1, 'SDL': 2}
global _rootinitialized, _rootConsoleRef
if not _fontinitialized: # set the default font to the one that comes with tdl
set_font(_os.path.join(__path__[0], 'terminal8x8.png'),
None, None, True, True)
if renderer.upper() not in RENDERERS:
raise TDLError('No such render type "%s", expected one of "%s"' % (renderer, '", "'.join(RENDERERS)))
renderer = RENDERERS[renderer.upper()]
# If a console already exists then make a clone to replace it
if _rootConsoleRef and _rootConsoleRef():
# unhook the root console, turning into a regular console and deleting
# the root console from libTCOD
_rootConsoleRef()._root_unhook()
if title is None: # use a default title
if _sys.argv:
# Use the script filename as the title.
title = _os.path.basename(_sys.argv[0])
else:
title = 'python-tdl'
_lib.TCOD_console_init_root(width, height, _encodeString(title), fullscreen, renderer)
#event.get() # flush the libtcod event queue to fix some issues
# issues may be fixed already
event._eventsflushed = False
_rootinitialized = True
rootconsole = Console._newConsole(_ffi.NULL)
_rootConsoleRef = _weakref.ref(rootconsole)
return rootconsole
|
python
|
def init(width, height, title=None, fullscreen=False, renderer='SDL'):
"""Start the main console with the given width and height and return the
root console.
Call the consoles drawing functions. Then remember to use L{tdl.flush} to
make what's drawn visible on the console.
Args:
width (int): width of the root console (in tiles)
height (int): height of the root console (in tiles)
title (Optiona[Text]):
Text to display as the window title.
If left None it defaults to the running scripts filename.
fullscreen (bool): Can be set to True to start in fullscreen mode.
renderer (Text): Can be one of 'GLSL', 'OPENGL', or 'SDL'.
Due to way Python works you're unlikely to see much of an
improvement by using 'GLSL' over 'OPENGL' as most of the
time Python is slow interacting with the console and the
rendering itself is pretty fast even on 'SDL'.
Returns:
tdl.Console: The root console.
Only what is drawn on the root console is
what's visible after a call to :any:`tdl.flush`.
After the root console is garbage collected, the window made by
this function will close.
.. seealso::
:any:`Console` :any:`set_font`
"""
RENDERERS = {'GLSL': 0, 'OPENGL': 1, 'SDL': 2}
global _rootinitialized, _rootConsoleRef
if not _fontinitialized: # set the default font to the one that comes with tdl
set_font(_os.path.join(__path__[0], 'terminal8x8.png'),
None, None, True, True)
if renderer.upper() not in RENDERERS:
raise TDLError('No such render type "%s", expected one of "%s"' % (renderer, '", "'.join(RENDERERS)))
renderer = RENDERERS[renderer.upper()]
# If a console already exists then make a clone to replace it
if _rootConsoleRef and _rootConsoleRef():
# unhook the root console, turning into a regular console and deleting
# the root console from libTCOD
_rootConsoleRef()._root_unhook()
if title is None: # use a default title
if _sys.argv:
# Use the script filename as the title.
title = _os.path.basename(_sys.argv[0])
else:
title = 'python-tdl'
_lib.TCOD_console_init_root(width, height, _encodeString(title), fullscreen, renderer)
#event.get() # flush the libtcod event queue to fix some issues
# issues may be fixed already
event._eventsflushed = False
_rootinitialized = True
rootconsole = Console._newConsole(_ffi.NULL)
_rootConsoleRef = _weakref.ref(rootconsole)
return rootconsole
|
[
"def",
"init",
"(",
"width",
",",
"height",
",",
"title",
"=",
"None",
",",
"fullscreen",
"=",
"False",
",",
"renderer",
"=",
"'SDL'",
")",
":",
"RENDERERS",
"=",
"{",
"'GLSL'",
":",
"0",
",",
"'OPENGL'",
":",
"1",
",",
"'SDL'",
":",
"2",
"}",
"global",
"_rootinitialized",
",",
"_rootConsoleRef",
"if",
"not",
"_fontinitialized",
":",
"# set the default font to the one that comes with tdl",
"set_font",
"(",
"_os",
".",
"path",
".",
"join",
"(",
"__path__",
"[",
"0",
"]",
",",
"'terminal8x8.png'",
")",
",",
"None",
",",
"None",
",",
"True",
",",
"True",
")",
"if",
"renderer",
".",
"upper",
"(",
")",
"not",
"in",
"RENDERERS",
":",
"raise",
"TDLError",
"(",
"'No such render type \"%s\", expected one of \"%s\"'",
"%",
"(",
"renderer",
",",
"'\", \"'",
".",
"join",
"(",
"RENDERERS",
")",
")",
")",
"renderer",
"=",
"RENDERERS",
"[",
"renderer",
".",
"upper",
"(",
")",
"]",
"# If a console already exists then make a clone to replace it",
"if",
"_rootConsoleRef",
"and",
"_rootConsoleRef",
"(",
")",
":",
"# unhook the root console, turning into a regular console and deleting",
"# the root console from libTCOD",
"_rootConsoleRef",
"(",
")",
".",
"_root_unhook",
"(",
")",
"if",
"title",
"is",
"None",
":",
"# use a default title",
"if",
"_sys",
".",
"argv",
":",
"# Use the script filename as the title.",
"title",
"=",
"_os",
".",
"path",
".",
"basename",
"(",
"_sys",
".",
"argv",
"[",
"0",
"]",
")",
"else",
":",
"title",
"=",
"'python-tdl'",
"_lib",
".",
"TCOD_console_init_root",
"(",
"width",
",",
"height",
",",
"_encodeString",
"(",
"title",
")",
",",
"fullscreen",
",",
"renderer",
")",
"#event.get() # flush the libtcod event queue to fix some issues",
"# issues may be fixed already",
"event",
".",
"_eventsflushed",
"=",
"False",
"_rootinitialized",
"=",
"True",
"rootconsole",
"=",
"Console",
".",
"_newConsole",
"(",
"_ffi",
".",
"NULL",
")",
"_rootConsoleRef",
"=",
"_weakref",
".",
"ref",
"(",
"rootconsole",
")",
"return",
"rootconsole"
] |
Start the main console with the given width and height and return the
root console.
Call the consoles drawing functions. Then remember to use L{tdl.flush} to
make what's drawn visible on the console.
Args:
width (int): width of the root console (in tiles)
height (int): height of the root console (in tiles)
title (Optiona[Text]):
Text to display as the window title.
If left None it defaults to the running scripts filename.
fullscreen (bool): Can be set to True to start in fullscreen mode.
renderer (Text): Can be one of 'GLSL', 'OPENGL', or 'SDL'.
Due to way Python works you're unlikely to see much of an
improvement by using 'GLSL' over 'OPENGL' as most of the
time Python is slow interacting with the console and the
rendering itself is pretty fast even on 'SDL'.
Returns:
tdl.Console: The root console.
Only what is drawn on the root console is
what's visible after a call to :any:`tdl.flush`.
After the root console is garbage collected, the window made by
this function will close.
.. seealso::
:any:`Console` :any:`set_font`
|
[
"Start",
"the",
"main",
"console",
"with",
"the",
"given",
"width",
"and",
"height",
"and",
"return",
"the",
"root",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L1014-L1080
|
9,121
|
libtcod/python-tcod
|
tdl/__init__.py
|
screenshot
|
def screenshot(path=None):
"""Capture the screen and save it as a png file.
If path is None then the image will be placed in the current
folder with the names:
``screenshot001.png, screenshot002.png, ...``
Args:
path (Optional[Text]): The file path to save the screenshot.
"""
if not _rootinitialized:
raise TDLError('Initialize first with tdl.init')
if isinstance(path, str):
_lib.TCOD_sys_save_screenshot(_encodeString(path))
elif path is None: # save to screenshot001.png, screenshot002.png, ...
filelist = _os.listdir('.')
n = 1
filename = 'screenshot%.3i.png' % n
while filename in filelist:
n += 1
filename = 'screenshot%.3i.png' % n
_lib.TCOD_sys_save_screenshot(_encodeString(filename))
else: # assume file like obj
#save to temp file and copy to file-like obj
tmpname = _os.tempnam()
_lib.TCOD_sys_save_screenshot(_encodeString(tmpname))
with tmpname as tmpfile:
path.write(tmpfile.read())
_os.remove(tmpname)
|
python
|
def screenshot(path=None):
"""Capture the screen and save it as a png file.
If path is None then the image will be placed in the current
folder with the names:
``screenshot001.png, screenshot002.png, ...``
Args:
path (Optional[Text]): The file path to save the screenshot.
"""
if not _rootinitialized:
raise TDLError('Initialize first with tdl.init')
if isinstance(path, str):
_lib.TCOD_sys_save_screenshot(_encodeString(path))
elif path is None: # save to screenshot001.png, screenshot002.png, ...
filelist = _os.listdir('.')
n = 1
filename = 'screenshot%.3i.png' % n
while filename in filelist:
n += 1
filename = 'screenshot%.3i.png' % n
_lib.TCOD_sys_save_screenshot(_encodeString(filename))
else: # assume file like obj
#save to temp file and copy to file-like obj
tmpname = _os.tempnam()
_lib.TCOD_sys_save_screenshot(_encodeString(tmpname))
with tmpname as tmpfile:
path.write(tmpfile.read())
_os.remove(tmpname)
|
[
"def",
"screenshot",
"(",
"path",
"=",
"None",
")",
":",
"if",
"not",
"_rootinitialized",
":",
"raise",
"TDLError",
"(",
"'Initialize first with tdl.init'",
")",
"if",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"_lib",
".",
"TCOD_sys_save_screenshot",
"(",
"_encodeString",
"(",
"path",
")",
")",
"elif",
"path",
"is",
"None",
":",
"# save to screenshot001.png, screenshot002.png, ...",
"filelist",
"=",
"_os",
".",
"listdir",
"(",
"'.'",
")",
"n",
"=",
"1",
"filename",
"=",
"'screenshot%.3i.png'",
"%",
"n",
"while",
"filename",
"in",
"filelist",
":",
"n",
"+=",
"1",
"filename",
"=",
"'screenshot%.3i.png'",
"%",
"n",
"_lib",
".",
"TCOD_sys_save_screenshot",
"(",
"_encodeString",
"(",
"filename",
")",
")",
"else",
":",
"# assume file like obj",
"#save to temp file and copy to file-like obj",
"tmpname",
"=",
"_os",
".",
"tempnam",
"(",
")",
"_lib",
".",
"TCOD_sys_save_screenshot",
"(",
"_encodeString",
"(",
"tmpname",
")",
")",
"with",
"tmpname",
"as",
"tmpfile",
":",
"path",
".",
"write",
"(",
"tmpfile",
".",
"read",
"(",
")",
")",
"_os",
".",
"remove",
"(",
"tmpname",
")"
] |
Capture the screen and save it as a png file.
If path is None then the image will be placed in the current
folder with the names:
``screenshot001.png, screenshot002.png, ...``
Args:
path (Optional[Text]): The file path to save the screenshot.
|
[
"Capture",
"the",
"screen",
"and",
"save",
"it",
"as",
"a",
"png",
"file",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L1243-L1271
|
9,122
|
libtcod/python-tcod
|
tdl/__init__.py
|
_BaseConsole._normalizePoint
|
def _normalizePoint(self, x, y):
"""Check if a point is in bounds and make minor adjustments.
Respects Pythons negative indexes. -1 starts at the bottom right.
Replaces the _drawable function
"""
# cast to int, always faster than type checking
x = int(x)
y = int(y)
assert (-self.width <= x < self.width) and \
(-self.height <= y < self.height), \
('(%i, %i) is an invalid postition on %s' % (x, y, self))
# handle negative indexes
return (x % self.width, y % self.height)
|
python
|
def _normalizePoint(self, x, y):
"""Check if a point is in bounds and make minor adjustments.
Respects Pythons negative indexes. -1 starts at the bottom right.
Replaces the _drawable function
"""
# cast to int, always faster than type checking
x = int(x)
y = int(y)
assert (-self.width <= x < self.width) and \
(-self.height <= y < self.height), \
('(%i, %i) is an invalid postition on %s' % (x, y, self))
# handle negative indexes
return (x % self.width, y % self.height)
|
[
"def",
"_normalizePoint",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"# cast to int, always faster than type checking",
"x",
"=",
"int",
"(",
"x",
")",
"y",
"=",
"int",
"(",
"y",
")",
"assert",
"(",
"-",
"self",
".",
"width",
"<=",
"x",
"<",
"self",
".",
"width",
")",
"and",
"(",
"-",
"self",
".",
"height",
"<=",
"y",
"<",
"self",
".",
"height",
")",
",",
"(",
"'(%i, %i) is an invalid postition on %s'",
"%",
"(",
"x",
",",
"y",
",",
"self",
")",
")",
"# handle negative indexes",
"return",
"(",
"x",
"%",
"self",
".",
"width",
",",
"y",
"%",
"self",
".",
"height",
")"
] |
Check if a point is in bounds and make minor adjustments.
Respects Pythons negative indexes. -1 starts at the bottom right.
Replaces the _drawable function
|
[
"Check",
"if",
"a",
"point",
"is",
"in",
"bounds",
"and",
"make",
"minor",
"adjustments",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L208-L223
|
9,123
|
libtcod/python-tcod
|
tdl/__init__.py
|
_BaseConsole._normalizeRect
|
def _normalizeRect(self, x, y, width, height):
"""Check if the rectangle is in bounds and make minor adjustments.
raise AssertionError's for any problems
"""
x, y = self._normalizePoint(x, y) # inherit _normalizePoint logic
assert width is None or isinstance(width, _INTTYPES), 'width must be an integer or None, got %s' % repr(width)
assert height is None or isinstance(height, _INTTYPES), 'height must be an integer or None, got %s' % repr(height)
# if width or height are None then extend them to the edge
if width is None:
width = self.width - x
elif width < 0: # handle negative numbers
width += self.width
width = max(0, width) # a 'too big' negative is clamped zero
if height is None:
height = self.height - y
height = max(0, height)
elif height < 0:
height += self.height
# reduce rect size to bounds
width = min(width, self.width - x)
height = min(height, self.height - y)
return x, y, width, height
|
python
|
def _normalizeRect(self, x, y, width, height):
"""Check if the rectangle is in bounds and make minor adjustments.
raise AssertionError's for any problems
"""
x, y = self._normalizePoint(x, y) # inherit _normalizePoint logic
assert width is None or isinstance(width, _INTTYPES), 'width must be an integer or None, got %s' % repr(width)
assert height is None or isinstance(height, _INTTYPES), 'height must be an integer or None, got %s' % repr(height)
# if width or height are None then extend them to the edge
if width is None:
width = self.width - x
elif width < 0: # handle negative numbers
width += self.width
width = max(0, width) # a 'too big' negative is clamped zero
if height is None:
height = self.height - y
height = max(0, height)
elif height < 0:
height += self.height
# reduce rect size to bounds
width = min(width, self.width - x)
height = min(height, self.height - y)
return x, y, width, height
|
[
"def",
"_normalizeRect",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
":",
"x",
",",
"y",
"=",
"self",
".",
"_normalizePoint",
"(",
"x",
",",
"y",
")",
"# inherit _normalizePoint logic",
"assert",
"width",
"is",
"None",
"or",
"isinstance",
"(",
"width",
",",
"_INTTYPES",
")",
",",
"'width must be an integer or None, got %s'",
"%",
"repr",
"(",
"width",
")",
"assert",
"height",
"is",
"None",
"or",
"isinstance",
"(",
"height",
",",
"_INTTYPES",
")",
",",
"'height must be an integer or None, got %s'",
"%",
"repr",
"(",
"height",
")",
"# if width or height are None then extend them to the edge",
"if",
"width",
"is",
"None",
":",
"width",
"=",
"self",
".",
"width",
"-",
"x",
"elif",
"width",
"<",
"0",
":",
"# handle negative numbers",
"width",
"+=",
"self",
".",
"width",
"width",
"=",
"max",
"(",
"0",
",",
"width",
")",
"# a 'too big' negative is clamped zero",
"if",
"height",
"is",
"None",
":",
"height",
"=",
"self",
".",
"height",
"-",
"y",
"height",
"=",
"max",
"(",
"0",
",",
"height",
")",
"elif",
"height",
"<",
"0",
":",
"height",
"+=",
"self",
".",
"height",
"# reduce rect size to bounds",
"width",
"=",
"min",
"(",
"width",
",",
"self",
".",
"width",
"-",
"x",
")",
"height",
"=",
"min",
"(",
"height",
",",
"self",
".",
"height",
"-",
"y",
")",
"return",
"x",
",",
"y",
",",
"width",
",",
"height"
] |
Check if the rectangle is in bounds and make minor adjustments.
raise AssertionError's for any problems
|
[
"Check",
"if",
"the",
"rectangle",
"is",
"in",
"bounds",
"and",
"make",
"minor",
"adjustments",
".",
"raise",
"AssertionError",
"s",
"for",
"any",
"problems"
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L225-L250
|
9,124
|
libtcod/python-tcod
|
tdl/__init__.py
|
_BaseConsole._normalizeCursor
|
def _normalizeCursor(self, x, y):
"""return the normalized the cursor position."""
width, height = self.get_size()
assert width != 0 and height != 0, 'can not print on a console with a width or height of zero'
while x >= width:
x -= width
y += 1
while y >= height:
if self._scrollMode == 'scroll':
y -= 1
self.scroll(0, -1)
elif self._scrollMode == 'error':
# reset the cursor on error
self._cursor = (0, 0)
raise TDLError('Cursor has reached the end of the console')
return (x, y)
|
python
|
def _normalizeCursor(self, x, y):
"""return the normalized the cursor position."""
width, height = self.get_size()
assert width != 0 and height != 0, 'can not print on a console with a width or height of zero'
while x >= width:
x -= width
y += 1
while y >= height:
if self._scrollMode == 'scroll':
y -= 1
self.scroll(0, -1)
elif self._scrollMode == 'error':
# reset the cursor on error
self._cursor = (0, 0)
raise TDLError('Cursor has reached the end of the console')
return (x, y)
|
[
"def",
"_normalizeCursor",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"width",
",",
"height",
"=",
"self",
".",
"get_size",
"(",
")",
"assert",
"width",
"!=",
"0",
"and",
"height",
"!=",
"0",
",",
"'can not print on a console with a width or height of zero'",
"while",
"x",
">=",
"width",
":",
"x",
"-=",
"width",
"y",
"+=",
"1",
"while",
"y",
">=",
"height",
":",
"if",
"self",
".",
"_scrollMode",
"==",
"'scroll'",
":",
"y",
"-=",
"1",
"self",
".",
"scroll",
"(",
"0",
",",
"-",
"1",
")",
"elif",
"self",
".",
"_scrollMode",
"==",
"'error'",
":",
"# reset the cursor on error",
"self",
".",
"_cursor",
"=",
"(",
"0",
",",
"0",
")",
"raise",
"TDLError",
"(",
"'Cursor has reached the end of the console'",
")",
"return",
"(",
"x",
",",
"y",
")"
] |
return the normalized the cursor position.
|
[
"return",
"the",
"normalized",
"the",
"cursor",
"position",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L252-L267
|
9,125
|
libtcod/python-tcod
|
tdl/__init__.py
|
_BaseConsole.set_mode
|
def set_mode(self, mode):
"""Configure how this console will react to the cursor writing past the
end if the console.
This is for methods that use the virtual cursor, such as
:any:`print_str`.
Args:
mode (Text): The mode to set.
Possible settings are:
- 'error' - A TDLError will be raised once the cursor
reaches the end of the console. Everything up until
the error will still be drawn.
This is the default setting.
- 'scroll' - The console will scroll up as stuff is
written to the end.
You can restrict the region with :any:`tdl.Window` when
doing this.
..seealso:: :any:`write`, :any:`print_str`
"""
MODES = ['error', 'scroll']
if mode.lower() not in MODES:
raise TDLError('mode must be one of %s, got %s' % (MODES, repr(mode)))
self._scrollMode = mode.lower()
|
python
|
def set_mode(self, mode):
"""Configure how this console will react to the cursor writing past the
end if the console.
This is for methods that use the virtual cursor, such as
:any:`print_str`.
Args:
mode (Text): The mode to set.
Possible settings are:
- 'error' - A TDLError will be raised once the cursor
reaches the end of the console. Everything up until
the error will still be drawn.
This is the default setting.
- 'scroll' - The console will scroll up as stuff is
written to the end.
You can restrict the region with :any:`tdl.Window` when
doing this.
..seealso:: :any:`write`, :any:`print_str`
"""
MODES = ['error', 'scroll']
if mode.lower() not in MODES:
raise TDLError('mode must be one of %s, got %s' % (MODES, repr(mode)))
self._scrollMode = mode.lower()
|
[
"def",
"set_mode",
"(",
"self",
",",
"mode",
")",
":",
"MODES",
"=",
"[",
"'error'",
",",
"'scroll'",
"]",
"if",
"mode",
".",
"lower",
"(",
")",
"not",
"in",
"MODES",
":",
"raise",
"TDLError",
"(",
"'mode must be one of %s, got %s'",
"%",
"(",
"MODES",
",",
"repr",
"(",
"mode",
")",
")",
")",
"self",
".",
"_scrollMode",
"=",
"mode",
".",
"lower",
"(",
")"
] |
Configure how this console will react to the cursor writing past the
end if the console.
This is for methods that use the virtual cursor, such as
:any:`print_str`.
Args:
mode (Text): The mode to set.
Possible settings are:
- 'error' - A TDLError will be raised once the cursor
reaches the end of the console. Everything up until
the error will still be drawn.
This is the default setting.
- 'scroll' - The console will scroll up as stuff is
written to the end.
You can restrict the region with :any:`tdl.Window` when
doing this.
..seealso:: :any:`write`, :any:`print_str`
|
[
"Configure",
"how",
"this",
"console",
"will",
"react",
"to",
"the",
"cursor",
"writing",
"past",
"the",
"end",
"if",
"the",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L269-L295
|
9,126
|
libtcod/python-tcod
|
tdl/__init__.py
|
_BaseConsole.print_str
|
def print_str(self, string):
"""Print a string at the virtual cursor.
Handles special characters such as '\\n' and '\\r'.
Printing past the bottom of the console will scroll everything upwards
if :any:`set_mode` is set to 'scroll'.
Colors can be set with :any:`set_colors` and the virtual cursor can
be moved with :any:`move`.
Args:
string (Text): The text to print.
.. seealso:: :any:`draw_str`, :any:`move`, :any:`set_colors`,
:any:`set_mode`, :any:`write`, :any:`Window`
"""
x, y = self._cursor
for char in string:
if char == '\n': # line break
x = 0
y += 1
continue
if char == '\r': # return
x = 0
continue
x, y = self._normalizeCursor(x, y)
self.draw_char(x, y, char, self._fg, self._bg)
x += 1
self._cursor = (x, y)
|
python
|
def print_str(self, string):
"""Print a string at the virtual cursor.
Handles special characters such as '\\n' and '\\r'.
Printing past the bottom of the console will scroll everything upwards
if :any:`set_mode` is set to 'scroll'.
Colors can be set with :any:`set_colors` and the virtual cursor can
be moved with :any:`move`.
Args:
string (Text): The text to print.
.. seealso:: :any:`draw_str`, :any:`move`, :any:`set_colors`,
:any:`set_mode`, :any:`write`, :any:`Window`
"""
x, y = self._cursor
for char in string:
if char == '\n': # line break
x = 0
y += 1
continue
if char == '\r': # return
x = 0
continue
x, y = self._normalizeCursor(x, y)
self.draw_char(x, y, char, self._fg, self._bg)
x += 1
self._cursor = (x, y)
|
[
"def",
"print_str",
"(",
"self",
",",
"string",
")",
":",
"x",
",",
"y",
"=",
"self",
".",
"_cursor",
"for",
"char",
"in",
"string",
":",
"if",
"char",
"==",
"'\\n'",
":",
"# line break",
"x",
"=",
"0",
"y",
"+=",
"1",
"continue",
"if",
"char",
"==",
"'\\r'",
":",
"# return",
"x",
"=",
"0",
"continue",
"x",
",",
"y",
"=",
"self",
".",
"_normalizeCursor",
"(",
"x",
",",
"y",
")",
"self",
".",
"draw_char",
"(",
"x",
",",
"y",
",",
"char",
",",
"self",
".",
"_fg",
",",
"self",
".",
"_bg",
")",
"x",
"+=",
"1",
"self",
".",
"_cursor",
"=",
"(",
"x",
",",
"y",
")"
] |
Print a string at the virtual cursor.
Handles special characters such as '\\n' and '\\r'.
Printing past the bottom of the console will scroll everything upwards
if :any:`set_mode` is set to 'scroll'.
Colors can be set with :any:`set_colors` and the virtual cursor can
be moved with :any:`move`.
Args:
string (Text): The text to print.
.. seealso:: :any:`draw_str`, :any:`move`, :any:`set_colors`,
:any:`set_mode`, :any:`write`, :any:`Window`
|
[
"Print",
"a",
"string",
"at",
"the",
"virtual",
"cursor",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L312-L340
|
9,127
|
libtcod/python-tcod
|
tdl/__init__.py
|
_BaseConsole.write
|
def write(self, string):
"""This method mimics basic file-like behaviour.
Because of this method you can replace sys.stdout or sys.stderr with
a :any:`Console` or :any:`Window` instance.
This is a convoluted process and behaviour seen now can be excepted to
change on later versions.
Args:
string (Text): The text to write out.
.. seealso:: :any:`set_colors`, :any:`set_mode`, :any:`Window`
"""
# some 'basic' line buffer stuff.
# there must be an easier way to do this. The textwrap module didn't
# help much.
x, y = self._normalizeCursor(*self._cursor)
width, height = self.get_size()
wrapper = _textwrap.TextWrapper(initial_indent=(' '*x), width=width)
writeLines = []
for line in string.split('\n'):
if line:
writeLines += wrapper.wrap(line)
wrapper.initial_indent = ''
else:
writeLines.append([])
for line in writeLines:
x, y = self._normalizeCursor(x, y)
self.draw_str(x, y, line[x:], self._fg, self._bg)
y += 1
x = 0
y -= 1
self._cursor = (x, y)
|
python
|
def write(self, string):
"""This method mimics basic file-like behaviour.
Because of this method you can replace sys.stdout or sys.stderr with
a :any:`Console` or :any:`Window` instance.
This is a convoluted process and behaviour seen now can be excepted to
change on later versions.
Args:
string (Text): The text to write out.
.. seealso:: :any:`set_colors`, :any:`set_mode`, :any:`Window`
"""
# some 'basic' line buffer stuff.
# there must be an easier way to do this. The textwrap module didn't
# help much.
x, y = self._normalizeCursor(*self._cursor)
width, height = self.get_size()
wrapper = _textwrap.TextWrapper(initial_indent=(' '*x), width=width)
writeLines = []
for line in string.split('\n'):
if line:
writeLines += wrapper.wrap(line)
wrapper.initial_indent = ''
else:
writeLines.append([])
for line in writeLines:
x, y = self._normalizeCursor(x, y)
self.draw_str(x, y, line[x:], self._fg, self._bg)
y += 1
x = 0
y -= 1
self._cursor = (x, y)
|
[
"def",
"write",
"(",
"self",
",",
"string",
")",
":",
"# some 'basic' line buffer stuff.",
"# there must be an easier way to do this. The textwrap module didn't",
"# help much.",
"x",
",",
"y",
"=",
"self",
".",
"_normalizeCursor",
"(",
"*",
"self",
".",
"_cursor",
")",
"width",
",",
"height",
"=",
"self",
".",
"get_size",
"(",
")",
"wrapper",
"=",
"_textwrap",
".",
"TextWrapper",
"(",
"initial_indent",
"=",
"(",
"' '",
"*",
"x",
")",
",",
"width",
"=",
"width",
")",
"writeLines",
"=",
"[",
"]",
"for",
"line",
"in",
"string",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"line",
":",
"writeLines",
"+=",
"wrapper",
".",
"wrap",
"(",
"line",
")",
"wrapper",
".",
"initial_indent",
"=",
"''",
"else",
":",
"writeLines",
".",
"append",
"(",
"[",
"]",
")",
"for",
"line",
"in",
"writeLines",
":",
"x",
",",
"y",
"=",
"self",
".",
"_normalizeCursor",
"(",
"x",
",",
"y",
")",
"self",
".",
"draw_str",
"(",
"x",
",",
"y",
",",
"line",
"[",
"x",
":",
"]",
",",
"self",
".",
"_fg",
",",
"self",
".",
"_bg",
")",
"y",
"+=",
"1",
"x",
"=",
"0",
"y",
"-=",
"1",
"self",
".",
"_cursor",
"=",
"(",
"x",
",",
"y",
")"
] |
This method mimics basic file-like behaviour.
Because of this method you can replace sys.stdout or sys.stderr with
a :any:`Console` or :any:`Window` instance.
This is a convoluted process and behaviour seen now can be excepted to
change on later versions.
Args:
string (Text): The text to write out.
.. seealso:: :any:`set_colors`, :any:`set_mode`, :any:`Window`
|
[
"This",
"method",
"mimics",
"basic",
"file",
"-",
"like",
"behaviour",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L342-L376
|
9,128
|
libtcod/python-tcod
|
tdl/__init__.py
|
_BaseConsole.draw_char
|
def draw_char(self, x, y, char, fg=Ellipsis, bg=Ellipsis):
"""Draws a single character.
Args:
x (int): x-coordinate to draw on.
y (int): y-coordinate to draw on.
char (Optional[Union[int, Text]]): An integer, single character
string, or None.
You can set the char parameter as None if you only want to change
the colors of the tile.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises: AssertionError: Having x or y values that can't be placed
inside of the console will raise an AssertionError.
You can use always use ((x, y) in console) to
check if a tile is drawable.
.. seealso:: :any:`get_char`
"""
#x, y = self._normalizePoint(x, y)
_put_char_ex(self.console_c, x, y, _format_char(char),
_format_color(fg, self._fg), _format_color(bg, self._bg), 1)
|
python
|
def draw_char(self, x, y, char, fg=Ellipsis, bg=Ellipsis):
"""Draws a single character.
Args:
x (int): x-coordinate to draw on.
y (int): y-coordinate to draw on.
char (Optional[Union[int, Text]]): An integer, single character
string, or None.
You can set the char parameter as None if you only want to change
the colors of the tile.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises: AssertionError: Having x or y values that can't be placed
inside of the console will raise an AssertionError.
You can use always use ((x, y) in console) to
check if a tile is drawable.
.. seealso:: :any:`get_char`
"""
#x, y = self._normalizePoint(x, y)
_put_char_ex(self.console_c, x, y, _format_char(char),
_format_color(fg, self._fg), _format_color(bg, self._bg), 1)
|
[
"def",
"draw_char",
"(",
"self",
",",
"x",
",",
"y",
",",
"char",
",",
"fg",
"=",
"Ellipsis",
",",
"bg",
"=",
"Ellipsis",
")",
":",
"#x, y = self._normalizePoint(x, y)",
"_put_char_ex",
"(",
"self",
".",
"console_c",
",",
"x",
",",
"y",
",",
"_format_char",
"(",
"char",
")",
",",
"_format_color",
"(",
"fg",
",",
"self",
".",
"_fg",
")",
",",
"_format_color",
"(",
"bg",
",",
"self",
".",
"_bg",
")",
",",
"1",
")"
] |
Draws a single character.
Args:
x (int): x-coordinate to draw on.
y (int): y-coordinate to draw on.
char (Optional[Union[int, Text]]): An integer, single character
string, or None.
You can set the char parameter as None if you only want to change
the colors of the tile.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises: AssertionError: Having x or y values that can't be placed
inside of the console will raise an AssertionError.
You can use always use ((x, y) in console) to
check if a tile is drawable.
.. seealso:: :any:`get_char`
|
[
"Draws",
"a",
"single",
"character",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L378-L401
|
9,129
|
libtcod/python-tcod
|
tdl/__init__.py
|
_BaseConsole.draw_str
|
def draw_str(self, x, y, string, fg=Ellipsis, bg=Ellipsis):
"""Draws a string starting at x and y.
A string that goes past the right side will wrap around. A string
wrapping to below the console will raise :any:`tdl.TDLError` but will
still be written out.
This means you can safely ignore the errors with a
try..except block if you're fine with partially written strings.
\\r and \\n are drawn on the console as normal character tiles. No
special encoding is done and any string will translate to the character
table as is.
For a string drawing operation that respects special characters see
:any:`print_str`.
Args:
x (int): x-coordinate to start at.
y (int): y-coordinate to start at.
string (Union[Text, Iterable[int]]): A string or an iterable of
numbers.
Special characters are ignored and rendered as any other
character.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if
a tile is drawable.
.. seealso:: :any:`print_str`
"""
x, y = self._normalizePoint(x, y)
fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)
width, height = self.get_size()
def _drawStrGen(x=x, y=y, string=string, width=width, height=height):
"""Generator for draw_str
Iterates over ((x, y), ch) data for _set_batch, raising an
error if the end of the console is reached.
"""
for char in _format_str(string):
if y == height:
raise TDLError('End of console reached.')
yield((x, y), char)
x += 1 # advance cursor
if x == width: # line break
x = 0
y += 1
self._set_batch(_drawStrGen(), fg, bg)
|
python
|
def draw_str(self, x, y, string, fg=Ellipsis, bg=Ellipsis):
"""Draws a string starting at x and y.
A string that goes past the right side will wrap around. A string
wrapping to below the console will raise :any:`tdl.TDLError` but will
still be written out.
This means you can safely ignore the errors with a
try..except block if you're fine with partially written strings.
\\r and \\n are drawn on the console as normal character tiles. No
special encoding is done and any string will translate to the character
table as is.
For a string drawing operation that respects special characters see
:any:`print_str`.
Args:
x (int): x-coordinate to start at.
y (int): y-coordinate to start at.
string (Union[Text, Iterable[int]]): A string or an iterable of
numbers.
Special characters are ignored and rendered as any other
character.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if
a tile is drawable.
.. seealso:: :any:`print_str`
"""
x, y = self._normalizePoint(x, y)
fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)
width, height = self.get_size()
def _drawStrGen(x=x, y=y, string=string, width=width, height=height):
"""Generator for draw_str
Iterates over ((x, y), ch) data for _set_batch, raising an
error if the end of the console is reached.
"""
for char in _format_str(string):
if y == height:
raise TDLError('End of console reached.')
yield((x, y), char)
x += 1 # advance cursor
if x == width: # line break
x = 0
y += 1
self._set_batch(_drawStrGen(), fg, bg)
|
[
"def",
"draw_str",
"(",
"self",
",",
"x",
",",
"y",
",",
"string",
",",
"fg",
"=",
"Ellipsis",
",",
"bg",
"=",
"Ellipsis",
")",
":",
"x",
",",
"y",
"=",
"self",
".",
"_normalizePoint",
"(",
"x",
",",
"y",
")",
"fg",
",",
"bg",
"=",
"_format_color",
"(",
"fg",
",",
"self",
".",
"_fg",
")",
",",
"_format_color",
"(",
"bg",
",",
"self",
".",
"_bg",
")",
"width",
",",
"height",
"=",
"self",
".",
"get_size",
"(",
")",
"def",
"_drawStrGen",
"(",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"string",
"=",
"string",
",",
"width",
"=",
"width",
",",
"height",
"=",
"height",
")",
":",
"\"\"\"Generator for draw_str\n\n Iterates over ((x, y), ch) data for _set_batch, raising an\n error if the end of the console is reached.\n \"\"\"",
"for",
"char",
"in",
"_format_str",
"(",
"string",
")",
":",
"if",
"y",
"==",
"height",
":",
"raise",
"TDLError",
"(",
"'End of console reached.'",
")",
"yield",
"(",
"(",
"x",
",",
"y",
")",
",",
"char",
")",
"x",
"+=",
"1",
"# advance cursor",
"if",
"x",
"==",
"width",
":",
"# line break",
"x",
"=",
"0",
"y",
"+=",
"1",
"self",
".",
"_set_batch",
"(",
"_drawStrGen",
"(",
")",
",",
"fg",
",",
"bg",
")"
] |
Draws a string starting at x and y.
A string that goes past the right side will wrap around. A string
wrapping to below the console will raise :any:`tdl.TDLError` but will
still be written out.
This means you can safely ignore the errors with a
try..except block if you're fine with partially written strings.
\\r and \\n are drawn on the console as normal character tiles. No
special encoding is done and any string will translate to the character
table as is.
For a string drawing operation that respects special characters see
:any:`print_str`.
Args:
x (int): x-coordinate to start at.
y (int): y-coordinate to start at.
string (Union[Text, Iterable[int]]): A string or an iterable of
numbers.
Special characters are ignored and rendered as any other
character.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if
a tile is drawable.
.. seealso:: :any:`print_str`
|
[
"Draws",
"a",
"string",
"starting",
"at",
"x",
"and",
"y",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L403-L457
|
9,130
|
libtcod/python-tcod
|
tdl/__init__.py
|
_BaseConsole.draw_rect
|
def draw_rect(self, x, y, width, height, string, fg=Ellipsis, bg=Ellipsis):
"""Draws a rectangle starting from x and y and extending to width and height.
If width or height are None then it will extend to the edge of the console.
Args:
x (int): x-coordinate for the top side of the rect.
y (int): y-coordinate for the left side of the rect.
width (Optional[int]): The width of the rectangle.
Can be None to extend to the bottom right of the
console or can be a negative number to be sized reltive
to the total size of the console.
height (Optional[int]): The height of the rectangle.
string (Optional[Union[Text, int]]): An integer, single character
string, or None.
You can set the string parameter as None if you only want
to change the colors of an area.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if a tile
is drawable.
.. seealso:: :any:`clear`, :any:`draw_frame`
"""
x, y, width, height = self._normalizeRect(x, y, width, height)
fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)
char = _format_char(string)
# use itertools to make an x,y grid
# using ctypes here reduces type converstions later
#grid = _itertools.product((_ctypes.c_int(x) for x in range(x, x + width)),
# (_ctypes.c_int(y) for y in range(y, y + height)))
grid = _itertools.product((x for x in range(x, x + width)),
(y for y in range(y, y + height)))
# zip the single character in a batch variable
batch = zip(grid, _itertools.repeat(char, width * height))
self._set_batch(batch, fg, bg, nullChar=(char is None))
|
python
|
def draw_rect(self, x, y, width, height, string, fg=Ellipsis, bg=Ellipsis):
"""Draws a rectangle starting from x and y and extending to width and height.
If width or height are None then it will extend to the edge of the console.
Args:
x (int): x-coordinate for the top side of the rect.
y (int): y-coordinate for the left side of the rect.
width (Optional[int]): The width of the rectangle.
Can be None to extend to the bottom right of the
console or can be a negative number to be sized reltive
to the total size of the console.
height (Optional[int]): The height of the rectangle.
string (Optional[Union[Text, int]]): An integer, single character
string, or None.
You can set the string parameter as None if you only want
to change the colors of an area.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if a tile
is drawable.
.. seealso:: :any:`clear`, :any:`draw_frame`
"""
x, y, width, height = self._normalizeRect(x, y, width, height)
fg, bg = _format_color(fg, self._fg), _format_color(bg, self._bg)
char = _format_char(string)
# use itertools to make an x,y grid
# using ctypes here reduces type converstions later
#grid = _itertools.product((_ctypes.c_int(x) for x in range(x, x + width)),
# (_ctypes.c_int(y) for y in range(y, y + height)))
grid = _itertools.product((x for x in range(x, x + width)),
(y for y in range(y, y + height)))
# zip the single character in a batch variable
batch = zip(grid, _itertools.repeat(char, width * height))
self._set_batch(batch, fg, bg, nullChar=(char is None))
|
[
"def",
"draw_rect",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"string",
",",
"fg",
"=",
"Ellipsis",
",",
"bg",
"=",
"Ellipsis",
")",
":",
"x",
",",
"y",
",",
"width",
",",
"height",
"=",
"self",
".",
"_normalizeRect",
"(",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
"fg",
",",
"bg",
"=",
"_format_color",
"(",
"fg",
",",
"self",
".",
"_fg",
")",
",",
"_format_color",
"(",
"bg",
",",
"self",
".",
"_bg",
")",
"char",
"=",
"_format_char",
"(",
"string",
")",
"# use itertools to make an x,y grid",
"# using ctypes here reduces type converstions later",
"#grid = _itertools.product((_ctypes.c_int(x) for x in range(x, x + width)),",
"# (_ctypes.c_int(y) for y in range(y, y + height)))",
"grid",
"=",
"_itertools",
".",
"product",
"(",
"(",
"x",
"for",
"x",
"in",
"range",
"(",
"x",
",",
"x",
"+",
"width",
")",
")",
",",
"(",
"y",
"for",
"y",
"in",
"range",
"(",
"y",
",",
"y",
"+",
"height",
")",
")",
")",
"# zip the single character in a batch variable",
"batch",
"=",
"zip",
"(",
"grid",
",",
"_itertools",
".",
"repeat",
"(",
"char",
",",
"width",
"*",
"height",
")",
")",
"self",
".",
"_set_batch",
"(",
"batch",
",",
"fg",
",",
"bg",
",",
"nullChar",
"=",
"(",
"char",
"is",
"None",
")",
")"
] |
Draws a rectangle starting from x and y and extending to width and height.
If width or height are None then it will extend to the edge of the console.
Args:
x (int): x-coordinate for the top side of the rect.
y (int): y-coordinate for the left side of the rect.
width (Optional[int]): The width of the rectangle.
Can be None to extend to the bottom right of the
console or can be a negative number to be sized reltive
to the total size of the console.
height (Optional[int]): The height of the rectangle.
string (Optional[Union[Text, int]]): An integer, single character
string, or None.
You can set the string parameter as None if you only want
to change the colors of an area.
fg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
bg (Optional[Union[Tuple[int, int, int], int, Ellipsis]])
Raises:
AssertionError: Having x or y values that can't be placed inside
of the console will raise an AssertionError.
You can use always use ``((x, y) in console)`` to check if a tile
is drawable.
.. seealso:: :any:`clear`, :any:`draw_frame`
|
[
"Draws",
"a",
"rectangle",
"starting",
"from",
"x",
"and",
"y",
"and",
"extending",
"to",
"width",
"and",
"height",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L459-L500
|
9,131
|
libtcod/python-tcod
|
tdl/__init__.py
|
_BaseConsole.blit
|
def blit(self, source, x=0, y=0, width=None, height=None, srcX=0, srcY=0,
fg_alpha=1.0, bg_alpha=1.0):
"""Blit another console or Window onto the current console.
By default it blits the entire source to the topleft corner.
Args:
source (Union[tdl.Console, tdl.Window]): The blitting source.
A console can blit to itself without any problems.
x (int): x-coordinate of this console to blit on.
y (int): y-coordinate of this console to blit on.
width (Optional[int]): Width of the rectangle.
Can be None to extend as far as possible to the
bottom right corner of the blit area or can be a negative
number to be sized reltive to the total size of the
B{destination} console.
height (Optional[int]): Height of the rectangle.
srcX (int): x-coordinate of the source region to blit.
srcY (int): y-coordinate of the source region to blit.
fg_alpha (float): The foreground alpha.
"""
assert isinstance(source, (Console, Window)), "source muse be a Window or Console instance"
# handle negative indexes and rects
# negative width and height will be set realtive to the destination
# and will also be clamped to the smallest Console
x, y, width, height = self._normalizeRect(x, y, width, height)
srcX, srcY, width, height = source._normalizeRect(srcX, srcY, width, height)
# translate source and self if any of them are Window instances
srcX, srcY = source._translate(srcX, srcY)
source = source.console
x, y = self._translate(x, y)
self = self.console
if self == source:
# if we are the same console then we need a third console to hold
# onto the data, otherwise it tries to copy into itself and
# starts destroying everything
tmp = Console(width, height)
_lib.TCOD_console_blit(source.console_c,
srcX, srcY, width, height,
tmp.console_c, 0, 0, fg_alpha, bg_alpha)
_lib.TCOD_console_blit(tmp.console_c, 0, 0, width, height,
self.console_c, x, y, fg_alpha, bg_alpha)
else:
_lib.TCOD_console_blit(source.console_c,
srcX, srcY, width, height,
self.console_c, x, y, fg_alpha, bg_alpha)
|
python
|
def blit(self, source, x=0, y=0, width=None, height=None, srcX=0, srcY=0,
fg_alpha=1.0, bg_alpha=1.0):
"""Blit another console or Window onto the current console.
By default it blits the entire source to the topleft corner.
Args:
source (Union[tdl.Console, tdl.Window]): The blitting source.
A console can blit to itself without any problems.
x (int): x-coordinate of this console to blit on.
y (int): y-coordinate of this console to blit on.
width (Optional[int]): Width of the rectangle.
Can be None to extend as far as possible to the
bottom right corner of the blit area or can be a negative
number to be sized reltive to the total size of the
B{destination} console.
height (Optional[int]): Height of the rectangle.
srcX (int): x-coordinate of the source region to blit.
srcY (int): y-coordinate of the source region to blit.
fg_alpha (float): The foreground alpha.
"""
assert isinstance(source, (Console, Window)), "source muse be a Window or Console instance"
# handle negative indexes and rects
# negative width and height will be set realtive to the destination
# and will also be clamped to the smallest Console
x, y, width, height = self._normalizeRect(x, y, width, height)
srcX, srcY, width, height = source._normalizeRect(srcX, srcY, width, height)
# translate source and self if any of them are Window instances
srcX, srcY = source._translate(srcX, srcY)
source = source.console
x, y = self._translate(x, y)
self = self.console
if self == source:
# if we are the same console then we need a third console to hold
# onto the data, otherwise it tries to copy into itself and
# starts destroying everything
tmp = Console(width, height)
_lib.TCOD_console_blit(source.console_c,
srcX, srcY, width, height,
tmp.console_c, 0, 0, fg_alpha, bg_alpha)
_lib.TCOD_console_blit(tmp.console_c, 0, 0, width, height,
self.console_c, x, y, fg_alpha, bg_alpha)
else:
_lib.TCOD_console_blit(source.console_c,
srcX, srcY, width, height,
self.console_c, x, y, fg_alpha, bg_alpha)
|
[
"def",
"blit",
"(",
"self",
",",
"source",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"srcX",
"=",
"0",
",",
"srcY",
"=",
"0",
",",
"fg_alpha",
"=",
"1.0",
",",
"bg_alpha",
"=",
"1.0",
")",
":",
"assert",
"isinstance",
"(",
"source",
",",
"(",
"Console",
",",
"Window",
")",
")",
",",
"\"source muse be a Window or Console instance\"",
"# handle negative indexes and rects",
"# negative width and height will be set realtive to the destination",
"# and will also be clamped to the smallest Console",
"x",
",",
"y",
",",
"width",
",",
"height",
"=",
"self",
".",
"_normalizeRect",
"(",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
"srcX",
",",
"srcY",
",",
"width",
",",
"height",
"=",
"source",
".",
"_normalizeRect",
"(",
"srcX",
",",
"srcY",
",",
"width",
",",
"height",
")",
"# translate source and self if any of them are Window instances",
"srcX",
",",
"srcY",
"=",
"source",
".",
"_translate",
"(",
"srcX",
",",
"srcY",
")",
"source",
"=",
"source",
".",
"console",
"x",
",",
"y",
"=",
"self",
".",
"_translate",
"(",
"x",
",",
"y",
")",
"self",
"=",
"self",
".",
"console",
"if",
"self",
"==",
"source",
":",
"# if we are the same console then we need a third console to hold",
"# onto the data, otherwise it tries to copy into itself and",
"# starts destroying everything",
"tmp",
"=",
"Console",
"(",
"width",
",",
"height",
")",
"_lib",
".",
"TCOD_console_blit",
"(",
"source",
".",
"console_c",
",",
"srcX",
",",
"srcY",
",",
"width",
",",
"height",
",",
"tmp",
".",
"console_c",
",",
"0",
",",
"0",
",",
"fg_alpha",
",",
"bg_alpha",
")",
"_lib",
".",
"TCOD_console_blit",
"(",
"tmp",
".",
"console_c",
",",
"0",
",",
"0",
",",
"width",
",",
"height",
",",
"self",
".",
"console_c",
",",
"x",
",",
"y",
",",
"fg_alpha",
",",
"bg_alpha",
")",
"else",
":",
"_lib",
".",
"TCOD_console_blit",
"(",
"source",
".",
"console_c",
",",
"srcX",
",",
"srcY",
",",
"width",
",",
"height",
",",
"self",
".",
"console_c",
",",
"x",
",",
"y",
",",
"fg_alpha",
",",
"bg_alpha",
")"
] |
Blit another console or Window onto the current console.
By default it blits the entire source to the topleft corner.
Args:
source (Union[tdl.Console, tdl.Window]): The blitting source.
A console can blit to itself without any problems.
x (int): x-coordinate of this console to blit on.
y (int): y-coordinate of this console to blit on.
width (Optional[int]): Width of the rectangle.
Can be None to extend as far as possible to the
bottom right corner of the blit area or can be a negative
number to be sized reltive to the total size of the
B{destination} console.
height (Optional[int]): Height of the rectangle.
srcX (int): x-coordinate of the source region to blit.
srcY (int): y-coordinate of the source region to blit.
fg_alpha (float): The foreground alpha.
|
[
"Blit",
"another",
"console",
"or",
"Window",
"onto",
"the",
"current",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L542-L591
|
9,132
|
libtcod/python-tcod
|
tdl/__init__.py
|
_BaseConsole.get_cursor
|
def get_cursor(self):
"""Return the virtual cursor position.
The cursor can be moved with the :any:`move` method.
Returns:
Tuple[int, int]: The (x, y) coordinate of where :any:`print_str`
will continue from.
.. seealso:: :any:move`
"""
x, y = self._cursor
width, height = self.parent.get_size()
while x >= width:
x -= width
y += 1
if y >= height and self.scrollMode == 'scroll':
y = height - 1
return x, y
|
python
|
def get_cursor(self):
"""Return the virtual cursor position.
The cursor can be moved with the :any:`move` method.
Returns:
Tuple[int, int]: The (x, y) coordinate of where :any:`print_str`
will continue from.
.. seealso:: :any:move`
"""
x, y = self._cursor
width, height = self.parent.get_size()
while x >= width:
x -= width
y += 1
if y >= height and self.scrollMode == 'scroll':
y = height - 1
return x, y
|
[
"def",
"get_cursor",
"(",
"self",
")",
":",
"x",
",",
"y",
"=",
"self",
".",
"_cursor",
"width",
",",
"height",
"=",
"self",
".",
"parent",
".",
"get_size",
"(",
")",
"while",
"x",
">=",
"width",
":",
"x",
"-=",
"width",
"y",
"+=",
"1",
"if",
"y",
">=",
"height",
"and",
"self",
".",
"scrollMode",
"==",
"'scroll'",
":",
"y",
"=",
"height",
"-",
"1",
"return",
"x",
",",
"y"
] |
Return the virtual cursor position.
The cursor can be moved with the :any:`move` method.
Returns:
Tuple[int, int]: The (x, y) coordinate of where :any:`print_str`
will continue from.
.. seealso:: :any:move`
|
[
"Return",
"the",
"virtual",
"cursor",
"position",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L593-L611
|
9,133
|
libtcod/python-tcod
|
tdl/__init__.py
|
_BaseConsole.move
|
def move(self, x, y):
"""Move the virtual cursor.
Args:
x (int): x-coordinate to place the cursor.
y (int): y-coordinate to place the cursor.
.. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write`
"""
self._cursor = self._normalizePoint(x, y)
|
python
|
def move(self, x, y):
"""Move the virtual cursor.
Args:
x (int): x-coordinate to place the cursor.
y (int): y-coordinate to place the cursor.
.. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write`
"""
self._cursor = self._normalizePoint(x, y)
|
[
"def",
"move",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"_cursor",
"=",
"self",
".",
"_normalizePoint",
"(",
"x",
",",
"y",
")"
] |
Move the virtual cursor.
Args:
x (int): x-coordinate to place the cursor.
y (int): y-coordinate to place the cursor.
.. seealso:: :any:`get_cursor`, :any:`print_str`, :any:`write`
|
[
"Move",
"the",
"virtual",
"cursor",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L632-L641
|
9,134
|
libtcod/python-tcod
|
tdl/__init__.py
|
_BaseConsole.scroll
|
def scroll(self, x, y):
"""Scroll the contents of the console in the direction of x,y.
Uncovered areas will be cleared to the default background color.
Does not move the virutal cursor.
Args:
x (int): Distance to scroll along the x-axis.
y (int): Distance to scroll along the y-axis.
Returns:
Iterator[Tuple[int, int]]: An iterator over the (x, y) coordinates
of any tile uncovered after scrolling.
.. seealso:: :any:`set_colors`
"""
assert isinstance(x, _INTTYPES), "x must be an integer, got %s" % repr(x)
assert isinstance(y, _INTTYPES), "y must be an integer, got %s" % repr(x)
def getSlide(x, length):
"""get the parameters needed to scroll the console in the given
direction with x
returns (x, length, srcx)
"""
if x > 0:
srcx = 0
length -= x
elif x < 0:
srcx = abs(x)
x = 0
length -= srcx
else:
srcx = 0
return x, length, srcx
def getCover(x, length):
"""return the (x, width) ranges of what is covered and uncovered"""
cover = (0, length) # everything covered
uncover = None # nothing uncovered
if x > 0: # left side uncovered
cover = (x, length - x)
uncover = (0, x)
elif x < 0: # right side uncovered
x = abs(x)
cover = (0, length - x)
uncover = (length - x, x)
return cover, uncover
width, height = self.get_size()
if abs(x) >= width or abs(y) >= height:
return self.clear() # just clear the console normally
# get the ranges of the areas that will be uncovered
coverX, uncoverX = getCover(x, width)
coverY, uncoverY = getCover(y, height)
# so at this point we know that coverX and coverY makes a rect that
# encases the area that we end up blitting to. uncoverX/Y makes a
# rect in the corner of the uncovered area. So we need to combine
# the uncoverX/Y with coverY/X to make what's left of the uncovered
# area. Explaining it makes it mush easier to do now.
# But first we need to blit.
x, width, srcx = getSlide(x, width)
y, height, srcy = getSlide(y, height)
self.blit(self, x, y, width, height, srcx, srcy)
if uncoverX: # clear sides (0x20 is space)
self.draw_rect(uncoverX[0], coverY[0], uncoverX[1], coverY[1],
0x20, self._fg, self._bg)
if uncoverY: # clear top/bottom
self.draw_rect(coverX[0], uncoverY[0], coverX[1], uncoverY[1],
0x20, self._fg, self._bg)
if uncoverX and uncoverY: # clear corner
self.draw_rect(uncoverX[0], uncoverY[0], uncoverX[1], uncoverY[1],
0x20, self._fg, self._bg)
|
python
|
def scroll(self, x, y):
"""Scroll the contents of the console in the direction of x,y.
Uncovered areas will be cleared to the default background color.
Does not move the virutal cursor.
Args:
x (int): Distance to scroll along the x-axis.
y (int): Distance to scroll along the y-axis.
Returns:
Iterator[Tuple[int, int]]: An iterator over the (x, y) coordinates
of any tile uncovered after scrolling.
.. seealso:: :any:`set_colors`
"""
assert isinstance(x, _INTTYPES), "x must be an integer, got %s" % repr(x)
assert isinstance(y, _INTTYPES), "y must be an integer, got %s" % repr(x)
def getSlide(x, length):
"""get the parameters needed to scroll the console in the given
direction with x
returns (x, length, srcx)
"""
if x > 0:
srcx = 0
length -= x
elif x < 0:
srcx = abs(x)
x = 0
length -= srcx
else:
srcx = 0
return x, length, srcx
def getCover(x, length):
"""return the (x, width) ranges of what is covered and uncovered"""
cover = (0, length) # everything covered
uncover = None # nothing uncovered
if x > 0: # left side uncovered
cover = (x, length - x)
uncover = (0, x)
elif x < 0: # right side uncovered
x = abs(x)
cover = (0, length - x)
uncover = (length - x, x)
return cover, uncover
width, height = self.get_size()
if abs(x) >= width or abs(y) >= height:
return self.clear() # just clear the console normally
# get the ranges of the areas that will be uncovered
coverX, uncoverX = getCover(x, width)
coverY, uncoverY = getCover(y, height)
# so at this point we know that coverX and coverY makes a rect that
# encases the area that we end up blitting to. uncoverX/Y makes a
# rect in the corner of the uncovered area. So we need to combine
# the uncoverX/Y with coverY/X to make what's left of the uncovered
# area. Explaining it makes it mush easier to do now.
# But first we need to blit.
x, width, srcx = getSlide(x, width)
y, height, srcy = getSlide(y, height)
self.blit(self, x, y, width, height, srcx, srcy)
if uncoverX: # clear sides (0x20 is space)
self.draw_rect(uncoverX[0], coverY[0], uncoverX[1], coverY[1],
0x20, self._fg, self._bg)
if uncoverY: # clear top/bottom
self.draw_rect(coverX[0], uncoverY[0], coverX[1], uncoverY[1],
0x20, self._fg, self._bg)
if uncoverX and uncoverY: # clear corner
self.draw_rect(uncoverX[0], uncoverY[0], uncoverX[1], uncoverY[1],
0x20, self._fg, self._bg)
|
[
"def",
"scroll",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"assert",
"isinstance",
"(",
"x",
",",
"_INTTYPES",
")",
",",
"\"x must be an integer, got %s\"",
"%",
"repr",
"(",
"x",
")",
"assert",
"isinstance",
"(",
"y",
",",
"_INTTYPES",
")",
",",
"\"y must be an integer, got %s\"",
"%",
"repr",
"(",
"x",
")",
"def",
"getSlide",
"(",
"x",
",",
"length",
")",
":",
"\"\"\"get the parameters needed to scroll the console in the given\n direction with x\n returns (x, length, srcx)\n \"\"\"",
"if",
"x",
">",
"0",
":",
"srcx",
"=",
"0",
"length",
"-=",
"x",
"elif",
"x",
"<",
"0",
":",
"srcx",
"=",
"abs",
"(",
"x",
")",
"x",
"=",
"0",
"length",
"-=",
"srcx",
"else",
":",
"srcx",
"=",
"0",
"return",
"x",
",",
"length",
",",
"srcx",
"def",
"getCover",
"(",
"x",
",",
"length",
")",
":",
"\"\"\"return the (x, width) ranges of what is covered and uncovered\"\"\"",
"cover",
"=",
"(",
"0",
",",
"length",
")",
"# everything covered",
"uncover",
"=",
"None",
"# nothing uncovered",
"if",
"x",
">",
"0",
":",
"# left side uncovered",
"cover",
"=",
"(",
"x",
",",
"length",
"-",
"x",
")",
"uncover",
"=",
"(",
"0",
",",
"x",
")",
"elif",
"x",
"<",
"0",
":",
"# right side uncovered",
"x",
"=",
"abs",
"(",
"x",
")",
"cover",
"=",
"(",
"0",
",",
"length",
"-",
"x",
")",
"uncover",
"=",
"(",
"length",
"-",
"x",
",",
"x",
")",
"return",
"cover",
",",
"uncover",
"width",
",",
"height",
"=",
"self",
".",
"get_size",
"(",
")",
"if",
"abs",
"(",
"x",
")",
">=",
"width",
"or",
"abs",
"(",
"y",
")",
">=",
"height",
":",
"return",
"self",
".",
"clear",
"(",
")",
"# just clear the console normally",
"# get the ranges of the areas that will be uncovered",
"coverX",
",",
"uncoverX",
"=",
"getCover",
"(",
"x",
",",
"width",
")",
"coverY",
",",
"uncoverY",
"=",
"getCover",
"(",
"y",
",",
"height",
")",
"# so at this point we know that coverX and coverY makes a rect that",
"# encases the area that we end up blitting to. uncoverX/Y makes a",
"# rect in the corner of the uncovered area. So we need to combine",
"# the uncoverX/Y with coverY/X to make what's left of the uncovered",
"# area. Explaining it makes it mush easier to do now.",
"# But first we need to blit.",
"x",
",",
"width",
",",
"srcx",
"=",
"getSlide",
"(",
"x",
",",
"width",
")",
"y",
",",
"height",
",",
"srcy",
"=",
"getSlide",
"(",
"y",
",",
"height",
")",
"self",
".",
"blit",
"(",
"self",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"srcx",
",",
"srcy",
")",
"if",
"uncoverX",
":",
"# clear sides (0x20 is space)",
"self",
".",
"draw_rect",
"(",
"uncoverX",
"[",
"0",
"]",
",",
"coverY",
"[",
"0",
"]",
",",
"uncoverX",
"[",
"1",
"]",
",",
"coverY",
"[",
"1",
"]",
",",
"0x20",
",",
"self",
".",
"_fg",
",",
"self",
".",
"_bg",
")",
"if",
"uncoverY",
":",
"# clear top/bottom",
"self",
".",
"draw_rect",
"(",
"coverX",
"[",
"0",
"]",
",",
"uncoverY",
"[",
"0",
"]",
",",
"coverX",
"[",
"1",
"]",
",",
"uncoverY",
"[",
"1",
"]",
",",
"0x20",
",",
"self",
".",
"_fg",
",",
"self",
".",
"_bg",
")",
"if",
"uncoverX",
"and",
"uncoverY",
":",
"# clear corner",
"self",
".",
"draw_rect",
"(",
"uncoverX",
"[",
"0",
"]",
",",
"uncoverY",
"[",
"0",
"]",
",",
"uncoverX",
"[",
"1",
"]",
",",
"uncoverY",
"[",
"1",
"]",
",",
"0x20",
",",
"self",
".",
"_fg",
",",
"self",
".",
"_bg",
")"
] |
Scroll the contents of the console in the direction of x,y.
Uncovered areas will be cleared to the default background color.
Does not move the virutal cursor.
Args:
x (int): Distance to scroll along the x-axis.
y (int): Distance to scroll along the y-axis.
Returns:
Iterator[Tuple[int, int]]: An iterator over the (x, y) coordinates
of any tile uncovered after scrolling.
.. seealso:: :any:`set_colors`
|
[
"Scroll",
"the",
"contents",
"of",
"the",
"console",
"in",
"the",
"direction",
"of",
"x",
"y",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L643-L714
|
9,135
|
libtcod/python-tcod
|
tdl/__init__.py
|
Console._newConsole
|
def _newConsole(cls, console):
"""Make a Console instance, from a console ctype"""
self = cls.__new__(cls)
_BaseConsole.__init__(self)
self.console_c = console
self.console = self
self.width = _lib.TCOD_console_get_width(console)
self.height = _lib.TCOD_console_get_height(console)
return self
|
python
|
def _newConsole(cls, console):
"""Make a Console instance, from a console ctype"""
self = cls.__new__(cls)
_BaseConsole.__init__(self)
self.console_c = console
self.console = self
self.width = _lib.TCOD_console_get_width(console)
self.height = _lib.TCOD_console_get_height(console)
return self
|
[
"def",
"_newConsole",
"(",
"cls",
",",
"console",
")",
":",
"self",
"=",
"cls",
".",
"__new__",
"(",
"cls",
")",
"_BaseConsole",
".",
"__init__",
"(",
"self",
")",
"self",
".",
"console_c",
"=",
"console",
"self",
".",
"console",
"=",
"self",
"self",
".",
"width",
"=",
"_lib",
".",
"TCOD_console_get_width",
"(",
"console",
")",
"self",
".",
"height",
"=",
"_lib",
".",
"TCOD_console_get_height",
"(",
"console",
")",
"return",
"self"
] |
Make a Console instance, from a console ctype
|
[
"Make",
"a",
"Console",
"instance",
"from",
"a",
"console",
"ctype"
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L787-L795
|
9,136
|
libtcod/python-tcod
|
tdl/__init__.py
|
Console._root_unhook
|
def _root_unhook(self):
"""Change this root console into a normal Console object and
delete the root console from TCOD
"""
global _rootinitialized, _rootConsoleRef
# do we recognise this as the root console?
# if not then assume the console has already been taken care of
if(_rootConsoleRef and _rootConsoleRef() is self):
# turn this console into a regular console
unhooked = _lib.TCOD_console_new(self.width, self.height)
_lib.TCOD_console_blit(self.console_c,
0, 0, self.width, self.height,
unhooked, 0, 0, 1, 1)
# delete root console from TDL and TCOD
_rootinitialized = False
_rootConsoleRef = None
_lib.TCOD_console_delete(self.console_c)
# this Console object is now a regular console
self.console_c = unhooked
|
python
|
def _root_unhook(self):
"""Change this root console into a normal Console object and
delete the root console from TCOD
"""
global _rootinitialized, _rootConsoleRef
# do we recognise this as the root console?
# if not then assume the console has already been taken care of
if(_rootConsoleRef and _rootConsoleRef() is self):
# turn this console into a regular console
unhooked = _lib.TCOD_console_new(self.width, self.height)
_lib.TCOD_console_blit(self.console_c,
0, 0, self.width, self.height,
unhooked, 0, 0, 1, 1)
# delete root console from TDL and TCOD
_rootinitialized = False
_rootConsoleRef = None
_lib.TCOD_console_delete(self.console_c)
# this Console object is now a regular console
self.console_c = unhooked
|
[
"def",
"_root_unhook",
"(",
"self",
")",
":",
"global",
"_rootinitialized",
",",
"_rootConsoleRef",
"# do we recognise this as the root console?",
"# if not then assume the console has already been taken care of",
"if",
"(",
"_rootConsoleRef",
"and",
"_rootConsoleRef",
"(",
")",
"is",
"self",
")",
":",
"# turn this console into a regular console",
"unhooked",
"=",
"_lib",
".",
"TCOD_console_new",
"(",
"self",
".",
"width",
",",
"self",
".",
"height",
")",
"_lib",
".",
"TCOD_console_blit",
"(",
"self",
".",
"console_c",
",",
"0",
",",
"0",
",",
"self",
".",
"width",
",",
"self",
".",
"height",
",",
"unhooked",
",",
"0",
",",
"0",
",",
"1",
",",
"1",
")",
"# delete root console from TDL and TCOD",
"_rootinitialized",
"=",
"False",
"_rootConsoleRef",
"=",
"None",
"_lib",
".",
"TCOD_console_delete",
"(",
"self",
".",
"console_c",
")",
"# this Console object is now a regular console",
"self",
".",
"console_c",
"=",
"unhooked"
] |
Change this root console into a normal Console object and
delete the root console from TCOD
|
[
"Change",
"this",
"root",
"console",
"into",
"a",
"normal",
"Console",
"object",
"and",
"delete",
"the",
"root",
"console",
"from",
"TCOD"
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L797-L815
|
9,137
|
libtcod/python-tcod
|
tdl/__init__.py
|
Console._set_char
|
def _set_char(self, x, y, char, fg=None, bg=None,
bgblend=_lib.TCOD_BKGND_SET):
"""
Sets a character.
This is called often and is designed to be as fast as possible.
Because of the need for speed this function will do NO TYPE CHECKING
AT ALL, it's up to the drawing functions to use the functions:
_format_char and _format_color before passing to this."""
# values are already formatted, honestly this function is redundant
return _put_char_ex(self.console_c, x, y, char, fg, bg, bgblend)
|
python
|
def _set_char(self, x, y, char, fg=None, bg=None,
bgblend=_lib.TCOD_BKGND_SET):
"""
Sets a character.
This is called often and is designed to be as fast as possible.
Because of the need for speed this function will do NO TYPE CHECKING
AT ALL, it's up to the drawing functions to use the functions:
_format_char and _format_color before passing to this."""
# values are already formatted, honestly this function is redundant
return _put_char_ex(self.console_c, x, y, char, fg, bg, bgblend)
|
[
"def",
"_set_char",
"(",
"self",
",",
"x",
",",
"y",
",",
"char",
",",
"fg",
"=",
"None",
",",
"bg",
"=",
"None",
",",
"bgblend",
"=",
"_lib",
".",
"TCOD_BKGND_SET",
")",
":",
"# values are already formatted, honestly this function is redundant",
"return",
"_put_char_ex",
"(",
"self",
".",
"console_c",
",",
"x",
",",
"y",
",",
"char",
",",
"fg",
",",
"bg",
",",
"bgblend",
")"
] |
Sets a character.
This is called often and is designed to be as fast as possible.
Because of the need for speed this function will do NO TYPE CHECKING
AT ALL, it's up to the drawing functions to use the functions:
_format_char and _format_color before passing to this.
|
[
"Sets",
"a",
"character",
".",
"This",
"is",
"called",
"often",
"and",
"is",
"designed",
"to",
"be",
"as",
"fast",
"as",
"possible",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L871-L881
|
9,138
|
libtcod/python-tcod
|
tdl/__init__.py
|
Console._set_batch
|
def _set_batch(self, batch, fg, bg, bgblend=1, nullChar=False):
"""
Try to perform a batch operation otherwise fall back to _set_char.
If fg and bg are defined then this is faster but not by very
much.
if any character is None then nullChar is True
batch is a iterable of [(x, y), ch] items
"""
for (x, y), char in batch:
self._set_char(x, y, char, fg, bg, bgblend)
|
python
|
def _set_batch(self, batch, fg, bg, bgblend=1, nullChar=False):
"""
Try to perform a batch operation otherwise fall back to _set_char.
If fg and bg are defined then this is faster but not by very
much.
if any character is None then nullChar is True
batch is a iterable of [(x, y), ch] items
"""
for (x, y), char in batch:
self._set_char(x, y, char, fg, bg, bgblend)
|
[
"def",
"_set_batch",
"(",
"self",
",",
"batch",
",",
"fg",
",",
"bg",
",",
"bgblend",
"=",
"1",
",",
"nullChar",
"=",
"False",
")",
":",
"for",
"(",
"x",
",",
"y",
")",
",",
"char",
"in",
"batch",
":",
"self",
".",
"_set_char",
"(",
"x",
",",
"y",
",",
"char",
",",
"fg",
",",
"bg",
",",
"bgblend",
")"
] |
Try to perform a batch operation otherwise fall back to _set_char.
If fg and bg are defined then this is faster but not by very
much.
if any character is None then nullChar is True
batch is a iterable of [(x, y), ch] items
|
[
"Try",
"to",
"perform",
"a",
"batch",
"operation",
"otherwise",
"fall",
"back",
"to",
"_set_char",
".",
"If",
"fg",
"and",
"bg",
"are",
"defined",
"then",
"this",
"is",
"faster",
"but",
"not",
"by",
"very",
"much",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L883-L894
|
9,139
|
libtcod/python-tcod
|
tdl/__init__.py
|
Window._translate
|
def _translate(self, x, y):
"""Convertion x and y to their position on the root Console"""
# we add our position relative to our parent and then call then next parent up
return self.parent._translate((x + self.x), (y + self.y))
|
python
|
def _translate(self, x, y):
"""Convertion x and y to their position on the root Console"""
# we add our position relative to our parent and then call then next parent up
return self.parent._translate((x + self.x), (y + self.y))
|
[
"def",
"_translate",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"# we add our position relative to our parent and then call then next parent up",
"return",
"self",
".",
"parent",
".",
"_translate",
"(",
"(",
"x",
"+",
"self",
".",
"x",
")",
",",
"(",
"y",
"+",
"self",
".",
"y",
")",
")"
] |
Convertion x and y to their position on the root Console
|
[
"Convertion",
"x",
"and",
"y",
"to",
"their",
"position",
"on",
"the",
"root",
"Console"
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/__init__.py#L948-L951
|
9,140
|
libtcod/python-tcod
|
tcod/path.py
|
_pycall_path_old
|
def _pycall_path_old(x1: int, y1: int, x2: int, y2: int, handle: Any) -> float:
"""libtcodpy style callback, needs to preserve the old userData issue."""
func, userData = ffi.from_handle(handle)
return func(x1, y1, x2, y2, userData)
|
python
|
def _pycall_path_old(x1: int, y1: int, x2: int, y2: int, handle: Any) -> float:
"""libtcodpy style callback, needs to preserve the old userData issue."""
func, userData = ffi.from_handle(handle)
return func(x1, y1, x2, y2, userData)
|
[
"def",
"_pycall_path_old",
"(",
"x1",
":",
"int",
",",
"y1",
":",
"int",
",",
"x2",
":",
"int",
",",
"y2",
":",
"int",
",",
"handle",
":",
"Any",
")",
"->",
"float",
":",
"func",
",",
"userData",
"=",
"ffi",
".",
"from_handle",
"(",
"handle",
")",
"return",
"func",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"userData",
")"
] |
libtcodpy style callback, needs to preserve the old userData issue.
|
[
"libtcodpy",
"style",
"callback",
"needs",
"to",
"preserve",
"the",
"old",
"userData",
"issue",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/path.py#L52-L55
|
9,141
|
libtcod/python-tcod
|
tcod/path.py
|
_pycall_path_simple
|
def _pycall_path_simple(
x1: int, y1: int, x2: int, y2: int, handle: Any
) -> float:
"""Does less and should run faster, just calls the handle function."""
return ffi.from_handle(handle)(x1, y1, x2, y2)
|
python
|
def _pycall_path_simple(
x1: int, y1: int, x2: int, y2: int, handle: Any
) -> float:
"""Does less and should run faster, just calls the handle function."""
return ffi.from_handle(handle)(x1, y1, x2, y2)
|
[
"def",
"_pycall_path_simple",
"(",
"x1",
":",
"int",
",",
"y1",
":",
"int",
",",
"x2",
":",
"int",
",",
"y2",
":",
"int",
",",
"handle",
":",
"Any",
")",
"->",
"float",
":",
"return",
"ffi",
".",
"from_handle",
"(",
"handle",
")",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")"
] |
Does less and should run faster, just calls the handle function.
|
[
"Does",
"less",
"and",
"should",
"run",
"faster",
"just",
"calls",
"the",
"handle",
"function",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/path.py#L59-L63
|
9,142
|
libtcod/python-tcod
|
tcod/path.py
|
_get_pathcost_func
|
def _get_pathcost_func(
name: str
) -> Callable[[int, int, int, int, Any], float]:
"""Return a properly cast PathCostArray callback."""
return ffi.cast( # type: ignore
"TCOD_path_func_t", ffi.addressof(lib, name)
)
|
python
|
def _get_pathcost_func(
name: str
) -> Callable[[int, int, int, int, Any], float]:
"""Return a properly cast PathCostArray callback."""
return ffi.cast( # type: ignore
"TCOD_path_func_t", ffi.addressof(lib, name)
)
|
[
"def",
"_get_pathcost_func",
"(",
"name",
":",
"str",
")",
"->",
"Callable",
"[",
"[",
"int",
",",
"int",
",",
"int",
",",
"int",
",",
"Any",
"]",
",",
"float",
"]",
":",
"return",
"ffi",
".",
"cast",
"(",
"# type: ignore",
"\"TCOD_path_func_t\"",
",",
"ffi",
".",
"addressof",
"(",
"lib",
",",
"name",
")",
")"
] |
Return a properly cast PathCostArray callback.
|
[
"Return",
"a",
"properly",
"cast",
"PathCostArray",
"callback",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/path.py#L82-L88
|
9,143
|
libtcod/python-tcod
|
tcod/path.py
|
Dijkstra.set_goal
|
def set_goal(self, x: int, y: int) -> None:
"""Set the goal point and recompute the Dijkstra path-finder.
"""
lib.TCOD_dijkstra_compute(self._path_c, x, y)
|
python
|
def set_goal(self, x: int, y: int) -> None:
"""Set the goal point and recompute the Dijkstra path-finder.
"""
lib.TCOD_dijkstra_compute(self._path_c, x, y)
|
[
"def",
"set_goal",
"(",
"self",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_dijkstra_compute",
"(",
"self",
".",
"_path_c",
",",
"x",
",",
"y",
")"
] |
Set the goal point and recompute the Dijkstra path-finder.
|
[
"Set",
"the",
"goal",
"point",
"and",
"recompute",
"the",
"Dijkstra",
"path",
"-",
"finder",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/path.py#L294-L297
|
9,144
|
libtcod/python-tcod
|
examples/termbox/termbox.py
|
Termbox.poll_event
|
def poll_event(self):
"""Wait for an event and return it.
Returns a tuple: (type, unicode character, key, mod, width, height,
mousex, mousey).
"""
"""
cdef tb_event e
with self._poll_lock:
with nogil:
result = tb_poll_event(&e)
assert(result >= 0)
if e.ch:
uch = unichr(e.ch)
else:
uch = None
"""
for e in tdl.event.get():
# [ ] not all events are passed thru
self.e.type = e.type
if e.type == 'KEYDOWN':
self.e.key = e.key
return self.e.gettuple()
|
python
|
def poll_event(self):
"""Wait for an event and return it.
Returns a tuple: (type, unicode character, key, mod, width, height,
mousex, mousey).
"""
"""
cdef tb_event e
with self._poll_lock:
with nogil:
result = tb_poll_event(&e)
assert(result >= 0)
if e.ch:
uch = unichr(e.ch)
else:
uch = None
"""
for e in tdl.event.get():
# [ ] not all events are passed thru
self.e.type = e.type
if e.type == 'KEYDOWN':
self.e.key = e.key
return self.e.gettuple()
|
[
"def",
"poll_event",
"(",
"self",
")",
":",
"\"\"\"\n cdef tb_event e\n with self._poll_lock:\n with nogil:\n result = tb_poll_event(&e)\n assert(result >= 0)\n if e.ch:\n uch = unichr(e.ch)\n else:\n uch = None\n \"\"\"",
"for",
"e",
"in",
"tdl",
".",
"event",
".",
"get",
"(",
")",
":",
"# [ ] not all events are passed thru",
"self",
".",
"e",
".",
"type",
"=",
"e",
".",
"type",
"if",
"e",
".",
"type",
"==",
"'KEYDOWN'",
":",
"self",
".",
"e",
".",
"key",
"=",
"e",
".",
"key",
"return",
"self",
".",
"e",
".",
"gettuple",
"(",
")"
] |
Wait for an event and return it.
Returns a tuple: (type, unicode character, key, mod, width, height,
mousex, mousey).
|
[
"Wait",
"for",
"an",
"event",
"and",
"return",
"it",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/examples/termbox/termbox.py#L271-L293
|
9,145
|
libtcod/python-tcod
|
tcod/random.py
|
Random._new_from_cdata
|
def _new_from_cdata(cls, cdata: Any) -> "Random":
"""Return a new instance encapsulating this cdata."""
self = object.__new__(cls) # type: "Random"
self.random_c = cdata
return self
|
python
|
def _new_from_cdata(cls, cdata: Any) -> "Random":
"""Return a new instance encapsulating this cdata."""
self = object.__new__(cls) # type: "Random"
self.random_c = cdata
return self
|
[
"def",
"_new_from_cdata",
"(",
"cls",
",",
"cdata",
":",
"Any",
")",
"->",
"\"Random\"",
":",
"self",
"=",
"object",
".",
"__new__",
"(",
"cls",
")",
"# type: \"Random\"",
"self",
".",
"random_c",
"=",
"cdata",
"return",
"self"
] |
Return a new instance encapsulating this cdata.
|
[
"Return",
"a",
"new",
"instance",
"encapsulating",
"this",
"cdata",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/random.py#L58-L62
|
9,146
|
libtcod/python-tcod
|
tcod/random.py
|
Random.guass
|
def guass(self, mu: float, sigma: float) -> float:
"""Return a random number using Gaussian distribution.
Args:
mu (float): The median returned value.
sigma (float): The standard deviation.
Returns:
float: A random float.
"""
return float(
lib.TCOD_random_get_gaussian_double(self.random_c, mu, sigma)
)
|
python
|
def guass(self, mu: float, sigma: float) -> float:
"""Return a random number using Gaussian distribution.
Args:
mu (float): The median returned value.
sigma (float): The standard deviation.
Returns:
float: A random float.
"""
return float(
lib.TCOD_random_get_gaussian_double(self.random_c, mu, sigma)
)
|
[
"def",
"guass",
"(",
"self",
",",
"mu",
":",
"float",
",",
"sigma",
":",
"float",
")",
"->",
"float",
":",
"return",
"float",
"(",
"lib",
".",
"TCOD_random_get_gaussian_double",
"(",
"self",
".",
"random_c",
",",
"mu",
",",
"sigma",
")",
")"
] |
Return a random number using Gaussian distribution.
Args:
mu (float): The median returned value.
sigma (float): The standard deviation.
Returns:
float: A random float.
|
[
"Return",
"a",
"random",
"number",
"using",
"Gaussian",
"distribution",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/random.py#L88-L100
|
9,147
|
libtcod/python-tcod
|
tcod/random.py
|
Random.inverse_guass
|
def inverse_guass(self, mu: float, sigma: float) -> float:
"""Return a random Gaussian number using the Box-Muller transform.
Args:
mu (float): The median returned value.
sigma (float): The standard deviation.
Returns:
float: A random float.
"""
return float(
lib.TCOD_random_get_gaussian_double_inv(self.random_c, mu, sigma)
)
|
python
|
def inverse_guass(self, mu: float, sigma: float) -> float:
"""Return a random Gaussian number using the Box-Muller transform.
Args:
mu (float): The median returned value.
sigma (float): The standard deviation.
Returns:
float: A random float.
"""
return float(
lib.TCOD_random_get_gaussian_double_inv(self.random_c, mu, sigma)
)
|
[
"def",
"inverse_guass",
"(",
"self",
",",
"mu",
":",
"float",
",",
"sigma",
":",
"float",
")",
"->",
"float",
":",
"return",
"float",
"(",
"lib",
".",
"TCOD_random_get_gaussian_double_inv",
"(",
"self",
".",
"random_c",
",",
"mu",
",",
"sigma",
")",
")"
] |
Return a random Gaussian number using the Box-Muller transform.
Args:
mu (float): The median returned value.
sigma (float): The standard deviation.
Returns:
float: A random float.
|
[
"Return",
"a",
"random",
"Gaussian",
"number",
"using",
"the",
"Box",
"-",
"Muller",
"transform",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/random.py#L102-L114
|
9,148
|
libtcod/python-tcod
|
tdl/noise.py
|
Noise.get_point
|
def get_point(self, *position):
"""Return the noise value of a specific position.
Example usage: value = noise.getPoint(x, y, z)
Args:
position (Tuple[float, ...]): The point to sample at.
Returns:
float: The noise value at position.
This will be a floating point in the 0.0-1.0 range.
"""
#array = self._array
#for d, pos in enumerate(position):
# array[d] = pos
#array = self._cFloatArray(*position)
array = _ffi.new(self._arrayType, position)
if self._useOctaves:
return (self._noiseFunc(self._noise, array, self._octaves) + 1) * 0.5
return (self._noiseFunc(self._noise, array) + 1) * 0.5
|
python
|
def get_point(self, *position):
"""Return the noise value of a specific position.
Example usage: value = noise.getPoint(x, y, z)
Args:
position (Tuple[float, ...]): The point to sample at.
Returns:
float: The noise value at position.
This will be a floating point in the 0.0-1.0 range.
"""
#array = self._array
#for d, pos in enumerate(position):
# array[d] = pos
#array = self._cFloatArray(*position)
array = _ffi.new(self._arrayType, position)
if self._useOctaves:
return (self._noiseFunc(self._noise, array, self._octaves) + 1) * 0.5
return (self._noiseFunc(self._noise, array) + 1) * 0.5
|
[
"def",
"get_point",
"(",
"self",
",",
"*",
"position",
")",
":",
"#array = self._array",
"#for d, pos in enumerate(position):",
"# array[d] = pos",
"#array = self._cFloatArray(*position)",
"array",
"=",
"_ffi",
".",
"new",
"(",
"self",
".",
"_arrayType",
",",
"position",
")",
"if",
"self",
".",
"_useOctaves",
":",
"return",
"(",
"self",
".",
"_noiseFunc",
"(",
"self",
".",
"_noise",
",",
"array",
",",
"self",
".",
"_octaves",
")",
"+",
"1",
")",
"*",
"0.5",
"return",
"(",
"self",
".",
"_noiseFunc",
"(",
"self",
".",
"_noise",
",",
"array",
")",
"+",
"1",
")",
"*",
"0.5"
] |
Return the noise value of a specific position.
Example usage: value = noise.getPoint(x, y, z)
Args:
position (Tuple[float, ...]): The point to sample at.
Returns:
float: The noise value at position.
This will be a floating point in the 0.0-1.0 range.
|
[
"Return",
"the",
"noise",
"value",
"of",
"a",
"specific",
"position",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/noise.py#L144-L164
|
9,149
|
libtcod/python-tcod
|
tcod/map.py
|
compute_fov
|
def compute_fov(
transparency: np.array,
x: int,
y: int,
radius: int = 0,
light_walls: bool = True,
algorithm: int = tcod.constants.FOV_RESTRICTIVE,
) -> np.array:
"""Return the visible area of a field-of-view computation.
`transparency` is a 2 dimensional array where all non-zero values are
considered transparent. The returned array will match the shape of this
array.
`x` and `y` are the 1st and 2nd coordinates of the origin point. Areas
are visible when they can be seen from this point-of-view.
`radius` is the maximum view distance from `x`/`y`. If this is zero then
the maximum distance is used.
If `light_walls` is True then visible obstacles will be returned, otherwise
only transparent areas will be.
`algorithm` is the field-of-view algorithm to run. The default value is
`tcod.FOV_RESTRICTIVE`.
The options are:
* `tcod.FOV_BASIC`:
Simple ray-cast implementation.
* `tcod.FOV_DIAMOND`
* `tcod.FOV_SHADOW`:
Recursive shadow caster.
* `tcod.FOV_PERMISSIVE(n)`:
`n` starts at 0 (most restrictive) and goes up to 8 (most permissive.)
* `tcod.FOV_RESTRICTIVE`
.. versionadded:: 9.3
Example::
>>> explored = np.zeros((3, 5), dtype=bool, order="F")
>>> transparency = np.ones((3, 5), dtype=bool, order="F")
>>> transparency[:2, 2] = False
>>> transparency # Transparent area.
array([[ True, True, False, True, True],
[ True, True, False, True, True],
[ True, True, True, True, True]]...)
>>> visible = tcod.map.compute_fov(transparency, 0, 0)
>>> visible # Visible area.
array([[ True, True, True, False, False],
[ True, True, True, False, False],
[ True, True, True, True, False]]...)
>>> explored |= visible # Keep track of an explored area.
"""
if len(transparency.shape) != 2:
raise TypeError(
"transparency must be an array of 2 dimensions"
" (shape is %r)" % transparency.shape
)
map_ = Map(transparency.shape[1], transparency.shape[0])
map_.transparent[...] = transparency
map_.compute_fov(x, y, radius, light_walls, algorithm)
return map_.fov
|
python
|
def compute_fov(
transparency: np.array,
x: int,
y: int,
radius: int = 0,
light_walls: bool = True,
algorithm: int = tcod.constants.FOV_RESTRICTIVE,
) -> np.array:
"""Return the visible area of a field-of-view computation.
`transparency` is a 2 dimensional array where all non-zero values are
considered transparent. The returned array will match the shape of this
array.
`x` and `y` are the 1st and 2nd coordinates of the origin point. Areas
are visible when they can be seen from this point-of-view.
`radius` is the maximum view distance from `x`/`y`. If this is zero then
the maximum distance is used.
If `light_walls` is True then visible obstacles will be returned, otherwise
only transparent areas will be.
`algorithm` is the field-of-view algorithm to run. The default value is
`tcod.FOV_RESTRICTIVE`.
The options are:
* `tcod.FOV_BASIC`:
Simple ray-cast implementation.
* `tcod.FOV_DIAMOND`
* `tcod.FOV_SHADOW`:
Recursive shadow caster.
* `tcod.FOV_PERMISSIVE(n)`:
`n` starts at 0 (most restrictive) and goes up to 8 (most permissive.)
* `tcod.FOV_RESTRICTIVE`
.. versionadded:: 9.3
Example::
>>> explored = np.zeros((3, 5), dtype=bool, order="F")
>>> transparency = np.ones((3, 5), dtype=bool, order="F")
>>> transparency[:2, 2] = False
>>> transparency # Transparent area.
array([[ True, True, False, True, True],
[ True, True, False, True, True],
[ True, True, True, True, True]]...)
>>> visible = tcod.map.compute_fov(transparency, 0, 0)
>>> visible # Visible area.
array([[ True, True, True, False, False],
[ True, True, True, False, False],
[ True, True, True, True, False]]...)
>>> explored |= visible # Keep track of an explored area.
"""
if len(transparency.shape) != 2:
raise TypeError(
"transparency must be an array of 2 dimensions"
" (shape is %r)" % transparency.shape
)
map_ = Map(transparency.shape[1], transparency.shape[0])
map_.transparent[...] = transparency
map_.compute_fov(x, y, radius, light_walls, algorithm)
return map_.fov
|
[
"def",
"compute_fov",
"(",
"transparency",
":",
"np",
".",
"array",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"radius",
":",
"int",
"=",
"0",
",",
"light_walls",
":",
"bool",
"=",
"True",
",",
"algorithm",
":",
"int",
"=",
"tcod",
".",
"constants",
".",
"FOV_RESTRICTIVE",
",",
")",
"->",
"np",
".",
"array",
":",
"if",
"len",
"(",
"transparency",
".",
"shape",
")",
"!=",
"2",
":",
"raise",
"TypeError",
"(",
"\"transparency must be an array of 2 dimensions\"",
"\" (shape is %r)\"",
"%",
"transparency",
".",
"shape",
")",
"map_",
"=",
"Map",
"(",
"transparency",
".",
"shape",
"[",
"1",
"]",
",",
"transparency",
".",
"shape",
"[",
"0",
"]",
")",
"map_",
".",
"transparent",
"[",
"...",
"]",
"=",
"transparency",
"map_",
".",
"compute_fov",
"(",
"x",
",",
"y",
",",
"radius",
",",
"light_walls",
",",
"algorithm",
")",
"return",
"map_",
".",
"fov"
] |
Return the visible area of a field-of-view computation.
`transparency` is a 2 dimensional array where all non-zero values are
considered transparent. The returned array will match the shape of this
array.
`x` and `y` are the 1st and 2nd coordinates of the origin point. Areas
are visible when they can be seen from this point-of-view.
`radius` is the maximum view distance from `x`/`y`. If this is zero then
the maximum distance is used.
If `light_walls` is True then visible obstacles will be returned, otherwise
only transparent areas will be.
`algorithm` is the field-of-view algorithm to run. The default value is
`tcod.FOV_RESTRICTIVE`.
The options are:
* `tcod.FOV_BASIC`:
Simple ray-cast implementation.
* `tcod.FOV_DIAMOND`
* `tcod.FOV_SHADOW`:
Recursive shadow caster.
* `tcod.FOV_PERMISSIVE(n)`:
`n` starts at 0 (most restrictive) and goes up to 8 (most permissive.)
* `tcod.FOV_RESTRICTIVE`
.. versionadded:: 9.3
Example::
>>> explored = np.zeros((3, 5), dtype=bool, order="F")
>>> transparency = np.ones((3, 5), dtype=bool, order="F")
>>> transparency[:2, 2] = False
>>> transparency # Transparent area.
array([[ True, True, False, True, True],
[ True, True, False, True, True],
[ True, True, True, True, True]]...)
>>> visible = tcod.map.compute_fov(transparency, 0, 0)
>>> visible # Visible area.
array([[ True, True, True, False, False],
[ True, True, True, False, False],
[ True, True, True, True, False]]...)
>>> explored |= visible # Keep track of an explored area.
|
[
"Return",
"the",
"visible",
"area",
"of",
"a",
"field",
"-",
"of",
"-",
"view",
"computation",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/map.py#L147-L209
|
9,150
|
libtcod/python-tcod
|
tcod/map.py
|
Map.compute_fov
|
def compute_fov(
self,
x: int,
y: int,
radius: int = 0,
light_walls: bool = True,
algorithm: int = tcod.constants.FOV_RESTRICTIVE,
) -> None:
"""Compute a field-of-view on the current instance.
Args:
x (int): Point of view, x-coordinate.
y (int): Point of view, y-coordinate.
radius (int): Maximum view distance from the point of view.
A value of `0` will give an infinite distance.
light_walls (bool): Light up walls, or only the floor.
algorithm (int): Defaults to tcod.FOV_RESTRICTIVE
If you already have transparency in a NumPy array then you could use
:any:`tcod.map_compute_fov` instead.
"""
lib.TCOD_map_compute_fov(
self.map_c, x, y, radius, light_walls, algorithm
)
|
python
|
def compute_fov(
self,
x: int,
y: int,
radius: int = 0,
light_walls: bool = True,
algorithm: int = tcod.constants.FOV_RESTRICTIVE,
) -> None:
"""Compute a field-of-view on the current instance.
Args:
x (int): Point of view, x-coordinate.
y (int): Point of view, y-coordinate.
radius (int): Maximum view distance from the point of view.
A value of `0` will give an infinite distance.
light_walls (bool): Light up walls, or only the floor.
algorithm (int): Defaults to tcod.FOV_RESTRICTIVE
If you already have transparency in a NumPy array then you could use
:any:`tcod.map_compute_fov` instead.
"""
lib.TCOD_map_compute_fov(
self.map_c, x, y, radius, light_walls, algorithm
)
|
[
"def",
"compute_fov",
"(",
"self",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"radius",
":",
"int",
"=",
"0",
",",
"light_walls",
":",
"bool",
"=",
"True",
",",
"algorithm",
":",
"int",
"=",
"tcod",
".",
"constants",
".",
"FOV_RESTRICTIVE",
",",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_map_compute_fov",
"(",
"self",
".",
"map_c",
",",
"x",
",",
"y",
",",
"radius",
",",
"light_walls",
",",
"algorithm",
")"
] |
Compute a field-of-view on the current instance.
Args:
x (int): Point of view, x-coordinate.
y (int): Point of view, y-coordinate.
radius (int): Maximum view distance from the point of view.
A value of `0` will give an infinite distance.
light_walls (bool): Light up walls, or only the floor.
algorithm (int): Defaults to tcod.FOV_RESTRICTIVE
If you already have transparency in a NumPy array then you could use
:any:`tcod.map_compute_fov` instead.
|
[
"Compute",
"a",
"field",
"-",
"of",
"-",
"view",
"on",
"the",
"current",
"instance",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/map.py#L99-L123
|
9,151
|
libtcod/python-tcod
|
tcod/noise.py
|
Noise.sample_mgrid
|
def sample_mgrid(self, mgrid: np.array) -> np.array:
"""Sample a mesh-grid array and return the result.
The :any:`sample_ogrid` method performs better as there is a lot of
overhead when working with large mesh-grids.
Args:
mgrid (numpy.ndarray): A mesh-grid array of points to sample.
A contiguous array of type `numpy.float32` is preferred.
Returns:
numpy.ndarray: An array of sampled points.
This array has the shape: ``mgrid.shape[:-1]``.
The ``dtype`` is `numpy.float32`.
"""
mgrid = np.ascontiguousarray(mgrid, np.float32)
if mgrid.shape[0] != self.dimensions:
raise ValueError(
"mgrid.shape[0] must equal self.dimensions, "
"%r[0] != %r" % (mgrid.shape, self.dimensions)
)
out = np.ndarray(mgrid.shape[1:], np.float32)
if mgrid.shape[1:] != out.shape:
raise ValueError(
"mgrid.shape[1:] must equal out.shape, "
"%r[1:] != %r" % (mgrid.shape, out.shape)
)
lib.NoiseSampleMeshGrid(
self._tdl_noise_c,
out.size,
ffi.cast("float*", mgrid.ctypes.data),
ffi.cast("float*", out.ctypes.data),
)
return out
|
python
|
def sample_mgrid(self, mgrid: np.array) -> np.array:
"""Sample a mesh-grid array and return the result.
The :any:`sample_ogrid` method performs better as there is a lot of
overhead when working with large mesh-grids.
Args:
mgrid (numpy.ndarray): A mesh-grid array of points to sample.
A contiguous array of type `numpy.float32` is preferred.
Returns:
numpy.ndarray: An array of sampled points.
This array has the shape: ``mgrid.shape[:-1]``.
The ``dtype`` is `numpy.float32`.
"""
mgrid = np.ascontiguousarray(mgrid, np.float32)
if mgrid.shape[0] != self.dimensions:
raise ValueError(
"mgrid.shape[0] must equal self.dimensions, "
"%r[0] != %r" % (mgrid.shape, self.dimensions)
)
out = np.ndarray(mgrid.shape[1:], np.float32)
if mgrid.shape[1:] != out.shape:
raise ValueError(
"mgrid.shape[1:] must equal out.shape, "
"%r[1:] != %r" % (mgrid.shape, out.shape)
)
lib.NoiseSampleMeshGrid(
self._tdl_noise_c,
out.size,
ffi.cast("float*", mgrid.ctypes.data),
ffi.cast("float*", out.ctypes.data),
)
return out
|
[
"def",
"sample_mgrid",
"(",
"self",
",",
"mgrid",
":",
"np",
".",
"array",
")",
"->",
"np",
".",
"array",
":",
"mgrid",
"=",
"np",
".",
"ascontiguousarray",
"(",
"mgrid",
",",
"np",
".",
"float32",
")",
"if",
"mgrid",
".",
"shape",
"[",
"0",
"]",
"!=",
"self",
".",
"dimensions",
":",
"raise",
"ValueError",
"(",
"\"mgrid.shape[0] must equal self.dimensions, \"",
"\"%r[0] != %r\"",
"%",
"(",
"mgrid",
".",
"shape",
",",
"self",
".",
"dimensions",
")",
")",
"out",
"=",
"np",
".",
"ndarray",
"(",
"mgrid",
".",
"shape",
"[",
"1",
":",
"]",
",",
"np",
".",
"float32",
")",
"if",
"mgrid",
".",
"shape",
"[",
"1",
":",
"]",
"!=",
"out",
".",
"shape",
":",
"raise",
"ValueError",
"(",
"\"mgrid.shape[1:] must equal out.shape, \"",
"\"%r[1:] != %r\"",
"%",
"(",
"mgrid",
".",
"shape",
",",
"out",
".",
"shape",
")",
")",
"lib",
".",
"NoiseSampleMeshGrid",
"(",
"self",
".",
"_tdl_noise_c",
",",
"out",
".",
"size",
",",
"ffi",
".",
"cast",
"(",
"\"float*\"",
",",
"mgrid",
".",
"ctypes",
".",
"data",
")",
",",
"ffi",
".",
"cast",
"(",
"\"float*\"",
",",
"out",
".",
"ctypes",
".",
"data",
")",
",",
")",
"return",
"out"
] |
Sample a mesh-grid array and return the result.
The :any:`sample_ogrid` method performs better as there is a lot of
overhead when working with large mesh-grids.
Args:
mgrid (numpy.ndarray): A mesh-grid array of points to sample.
A contiguous array of type `numpy.float32` is preferred.
Returns:
numpy.ndarray: An array of sampled points.
This array has the shape: ``mgrid.shape[:-1]``.
The ``dtype`` is `numpy.float32`.
|
[
"Sample",
"a",
"mesh",
"-",
"grid",
"array",
"and",
"return",
"the",
"result",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/noise.py#L162-L196
|
9,152
|
libtcod/python-tcod
|
tcod/noise.py
|
Noise.sample_ogrid
|
def sample_ogrid(self, ogrid: np.array) -> np.array:
"""Sample an open mesh-grid array and return the result.
Args
ogrid (Sequence[Sequence[float]]): An open mesh-grid.
Returns:
numpy.ndarray: An array of sampled points.
The ``shape`` is based on the lengths of the open mesh-grid
arrays.
The ``dtype`` is `numpy.float32`.
"""
if len(ogrid) != self.dimensions:
raise ValueError(
"len(ogrid) must equal self.dimensions, "
"%r != %r" % (len(ogrid), self.dimensions)
)
ogrids = [np.ascontiguousarray(array, np.float32) for array in ogrid]
out = np.ndarray([array.size for array in ogrids], np.float32)
lib.NoiseSampleOpenMeshGrid(
self._tdl_noise_c,
len(ogrids),
out.shape,
[ffi.cast("float*", array.ctypes.data) for array in ogrids],
ffi.cast("float*", out.ctypes.data),
)
return out
|
python
|
def sample_ogrid(self, ogrid: np.array) -> np.array:
"""Sample an open mesh-grid array and return the result.
Args
ogrid (Sequence[Sequence[float]]): An open mesh-grid.
Returns:
numpy.ndarray: An array of sampled points.
The ``shape`` is based on the lengths of the open mesh-grid
arrays.
The ``dtype`` is `numpy.float32`.
"""
if len(ogrid) != self.dimensions:
raise ValueError(
"len(ogrid) must equal self.dimensions, "
"%r != %r" % (len(ogrid), self.dimensions)
)
ogrids = [np.ascontiguousarray(array, np.float32) for array in ogrid]
out = np.ndarray([array.size for array in ogrids], np.float32)
lib.NoiseSampleOpenMeshGrid(
self._tdl_noise_c,
len(ogrids),
out.shape,
[ffi.cast("float*", array.ctypes.data) for array in ogrids],
ffi.cast("float*", out.ctypes.data),
)
return out
|
[
"def",
"sample_ogrid",
"(",
"self",
",",
"ogrid",
":",
"np",
".",
"array",
")",
"->",
"np",
".",
"array",
":",
"if",
"len",
"(",
"ogrid",
")",
"!=",
"self",
".",
"dimensions",
":",
"raise",
"ValueError",
"(",
"\"len(ogrid) must equal self.dimensions, \"",
"\"%r != %r\"",
"%",
"(",
"len",
"(",
"ogrid",
")",
",",
"self",
".",
"dimensions",
")",
")",
"ogrids",
"=",
"[",
"np",
".",
"ascontiguousarray",
"(",
"array",
",",
"np",
".",
"float32",
")",
"for",
"array",
"in",
"ogrid",
"]",
"out",
"=",
"np",
".",
"ndarray",
"(",
"[",
"array",
".",
"size",
"for",
"array",
"in",
"ogrids",
"]",
",",
"np",
".",
"float32",
")",
"lib",
".",
"NoiseSampleOpenMeshGrid",
"(",
"self",
".",
"_tdl_noise_c",
",",
"len",
"(",
"ogrids",
")",
",",
"out",
".",
"shape",
",",
"[",
"ffi",
".",
"cast",
"(",
"\"float*\"",
",",
"array",
".",
"ctypes",
".",
"data",
")",
"for",
"array",
"in",
"ogrids",
"]",
",",
"ffi",
".",
"cast",
"(",
"\"float*\"",
",",
"out",
".",
"ctypes",
".",
"data",
")",
",",
")",
"return",
"out"
] |
Sample an open mesh-grid array and return the result.
Args
ogrid (Sequence[Sequence[float]]): An open mesh-grid.
Returns:
numpy.ndarray: An array of sampled points.
The ``shape`` is based on the lengths of the open mesh-grid
arrays.
The ``dtype`` is `numpy.float32`.
|
[
"Sample",
"an",
"open",
"mesh",
"-",
"grid",
"array",
"and",
"return",
"the",
"result",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/noise.py#L198-L225
|
9,153
|
libtcod/python-tcod
|
tdl/event.py
|
_processEvents
|
def _processEvents():
"""Flushes the event queue from libtcod into the global list _eventQueue"""
global _mousel, _mousem, _mouser, _eventsflushed, _pushedEvents
_eventsflushed = True
events = _pushedEvents # get events from event.push
_pushedEvents = [] # then clear the pushed events queue
mouse = _ffi.new('TCOD_mouse_t *')
libkey = _ffi.new('TCOD_key_t *')
while 1:
libevent = _lib.TCOD_sys_check_for_event(_lib.TCOD_EVENT_ANY, libkey, mouse)
if not libevent: # no more events from libtcod
break
#if mouse.dx or mouse.dy:
if libevent & _lib.TCOD_EVENT_MOUSE_MOVE:
events.append(MouseMotion((mouse.x, mouse.y),
(mouse.cx, mouse.cy),
(mouse.dx, mouse.dy),
(mouse.dcx, mouse.dcy)))
mousepos = ((mouse.x, mouse.y), (mouse.cx, mouse.cy))
for oldstate, newstate, released, button in \
zip((_mousel, _mousem, _mouser),
(mouse.lbutton, mouse.mbutton, mouse.rbutton),
(mouse.lbutton_pressed, mouse.mbutton_pressed,
mouse.rbutton_pressed),
(1, 2, 3)):
if released:
if not oldstate:
events.append(MouseDown(button, *mousepos))
events.append(MouseUp(button, *mousepos))
if newstate:
events.append(MouseDown(button, *mousepos))
elif newstate and not oldstate:
events.append(MouseDown(button, *mousepos))
if mouse.wheel_up:
events.append(MouseDown(4, *mousepos))
if mouse.wheel_down:
events.append(MouseDown(5, *mousepos))
_mousel = mouse.lbutton
_mousem = mouse.mbutton
_mouser = mouse.rbutton
if libkey.vk == _lib.TCODK_NONE:
break
if libkey.pressed:
keyevent = KeyDown
else:
keyevent = KeyUp
events.append(
keyevent(
libkey.vk,
libkey.c.decode('ascii', errors='ignore'),
_ffi.string(libkey.text).decode('utf-8'),
libkey.shift,
libkey.lalt,
libkey.ralt,
libkey.lctrl,
libkey.rctrl,
libkey.lmeta,
libkey.rmeta,
)
)
if _lib.TCOD_console_is_window_closed():
events.append(Quit())
_eventQueue.extend(events)
|
python
|
def _processEvents():
"""Flushes the event queue from libtcod into the global list _eventQueue"""
global _mousel, _mousem, _mouser, _eventsflushed, _pushedEvents
_eventsflushed = True
events = _pushedEvents # get events from event.push
_pushedEvents = [] # then clear the pushed events queue
mouse = _ffi.new('TCOD_mouse_t *')
libkey = _ffi.new('TCOD_key_t *')
while 1:
libevent = _lib.TCOD_sys_check_for_event(_lib.TCOD_EVENT_ANY, libkey, mouse)
if not libevent: # no more events from libtcod
break
#if mouse.dx or mouse.dy:
if libevent & _lib.TCOD_EVENT_MOUSE_MOVE:
events.append(MouseMotion((mouse.x, mouse.y),
(mouse.cx, mouse.cy),
(mouse.dx, mouse.dy),
(mouse.dcx, mouse.dcy)))
mousepos = ((mouse.x, mouse.y), (mouse.cx, mouse.cy))
for oldstate, newstate, released, button in \
zip((_mousel, _mousem, _mouser),
(mouse.lbutton, mouse.mbutton, mouse.rbutton),
(mouse.lbutton_pressed, mouse.mbutton_pressed,
mouse.rbutton_pressed),
(1, 2, 3)):
if released:
if not oldstate:
events.append(MouseDown(button, *mousepos))
events.append(MouseUp(button, *mousepos))
if newstate:
events.append(MouseDown(button, *mousepos))
elif newstate and not oldstate:
events.append(MouseDown(button, *mousepos))
if mouse.wheel_up:
events.append(MouseDown(4, *mousepos))
if mouse.wheel_down:
events.append(MouseDown(5, *mousepos))
_mousel = mouse.lbutton
_mousem = mouse.mbutton
_mouser = mouse.rbutton
if libkey.vk == _lib.TCODK_NONE:
break
if libkey.pressed:
keyevent = KeyDown
else:
keyevent = KeyUp
events.append(
keyevent(
libkey.vk,
libkey.c.decode('ascii', errors='ignore'),
_ffi.string(libkey.text).decode('utf-8'),
libkey.shift,
libkey.lalt,
libkey.ralt,
libkey.lctrl,
libkey.rctrl,
libkey.lmeta,
libkey.rmeta,
)
)
if _lib.TCOD_console_is_window_closed():
events.append(Quit())
_eventQueue.extend(events)
|
[
"def",
"_processEvents",
"(",
")",
":",
"global",
"_mousel",
",",
"_mousem",
",",
"_mouser",
",",
"_eventsflushed",
",",
"_pushedEvents",
"_eventsflushed",
"=",
"True",
"events",
"=",
"_pushedEvents",
"# get events from event.push",
"_pushedEvents",
"=",
"[",
"]",
"# then clear the pushed events queue",
"mouse",
"=",
"_ffi",
".",
"new",
"(",
"'TCOD_mouse_t *'",
")",
"libkey",
"=",
"_ffi",
".",
"new",
"(",
"'TCOD_key_t *'",
")",
"while",
"1",
":",
"libevent",
"=",
"_lib",
".",
"TCOD_sys_check_for_event",
"(",
"_lib",
".",
"TCOD_EVENT_ANY",
",",
"libkey",
",",
"mouse",
")",
"if",
"not",
"libevent",
":",
"# no more events from libtcod",
"break",
"#if mouse.dx or mouse.dy:",
"if",
"libevent",
"&",
"_lib",
".",
"TCOD_EVENT_MOUSE_MOVE",
":",
"events",
".",
"append",
"(",
"MouseMotion",
"(",
"(",
"mouse",
".",
"x",
",",
"mouse",
".",
"y",
")",
",",
"(",
"mouse",
".",
"cx",
",",
"mouse",
".",
"cy",
")",
",",
"(",
"mouse",
".",
"dx",
",",
"mouse",
".",
"dy",
")",
",",
"(",
"mouse",
".",
"dcx",
",",
"mouse",
".",
"dcy",
")",
")",
")",
"mousepos",
"=",
"(",
"(",
"mouse",
".",
"x",
",",
"mouse",
".",
"y",
")",
",",
"(",
"mouse",
".",
"cx",
",",
"mouse",
".",
"cy",
")",
")",
"for",
"oldstate",
",",
"newstate",
",",
"released",
",",
"button",
"in",
"zip",
"(",
"(",
"_mousel",
",",
"_mousem",
",",
"_mouser",
")",
",",
"(",
"mouse",
".",
"lbutton",
",",
"mouse",
".",
"mbutton",
",",
"mouse",
".",
"rbutton",
")",
",",
"(",
"mouse",
".",
"lbutton_pressed",
",",
"mouse",
".",
"mbutton_pressed",
",",
"mouse",
".",
"rbutton_pressed",
")",
",",
"(",
"1",
",",
"2",
",",
"3",
")",
")",
":",
"if",
"released",
":",
"if",
"not",
"oldstate",
":",
"events",
".",
"append",
"(",
"MouseDown",
"(",
"button",
",",
"*",
"mousepos",
")",
")",
"events",
".",
"append",
"(",
"MouseUp",
"(",
"button",
",",
"*",
"mousepos",
")",
")",
"if",
"newstate",
":",
"events",
".",
"append",
"(",
"MouseDown",
"(",
"button",
",",
"*",
"mousepos",
")",
")",
"elif",
"newstate",
"and",
"not",
"oldstate",
":",
"events",
".",
"append",
"(",
"MouseDown",
"(",
"button",
",",
"*",
"mousepos",
")",
")",
"if",
"mouse",
".",
"wheel_up",
":",
"events",
".",
"append",
"(",
"MouseDown",
"(",
"4",
",",
"*",
"mousepos",
")",
")",
"if",
"mouse",
".",
"wheel_down",
":",
"events",
".",
"append",
"(",
"MouseDown",
"(",
"5",
",",
"*",
"mousepos",
")",
")",
"_mousel",
"=",
"mouse",
".",
"lbutton",
"_mousem",
"=",
"mouse",
".",
"mbutton",
"_mouser",
"=",
"mouse",
".",
"rbutton",
"if",
"libkey",
".",
"vk",
"==",
"_lib",
".",
"TCODK_NONE",
":",
"break",
"if",
"libkey",
".",
"pressed",
":",
"keyevent",
"=",
"KeyDown",
"else",
":",
"keyevent",
"=",
"KeyUp",
"events",
".",
"append",
"(",
"keyevent",
"(",
"libkey",
".",
"vk",
",",
"libkey",
".",
"c",
".",
"decode",
"(",
"'ascii'",
",",
"errors",
"=",
"'ignore'",
")",
",",
"_ffi",
".",
"string",
"(",
"libkey",
".",
"text",
")",
".",
"decode",
"(",
"'utf-8'",
")",
",",
"libkey",
".",
"shift",
",",
"libkey",
".",
"lalt",
",",
"libkey",
".",
"ralt",
",",
"libkey",
".",
"lctrl",
",",
"libkey",
".",
"rctrl",
",",
"libkey",
".",
"lmeta",
",",
"libkey",
".",
"rmeta",
",",
")",
")",
"if",
"_lib",
".",
"TCOD_console_is_window_closed",
"(",
")",
":",
"events",
".",
"append",
"(",
"Quit",
"(",
")",
")",
"_eventQueue",
".",
"extend",
"(",
"events",
")"
] |
Flushes the event queue from libtcod into the global list _eventQueue
|
[
"Flushes",
"the",
"event",
"queue",
"from",
"libtcod",
"into",
"the",
"global",
"list",
"_eventQueue"
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/event.py#L331-L403
|
9,154
|
libtcod/python-tcod
|
tdl/event.py
|
wait
|
def wait(timeout=None, flush=True):
"""Wait for an event.
Args:
timeout (Optional[int]): The time in seconds that this function will
wait before giving up and returning None.
With the default value of None, this will block forever.
flush (bool): If True a call to :any:`tdl.flush` will be made before
listening for events.
Returns: Type[Event]: An event, or None if the function
has timed out.
Anything added via :any:`push` will also be returned.
"""
if timeout is not None:
timeout = timeout + _time.clock() # timeout at this time
while True:
if _eventQueue:
return _eventQueue.pop(0)
if flush:
# a full 'round' of events need to be processed before flushing
_tdl.flush()
if timeout and _time.clock() >= timeout:
return None # return None on timeout
_time.sleep(0.001) # sleep 1ms
_processEvents()
|
python
|
def wait(timeout=None, flush=True):
"""Wait for an event.
Args:
timeout (Optional[int]): The time in seconds that this function will
wait before giving up and returning None.
With the default value of None, this will block forever.
flush (bool): If True a call to :any:`tdl.flush` will be made before
listening for events.
Returns: Type[Event]: An event, or None if the function
has timed out.
Anything added via :any:`push` will also be returned.
"""
if timeout is not None:
timeout = timeout + _time.clock() # timeout at this time
while True:
if _eventQueue:
return _eventQueue.pop(0)
if flush:
# a full 'round' of events need to be processed before flushing
_tdl.flush()
if timeout and _time.clock() >= timeout:
return None # return None on timeout
_time.sleep(0.001) # sleep 1ms
_processEvents()
|
[
"def",
"wait",
"(",
"timeout",
"=",
"None",
",",
"flush",
"=",
"True",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"timeout",
"+",
"_time",
".",
"clock",
"(",
")",
"# timeout at this time",
"while",
"True",
":",
"if",
"_eventQueue",
":",
"return",
"_eventQueue",
".",
"pop",
"(",
"0",
")",
"if",
"flush",
":",
"# a full 'round' of events need to be processed before flushing",
"_tdl",
".",
"flush",
"(",
")",
"if",
"timeout",
"and",
"_time",
".",
"clock",
"(",
")",
">=",
"timeout",
":",
"return",
"None",
"# return None on timeout",
"_time",
".",
"sleep",
"(",
"0.001",
")",
"# sleep 1ms",
"_processEvents",
"(",
")"
] |
Wait for an event.
Args:
timeout (Optional[int]): The time in seconds that this function will
wait before giving up and returning None.
With the default value of None, this will block forever.
flush (bool): If True a call to :any:`tdl.flush` will be made before
listening for events.
Returns: Type[Event]: An event, or None if the function
has timed out.
Anything added via :any:`push` will also be returned.
|
[
"Wait",
"for",
"an",
"event",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/event.py#L428-L454
|
9,155
|
libtcod/python-tcod
|
tdl/event.py
|
App.run_once
|
def run_once(self):
"""Pump events to this App instance and then return.
This works in the way described in :any:`App.run` except it immediately
returns after the first :any:`update` call.
Having multiple :any:`App` instances and selectively calling runOnce on
them is a decent way to create a state machine.
"""
if not hasattr(self, '_App__prevTime'):
self.__prevTime = _time.clock() # initiate __prevTime
for event in get():
if event.type: # exclude custom events with a blank type variable
# call the ev_* methods
method = 'ev_%s' % event.type # ev_TYPE
getattr(self, method)(event)
if event.type == 'KEYDOWN':
# call the key_* methods
method = 'key_%s' % event.key # key_KEYNAME
if hasattr(self, method): # silently exclude undefined methods
getattr(self, method)(event)
newTime = _time.clock()
self.update(newTime - self.__prevTime)
self.__prevTime = newTime
|
python
|
def run_once(self):
"""Pump events to this App instance and then return.
This works in the way described in :any:`App.run` except it immediately
returns after the first :any:`update` call.
Having multiple :any:`App` instances and selectively calling runOnce on
them is a decent way to create a state machine.
"""
if not hasattr(self, '_App__prevTime'):
self.__prevTime = _time.clock() # initiate __prevTime
for event in get():
if event.type: # exclude custom events with a blank type variable
# call the ev_* methods
method = 'ev_%s' % event.type # ev_TYPE
getattr(self, method)(event)
if event.type == 'KEYDOWN':
# call the key_* methods
method = 'key_%s' % event.key # key_KEYNAME
if hasattr(self, method): # silently exclude undefined methods
getattr(self, method)(event)
newTime = _time.clock()
self.update(newTime - self.__prevTime)
self.__prevTime = newTime
|
[
"def",
"run_once",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_App__prevTime'",
")",
":",
"self",
".",
"__prevTime",
"=",
"_time",
".",
"clock",
"(",
")",
"# initiate __prevTime",
"for",
"event",
"in",
"get",
"(",
")",
":",
"if",
"event",
".",
"type",
":",
"# exclude custom events with a blank type variable",
"# call the ev_* methods",
"method",
"=",
"'ev_%s'",
"%",
"event",
".",
"type",
"# ev_TYPE",
"getattr",
"(",
"self",
",",
"method",
")",
"(",
"event",
")",
"if",
"event",
".",
"type",
"==",
"'KEYDOWN'",
":",
"# call the key_* methods",
"method",
"=",
"'key_%s'",
"%",
"event",
".",
"key",
"# key_KEYNAME",
"if",
"hasattr",
"(",
"self",
",",
"method",
")",
":",
"# silently exclude undefined methods",
"getattr",
"(",
"self",
",",
"method",
")",
"(",
"event",
")",
"newTime",
"=",
"_time",
".",
"clock",
"(",
")",
"self",
".",
"update",
"(",
"newTime",
"-",
"self",
".",
"__prevTime",
")",
"self",
".",
"__prevTime",
"=",
"newTime"
] |
Pump events to this App instance and then return.
This works in the way described in :any:`App.run` except it immediately
returns after the first :any:`update` call.
Having multiple :any:`App` instances and selectively calling runOnce on
them is a decent way to create a state machine.
|
[
"Pump",
"events",
"to",
"this",
"App",
"instance",
"and",
"then",
"return",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tdl/event.py#L305-L328
|
9,156
|
libtcod/python-tcod
|
tcod/tileset.py
|
load_truetype_font
|
def load_truetype_font(
path: str, tile_width: int, tile_height: int
) -> Tileset:
"""Return a new Tileset from a `.ttf` or `.otf` file.
Same as :any:`set_truetype_font`, but returns a :any:`Tileset` instead.
You can send this Tileset to :any:`set_default`.
This function is provisional. The API may change.
"""
if not os.path.exists(path):
raise RuntimeError("File not found:\n\t%s" % (os.path.realpath(path),))
return Tileset._claim(
lib.TCOD_load_truetype_font_(path.encode(), tile_width, tile_height)
)
|
python
|
def load_truetype_font(
path: str, tile_width: int, tile_height: int
) -> Tileset:
"""Return a new Tileset from a `.ttf` or `.otf` file.
Same as :any:`set_truetype_font`, but returns a :any:`Tileset` instead.
You can send this Tileset to :any:`set_default`.
This function is provisional. The API may change.
"""
if not os.path.exists(path):
raise RuntimeError("File not found:\n\t%s" % (os.path.realpath(path),))
return Tileset._claim(
lib.TCOD_load_truetype_font_(path.encode(), tile_width, tile_height)
)
|
[
"def",
"load_truetype_font",
"(",
"path",
":",
"str",
",",
"tile_width",
":",
"int",
",",
"tile_height",
":",
"int",
")",
"->",
"Tileset",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"RuntimeError",
"(",
"\"File not found:\\n\\t%s\"",
"%",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
",",
")",
")",
"return",
"Tileset",
".",
"_claim",
"(",
"lib",
".",
"TCOD_load_truetype_font_",
"(",
"path",
".",
"encode",
"(",
")",
",",
"tile_width",
",",
"tile_height",
")",
")"
] |
Return a new Tileset from a `.ttf` or `.otf` file.
Same as :any:`set_truetype_font`, but returns a :any:`Tileset` instead.
You can send this Tileset to :any:`set_default`.
This function is provisional. The API may change.
|
[
"Return",
"a",
"new",
"Tileset",
"from",
"a",
".",
"ttf",
"or",
".",
"otf",
"file",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/tileset.py#L120-L134
|
9,157
|
libtcod/python-tcod
|
tcod/tileset.py
|
set_truetype_font
|
def set_truetype_font(path: str, tile_width: int, tile_height: int) -> None:
"""Set the default tileset from a `.ttf` or `.otf` file.
`path` is the file path for the font file.
`tile_width` and `tile_height` are the desired size of the tiles in the new
tileset. The font will be scaled to fit the given `tile_height` and
`tile_width`.
This function will only affect the `SDL2` and `OPENGL2` renderers.
This function must be called before :any:`tcod.console_init_root`. Once
the root console is setup you may call this funtion again to change the
font. The tileset can be changed but the window will not be resized
automatically.
.. versionadded:: 9.2
"""
if not os.path.exists(path):
raise RuntimeError("File not found:\n\t%s" % (os.path.realpath(path),))
lib.TCOD_tileset_load_truetype_(path.encode(), tile_width, tile_height)
|
python
|
def set_truetype_font(path: str, tile_width: int, tile_height: int) -> None:
"""Set the default tileset from a `.ttf` or `.otf` file.
`path` is the file path for the font file.
`tile_width` and `tile_height` are the desired size of the tiles in the new
tileset. The font will be scaled to fit the given `tile_height` and
`tile_width`.
This function will only affect the `SDL2` and `OPENGL2` renderers.
This function must be called before :any:`tcod.console_init_root`. Once
the root console is setup you may call this funtion again to change the
font. The tileset can be changed but the window will not be resized
automatically.
.. versionadded:: 9.2
"""
if not os.path.exists(path):
raise RuntimeError("File not found:\n\t%s" % (os.path.realpath(path),))
lib.TCOD_tileset_load_truetype_(path.encode(), tile_width, tile_height)
|
[
"def",
"set_truetype_font",
"(",
"path",
":",
"str",
",",
"tile_width",
":",
"int",
",",
"tile_height",
":",
"int",
")",
"->",
"None",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"RuntimeError",
"(",
"\"File not found:\\n\\t%s\"",
"%",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
",",
")",
")",
"lib",
".",
"TCOD_tileset_load_truetype_",
"(",
"path",
".",
"encode",
"(",
")",
",",
"tile_width",
",",
"tile_height",
")"
] |
Set the default tileset from a `.ttf` or `.otf` file.
`path` is the file path for the font file.
`tile_width` and `tile_height` are the desired size of the tiles in the new
tileset. The font will be scaled to fit the given `tile_height` and
`tile_width`.
This function will only affect the `SDL2` and `OPENGL2` renderers.
This function must be called before :any:`tcod.console_init_root`. Once
the root console is setup you may call this funtion again to change the
font. The tileset can be changed but the window will not be resized
automatically.
.. versionadded:: 9.2
|
[
"Set",
"the",
"default",
"tileset",
"from",
"a",
".",
"ttf",
"or",
".",
"otf",
"file",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/tileset.py#L137-L157
|
9,158
|
libtcod/python-tcod
|
tcod/tileset.py
|
Tileset.get_tile
|
def get_tile(self, codepoint: int) -> np.array:
"""Return a copy of a tile for the given codepoint.
If the tile does not exist yet then a blank array will be returned.
The tile will have a shape of (height, width, rgba) and a dtype of
uint8. Note that most grey-scale tiles will only use the alpha
channel and will usually have a solid white color channel.
"""
tile = np.zeros(self.tile_shape + (4,), dtype=np.uint8)
lib.TCOD_tileset_get_tile_(
self._tileset_p,
codepoint,
ffi.cast("struct TCOD_ColorRGBA*", tile.ctypes.data),
)
return tile
|
python
|
def get_tile(self, codepoint: int) -> np.array:
"""Return a copy of a tile for the given codepoint.
If the tile does not exist yet then a blank array will be returned.
The tile will have a shape of (height, width, rgba) and a dtype of
uint8. Note that most grey-scale tiles will only use the alpha
channel and will usually have a solid white color channel.
"""
tile = np.zeros(self.tile_shape + (4,), dtype=np.uint8)
lib.TCOD_tileset_get_tile_(
self._tileset_p,
codepoint,
ffi.cast("struct TCOD_ColorRGBA*", tile.ctypes.data),
)
return tile
|
[
"def",
"get_tile",
"(",
"self",
",",
"codepoint",
":",
"int",
")",
"->",
"np",
".",
"array",
":",
"tile",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"tile_shape",
"+",
"(",
"4",
",",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"lib",
".",
"TCOD_tileset_get_tile_",
"(",
"self",
".",
"_tileset_p",
",",
"codepoint",
",",
"ffi",
".",
"cast",
"(",
"\"struct TCOD_ColorRGBA*\"",
",",
"tile",
".",
"ctypes",
".",
"data",
")",
",",
")",
"return",
"tile"
] |
Return a copy of a tile for the given codepoint.
If the tile does not exist yet then a blank array will be returned.
The tile will have a shape of (height, width, rgba) and a dtype of
uint8. Note that most grey-scale tiles will only use the alpha
channel and will usually have a solid white color channel.
|
[
"Return",
"a",
"copy",
"of",
"a",
"tile",
"for",
"the",
"given",
"codepoint",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/tileset.py#L55-L70
|
9,159
|
libtcod/python-tcod
|
tcod/tileset.py
|
Tileset.set_tile
|
def set_tile(self, codepoint: int, tile: np.array) -> None:
"""Upload a tile into this array.
The tile can be in 32-bit color (height, width, rgba), or grey-scale
(height, width). The tile should have a dtype of ``np.uint8``.
This data may need to be sent to graphics card memory, this is a slow
operation.
"""
tile = np.ascontiguousarray(tile, dtype=np.uint8)
if tile.shape == self.tile_shape:
full_tile = np.empty(self.tile_shape + (4,), dtype=np.uint8)
full_tile[:, :, :3] = 255
full_tile[:, :, 3] = tile
return self.set_tile(codepoint, full_tile)
required = self.tile_shape + (4,)
if tile.shape != required:
raise ValueError(
"Tile shape must be %r or %r, got %r."
% (required, self.tile_shape, tile.shape)
)
lib.TCOD_tileset_set_tile_(
self._tileset_p,
codepoint,
ffi.cast("struct TCOD_ColorRGBA*", tile.ctypes.data),
)
|
python
|
def set_tile(self, codepoint: int, tile: np.array) -> None:
"""Upload a tile into this array.
The tile can be in 32-bit color (height, width, rgba), or grey-scale
(height, width). The tile should have a dtype of ``np.uint8``.
This data may need to be sent to graphics card memory, this is a slow
operation.
"""
tile = np.ascontiguousarray(tile, dtype=np.uint8)
if tile.shape == self.tile_shape:
full_tile = np.empty(self.tile_shape + (4,), dtype=np.uint8)
full_tile[:, :, :3] = 255
full_tile[:, :, 3] = tile
return self.set_tile(codepoint, full_tile)
required = self.tile_shape + (4,)
if tile.shape != required:
raise ValueError(
"Tile shape must be %r or %r, got %r."
% (required, self.tile_shape, tile.shape)
)
lib.TCOD_tileset_set_tile_(
self._tileset_p,
codepoint,
ffi.cast("struct TCOD_ColorRGBA*", tile.ctypes.data),
)
|
[
"def",
"set_tile",
"(",
"self",
",",
"codepoint",
":",
"int",
",",
"tile",
":",
"np",
".",
"array",
")",
"->",
"None",
":",
"tile",
"=",
"np",
".",
"ascontiguousarray",
"(",
"tile",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"if",
"tile",
".",
"shape",
"==",
"self",
".",
"tile_shape",
":",
"full_tile",
"=",
"np",
".",
"empty",
"(",
"self",
".",
"tile_shape",
"+",
"(",
"4",
",",
")",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
"full_tile",
"[",
":",
",",
":",
",",
":",
"3",
"]",
"=",
"255",
"full_tile",
"[",
":",
",",
":",
",",
"3",
"]",
"=",
"tile",
"return",
"self",
".",
"set_tile",
"(",
"codepoint",
",",
"full_tile",
")",
"required",
"=",
"self",
".",
"tile_shape",
"+",
"(",
"4",
",",
")",
"if",
"tile",
".",
"shape",
"!=",
"required",
":",
"raise",
"ValueError",
"(",
"\"Tile shape must be %r or %r, got %r.\"",
"%",
"(",
"required",
",",
"self",
".",
"tile_shape",
",",
"tile",
".",
"shape",
")",
")",
"lib",
".",
"TCOD_tileset_set_tile_",
"(",
"self",
".",
"_tileset_p",
",",
"codepoint",
",",
"ffi",
".",
"cast",
"(",
"\"struct TCOD_ColorRGBA*\"",
",",
"tile",
".",
"ctypes",
".",
"data",
")",
",",
")"
] |
Upload a tile into this array.
The tile can be in 32-bit color (height, width, rgba), or grey-scale
(height, width). The tile should have a dtype of ``np.uint8``.
This data may need to be sent to graphics card memory, this is a slow
operation.
|
[
"Upload",
"a",
"tile",
"into",
"this",
"array",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/tileset.py#L72-L97
|
9,160
|
libtcod/python-tcod
|
build_libtcod.py
|
fix_header
|
def fix_header(filepath):
"""Removes leading whitespace from a MacOS header file.
This whitespace is causing issues with directives on some platforms.
"""
with open(filepath, "r+") as f:
current = f.read()
fixed = "\n".join(line.strip() for line in current.split("\n"))
if current == fixed:
return
f.seek(0)
f.truncate()
f.write(fixed)
|
python
|
def fix_header(filepath):
"""Removes leading whitespace from a MacOS header file.
This whitespace is causing issues with directives on some platforms.
"""
with open(filepath, "r+") as f:
current = f.read()
fixed = "\n".join(line.strip() for line in current.split("\n"))
if current == fixed:
return
f.seek(0)
f.truncate()
f.write(fixed)
|
[
"def",
"fix_header",
"(",
"filepath",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"\"r+\"",
")",
"as",
"f",
":",
"current",
"=",
"f",
".",
"read",
"(",
")",
"fixed",
"=",
"\"\\n\"",
".",
"join",
"(",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"current",
".",
"split",
"(",
"\"\\n\"",
")",
")",
"if",
"current",
"==",
"fixed",
":",
"return",
"f",
".",
"seek",
"(",
"0",
")",
"f",
".",
"truncate",
"(",
")",
"f",
".",
"write",
"(",
"fixed",
")"
] |
Removes leading whitespace from a MacOS header file.
This whitespace is causing issues with directives on some platforms.
|
[
"Removes",
"leading",
"whitespace",
"from",
"a",
"MacOS",
"header",
"file",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/build_libtcod.py#L145-L157
|
9,161
|
libtcod/python-tcod
|
build_libtcod.py
|
find_sdl_attrs
|
def find_sdl_attrs(prefix: str) -> Iterator[Tuple[str, Any]]:
"""Return names and values from `tcod.lib`.
`prefix` is used to filter out which names to copy.
"""
from tcod._libtcod import lib
if prefix.startswith("SDL_"):
name_starts_at = 4
elif prefix.startswith("SDL"):
name_starts_at = 3
else:
name_starts_at = 0
for attr in dir(lib):
if attr.startswith(prefix):
yield attr[name_starts_at:], getattr(lib, attr)
|
python
|
def find_sdl_attrs(prefix: str) -> Iterator[Tuple[str, Any]]:
"""Return names and values from `tcod.lib`.
`prefix` is used to filter out which names to copy.
"""
from tcod._libtcod import lib
if prefix.startswith("SDL_"):
name_starts_at = 4
elif prefix.startswith("SDL"):
name_starts_at = 3
else:
name_starts_at = 0
for attr in dir(lib):
if attr.startswith(prefix):
yield attr[name_starts_at:], getattr(lib, attr)
|
[
"def",
"find_sdl_attrs",
"(",
"prefix",
":",
"str",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"from",
"tcod",
".",
"_libtcod",
"import",
"lib",
"if",
"prefix",
".",
"startswith",
"(",
"\"SDL_\"",
")",
":",
"name_starts_at",
"=",
"4",
"elif",
"prefix",
".",
"startswith",
"(",
"\"SDL\"",
")",
":",
"name_starts_at",
"=",
"3",
"else",
":",
"name_starts_at",
"=",
"0",
"for",
"attr",
"in",
"dir",
"(",
"lib",
")",
":",
"if",
"attr",
".",
"startswith",
"(",
"prefix",
")",
":",
"yield",
"attr",
"[",
"name_starts_at",
":",
"]",
",",
"getattr",
"(",
"lib",
",",
"attr",
")"
] |
Return names and values from `tcod.lib`.
`prefix` is used to filter out which names to copy.
|
[
"Return",
"names",
"and",
"values",
"from",
"tcod",
".",
"lib",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/build_libtcod.py#L357-L372
|
9,162
|
libtcod/python-tcod
|
build_libtcod.py
|
write_library_constants
|
def write_library_constants():
"""Write libtcod constants into the tcod.constants module."""
from tcod._libtcod import lib, ffi
import tcod.color
with open("tcod/constants.py", "w") as f:
all_names = []
f.write(CONSTANT_MODULE_HEADER)
for name in dir(lib):
value = getattr(lib, name)
if name[:5] == "TCOD_":
if name.isupper(): # const names
f.write("%s = %r\n" % (name[5:], value))
all_names.append(name[5:])
elif name.startswith("FOV"): # fov const names
f.write("%s = %r\n" % (name, value))
all_names.append(name)
elif name[:6] == "TCODK_": # key name
f.write("KEY_%s = %r\n" % (name[6:], value))
all_names.append("KEY_%s" % name[6:])
f.write("\n# --- colors ---\n")
for name in dir(lib):
if name[:5] != "TCOD_":
continue
value = getattr(lib, name)
if not isinstance(value, ffi.CData):
continue
if ffi.typeof(value) != ffi.typeof("TCOD_color_t"):
continue
color = tcod.color.Color._new_from_cdata(value)
f.write("%s = %r\n" % (name[5:], color))
all_names.append(name[5:])
all_names = ",\n ".join('"%s"' % name for name in all_names)
f.write("\n__all__ = [\n %s,\n]\n" % (all_names,))
with open("tcod/event_constants.py", "w") as f:
all_names = []
f.write(EVENT_CONSTANT_MODULE_HEADER)
f.write("# --- SDL scancodes ---\n")
f.write(
"%s\n_REVERSE_SCANCODE_TABLE = %s\n"
% parse_sdl_attrs("SDL_SCANCODE", all_names)
)
f.write("\n# --- SDL keyboard symbols ---\n")
f.write(
"%s\n_REVERSE_SYM_TABLE = %s\n"
% parse_sdl_attrs("SDLK", all_names)
)
f.write("\n# --- SDL keyboard modifiers ---\n")
f.write(
"%s\n_REVERSE_MOD_TABLE = %s\n"
% parse_sdl_attrs("KMOD", all_names)
)
f.write("\n# --- SDL wheel ---\n")
f.write(
"%s\n_REVERSE_WHEEL_TABLE = %s\n"
% parse_sdl_attrs("SDL_MOUSEWHEEL", all_names)
)
all_names = ",\n ".join('"%s"' % name for name in all_names)
f.write("\n__all__ = [\n %s,\n]\n" % (all_names,))
|
python
|
def write_library_constants():
"""Write libtcod constants into the tcod.constants module."""
from tcod._libtcod import lib, ffi
import tcod.color
with open("tcod/constants.py", "w") as f:
all_names = []
f.write(CONSTANT_MODULE_HEADER)
for name in dir(lib):
value = getattr(lib, name)
if name[:5] == "TCOD_":
if name.isupper(): # const names
f.write("%s = %r\n" % (name[5:], value))
all_names.append(name[5:])
elif name.startswith("FOV"): # fov const names
f.write("%s = %r\n" % (name, value))
all_names.append(name)
elif name[:6] == "TCODK_": # key name
f.write("KEY_%s = %r\n" % (name[6:], value))
all_names.append("KEY_%s" % name[6:])
f.write("\n# --- colors ---\n")
for name in dir(lib):
if name[:5] != "TCOD_":
continue
value = getattr(lib, name)
if not isinstance(value, ffi.CData):
continue
if ffi.typeof(value) != ffi.typeof("TCOD_color_t"):
continue
color = tcod.color.Color._new_from_cdata(value)
f.write("%s = %r\n" % (name[5:], color))
all_names.append(name[5:])
all_names = ",\n ".join('"%s"' % name for name in all_names)
f.write("\n__all__ = [\n %s,\n]\n" % (all_names,))
with open("tcod/event_constants.py", "w") as f:
all_names = []
f.write(EVENT_CONSTANT_MODULE_HEADER)
f.write("# --- SDL scancodes ---\n")
f.write(
"%s\n_REVERSE_SCANCODE_TABLE = %s\n"
% parse_sdl_attrs("SDL_SCANCODE", all_names)
)
f.write("\n# --- SDL keyboard symbols ---\n")
f.write(
"%s\n_REVERSE_SYM_TABLE = %s\n"
% parse_sdl_attrs("SDLK", all_names)
)
f.write("\n# --- SDL keyboard modifiers ---\n")
f.write(
"%s\n_REVERSE_MOD_TABLE = %s\n"
% parse_sdl_attrs("KMOD", all_names)
)
f.write("\n# --- SDL wheel ---\n")
f.write(
"%s\n_REVERSE_WHEEL_TABLE = %s\n"
% parse_sdl_attrs("SDL_MOUSEWHEEL", all_names)
)
all_names = ",\n ".join('"%s"' % name for name in all_names)
f.write("\n__all__ = [\n %s,\n]\n" % (all_names,))
|
[
"def",
"write_library_constants",
"(",
")",
":",
"from",
"tcod",
".",
"_libtcod",
"import",
"lib",
",",
"ffi",
"import",
"tcod",
".",
"color",
"with",
"open",
"(",
"\"tcod/constants.py\"",
",",
"\"w\"",
")",
"as",
"f",
":",
"all_names",
"=",
"[",
"]",
"f",
".",
"write",
"(",
"CONSTANT_MODULE_HEADER",
")",
"for",
"name",
"in",
"dir",
"(",
"lib",
")",
":",
"value",
"=",
"getattr",
"(",
"lib",
",",
"name",
")",
"if",
"name",
"[",
":",
"5",
"]",
"==",
"\"TCOD_\"",
":",
"if",
"name",
".",
"isupper",
"(",
")",
":",
"# const names",
"f",
".",
"write",
"(",
"\"%s = %r\\n\"",
"%",
"(",
"name",
"[",
"5",
":",
"]",
",",
"value",
")",
")",
"all_names",
".",
"append",
"(",
"name",
"[",
"5",
":",
"]",
")",
"elif",
"name",
".",
"startswith",
"(",
"\"FOV\"",
")",
":",
"# fov const names",
"f",
".",
"write",
"(",
"\"%s = %r\\n\"",
"%",
"(",
"name",
",",
"value",
")",
")",
"all_names",
".",
"append",
"(",
"name",
")",
"elif",
"name",
"[",
":",
"6",
"]",
"==",
"\"TCODK_\"",
":",
"# key name",
"f",
".",
"write",
"(",
"\"KEY_%s = %r\\n\"",
"%",
"(",
"name",
"[",
"6",
":",
"]",
",",
"value",
")",
")",
"all_names",
".",
"append",
"(",
"\"KEY_%s\"",
"%",
"name",
"[",
"6",
":",
"]",
")",
"f",
".",
"write",
"(",
"\"\\n# --- colors ---\\n\"",
")",
"for",
"name",
"in",
"dir",
"(",
"lib",
")",
":",
"if",
"name",
"[",
":",
"5",
"]",
"!=",
"\"TCOD_\"",
":",
"continue",
"value",
"=",
"getattr",
"(",
"lib",
",",
"name",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"ffi",
".",
"CData",
")",
":",
"continue",
"if",
"ffi",
".",
"typeof",
"(",
"value",
")",
"!=",
"ffi",
".",
"typeof",
"(",
"\"TCOD_color_t\"",
")",
":",
"continue",
"color",
"=",
"tcod",
".",
"color",
".",
"Color",
".",
"_new_from_cdata",
"(",
"value",
")",
"f",
".",
"write",
"(",
"\"%s = %r\\n\"",
"%",
"(",
"name",
"[",
"5",
":",
"]",
",",
"color",
")",
")",
"all_names",
".",
"append",
"(",
"name",
"[",
"5",
":",
"]",
")",
"all_names",
"=",
"\",\\n \"",
".",
"join",
"(",
"'\"%s\"'",
"%",
"name",
"for",
"name",
"in",
"all_names",
")",
"f",
".",
"write",
"(",
"\"\\n__all__ = [\\n %s,\\n]\\n\"",
"%",
"(",
"all_names",
",",
")",
")",
"with",
"open",
"(",
"\"tcod/event_constants.py\"",
",",
"\"w\"",
")",
"as",
"f",
":",
"all_names",
"=",
"[",
"]",
"f",
".",
"write",
"(",
"EVENT_CONSTANT_MODULE_HEADER",
")",
"f",
".",
"write",
"(",
"\"# --- SDL scancodes ---\\n\"",
")",
"f",
".",
"write",
"(",
"\"%s\\n_REVERSE_SCANCODE_TABLE = %s\\n\"",
"%",
"parse_sdl_attrs",
"(",
"\"SDL_SCANCODE\"",
",",
"all_names",
")",
")",
"f",
".",
"write",
"(",
"\"\\n# --- SDL keyboard symbols ---\\n\"",
")",
"f",
".",
"write",
"(",
"\"%s\\n_REVERSE_SYM_TABLE = %s\\n\"",
"%",
"parse_sdl_attrs",
"(",
"\"SDLK\"",
",",
"all_names",
")",
")",
"f",
".",
"write",
"(",
"\"\\n# --- SDL keyboard modifiers ---\\n\"",
")",
"f",
".",
"write",
"(",
"\"%s\\n_REVERSE_MOD_TABLE = %s\\n\"",
"%",
"parse_sdl_attrs",
"(",
"\"KMOD\"",
",",
"all_names",
")",
")",
"f",
".",
"write",
"(",
"\"\\n# --- SDL wheel ---\\n\"",
")",
"f",
".",
"write",
"(",
"\"%s\\n_REVERSE_WHEEL_TABLE = %s\\n\"",
"%",
"parse_sdl_attrs",
"(",
"\"SDL_MOUSEWHEEL\"",
",",
"all_names",
")",
")",
"all_names",
"=",
"\",\\n \"",
".",
"join",
"(",
"'\"%s\"'",
"%",
"name",
"for",
"name",
"in",
"all_names",
")",
"f",
".",
"write",
"(",
"\"\\n__all__ = [\\n %s,\\n]\\n\"",
"%",
"(",
"all_names",
",",
")",
")"
] |
Write libtcod constants into the tcod.constants module.
|
[
"Write",
"libtcod",
"constants",
"into",
"the",
"tcod",
".",
"constants",
"module",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/build_libtcod.py#L394-L458
|
9,163
|
libtcod/python-tcod
|
build_libtcod.py
|
CustomPostParser.visit_EnumeratorList
|
def visit_EnumeratorList(self, node):
"""Replace enumerator expressions with '...' stubs."""
for type, enum in node.children():
if enum.value is None:
pass
elif isinstance(enum.value, (c_ast.BinaryOp, c_ast.UnaryOp)):
enum.value = c_ast.Constant("int", "...")
elif hasattr(enum.value, "type"):
enum.value = c_ast.Constant(enum.value.type, "...")
|
python
|
def visit_EnumeratorList(self, node):
"""Replace enumerator expressions with '...' stubs."""
for type, enum in node.children():
if enum.value is None:
pass
elif isinstance(enum.value, (c_ast.BinaryOp, c_ast.UnaryOp)):
enum.value = c_ast.Constant("int", "...")
elif hasattr(enum.value, "type"):
enum.value = c_ast.Constant(enum.value.type, "...")
|
[
"def",
"visit_EnumeratorList",
"(",
"self",
",",
"node",
")",
":",
"for",
"type",
",",
"enum",
"in",
"node",
".",
"children",
"(",
")",
":",
"if",
"enum",
".",
"value",
"is",
"None",
":",
"pass",
"elif",
"isinstance",
"(",
"enum",
".",
"value",
",",
"(",
"c_ast",
".",
"BinaryOp",
",",
"c_ast",
".",
"UnaryOp",
")",
")",
":",
"enum",
".",
"value",
"=",
"c_ast",
".",
"Constant",
"(",
"\"int\"",
",",
"\"...\"",
")",
"elif",
"hasattr",
"(",
"enum",
".",
"value",
",",
"\"type\"",
")",
":",
"enum",
".",
"value",
"=",
"c_ast",
".",
"Constant",
"(",
"enum",
".",
"value",
".",
"type",
",",
"\"...\"",
")"
] |
Replace enumerator expressions with '...' stubs.
|
[
"Replace",
"enumerator",
"expressions",
"with",
"...",
"stubs",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/build_libtcod.py#L214-L222
|
9,164
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
bsp_new_with_size
|
def bsp_new_with_size(x: int, y: int, w: int, h: int) -> tcod.bsp.BSP:
"""Create a new BSP instance with the given rectangle.
Args:
x (int): Rectangle left coordinate.
y (int): Rectangle top coordinate.
w (int): Rectangle width.
h (int): Rectangle height.
Returns:
BSP: A new BSP instance.
.. deprecated:: 2.0
Call the :any:`BSP` class instead.
"""
return Bsp(x, y, w, h)
|
python
|
def bsp_new_with_size(x: int, y: int, w: int, h: int) -> tcod.bsp.BSP:
"""Create a new BSP instance with the given rectangle.
Args:
x (int): Rectangle left coordinate.
y (int): Rectangle top coordinate.
w (int): Rectangle width.
h (int): Rectangle height.
Returns:
BSP: A new BSP instance.
.. deprecated:: 2.0
Call the :any:`BSP` class instead.
"""
return Bsp(x, y, w, h)
|
[
"def",
"bsp_new_with_size",
"(",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"w",
":",
"int",
",",
"h",
":",
"int",
")",
"->",
"tcod",
".",
"bsp",
".",
"BSP",
":",
"return",
"Bsp",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
")"
] |
Create a new BSP instance with the given rectangle.
Args:
x (int): Rectangle left coordinate.
y (int): Rectangle top coordinate.
w (int): Rectangle width.
h (int): Rectangle height.
Returns:
BSP: A new BSP instance.
.. deprecated:: 2.0
Call the :any:`BSP` class instead.
|
[
"Create",
"a",
"new",
"BSP",
"instance",
"with",
"the",
"given",
"rectangle",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L533-L548
|
9,165
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
_bsp_traverse
|
def _bsp_traverse(
node_iter: Iterable[tcod.bsp.BSP],
callback: Callable[[tcod.bsp.BSP, Any], None],
userData: Any,
) -> None:
"""pack callback into a handle for use with the callback
_pycall_bsp_callback
"""
for node in node_iter:
callback(node, userData)
|
python
|
def _bsp_traverse(
node_iter: Iterable[tcod.bsp.BSP],
callback: Callable[[tcod.bsp.BSP, Any], None],
userData: Any,
) -> None:
"""pack callback into a handle for use with the callback
_pycall_bsp_callback
"""
for node in node_iter:
callback(node, userData)
|
[
"def",
"_bsp_traverse",
"(",
"node_iter",
":",
"Iterable",
"[",
"tcod",
".",
"bsp",
".",
"BSP",
"]",
",",
"callback",
":",
"Callable",
"[",
"[",
"tcod",
".",
"bsp",
".",
"BSP",
",",
"Any",
"]",
",",
"None",
"]",
",",
"userData",
":",
"Any",
",",
")",
"->",
"None",
":",
"for",
"node",
"in",
"node_iter",
":",
"callback",
"(",
"node",
",",
"userData",
")"
] |
pack callback into a handle for use with the callback
_pycall_bsp_callback
|
[
"pack",
"callback",
"into",
"a",
"handle",
"for",
"use",
"with",
"the",
"callback",
"_pycall_bsp_callback"
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L649-L658
|
9,166
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
color_lerp
|
def color_lerp(
c1: Tuple[int, int, int], c2: Tuple[int, int, int], a: float
) -> Color:
"""Return the linear interpolation between two colors.
``a`` is the interpolation value, with 0 returing ``c1``,
1 returning ``c2``, and 0.5 returing a color halfway between both.
Args:
c1 (Union[Tuple[int, int, int], Sequence[int]]):
The first color. At a=0.
c2 (Union[Tuple[int, int, int], Sequence[int]]):
The second color. At a=1.
a (float): The interpolation value,
Returns:
Color: The interpolated Color.
"""
return Color._new_from_cdata(lib.TCOD_color_lerp(c1, c2, a))
|
python
|
def color_lerp(
c1: Tuple[int, int, int], c2: Tuple[int, int, int], a: float
) -> Color:
"""Return the linear interpolation between two colors.
``a`` is the interpolation value, with 0 returing ``c1``,
1 returning ``c2``, and 0.5 returing a color halfway between both.
Args:
c1 (Union[Tuple[int, int, int], Sequence[int]]):
The first color. At a=0.
c2 (Union[Tuple[int, int, int], Sequence[int]]):
The second color. At a=1.
a (float): The interpolation value,
Returns:
Color: The interpolated Color.
"""
return Color._new_from_cdata(lib.TCOD_color_lerp(c1, c2, a))
|
[
"def",
"color_lerp",
"(",
"c1",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
",",
"c2",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
",",
"a",
":",
"float",
")",
"->",
"Color",
":",
"return",
"Color",
".",
"_new_from_cdata",
"(",
"lib",
".",
"TCOD_color_lerp",
"(",
"c1",
",",
"c2",
",",
"a",
")",
")"
] |
Return the linear interpolation between two colors.
``a`` is the interpolation value, with 0 returing ``c1``,
1 returning ``c2``, and 0.5 returing a color halfway between both.
Args:
c1 (Union[Tuple[int, int, int], Sequence[int]]):
The first color. At a=0.
c2 (Union[Tuple[int, int, int], Sequence[int]]):
The second color. At a=1.
a (float): The interpolation value,
Returns:
Color: The interpolated Color.
|
[
"Return",
"the",
"linear",
"interpolation",
"between",
"two",
"colors",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L762-L780
|
9,167
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
color_scale_HSV
|
def color_scale_HSV(c: Color, scoef: float, vcoef: float) -> None:
"""Scale a color's saturation and value.
Does not return a new Color. ``c`` is modified inplace.
Args:
c (Union[Color, List[int]]): A Color instance, or an [r, g, b] list.
scoef (float): Saturation multiplier, from 0 to 1.
Use 1 to keep current saturation.
vcoef (float): Value multiplier, from 0 to 1.
Use 1 to keep current value.
"""
color_p = ffi.new("TCOD_color_t*")
color_p.r, color_p.g, color_p.b = c.r, c.g, c.b
lib.TCOD_color_scale_HSV(color_p, scoef, vcoef)
c[:] = color_p.r, color_p.g, color_p.b
|
python
|
def color_scale_HSV(c: Color, scoef: float, vcoef: float) -> None:
"""Scale a color's saturation and value.
Does not return a new Color. ``c`` is modified inplace.
Args:
c (Union[Color, List[int]]): A Color instance, or an [r, g, b] list.
scoef (float): Saturation multiplier, from 0 to 1.
Use 1 to keep current saturation.
vcoef (float): Value multiplier, from 0 to 1.
Use 1 to keep current value.
"""
color_p = ffi.new("TCOD_color_t*")
color_p.r, color_p.g, color_p.b = c.r, c.g, c.b
lib.TCOD_color_scale_HSV(color_p, scoef, vcoef)
c[:] = color_p.r, color_p.g, color_p.b
|
[
"def",
"color_scale_HSV",
"(",
"c",
":",
"Color",
",",
"scoef",
":",
"float",
",",
"vcoef",
":",
"float",
")",
"->",
"None",
":",
"color_p",
"=",
"ffi",
".",
"new",
"(",
"\"TCOD_color_t*\"",
")",
"color_p",
".",
"r",
",",
"color_p",
".",
"g",
",",
"color_p",
".",
"b",
"=",
"c",
".",
"r",
",",
"c",
".",
"g",
",",
"c",
".",
"b",
"lib",
".",
"TCOD_color_scale_HSV",
"(",
"color_p",
",",
"scoef",
",",
"vcoef",
")",
"c",
"[",
":",
"]",
"=",
"color_p",
".",
"r",
",",
"color_p",
".",
"g",
",",
"color_p",
".",
"b"
] |
Scale a color's saturation and value.
Does not return a new Color. ``c`` is modified inplace.
Args:
c (Union[Color, List[int]]): A Color instance, or an [r, g, b] list.
scoef (float): Saturation multiplier, from 0 to 1.
Use 1 to keep current saturation.
vcoef (float): Value multiplier, from 0 to 1.
Use 1 to keep current value.
|
[
"Scale",
"a",
"color",
"s",
"saturation",
"and",
"value",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L818-L833
|
9,168
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
color_gen_map
|
def color_gen_map(
colors: Iterable[Tuple[int, int, int]], indexes: Iterable[int]
) -> List[Color]:
"""Return a smoothly defined scale of colors.
If ``indexes`` is [0, 3, 9] for example, the first color from ``colors``
will be returned at 0, the 2nd will be at 3, and the 3rd will be at 9.
All in-betweens will be filled with a gradient.
Args:
colors (Iterable[Union[Tuple[int, int, int], Sequence[int]]]):
Array of colors to be sampled.
indexes (Iterable[int]): A list of indexes.
Returns:
List[Color]: A list of Color instances.
Example:
>>> tcod.color_gen_map([(0, 0, 0), (255, 128, 0)], [0, 5])
[Color(0, 0, 0), Color(51, 25, 0), Color(102, 51, 0), \
Color(153, 76, 0), Color(204, 102, 0), Color(255, 128, 0)]
"""
ccolors = ffi.new("TCOD_color_t[]", colors)
cindexes = ffi.new("int[]", indexes)
cres = ffi.new("TCOD_color_t[]", max(indexes) + 1)
lib.TCOD_color_gen_map(cres, len(ccolors), ccolors, cindexes)
return [Color._new_from_cdata(cdata) for cdata in cres]
|
python
|
def color_gen_map(
colors: Iterable[Tuple[int, int, int]], indexes: Iterable[int]
) -> List[Color]:
"""Return a smoothly defined scale of colors.
If ``indexes`` is [0, 3, 9] for example, the first color from ``colors``
will be returned at 0, the 2nd will be at 3, and the 3rd will be at 9.
All in-betweens will be filled with a gradient.
Args:
colors (Iterable[Union[Tuple[int, int, int], Sequence[int]]]):
Array of colors to be sampled.
indexes (Iterable[int]): A list of indexes.
Returns:
List[Color]: A list of Color instances.
Example:
>>> tcod.color_gen_map([(0, 0, 0), (255, 128, 0)], [0, 5])
[Color(0, 0, 0), Color(51, 25, 0), Color(102, 51, 0), \
Color(153, 76, 0), Color(204, 102, 0), Color(255, 128, 0)]
"""
ccolors = ffi.new("TCOD_color_t[]", colors)
cindexes = ffi.new("int[]", indexes)
cres = ffi.new("TCOD_color_t[]", max(indexes) + 1)
lib.TCOD_color_gen_map(cres, len(ccolors), ccolors, cindexes)
return [Color._new_from_cdata(cdata) for cdata in cres]
|
[
"def",
"color_gen_map",
"(",
"colors",
":",
"Iterable",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
"]",
",",
"indexes",
":",
"Iterable",
"[",
"int",
"]",
")",
"->",
"List",
"[",
"Color",
"]",
":",
"ccolors",
"=",
"ffi",
".",
"new",
"(",
"\"TCOD_color_t[]\"",
",",
"colors",
")",
"cindexes",
"=",
"ffi",
".",
"new",
"(",
"\"int[]\"",
",",
"indexes",
")",
"cres",
"=",
"ffi",
".",
"new",
"(",
"\"TCOD_color_t[]\"",
",",
"max",
"(",
"indexes",
")",
"+",
"1",
")",
"lib",
".",
"TCOD_color_gen_map",
"(",
"cres",
",",
"len",
"(",
"ccolors",
")",
",",
"ccolors",
",",
"cindexes",
")",
"return",
"[",
"Color",
".",
"_new_from_cdata",
"(",
"cdata",
")",
"for",
"cdata",
"in",
"cres",
"]"
] |
Return a smoothly defined scale of colors.
If ``indexes`` is [0, 3, 9] for example, the first color from ``colors``
will be returned at 0, the 2nd will be at 3, and the 3rd will be at 9.
All in-betweens will be filled with a gradient.
Args:
colors (Iterable[Union[Tuple[int, int, int], Sequence[int]]]):
Array of colors to be sampled.
indexes (Iterable[int]): A list of indexes.
Returns:
List[Color]: A list of Color instances.
Example:
>>> tcod.color_gen_map([(0, 0, 0), (255, 128, 0)], [0, 5])
[Color(0, 0, 0), Color(51, 25, 0), Color(102, 51, 0), \
Color(153, 76, 0), Color(204, 102, 0), Color(255, 128, 0)]
|
[
"Return",
"a",
"smoothly",
"defined",
"scale",
"of",
"colors",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L837-L863
|
9,169
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_init_root
|
def console_init_root(
w: int,
h: int,
title: Optional[str] = None,
fullscreen: bool = False,
renderer: Optional[int] = None,
order: str = "C",
) -> tcod.console.Console:
"""Set up the primary display and return the root console.
`w` and `h` are the columns and rows of the new window (in tiles.)
`title` is an optional string to display on the windows title bar.
`fullscreen` determines if the window will start in fullscreen. Fullscreen
mode is unreliable unless the renderer is set to `tcod.RENDERER_SDL2` or
`tcod.RENDERER_OPENGL2`.
`renderer` is the rendering back-end that libtcod will use.
If you don't know which to pick, then use `tcod.RENDERER_SDL2`.
Options are:
* `tcod.RENDERER_SDL`:
A deprecated software/SDL2 renderer.
* `tcod.RENDERER_OPENGL`:
A deprecated SDL2/OpenGL1 renderer.
* `tcod.RENDERER_GLSL`:
A deprecated SDL2/OpenGL2 renderer.
* `tcod.RENDERER_SDL2`:
The recommended SDL2 renderer. Rendering is decided by SDL2 and can be
changed by using an SDL2 hint.
* `tcod.RENDERER_OPENGL2`:
An SDL2/OPENGL2 renderer. Usually faster than regular SDL2.
Requires OpenGL 2.0 Core.
`order` will affect how the array attributes of the returned root console
are indexed. `order='C'` is the default, but `order='F'` is recommended.
.. versionchanged:: 4.3
Added `order` parameter.
`title` parameter is now optional.
.. versionchanged:: 8.0
The default `renderer` is now automatic instead of always being
`RENDERER_SDL`.
"""
if title is None:
# Use the scripts filename as the title.
title = os.path.basename(sys.argv[0])
if renderer is None:
warnings.warn(
"A renderer should be given, see the online documentation.",
DeprecationWarning,
stacklevel=2,
)
renderer = tcod.constants.RENDERER_SDL
elif renderer in (
tcod.constants.RENDERER_SDL,
tcod.constants.RENDERER_OPENGL,
tcod.constants.RENDERER_GLSL,
):
warnings.warn(
"The SDL, OPENGL, and GLSL renderers are deprecated.",
DeprecationWarning,
stacklevel=2,
)
lib.TCOD_console_init_root(w, h, _bytes(title), fullscreen, renderer)
console = tcod.console.Console._get_root(order)
console.clear()
return console
|
python
|
def console_init_root(
w: int,
h: int,
title: Optional[str] = None,
fullscreen: bool = False,
renderer: Optional[int] = None,
order: str = "C",
) -> tcod.console.Console:
"""Set up the primary display and return the root console.
`w` and `h` are the columns and rows of the new window (in tiles.)
`title` is an optional string to display on the windows title bar.
`fullscreen` determines if the window will start in fullscreen. Fullscreen
mode is unreliable unless the renderer is set to `tcod.RENDERER_SDL2` or
`tcod.RENDERER_OPENGL2`.
`renderer` is the rendering back-end that libtcod will use.
If you don't know which to pick, then use `tcod.RENDERER_SDL2`.
Options are:
* `tcod.RENDERER_SDL`:
A deprecated software/SDL2 renderer.
* `tcod.RENDERER_OPENGL`:
A deprecated SDL2/OpenGL1 renderer.
* `tcod.RENDERER_GLSL`:
A deprecated SDL2/OpenGL2 renderer.
* `tcod.RENDERER_SDL2`:
The recommended SDL2 renderer. Rendering is decided by SDL2 and can be
changed by using an SDL2 hint.
* `tcod.RENDERER_OPENGL2`:
An SDL2/OPENGL2 renderer. Usually faster than regular SDL2.
Requires OpenGL 2.0 Core.
`order` will affect how the array attributes of the returned root console
are indexed. `order='C'` is the default, but `order='F'` is recommended.
.. versionchanged:: 4.3
Added `order` parameter.
`title` parameter is now optional.
.. versionchanged:: 8.0
The default `renderer` is now automatic instead of always being
`RENDERER_SDL`.
"""
if title is None:
# Use the scripts filename as the title.
title = os.path.basename(sys.argv[0])
if renderer is None:
warnings.warn(
"A renderer should be given, see the online documentation.",
DeprecationWarning,
stacklevel=2,
)
renderer = tcod.constants.RENDERER_SDL
elif renderer in (
tcod.constants.RENDERER_SDL,
tcod.constants.RENDERER_OPENGL,
tcod.constants.RENDERER_GLSL,
):
warnings.warn(
"The SDL, OPENGL, and GLSL renderers are deprecated.",
DeprecationWarning,
stacklevel=2,
)
lib.TCOD_console_init_root(w, h, _bytes(title), fullscreen, renderer)
console = tcod.console.Console._get_root(order)
console.clear()
return console
|
[
"def",
"console_init_root",
"(",
"w",
":",
"int",
",",
"h",
":",
"int",
",",
"title",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"fullscreen",
":",
"bool",
"=",
"False",
",",
"renderer",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"order",
":",
"str",
"=",
"\"C\"",
",",
")",
"->",
"tcod",
".",
"console",
".",
"Console",
":",
"if",
"title",
"is",
"None",
":",
"# Use the scripts filename as the title.",
"title",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
"if",
"renderer",
"is",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"A renderer should be given, see the online documentation.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"renderer",
"=",
"tcod",
".",
"constants",
".",
"RENDERER_SDL",
"elif",
"renderer",
"in",
"(",
"tcod",
".",
"constants",
".",
"RENDERER_SDL",
",",
"tcod",
".",
"constants",
".",
"RENDERER_OPENGL",
",",
"tcod",
".",
"constants",
".",
"RENDERER_GLSL",
",",
")",
":",
"warnings",
".",
"warn",
"(",
"\"The SDL, OPENGL, and GLSL renderers are deprecated.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"lib",
".",
"TCOD_console_init_root",
"(",
"w",
",",
"h",
",",
"_bytes",
"(",
"title",
")",
",",
"fullscreen",
",",
"renderer",
")",
"console",
"=",
"tcod",
".",
"console",
".",
"Console",
".",
"_get_root",
"(",
"order",
")",
"console",
".",
"clear",
"(",
")",
"return",
"console"
] |
Set up the primary display and return the root console.
`w` and `h` are the columns and rows of the new window (in tiles.)
`title` is an optional string to display on the windows title bar.
`fullscreen` determines if the window will start in fullscreen. Fullscreen
mode is unreliable unless the renderer is set to `tcod.RENDERER_SDL2` or
`tcod.RENDERER_OPENGL2`.
`renderer` is the rendering back-end that libtcod will use.
If you don't know which to pick, then use `tcod.RENDERER_SDL2`.
Options are:
* `tcod.RENDERER_SDL`:
A deprecated software/SDL2 renderer.
* `tcod.RENDERER_OPENGL`:
A deprecated SDL2/OpenGL1 renderer.
* `tcod.RENDERER_GLSL`:
A deprecated SDL2/OpenGL2 renderer.
* `tcod.RENDERER_SDL2`:
The recommended SDL2 renderer. Rendering is decided by SDL2 and can be
changed by using an SDL2 hint.
* `tcod.RENDERER_OPENGL2`:
An SDL2/OPENGL2 renderer. Usually faster than regular SDL2.
Requires OpenGL 2.0 Core.
`order` will affect how the array attributes of the returned root console
are indexed. `order='C'` is the default, but `order='F'` is recommended.
.. versionchanged:: 4.3
Added `order` parameter.
`title` parameter is now optional.
.. versionchanged:: 8.0
The default `renderer` is now automatic instead of always being
`RENDERER_SDL`.
|
[
"Set",
"up",
"the",
"primary",
"display",
"and",
"return",
"the",
"root",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L866-L935
|
9,170
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_set_custom_font
|
def console_set_custom_font(
fontFile: AnyStr,
flags: int = FONT_LAYOUT_ASCII_INCOL,
nb_char_horiz: int = 0,
nb_char_vertic: int = 0,
) -> None:
"""Load the custom font file at `fontFile`.
Call this before function before calling :any:`tcod.console_init_root`.
Flags can be a mix of the following:
* tcod.FONT_LAYOUT_ASCII_INCOL:
Decode tileset raw in column-major order.
* tcod.FONT_LAYOUT_ASCII_INROW:
Decode tileset raw in row-major order.
* tcod.FONT_TYPE_GREYSCALE:
Force tileset to be read as greyscale.
* tcod.FONT_TYPE_GRAYSCALE
* tcod.FONT_LAYOUT_TCOD:
Unique layout used by libtcod.
* tcod.FONT_LAYOUT_CP437:
Decode a row-major Code Page 437 tileset into Unicode.
`nb_char_horiz` and `nb_char_vertic` are the columns and rows of the font
file respectfully.
"""
if not os.path.exists(fontFile):
raise RuntimeError(
"File not found:\n\t%s" % (os.path.realpath(fontFile),)
)
lib.TCOD_console_set_custom_font(
_bytes(fontFile), flags, nb_char_horiz, nb_char_vertic
)
|
python
|
def console_set_custom_font(
fontFile: AnyStr,
flags: int = FONT_LAYOUT_ASCII_INCOL,
nb_char_horiz: int = 0,
nb_char_vertic: int = 0,
) -> None:
"""Load the custom font file at `fontFile`.
Call this before function before calling :any:`tcod.console_init_root`.
Flags can be a mix of the following:
* tcod.FONT_LAYOUT_ASCII_INCOL:
Decode tileset raw in column-major order.
* tcod.FONT_LAYOUT_ASCII_INROW:
Decode tileset raw in row-major order.
* tcod.FONT_TYPE_GREYSCALE:
Force tileset to be read as greyscale.
* tcod.FONT_TYPE_GRAYSCALE
* tcod.FONT_LAYOUT_TCOD:
Unique layout used by libtcod.
* tcod.FONT_LAYOUT_CP437:
Decode a row-major Code Page 437 tileset into Unicode.
`nb_char_horiz` and `nb_char_vertic` are the columns and rows of the font
file respectfully.
"""
if not os.path.exists(fontFile):
raise RuntimeError(
"File not found:\n\t%s" % (os.path.realpath(fontFile),)
)
lib.TCOD_console_set_custom_font(
_bytes(fontFile), flags, nb_char_horiz, nb_char_vertic
)
|
[
"def",
"console_set_custom_font",
"(",
"fontFile",
":",
"AnyStr",
",",
"flags",
":",
"int",
"=",
"FONT_LAYOUT_ASCII_INCOL",
",",
"nb_char_horiz",
":",
"int",
"=",
"0",
",",
"nb_char_vertic",
":",
"int",
"=",
"0",
",",
")",
"->",
"None",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fontFile",
")",
":",
"raise",
"RuntimeError",
"(",
"\"File not found:\\n\\t%s\"",
"%",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"fontFile",
")",
",",
")",
")",
"lib",
".",
"TCOD_console_set_custom_font",
"(",
"_bytes",
"(",
"fontFile",
")",
",",
"flags",
",",
"nb_char_horiz",
",",
"nb_char_vertic",
")"
] |
Load the custom font file at `fontFile`.
Call this before function before calling :any:`tcod.console_init_root`.
Flags can be a mix of the following:
* tcod.FONT_LAYOUT_ASCII_INCOL:
Decode tileset raw in column-major order.
* tcod.FONT_LAYOUT_ASCII_INROW:
Decode tileset raw in row-major order.
* tcod.FONT_TYPE_GREYSCALE:
Force tileset to be read as greyscale.
* tcod.FONT_TYPE_GRAYSCALE
* tcod.FONT_LAYOUT_TCOD:
Unique layout used by libtcod.
* tcod.FONT_LAYOUT_CP437:
Decode a row-major Code Page 437 tileset into Unicode.
`nb_char_horiz` and `nb_char_vertic` are the columns and rows of the font
file respectfully.
|
[
"Load",
"the",
"custom",
"font",
"file",
"at",
"fontFile",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L938-L971
|
9,171
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_get_width
|
def console_get_width(con: tcod.console.Console) -> int:
"""Return the width of a console.
Args:
con (Console): Any Console instance.
Returns:
int: The width of a Console.
.. deprecated:: 2.0
Use `Console.width` instead.
"""
return int(lib.TCOD_console_get_width(_console(con)))
|
python
|
def console_get_width(con: tcod.console.Console) -> int:
"""Return the width of a console.
Args:
con (Console): Any Console instance.
Returns:
int: The width of a Console.
.. deprecated:: 2.0
Use `Console.width` instead.
"""
return int(lib.TCOD_console_get_width(_console(con)))
|
[
"def",
"console_get_width",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
")",
"->",
"int",
":",
"return",
"int",
"(",
"lib",
".",
"TCOD_console_get_width",
"(",
"_console",
"(",
"con",
")",
")",
")"
] |
Return the width of a console.
Args:
con (Console): Any Console instance.
Returns:
int: The width of a Console.
.. deprecated:: 2.0
Use `Console.width` instead.
|
[
"Return",
"the",
"width",
"of",
"a",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L975-L987
|
9,172
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_get_height
|
def console_get_height(con: tcod.console.Console) -> int:
"""Return the height of a console.
Args:
con (Console): Any Console instance.
Returns:
int: The height of a Console.
.. deprecated:: 2.0
Use `Console.height` instead.
"""
return int(lib.TCOD_console_get_height(_console(con)))
|
python
|
def console_get_height(con: tcod.console.Console) -> int:
"""Return the height of a console.
Args:
con (Console): Any Console instance.
Returns:
int: The height of a Console.
.. deprecated:: 2.0
Use `Console.height` instead.
"""
return int(lib.TCOD_console_get_height(_console(con)))
|
[
"def",
"console_get_height",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
")",
"->",
"int",
":",
"return",
"int",
"(",
"lib",
".",
"TCOD_console_get_height",
"(",
"_console",
"(",
"con",
")",
")",
")"
] |
Return the height of a console.
Args:
con (Console): Any Console instance.
Returns:
int: The height of a Console.
.. deprecated:: 2.0
Use `Console.height` instead.
|
[
"Return",
"the",
"height",
"of",
"a",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L991-L1003
|
9,173
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_map_ascii_code_to_font
|
def console_map_ascii_code_to_font(
asciiCode: int, fontCharX: int, fontCharY: int
) -> None:
"""Set a character code to new coordinates on the tile-set.
`asciiCode` must be within the bounds created during the initialization of
the loaded tile-set. For example, you can't use 255 here unless you have a
256 tile tile-set loaded. This applies to all functions in this group.
Args:
asciiCode (int): The character code to change.
fontCharX (int): The X tile coordinate on the loaded tileset.
0 is the leftmost tile.
fontCharY (int): The Y tile coordinate on the loaded tileset.
0 is the topmost tile.
"""
lib.TCOD_console_map_ascii_code_to_font(
_int(asciiCode), fontCharX, fontCharY
)
|
python
|
def console_map_ascii_code_to_font(
asciiCode: int, fontCharX: int, fontCharY: int
) -> None:
"""Set a character code to new coordinates on the tile-set.
`asciiCode` must be within the bounds created during the initialization of
the loaded tile-set. For example, you can't use 255 here unless you have a
256 tile tile-set loaded. This applies to all functions in this group.
Args:
asciiCode (int): The character code to change.
fontCharX (int): The X tile coordinate on the loaded tileset.
0 is the leftmost tile.
fontCharY (int): The Y tile coordinate on the loaded tileset.
0 is the topmost tile.
"""
lib.TCOD_console_map_ascii_code_to_font(
_int(asciiCode), fontCharX, fontCharY
)
|
[
"def",
"console_map_ascii_code_to_font",
"(",
"asciiCode",
":",
"int",
",",
"fontCharX",
":",
"int",
",",
"fontCharY",
":",
"int",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_map_ascii_code_to_font",
"(",
"_int",
"(",
"asciiCode",
")",
",",
"fontCharX",
",",
"fontCharY",
")"
] |
Set a character code to new coordinates on the tile-set.
`asciiCode` must be within the bounds created during the initialization of
the loaded tile-set. For example, you can't use 255 here unless you have a
256 tile tile-set loaded. This applies to all functions in this group.
Args:
asciiCode (int): The character code to change.
fontCharX (int): The X tile coordinate on the loaded tileset.
0 is the leftmost tile.
fontCharY (int): The Y tile coordinate on the loaded tileset.
0 is the topmost tile.
|
[
"Set",
"a",
"character",
"code",
"to",
"new",
"coordinates",
"on",
"the",
"tile",
"-",
"set",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1007-L1025
|
9,174
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_map_ascii_codes_to_font
|
def console_map_ascii_codes_to_font(
firstAsciiCode: int, nbCodes: int, fontCharX: int, fontCharY: int
) -> None:
"""Remap a contiguous set of codes to a contiguous set of tiles.
Both the tile-set and character codes must be contiguous to use this
function. If this is not the case you may want to use
:any:`console_map_ascii_code_to_font`.
Args:
firstAsciiCode (int): The starting character code.
nbCodes (int): The length of the contiguous set.
fontCharX (int): The starting X tile coordinate on the loaded tileset.
0 is the leftmost tile.
fontCharY (int): The starting Y tile coordinate on the loaded tileset.
0 is the topmost tile.
"""
lib.TCOD_console_map_ascii_codes_to_font(
_int(firstAsciiCode), nbCodes, fontCharX, fontCharY
)
|
python
|
def console_map_ascii_codes_to_font(
firstAsciiCode: int, nbCodes: int, fontCharX: int, fontCharY: int
) -> None:
"""Remap a contiguous set of codes to a contiguous set of tiles.
Both the tile-set and character codes must be contiguous to use this
function. If this is not the case you may want to use
:any:`console_map_ascii_code_to_font`.
Args:
firstAsciiCode (int): The starting character code.
nbCodes (int): The length of the contiguous set.
fontCharX (int): The starting X tile coordinate on the loaded tileset.
0 is the leftmost tile.
fontCharY (int): The starting Y tile coordinate on the loaded tileset.
0 is the topmost tile.
"""
lib.TCOD_console_map_ascii_codes_to_font(
_int(firstAsciiCode), nbCodes, fontCharX, fontCharY
)
|
[
"def",
"console_map_ascii_codes_to_font",
"(",
"firstAsciiCode",
":",
"int",
",",
"nbCodes",
":",
"int",
",",
"fontCharX",
":",
"int",
",",
"fontCharY",
":",
"int",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_map_ascii_codes_to_font",
"(",
"_int",
"(",
"firstAsciiCode",
")",
",",
"nbCodes",
",",
"fontCharX",
",",
"fontCharY",
")"
] |
Remap a contiguous set of codes to a contiguous set of tiles.
Both the tile-set and character codes must be contiguous to use this
function. If this is not the case you may want to use
:any:`console_map_ascii_code_to_font`.
Args:
firstAsciiCode (int): The starting character code.
nbCodes (int): The length of the contiguous set.
fontCharX (int): The starting X tile coordinate on the loaded tileset.
0 is the leftmost tile.
fontCharY (int): The starting Y tile coordinate on the loaded tileset.
0 is the topmost tile.
|
[
"Remap",
"a",
"contiguous",
"set",
"of",
"codes",
"to",
"a",
"contiguous",
"set",
"of",
"tiles",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1029-L1049
|
9,175
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_map_string_to_font
|
def console_map_string_to_font(s: str, fontCharX: int, fontCharY: int) -> None:
"""Remap a string of codes to a contiguous set of tiles.
Args:
s (AnyStr): A string of character codes to map to new values.
The null character `'\\x00'` will prematurely end this
function.
fontCharX (int): The starting X tile coordinate on the loaded tileset.
0 is the leftmost tile.
fontCharY (int): The starting Y tile coordinate on the loaded tileset.
0 is the topmost tile.
"""
lib.TCOD_console_map_string_to_font_utf(_unicode(s), fontCharX, fontCharY)
|
python
|
def console_map_string_to_font(s: str, fontCharX: int, fontCharY: int) -> None:
"""Remap a string of codes to a contiguous set of tiles.
Args:
s (AnyStr): A string of character codes to map to new values.
The null character `'\\x00'` will prematurely end this
function.
fontCharX (int): The starting X tile coordinate on the loaded tileset.
0 is the leftmost tile.
fontCharY (int): The starting Y tile coordinate on the loaded tileset.
0 is the topmost tile.
"""
lib.TCOD_console_map_string_to_font_utf(_unicode(s), fontCharX, fontCharY)
|
[
"def",
"console_map_string_to_font",
"(",
"s",
":",
"str",
",",
"fontCharX",
":",
"int",
",",
"fontCharY",
":",
"int",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_map_string_to_font_utf",
"(",
"_unicode",
"(",
"s",
")",
",",
"fontCharX",
",",
"fontCharY",
")"
] |
Remap a string of codes to a contiguous set of tiles.
Args:
s (AnyStr): A string of character codes to map to new values.
The null character `'\\x00'` will prematurely end this
function.
fontCharX (int): The starting X tile coordinate on the loaded tileset.
0 is the leftmost tile.
fontCharY (int): The starting Y tile coordinate on the loaded tileset.
0 is the topmost tile.
|
[
"Remap",
"a",
"string",
"of",
"codes",
"to",
"a",
"contiguous",
"set",
"of",
"tiles",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1053-L1065
|
9,176
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_set_default_background
|
def console_set_default_background(
con: tcod.console.Console, col: Tuple[int, int, int]
) -> None:
"""Change the default background color for a console.
Args:
con (Console): Any Console instance.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
.. deprecated:: 8.5
Use :any:`Console.default_bg` instead.
"""
lib.TCOD_console_set_default_background(_console(con), col)
|
python
|
def console_set_default_background(
con: tcod.console.Console, col: Tuple[int, int, int]
) -> None:
"""Change the default background color for a console.
Args:
con (Console): Any Console instance.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
.. deprecated:: 8.5
Use :any:`Console.default_bg` instead.
"""
lib.TCOD_console_set_default_background(_console(con), col)
|
[
"def",
"console_set_default_background",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"col",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_set_default_background",
"(",
"_console",
"(",
"con",
")",
",",
"col",
")"
] |
Change the default background color for a console.
Args:
con (Console): Any Console instance.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
.. deprecated:: 8.5
Use :any:`Console.default_bg` instead.
|
[
"Change",
"the",
"default",
"background",
"color",
"for",
"a",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1138-L1151
|
9,177
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_set_default_foreground
|
def console_set_default_foreground(
con: tcod.console.Console, col: Tuple[int, int, int]
) -> None:
"""Change the default foreground color for a console.
Args:
con (Console): Any Console instance.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
.. deprecated:: 8.5
Use :any:`Console.default_fg` instead.
"""
lib.TCOD_console_set_default_foreground(_console(con), col)
|
python
|
def console_set_default_foreground(
con: tcod.console.Console, col: Tuple[int, int, int]
) -> None:
"""Change the default foreground color for a console.
Args:
con (Console): Any Console instance.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
.. deprecated:: 8.5
Use :any:`Console.default_fg` instead.
"""
lib.TCOD_console_set_default_foreground(_console(con), col)
|
[
"def",
"console_set_default_foreground",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"col",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_set_default_foreground",
"(",
"_console",
"(",
"con",
")",
",",
"col",
")"
] |
Change the default foreground color for a console.
Args:
con (Console): Any Console instance.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
.. deprecated:: 8.5
Use :any:`Console.default_fg` instead.
|
[
"Change",
"the",
"default",
"foreground",
"color",
"for",
"a",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1155-L1168
|
9,178
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_put_char_ex
|
def console_put_char_ex(
con: tcod.console.Console,
x: int,
y: int,
c: Union[int, str],
fore: Tuple[int, int, int],
back: Tuple[int, int, int],
) -> None:
"""Draw the character c at x,y using the colors fore and back.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
c (Union[int, AnyStr]): Character to draw, can be an integer or string.
fore (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
back (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
"""
lib.TCOD_console_put_char_ex(_console(con), x, y, _int(c), fore, back)
|
python
|
def console_put_char_ex(
con: tcod.console.Console,
x: int,
y: int,
c: Union[int, str],
fore: Tuple[int, int, int],
back: Tuple[int, int, int],
) -> None:
"""Draw the character c at x,y using the colors fore and back.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
c (Union[int, AnyStr]): Character to draw, can be an integer or string.
fore (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
back (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
"""
lib.TCOD_console_put_char_ex(_console(con), x, y, _int(c), fore, back)
|
[
"def",
"console_put_char_ex",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"c",
":",
"Union",
"[",
"int",
",",
"str",
"]",
",",
"fore",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
",",
"back",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
",",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_put_char_ex",
"(",
"_console",
"(",
"con",
")",
",",
"x",
",",
"y",
",",
"_int",
"(",
"c",
")",
",",
"fore",
",",
"back",
")"
] |
Draw the character c at x,y using the colors fore and back.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
c (Union[int, AnyStr]): Character to draw, can be an integer or string.
fore (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
back (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
|
[
"Draw",
"the",
"character",
"c",
"at",
"x",
"y",
"using",
"the",
"colors",
"fore",
"and",
"back",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1209-L1229
|
9,179
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_set_char_background
|
def console_set_char_background(
con: tcod.console.Console,
x: int,
y: int,
col: Tuple[int, int, int],
flag: int = BKGND_SET,
) -> None:
"""Change the background color of x,y to col using a blend mode.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
flag (int): Blending mode to use, defaults to BKGND_SET.
"""
lib.TCOD_console_set_char_background(_console(con), x, y, col, flag)
|
python
|
def console_set_char_background(
con: tcod.console.Console,
x: int,
y: int,
col: Tuple[int, int, int],
flag: int = BKGND_SET,
) -> None:
"""Change the background color of x,y to col using a blend mode.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
flag (int): Blending mode to use, defaults to BKGND_SET.
"""
lib.TCOD_console_set_char_background(_console(con), x, y, col, flag)
|
[
"def",
"console_set_char_background",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"col",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
",",
"flag",
":",
"int",
"=",
"BKGND_SET",
",",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_set_char_background",
"(",
"_console",
"(",
"con",
")",
",",
"x",
",",
"y",
",",
"col",
",",
"flag",
")"
] |
Change the background color of x,y to col using a blend mode.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
flag (int): Blending mode to use, defaults to BKGND_SET.
|
[
"Change",
"the",
"background",
"color",
"of",
"x",
"y",
"to",
"col",
"using",
"a",
"blend",
"mode",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1233-L1250
|
9,180
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_set_char_foreground
|
def console_set_char_foreground(
con: tcod.console.Console, x: int, y: int, col: Tuple[int, int, int]
) -> None:
"""Change the foreground color of x,y to col.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.fg`.
"""
lib.TCOD_console_set_char_foreground(_console(con), x, y, col)
|
python
|
def console_set_char_foreground(
con: tcod.console.Console, x: int, y: int, col: Tuple[int, int, int]
) -> None:
"""Change the foreground color of x,y to col.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.fg`.
"""
lib.TCOD_console_set_char_foreground(_console(con), x, y, col)
|
[
"def",
"console_set_char_foreground",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"col",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_set_char_foreground",
"(",
"_console",
"(",
"con",
")",
",",
"x",
",",
"y",
",",
"col",
")"
] |
Change the foreground color of x,y to col.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.fg`.
|
[
"Change",
"the",
"foreground",
"color",
"of",
"x",
"y",
"to",
"col",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1254-L1270
|
9,181
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_set_char
|
def console_set_char(
con: tcod.console.Console, x: int, y: int, c: Union[int, str]
) -> None:
"""Change the character at x,y to c, keeping the current colors.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
c (Union[int, AnyStr]): Character to draw, can be an integer or string.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.ch`.
"""
lib.TCOD_console_set_char(_console(con), x, y, _int(c))
|
python
|
def console_set_char(
con: tcod.console.Console, x: int, y: int, c: Union[int, str]
) -> None:
"""Change the character at x,y to c, keeping the current colors.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
c (Union[int, AnyStr]): Character to draw, can be an integer or string.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.ch`.
"""
lib.TCOD_console_set_char(_console(con), x, y, _int(c))
|
[
"def",
"console_set_char",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"c",
":",
"Union",
"[",
"int",
",",
"str",
"]",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_set_char",
"(",
"_console",
"(",
"con",
")",
",",
"x",
",",
"y",
",",
"_int",
"(",
"c",
")",
")"
] |
Change the character at x,y to c, keeping the current colors.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
c (Union[int, AnyStr]): Character to draw, can be an integer or string.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.ch`.
|
[
"Change",
"the",
"character",
"at",
"x",
"y",
"to",
"c",
"keeping",
"the",
"current",
"colors",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1274-L1289
|
9,182
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_set_background_flag
|
def console_set_background_flag(con: tcod.console.Console, flag: int) -> None:
"""Change the default blend mode for this console.
Args:
con (Console): Any Console instance.
flag (int): Blend mode to use by default.
.. deprecated:: 8.5
Set :any:`Console.default_bg_blend` instead.
"""
lib.TCOD_console_set_background_flag(_console(con), flag)
|
python
|
def console_set_background_flag(con: tcod.console.Console, flag: int) -> None:
"""Change the default blend mode for this console.
Args:
con (Console): Any Console instance.
flag (int): Blend mode to use by default.
.. deprecated:: 8.5
Set :any:`Console.default_bg_blend` instead.
"""
lib.TCOD_console_set_background_flag(_console(con), flag)
|
[
"def",
"console_set_background_flag",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"flag",
":",
"int",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_set_background_flag",
"(",
"_console",
"(",
"con",
")",
",",
"flag",
")"
] |
Change the default blend mode for this console.
Args:
con (Console): Any Console instance.
flag (int): Blend mode to use by default.
.. deprecated:: 8.5
Set :any:`Console.default_bg_blend` instead.
|
[
"Change",
"the",
"default",
"blend",
"mode",
"for",
"this",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1293-L1303
|
9,183
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_get_background_flag
|
def console_get_background_flag(con: tcod.console.Console) -> int:
"""Return this consoles current blend mode.
Args:
con (Console): Any Console instance.
.. deprecated:: 8.5
Check :any:`Console.default_bg_blend` instead.
"""
return int(lib.TCOD_console_get_background_flag(_console(con)))
|
python
|
def console_get_background_flag(con: tcod.console.Console) -> int:
"""Return this consoles current blend mode.
Args:
con (Console): Any Console instance.
.. deprecated:: 8.5
Check :any:`Console.default_bg_blend` instead.
"""
return int(lib.TCOD_console_get_background_flag(_console(con)))
|
[
"def",
"console_get_background_flag",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
")",
"->",
"int",
":",
"return",
"int",
"(",
"lib",
".",
"TCOD_console_get_background_flag",
"(",
"_console",
"(",
"con",
")",
")",
")"
] |
Return this consoles current blend mode.
Args:
con (Console): Any Console instance.
.. deprecated:: 8.5
Check :any:`Console.default_bg_blend` instead.
|
[
"Return",
"this",
"consoles",
"current",
"blend",
"mode",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1307-L1316
|
9,184
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_set_alignment
|
def console_set_alignment(con: tcod.console.Console, alignment: int) -> None:
"""Change this consoles current alignment mode.
* tcod.LEFT
* tcod.CENTER
* tcod.RIGHT
Args:
con (Console): Any Console instance.
alignment (int):
.. deprecated:: 8.5
Set :any:`Console.default_alignment` instead.
"""
lib.TCOD_console_set_alignment(_console(con), alignment)
|
python
|
def console_set_alignment(con: tcod.console.Console, alignment: int) -> None:
"""Change this consoles current alignment mode.
* tcod.LEFT
* tcod.CENTER
* tcod.RIGHT
Args:
con (Console): Any Console instance.
alignment (int):
.. deprecated:: 8.5
Set :any:`Console.default_alignment` instead.
"""
lib.TCOD_console_set_alignment(_console(con), alignment)
|
[
"def",
"console_set_alignment",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"alignment",
":",
"int",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_set_alignment",
"(",
"_console",
"(",
"con",
")",
",",
"alignment",
")"
] |
Change this consoles current alignment mode.
* tcod.LEFT
* tcod.CENTER
* tcod.RIGHT
Args:
con (Console): Any Console instance.
alignment (int):
.. deprecated:: 8.5
Set :any:`Console.default_alignment` instead.
|
[
"Change",
"this",
"consoles",
"current",
"alignment",
"mode",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1320-L1334
|
9,185
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_get_alignment
|
def console_get_alignment(con: tcod.console.Console) -> int:
"""Return this consoles current alignment mode.
Args:
con (Console): Any Console instance.
.. deprecated:: 8.5
Check :any:`Console.default_alignment` instead.
"""
return int(lib.TCOD_console_get_alignment(_console(con)))
|
python
|
def console_get_alignment(con: tcod.console.Console) -> int:
"""Return this consoles current alignment mode.
Args:
con (Console): Any Console instance.
.. deprecated:: 8.5
Check :any:`Console.default_alignment` instead.
"""
return int(lib.TCOD_console_get_alignment(_console(con)))
|
[
"def",
"console_get_alignment",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
")",
"->",
"int",
":",
"return",
"int",
"(",
"lib",
".",
"TCOD_console_get_alignment",
"(",
"_console",
"(",
"con",
")",
")",
")"
] |
Return this consoles current alignment mode.
Args:
con (Console): Any Console instance.
.. deprecated:: 8.5
Check :any:`Console.default_alignment` instead.
|
[
"Return",
"this",
"consoles",
"current",
"alignment",
"mode",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1338-L1347
|
9,186
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_print_ex
|
def console_print_ex(
con: tcod.console.Console,
x: int,
y: int,
flag: int,
alignment: int,
fmt: str,
) -> None:
"""Print a string on a console using a blend mode and alignment mode.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
.. deprecated:: 8.5
Use :any:`Console.print_` instead.
"""
lib.TCOD_console_printf_ex(_console(con), x, y, flag, alignment, _fmt(fmt))
|
python
|
def console_print_ex(
con: tcod.console.Console,
x: int,
y: int,
flag: int,
alignment: int,
fmt: str,
) -> None:
"""Print a string on a console using a blend mode and alignment mode.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
.. deprecated:: 8.5
Use :any:`Console.print_` instead.
"""
lib.TCOD_console_printf_ex(_console(con), x, y, flag, alignment, _fmt(fmt))
|
[
"def",
"console_print_ex",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"flag",
":",
"int",
",",
"alignment",
":",
"int",
",",
"fmt",
":",
"str",
",",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_printf_ex",
"(",
"_console",
"(",
"con",
")",
",",
"x",
",",
"y",
",",
"flag",
",",
"alignment",
",",
"_fmt",
"(",
"fmt",
")",
")"
] |
Print a string on a console using a blend mode and alignment mode.
Args:
con (Console): Any Console instance.
x (int): Character x position from the left.
y (int): Character y position from the top.
.. deprecated:: 8.5
Use :any:`Console.print_` instead.
|
[
"Print",
"a",
"string",
"on",
"a",
"console",
"using",
"a",
"blend",
"mode",
"and",
"alignment",
"mode",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1367-L1385
|
9,187
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_print_rect_ex
|
def console_print_rect_ex(
con: tcod.console.Console,
x: int,
y: int,
w: int,
h: int,
flag: int,
alignment: int,
fmt: str,
) -> int:
"""Print a string constrained to a rectangle with blend and alignment.
Returns:
int: The number of lines of text once word-wrapped.
.. deprecated:: 8.5
Use :any:`Console.print_rect` instead.
"""
return int(
lib.TCOD_console_printf_rect_ex(
_console(con), x, y, w, h, flag, alignment, _fmt(fmt)
)
)
|
python
|
def console_print_rect_ex(
con: tcod.console.Console,
x: int,
y: int,
w: int,
h: int,
flag: int,
alignment: int,
fmt: str,
) -> int:
"""Print a string constrained to a rectangle with blend and alignment.
Returns:
int: The number of lines of text once word-wrapped.
.. deprecated:: 8.5
Use :any:`Console.print_rect` instead.
"""
return int(
lib.TCOD_console_printf_rect_ex(
_console(con), x, y, w, h, flag, alignment, _fmt(fmt)
)
)
|
[
"def",
"console_print_rect_ex",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"w",
":",
"int",
",",
"h",
":",
"int",
",",
"flag",
":",
"int",
",",
"alignment",
":",
"int",
",",
"fmt",
":",
"str",
",",
")",
"->",
"int",
":",
"return",
"int",
"(",
"lib",
".",
"TCOD_console_printf_rect_ex",
"(",
"_console",
"(",
"con",
")",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"flag",
",",
"alignment",
",",
"_fmt",
"(",
"fmt",
")",
")",
")"
] |
Print a string constrained to a rectangle with blend and alignment.
Returns:
int: The number of lines of text once word-wrapped.
.. deprecated:: 8.5
Use :any:`Console.print_rect` instead.
|
[
"Print",
"a",
"string",
"constrained",
"to",
"a",
"rectangle",
"with",
"blend",
"and",
"alignment",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1412-L1434
|
9,188
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_get_height_rect
|
def console_get_height_rect(
con: tcod.console.Console, x: int, y: int, w: int, h: int, fmt: str
) -> int:
"""Return the height of this text once word-wrapped into this rectangle.
Returns:
int: The number of lines of text once word-wrapped.
.. deprecated:: 8.5
Use :any:`Console.get_height_rect` instead.
"""
return int(
lib.TCOD_console_get_height_rect_fmt(
_console(con), x, y, w, h, _fmt(fmt)
)
)
|
python
|
def console_get_height_rect(
con: tcod.console.Console, x: int, y: int, w: int, h: int, fmt: str
) -> int:
"""Return the height of this text once word-wrapped into this rectangle.
Returns:
int: The number of lines of text once word-wrapped.
.. deprecated:: 8.5
Use :any:`Console.get_height_rect` instead.
"""
return int(
lib.TCOD_console_get_height_rect_fmt(
_console(con), x, y, w, h, _fmt(fmt)
)
)
|
[
"def",
"console_get_height_rect",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"w",
":",
"int",
",",
"h",
":",
"int",
",",
"fmt",
":",
"str",
")",
"->",
"int",
":",
"return",
"int",
"(",
"lib",
".",
"TCOD_console_get_height_rect_fmt",
"(",
"_console",
"(",
"con",
")",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"_fmt",
"(",
"fmt",
")",
")",
")"
] |
Return the height of this text once word-wrapped into this rectangle.
Returns:
int: The number of lines of text once word-wrapped.
.. deprecated:: 8.5
Use :any:`Console.get_height_rect` instead.
|
[
"Return",
"the",
"height",
"of",
"this",
"text",
"once",
"word",
"-",
"wrapped",
"into",
"this",
"rectangle",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1438-L1453
|
9,189
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_print_frame
|
def console_print_frame(
con: tcod.console.Console,
x: int,
y: int,
w: int,
h: int,
clear: bool = True,
flag: int = BKGND_DEFAULT,
fmt: str = "",
) -> None:
"""Draw a framed rectangle with optinal text.
This uses the default background color and blend mode to fill the
rectangle and the default foreground to draw the outline.
`fmt` will be printed on the inside of the rectangle, word-wrapped.
If `fmt` is empty then no title will be drawn.
.. versionchanged:: 8.2
Now supports Unicode strings.
.. deprecated:: 8.5
Use :any:`Console.print_frame` instead.
"""
fmt = _fmt(fmt) if fmt else ffi.NULL
lib.TCOD_console_printf_frame(_console(con), x, y, w, h, clear, flag, fmt)
|
python
|
def console_print_frame(
con: tcod.console.Console,
x: int,
y: int,
w: int,
h: int,
clear: bool = True,
flag: int = BKGND_DEFAULT,
fmt: str = "",
) -> None:
"""Draw a framed rectangle with optinal text.
This uses the default background color and blend mode to fill the
rectangle and the default foreground to draw the outline.
`fmt` will be printed on the inside of the rectangle, word-wrapped.
If `fmt` is empty then no title will be drawn.
.. versionchanged:: 8.2
Now supports Unicode strings.
.. deprecated:: 8.5
Use :any:`Console.print_frame` instead.
"""
fmt = _fmt(fmt) if fmt else ffi.NULL
lib.TCOD_console_printf_frame(_console(con), x, y, w, h, clear, flag, fmt)
|
[
"def",
"console_print_frame",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"w",
":",
"int",
",",
"h",
":",
"int",
",",
"clear",
":",
"bool",
"=",
"True",
",",
"flag",
":",
"int",
"=",
"BKGND_DEFAULT",
",",
"fmt",
":",
"str",
"=",
"\"\"",
",",
")",
"->",
"None",
":",
"fmt",
"=",
"_fmt",
"(",
"fmt",
")",
"if",
"fmt",
"else",
"ffi",
".",
"NULL",
"lib",
".",
"TCOD_console_printf_frame",
"(",
"_console",
"(",
"con",
")",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"clear",
",",
"flag",
",",
"fmt",
")"
] |
Draw a framed rectangle with optinal text.
This uses the default background color and blend mode to fill the
rectangle and the default foreground to draw the outline.
`fmt` will be printed on the inside of the rectangle, word-wrapped.
If `fmt` is empty then no title will be drawn.
.. versionchanged:: 8.2
Now supports Unicode strings.
.. deprecated:: 8.5
Use :any:`Console.print_frame` instead.
|
[
"Draw",
"a",
"framed",
"rectangle",
"with",
"optinal",
"text",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1513-L1538
|
9,190
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_get_default_background
|
def console_get_default_background(con: tcod.console.Console) -> Color:
"""Return this consoles default background color.
.. deprecated:: 8.5
Use :any:`Console.default_bg` instead.
"""
return Color._new_from_cdata(
lib.TCOD_console_get_default_background(_console(con))
)
|
python
|
def console_get_default_background(con: tcod.console.Console) -> Color:
"""Return this consoles default background color.
.. deprecated:: 8.5
Use :any:`Console.default_bg` instead.
"""
return Color._new_from_cdata(
lib.TCOD_console_get_default_background(_console(con))
)
|
[
"def",
"console_get_default_background",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
")",
"->",
"Color",
":",
"return",
"Color",
".",
"_new_from_cdata",
"(",
"lib",
".",
"TCOD_console_get_default_background",
"(",
"_console",
"(",
"con",
")",
")",
")"
] |
Return this consoles default background color.
.. deprecated:: 8.5
Use :any:`Console.default_bg` instead.
|
[
"Return",
"this",
"consoles",
"default",
"background",
"color",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1558-L1566
|
9,191
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_get_default_foreground
|
def console_get_default_foreground(con: tcod.console.Console) -> Color:
"""Return this consoles default foreground color.
.. deprecated:: 8.5
Use :any:`Console.default_fg` instead.
"""
return Color._new_from_cdata(
lib.TCOD_console_get_default_foreground(_console(con))
)
|
python
|
def console_get_default_foreground(con: tcod.console.Console) -> Color:
"""Return this consoles default foreground color.
.. deprecated:: 8.5
Use :any:`Console.default_fg` instead.
"""
return Color._new_from_cdata(
lib.TCOD_console_get_default_foreground(_console(con))
)
|
[
"def",
"console_get_default_foreground",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
")",
"->",
"Color",
":",
"return",
"Color",
".",
"_new_from_cdata",
"(",
"lib",
".",
"TCOD_console_get_default_foreground",
"(",
"_console",
"(",
"con",
")",
")",
")"
] |
Return this consoles default foreground color.
.. deprecated:: 8.5
Use :any:`Console.default_fg` instead.
|
[
"Return",
"this",
"consoles",
"default",
"foreground",
"color",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1570-L1578
|
9,192
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_get_char_background
|
def console_get_char_background(
con: tcod.console.Console, x: int, y: int
) -> Color:
"""Return the background color at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.bg`.
"""
return Color._new_from_cdata(
lib.TCOD_console_get_char_background(_console(con), x, y)
)
|
python
|
def console_get_char_background(
con: tcod.console.Console, x: int, y: int
) -> Color:
"""Return the background color at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.bg`.
"""
return Color._new_from_cdata(
lib.TCOD_console_get_char_background(_console(con), x, y)
)
|
[
"def",
"console_get_char_background",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
")",
"->",
"Color",
":",
"return",
"Color",
".",
"_new_from_cdata",
"(",
"lib",
".",
"TCOD_console_get_char_background",
"(",
"_console",
"(",
"con",
")",
",",
"x",
",",
"y",
")",
")"
] |
Return the background color at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.bg`.
|
[
"Return",
"the",
"background",
"color",
"at",
"the",
"x",
"y",
"of",
"this",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1582-L1593
|
9,193
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_get_char_foreground
|
def console_get_char_foreground(
con: tcod.console.Console, x: int, y: int
) -> Color:
"""Return the foreground color at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.fg`.
"""
return Color._new_from_cdata(
lib.TCOD_console_get_char_foreground(_console(con), x, y)
)
|
python
|
def console_get_char_foreground(
con: tcod.console.Console, x: int, y: int
) -> Color:
"""Return the foreground color at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.fg`.
"""
return Color._new_from_cdata(
lib.TCOD_console_get_char_foreground(_console(con), x, y)
)
|
[
"def",
"console_get_char_foreground",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
")",
"->",
"Color",
":",
"return",
"Color",
".",
"_new_from_cdata",
"(",
"lib",
".",
"TCOD_console_get_char_foreground",
"(",
"_console",
"(",
"con",
")",
",",
"x",
",",
"y",
")",
")"
] |
Return the foreground color at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.fg`.
|
[
"Return",
"the",
"foreground",
"color",
"at",
"the",
"x",
"y",
"of",
"this",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1597-L1608
|
9,194
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_get_char
|
def console_get_char(con: tcod.console.Console, x: int, y: int) -> int:
"""Return the character at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.ch`.
"""
return lib.TCOD_console_get_char(_console(con), x, y)
|
python
|
def console_get_char(con: tcod.console.Console, x: int, y: int) -> int:
"""Return the character at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.ch`.
"""
return lib.TCOD_console_get_char(_console(con), x, y)
|
[
"def",
"console_get_char",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
")",
"->",
"int",
":",
"return",
"lib",
".",
"TCOD_console_get_char",
"(",
"_console",
"(",
"con",
")",
",",
"x",
",",
"y",
")"
] |
Return the character at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.ch`.
|
[
"Return",
"the",
"character",
"at",
"the",
"x",
"y",
"of",
"this",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1612-L1619
|
9,195
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_wait_for_keypress
|
def console_wait_for_keypress(flush: bool) -> Key:
"""Block until the user presses a key, then returns a new Key.
Args:
flush bool: If True then the event queue is cleared before waiting
for the next event.
Returns:
Key: A new Key instance.
.. deprecated:: 9.3
Use the :any:`tcod.event.wait` function to wait for events.
"""
key = Key()
lib.TCOD_console_wait_for_keypress_wrapper(key.key_p, flush)
return key
|
python
|
def console_wait_for_keypress(flush: bool) -> Key:
"""Block until the user presses a key, then returns a new Key.
Args:
flush bool: If True then the event queue is cleared before waiting
for the next event.
Returns:
Key: A new Key instance.
.. deprecated:: 9.3
Use the :any:`tcod.event.wait` function to wait for events.
"""
key = Key()
lib.TCOD_console_wait_for_keypress_wrapper(key.key_p, flush)
return key
|
[
"def",
"console_wait_for_keypress",
"(",
"flush",
":",
"bool",
")",
"->",
"Key",
":",
"key",
"=",
"Key",
"(",
")",
"lib",
".",
"TCOD_console_wait_for_keypress_wrapper",
"(",
"key",
".",
"key_p",
",",
"flush",
")",
"return",
"key"
] |
Block until the user presses a key, then returns a new Key.
Args:
flush bool: If True then the event queue is cleared before waiting
for the next event.
Returns:
Key: A new Key instance.
.. deprecated:: 9.3
Use the :any:`tcod.event.wait` function to wait for events.
|
[
"Block",
"until",
"the",
"user",
"presses",
"a",
"key",
"then",
"returns",
"a",
"new",
"Key",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1639-L1654
|
9,196
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_from_file
|
def console_from_file(filename: str) -> tcod.console.Console:
"""Return a new console object from a filename.
The file format is automactially determined. This can load REXPaint `.xp`,
ASCII Paint `.apf`, or Non-delimited ASCII `.asc` files.
Args:
filename (Text): The path to the file, as a string.
Returns: A new :any`Console` instance.
"""
return tcod.console.Console._from_cdata(
lib.TCOD_console_from_file(filename.encode("utf-8"))
)
|
python
|
def console_from_file(filename: str) -> tcod.console.Console:
"""Return a new console object from a filename.
The file format is automactially determined. This can load REXPaint `.xp`,
ASCII Paint `.apf`, or Non-delimited ASCII `.asc` files.
Args:
filename (Text): The path to the file, as a string.
Returns: A new :any`Console` instance.
"""
return tcod.console.Console._from_cdata(
lib.TCOD_console_from_file(filename.encode("utf-8"))
)
|
[
"def",
"console_from_file",
"(",
"filename",
":",
"str",
")",
"->",
"tcod",
".",
"console",
".",
"Console",
":",
"return",
"tcod",
".",
"console",
".",
"Console",
".",
"_from_cdata",
"(",
"lib",
".",
"TCOD_console_from_file",
"(",
"filename",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
")"
] |
Return a new console object from a filename.
The file format is automactially determined. This can load REXPaint `.xp`,
ASCII Paint `.apf`, or Non-delimited ASCII `.asc` files.
Args:
filename (Text): The path to the file, as a string.
Returns: A new :any`Console` instance.
|
[
"Return",
"a",
"new",
"console",
"object",
"from",
"a",
"filename",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1685-L1698
|
9,197
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_blit
|
def console_blit(
src: tcod.console.Console,
x: int,
y: int,
w: int,
h: int,
dst: tcod.console.Console,
xdst: int,
ydst: int,
ffade: float = 1.0,
bfade: float = 1.0,
) -> None:
"""Blit the console src from x,y,w,h to console dst at xdst,ydst.
.. deprecated:: 8.5
Call the :any:`Console.blit` method instead.
"""
lib.TCOD_console_blit(
_console(src), x, y, w, h, _console(dst), xdst, ydst, ffade, bfade
)
|
python
|
def console_blit(
src: tcod.console.Console,
x: int,
y: int,
w: int,
h: int,
dst: tcod.console.Console,
xdst: int,
ydst: int,
ffade: float = 1.0,
bfade: float = 1.0,
) -> None:
"""Blit the console src from x,y,w,h to console dst at xdst,ydst.
.. deprecated:: 8.5
Call the :any:`Console.blit` method instead.
"""
lib.TCOD_console_blit(
_console(src), x, y, w, h, _console(dst), xdst, ydst, ffade, bfade
)
|
[
"def",
"console_blit",
"(",
"src",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
",",
"w",
":",
"int",
",",
"h",
":",
"int",
",",
"dst",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"xdst",
":",
"int",
",",
"ydst",
":",
"int",
",",
"ffade",
":",
"float",
"=",
"1.0",
",",
"bfade",
":",
"float",
"=",
"1.0",
",",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_blit",
"(",
"_console",
"(",
"src",
")",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"_console",
"(",
"dst",
")",
",",
"xdst",
",",
"ydst",
",",
"ffade",
",",
"bfade",
")"
] |
Blit the console src from x,y,w,h to console dst at xdst,ydst.
.. deprecated:: 8.5
Call the :any:`Console.blit` method instead.
|
[
"Blit",
"the",
"console",
"src",
"from",
"x",
"y",
"w",
"h",
"to",
"console",
"dst",
"at",
"xdst",
"ydst",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1702-L1721
|
9,198
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_delete
|
def console_delete(con: tcod.console.Console) -> None:
"""Closes the window if `con` is the root console.
libtcod objects are automatically garbage collected once they go out of
scope.
This function exists for backwards compatibility.
.. deprecated:: 9.3
This function is not needed for normal :any:`tcod.console.Console`'s.
The root console should be used in a with statement instead to ensure
that it closes.
"""
con = _console(con)
if con == ffi.NULL:
lib.TCOD_console_delete(con)
warnings.warn(
"Instead of this call you should use a with statement to ensure"
" the root console closes, for example:"
"\n with tcod.console_init_root(...) as root_console:"
"\n ...",
DeprecationWarning,
stacklevel=2,
)
else:
warnings.warn(
"You no longer need to make this call, "
"Console's are deleted when they go out of scope.",
DeprecationWarning,
stacklevel=2,
)
|
python
|
def console_delete(con: tcod.console.Console) -> None:
"""Closes the window if `con` is the root console.
libtcod objects are automatically garbage collected once they go out of
scope.
This function exists for backwards compatibility.
.. deprecated:: 9.3
This function is not needed for normal :any:`tcod.console.Console`'s.
The root console should be used in a with statement instead to ensure
that it closes.
"""
con = _console(con)
if con == ffi.NULL:
lib.TCOD_console_delete(con)
warnings.warn(
"Instead of this call you should use a with statement to ensure"
" the root console closes, for example:"
"\n with tcod.console_init_root(...) as root_console:"
"\n ...",
DeprecationWarning,
stacklevel=2,
)
else:
warnings.warn(
"You no longer need to make this call, "
"Console's are deleted when they go out of scope.",
DeprecationWarning,
stacklevel=2,
)
|
[
"def",
"console_delete",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
")",
"->",
"None",
":",
"con",
"=",
"_console",
"(",
"con",
")",
"if",
"con",
"==",
"ffi",
".",
"NULL",
":",
"lib",
".",
"TCOD_console_delete",
"(",
"con",
")",
"warnings",
".",
"warn",
"(",
"\"Instead of this call you should use a with statement to ensure\"",
"\" the root console closes, for example:\"",
"\"\\n with tcod.console_init_root(...) as root_console:\"",
"\"\\n ...\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",
")",
"else",
":",
"warnings",
".",
"warn",
"(",
"\"You no longer need to make this call, \"",
"\"Console's are deleted when they go out of scope.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
",",
")"
] |
Closes the window if `con` is the root console.
libtcod objects are automatically garbage collected once they go out of
scope.
This function exists for backwards compatibility.
.. deprecated:: 9.3
This function is not needed for normal :any:`tcod.console.Console`'s.
The root console should be used in a with statement instead to ensure
that it closes.
|
[
"Closes",
"the",
"window",
"if",
"con",
"is",
"the",
"root",
"console",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1741-L1771
|
9,199
|
libtcod/python-tcod
|
tcod/libtcodpy.py
|
console_fill_foreground
|
def console_fill_foreground(
con: tcod.console.Console,
r: Sequence[int],
g: Sequence[int],
b: Sequence[int],
) -> None:
"""Fill the foregound of a console with r,g,b.
Args:
con (Console): Any Console instance.
r (Sequence[int]): An array of integers with a length of width*height.
g (Sequence[int]): An array of integers with a length of width*height.
b (Sequence[int]): An array of integers with a length of width*height.
.. deprecated:: 8.4
You should assign to :any:`tcod.console.Console.fg` instead.
"""
if len(r) != len(g) or len(r) != len(b):
raise TypeError("R, G and B must all have the same size.")
if (
isinstance(r, np.ndarray)
and isinstance(g, np.ndarray)
and isinstance(b, np.ndarray)
):
# numpy arrays, use numpy's ctypes functions
r_ = np.ascontiguousarray(r, dtype=np.intc)
g_ = np.ascontiguousarray(g, dtype=np.intc)
b_ = np.ascontiguousarray(b, dtype=np.intc)
cr = ffi.cast("int *", r_.ctypes.data)
cg = ffi.cast("int *", g_.ctypes.data)
cb = ffi.cast("int *", b_.ctypes.data)
else:
# otherwise convert using ffi arrays
cr = ffi.new("int[]", r)
cg = ffi.new("int[]", g)
cb = ffi.new("int[]", b)
lib.TCOD_console_fill_foreground(_console(con), cr, cg, cb)
|
python
|
def console_fill_foreground(
con: tcod.console.Console,
r: Sequence[int],
g: Sequence[int],
b: Sequence[int],
) -> None:
"""Fill the foregound of a console with r,g,b.
Args:
con (Console): Any Console instance.
r (Sequence[int]): An array of integers with a length of width*height.
g (Sequence[int]): An array of integers with a length of width*height.
b (Sequence[int]): An array of integers with a length of width*height.
.. deprecated:: 8.4
You should assign to :any:`tcod.console.Console.fg` instead.
"""
if len(r) != len(g) or len(r) != len(b):
raise TypeError("R, G and B must all have the same size.")
if (
isinstance(r, np.ndarray)
and isinstance(g, np.ndarray)
and isinstance(b, np.ndarray)
):
# numpy arrays, use numpy's ctypes functions
r_ = np.ascontiguousarray(r, dtype=np.intc)
g_ = np.ascontiguousarray(g, dtype=np.intc)
b_ = np.ascontiguousarray(b, dtype=np.intc)
cr = ffi.cast("int *", r_.ctypes.data)
cg = ffi.cast("int *", g_.ctypes.data)
cb = ffi.cast("int *", b_.ctypes.data)
else:
# otherwise convert using ffi arrays
cr = ffi.new("int[]", r)
cg = ffi.new("int[]", g)
cb = ffi.new("int[]", b)
lib.TCOD_console_fill_foreground(_console(con), cr, cg, cb)
|
[
"def",
"console_fill_foreground",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"r",
":",
"Sequence",
"[",
"int",
"]",
",",
"g",
":",
"Sequence",
"[",
"int",
"]",
",",
"b",
":",
"Sequence",
"[",
"int",
"]",
",",
")",
"->",
"None",
":",
"if",
"len",
"(",
"r",
")",
"!=",
"len",
"(",
"g",
")",
"or",
"len",
"(",
"r",
")",
"!=",
"len",
"(",
"b",
")",
":",
"raise",
"TypeError",
"(",
"\"R, G and B must all have the same size.\"",
")",
"if",
"(",
"isinstance",
"(",
"r",
",",
"np",
".",
"ndarray",
")",
"and",
"isinstance",
"(",
"g",
",",
"np",
".",
"ndarray",
")",
"and",
"isinstance",
"(",
"b",
",",
"np",
".",
"ndarray",
")",
")",
":",
"# numpy arrays, use numpy's ctypes functions",
"r_",
"=",
"np",
".",
"ascontiguousarray",
"(",
"r",
",",
"dtype",
"=",
"np",
".",
"intc",
")",
"g_",
"=",
"np",
".",
"ascontiguousarray",
"(",
"g",
",",
"dtype",
"=",
"np",
".",
"intc",
")",
"b_",
"=",
"np",
".",
"ascontiguousarray",
"(",
"b",
",",
"dtype",
"=",
"np",
".",
"intc",
")",
"cr",
"=",
"ffi",
".",
"cast",
"(",
"\"int *\"",
",",
"r_",
".",
"ctypes",
".",
"data",
")",
"cg",
"=",
"ffi",
".",
"cast",
"(",
"\"int *\"",
",",
"g_",
".",
"ctypes",
".",
"data",
")",
"cb",
"=",
"ffi",
".",
"cast",
"(",
"\"int *\"",
",",
"b_",
".",
"ctypes",
".",
"data",
")",
"else",
":",
"# otherwise convert using ffi arrays",
"cr",
"=",
"ffi",
".",
"new",
"(",
"\"int[]\"",
",",
"r",
")",
"cg",
"=",
"ffi",
".",
"new",
"(",
"\"int[]\"",
",",
"g",
")",
"cb",
"=",
"ffi",
".",
"new",
"(",
"\"int[]\"",
",",
"b",
")",
"lib",
".",
"TCOD_console_fill_foreground",
"(",
"_console",
"(",
"con",
")",
",",
"cr",
",",
"cg",
",",
"cb",
")"
] |
Fill the foregound of a console with r,g,b.
Args:
con (Console): Any Console instance.
r (Sequence[int]): An array of integers with a length of width*height.
g (Sequence[int]): An array of integers with a length of width*height.
b (Sequence[int]): An array of integers with a length of width*height.
.. deprecated:: 8.4
You should assign to :any:`tcod.console.Console.fg` instead.
|
[
"Fill",
"the",
"foregound",
"of",
"a",
"console",
"with",
"r",
"g",
"b",
"."
] |
8ba10c5cfb813eaf3e834de971ba2d6acb7838e4
|
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L1775-L1812
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.