Skip to content

Commit

Permalink
Refactoring / code cleanup.
Browse files Browse the repository at this point in the history
  • Loading branch information
shlomif committed May 31, 2019
1 parent 26e5aeb commit 9acc97b
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 62 deletions.
13 changes: 2 additions & 11 deletions pysollib/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,15 +518,12 @@ def mEditGameComment(self, *args):
text += os.linesep
enc = locale.getpreferredencoding()
try:
fd = open(fn, 'a')
fd.write(text.encode(enc, 'replace'))
open(fn, 'a').write(text.encode(enc, 'replace'))
except Exception as err:
d = MfxExceptionDialog(
self.top, err,
text=_("Error while writing to file"))
else:
if fd:
fd.close()
d = MfxMessageDialog(
self.top, title=TITLE+_(" Info"), bitmap="info",
text=_("Comments were appended to\n\n") + fn)
Expand All @@ -537,7 +534,6 @@ def mEditGameComment(self, *args):
#

def _mStatsSave(self, player, filename, write_method):
file = None
if player is None:
text = _("Demo statistics")
filename = filename + "_demo"
Expand All @@ -546,17 +542,12 @@ def _mStatsSave(self, player, filename, write_method):
filename = os.path.join(self.app.dn.config, filename + ".txt")
filename = os.path.normpath(filename)
try:
file = open(filename, "a")
a = FileStatsFormatter(self.app, file)
a = FileStatsFormatter(self.app, open(filename, "a"))
write_method(a, player)
except EnvironmentError as ex:
if file:
file.close()
MfxExceptionDialog(self.top, ex,
text=_("Error while writing to file"))
else:
if file:
file.close()
MfxMessageDialog(
self.top, title=TITLE+_(" Info"), bitmap="info",
text=text + _(" were appended to\n\n") + filename)
Expand Down
11 changes: 3 additions & 8 deletions pysollib/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -1059,13 +1059,8 @@ def loadPlugins(self, dirname):

# read & parse a cardset config.txt file - see class Cardset in resource.py
def _readCardsetConfig(self, dirname, filename):
f = None
try:
f = open(filename, "r")
with open(filename, "r") as f:
lines = f.readlines()
finally:
if f:
f.close()
lines = [l.strip() for l in lines]
if not lines[0].startswith("PySol"):
return None
Expand Down Expand Up @@ -1309,7 +1304,7 @@ def _my_list_dir(self, dirname):
#

def initResource(self, manager, dirs, ext_re, Resource_Class):
found, t = [], {}
found, t = [], set()
for dirname in dirs:
dirname = dirname.strip()
if dirname:
Expand All @@ -1328,7 +1323,7 @@ def initResource(self, manager, dirs, ext_re, Resource_Class):
obj.name = n
key = n.lower()
if key not in t:
t[key] = 1
t.add(key)
found.append((n, obj))
except EnvironmentError:
pass
Expand Down
19 changes: 4 additions & 15 deletions pysollib/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -3165,14 +3165,9 @@ def saveGame(self, filename, protocol=-1):

def _loadGame(self, filename, app):
game = None
f = None
try:
f = open(filename, "rb")
with open(filename, "rb") as f:
game = self._undumpGame(Unpickler(f), app)
game.gstats.loaded = game.gstats.loaded + 1
finally:
if f:
f.close()
return game

def _undumpGame(self, p, app):
Expand Down Expand Up @@ -3269,15 +3264,9 @@ def validate(v, txt):
return game

def _saveGame(self, filename, protocol=-1):
f = None
try:
if not self.canSaveGame():
raise Exception("Cannot save this game.")
f = open(filename, "wb")
self._dumpGame(Pickler(f, protocol))
finally:
if f:
f.close()
if self.canSaveGame():
with open(filename, "wb") as f:
self._dumpGame(Pickler(f, protocol))

def _dumpGame(self, p, bookmark=0):
self.updateTime()
Expand Down
55 changes: 27 additions & 28 deletions pysollib/wizardutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -399,11 +399,11 @@ def write_game(app, game=None):
check_game = False

# print '===>', fn
fd = open(fn, 'w')
with open(fn, 'w') as fd:

fd.write('''\
fd.write('''\
## -*- coding: utf-8 -*-
## THIS FILE WAS GENERATED AUTOMATICALLY BY SOLITAIRE WIZARD
## THIS FILE WAS GENERATED AUTOMATICALLY BY THE SOLITAIRE WIZARD
## DO NOT EDIT
from pysollib.customgame import CustomGame, registerCustomGame
Expand All @@ -413,35 +413,34 @@ class MyCustomGame(CustomGame):
SETTINGS = {
''')

for w in WizardWidgets:
if isinstance(w, six.string_types):
continue
v = w.variable.get()
if w.widget in ('menu', 'preset'):
v = w.translation_map[v]
if v == w.default:
# save only unique values
continue
if isinstance(v, int):
fd.write(" '%s': %i,\n" % (w.var_name, v))
else:
if w.var_name == 'name':
# escape
v = v.replace('\\', '\\\\')
v = v.replace("'", "\\'")
if isinstance(v, six.text_type):
v = v.encode('utf-8')
if not v:
v = 'Invalid Game Name'
fd.write(" '%s': '%s',\n" % (w.var_name, v))
fd.write(" 'gameid': %i,\n" % gameid)
for w in WizardWidgets:
if isinstance(w, six.string_types):
continue
v = w.variable.get()
if w.widget in ('menu', 'preset'):
v = w.translation_map[v]
if v == w.default:
# save only unique values
continue
if isinstance(v, int):
fd.write(" '%s': %i,\n" % (w.var_name, v))
else:
if w.var_name == 'name':
# escape
v = v.replace('\\', '\\\\')
v = v.replace("'", "\\'")
if isinstance(v, six.text_type):
v = v.encode('utf-8')
if not v:
v = 'Invalid Game Name'
fd.write(" '%s': '%s',\n" % (w.var_name, v))
fd.write(" 'gameid': %i,\n" % gameid)

fd.write('''\
}
fd.write('''\
}
registerCustomGame(MyCustomGame)
''')
fd.close()

loadGame(mn, fn, check_game=check_game)

Expand Down

0 comments on commit 9acc97b

Please sign in to comment.