1
0
Fork 0
mirror of https://github.com/shlomif/PySolFC.git synced 2025-04-05 00:02:29 -04:00

Ran 2to3 and did some other conversions.

Trying to port PySol to Python 3 - this is time consuming.
This commit is contained in:
Shlomi Fish 2015-07-11 19:52:43 +03:00
parent d53e708a38
commit a76c85e71f
145 changed files with 1537 additions and 1340 deletions

View file

@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
##---------------------------------------------------------------------------##
##
## PySol -- a Python Solitaire game

195
pysollib/Py2Canvas.py Normal file
View file

@ -0,0 +1,195 @@
# Copied from:
# /usr/lib64/python2.7/lib-tk/Canvas.py
#
# Python 2-Licensed.
# -- Shlomi Fish
# This module exports classes for the various canvas item types
# NOTE: This module was an experiment and is now obsolete.
# It's best to use the Tkinter.Canvas class directly.
from tkinter import Canvas, _cnfmerge, _flatten
class CanvasItem:
def __init__(self, canvas, itemType, *args, **kw):
self.canvas = canvas
self.id = canvas._create(itemType, args, kw)
if not hasattr(canvas, 'items'):
canvas.items = {}
canvas.items[self.id] = self
def __str__(self):
return str(self.id)
def __repr__(self):
return '<%s, id=%d>' % (self.__class__.__name__, self.id)
def delete(self):
del self.canvas.items[self.id]
self.canvas.delete(self.id)
def __getitem__(self, key):
v = self.canvas.tk.split(self.canvas.tk.call(
self.canvas._w, 'itemconfigure',
self.id, '-' + key))
return v[4]
cget = __getitem__
def __setitem__(self, key, value):
self.canvas.itemconfig(self.id, {key: value})
def keys(self):
if not hasattr(self, '_keys'):
self._keys = map(lambda x, tk=self.canvas.tk:
tk.splitlist(x)[0][1:],
self.canvas.tk.splitlist(
self.canvas._do(
'itemconfigure',
(self.id,))))
return self._keys
def has_key(self, key):
return key in self.keys()
def __contains__(self, key):
return key in self.keys()
def addtag(self, tag, option='withtag'):
self.canvas.addtag(tag, option, self.id)
def bbox(self):
x1, y1, x2, y2 = self.canvas.bbox(self.id)
return (x1, y1), (x2, y2)
def bind(self, sequence=None, command=None, add=None):
return self.canvas.tag_bind(self.id, sequence, command, add)
def unbind(self, sequence, funcid=None):
self.canvas.tag_unbind(self.id, sequence, funcid)
def config(self, cnf={}, **kw):
return self.canvas.itemconfig(self.id, _cnfmerge((cnf, kw)))
def coords(self, pts = ()):
flat = ()
for x, y in pts: flat = flat + (x, y)
return self.canvas.coords(self.id, *flat)
def dchars(self, first, last=None):
self.canvas.dchars(self.id, first, last)
def dtag(self, ttd):
self.canvas.dtag(self.id, ttd)
def focus(self):
self.canvas.focus(self.id)
def gettags(self):
return self.canvas.gettags(self.id)
def icursor(self, index):
self.canvas.icursor(self.id, index)
def index(self, index):
return self.canvas.index(self.id, index)
def insert(self, beforethis, string):
self.canvas.insert(self.id, beforethis, string)
def lower(self, belowthis=None):
self.canvas.tag_lower(self.id, belowthis)
def move(self, xamount, yamount):
self.canvas.move(self.id, xamount, yamount)
def tkraise(self, abovethis=None):
self.canvas.tag_raise(self.id, abovethis)
raise_ = tkraise # BW compat
def scale(self, xorigin, yorigin, xscale, yscale):
self.canvas.scale(self.id, xorigin, yorigin, xscale, yscale)
def type(self):
return self.canvas.type(self.id)
class Arc(CanvasItem):
def __init__(self, canvas, *args, **kw):
CanvasItem.__init__(self, canvas, 'arc', *args, **kw)
class Bitmap(CanvasItem):
def __init__(self, canvas, *args, **kw):
CanvasItem.__init__(self, canvas, 'bitmap', *args, **kw)
class ImageItem(CanvasItem):
def __init__(self, canvas, *args, **kw):
CanvasItem.__init__(self, canvas, 'image', *args, **kw)
class Line(CanvasItem):
def __init__(self, canvas, *args, **kw):
CanvasItem.__init__(self, canvas, 'line', *args, **kw)
class Oval(CanvasItem):
def __init__(self, canvas, *args, **kw):
CanvasItem.__init__(self, canvas, 'oval', *args, **kw)
class Polygon(CanvasItem):
def __init__(self, canvas, *args, **kw):
CanvasItem.__init__(self, canvas, 'polygon', *args, **kw)
class Rectangle(CanvasItem):
def __init__(self, canvas, *args, **kw):
CanvasItem.__init__(self, canvas, 'rectangle', *args, **kw)
# XXX "Text" is taken by the Text widget...
class CanvasText(CanvasItem):
def __init__(self, canvas, *args, **kw):
CanvasItem.__init__(self, canvas, 'text', *args, **kw)
class Window(CanvasItem):
def __init__(self, canvas, *args, **kw):
CanvasItem.__init__(self, canvas, 'window', *args, **kw)
class Group:
def __init__(self, canvas, tag=None):
if not tag:
tag = 'Group%d' % id(self)
self.tag = self.id = tag
self.canvas = canvas
self.canvas.dtag(self.tag)
def str(self):
return self.tag
__str__ = str
def _do(self, cmd, *args):
return self.canvas._do(cmd, (self.tag,) + _flatten(args))
def addtag_above(self, tagOrId):
self._do('addtag', 'above', tagOrId)
def addtag_all(self):
self._do('addtag', 'all')
def addtag_below(self, tagOrId):
self._do('addtag', 'below', tagOrId)
def addtag_closest(self, x, y, halo=None, start=None):
self._do('addtag', 'closest', x, y, halo, start)
def addtag_enclosed(self, x1, y1, x2, y2):
self._do('addtag', 'enclosed', x1, y1, x2, y2)
def addtag_overlapping(self, x1, y1, x2, y2):
self._do('addtag', 'overlapping', x1, y1, x2, y2)
def addtag_withtag(self, tagOrId):
self._do('addtag', 'withtag', tagOrId)
def bbox(self):
return self.canvas._getints(self._do('bbox'))
def bind(self, sequence=None, command=None, add=None):
return self.canvas.tag_bind(self.id, sequence, command, add)
def unbind(self, sequence, funcid=None):
self.canvas.tag_unbind(self.id, sequence, funcid)
def coords(self, *pts):
return self._do('coords', pts)
def dchars(self, first, last=None):
self._do('dchars', first, last)
def delete(self):
self._do('delete')
def dtag(self, tagToDelete=None):
self._do('dtag', tagToDelete)
def focus(self):
self._do('focus')
def gettags(self):
return self.canvas.tk.splitlist(self._do('gettags', self.tag))
def icursor(self, index):
return self._do('icursor', index)
def index(self, index):
return self.canvas.tk.getint(self._do('index', index))
def insert(self, beforeThis, string):
self._do('insert', beforeThis, string)
def config(self, cnf={}, **kw):
return self.canvas.itemconfigure(self.tag, _cnfmerge((cnf,kw)))
def lower(self, belowThis=None):
self._do('lower', belowThis)
def move(self, xAmount, yAmount):
self._do('move', xAmount, yAmount)
def tkraise(self, aboveThis=None):
self._do('raise', aboveThis)
lift = tkraise
def scale(self, xOrigin, yOrigin, xScale, yScale):
self._do('scale', xOrigin, yOrigin, xScale, yScale)
def select_adjust(self, index):
self.canvas._do('select', ('adjust', self.tag, index))
def select_from(self, index):
self.canvas._do('select', ('from', self.tag, index))
def select_to(self, index):
self.canvas._do('select', ('to', self.tag, index))
def type(self):
return self._do('type')

View file

@ -116,7 +116,7 @@ class PysolMenubar(PysolMenubarTk):
def _clearMenuState(self):
ms = self.menustate
for k, v in ms.__dict__.items():
for k, v in list(ms.__dict__.items()):
if isinstance(v, list):
ms.__dict__[k] = [0] * len(v)
else:
@ -263,7 +263,7 @@ class PysolMenubar(PysolMenubarTk):
id = self.game.id
if not self.app.getGameInfo(id):
raise ValueError
except (ValueError, TypeError), ex:
except (ValueError, TypeError) as ex:
d = MfxMessageDialog(self.top, title=_("Invalid game number"),
text=_("Invalid game number\n") + str(seed),
bitmap="error")
@ -497,7 +497,7 @@ class PysolMenubar(PysolMenubarTk):
try:
fd = open(fn, 'a')
fd.write(text.encode(enc, 'replace'))
except Exception, err:
except Exception as err:
d = MfxExceptionDialog(self.top, err,
text=_("Error while writing to file"))
else:
@ -524,7 +524,7 @@ class PysolMenubar(PysolMenubarTk):
file = open(filename, "a")
a = FileStatsFormatter(self.app, file)
write_method(a, player)
except EnvironmentError, ex:
except EnvironmentError as ex:
if file: file.close()
d = MfxExceptionDialog(self.top, ex,
text=_("Error while writing to file"))
@ -779,7 +779,7 @@ class PysolMenubar(PysolMenubarTk):
index = self.app.audio.getMusicInfo()
music = self.app.music_manager.get(index)
if music:
print "playing music:", music.filename
print("playing music:", music.filename)
def mIconify(self, *args):
if self._cancelDrag(break_pause=False): return

View file

@ -368,7 +368,7 @@ class Application:
savegames = os.path.join(config, "savegames"),
maint = os.path.join(config, "maint"), # debug
)
for k, v in self.dn.__dict__.items():
for k, v in list(self.dn.__dict__.items()):
## if os.name == "nt":
## v = os.path.normcase(v)
v = os.path.normpath(v)
@ -381,7 +381,7 @@ class Application:
holdgame = os.path.join(self.dn.config, "holdgame.dat"),
comments = os.path.join(self.dn.config, "comments.dat"),
)
for k, v in self.dn.__dict__.items():
for k, v in list(self.dn.__dict__.items()):
if os.name == "nt":
v = os.path.normcase(v)
v = os.path.normpath(v)
@ -503,7 +503,7 @@ class Application:
compound=self.opt.toolbar_compound)
self.toolbar.show(self.opt.toolbar)
if TOOLKIT == 'tk':
for w, v in self.opt.toolbar_vars.items():
for w, v in list(self.opt.toolbar_vars.items()):
self.toolbar.config(w, v)
#
if self.intro.progress: self.intro.progress.update(step=1)
@ -756,7 +756,7 @@ class Application:
def loadImages4(self):
# load all remaining images
for k, v in self.gimages.__dict__.items():
for k, v in list(self.gimages.__dict__.items()):
if isinstance(v, list):
for i in range(len(v)):
if isinstance(v[i], str):
@ -892,7 +892,7 @@ class Application:
self.subsampled_images = simages
self.updateCardset(id, update=update)
r = 1
except (Exception, TclError, UnpicklingError), ex:
except (Exception, TclError, UnpicklingError) as ex:
traceback.print_exc()
cs.error = 1
# restore settings
@ -1237,7 +1237,7 @@ Please select a %s type %s.
def getAllUserNames(self):
names = []
for n in self.stats.games_stats.keys():
for n in list(self.stats.games_stats.keys()):
if n is None: # demo
continue
if self.stats.games_stats[n]:
@ -1258,7 +1258,7 @@ Please select a %s type %s.
if not dir or not os.path.isdir(dir):
return
names = os.listdir(dir)
names = map(os.path.normcase, names)
names = list(map(os.path.normcase, names))
names.sort()
for name in names:
m = re.search(r"^(.+)\.py$", name)
@ -1266,7 +1266,7 @@ Please select a %s type %s.
if m and os.path.isfile(n):
try:
loadGame(m.group(1), n)
except Exception, ex:
except Exception as ex:
if DEBUG:
traceback.print_exc()
print_err(_("error loading plugin %s: %s") % (n, ex))
@ -1439,10 +1439,10 @@ Please select a %s type %s.
print_err('fail _readCardsetConfig: %s %s'
% (d, f1))
pass
except Exception, err:
except Exception as err:
##traceback.print_exc()
pass
except EnvironmentError, ex:
except EnvironmentError as ex:
pass
# register cardsets
for obj in found:
@ -1493,7 +1493,7 @@ Please select a %s type %s.
if key not in t:
t[key] = 1
found.append((n, tile))
except EnvironmentError, ex:
except EnvironmentError as ex:
pass
# register tiles
found.sort()
@ -1517,7 +1517,7 @@ Please select a %s type %s.
names = []
if dir and os.path.isdir(dir):
names = os.listdir(dir)
names = map(os.path.normcase, names)
names = list(map(os.path.normcase, names))
names.sort()
for name in names:
if not name or not ext_re.search(name):
@ -1534,7 +1534,7 @@ Please select a %s type %s.
if key not in t:
t[key] = 1
found.append((n, obj))
except EnvironmentError, ex:
except EnvironmentError as ex:
pass
# register songs
found.sort()

View file

@ -16,7 +16,7 @@
# http://lists.sourceforge.net/lists/listinfo/configobj-develop
# Comments, suggestions and bug reports welcome.
from __future__ import generators
import sys
INTP_VER = sys.version_info[:2]
@ -89,7 +89,7 @@ BOM_SET = {
}
try:
from validate import VdtMissingValue
from .validate import VdtMissingValue
except ImportError:
VdtMissingValue = None
@ -176,7 +176,7 @@ class Builder:
return m(o)
def build_List(self, o):
return map(self.build, o.getChildren())
return list(map(self.build, o.getChildren()))
def build_Const(self, o):
return o.value
@ -185,7 +185,7 @@ class Builder:
d = {}
i = iter(map(self.build, o.getChildren()))
for el in i:
d[el] = i.next()
d[el] = next(i)
return d
def build_Tuple(self, o):
@ -203,7 +203,7 @@ class Builder:
raise UnknownType('Undefined Name')
def build_Add(self, o):
real, imag = map(self.build_Const, o.getChildren())
real, imag = list(map(self.build_Const, o.getChildren()))
try:
real = float(real)
except TypeError:
@ -320,7 +320,7 @@ class InterpolationEngine(object):
This is similar to a depth-first-search algorithm.
"""
# Have we been here already?
if backtrail.has_key((key, section.name)):
if (key, section.name) in backtrail:
# Yes - infinite loop detected
raise InterpolationLoopError(key)
# Place a marker on our backtrail so we won't come back here again
@ -549,9 +549,9 @@ class Section(dict):
creating a new sub-section.
"""
if not isinstance(key, StringTypes):
raise ValueError, 'The key "%s" is not a string.' % key
raise ValueError('The key "%s" is not a string.' % key)
# add the comment
if not self.comments.has_key(key):
if key not in self.comments:
self.comments[key] = []
self.inline_comments[key] = ''
# remove the entry from defaults
@ -559,13 +559,13 @@ class Section(dict):
self.defaults.remove(key)
#
if isinstance(value, Section):
if not self.has_key(key):
if key not in self:
self.sections.append(key)
dict.__setitem__(self, key, value)
elif isinstance(value, dict) and not unrepr:
# First create the new depth level,
# then create the section
if not self.has_key(key):
if key not in self:
self.sections.append(key)
new_depth = self.depth + 1
dict.__setitem__(
@ -578,7 +578,7 @@ class Section(dict):
indict=value,
name=key))
else:
if not self.has_key(key):
if key not in self:
self.scalars.append(key)
if not self.main.stringify:
if isinstance(value, StringTypes):
@ -586,10 +586,10 @@ class Section(dict):
elif isinstance(value, (list, tuple)):
for entry in value:
if not isinstance(entry, StringTypes):
raise TypeError, (
raise TypeError(
'Value is not a string "%s".' % entry)
else:
raise TypeError, 'Value is not a string "%s".' % value
raise TypeError('Value is not a string "%s".' % value)
dict.__setitem__(self, key, value)
def __delitem__(self, key):
@ -635,7 +635,7 @@ class Section(dict):
"""Pops the first (key,val)"""
sequence = (self.scalars + self.sections)
if not sequence:
raise KeyError, ": 'popitem(): dictionary is empty'"
raise KeyError(": 'popitem(): dictionary is empty'")
key = sequence[0]
val = self[key]
del self[key]
@ -666,7 +666,7 @@ class Section(dict):
def items(self):
""" """
return zip((self.scalars + self.sections), self.values())
return list(zip((self.scalars + self.sections), list(self.values())))
def keys(self):
""" """
@ -678,7 +678,7 @@ class Section(dict):
def iteritems(self):
""" """
return iter(self.items())
return iter(list(self.items()))
def iterkeys(self):
""" """
@ -688,7 +688,7 @@ class Section(dict):
def itervalues(self):
""" """
return iter(self.values())
return iter(list(self.values()))
def __repr__(self):
return '{%s}' % ', '.join([('%s: %s' % (repr(key), repr(self[key])))
@ -744,7 +744,7 @@ class Section(dict):
>>> c2
{'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}}
"""
for key, val in indict.items():
for key, val in list(indict.items()):
if (key in self and isinstance(self[key], dict) and
isinstance(val, dict)):
self[key].merge(val)
@ -765,7 +765,7 @@ class Section(dict):
elif oldkey in self.sections:
the_list = self.sections
else:
raise KeyError, 'Key "%s" not found.' % oldkey
raise KeyError('Key "%s" not found.' % oldkey)
pos = the_list.index(oldkey)
#
val = self[oldkey]
@ -1144,9 +1144,9 @@ class ConfigObj(Section):
Section.__init__(self, self, 0, self)
#
defaults = OPTION_DEFAULTS.copy()
for entry in options.keys():
if entry not in defaults.keys():
raise TypeError, 'Unrecognised option "%s".' % entry
for entry in list(options.keys()):
if entry not in list(defaults.keys()):
raise TypeError('Unrecognised option "%s".' % entry)
# TODO: check the values too.
#
# Add any explicit options to the defaults
@ -1180,7 +1180,7 @@ class ConfigObj(Section):
infile = open(infile).read() or []
elif self.file_error:
# raise an error if the file doesn't exist
raise IOError, 'Config file not found: "%s".' % self.filename
raise IOError('Config file not found: "%s".' % self.filename)
else:
# file doesn't already exist
if self.create_empty:
@ -1212,7 +1212,7 @@ class ConfigObj(Section):
# needs splitting into lines - but needs doing *after* decoding
# in case it's not an 8 bit encoding
else:
raise TypeError, ('infile must be a filename,'
raise TypeError('infile must be a filename,'
' file like object, or list of lines.')
#
if infile:
@ -1304,7 +1304,7 @@ class ConfigObj(Section):
enc = BOM_LIST[self.encoding.lower()]
if enc == 'utf_16':
# For UTF16 we try big endian and little endian
for BOM, (encoding, final_encoding) in BOMS.items():
for BOM, (encoding, final_encoding) in list(BOMS.items()):
if not final_encoding:
# skip UTF8
continue
@ -1334,7 +1334,7 @@ class ConfigObj(Section):
return self._decode(infile, self.encoding)
#
# No encoding specified - so we need to check for UTF8/UTF16
for BOM, (encoding, final_encoding) in BOMS.items():
for BOM, (encoding, final_encoding) in list(BOMS.items()):
if not line.startswith(BOM):
continue
else:
@ -1382,7 +1382,7 @@ class ConfigObj(Section):
# NOTE: Could raise a ``UnicodeDecodeError``
return infile.decode(encoding).splitlines(True)
for i, line in enumerate(infile):
if not isinstance(line, unicode):
if not isinstance(line, str):
# NOTE: The isinstance test here handles mixed lists of unicode/string
# NOTE: But the decode will break on any non-string values
# NOTE: Or could raise a ``UnicodeDecodeError``
@ -1473,7 +1473,7 @@ class ConfigObj(Section):
NestingError, infile, cur_index)
#
sect_name = self._unquote(sect_name)
if parent.has_key(sect_name):
if sect_name in parent:
self._handle_error(
'Duplicate section name at line %s.',
DuplicateError, infile, cur_index)
@ -1519,7 +1519,7 @@ class ConfigObj(Section):
comment = ''
try:
value = unrepr(value)
except Exception, e:
except Exception as e:
if type(e) == UnknownType:
msg = 'Unknown name or type in value at line %s.'
else:
@ -1532,7 +1532,7 @@ class ConfigObj(Section):
comment = ''
try:
value = unrepr(value)
except Exception, e:
except Exception as e:
if isinstance(e, UnknownType):
msg = 'Unknown name or type in value at line %s.'
else:
@ -1551,7 +1551,7 @@ class ConfigObj(Section):
continue
#
key = self._unquote(key)
if this_section.has_key(key):
if key in this_section:
self._handle_error(
'Duplicate keyword name at line %s.',
DuplicateError, infile, cur_index)
@ -1653,7 +1653,7 @@ class ConfigObj(Section):
if self.stringify:
value = str(value)
else:
raise TypeError, 'Value "%s" is not a string.' % value
raise TypeError('Value "%s" is not a string.' % value)
squot = "'%s'"
dquot = '"%s"'
noquot = "%s"
@ -1670,7 +1670,7 @@ class ConfigObj(Section):
# for normal values either single or double quotes will do
elif '\n' in value:
# will only happen if multiline is off - e.g. '\n' in key
raise ConfigObjError, ('Value "%s" cannot be safely quoted.' %
raise ConfigObjError('Value "%s" cannot be safely quoted.' %
value)
elif ((value[0] not in wspace_plus) and
(value[-1] not in wspace_plus) and
@ -1678,7 +1678,7 @@ class ConfigObj(Section):
quot = noquot
else:
if ("'" in value) and ('"' in value):
raise ConfigObjError, (
raise ConfigObjError(
'Value "%s" cannot be safely quoted.' % value)
elif '"' in value:
quot = squot
@ -1689,7 +1689,7 @@ class ConfigObj(Section):
else:
# if value has '\n' or "'" *and* '"', it will need triple quotes
if (value.find('"""') != -1) and (value.find("'''") != -1):
raise ConfigObjError, (
raise ConfigObjError(
'Value "%s" cannot be safely quoted.' % value)
if value.find('"""') == -1:
quot = tdquot
@ -1787,11 +1787,11 @@ class ConfigObj(Section):
raise_errors=True,
file_error=True,
list_values=False)
except ConfigObjError, e:
except ConfigObjError as e:
# FIXME: Should these errors have a reference
# to the already parsed ConfigObj ?
raise ConfigspecError('Parsing configspec failed: %s' % e)
except IOError, e:
except IOError as e:
raise IOError('Reading configspec failed: %s' % e)
self._set_configspec_value(configspec, self)
@ -1821,7 +1821,7 @@ class ConfigObj(Section):
section._cs_section_comments[entry] = configspec.comments[entry]
section._cs_section_inline_comments[entry] = (
configspec.inline_comments[entry])
if not section.has_key(entry):
if entry not in section:
section[entry] = {}
self._set_configspec_value(configspec[entry], section[entry])
@ -1852,7 +1852,7 @@ class ConfigObj(Section):
#
section.configspec = scalars
for entry in sections:
if not section.has_key(entry):
if entry not in section:
section[entry] = {}
self._handle_repeat(section[entry], sections[entry])
@ -2029,7 +2029,7 @@ class ConfigObj(Section):
"""
if section is None:
if self.configspec is None:
raise ValueError, 'No configspec supplied.'
raise ValueError('No configspec supplied.')
if preserve_errors:
if VdtMissingValue is None:
raise ImportError('Missing validate module.')
@ -2078,7 +2078,7 @@ class ConfigObj(Section):
val,
missing=missing
)
except validator.baseErrorClass, e:
except validator.baseErrorClass as e:
if not preserve_errors or isinstance(e, VdtMissingValue):
out[entry] = False
else:
@ -2262,7 +2262,7 @@ def flatten_errors(cfg, res, levels=None, results=None):
if levels:
levels.pop()
return results
for (key, val) in res.items():
for (key, val) in list(res.items()):
if val == True:
continue
if isinstance(cfg.get(key), dict):

View file

@ -167,7 +167,7 @@ if INTP_VER < (2, 2):
raise RuntimeError("Python v.2.2 or later needed")
import re
StringTypes = (str, unicode)
StringTypes = (str, str)
_list_arg = re.compile(r'''
@ -289,7 +289,7 @@ def dottedQuadToNum(ip):
except socket.error:
# bug in inet_aton, corrected in Python 2.3
if ip.strip() == '255.255.255.255':
return 0xFFFFFFFFL
return 0xFFFFFFFF
else:
raise ValueError('Not a good dotted-quad IP: %s' % ip)
return
@ -322,7 +322,7 @@ def numToDottedQuad(num):
# no need to intercept here, 4294967295L is fine
try:
return socket.inet_ntoa(
struct.pack('!L', long(num)))
struct.pack('!L', int(num)))
except (socket.error, struct.error, OverflowError):
raise ValueError('Not a good numeric IP: %s' % num)
@ -686,10 +686,10 @@ def _is_num_param(names, values, to_float=False):
for (name, val) in zip(names, values):
if val is None:
out_params.append(val)
elif isinstance(val, (int, long, float, StringTypes)):
elif isinstance(val, (int, float, StringTypes)):
try:
out_params.append(fun(val))
except ValueError, e:
except ValueError as e:
raise VdtParamError(name, val)
else:
raise VdtParamError(name, val)
@ -743,7 +743,7 @@ def is_integer(value, min=None, max=None):
"""
# print value, type(value)
(min_val, max_val) = _is_num_param(('min', 'max'), (min, max))
if not isinstance(value, (int, long, StringTypes)):
if not isinstance(value, (int, StringTypes)):
raise VdtTypeError(value)
if isinstance(value, StringTypes):
# if it's a string - does it represent an integer ?
@ -794,7 +794,7 @@ def is_float(value, min=None, max=None):
"""
(min_val, max_val) = _is_num_param(
('min', 'max'), (min, max), to_float=True)
if not isinstance(value, (int, long, float, StringTypes)):
if not isinstance(value, (int, float, StringTypes)):
raise VdtTypeError(value)
if not isinstance(value, float):
# if it's a string - does it represent a float ?
@ -1176,7 +1176,7 @@ def is_mixed_list(value, *args):
raise VdtValueTooLongError(value)
try:
return [fun_dict[arg](val) for arg, val in zip(args, value)]
except KeyError, e:
except KeyError as e:
raise VdtParamError('mixed_list', e)
def is_option(value, *options):

View file

@ -37,7 +37,7 @@ from pysollib.wizardutil import WizardWidgets
def get_settings(ss):
s = {}
for w in WizardWidgets:
if isinstance(w, basestring):
if isinstance(w, str):
continue
if w.var_name in ss:
v = ss[w.var_name]

View file

@ -30,7 +30,7 @@ import traceback
from pysollib.mygettext import _, n_
from gettext import ungettext
from cStringIO import StringIO
from io import StringIO
# PySol imports
from pysollib.mfxutil import Pickler, Unpickler, UnpicklingError
@ -765,7 +765,7 @@ class Game:
state = self.random.getstate()
self.app.gamerandom.setstate(state)
# we want at least 17 digits
seed = self.app.gamerandom.randrange(10000000000000000L,
seed = self.app.gamerandom.randrange(10000000000000000,
PysolRandom.MAX_SEED)
self.random = PysolRandom(seed)
self.random.origin = self.random.ORIGIN_RANDOM
@ -810,7 +810,7 @@ class Game:
else:
# new group
sg[s] = [s.id]
sg = sg.values()
sg = list(sg.values())
self.sn_groups = sg
##print sg
@ -1017,13 +1017,13 @@ class Game:
if self.preview:
return
tb, sb = self.app.toolbar, self.app.statusbar
for k, v in kw.items():
for k, v in list(kw.items()):
if k == "gamenumber":
if v is None:
if sb: sb.updateText(gamenumber="")
#self.top.wm_title("%s - %s" % (TITLE, self.getTitleName()))
continue
if isinstance(v, basestring):
if isinstance(v, str):
if sb: sb.updateText(gamenumber=v)
#self.top.wm_title("%s - %s %s" % (TITLE,
# self.getTitleName(), v))
@ -1057,7 +1057,7 @@ class Game:
if v is None:
if tb: tb.updateText(player=_("Player\n"))
continue
if isinstance(v, basestring):
if isinstance(v, str):
if tb:
#if self.app.opt.toolbar_size:
if self.app.toolbar.getSize():
@ -1076,7 +1076,7 @@ class Game:
if k == "time":
if v is None:
if sb: sb.updateText(time='')
if isinstance(v, basestring):
if isinstance(v, str):
if sb: sb.updateText(time=v)
continue
if k == 'stuck':
@ -1508,7 +1508,7 @@ class Game:
cards = self.cards[:]
scards = []
ncards = min(10, len(cards))
for i in xrange(ncards):
for i in range(ncards):
c = self.app.miscrandom.choice(cards)
scards.append(c)
cards.remove(c)
@ -2342,9 +2342,9 @@ Congratulations, you did it !
if DEBUG:
if not to_stack.acceptsCards(
from_stack, from_stack.cards[-ncards:]):
print '*fail accepts cards*', from_stack, to_stack, ncards
print('*fail accepts cards*', from_stack, to_stack, ncards)
if not from_stack.canMoveCards(from_stack.cards[-ncards:]):
print '*fail move cards*', from_stack, ncards
print('*fail move cards*', from_stack, ncards)
##assert from_stack.canMoveCards(from_stack.cards[-ncards:]) # FIXME: Pyramid
assert to_stack.acceptsCards(from_stack, from_stack.cards[-ncards:])
if sleep <= 0.0:
@ -3027,7 +3027,7 @@ Congratulations, you did it !
try:
game = self._loadGame(filename, self.app)
game.gstats.holded = 0
except AssertionError, ex:
except AssertionError as ex:
self.updateMenus()
self.setCursor(cursor=self.app.top_cursor)
d = MfxMessageDialog(self.top, title=_("Load game error"), bitmap="error",
@ -3037,7 +3037,7 @@ Error while loading game.
Probably the game file is damaged,
but this could also be a bug you might want to report."""))
traceback.print_exc()
except UnpicklingError, ex:
except UnpicklingError as ex:
self.updateMenus()
self.setCursor(cursor=self.app.top_cursor)
d = MfxExceptionDialog(self.top, ex, title=_("Load game error"),
@ -3073,7 +3073,7 @@ Please report this bug."""))
self.setCursor(cursor=CURSOR_WATCH)
try:
self._saveGame(filename, protocol)
except Exception, ex:
except Exception as ex:
self.setCursor(cursor=self.app.top_cursor)
d = MfxExceptionDialog(self.top, ex, title=_("Save game error"),
text=_("Error while saving game"))
@ -3141,7 +3141,7 @@ in the current implementation.''') % version)
game.version = version
game.version_tuple = version_tuple
#
initial_seed = pload(long)
initial_seed = pload(int)
if initial_seed <= 32000:
game.random = LCRandom31(initial_seed)
else:

View file

@ -403,18 +403,18 @@ class GameInfo(Struct):
# keyword arguments:
si={}, category=0,
short_name=None, altnames=(),
suits=range(4), ranks=range(13), trumps=(),
suits=list(range(4)), ranks=list(range(13)), trumps=(),
rules_filename=None,
):
#
def to_unicode(s):
if isinstance(s, unicode):
if isinstance(s, str):
return s
try:
s = unicode(s, 'utf-8')
except UnicodeDecodeError, err:
s = str(s, 'utf-8')
except UnicodeDecodeError as err:
print_err(err)
s = unicode(s, 'utf-8', 'ignore')
s = str(s, 'utf-8', 'ignore')
return s
ncards = decks * (len(suits) * len(ranks) + len(trumps))
game_flags = game_type & ~1023
@ -429,7 +429,7 @@ class GameInfo(Struct):
short_name = to_unicode(short_name)
if pysollib.settings.TRANSLATE_GAME_NAMES:
short_name = _(short_name)
if isinstance(altnames, basestring):
if isinstance(altnames, str):
altnames = (altnames,)
altnames = [to_unicode(n) for n in altnames]
if pysollib.settings.TRANSLATE_GAME_NAMES:
@ -532,7 +532,7 @@ class GameManager:
(gi.name, str(gi.gameclass),
str(gameclass)))
if 1:
for id, game in self.__all_games.items():
for id, game in list(self.__all_games.items()):
if gi.gameclass is game.gameclass:
raise GameInfoException(
"duplicate game class %s: %s and %s" %
@ -587,11 +587,11 @@ class GameManager:
def getAllGames(self):
##return self.__all_games
return self.__games.values()
return list(self.__games.values())
def getGamesIdSortedById(self):
if self.__games_by_id is None:
l = self.__games.keys()
l = list(self.__games.keys())
l.sort()
self.__games_by_id = tuple(l)
return self.__games_by_id
@ -599,7 +599,7 @@ class GameManager:
def getGamesIdSortedByName(self):
if self.__games_by_name is None:
l1, l2, l3 = [], [], []
for id, gi in self.__games.items():
for id, gi in list(self.__games.items()):
name = gi.name #.lower()
l1.append((name, id))
if gi.name != gi.short_name:

View file

@ -20,67 +20,67 @@
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
##---------------------------------------------------------------------------##
import acesup
import algerian
import auldlangsyne
import bakersdozen
import bakersgame
import beleagueredcastle
import bisley
import braid
import bristol
import buffalobill
import calculation
import camelot
import canfield
import capricieuse
import curdsandwhey
import daddylonglegs
import dieboesesieben
import diplomat
import doublets
import eiffeltower
import fan
import fortythieves
import freecell
import glenwood
import golf
import grandduchess
import grandfathersclock
import gypsy
import harp
import headsandtails
import katzenschwanz
import klondike
import labyrinth
import larasgame
import matriarchy
import montana
import montecarlo
import napoleon
import needle
import numerica
import osmosis
import parallels
import pasdedeux
import picturegallery
import pileon
import pushpin
import pyramid
import royalcotillion
import royaleast
import sanibel
import siebenbisas
import simplex
import spider
import sthelena
import sultan
import takeaway
import terrace
import threepeaks
import tournament
import unionsquare
import wavemotion
import windmill
import yukon
import zodiac
from . import acesup
from . import algerian
from . import auldlangsyne
from . import bakersdozen
from . import bakersgame
from . import beleagueredcastle
from . import bisley
from . import braid
from . import bristol
from . import buffalobill
from . import calculation
from . import camelot
from . import canfield
from . import capricieuse
from . import curdsandwhey
from . import daddylonglegs
from . import dieboesesieben
from . import diplomat
from . import doublets
from . import eiffeltower
from . import fan
from . import fortythieves
from . import freecell
from . import glenwood
from . import golf
from . import grandduchess
from . import grandfathersclock
from . import gypsy
from . import harp
from . import headsandtails
from . import katzenschwanz
from . import klondike
from . import labyrinth
from . import larasgame
from . import matriarchy
from . import montana
from . import montecarlo
from . import napoleon
from . import needle
from . import numerica
from . import osmosis
from . import parallels
from . import pasdedeux
from . import picturegallery
from . import pileon
from . import pushpin
from . import pyramid
from . import royalcotillion
from . import royaleast
from . import sanibel
from . import siebenbisas
from . import simplex
from . import spider
from . import sthelena
from . import sultan
from . import takeaway
from . import terrace
from . import threepeaks
from . import tournament
from . import unionsquare
from . import wavemotion
from . import windmill
from . import yukon
from . import zodiac

View file

@ -34,7 +34,7 @@ from pysollib.game import Game
from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from montecarlo import MonteCarlo_RowStack
from .montecarlo import MonteCarlo_RowStack
# ************************************************************************

View file

@ -34,7 +34,7 @@ from pysollib.game import Game
from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from numerica import Numerica_Hint
from .numerica import Numerica_Hint
# ************************************************************************

View file

@ -35,7 +35,7 @@ from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from pysollib.pysoltk import MfxCanvasText
from numerica import Numerica_Hint
from .numerica import Numerica_Hint
# ************************************************************************

View file

@ -34,7 +34,7 @@ from pysollib.game import Game
from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from gypsy import DieRussische_Foundation
from .gypsy import DieRussische_Foundation
# ************************************************************************

View file

@ -34,7 +34,7 @@ from pysollib.game import Game
from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from gypsy import DieKoenigsbergerin_Talon, DieRussische_Foundation
from .gypsy import DieKoenigsbergerin_Talon, DieRussische_Foundation
# ************************************************************************
# * Die böse Sieben

View file

@ -34,8 +34,8 @@ from pysollib.game import Game
from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from fortythieves import FortyThieves_Hint
from spider import Spider_Hint
from .fortythieves import FortyThieves_Hint
from .spider import Spider_Hint
# ************************************************************************

View file

@ -33,7 +33,7 @@ from pysollib.game import Game
from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from gypsy import DieRussische_Foundation
from .gypsy import DieRussische_Foundation
# ************************************************************************

View file

@ -36,7 +36,7 @@ from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from pysollib.hint import FreeCellType_Hint, FreeCellSolverWrapper
from spider import Spider_AC_Foundation
from .spider import Spider_AC_Foundation
# ************************************************************************

View file

@ -35,7 +35,7 @@ from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from pysollib.pysoltk import MfxCanvasText
from canfield import Canfield_Hint
from .canfield import Canfield_Hint
# ************************************************************************
# * Glenwood

View file

@ -1024,7 +1024,7 @@ class NapoleonLeavesMoscow(NapoleonTakesMoscow):
# * Flake (2 decks)
# ************************************************************************
from pileon import FourByFour_Hint
from .pileon import FourByFour_Hint
class Flake(Game):
Hint_Class = FourByFour_Hint #CautiousDefaultHint

View file

@ -443,7 +443,7 @@ class BigBen(Game):
def _shuffleHook(self, cards):
# move clock cards to top of the Talon (i.e. first cards to be dealt)
C, S, H, D = range(4) # suits
C, S, H, D = list(range(4)) # suits
t = [(1,C), (2,H), (3,S), (4,D), (5,C), (6,H),
(7,S), (8,D), (9,C), (JACK,H), (QUEEN,S), (KING,D)]
clocks = []

View file

@ -36,7 +36,7 @@ from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from pysollib.hint import KlondikeType_Hint, YukonType_Hint
from spider import Spider_SS_Foundation, Spider_RowStack, Spider_Hint
from .spider import Spider_SS_Foundation, Spider_RowStack, Spider_Hint
# ************************************************************************

View file

@ -36,7 +36,7 @@ from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from pysollib.hint import KlondikeType_Hint
from spider import Spider_RowStack, Spider_SS_Foundation, Spider_Hint
from .spider import Spider_RowStack, Spider_SS_Foundation, Spider_Hint
# ************************************************************************

View file

@ -39,7 +39,7 @@ from pysollib.hint import KlondikeType_Hint
from pysollib.hint import FreeCellSolverWrapper
from pysollib.pysoltk import MfxCanvasText
from canfield import CanfieldRush_Talon
from .canfield import CanfieldRush_Talon
# ************************************************************************

View file

@ -20,7 +20,7 @@
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
##---------------------------------------------------------------------------##
import mahjongg1
import mahjongg2
import mahjongg3
import shisensho
from . import mahjongg1
from . import mahjongg2
from . import mahjongg3
from . import shisensho

View file

@ -48,7 +48,7 @@ def factorial(x):
if x <= 1:
return 1
a = 1
for i in xrange(x):
for i in range(x):
a *= (i+1)
return a
@ -461,10 +461,10 @@ class AbstractMahjonggGame(Game):
assert tilemap.get((level, tx, ty+1)) is stack
assert tilemap.get((level, tx+1, ty+1)) is stack
#
above = tuple(filter(None, above.keys()))
below = tuple(filter(None, below.keys()))
left = tuple(filter(None, left.keys()))
right = tuple(filter(None, right.keys()))
above = tuple([_f for _f in list(above.keys()) if _f])
below = tuple([_f for _f in list(below.keys()) if _f])
left = tuple([_f for _f in list(left.keys()) if _f])
right = tuple([_f for _f in list(right.keys()) if _f])
##up = tuple(filter(None, up.keys()))
##bottom = tuple(filter(None, bottom.keys()))
@ -584,7 +584,7 @@ class AbstractMahjonggGame(Game):
c1 = cards[0]
del cards[0]
c2 = None
for i in xrange(len(cards)):
for i in range(len(cards)):
if self.cardsMatch(c1, cards[i]):
c2 = cards[i]
del cards[i]
@ -599,7 +599,7 @@ class AbstractMahjonggGame(Game):
#
i = factorial(len(free_stacks))/2/factorial(len(free_stacks)-2)
old_pairs = []
for j in xrange(i):
for j in range(i):
nc = new_cards[:]
while True:
# create uniq pair
@ -625,7 +625,7 @@ class AbstractMahjonggGame(Game):
if new_cards:
new_cards.reverse()
return new_cards
print 'oops! can\'t create a solvable game'
print('oops! can\'t create a solvable game')
return old_cards
@ -683,7 +683,7 @@ class AbstractMahjonggGame(Game):
c1 = cards[0]
del cards[0]
c2 = None
for i in xrange(len(cards)):
for i in range(len(cards)):
if self.cardsMatch(c1, cards[i]):
c2 = cards[i]
del cards[i]
@ -699,7 +699,7 @@ class AbstractMahjonggGame(Game):
old_pairs = []
i = factorial(len(suitable_stacks))/2/factorial(len(suitable_stacks)-2)
for j in xrange(i):
for j in range(i):
if iters[0] > max_iters:
return None
if time.time() - start_time > max_time:
@ -742,16 +742,16 @@ class AbstractMahjonggGame(Game):
while True:
ret = create_solvable(cards[:], new_cards)
if DEBUG:
print 'create_solvable time:', time.time() - start_time
print('create_solvable time:', time.time() - start_time)
if ret:
ret.reverse()
return ret
if time.time() - start_time > max_time or \
iters[0] <= max_iters:
print 'oops! can\'t create a solvable game'
print('oops! can\'t create a solvable game')
return None
iters = [0]
print 'oops! can\'t create a solvable game'
print('oops! can\'t create a solvable game')
return None
def _mahjonggShuffle(self):
@ -1016,7 +1016,7 @@ def r(id, short_name, name=None, ncards=144, layout=None):
gi = GameInfo(id, gameclass, name,
GI.GT_MAHJONGG, 4*decks, 0, ##GI.SL_MOSTLY_SKILL,
category=GI.GC_MAHJONGG, short_name=short_name,
suits=range(3), ranks=range(ranks), trumps=range(trumps),
suits=list(range(3)), ranks=list(range(ranks)), trumps=list(range(trumps)),
si={"decks": decks, "ncards": ncards})
gi.ncards = ncards
gi.rules_filename = "mahjongg.html"

View file

@ -21,7 +21,7 @@
##
##---------------------------------------------------------------------------##
from mahjongg import r
from .mahjongg import r
# ************************************************************************
# * game definitions

View file

@ -25,7 +25,7 @@
# http://www.kyodai.com/index.en.html
# http://files.cyna.net/layouts.zip
from mahjongg import r
from .mahjongg import r
# ************************************************************************
# * game definitions

View file

@ -21,7 +21,7 @@
##
##---------------------------------------------------------------------------##
from mahjongg import r
from .mahjongg import r
# test
#r(5991, "AAA 1", ncards=4, layout="0daa")

View file

@ -39,7 +39,7 @@ from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from pysollib.pysoltk import MfxCanvasText, MfxCanvasLine
from mahjongg import Mahjongg_RowStack, AbstractMahjonggGame, comp_cardset
from .mahjongg import Mahjongg_RowStack, AbstractMahjonggGame, comp_cardset
# ************************************************************************
@ -113,7 +113,7 @@ class Shisen_RowStack(Mahjongg_RowStack):
dx, dy = x2 - x1, y2 - y1
a = []
for i in xrange(cols+2):
for i in range(cols+2):
a.append([5]*(rows+2))
def can_move(x, y, nx, ny, direct, d, direct_chng_cnt):
@ -344,12 +344,12 @@ class AbstractShisenGame(AbstractMahjonggGame):
self.check_dist = l.CW*l.CW + l.CH*l.CH # see _getClosestStack()
#
self.cols = [[] for i in xrange(cols)]
cl = range(cols)
self.cols = [[] for i in range(cols)]
cl = list(range(cols))
if dx > 0:
cl.reverse()
for col in cl:
for row in xrange(rows):
for row in range(rows):
x = l.XM + dxx + col * cardw
y = l.YM + dyy + row * cardh
stack = self.RowStack_Class(x, y, self)
@ -500,7 +500,7 @@ def r(id, gameclass, name, rules_filename="shisensho.html"):
gi = GameInfo(id, gameclass, name,
GI.GT_SHISEN_SHO, 4*decks, 0, GI.SL_MOSTLY_SKILL,
category=GI.GC_MAHJONGG, short_name=name,
suits=range(3), ranks=range(ranks), trumps=range(trumps),
suits=list(range(3)), ranks=list(range(ranks)), trumps=list(range(trumps)),
si={"decks": decks, "ncards": gameclass.NCARDS})
gi.ncards = gameclass.NCARDS
gi.rules_filename = rules_filename

View file

@ -497,7 +497,7 @@ class Nestor(Game):
if j < 0:
break
j += i*6
k = self.random.choice(range((i+1)*6, 52))
k = self.random.choice(list(range((i+1)*6, 52)))
cards[j], cards[k] = cards[k], cards[j]
cards.reverse()
return cards

View file

@ -37,7 +37,7 @@ from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from pysollib.pysoltk import MfxCanvasText
from braid import Braid_Foundation
from .braid import Braid_Foundation
# ************************************************************************

View file

@ -61,7 +61,7 @@ class PasDeDeux_Hint(AbstractHint):
for r in rows:
r1_d = self.getDistance(r, r.cards[-1])
column, row = r.id % 13, r.id / 13
stack_ids = range(column, 52, 13) + range(13*row, 13*row+13)
stack_ids = list(range(column, 52, 13)) + list(range(13*row, 13*row+13))
for i in stack_ids:
t = self.game.s.rows[i]
if t is r:

View file

@ -553,7 +553,7 @@ registerGame(GameInfo(7, PictureGallery, "Picture Gallery",
altnames=("Die Bildgallerie", "Mod-3") ))
registerGame(GameInfo(397, GreatWheel, "Great Wheel",
GI.GT_2DECK_TYPE, 2, 0, GI.SL_BALANCED,
ranks=range(12) # without Kings
ranks=list(range(12)) # without Kings
))
registerGame(GameInfo(398, MountOlympus, "Mount Olympus",
GI.GT_2DECK_TYPE, 2, 0, GI.SL_BALANCED))

View file

@ -35,7 +35,7 @@ from pysollib.game import Game
from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from unionsquare import UnionSquare_Foundation
from .unionsquare import UnionSquare_Foundation
# ************************************************************************
@ -1342,11 +1342,11 @@ registerGame(GameInfo(97, Carpet, "Carpet",
GI.GT_1DECK_TYPE, 1, 0, GI.SL_MOSTLY_LUCK))
registerGame(GameInfo(391, BritishConstitution, "British Constitution",
GI.GT_2DECK_TYPE, 2, 0, GI.SL_BALANCED,
ranks=range(11), # without Queens and Kings
ranks=list(range(11)), # without Queens and Kings
altnames=("Constitution",) ))
registerGame(GameInfo(392, NewBritishConstitution, "New British Constitution",
GI.GT_2DECK_TYPE | GI.GT_ORIGINAL, 2, 0, GI.SL_BALANCED,
ranks=range(11) # without Queens and Kings
ranks=list(range(11)) # without Queens and Kings
))
registerGame(GameInfo(443, Twenty, "Twenty",
GI.GT_2DECK_TYPE, 2, 0, GI.SL_BALANCED))

View file

@ -20,8 +20,8 @@
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
##---------------------------------------------------------------------------##
import hanoi
import memory
import pegged
import poker
import tarock
from . import hanoi
from . import memory
from . import pegged
from . import poker
from . import tarock

View file

@ -152,20 +152,20 @@ class HanoiSequence(TowerOfHanoy):
# register the game
registerGame(GameInfo(124, TowerOfHanoy, "Tower of Hanoy",
GI.GT_PUZZLE_TYPE, 1, 0, GI.SL_SKILL,
suits=(2,), ranks=range(9)))
suits=(2,), ranks=list(range(9))))
registerGame(GameInfo(207, HanoiPuzzle4, "Hanoi Puzzle 4",
GI.GT_PUZZLE_TYPE, 1, 0, GI.SL_SKILL,
suits=(2,), ranks=range(4),
suits=(2,), ranks=list(range(4)),
rules_filename="hanoipuzzle.html"))
registerGame(GameInfo(208, HanoiPuzzle5, "Hanoi Puzzle 5",
GI.GT_PUZZLE_TYPE, 1, 0, GI.SL_SKILL,
suits=(2,), ranks=range(5),
suits=(2,), ranks=list(range(5)),
rules_filename="hanoipuzzle.html"))
registerGame(GameInfo(209, HanoiPuzzle6, "Hanoi Puzzle 6",
GI.GT_PUZZLE_TYPE, 1, 0, GI.SL_SKILL,
suits=(2,), ranks=range(6),
suits=(2,), ranks=list(range(6)),
rules_filename="hanoipuzzle.html"))
registerGame(GameInfo(769, HanoiSequence, "Hanoi Sequence",
GI.GT_PUZZLE_TYPE, 1, 0, GI.SL_SKILL,
suits=(2,), ranks=range(9)))
suits=(2,), ranks=list(range(9))))

View file

@ -247,7 +247,7 @@ def r(id, gameclass, name):
gi = GameInfo(id, gameclass, name,
GI.GT_PUZZLE_TYPE, 1, 0, GI.SL_SKILL,
category=GI.GC_TRUMP_ONLY,
suits=(), ranks=(), trumps=range(ncards),
suits=(), ranks=(), trumps=list(range(ncards)),
si = {"decks": 1, "ncards": ncards},
rules_filename = "pegged.html")
registerGame(gi)

View file

@ -140,7 +140,7 @@ One Pair'''))
(r[3], r[3+5], r[3+10], r[3+15], r[3+20]),
(r[4], r[4+5], r[4+10], r[4+15], r[4+20]),
]
self.poker_hands = map(tuple, self.poker_hands)
self.poker_hands = list(map(tuple, self.poker_hands))
# define stack-groups
l.defaultStackGroups()

View file

@ -909,7 +909,7 @@ class Nasty(Wicked):
def r(id, gameclass, name, game_type, decks, redeals, skill_level):
game_type = game_type | GI.GT_TAROCK | GI.GT_CONTRIB | GI.GT_ORIGINAL
gi = GameInfo(id, gameclass, name, game_type, decks, redeals, skill_level,
ranks=range(14), trumps=range(22))
ranks=list(range(14)), trumps=list(range(22)))
registerGame(gi)
return gi

View file

@ -1035,7 +1035,7 @@ class Khedive(Game):
x += l.XS
x, y = l.XM+4*l.XS, l.YM
r = range(11)
r = list(range(11))
for i in range(5,0,-1):
for j in r[i:-i]:
x, y = l.XM+(j-0.5)*l.XS, l.YM+(5-i)*l.YS

View file

@ -36,7 +36,7 @@ from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from pysollib.pysoltk import MfxCanvasText
from golf import Golf_Waste, Golf_Hint
from .golf import Golf_Waste, Golf_Hint
# ************************************************************************

View file

@ -20,11 +20,11 @@
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
##---------------------------------------------------------------------------##
import dashavatara
import hanafuda
import hanafuda1
import hexadeck
import larasgame
import matrix
import mughal
import tarock
from . import dashavatara
from . import hanafuda
from . import hanafuda1
from . import hexadeck
from . import larasgame
from . import matrix
from . import mughal
from . import tarock

View file

@ -1267,7 +1267,7 @@ class Dashavatara(Game):
def r(id, gameclass, name, game_type, decks, redeals, skill_level):
game_type = game_type | GI.GT_DASHAVATARA_GANJIFA
gi = GameInfo(id, gameclass, name, game_type, decks, redeals, skill_level,
suits=range(10), ranks=range(12))
suits=list(range(10)), ranks=list(range(12)))
registerGame(gi)
return gi

View file

@ -37,7 +37,7 @@ from pysollib.layout import Layout
from pysollib.hint import FreeCellType_Hint
from pysollib.pysoltk import MfxCanvasText
from hanafuda_common import *
from .hanafuda_common import *
# ************************************************************************
@ -1025,7 +1025,7 @@ class Paulownia(AbstractFlowerGame):
def r(id, gameclass, name, game_type, decks, redeals, skill_level):
game_type = game_type | GI.GT_HANAFUDA
gi = GameInfo(id, gameclass, name, game_type, decks, redeals, skill_level,
suits=range(12), ranks=range(4))
suits=list(range(12)), ranks=list(range(4)))
registerGame(gi)
return gi

View file

@ -37,7 +37,7 @@ from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from pysollib.pysoltk import MfxCanvasText
from hanafuda_common import *
from .hanafuda_common import *
# ************************************************************************
# * Paulownia
@ -590,7 +590,7 @@ class FlowerArrangement_TableauStack(Flower_OpenStack):
if not self.basicAcceptsCards(from_stack, cards):
return 0
# check that the base card is correct
suits = range(self.cap.mod, (self.cap.mod + 4))
suits = list(range(self.cap.mod, (self.cap.mod + 4)))
if self.cards and (self.cards[0].rank == 3
and self.cards[-1].suit in suits):
return self.isHanafudaSequence([self.cards[-1], cards[0]])
@ -693,7 +693,7 @@ class FlowerArrangement(Game):
def r(id, gameclass, name, game_type, decks, redeals, skill_level):
game_type = game_type | GI.GT_HANAFUDA
gi = GameInfo(id, gameclass, name, game_type, decks, redeals, skill_level,
suits=range(12), ranks=range(4))
suits=list(range(12)), ranks=list(range(4)))
registerGame(gi)
return gi

View file

@ -1379,7 +1379,7 @@ class Snakestone(Convolution):
def r(id, gameclass, name, game_type, decks, redeals, skill_level):
game_type = game_type | GI.GT_HEXADECK
gi = GameInfo(id, gameclass, name, game_type, decks, redeals, skill_level,
suits=range(4), ranks=range(16), trumps=range(4))
suits=list(range(4)), ranks=list(range(16)), trumps=list(range(4)))
registerGame(gi)
return gi

View file

@ -284,37 +284,37 @@ class DoubleDojoujisGame(DojoujisGame):
# register the game
registerGame(GameInfo(13001, KatrinasGame, "Katrina's Game",
GI.GT_TAROCK, 2, 1, GI.SL_BALANCED,
ranks = range(14), trumps = range(22)))
ranks = list(range(14)), trumps = list(range(22))))
registerGame(GameInfo(13002, BridgetsGame, "Bridget's Game",
GI.GT_HEXADECK, 2, 1, GI.SL_BALANCED,
ranks = range(16), trumps = range(4)))
ranks = list(range(16)), trumps = list(range(4))))
registerGame(GameInfo(13003, FatimehsGame, "Fatimeh's Game",
GI.GT_MUGHAL_GANJIFA, 1, 2, GI.SL_BALANCED,
suits = range(8), ranks = range(12)))
suits = list(range(8)), ranks = list(range(12))))
registerGame(GameInfo(13004, KalisGame, "Kali's Game",
GI.GT_DASHAVATARA_GANJIFA, 1, 2, GI.SL_BALANCED,
suits = range(10), ranks = range(12)))
suits = list(range(10)), ranks = list(range(12))))
registerGame(GameInfo(13005, DojoujisGame, "Dojouji's Game",
GI.GT_HANAFUDA, 2, 0, GI.SL_BALANCED,
suits = range(12), ranks = range(4)))
suits = list(range(12)), ranks = list(range(4))))
registerGame(GameInfo(13008, RelaxedKatrinasGame, "Katrina's Game Relaxed",
GI.GT_TAROCK, 2, 1, GI.SL_BALANCED,
ranks = range(14), trumps = range(22)))
ranks = list(range(14)), trumps = list(range(22))))
registerGame(GameInfo(13009, DoubleKatrinasGame, "Katrina's Game Doubled",
GI.GT_TAROCK, 4, 2, GI.SL_BALANCED,
ranks = range(14), trumps = range(22)))
ranks = list(range(14)), trumps = list(range(22))))
registerGame(GameInfo(13010, DoubleBridgetsGame, "Bridget's Game Doubled",
GI.GT_HEXADECK, 4, 2, GI.SL_BALANCED,
ranks = range(16), trumps = range(4)))
ranks = list(range(16)), trumps = list(range(4))))
registerGame(GameInfo(13011, RelaxedKalisGame, "Kali's Game Relaxed",
GI.GT_DASHAVATARA_GANJIFA, 1, 2, GI.SL_BALANCED,
suits = range(10), ranks = range(12)))
suits = list(range(10)), ranks = list(range(12))))
registerGame(GameInfo(13012, DoubleKalisGame, "Kali's Game Doubled",
GI.GT_DASHAVATARA_GANJIFA, 2, 3, GI.SL_BALANCED,
suits = range(10), ranks = range(12)))
suits = list(range(10)), ranks = list(range(12))))
registerGame(GameInfo(13013, RelaxedFatimehsGame, "Fatimeh's Game Relaxed",
GI.GT_MUGHAL_GANJIFA, 1, 2, GI.SL_BALANCED,
suits = range(8), ranks = range(12)))
suits = list(range(8)), ranks = list(range(12))))
registerGame(GameInfo(13014, DoubleDojoujisGame, "Dojouji's Game Doubled",
GI.GT_HANAFUDA, 4, 0, GI.SL_BALANCED,
suits = range(12), ranks = range(4)))
suits = list(range(12)), ranks = list(range(4))))

View file

@ -239,7 +239,7 @@ def r(id, gameclass, short_name):
gi = GameInfo(id, gameclass, name,
GI.GT_MATRIX, 1, 0, GI.SL_SKILL,
category=GI.GC_TRUMP_ONLY, short_name=short_name,
suits=(), ranks=(), trumps=range(ncards),
suits=(), ranks=(), trumps=list(range(ncards)),
si = {"decks": 1, "ncards": ncards})
gi.ncards = ncards
gi.rules_filename = "matrix.html"

View file

@ -1146,7 +1146,7 @@ class AshtaDikapala(Game):
def r(id, gameclass, name, game_type, decks, redeals, skill_level):
game_type = game_type | GI.GT_MUGHAL_GANJIFA
gi = GameInfo(id, gameclass, name, game_type, decks, redeals, skill_level,
suits=range(8), ranks=range(12))
suits=list(range(8)), ranks=list(range(12)))
registerGame(gi)
return gi

View file

@ -267,7 +267,7 @@ class LeGrandeTeton(ThreePeaksNoScore):
def r(id, gameclass, name, game_type, decks, redeals, skill_level):
game_type = game_type | GI.GT_TAROCK | GI.GT_CONTRIB | GI.GT_ORIGINAL
gi = GameInfo(id, gameclass, name, game_type, decks, redeals, skill_level,
ranks=range(14), trumps=range(22))
ranks=list(range(14)), trumps=list(range(22)))
registerGame(gi)
return gi

View file

@ -34,7 +34,7 @@ from pysollib.game import Game
from pysollib.layout import Layout
from pysollib.hint import AbstractHint, DefaultHint, CautiousDefaultHint
from golf import BlackHole_Foundation
from .golf import BlackHole_Foundation
# ************************************************************************

View file

@ -39,7 +39,7 @@ from pysollib.hint import YukonType_Hint
from pysollib.hint import FreeCellSolverWrapper
from pysollib.pysoltk import MfxCanvasText
from spider import Spider_SS_Foundation
from .spider import Spider_SS_Foundation
# ************************************************************************

View file

@ -828,7 +828,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint):
board = board + b.strip() + '\n'
#
if DEBUG:
print '--------------------\n', board, '--------------------'
print('--------------------\n', board, '--------------------')
#
args = []
##args += ['-sam', '-p', '-opt', '--display-10-as-t']
@ -857,7 +857,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint):
command = FCS_COMMAND+' '+' '.join([str(i) for i in args])
if DEBUG:
print command
print(command)
kw = {'shell': True,
'stdin': subprocess.PIPE,
'stdout': subprocess.PIPE,
@ -884,7 +884,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint):
for s in pout:
if DEBUG >= 5:
print s,
print(s, end=' ')
if self.colonPrefixMatch('Iteration', s):
iter = self._v
@ -904,7 +904,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint):
hints = []
for s in pout:
if DEBUG:
print s,
print(s, end=' ')
if self._determineIfSolverState(s):
next
m = re.match('Total number of states checked is (\d+)\.', s)
@ -963,7 +963,7 @@ class FreeCellSolver_Hint(Base_Solver_Hint):
#
if DEBUG:
print 'time:', time.time()-start_time
print('time:', time.time()-start_time)
##print perr.read(),
self.hints = hints
@ -1004,7 +1004,7 @@ class BlackHoleSolver_Hint(Base_Solver_Hint):
board += b.strip() + '\n'
#
if DEBUG:
print '--------------------\n', board, '--------------------'
print('--------------------\n', board, '--------------------')
#
args = []
##args += ['-sam', '-p', '-opt', '--display-10-as-t']
@ -1014,7 +1014,7 @@ class BlackHoleSolver_Hint(Base_Solver_Hint):
command = self.BLACK_HOLE_SOLVER_COMMAND+' '+' '.join([str(i) for i in args])
if DEBUG:
print command
print(command)
kw = {'shell': True,
'stdin': subprocess.PIPE,
'stdout': subprocess.PIPE,
@ -1037,7 +1037,7 @@ class BlackHoleSolver_Hint(Base_Solver_Hint):
for s in pout:
if DEBUG >= 5:
print s,
print(s, end=' ')
m = re.search('^(Intractable!|Unsolved!|Solved!)\n', s)
if m:
@ -1057,7 +1057,7 @@ class BlackHoleSolver_Hint(Base_Solver_Hint):
hints = []
for s in pout:
if DEBUG:
print s,
print(s, end=' ')
m = re.match('Total number of states checked is (\d+)\.', s)
if m:
iter = int(m.group(1))
@ -1087,7 +1087,7 @@ class BlackHoleSolver_Hint(Base_Solver_Hint):
#
if DEBUG:
print 'time:', time.time()-start_time
print('time:', time.time()-start_time)
##print perr.read(),
self.hints = hints

View file

@ -424,7 +424,7 @@ class Images:
self._pil_shadow = {}
def reset(self):
print 'Image.reset'
print('Image.reset')
self.resize(1, 1)

View file

@ -61,13 +61,13 @@ def init():
## debug
if 'PYSOL_CHECK_GAMES' in os.environ or 'PYSOL_DEBUG' in os.environ:
pysollib.settings.CHECK_GAMES = True
print 'PySol debugging: set CHECK_GAMES to True'
print('PySol debugging: set CHECK_GAMES to True')
if 'PYSOL_DEBUG' in os.environ:
try:
pysollib.settings.DEBUG = int(os.environ['PYSOL_DEBUG'])
except:
pysollib.settings.DEBUG = 1
print 'PySol debugging: set DEBUG to', pysollib.settings.DEBUG
print('PySol debugging: set DEBUG to', pysollib.settings.DEBUG)
## init toolkit
if '--gtk' in sys.argv:
@ -82,13 +82,13 @@ def init():
pysollib.settings.USE_TILE = True
sys.argv.remove('--tile')
if pysollib.settings.TOOLKIT == 'tk':
import Tkinter
root = Tkinter.Tk(className=pysollib.settings.TITLE)
import tkinter
root = tkinter.Tk(className=pysollib.settings.TITLE)
root.withdraw()
if Tkinter.TkVersion < 8.4:
if tkinter.TkVersion < 8.4:
# we need unicode support
sys.exit("%s needs Tcl/Tk 8.4 or better (you have %s)" %
(pysollib.settings.TITLE, str(Tkinter.TkVersion)))
(pysollib.settings.TITLE, str(tkinter.TkVersion)))
pysollib.settings.WIN_SYSTEM = root.tk.call('tk', 'windowingsystem')
if pysollib.settings.WIN_SYSTEM == 'aqua':
# TkAqua displays the console automatically in application
@ -101,13 +101,13 @@ def init():
pysollib.settings.USE_TILE = False
try:
root.tk.eval('package require tile 0.7.8')
except Tkinter.TclError:
except tkinter.TclError:
pass
else:
pysollib.settings.USE_TILE = True
# "can't invoke event <<ThemeChanged>>: application has been destroyed"
#root.destroy()
Tkinter._default_root = None
tkinter._default_root = None
# check FreeCell-Solver
pysollib.settings.USE_FREECELL_SOLVER = False

View file

@ -25,7 +25,7 @@ A number of function that enhance PySol on MacOSX when it used as a normal
GUI application (as opposed to an X11 application).
"""
import sys
from Tkinter import Menu, Text, TclError
from tkinter import Menu, Text, TclError
def runningAsOSXApp():
""" Returns True iff running from the PySol.app bundle on OSX """

View file

@ -77,7 +77,7 @@ def parse_option(argv):
"nosound",
"sound-mod=",
"help"])
except getopt.GetoptError, err:
except getopt.GetoptError as err:
print_err(_("%s\ntry %s --help for more information") %
(err, prog_name), 0)
return None
@ -107,7 +107,7 @@ def parse_option(argv):
opts["sound-mod"] = i[1]
if opts["help"]:
print _("""Usage: %s [OPTIONS] [FILE]
print(_("""Usage: %s [OPTIONS] [FILE]
-g --game=GAMENAME start game GAMENAME
-i --gameid=GAMEID
--french-only
@ -118,7 +118,7 @@ def parse_option(argv):
FILE - file name of a saved game
MOD - one of following: pss(default), pygame, oss, win
""") % prog_name
""") % prog_name)
return None
if len(args) > 1:

View file

@ -27,12 +27,12 @@ import sys, os, time, types, locale
import webbrowser
try:
from cPickle import Pickler, Unpickler, UnpicklingError
from pickle import Pickler, Unpickler, UnpicklingError
except ImportError:
from pickle import Pickler, Unpickler, UnpicklingError
try:
import thread
import _thread
except:
thread = None
@ -102,7 +102,7 @@ def print_err(s, level=1):
ss = PACKAGE+': WARNING:'
elif level == 2:
ss = PACKAGE+': DEBUG WARNING:'
print >> sys.stderr, ss, s.encode(locale.getpreferredencoding())
print(ss, s.encode(locale.getpreferredencoding()), file=sys.stderr)
sys.stderr.flush()
@ -141,7 +141,7 @@ if os.name == "posix":
def win32_getusername():
user = os.environ.get('USERNAME','').strip()
try:
user = unicode(user, locale.getpreferredencoding())
user = str(user, locale.getpreferredencoding())
except:
user = ''
return user
@ -169,7 +169,7 @@ def destruct(obj):
# assist in breaking circular references
if obj is not None:
assert isinstance(obj, types.InstanceType)
for k in obj.__dict__.keys():
for k in list(obj.__dict__.keys()):
obj.__dict__[k] = None
##del obj.__dict__[k]
@ -191,19 +191,19 @@ class Struct:
self.__dict__[key] = value
def addattr(self, **kw):
for key in kw.keys():
for key in list(kw.keys()):
if hasattr(self, key):
raise AttributeError(key)
self.__dict__.update(kw)
def update(self, dict):
for key in dict.keys():
for key in list(dict.keys()):
if key not in self.__dict__:
raise AttributeError(key)
self.__dict__.update(dict)
def clear(self):
for key in self.__dict__.keys():
for key in list(self.__dict__.keys()):
if isinstance(key, list):
self.__dict__[key] = []
elif isinstance(key, tuple):
@ -225,7 +225,7 @@ class Struct:
# update keyword arguments with default arguments
def kwdefault(kw, **defaults):
for k, v in defaults.items():
for k, v in list(defaults.items()):
if k not in kw:
kw[k] = v
@ -238,7 +238,7 @@ class KwStruct:
defaults = defaults.__dict__
if defaults:
kw = kw.copy()
for k, v in defaults.items():
for k, v in list(defaults.items()):
if k not in kw:
kw[k] = v
self.__dict__.update(kw)

View file

@ -9,8 +9,8 @@ def n_(x):
def fix_gettext():
def ugettext(message):
# unicoded gettext
if not isinstance(message, unicode):
message = unicode(message, 'utf-8')
if not isinstance(message, str):
message = str(message, 'utf-8')
domain = gettext._current_domain
try:
t = gettext.translation(domain,
@ -21,10 +21,10 @@ def fix_gettext():
gettext.ugettext = ugettext
def ungettext(msgid1, msgid2, n):
# unicoded ngettext
if not isinstance(msgid1, unicode):
msgid1 = unicode(msgid1, 'utf-8')
if not isinstance(msgid2, unicode):
msgid2 = unicode(msgid2, 'utf-8')
if not isinstance(msgid1, str):
msgid1 = str(msgid1, 'utf-8')
if not isinstance(msgid2, str):
msgid2 = str(msgid2, 'utf-8')
domain = gettext._current_domain
try:
t = gettext.translation(domain,

View file

@ -479,7 +479,7 @@ class Options:
for key, t in self.GENERAL_OPTIONS:
val = getattr(self, key)
if isinstance(val, str):
val = unicode(val, 'utf-8')
val = str(val, 'utf-8')
config['general'][key] = val
config['general']['recent_gameid'] = self.recent_gameid
@ -493,7 +493,7 @@ class Options:
config['sound_samples'] = self.sound_samples
# fonts
for key, val in self.fonts.items():
for key, val in list(self.fonts.items()):
if key == 'default':
continue
if val is None:
@ -507,7 +507,7 @@ class Options:
config['timeouts'] = self.timeouts
# cardsets
for key, val in self.cardset.items():
for key, val in list(self.cardset.items()):
config['cardsets'][str(key)] = val
for key in ('scale_cards', 'scale_x', 'scale_y',
'auto_scale', 'preserve_aspect_ratio'):
@ -515,12 +515,12 @@ class Options:
# games_geometry
config['games_geometry'].clear()
for key, val in self.games_geometry.items():
for key, val in list(self.games_geometry.items()):
config['games_geometry'][str(key)] = val
config['general']['game_geometry'] = self.game_geometry
# offsets
for key, val in self.offsets.items():
for key, val in list(self.offsets.items()):
config['offsets'][key] = val
config.write()
@ -590,10 +590,10 @@ class Options:
res = config.validate(vdt)
##from pprint import pprint; pprint(res)
if res is not True:
for section, data in res.items():
for section, data in list(res.items()):
if data is True:
continue
for key, value in data.items():
for key, value in list(data.items()):
if value is False:
print_err('config file: validation error: '
'section: "%s", key: "%s"' % (section, key))
@ -686,7 +686,7 @@ class Options:
setattr(self, key, val)
# games_geometry
for key, val in config['games_geometry'].items():
for key, val in list(config['games_geometry'].items()):
try:
val = [int(i) for i in val]
assert len(val) == 2
@ -701,7 +701,7 @@ class Options:
traceback.print_exc()
# cards offsets
for key, val in config['offsets'].items():
for key, val in list(config['offsets'].items()):
try:
val = [int(i) for i in val]
assert len(val) == 2

View file

@ -27,7 +27,7 @@ import os
import traceback
try:
import thread
import _thread
from threading import Thread
except ImportError:
thread = None

View file

@ -29,7 +29,7 @@ import gtk
from pysollib.acard import AbstractCard
# Toolkit imports
from tkcanvas import MfxCanvasGroup, MfxCanvasImage
from .tkcanvas import MfxCanvasGroup, MfxCanvasImage
# ************************************************************************

View file

@ -29,7 +29,7 @@ __all__ = ['EditTextDialog']
# PySol imports
# Toolkit imports
from tkwidget import MfxDialog
from .tkwidget import MfxDialog
# ************************************************************************
# *

View file

@ -31,7 +31,7 @@ import gtk.glade
# PySol imports
from pysollib.mygettext import _, n_
from tkutil import create_pango_font_desc
from .tkutil import create_pango_font_desc
# ************************************************************************

View file

@ -33,7 +33,7 @@ __all__ = ['GameInfoDialog']
## from pysollib.gamedb import GI
# Toolkit imports
from tkwidget import MfxDialog
from .tkwidget import MfxDialog
# ************************************************************************
# *

View file

@ -34,13 +34,13 @@ from pysollib.gamedb import GI
from pysollib.settings import TITLE
# toolkit imports
from tkutil import setTransient
from tkutil import color_tk2gtk, color_gtk2tk
from soundoptionsdialog import SoundOptionsDialog
from selectcardset import SelectCardsetDialogWithPreview
from selecttile import SelectTileDialogWithPreview
from selectgame import SelectGameDialogWithPreview
from findcarddialog import connect_game_find_card_dialog, destroy_find_card_dialog
from .tkutil import setTransient
from .tkutil import color_tk2gtk, color_gtk2tk
from .soundoptionsdialog import SoundOptionsDialog
from .selectcardset import SelectCardsetDialogWithPreview
from .selecttile import SelectTileDialogWithPreview
from .selectgame import SelectGameDialogWithPreview
from .findcarddialog import connect_game_find_card_dialog, destroy_find_card_dialog
def ltk2gtk(s):
# label tk to gtk
@ -456,7 +456,7 @@ class PysolMenubarTk:
#ui_manager.get_widget('/menubar/file/recentgames').show()
#ui_manager.get_widget('/menubar/file/favoritegames').show()
games = map(self.app.gdb.get, self.app.gdb.getGamesIdSortedByName())
games = list(map(self.app.gdb.get, self.app.gdb.getGamesIdSortedByName()))
menu = ui_manager.get_widget('/menubar/select').get_submenu()
self._createSelectMenu(games, menu)
@ -475,7 +475,7 @@ class PysolMenubarTk:
def _getNumGames(self, games, select_data):
ngames = 0
for label, select_func in select_data:
ngames += len(filter(select_func, games))
ngames += len(list(filter(select_func, games)))
return ngames
def _createSubMenu(self, menu, label):
@ -520,7 +520,7 @@ class PysolMenubarTk:
def _addSelectedGamesSubMenu(self, games, menu, select_data):
for label, select_func in select_data:
g = filter(select_func, games)
g = list(filter(select_func, games))
if not g:
continue
submenu = self._createSubMenu(menu, label=label)
@ -528,7 +528,7 @@ class PysolMenubarTk:
def _addPopularGamesMenu(self, games, menu):
select_func = lambda gi: gi.si.game_flags & GI.GT_POPULAR
if len(filter(select_func, games)) == 0:
if len(list(filter(select_func, games))) == 0:
return
data = (ltk2gtk('&Popular games'), select_func)
self._addSelectedGamesSubMenu(games, menu, (data, ))
@ -541,7 +541,7 @@ class PysolMenubarTk:
def _addMahjonggGamesMenu(self, games, menu):
select_func = lambda gi: gi.si.game_type == GI.GT_MAHJONGG
mahjongg_games = filter(select_func, games)
mahjongg_games = list(filter(select_func, games))
if len(mahjongg_games) == 0:
return
menu = self._createSubMenu(menu, label=ltk2gtk('&Mahjongg games'))
@ -562,7 +562,7 @@ class PysolMenubarTk:
games[c].append(gi)
else:
games[c] = [gi]
games = games.items()
games = list(games.items())
games.sort()
#
g0 = []
@ -618,7 +618,7 @@ class PysolMenubarTk:
path = '/toolbar/'+path
button = self.top.ui_manager.get_widget(path)
if not button:
print 'WARNING: setToolbarState: not found:', path
print('WARNING: setToolbarState: not found:', path)
else:
button.set_sensitive(state)

View file

@ -30,7 +30,7 @@ import gobject, gtk
from pysollib.mygettext import _, n_
# Toolkit imports
from tkwidget import MfxDialog
from .tkwidget import MfxDialog
from pysollib.mfxutil import kwdefault

View file

@ -29,7 +29,7 @@ import gtk
from gtk import gdk
# Toolkit imports
from tkutil import makeToplevel, setTransient
from .tkutil import makeToplevel, setTransient
# ************************************************************************
@ -159,7 +159,7 @@ def progressbar_main(args):
root.connect("delete_event", mainquit)
images = None
if 1:
from tkwrap import loadImage
from .tkwrap import loadImage
im = loadImage(os.path.join(os.pardir, os.pardir, 'data', 'images', 'jokers', 'joker07_40_774.gif'))
images = (im, im)
pb = TestProgressBar(root, images=images)

View file

@ -32,10 +32,10 @@ from pysollib.resource import CSI
from pysollib.mfxutil import kwdefault
# Toolkit imports
from tkwidget import MfxDialog
from pysoltree import PysolTreeView
from tkcanvas import MfxCanvas, MfxCanvasImage
from tkutil import loadImage
from .tkwidget import MfxDialog
from .pysoltree import PysolTreeView
from .tkcanvas import MfxCanvas, MfxCanvasImage
from .tkutil import loadImage
# ************************************************************************
@ -118,7 +118,7 @@ class SelectCardsetDialogWithPreview(MfxDialog):
manager = self.manager
root_iter = store.append(None)
store.set(root_iter, 0, root_label, 1, -1)
items = cardset_types.items()
items = list(cardset_types.items())
items.sort(lambda a, b: cmp(a[1], b[1]))
added = False
for key, label in items:

View file

@ -38,10 +38,10 @@ from pysollib.help import help_html
from pysollib.resource import CSI
# Toolkit imports
from tkutil import unbind_destroy
from tkwidget import MfxDialog
from tkcanvas import MfxCanvas, MfxCanvasText
from pysoltree import PysolTreeView
from .tkutil import unbind_destroy
from .tkwidget import MfxDialog
from .tkcanvas import MfxCanvas, MfxCanvasText
from .pysoltree import PysolTreeView
# ************************************************************************
@ -211,7 +211,7 @@ class SelectGameDialogWithPreview(MfxDialog):
app = self.app
gdb = app.gdb
all_games = map(gdb.get, gdb.getGamesIdSortedByName())
all_games = list(map(gdb.get, gdb.getGamesIdSortedByName()))
#
alter_games = gdb.getGamesTuplesSortedByAlternateName()
for label, games, selecter in (
@ -507,7 +507,7 @@ class SelectGameDialogWithPreview(MfxDialog):
def done(self, button):
button = button.get_data("user_data")
print 'done', button
print('done', button)
if button == 0: # Ok or double click
id = self.getSelected()
if id:

View file

@ -36,10 +36,10 @@ from pysollib.mfxutil import kwdefault
# Toolkit imports
## from tkutil import loadImage
from tkwidget import MfxDialog
from tkcanvas import MfxCanvas
from tkutil import setTransient
from pysoltree import PysolTreeView
from .tkwidget import MfxDialog
from .tkcanvas import MfxCanvas
from .tkutil import setTransient
from .pysoltree import PysolTreeView
class SelectTileDialogWithPreview(MfxDialog):
@ -85,7 +85,7 @@ class SelectTileDialogWithPreview(MfxDialog):
def rowActivated(self, w, row, col):
# FIXME
print 'row-activated-event', row, col
print('row-activated-event', row, col)
def getSelected(self):

View file

@ -31,7 +31,7 @@ from gtk import glade
from pysollib.mygettext import _, n_
# Toolkit imports
from tkwidget import MfxDialog
from .tkwidget import MfxDialog
# ************************************************************************

View file

@ -65,10 +65,10 @@ class BasicStatusbar:
def updateText(self, **kw):
for k, v in kw.items():
for k, v in list(kw.items()):
label = getattr(self, k + "_label")
label.pop(0)
label.push(0, unicode(v))
label.push(0, str(v))
def config(self, name, show):
# FIXME
@ -78,7 +78,7 @@ class BasicStatusbar:
label = getattr(self, name + "_label")
# FIXME kw['fg']
label.pop(0)
label.push(0, unicode(kw['text']))
label.push(0, str(kw['text']))
def show(self, show=True, resize=False):

View file

@ -51,7 +51,7 @@ except ImportError:
import gnome.canvas as gnomecanvas
# toolkit imports
from tkutil import anchor_tk2gtk, loadImage, bind, create_pango_font_desc
from .tkutil import anchor_tk2gtk, loadImage, bind, create_pango_font_desc
# ************************************************************************
@ -78,7 +78,7 @@ class _CanvasItem:
##~ assert isinstance(group._item, CanvasGroup)
self._item.reparent(group._item)
if self._group == group:
print 'addtag: new_group == old_group'
print('addtag: new_group == old_group')
self._group = group
def dtag(self, group):
@ -100,7 +100,7 @@ class _CanvasItem:
self._item = None
def lower(self, positions=None):
print 'lower', self, positions
print('lower', self, positions)
return # don't need?
## if positions is None:
## pass
@ -241,7 +241,7 @@ class MfxCanvasText(_CanvasItem):
x=x, y=y, anchor=anchor)
if 'fill' not in kw:
kw['fill'] = canvas._text_color
for k, v in kw.items():
for k, v in list(kw.items()):
self[k] = v
##~ self.text_format = None
canvas._text_items.append(self)
@ -257,17 +257,17 @@ class MfxCanvasText(_CanvasItem):
elif key == 'text':
self._item.set(text=value)
else:
raise AttributeError, key
raise AttributeError(key)
def config(self, **kw):
for k, v in kw.items():
for k, v in list(kw.items()):
self[k] = v
def __getitem__(self, key):
if key == 'text':
return self._item.get_property('text')
else:
raise AttributeError, key
raise AttributeError(key)
cget = __getitem__
@ -322,7 +322,7 @@ class MfxCanvas(gnomecanvas.Canvas):
def bind(self, sequence=None, func=None, add=None):
assert add is None
# FIXME
print 'TkCanvas bind:', sequence
print('TkCanvas bind:', sequence)
return
def cget(self, attr):
@ -334,8 +334,8 @@ class MfxCanvas(gnomecanvas.Canvas):
return self.get_size()[0]
elif attr == 'height':
return self.get_size()[1]
print 'TkCanvas cget:', attr
raise AttributeError, attr
print('TkCanvas cget:', attr)
raise AttributeError(attr)
def xview(self):
w, h = self.get_size()
@ -353,7 +353,7 @@ class MfxCanvas(gnomecanvas.Canvas):
def configure(self, **kw):
height, width = -1, -1
for k, v in kw.items():
for k, v in list(kw.items()):
if k in ('background', 'bg'):
self.modify_bg(gtk.STATE_NORMAL, gdk.color_parse(v))
elif k == 'cursor':
@ -367,8 +367,8 @@ class MfxCanvas(gnomecanvas.Canvas):
elif k == 'width':
width = v
else:
print 'TkCanvas', k, v
raise AttributeError, k
print('TkCanvas', k, v)
raise AttributeError(k)
if height > 0 and width > 0:
self.set_size_request(width, height)
@ -535,14 +535,14 @@ class MfxCanvas(gnomecanvas.Canvas):
pass
def updateAll(self):
print 'Canvas - updateAll',
print('Canvas - updateAll', end=' ')
for i in self._all_items:
i._item.hide()
self.update_now()
n = 0
for i in self._all_items:
i._item.show()
print n, i
print(n, i)
n += 1
self.update_now()
#self.window.invalidate_rect((0, 0, 400, 400), True)

View file

@ -36,15 +36,15 @@ if __name__ == '__main__':
d = os.path.abspath(os.path.join(sys.path[0], '..', '..'))
sys.path.append(d)
import gettext
gettext.install('pysol', d, unicode=True)
gettext.install('pysol', d, str=True)
# PySol imports
from pysollib.mfxutil import Struct, openURL
from pysollib.settings import TITLE
# Toolkit imports
from tkutil import bind, unbind_destroy, loadImage
from tkwidget import MfxMessageDialog
from .tkutil import bind, unbind_destroy, loadImage
from .tkwidget import MfxMessageDialog
REMOTE_PROTOCOLS = ('ftp:', 'gopher:', 'http:', 'mailto:', 'news:', 'telnet:')
@ -70,7 +70,7 @@ class tkHTMLWriter(formatter.NullWriter):
def write(self, data):
data = unicode(data)
data = str(data)
self.text.insert(self.text.get_end_iter(), data, len(data))
def anchor_bgn(self, href, name, type):
@ -251,7 +251,7 @@ class HTMLViewer:
vbox.pack_start(self.statusbar, fill=True, expand=False)
# load images
for name, fn in self.symbols_fn.items():
for name, fn in list(self.symbols_fn.items()):
self.symbols_img[name] = self.getImage(fn)
# bindings
@ -282,7 +282,7 @@ class HTMLViewer:
x, y = widget.window_to_buffer_coords(gtk.TEXT_WINDOW_TEXT, x, y)
tags = widget.get_iter_at_location(x, y).get_tags()
is_over_anchor = False
for tag, href in self.anchor_tags.values():
for tag, href in list(self.anchor_tags.values()):
if tag in tags:
is_over_anchor = True
break
@ -346,7 +346,7 @@ class HTMLViewer:
'bold' : (default_font[0], size, 'bold'),
}
for tag_name in self.fontmap.keys():
for tag_name in list(self.fontmap.keys()):
font = self.fontmap[tag_name]
font = font[0]+' '+str(font[1])
tag = self.textbuffer.create_tag(tag_name, font=font)
@ -385,8 +385,8 @@ class HTMLViewer:
if baseurl is None:
baseurl = self.url
if 0:
import urllib
url = urllib.pathname2url(url)
import urllib.request, urllib.parse, urllib.error
url = urllib.request.pathname2url(url)
if relpath and self.url:
url = urllib.basejoin(baseurl, url)
else:
@ -449,14 +449,14 @@ to open the following URL:
try:
file = None
if 0:
import urllib
file = urllib.urlopen(url)
import urllib.request, urllib.parse, urllib.error
file = urllib.request.urlopen(url)
else:
file, url = self.openfile(url)
data = file.read()
file.close()
file = None
except Exception, ex:
except Exception as ex:
if file: file.close()
self.errorDialog(_('Unable to service request:\n') + url + '\n\n' + str(ex))
return

View file

@ -34,7 +34,7 @@ from pysollib.settings import TOP_TITLE, TITLE
from pysollib.stats import PysolStatsFormatter
# Toolkit imports
from tkwidget import MfxDialog, MfxMessageDialog
from .tkwidget import MfxDialog, MfxMessageDialog
# ************************************************************************
@ -494,8 +494,8 @@ class Game_StatsDialog:
def _cmpPlayingTime(self, store, iter1, iter2):
val1 = store.get_value(iter1, 4)
val2 = store.get_value(iter2, 4)
t1 = map(int, val1.split(':'))
t2 = map(int, val2.split(':'))
t1 = list(map(int, val1.split(':')))
t2 = list(map(int, val2.split(':')))
return cmp(len(t1), len(t2)) or cmp(t1, t2)
def _cmpMoves(self, store, iter1, iter2):

View file

@ -32,7 +32,7 @@ gdk = gtk.gdk
from pysollib.mygettext import _, n_
# Toolkit imports
from tkutil import makeToplevel, setTransient, wm_withdraw
from .tkutil import makeToplevel, setTransient, wm_withdraw
from pysollib.mfxutil import kwdefault, KwStruct, openURL

View file

@ -33,7 +33,7 @@ from gtk import gdk
from pysollib.settings import TITLE, VERSION
# Toolkit imports
from tkutil import makeToplevel, loadImage
from .tkutil import makeToplevel, loadImage
# ************************************************************************
@ -72,13 +72,13 @@ class _MfxToplevel(gtk.Window):
c = self.style.bg[gtk.STATE_NORMAL]
c = '#%02x%02x%02x' % (c.red/256, c.green/256, c.blue/256)
return c
print "Toplevel cget:", attr
print("Toplevel cget:", attr)
##~ raise AttributeError, attr
return None
def configure(self, **kw):
height, width = -1, -1
for k, v in kw.items():
for k, v in list(kw.items()):
if k in ("background", "bg"):
##print "Toplevel configure: bg"
pass
@ -89,8 +89,8 @@ class _MfxToplevel(gtk.Window):
elif k == "width":
width = v
else:
print "Toplevel configure:", k, v
raise AttributeError, k
print("Toplevel configure:", k, v)
raise AttributeError(k)
if height > 0 and width > 0:
##print 'configure: size:', width, height
## FIXME
@ -163,7 +163,7 @@ class _MfxToplevel(gtk.Window):
pass
def wm_iconbitmap(self, name):
print 'wm_iconbitmap:', name
print('wm_iconbitmap:', name)
if name and name[0] == '@' and name[-4:] == '.xbm':
name = name[1:-4] + '.xpm'
bg = self.get_style().bg[gtk.STATE_NORMAL]
@ -191,7 +191,7 @@ class _MfxToplevel(gtk.Window):
def option_get(self, *args):
if args and args[0] == 'font':
return self.get_style().font_desc.to_string()
print '_MfxToplevel: option_get', args
print('_MfxToplevel: option_get', args)
return None
def grid_columnconfigure(self, *args, **kw):

View file

@ -38,7 +38,7 @@ from pysollib.mfxutil import SubclassResponsibility
class BasicRandom:
#MAX_SEED = 0L
#MAX_SEED = 0xffffffffffffffffL # 64 bits
MAX_SEED = 100000000000000000000L # 20 digits
MAX_SEED = 100000000000000000000 # 20 digits
ORIGIN_UNKNOWN = 0
ORIGIN_RANDOM = 1
@ -59,18 +59,18 @@ class BasicRandom:
raise SubclassResponsibility
def copy(self):
random = self.__class__(0L)
random = self.__class__(0)
random.__dict__.update(self.__dict__)
return random
def increaseSeed(self, seed):
if seed < self.MAX_SEED:
return seed + 1L
return 0L
return seed + 1
return 0
def _getRandomSeed(self):
t = long(time.time() * 256.0)
t = (t ^ (t >> 24)) % (self.MAX_SEED + 1L)
t = int(time.time() * 256.0)
t = (t ^ (t >> 24)) % (self.MAX_SEED + 1)
return t
def setSeedAsStr(self, new_s):
@ -142,9 +142,9 @@ class MFXRandom(BasicRandom):
return self.seed
def setSeed(self, seed):
seed = long(seed)
if not (0L <= seed <= self.MAX_SEED):
raise ValueError, "seed out of range"
seed = int(seed)
if not (0 <= seed <= self.MAX_SEED):
raise ValueError("seed out of range")
self.seed = seed
return seed
@ -163,7 +163,7 @@ class MFXRandom(BasicRandom):
# Get a random integer in the range [a, b] including both end points.
def randint(self, a, b):
return a + long(self.random() * (b+1-a))
return a + int(self.random() * (b+1-a))
def randrange(self, a, b):
return self.randint(a, b-1)
@ -187,8 +187,8 @@ class MFXRandom(BasicRandom):
class LCRandom64(MFXRandom):
def random(self):
self.seed = (self.seed*6364136223846793005L + 1L) & self.MAX_SEED
return ((self.seed >> 21) & 0x7fffffffL) / 2147483648.0
self.seed = (self.seed*6364136223846793005 + 1) & self.MAX_SEED
return ((self.seed >> 21) & 0x7fffffff) / 2147483648.0
# ************************************************************************
@ -198,17 +198,17 @@ class LCRandom64(MFXRandom):
# ************************************************************************
class LCRandom31(MFXRandom):
MAX_SEED = 0x7fffffffL # 31 bits
MAX_SEED = 0x7fffffff # 31 bits
def str(self, seed):
return "%05d" % int(seed)
def random(self):
self.seed = (self.seed*214013L + 2531011L) & self.MAX_SEED
self.seed = (self.seed*214013 + 2531011) & self.MAX_SEED
return (self.seed >> 16) / 32768.0
def randint(self, a, b):
self.seed = (self.seed*214013L + 2531011L) & self.MAX_SEED
self.seed = (self.seed*214013 + 2531011) & self.MAX_SEED
return a + (int(self.seed >> 16) % (b+1-a))
def shuffle(self, seq):
@ -233,18 +233,18 @@ PysolRandom = MTRandom
def constructRandom(s):
m = re.match(r"ms(\d+)\n?\Z", s);
if m:
seed = long(m.group(1))
seed = int(m.group(1))
if 0 <= seed < (1 << 31):
ret = LCRandom31(seed)
ret.setSeedAsStr(s)
return ret
else:
raise ValueError, "ms seed out of range"
raise ValueError("ms seed out of range")
s = re.sub(r"L$", "", str(s)) # cut off "L" from possible conversion to long
s = re.sub(r"[\s\#\-\_\.\,]", "", s.lower())
if not s:
return None
seed = long(s)
seed = int(s)
if 0 <= seed < 32000:
return LCRandom31(seed)
return PysolRandom(seed)
@ -252,8 +252,8 @@ def constructRandom(s):
# test
if __name__ == '__main__':
r = constructRandom('12345')
print r.randint(0, 100)
print r.random()
print type(r)
print(r.randint(0, 100))
print(r.random())
print(type(r))

View file

@ -118,7 +118,7 @@ class ResourceManager:
dir = os.path.normpath(dir)
if dir and os.path.isdir(dir) and dir not in result:
result.append(dir)
except EnvironmentError, ex:
except EnvironmentError as ex:
pass
def getSearchDirs(self, app, search, env=None):
@ -145,11 +145,11 @@ class ResourceManager:
self._addDir(result, d)
else:
self._addDir(result, os.path.join(dir, s))
except EnvironmentError, ex:
except EnvironmentError as ex:
traceback.print_exc()
pass
if DEBUG >= 6:
print "getSearchDirs", env, search, "->", result
print("getSearchDirs", env, search, "->", result)
return result
@ -369,7 +369,7 @@ class Cardset(Resource):
ls = min(ls, 4)
low_ranks, high_ranks = 1, 3
###if self.type == 3: high_ranks = 4
for rank in range(0, low_ranks) + range(lr-high_ranks, lr):
for rank in list(range(0, low_ranks)) + list(range(lr-high_ranks, lr)):
for suit in range(ls):
index = suit * len(self.ranks) + rank
pnames.append(names[index % len(names)])
@ -377,7 +377,7 @@ class Cardset(Resource):
def updateCardback(self, backname=None, backindex=None):
# update default back
if isinstance(backname, basestring):
if isinstance(backname, str):
if backname in self.backnames:
backindex = self.backnames.index(backname)
if isinstance(backindex, int):
@ -385,7 +385,7 @@ class Cardset(Resource):
self.backname = self.backnames[self.backindex]
def saveSettings(self):
print 'saveSettings'
print('saveSettings')
class CardsetManager(ResourceManager):
@ -403,42 +403,42 @@ class CardsetManager(ResourceManager):
return 0
cs.si.type = s
if s == CSI.TYPE_FRENCH:
cs.ranks = range(13)
cs.ranks = list(range(13))
cs.suits = "cshd"
elif s == CSI.TYPE_HANAFUDA:
cs.nbottoms = 15
cs.ranks = range(4)
cs.ranks = list(range(4))
cs.suits = "abcdefghijkl"
elif s == CSI.TYPE_TAROCK:
cs.nbottoms = 8
cs.ranks = range(14)
cs.ranks = list(range(14))
cs.suits = "cshd"
cs.trumps = range(22)
cs.trumps = list(range(22))
elif s == CSI.TYPE_MAHJONGG:
cs.ranks = range(10)
cs.ranks = list(range(10))
cs.suits = "abc"
cs.trumps = range(12)
cs.trumps = list(range(12))
#
cs.nbottoms = 0
cs.nletters = 0
cs.nshadows = 0
elif s == CSI.TYPE_HEXADECK:
cs.nbottoms = 8
cs.ranks = range(16)
cs.ranks = list(range(16))
cs.suits = "cshd"
cs.trumps = range(4)
cs.trumps = list(range(4))
elif s == CSI.TYPE_MUGHAL_GANJIFA:
cs.nbottoms = 11
cs.ranks = range(12)
cs.ranks = list(range(12))
cs.suits = "abcdefgh"
elif s == CSI.TYPE_NAVAGRAHA_GANJIFA:
#???return 0 ## FIXME
cs.nbottoms = 12
cs.ranks = range(12)
cs.ranks = list(range(12))
cs.suits = "abcdefghi"
elif s == CSI.TYPE_DASHAVATARA_GANJIFA:
cs.nbottoms = 13
cs.ranks = range(12)
cs.ranks = list(range(12))
cs.suits = "abcdefghij"
elif s == CSI.TYPE_TRUMP_ONLY:
#???return 0 ## FIXME
@ -451,7 +451,7 @@ class CardsetManager(ResourceManager):
cs.nshadows = 0
cs.ranks = ()
cs.suits = ""
cs.trumps = range(cs.ncards)
cs.trumps = list(range(cs.ncards))
else:
return 0

View file

@ -375,9 +375,9 @@ class Stack:
self.can_hide_cards = self.is_visible
if self.cap.max_cards < 3:
self.can_hide_cards = 0
elif filter(None, self.CARD_XOFFSET):
elif [_f for _f in self.CARD_XOFFSET if _f]:
self.can_hide_cards = 0
elif filter(None, self.CARD_YOFFSET):
elif [_f for _f in self.CARD_YOFFSET if _f]:
self.can_hide_cards = 0
elif self.canvas.preview:
self.can_hide_cards = 0
@ -3003,7 +3003,7 @@ class ArbitraryStack(OpenStack):
# self.cap override any call-time cap
class StackWrapper:
def __init__(self, stack_class, **cap):
assert isinstance(stack_class, types.ClassType)
assert isinstance(stack_class, type)
assert issubclass(stack_class, Stack)
self.stack_class = stack_class
self.cap = cap

View file

@ -303,7 +303,7 @@ class ProgressionFormatter:
t[0] -= 1
lt = self.norm_time(t)
marks = [lt[:3], tt[:3]]
for i in xrange(5):
for i in range(5):
tt[1] -= 2
marks.append(self.norm_time(tt)[:3])
delta = 7
@ -342,7 +342,7 @@ class ProgressionFormatter:
played = 0
won = 0
text = None
for i in xrange(delta):
for i in range(delta):
if marks:
if ct[:3] in marks:
text = time.strftime(format, ct)

View file

@ -29,7 +29,7 @@ __all__ = ['Card']
from pysollib.acard import AbstractCard
# Toolkit imports
from tkcanvas import MfxCanvasGroup, MfxCanvasImage
from .tkcanvas import MfxCanvasGroup, MfxCanvasImage
# ************************************************************************

View file

@ -24,16 +24,16 @@
__all__ = ['ColorsDialog']
# imports
import Tkinter
import ttk
from tkColorChooser import askcolor
import tkinter
from . import ttk
from tkinter.colorchooser import askcolor
# PySol imports
from pysollib.mfxutil import KwStruct
from pysollib.mygettext import _, n_
# Toolkit imports
from tkwidget import MfxDialog
from .tkwidget import MfxDialog
# ************************************************************************
# *
@ -50,21 +50,21 @@ class ColorsDialog(MfxDialog):
frame.pack(expand=True, fill='both', padx=5, pady=10)
frame.columnconfigure(0, weight=1)
self.text_var = Tkinter.StringVar()
self.text_var = tkinter.StringVar()
self.text_var.set(app.opt.colors['text'])
self.piles_var = Tkinter.StringVar()
self.piles_var = tkinter.StringVar()
self.piles_var.set(app.opt.colors['piles'])
self.cards_1_var = Tkinter.StringVar()
self.cards_1_var = tkinter.StringVar()
self.cards_1_var.set(app.opt.colors['cards_1'])
self.cards_2_var = Tkinter.StringVar()
self.cards_2_var = tkinter.StringVar()
self.cards_2_var.set(app.opt.colors['cards_2'])
self.samerank_1_var = Tkinter.StringVar()
self.samerank_1_var = tkinter.StringVar()
self.samerank_1_var.set(app.opt.colors['samerank_1'])
self.samerank_2_var = Tkinter.StringVar()
self.samerank_2_var = tkinter.StringVar()
self.samerank_2_var.set(app.opt.colors['samerank_2'])
self.hintarrow_var = Tkinter.StringVar()
self.hintarrow_var = tkinter.StringVar()
self.hintarrow_var.set(app.opt.colors['hintarrow'])
self.not_matching_var = Tkinter.StringVar()
self.not_matching_var = tkinter.StringVar()
self.not_matching_var.set(app.opt.colors['not_matching'])
#
row = 0
@ -80,7 +80,7 @@ class ColorsDialog(MfxDialog):
):
ttk.Label(frame, text=title, anchor='w',
).grid(row=row, column=0, sticky='we')
l = Tkinter.Label(frame, width=10, height=2,
l = tkinter.Label(frame, width=10, height=2,
bg=var.get(), textvariable=var)
l.grid(row=row, column=1, padx=5)
b = ttk.Button(frame, text=_('Change...'), width=10,

View file

@ -24,15 +24,15 @@
__all__ = ['EditTextDialog']
# imports
import Tkinter
import ttk
import tkinter
from . import ttk
# PySol imports
from pysollib.mfxutil import KwStruct
from pysollib.mygettext import _, n_
# Toolkit imports
from tkwidget import MfxDialog
from .tkwidget import MfxDialog
# ************************************************************************
# *
@ -46,7 +46,7 @@ class EditTextDialog(MfxDialog):
top_frame, bottom_frame = self.createFrames(kw)
self.createBitmaps(top_frame, kw)
#
self.text_w = Tkinter.Text(top_frame, bd=1, relief="sunken",
self.text_w = tkinter.Text(top_frame, bd=1, relief="sunken",
wrap="word", width=64, height=16)
self.text_w.pack(side='left', fill="both", expand=True)
###self.text_w.pack(side='top', padx=kw.padx, pady=kw.pady)

View file

@ -28,13 +28,13 @@ __all__ = ['create_find_card_dialog',
# imports
import os
import Tkinter
import tkinter
from pysollib.mygettext import _, n_
# Toolkit imports
from tkutil import after, after_cancel
from tkutil import bind, unbind_destroy, makeImage
from tkcanvas import MfxCanvas, MfxCanvasGroup, MfxCanvasImage, MfxCanvasRectangle
from .tkutil import after, after_cancel
from .tkutil import bind, unbind_destroy, makeImage
from .tkcanvas import MfxCanvas, MfxCanvasGroup, MfxCanvasImage, MfxCanvasRectangle
from pysollib.settings import TITLE
@ -46,11 +46,11 @@ from pysollib.settings import TITLE
LARGE_EMBLEMS_SIZE = (38, 34)
SMALL_EMBLEMS_SIZE = (31, 21)
class FindCardDialog(Tkinter.Toplevel):
class FindCardDialog(tkinter.Toplevel):
CARD_IMAGES = {} # key: (rank, suit)
def __init__(self, parent, game, dir, size='large'):
Tkinter.Toplevel.__init__(self)
tkinter.Toplevel.__init__(self)
title = TITLE + ' - ' + _('Find card')
self.title(title)
self.wm_resizable(False, False)
@ -194,7 +194,7 @@ class FindCardDialog(Tkinter.Toplevel):
if self.highlight_items:
for i in self.highlight_items:
i.delete()
Tkinter.Toplevel.destroy(self)
tkinter.Toplevel.destroy(self)

View file

@ -24,18 +24,18 @@
__all__ = ['FontsDialog']
# imports
import Tkinter
import ttk
import tkFont
import tkinter
from . import ttk
import tkinter.font
# PySol imports
from pysollib.mfxutil import KwStruct
from pysollib.mygettext import _, n_
# Toolkit imports
from tkwidget import MfxDialog
from tkutil import bind
from tkwidget import PysolScale
from .tkwidget import MfxDialog
from .tkutil import bind
from .tkwidget import PysolScale
# ************************************************************************
@ -75,11 +75,11 @@ class FontChooserDialog(MfxDialog):
raise ValueError('invalid font style: '+init_font[3])
#self.family_var = Tkinter.StringVar()
self.weight_var = Tkinter.BooleanVar()
self.weight_var = tkinter.BooleanVar()
self.weight_var.set(self.font_weight == 'bold')
self.slant_var = Tkinter.BooleanVar()
self.slant_var = tkinter.BooleanVar()
self.slant_var.set(self.font_slant == 'italic')
self.size_var = Tkinter.IntVar()
self.size_var = tkinter.IntVar()
self.size_var.set(self.font_size)
#
frame = ttk.Frame(top_frame)
@ -89,7 +89,7 @@ class FontChooserDialog(MfxDialog):
self.entry = ttk.Entry(frame)
self.entry.grid(row=0, column=0, columnspan=2, sticky='news')
self.entry.insert('end', _('abcdefghABCDEFGH'))
self.list_box = Tkinter.Listbox(frame, width=36, exportselection=False)
self.list_box = tkinter.Listbox(frame, width=36, exportselection=False)
sb = ttk.Scrollbar(frame)
self.list_box.configure(yscrollcommand=sb.set)
sb.configure(command=self.list_box.yview)
@ -111,7 +111,7 @@ class FontChooserDialog(MfxDialog):
command=self.fontupdate, variable=self.size_var)
sc.grid(row=4, column=0, columnspan=2, sticky='news')
#
font_families = list(tkFont.families())
font_families = list(tkinter.font.families())
font_families.sort()
selected = -1
n = 0

View file

@ -25,7 +25,7 @@
__all__ = ['GameInfoDialog']
# imports
import ttk
from . import ttk
# PySol imports
from pysollib.mygettext import _, n_
@ -33,7 +33,7 @@ from pysollib.mfxutil import KwStruct
from pysollib.gamedb import GI
# Toolkit imports
from tkwidget import MfxDialog
from .tkwidget import MfxDialog
# ************************************************************************
# *
@ -146,7 +146,7 @@ class GameInfoDialog(MfxDialog):
fs[cn] += 1
else:
fs[cn] = 1
t = '\n'.join(['%s (%d)' % (i[0], i[1]) for i in fs.items()])
t = '\n'.join(['%s (%d)' % (i[0], i[1]) for i in list(fs.items())])
else:
t = stacks.__class__.__name__
ttk.Label(frame, text=t, anchor='w', justify='left'

View file

@ -25,9 +25,9 @@ __all__ = ['PysolMenubarTk']
# imports
import math, os, sys, re, traceback
import Tkinter
import ttk
import tkFileDialog
import tkinter
from . import ttk
import tkinter.filedialog
# PySol imports
from pysollib.mygettext import _, n_
@ -41,18 +41,18 @@ from pysollib.settings import DEBUG
from pysollib.gamedb import GI
# toolkit imports
from tkconst import EVENT_HANDLED, EVENT_PROPAGATE, CURSOR_WATCH, COMPOUNDS
from tkutil import bind, after_idle
from selectgame import SelectGameDialog, SelectGameDialogWithPreview
from soundoptionsdialog import SoundOptionsDialog
from selectcardset import SelectCardsetDialogWithPreview
from selecttile import SelectTileDialogWithPreview
from findcarddialog import connect_game_find_card_dialog, destroy_find_card_dialog
from solverdialog import connect_game_solver_dialog
from tkwidget import MfxMessageDialog
from .tkconst import EVENT_HANDLED, EVENT_PROPAGATE, CURSOR_WATCH, COMPOUNDS
from .tkutil import bind, after_idle
from .selectgame import SelectGameDialog, SelectGameDialogWithPreview
from .soundoptionsdialog import SoundOptionsDialog
from .selectcardset import SelectCardsetDialogWithPreview
from .selecttile import SelectTileDialogWithPreview
from .findcarddialog import connect_game_find_card_dialog, destroy_find_card_dialog
from .solverdialog import connect_game_solver_dialog
from .tkwidget import MfxMessageDialog
#from toolbar import TOOLBAR_BUTTONS
from tkconst import TOOLBAR_BUTTONS
from .tkconst import TOOLBAR_BUTTONS
# ************************************************************************
@ -110,14 +110,14 @@ def createToolbarMenu(menubar, menu):
# *
# ************************************************************************
class MfxMenubar(Tkinter.Menu):
class MfxMenubar(tkinter.Menu):
addPath = None
def __init__(self, master, **kw):
self.name = kw["name"]
tearoff = 0
self.n = kw["tearoff"] = int(kw.get("tearoff", tearoff))
Tkinter.Menu.__init__(self, master, **kw)
tkinter.Menu.__init__(self, master, **kw)
def labeltoname(self, label):
#print label, type(label)
@ -141,7 +141,7 @@ class MfxMenubar(Tkinter.Menu):
if name and self.addPath:
path = str(self._w) + "." + name
self.addPath(path, self, self.n, cnf.get("menu"))
Tkinter.Menu.add(self, itemType, cnf)
tkinter.Menu.add(self, itemType, cnf)
self.n = self.n + 1
@ -193,54 +193,54 @@ class PysolMenubarTk:
def _createTkOpt(self):
# structure to convert menu-options to Toolkit variables
self.tkopt = Struct(
gameid = Tkinter.IntVar(),
gameid_popular = Tkinter.IntVar(),
comment = Tkinter.BooleanVar(),
autofaceup = Tkinter.BooleanVar(),
autodrop = Tkinter.BooleanVar(),
autodeal = Tkinter.BooleanVar(),
quickplay = Tkinter.BooleanVar(),
undo = Tkinter.BooleanVar(),
bookmarks = Tkinter.BooleanVar(),
hint = Tkinter.BooleanVar(),
shuffle = Tkinter.BooleanVar(),
highlight_piles = Tkinter.BooleanVar(),
highlight_cards = Tkinter.BooleanVar(),
highlight_samerank = Tkinter.BooleanVar(),
highlight_not_matching = Tkinter.BooleanVar(),
mahjongg_show_removed = Tkinter.BooleanVar(),
shisen_show_hint = Tkinter.BooleanVar(),
sound = Tkinter.BooleanVar(),
auto_scale = Tkinter.BooleanVar(),
cardback = Tkinter.IntVar(),
tabletile = Tkinter.IntVar(),
animations = Tkinter.IntVar(),
redeal_animation = Tkinter.BooleanVar(),
win_animation = Tkinter.BooleanVar(),
shadow = Tkinter.BooleanVar(),
shade = Tkinter.BooleanVar(),
shade_filled_stacks = Tkinter.BooleanVar(),
shrink_face_down = Tkinter.BooleanVar(),
toolbar = Tkinter.IntVar(),
toolbar_style = Tkinter.StringVar(),
toolbar_relief = Tkinter.StringVar(),
toolbar_compound = Tkinter.StringVar(),
toolbar_size = Tkinter.IntVar(),
statusbar = Tkinter.BooleanVar(),
num_cards = Tkinter.BooleanVar(),
helpbar = Tkinter.BooleanVar(),
save_games_geometry = Tkinter.BooleanVar(),
splashscreen = Tkinter.BooleanVar(),
demo_logo = Tkinter.BooleanVar(),
mouse_type = Tkinter.StringVar(),
mouse_undo = Tkinter.BooleanVar(),
negative_bottom = Tkinter.BooleanVar(),
pause = Tkinter.BooleanVar(),
theme = Tkinter.StringVar(),
gameid = tkinter.IntVar(),
gameid_popular = tkinter.IntVar(),
comment = tkinter.BooleanVar(),
autofaceup = tkinter.BooleanVar(),
autodrop = tkinter.BooleanVar(),
autodeal = tkinter.BooleanVar(),
quickplay = tkinter.BooleanVar(),
undo = tkinter.BooleanVar(),
bookmarks = tkinter.BooleanVar(),
hint = tkinter.BooleanVar(),
shuffle = tkinter.BooleanVar(),
highlight_piles = tkinter.BooleanVar(),
highlight_cards = tkinter.BooleanVar(),
highlight_samerank = tkinter.BooleanVar(),
highlight_not_matching = tkinter.BooleanVar(),
mahjongg_show_removed = tkinter.BooleanVar(),
shisen_show_hint = tkinter.BooleanVar(),
sound = tkinter.BooleanVar(),
auto_scale = tkinter.BooleanVar(),
cardback = tkinter.IntVar(),
tabletile = tkinter.IntVar(),
animations = tkinter.IntVar(),
redeal_animation = tkinter.BooleanVar(),
win_animation = tkinter.BooleanVar(),
shadow = tkinter.BooleanVar(),
shade = tkinter.BooleanVar(),
shade_filled_stacks = tkinter.BooleanVar(),
shrink_face_down = tkinter.BooleanVar(),
toolbar = tkinter.IntVar(),
toolbar_style = tkinter.StringVar(),
toolbar_relief = tkinter.StringVar(),
toolbar_compound = tkinter.StringVar(),
toolbar_size = tkinter.IntVar(),
statusbar = tkinter.BooleanVar(),
num_cards = tkinter.BooleanVar(),
helpbar = tkinter.BooleanVar(),
save_games_geometry = tkinter.BooleanVar(),
splashscreen = tkinter.BooleanVar(),
demo_logo = tkinter.BooleanVar(),
mouse_type = tkinter.StringVar(),
mouse_undo = tkinter.BooleanVar(),
negative_bottom = tkinter.BooleanVar(),
pause = tkinter.BooleanVar(),
theme = tkinter.StringVar(),
toolbar_vars = {},
)
for w in TOOLBAR_BUTTONS:
self.tkopt.toolbar_vars[w] = Tkinter.BooleanVar()
self.tkopt.toolbar_vars[w] = tkinter.BooleanVar()
def _setOptions(self):
tkopt, opt = self.tkopt, self.app.opt
@ -631,7 +631,7 @@ class PysolMenubarTk:
def _addSelectGameMenu(self, menu):
#games = map(self.app.gdb.get, self.app.gdb.getGamesIdSortedByShortName())
games = map(self.app.gdb.get, self.app.gdb.getGamesIdSortedByName())
games = list(map(self.app.gdb.get, self.app.gdb.getGamesIdSortedByName()))
##games = tuple(games)
###menu = MfxMenu(menu, label="Select &game")
m = "Ctrl-"
@ -670,7 +670,7 @@ class PysolMenubarTk:
if label is None:
need_sep = 1
continue
g = filter(select_func, games)
g = list(filter(select_func, games))
if not g:
continue
if need_sep:
@ -682,12 +682,12 @@ class PysolMenubarTk:
def _getNumGames(self, games, select_data):
ngames = 0
for label, select_func in select_data:
ngames += len(filter(select_func, games))
ngames += len(list(filter(select_func, games)))
return ngames
def _addSelectMahjonggGameSubMenu(self, games, menu, command, variable):
select_func = lambda gi: gi.si.game_type == GI.GT_MAHJONGG
mahjongg_games = filter(select_func, games)
mahjongg_games = list(filter(select_func, games))
if len(mahjongg_games) == 0:
return
#
@ -711,7 +711,7 @@ class PysolMenubarTk:
games[c].append(gi)
else:
games[c] = [gi]
games = games.items()
games = list(games.items())
games.sort()
g0 = []
c0 = c1 = games[0][0]
@ -727,7 +727,7 @@ class PysolMenubarTk:
def _addSelectPopularGameSubMenu(self, games, menu, command, variable):
select_func = lambda gi: gi.si.game_flags & GI.GT_POPULAR
if len(filter(select_func, games)) == 0:
if len(list(filter(select_func, games))) == 0:
return
data = (n_("&Popular games"), select_func)
self._addSelectGameSubMenu(games, menu, (data, ),
@ -760,7 +760,7 @@ class PysolMenubarTk:
def _addSelectCustomGameSubMenu(self, games, menu, command, variable):
submenu = MfxMenu(menu, label=n_("&Custom games"))
select_func = lambda gi: gi.si.game_type == GI.GT_CUSTOM
games = filter(select_func, games)
games = list(filter(select_func, games))
self.updateGamesMenu(submenu, games)
def _addSelectAllGameSubMenu(self, games, menu, command, variable):
@ -991,7 +991,7 @@ class PysolMenubarTk:
idir, ifile = "", ""
if not idir:
idir = self.app.dn.savegames
d = tkFileDialog.Open()
d = tkinter.filedialog.Open()
filename = d.show(filetypes=self.FILETYPES,
defaultextension=self.DEFAULTEXTENSION,
initialdir=idir, initialfile=ifile)
@ -1019,7 +1019,7 @@ class PysolMenubarTk:
if not idir:
idir = self.app.dn.savegames
##print self.game.filename, ifile
d = tkFileDialog.SaveAs()
d = tkinter.filedialog.SaveAs()
filename = d.show(filetypes=self.FILETYPES,
defaultextension=self.DEFAULTEXTENSION,
initialdir=idir, initialfile=ifile)
@ -1418,7 +1418,7 @@ the next time you restart """)+TITLE,
def wizardDialog(self, edit=False):
from pysollib.wizardutil import write_game, reset_wizard
from wizarddialog import WizardDialog
from .wizarddialog import WizardDialog
if edit:
reset_wizard(self.game)
@ -1431,7 +1431,7 @@ the next time you restart """)+TITLE,
gameid = write_game(self.app, game=self.game)
else:
gameid = write_game(self.app)
except Exception, err:
except Exception as err:
if DEBUG:
traceback.print_exc()
d = MfxMessageDialog(self.top, title=_('Save game error'),
@ -1446,9 +1446,9 @@ Error while saving game.
if SELECT_GAME_MENU:
menu = self.__menupath[".menubar.select.customgames"][2]
select_func = lambda gi: gi.si.game_type == GI.GT_CUSTOM
games = map(self.app.gdb.get,
self.app.gdb.getGamesIdSortedByName())
games = filter(select_func, games)
games = list(map(self.app.gdb.get,
self.app.gdb.getGamesIdSortedByName()))
games = list(filter(select_func, games))
self.updateGamesMenu(menu, games)
self.tkopt.gameid.set(gameid)

View file

@ -24,15 +24,15 @@
__all__ = ['PlayerOptionsDialog']
# imports
import Tkinter
import ttk
import tkinter
from . import ttk
# PySol imports
from pysollib.mygettext import _, n_
from pysollib.mfxutil import KwStruct
# Toolkit imports
from tkwidget import MfxDialog
from .tkwidget import MfxDialog
# ************************************************************************
@ -47,11 +47,11 @@ class PlayerOptionsDialog(MfxDialog):
self.createBitmaps(top_frame, kw)
self.app = app
#
self.update_stats_var = Tkinter.BooleanVar()
self.update_stats_var = tkinter.BooleanVar()
self.update_stats_var.set(app.opt.update_player_stats != 0)
self.confirm_var = Tkinter.BooleanVar()
self.confirm_var = tkinter.BooleanVar()
self.confirm_var.set(app.opt.confirm != 0)
self.win_animation_var = Tkinter.BooleanVar()
self.win_animation_var = tkinter.BooleanVar()
self.win_animation_var.set(app.opt.win_animation != 0)
#
frame = ttk.Frame(top_frame)

View file

@ -24,12 +24,12 @@
__all__ = ['PysolProgressBar']
# imports
import Tkinter
import ttk
import tkinter
from . import ttk
# Toolkit imports
from tkconst import EVENT_HANDLED
from tkutil import makeToplevel, setTransient
from .tkconst import EVENT_HANDLED
from .tkutil import makeToplevel, setTransient
# ************************************************************************
@ -119,8 +119,8 @@ class TestProgressBar:
self.progress.frame.after(30, self.update)
def progressbar_main(args):
from tkutil import wm_withdraw
tk = Tkinter.Tk()
from .tkutil import wm_withdraw
tk = tkinter.Tk()
wm_withdraw(tk)
pb = TestProgressBar(tk)
tk.mainloop()

View file

@ -26,8 +26,8 @@ __all__ = ['SelectCardsetDialogWithPreview']
# imports
import os
import traceback
import Tkinter
import ttk
import tkinter
from . import ttk
# PySol imports
from pysollib.mygettext import _, n_
@ -36,11 +36,11 @@ from pysollib.util import CARDSET
from pysollib.resource import CSI
# Toolkit imports
from tkutil import loadImage
from tkwidget import MfxDialog, MfxScrolledCanvas, PysolScale
from tkcanvas import MfxCanvasImage
from selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode
from selecttree import SelectDialogTreeData, SelectDialogTreeCanvas
from .tkutil import loadImage
from .tkwidget import MfxDialog, MfxScrolledCanvas, PysolScale
from .tkcanvas import MfxCanvasImage
from .selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode
from .selecttree import SelectDialogTreeData, SelectDialogTreeCanvas
# ************************************************************************
@ -73,7 +73,7 @@ class SelectCardsetData(SelectDialogTreeData):
self.no_contents = [ SelectCardsetLeaf(None, None, _("(no cardsets)"), key=None), ]
#
select_by_type = None
items = CSI.TYPE.items()
items = list(CSI.TYPE.items())
items.sort(lambda a, b: cmp(a[1], b[1]))
nodes = []
for key, name in items:
@ -83,7 +83,7 @@ class SelectCardsetData(SelectDialogTreeData):
select_by_type = SelectCardsetNode(None, _("by Type"), tuple(nodes), expanded=1)
#
select_by_style = None
items = CSI.STYLE.items()
items = list(CSI.STYLE.items())
items.sort(lambda a, b: cmp(a[1], b[1]))
nodes = []
for key, name in items:
@ -94,7 +94,7 @@ class SelectCardsetData(SelectDialogTreeData):
select_by_style = SelectCardsetNode(None, _("by Style"), tuple(nodes))
#
select_by_nationality = None
items = CSI.NATIONALITY.items()
items = list(CSI.NATIONALITY.items())
items.sort(lambda a, b: cmp(a[1], b[1]))
nodes = []
for key, name in items:
@ -105,7 +105,7 @@ class SelectCardsetData(SelectDialogTreeData):
select_by_nationality = SelectCardsetNode(None, _("by Nationality"), tuple(nodes))
#
select_by_date = None
items = CSI.DATE.items()
items = list(CSI.DATE.items())
items.sort(lambda a, b: cmp(a[1], b[1]))
nodes = []
for key, name in items:
@ -115,7 +115,7 @@ class SelectCardsetData(SelectDialogTreeData):
nodes.append(SelectCardsetNode(None, _("Uncategorized"), lambda cs: not cs.si.dates))
select_by_date = SelectCardsetNode(None, _("by Date"), tuple(nodes))
#
self.rootnodes = filter(None, (
self.rootnodes = [_f for _f in (
SelectCardsetNode(None, _("All Cardsets"), lambda cs: 1, expanded=len(self.all_objects)<=12),
SelectCardsetNode(None, _("by Size"), (
SelectCardsetNode(None, _("Tiny cardsets"), lambda cs: cs.si.size == CSI.SIZE_TINY),
@ -128,7 +128,7 @@ class SelectCardsetData(SelectDialogTreeData):
select_by_style,
select_by_date,
select_by_nationality,
))
) if _f]
class SelectCardsetByTypeData(SelectDialogTreeData):
@ -137,7 +137,7 @@ class SelectCardsetByTypeData(SelectDialogTreeData):
self.all_objects = manager.getAllSortedByName()
self.no_contents = [ SelectCardsetLeaf(None, None, _("(no cardsets)"), key=None), ]
#
items = CSI.TYPE.items()
items = list(CSI.TYPE.items())
items.sort(lambda a, b: cmp(a[1], b[1]))
nodes = []
for key, name in items:
@ -145,9 +145,9 @@ class SelectCardsetByTypeData(SelectDialogTreeData):
nodes.append(SelectCardsetNode(None, name, lambda cs, key=key: key == cs.si.type))
select_by_type = SelectCardsetNode(None, _("by Type"), tuple(nodes), expanded=1)
#
self.rootnodes = filter(None, (
self.rootnodes = [_f for _f in (
select_by_type,
))
) if _f]
# ************************************************************************
@ -207,7 +207,7 @@ class SelectCardsetDialogWithPreview(MfxDialog):
padx=padx, pady=pady)
if USE_PIL:
#
var = Tkinter.DoubleVar()
var = tkinter.DoubleVar()
var.set(app.opt.scale_x)
self.scale_x = PysolScale(
left_frame, label=_('Scale X:'),
@ -217,7 +217,7 @@ class SelectCardsetDialogWithPreview(MfxDialog):
command=self._updateScale)
self.scale_x.grid(row=1, column=0, sticky='ew', padx=padx, pady=pady)
#
var = Tkinter.DoubleVar()
var = tkinter.DoubleVar()
var.set(app.opt.scale_y)
self.scale_y = PysolScale(
left_frame, label=_('Scale Y:'),
@ -227,7 +227,7 @@ class SelectCardsetDialogWithPreview(MfxDialog):
command=self._updateScale)
self.scale_y.grid(row=2, column=0, sticky='ew', padx=padx, pady=pady)
#
self.auto_scale = Tkinter.BooleanVar()
self.auto_scale = tkinter.BooleanVar()
self.auto_scale.set(app.opt.auto_scale)
check = ttk.Checkbutton(
left_frame, text=_('Auto scaling'),
@ -238,7 +238,7 @@ class SelectCardsetDialogWithPreview(MfxDialog):
check.grid(row=3, column=0, columnspan=2, sticky='ew',
padx=padx, pady=pady)
#
self.preserve_aspect = Tkinter.BooleanVar()
self.preserve_aspect = tkinter.BooleanVar()
self.preserve_aspect.set(app.opt.preserve_aspect_ratio)
self.aspect_check = ttk.Checkbutton(
left_frame, text=_('Preserve aspect ratio'),
@ -452,7 +452,7 @@ class CardsetInfoDialog(MfxDialog):
settings_frame.grid(row=row, column=0, columnspan=2, sticky='ew',
padx=0, pady=5, ipadx=5, ipady=5)
row += 1
var = Tkinter.IntVar()
var = tkinter.IntVar()
self.x_offset = PysolScale(
settings_frame, label=_('X offset:'),
from_=5, to=40, resolution=1,
@ -462,7 +462,7 @@ class CardsetInfoDialog(MfxDialog):
)
self.x_offset.grid(row=0, column=0, sticky='ew',
padx=padx, pady=pady)
var = Tkinter.IntVar()
var = tkinter.IntVar()
self.y_offset = PysolScale(
settings_frame, label=_('Y offset:'),
from_=5, to=40, resolution=1,
@ -476,7 +476,7 @@ class CardsetInfoDialog(MfxDialog):
##bg = top_frame["bg"]
bg = 'white'
text_w = Tkinter.Text(frame, bd=1, relief="sunken", wrap="word",
text_w = tkinter.Text(frame, bd=1, relief="sunken", wrap="word",
padx=4, width=64, height=16, bg=bg)
text_w.grid(row=row, column=0, sticky='nsew')
sb = ttk.Scrollbar(frame)

View file

@ -24,8 +24,8 @@
# imports
import os
import ttk
from UserList import UserList
from . import ttk
from collections import UserList
# PySol imports
from pysollib.mygettext import _, n_
@ -35,10 +35,10 @@ from pysollib.gamedb import GI
from pysollib.resource import CSI
# Toolkit imports
from tkutil import unbind_destroy
from tkwidget import MfxDialog, MfxScrolledCanvas
from selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode
from selecttree import SelectDialogTreeData, SelectDialogTreeCanvas
from .tkutil import unbind_destroy
from .tkwidget import MfxDialog, MfxScrolledCanvas
from .selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode
from .selecttree import SelectDialogTreeData, SelectDialogTreeCanvas
# ************************************************************************
@ -80,7 +80,7 @@ class SelectGameNode(SelectDialogTreeNode):
class SelectGameData(SelectDialogTreeData):
def __init__(self, app):
SelectDialogTreeData.__init__(self)
self.all_games_gi = map(app.gdb.get, app.gdb.getGamesIdSortedByName())
self.all_games_gi = list(map(app.gdb.get, app.gdb.getGamesIdSortedByName()))
self.no_games = [ SelectGameLeaf(None, None, _("(no games)"), None), ]
#
s_by_type = s_oriental = s_special = s_original = s_contrib = s_mahjongg = None
@ -93,13 +93,13 @@ class SelectGameData(SelectDialogTreeData):
):
gg = []
for name, select_func in data:
if name is None or not filter(select_func, self.all_games_gi):
if name is None or not list(filter(select_func, self.all_games_gi)):
continue
gg.append(SelectGameNode(None, _(name), select_func))
g.append(gg)
select_mahjongg_game = lambda gi: gi.si.game_type == GI.GT_MAHJONGG
gg = None
if filter(select_mahjongg_game, self.all_games_gi):
if list(filter(select_mahjongg_game, self.all_games_gi)):
gg = SelectGameNode(None, _("Mahjongg Games"),
select_mahjongg_game)
g.append(gg)
@ -123,7 +123,7 @@ class SelectGameData(SelectDialogTreeData):
s_by_compatibility, gg = None, []
for name, games in GI.GAMES_BY_COMPATIBILITY:
select_func = lambda gi, games=games: gi.id in games
if name is None or not filter(select_func, self.all_games_gi):
if name is None or not list(filter(select_func, self.all_games_gi)):
continue
gg.append(SelectGameNode(None, name, select_func))
if 1 and gg:
@ -133,7 +133,7 @@ class SelectGameData(SelectDialogTreeData):
s_by_pysol_version, gg = None, []
for name, games in GI.GAMES_BY_PYSOL_VERSION:
select_func = lambda gi, games=games: gi.id in games
if name is None or not filter(select_func, self.all_games_gi):
if name is None or not list(filter(select_func, self.all_games_gi)):
continue
name = _("New games in v. ") + name
gg.append(SelectGameNode(None, name, select_func))
@ -143,7 +143,7 @@ class SelectGameData(SelectDialogTreeData):
s_by_inventors, gg = None, []
for name, games in GI.GAMES_BY_INVENTORS:
select_func = lambda gi, games=games: gi.id in games
if name is None or not filter(select_func, self.all_games_gi):
if name is None or not list(filter(select_func, self.all_games_gi)):
continue
gg.append(SelectGameNode(None, name, select_func))
if 1 and gg:
@ -152,7 +152,7 @@ class SelectGameData(SelectDialogTreeData):
#
ul_alternate_names = UserList(list(app.gdb.getGamesTuplesSortedByAlternateName()))
#
self.rootnodes = filter(None, (
self.rootnodes = [_f for _f in (
SelectGameNode(None, _("All Games"), None, expanded=0),
SelectGameNode(None, _("Alternate Names"), ul_alternate_names),
SelectGameNode(None, _("Popular Games"),
@ -238,7 +238,7 @@ class SelectGameData(SelectDialogTreeData):
)),
s_original,
s_contrib,
))
) if _f]
# ************************************************************************

View file

@ -23,18 +23,18 @@
# imports
import Tkinter
import ttk
import tkColorChooser
import tkinter
from . import ttk
import tkinter.colorchooser
# PySol imports
from pysollib.mygettext import _, n_
from pysollib.mfxutil import KwStruct
# Toolkit imports
from tkwidget import MfxDialog, MfxScrolledCanvas
from selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode
from selecttree import SelectDialogTreeData, SelectDialogTreeCanvas
from .tkwidget import MfxDialog, MfxScrolledCanvas
from .selecttree import SelectDialogTreeLeaf, SelectDialogTreeNode
from .selecttree import SelectDialogTreeData, SelectDialogTreeCanvas
# ************************************************************************
@ -158,17 +158,17 @@ class SelectTileDialogWithPreview(MfxDialog):
def mDone(self, button):
if button == 0: # "OK" or double click
if isinstance(self.tree.selection_key, basestring):
if isinstance(self.tree.selection_key, str):
self.key = str(self.tree.selection_key)
else:
self.key = self.tree.selection_key
self.tree.n_expansions = 1 # save xyview in any case
if button == 10: # "Solid color..."
try:
c = tkColorChooser.askcolor(master=self.top,
c = tkinter.colorchooser.askcolor(master=self.top,
initialcolor=self.table_color,
title=_("Select table color"))
except Tkinter.TclError:
except tkinter.TclError:
pass
else:
if c and c[1]:
@ -185,7 +185,7 @@ class SelectTileDialogWithPreview(MfxDialog):
return
canvas = self.preview.canvas
canvas.deleteAllItems()
if isinstance(key, basestring):
if isinstance(key, str):
# solid color
canvas.config(bg=key)
canvas.setTile(None)

View file

@ -24,10 +24,10 @@
__all__ = ['SelectDialogTreeData']
# imports
import tkFont
import tkinter.font
# Toolkit imports
from tktree import MfxTreeLeaf, MfxTreeNode, MfxTreeInCanvas
from .tktree import MfxTreeLeaf, MfxTreeNode, MfxTreeInCanvas
# ************************************************************************
@ -110,7 +110,7 @@ class SelectDialogTreeCanvas(MfxTreeInCanvas):
self.style.height = 14 # height of symbol
if font:
self.style.font = font
f = tkFont.Font(parent, font)
f = tkinter.font.Font(parent, font)
h = f.metrics()["linespace"]
self.style.disty = max(self.style.width, h)

View file

@ -30,8 +30,8 @@ __all__ = [
]
# imports
import Tkinter
import ttk
import tkinter
from . import ttk
# PySol imports
from pysollib.mygettext import _, n_
@ -39,9 +39,9 @@ from pysollib.settings import TITLE
from pysollib.mfxutil import KwStruct
# Toolkit imports
from tkconst import EVENT_HANDLED
from tkwidget import MfxDialog
from tkwidget import PysolCombo
from .tkconst import EVENT_HANDLED
from .tkwidget import MfxDialog
from .tkwidget import PysolCombo
# ************************************************************************
@ -104,27 +104,27 @@ class SolverDialog(MfxDialog):
#
row += 1
self.max_iters_var = Tkinter.IntVar()
self.max_iters_var = tkinter.IntVar()
self.max_iters_var.set(10e4)
ttk.Label(frame, text=_('Max iterations:'), anchor='w'
).grid(row=row, column=0, sticky='ew', padx=2, pady=2)
spin = Tkinter.Spinbox(frame, bg='white', from_=1000, to=10e6,
spin = tkinter.Spinbox(frame, bg='white', from_=1000, to=10e6,
increment=1000, textvariable=self.max_iters_var)
spin.grid(row=row, column=1, sticky='w', padx=2, pady=2)
#
row += 1
self.max_depth_var = Tkinter.IntVar()
self.max_depth_var = tkinter.IntVar()
self.max_depth_var.set(1000)
ttk.Label(frame, text=_('Max depth:'), anchor='w'
).grid(row=row, column=0, sticky='ew', padx=2, pady=2)
spin = Tkinter.Spinbox(frame, bg='white', from_=100, to=10000,
spin = tkinter.Spinbox(frame, bg='white', from_=100, to=10000,
increment=100, textvariable=self.max_depth_var)
spin.grid(row=row, column=1, sticky='w', padx=2, pady=2)
#
row += 1
self.progress_var = Tkinter.BooleanVar()
self.progress_var = tkinter.BooleanVar()
self.progress_var.set(True)
w = ttk.Checkbutton(frame, variable=self.progress_var,
text=_('Show progress'))

View file

@ -25,8 +25,8 @@ __all__ = ['SoundOptionsDialog']
# imports
import os
import Tkinter
import ttk
import tkinter
from . import ttk
# PySol imports
from pysollib.mygettext import _, n_
@ -35,9 +35,9 @@ from pysollib.settings import TITLE
from pysollib.pysolaudio import pysolsoundserver
# Toolkit imports
from tkconst import EVENT_HANDLED
from tkwidget import MfxDialog, MfxMessageDialog
from tkwidget import PysolScale
from .tkconst import EVENT_HANDLED
from .tkwidget import MfxDialog, MfxMessageDialog
from .tkwidget import PysolScale
# ************************************************************************
@ -54,42 +54,42 @@ class SoundOptionsDialog(MfxDialog):
self.createBitmaps(top_frame, kw)
#
self.saved_opt = app.opt.copy()
self.sound = Tkinter.BooleanVar()
self.sound = tkinter.BooleanVar()
self.sound.set(app.opt.sound != 0)
self.sound_mode = Tkinter.BooleanVar()
self.sound_mode = tkinter.BooleanVar()
self.sound_mode.set(app.opt.sound_mode != 0)
self.sample_volume = Tkinter.IntVar()
self.sample_volume = tkinter.IntVar()
self.sample_volume.set(app.opt.sound_sample_volume)
self.music_volume = Tkinter.IntVar()
self.music_volume = tkinter.IntVar()
self.music_volume.set(app.opt.sound_music_volume)
self.samples = [
('areyousure', _('Are You Sure'), Tkinter.BooleanVar()),
('areyousure', _('Are You Sure'), tkinter.BooleanVar()),
('deal', _('Deal'), Tkinter.BooleanVar()),
('dealwaste', _('Deal waste'), Tkinter.BooleanVar()),
('deal', _('Deal'), tkinter.BooleanVar()),
('dealwaste', _('Deal waste'), tkinter.BooleanVar()),
('turnwaste', _('Turn waste'), Tkinter.BooleanVar()),
('startdrag', _('Start drag'), Tkinter.BooleanVar()),
('turnwaste', _('Turn waste'), tkinter.BooleanVar()),
('startdrag', _('Start drag'), tkinter.BooleanVar()),
('drop', _('Drop'), Tkinter.BooleanVar()),
('droppair', _('Drop pair'), Tkinter.BooleanVar()),
('autodrop', _('Auto drop'), Tkinter.BooleanVar()),
('drop', _('Drop'), tkinter.BooleanVar()),
('droppair', _('Drop pair'), tkinter.BooleanVar()),
('autodrop', _('Auto drop'), tkinter.BooleanVar()),
('flip', _('Flip'), Tkinter.BooleanVar()),
('autoflip', _('Auto flip'), Tkinter.BooleanVar()),
('move', _('Move'), Tkinter.BooleanVar()),
('nomove', _('No move'), Tkinter.BooleanVar()),
('flip', _('Flip'), tkinter.BooleanVar()),
('autoflip', _('Auto flip'), tkinter.BooleanVar()),
('move', _('Move'), tkinter.BooleanVar()),
('nomove', _('No move'), tkinter.BooleanVar()),
('undo', _('Undo'), Tkinter.BooleanVar()),
('redo', _('Redo'), Tkinter.BooleanVar()),
('undo', _('Undo'), tkinter.BooleanVar()),
('redo', _('Redo'), tkinter.BooleanVar()),
('autopilotlost', _('Autopilot lost'), Tkinter.BooleanVar()),
('autopilotwon', _('Autopilot won'), Tkinter.BooleanVar()),
('autopilotlost', _('Autopilot lost'), tkinter.BooleanVar()),
('autopilotwon', _('Autopilot won'), tkinter.BooleanVar()),
('gamefinished', _('Game finished'), Tkinter.BooleanVar()),
('gamelost', _('Game lost'), Tkinter.BooleanVar()),
('gamewon', _('Game won'), Tkinter.BooleanVar()),
('gameperfect', _('Perfect game'), Tkinter.BooleanVar()),
('gamefinished', _('Game finished'), tkinter.BooleanVar()),
('gamelost', _('Game lost'), tkinter.BooleanVar()),
('gamewon', _('Game won'), tkinter.BooleanVar()),
('gameperfect', _('Perfect game'), tkinter.BooleanVar()),
]
#

View file

@ -26,20 +26,20 @@ __all__ = ['PysolStatusbar',
# imports
import os, sys
import Tkinter
import ttk
import tkinter
from . import ttk
from pysollib.mygettext import _, n_
if __name__ == '__main__':
d = os.path.abspath(os.path.join(sys.path[0], os.pardir, os.pardir))
sys.path.append(d)
import gettext
gettext.install('pysol', d, unicode=True)
gettext.install('pysol', d, str=True)
# PySol imports
# Toolkit imports
from tkwidget import MfxTooltip
from .tkwidget import MfxTooltip
# ************************************************************************
# *
@ -96,9 +96,9 @@ class MfxStatusbar:
#
def updateText(self, **kw):
for k, v in kw.items():
for k, v in list(kw.items()):
label = getattr(self, k + '_label')
text = unicode(v)
text = str(v)
width = label['width']
if width and len(text) > width:
label['width'] = len(text)
@ -193,7 +193,7 @@ class TestStatusbar(PysolStatusbar):
self.updateText(info='Some info text.')
def statusbar_main(args):
tk = Tkinter.Tk()
tk = tkinter.Tk()
statusbar = TestStatusbar(tk, args)
tk.mainloop()
return 0

View file

@ -24,15 +24,15 @@
__all__ = ['TimeoutsDialog']
# imports
import Tkinter
import ttk
import tkinter
from . import ttk
# PySol imports
from pysollib.mygettext import _, n_
from pysollib.mfxutil import KwStruct
# Toolkit imports
from tkwidget import MfxDialog, PysolScale
from .tkwidget import MfxDialog, PysolScale
# ************************************************************************
@ -50,17 +50,17 @@ class TimeoutsDialog(MfxDialog):
frame.pack(expand=True, fill='both', padx=5, pady=10)
frame.columnconfigure(0, weight=1)
self.demo_sleep_var = Tkinter.DoubleVar()
self.demo_sleep_var = tkinter.DoubleVar()
self.demo_sleep_var.set(app.opt.timeouts['demo'])
self.hint_sleep_var = Tkinter.DoubleVar()
self.hint_sleep_var = tkinter.DoubleVar()
self.hint_sleep_var.set(app.opt.timeouts['hint'])
self.raise_card_sleep_var = Tkinter.DoubleVar()
self.raise_card_sleep_var = tkinter.DoubleVar()
self.raise_card_sleep_var.set(app.opt.timeouts['raise_card'])
self.highlight_piles_sleep_var = Tkinter.DoubleVar()
self.highlight_piles_sleep_var = tkinter.DoubleVar()
self.highlight_piles_sleep_var.set(app.opt.timeouts['highlight_piles'])
self.highlight_cards_sleep_var = Tkinter.DoubleVar()
self.highlight_cards_sleep_var = tkinter.DoubleVar()
self.highlight_cards_sleep_var.set(app.opt.timeouts['highlight_cards'])
self.highlight_samerank_sleep_var = Tkinter.DoubleVar()
self.highlight_samerank_sleep_var = tkinter.DoubleVar()
self.highlight_samerank_sleep_var.set(app.opt.timeouts['highlight_samerank'])
#
lframe = ttk.LabelFrame(frame, text=_('Set delays in seconds'),

Some files were not shown because too many files have changed in this diff Show more