summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDiego Roversi <diegor@tiscali.it>2019-09-08 22:05:57 +0200
committerDiego Roversi <diegor@tiscali.it>2019-09-08 22:05:57 +0200
commitc23b138ed72d794521b19ff7d8076b32b0b7bf46 (patch)
treec8e82a4ca4da05ba1ad28d4ff64a157bc1eb7952
parent1d9925c287b318ec21343e2682b51ab6a36ae8db (diff)
2to3
-rwxr-xr-xBubBob.py48
-rwxr-xr-xbubbob/bb.py76
-rw-r--r--bubbob/binboards.py12
-rw-r--r--bubbob/boards.py48
-rw-r--r--bubbob/bonuses.py40
-rw-r--r--bubbob/bubbles.py20
-rw-r--r--bubbob/command.py2
-rw-r--r--bubbob/images.py27
-rw-r--r--bubbob/macbinary.py26
-rw-r--r--bubbob/mnstrmap.py6
-rw-r--r--bubbob/monsters.py4
-rw-r--r--bubbob/player.py24
-rw-r--r--bubbob/ranking.py16
-rw-r--r--bubbob/save_rnglevel.py34
-rw-r--r--bubbob/statesaver.py16
-rw-r--r--bubbob/test_rnglevel.py12
-rw-r--r--bubbob/test_statesaver.py34
-rw-r--r--common/gamesrv.py132
-rw-r--r--common/hostchooser.py59
-rw-r--r--common/javaserver.py12
-rw-r--r--common/msgstruct.py60
-rw-r--r--common/pixmap.py18
-rw-r--r--common/stdlog.py6
-rw-r--r--common/udpovertcp.py10
-rw-r--r--metaserver/metaclient.py162
-rw-r--r--metaserver/metaserver.py50
-rw-r--r--metaserver/metastruct.py4
-rw-r--r--metaserver/pipelayer.py16
-rw-r--r--metaserver/socketoverudp.py4
29 files changed, 493 insertions, 485 deletions
diff --git a/BubBob.py b/BubBob.py
index 52820c3..fc60258 100755
--- a/BubBob.py
+++ b/BubBob.py
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#! /usr/bin/env python3
#
# This script is used to start the server.
@@ -9,7 +9,7 @@
# __________
import os, sys
-print 'Running on Python', sys.version
+print(( 'Running on Python', sys.version ))
if __name__ == '__main__':
LOCALDIR = sys.argv[0]
else:
@@ -61,12 +61,12 @@ def look_for_local_server():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect(('127.0.0.1', port))
- except socket.error, e:
+ except socket.error as e:
return None
try:
s.shutdown(2)
s.close()
- except Exception, e:
+ except Exception as e:
pass
url2, port2 = load_url_file()
if port2 != port:
@@ -93,9 +93,9 @@ def start_local_server():
else:
httppages.main(None, TAGFILENAME, 0)
if logfile:
- print >> logfile
+ print(file=logfile)
if logfile:
- print "Logging to", logfile.filename
+ print("Logging to", logfile.filename)
fd = logfile.f.fileno()
try:
# detach from parent
@@ -130,35 +130,35 @@ if not url:
if url:
break
else:
- print >> sys.stderr, 'The local server is not starting, giving up.'
+ print('The local server is not starting, giving up.', file=sys.stderr)
sys.exit(1)
try:
import webbrowser
browser = webbrowser.get()
name = getattr(browser, 'name', browser.__class__.__name__)
- print "Trying to open '%s' with '%s'..." % (url, name)
+ print("Trying to open '%s' with '%s'..." % (url, name))
browser.open(url)
except:
exc, val, tb = sys.exc_info()
- print '-'*60
- print >> sys.stderr, "Failed to launch the web browser:"
- print >> sys.stderr, " %s: %s" % (exc.__name__, val)
- print
- print "Sorry, I guess you have to go to the following URL manually:"
+ print('-'*60)
+ print("Failed to launch the web browser:", file=sys.stderr)
+ print(" %s: %s" % (exc.__name__, val), file=sys.stderr)
+ print()
+ print("Sorry, I guess you have to go to the following URL manually:")
else:
- print "Done running '%s'." % name
+ print("Done running '%s'." % name)
if look_for_local_server() != url:
# assume that browser.open() waited for the browser to finish
# and that the server has been closed from the browser.
raise SystemExit
- print
- print '-'*60
- print "If the browser fails to open the page automatically,"
- print "you will have to manually go to the following URL:"
-print ' ', url
-print '-'*60
-print "Note that the server runs in the background. You have to use"
-print "the 'Stop this program' link to cleanly stop it."
-print "Normally, however, running this script multiple times should"
-print "not create multiple servers in the background."
+ print()
+ print('-'*60)
+ print("If the browser fails to open the page automatically,")
+ print("you will have to manually go to the following URL:")
+print(' ', url)
+print('-'*60)
+print("Note that the server runs in the background. You have to use")
+print("the 'Stop this program' link to cleanly stop it.")
+print("Normally, however, running this script multiple times should")
+print("not create multiple servers in the background.")
diff --git a/bubbob/bb.py b/bubbob/bb.py
index c0ab351..49b4349 100755
--- a/bubbob/bb.py
+++ b/bubbob/bb.py
@@ -1,6 +1,6 @@
#! /usr/bin/env python
-from __future__ import generators
+
# __________
import os, sys
@@ -89,11 +89,11 @@ class BubBobGame(gamesrv.Game):
if self.metaregister:
self.do_updatemetaserver()
frametime = 0.0
- for i in xrange(500):
+ for i in range(500):
import boards
for gen in boards.BoardGen[:]:
try:
- frametime += gen.next()
+ frametime += next(gen)
except StopIteration:
try:
boards.BoardGen.remove(gen)
@@ -110,7 +110,7 @@ class BubBobGame(gamesrv.Game):
self.game_reset_gen = boards.game_reset()
else:
try:
- self.game_reset_gen.next()
+ next(self.game_reset_gen)
except StopIteration:
self.game_reset_gen = None
return frametime * boards.FRAME_TIME
@@ -132,9 +132,9 @@ class BubBobGame(gamesrv.Game):
if kbd and not [p for p in BubPlayer.PlayerList if p.isplaying()]:
return 0
import traceback
- print "-"*60
+ print("-"*60)
traceback.print_exc()
- print "-"*60
+ print("-"*60)
if not kbd:
try:
if self.metaserver:
@@ -145,15 +145,15 @@ class BubBobGame(gamesrv.Game):
else:
if metaclient.metaclisrv:
metaclient.metaclisrv.send_traceback()
- except Exception, e:
- print '! %s: %s' % (e.__class__.__name__, e)
+ except Exception as e:
+ print('! %s: %s' % (e.__class__.__name__, e))
import boards
num = getattr(boards.curboard, 'num', None)
if self.Quiet:
- print "Crash recovery! Automatically restarting board %s" % num
+ print("Crash recovery! Automatically restarting board %s" % num)
import time; time.sleep(2)
else:
- print "Correct the problem and leave pdb to restart board %s..."%num
+ print("Correct the problem and leave pdb to restart board %s..."%num)
import pdb; pdb.post_mortem(sys.exc_info()[2])
self.openboard(num)
return 1
@@ -183,7 +183,7 @@ class BubBobGame(gamesrv.Game):
setuppath('metaserver')
import metaclient
metaclient.meta_register(self)
- print '.'
+ print('.')
else:
try:
import metaclient
@@ -201,8 +201,8 @@ class BubBobGame(gamesrv.Game):
def setuppath(dirname):
dir = os.path.abspath(os.path.join(LOCALDIR, os.pardir, dirname))
if not os.path.isdir(dir):
- print >> sys.stderr, (
- '../%s: directory not found ("cvs update -d" ?)' % dirname)
+ print((
+ '../%s: directory not found ("cvs update -d" ?)' % dirname), file=sys.stderr)
sys.exit(1)
if dir not in sys.path:
sys.path.insert(0, dir)
@@ -210,28 +210,28 @@ def setuppath(dirname):
def parse_cmdline(argv):
# parse command-line
def usage():
- print >> sys.stderr, 'usage:'
- print >> sys.stderr, ' python bb.py'
+ print('usage:', file=sys.stderr)
+ print(' python bb.py', file=sys.stderr)
## print >> sys.stderr, ' python bb.py [-w/--webbrowser=no]'
## print >> sys.stderr, 'where:'
## print >> sys.stderr, ' -w --webbrowser=no don''t automatically start web browser'
- print >> sys.stderr, 'or:'
- print >> sys.stderr, ' python bb.py [level-file.bin] [-m] [-b#] [-s#] [-l#] [-M#]'
- print >> sys.stderr, 'with options:'
- print >> sys.stderr, ' -m --metaserver register the server on the Metaserver so anyone can join'
- print >> sys.stderr, ' -b# --begin # start at board number # (default 1)'
- print >> sys.stderr, ' --start # synonym for --begin'
- print >> sys.stderr, ' --final # end at board number # (default 100)'
- print >> sys.stderr, ' -s# --step # advance board number by steps of # (default 1)'
- print >> sys.stderr, ' -l# --lives # limit the number of lives to #'
- print >> sys.stderr, ' --extralife # gain extra life every # points'
- print >> sys.stderr, ' --limitlives # max # of lives player can gain in one board'
- print >> sys.stderr, ' -M# --monsters # multiply the number of monsters by #'
- print >> sys.stderr, ' (default between 1.0 and 2.0 depending on # of players)'
- print >> sys.stderr, ' -i --infinite restart the server at the end of the game'
- print >> sys.stderr, ' --port LISTEN=# set fixed tcp port for game server'
- print >> sys.stderr, ' --port HTTP=# set fixed tcp port for http server'
- print >> sys.stderr, ' -h --help display this text'
+ print('or:', file=sys.stderr)
+ print(' python bb.py [level-file.bin] [-m] [-b#] [-s#] [-l#] [-M#]', file=sys.stderr)
+ print('with options:', file=sys.stderr)
+ print(' -m --metaserver register the server on the Metaserver so anyone can join', file=sys.stderr)
+ print(' -b# --begin # start at board number # (default 1)', file=sys.stderr)
+ print(' --start # synonym for --begin', file=sys.stderr)
+ print(' --final # end at board number # (default 100)', file=sys.stderr)
+ print(' -s# --step # advance board number by steps of # (default 1)', file=sys.stderr)
+ print(' -l# --lives # limit the number of lives to #', file=sys.stderr)
+ print(' --extralife # gain extra life every # points', file=sys.stderr)
+ print(' --limitlives # max # of lives player can gain in one board', file=sys.stderr)
+ print(' -M# --monsters # multiply the number of monsters by #', file=sys.stderr)
+ print(' (default between 1.0 and 2.0 depending on # of players)', file=sys.stderr)
+ print(' -i --infinite restart the server at the end of the game', file=sys.stderr)
+ print(' --port LISTEN=# set fixed tcp port for game server', file=sys.stderr)
+ print(' --port HTTP=# set fixed tcp port for http server', file=sys.stderr)
+ print(' -h --help display this text', file=sys.stderr)
#print >> sys.stderr, ' -rxxx record the game in file xxx'
sys.exit(1)
@@ -246,9 +246,9 @@ def parse_cmdline(argv):
'lives=', 'monsters=', 'infinite', 'help',
'extralife=', 'limitlives=', 'final=',
'saveurlto=', 'quiet', 'port=', 'makeimages'])
- except error, e:
- print >> sys.stderr, 'bb.py: %s' % str(e)
- print >> sys.stderr
+ except error as e:
+ print('bb.py: %s' % str(e), file=sys.stderr)
+ print(file=sys.stderr)
usage()
options = {}
@@ -269,7 +269,7 @@ def parse_cmdline(argv):
elif key in ('--final'):
options['finalboard'] = int(value)
if options['finalboard'] < options['beginboard']:
- print >> sys.stderr, 'bb.py: final board value must be larger than begin board.'
+ print('bb.py: final board value must be larger than begin board.', file=sys.stderr)
sys.exit(1)
elif key in ('--extralife'):
options['extralife'] = int(value)
@@ -295,14 +295,14 @@ def parse_cmdline(argv):
# webbrowser = value.startswith('y')
if args:
if len(args) > 1:
- print >> sys.stderr, 'bb.py: multiple level files specified'
+ print('bb.py: multiple level files specified', file=sys.stderr)
sys.exit(1)
levelfile = os.path.abspath(args[0])
os.chdir(LOCALDIR)
BubBobGame(levelfile, **options)
else:
if options:
- print >> sys.stderr, 'bb.py: command-line options ignored'
+ print('bb.py: command-line options ignored', file=sys.stderr)
start_metaserver(save_url_to, quiet)
def start_metaserver(save_url_to, quiet):
diff --git a/bubbob/binboards.py b/bubbob/binboards.py
index af878ff..110d8ed 100644
--- a/bubbob/binboards.py
+++ b/bubbob/binboards.py
@@ -20,7 +20,8 @@ def meancolor(img):
b1 += b
return r1/count, g1/count, b1/count
-def addshadow(img, (r1, g1, b1), depth=8):
+def addshadow(img, xxx_todo_changeme, depth=8):
+ (r1, g1, b1) = xxx_todo_changeme
w = len(img[0])
h = len(img)
pad = depth * [keycol]
@@ -35,7 +36,8 @@ def addshadow(img, (r1, g1, b1), depth=8):
result[1+d+i][w+d] = color
return result
-def addrshadow(img, (r1, g1, b1), depth=8):
+def addrshadow(img, xxx_todo_changeme1, depth=8):
+ (r1, g1, b1) = xxx_todo_changeme1
w = len(img[0])
h = len(img)
pad = depth * [keycol]
@@ -49,17 +51,17 @@ def addrshadow(img, (r1, g1, b1), depth=8):
def load(filename):
- print "Loading %s..." % filename
+ print("Loading %s..." % filename)
Bin = macbinary.MacBinary(filename)
levels = {}
mnstrlist = [Nasty, Monky, Ghosty, Flappy,
Springy, Orcy, Gramy, Blitzy]
- for key, lvl in Bin['LEVL'].items():
+ for key, lvl in list(Bin['LEVL'].items()):
d = lvl.getlevel(mnstrlist)
class BinBoard(boards.Board):
pass
- for key1, value1 in d.items():
+ for key1, value1 in list(d.items()):
setattr(BinBoard, key1, value1)
levels[key] = BinBoard
diff --git a/bubbob/boards.py b/bubbob/boards.py
index dced6f5..2463b11 100644
--- a/bubbob/boards.py
+++ b/bubbob/boards.py
@@ -1,4 +1,4 @@
-from __future__ import generators
+
import random, os, sys, math
import gamesrv
import images
@@ -72,8 +72,8 @@ class Board(Copyable):
def enter(self, complete=1, inplace=0, fastreenter=False):
global curboard
if inplace:
- print "Re -",
- print "Entering board", self.num+1
+ print("Re -", end=' ')
+ print("Entering board", self.num+1)
self.set_musics()
# add board walls
l = self.sprites.setdefault('walls', [])
@@ -96,9 +96,9 @@ class Board(Copyable):
righticon = patget((self.num, 'r'))
else:
righticon = lefticon
- xrange = range(2, self.width-2)
+ xrange = list(range(2, self.width-2))
else:
- xrange = range(self.width)
+ xrange = list(range(self.width))
lefticon = righticon = None
if BOARD_BKGND == 1:
@@ -255,7 +255,7 @@ class Board(Copyable):
def reorder_walls(self):
walls_by_pos = self.walls_by_pos
- items = [(yx, w1.ico) for yx, w1 in walls_by_pos.items()]
+ items = [(yx, w1.ico) for yx, w1 in list(walls_by_pos.items())]
if not items:
return # otherwise self.sprites['walls'] would be emptied
items.sort()
@@ -289,7 +289,7 @@ class Board(Copyable):
yield 0.9
i = 0
sprites = []
- for l in self.sprites.values():
+ for l in list(self.sprites.values()):
sprites += l
self.sprites.clear()
self.walls_by_pos.clear()
@@ -440,7 +440,7 @@ def loadmodules(force=0):
elif os.path.isfile(os.path.join(m, '__init__.py')):
modulefiles[m] = os.path.join(m, '__init__.py')
mtimes = {}
- for m, mfile in modulefiles.items():
+ for m, mfile in list(modulefiles.items()):
mtimes[m] = os.stat(mfile).st_mtime
reload = force or (mtimes != getattr(sys, 'ST_MTIMES', None))
import player
@@ -449,8 +449,8 @@ def loadmodules(force=0):
delete = hasattr(sys, 'ST_MTIMES')
sys.ST_MTIMES = mtimes
if delete:
- print "Reloading modules."
- for m, mfile in modulefiles.items():
+ print("Reloading modules.")
+ for m, mfile in list(modulefiles.items()):
if m is not None and m in sys.modules:
del sys.modules[m]
@@ -471,12 +471,12 @@ def loadmodules(force=0):
del boards.BoardList[:]
if levelfilename.lower().endswith('.py'):
levels = {}
- print 'Source level file:', levelfilename
- execfile(levelfilename, levels)
+ print('Source level file:', levelfilename)
+ exec(compile(open(levelfilename, "rb").read(), levelfilename, 'exec'), levels)
if 'GenerateLevels' in levels:
levels = levels['GenerateLevels']()
if isinstance(levels, list):
- levels = dict(zip(range(len(levels)), levels))
+ levels = dict(list(zip(list(range(len(levels))), levels)))
else:
import binboards
levels = binboards.load(levelfilename)
@@ -555,7 +555,7 @@ def wait_for_one_player():
if random.random() > 0.4321:
try:
key, (filename, (x, y, w, h)) = random.choice(
- images.sprmap.items())
+ list(images.sprmap.items()))
except:
w = h = 0
if w == h == 32:
@@ -1116,7 +1116,7 @@ def extra_aquarium():
for s in waves_sprites:
s.kill()
BubPlayer.SuperFish = True
- fishplayers(-sys.maxint)
+ fishplayers(-sys.maxsize)
def extra_walls_falling():
walls_by_pos = curboard.walls_by_pos
@@ -1156,7 +1156,7 @@ def single_blocks_falling(xylist):
def extra_display_repulse(cx, cy, dlimit=5000, dfactor=1000):
offsets = {}
- for s in gamesrv.sprites_by_n.values():
+ for s in list(gamesrv.sprites_by_n.values()):
x, y = s.getdisplaypos()
if x is not None:
dx = x - cx
@@ -1172,7 +1172,7 @@ def extra_display_repulse(cx, cy, dlimit=5000, dfactor=1000):
while offsets:
prevoffsets = offsets
offsets = {}
- for s, (dx, dy) in prevoffsets.items():
+ for s, (dx, dy) in list(prevoffsets.items()):
if s.alive:
if dx < 0:
dx += max(1, (-dx)//5)
@@ -1212,7 +1212,7 @@ def extra_light_off(timeout, icocache={}):
for bubber in playerlist:
for dragon in bubber.dragons:
dragons[dragon] = True
- for s in gamesrv.sprites_by_n.values():
+ for s in list(gamesrv.sprites_by_n.values()):
try:
ico = icocache[s.ico, s in dragons]
except KeyError:
@@ -1220,12 +1220,12 @@ def extra_light_off(timeout, icocache={}):
icocache[s.ico, s in dragons] = ico
s.setdisplayicon(ico)
yield 0
- for s in gamesrv.sprites_by_n.values():
+ for s in list(gamesrv.sprites_by_n.values()):
s.setdisplayicon(s.ico)
def extra_swap_up_down(N=27):
# unregister all walls
- walls = curboard.walls_by_pos.items()
+ walls = list(curboard.walls_by_pos.items())
walls.sort()
if not walls:
return
@@ -1317,7 +1317,7 @@ def extra_make_random_level(cx=None, cy=None, repeat_delay=200):
localdir = os.path.dirname(__file__)
filename = os.path.join(localdir, 'levels', 'RandomLevels.py')
d = {}
- execfile(filename, d)
+ exec(compile(open(filename, "rb").read(), filename, 'exec'), d)
Level = d['GenerateSingleLevel'](curboard.width, curboard.height)
lvl = Level(curboard.num)
walllist = []
@@ -1413,7 +1413,7 @@ def initsubgame(music, displaypoints):
def register(dict):
global width, height, bwidth, bheight, bheightmod
- items = dict.items()
+ items = list(dict.items())
items.sort()
for name, board in items:
try:
@@ -1433,8 +1433,8 @@ def register(dict):
test = B(-1)
assert test.width == width, "some boards have a different width"
assert test.height == height, "some boards have a different height"
- except Exception, e:
- print 'Caught "%s" in level "%s":' % (e, B.__name__)
+ except Exception as e:
+ print('Caught "%s" in level "%s":' % (e, B.__name__))
raise e
bwidth = width*CELL
bheight = height*CELL
diff --git a/bubbob/bonuses.py b/bubbob/bonuses.py
index 6873188..b3ce653 100644
--- a/bubbob/bonuses.py
+++ b/bubbob/bonuses.py
@@ -1,4 +1,4 @@
-from __future__ import generators
+
import random, os, math
import random as random_module
import gamesrv
@@ -646,13 +646,13 @@ class Megabonus(Bonus):
return self.y == boards.bheight - CELL - self.ico.h
def kill(self):
- for bubble in self.bubbles.values():
+ for bubble in list(self.bubbles.values()):
bubble.pop()
Bonus.kill(self)
def taken(self, dragon):
poplist = [dragon]
- for bubble in self.bubbles.values():
+ for bubble in list(self.bubbles.values()):
bubble.pop(poplist)
def bubbles_position(self):
@@ -712,7 +712,7 @@ class Megabonus(Bonus):
while 1:
for t in range(2):
yield None
- bubbles = [dxy for dxy, b in self.bubbles.items()
+ bubbles = [dxy for dxy, b in list(self.bubbles.items())
if b.bubber is bubber]
if not bubbles:
break
@@ -776,7 +776,7 @@ class Megabonus(Bonus):
while 1:
for cycle in [1]*8 + [2]*10 + [1]*8 + [0]*10:
yield None
- for (dx, dy), bubble in bubbles.items():
+ for (dx, dy), bubble in list(bubbles.items()):
if not hasattr(bubble, 'poplist'):
if 0: # disabled clipping
if (dx, north[dy]) in bubbles:
@@ -822,7 +822,7 @@ class Megabonus(Bonus):
yield None
bubble.pop(poplist)
- for bubble in self.bubbles.values():
+ for bubble in list(self.bubbles.values()):
bubble.gen.append(bubble_timeout(bubble, self.vspeed))
self.bubbles.clear()
self.kill()
@@ -1249,7 +1249,7 @@ class Lollipop(TemporaryBonus):
def taken(self, dragon):
dragon.dcap['left2right'] = -dragon.dcap['left2right']
if self.big:
- perm = range(4)
+ perm = list(range(4))
while perm[0] == 0 or perm[1] == 1 or perm[2] == 2 or perm[3] == 3:
random.shuffle(perm)
names = ('key_left', 'key_right', 'key_jump', 'key_fire')
@@ -1589,7 +1589,7 @@ class Egg(RandomBonus):
d1 = dragons[0]
d1.move(x, y)
d1.dcap['shield'] = 50
- for d1, bubber2 in xchg.items():
+ for d1, bubber2 in list(xchg.items()):
d1.bubber.dragons.remove(d1)
d1.bubber = bubber2
bubber2.dragons.append(d1)
@@ -1705,7 +1705,7 @@ class Chestnut(RandomBonus):
try:
import statesaver
except ImportError:
- print "'statesaver' module not compiled, no clock bonus"
+ print("'statesaver' module not compiled, no clock bonus")
Clock = None
else:
import new
@@ -1734,11 +1734,11 @@ else:
boards.curboard,
images.ActiveSprites,
images.SpritesByLoc,
- BubPlayer.__dict__.items(),
+ list(BubPlayer.__dict__.items()),
gamesrv.sprites,
gamesrv.sprites_by_n,
ps,
- images.Snd.__dict__.items(),
+ list(images.Snd.__dict__.items()),
)
#import pdb; pdb.set_trace()
return statesaver.copy(topstate)
@@ -1938,8 +1938,8 @@ else:
random = random_module.Random()
localrandom = DustStar.localrandom
self.state = 'pre'
- self.randombase1 = hash(localrandom.random()) * 914971L
- self.randombase2 = hash(localrandom.random()) * 914971L
+ self.randombase1 = hash(localrandom.random()) * 914971
+ self.randombase2 = hash(localrandom.random()) * 914971
self.saved_next = None
self.saved_last = self
random.seed(self.randombase1)
@@ -2019,7 +2019,7 @@ else:
for s in touching:
if isinstance(s, interact):
s.touched(ghost)
- for d, ghost in self.ghosts.items():
+ for d, ghost in list(self.ghosts.items()):
if d not in new_ghosts:
ghost.kill()
self.ghosts = new_ghosts
@@ -2036,12 +2036,12 @@ else:
DragonBubble(*args)
if self.state == 'restoring' and self.ghosts:
self.state = 'post'
- for ghost in self.ghosts.values():
+ for ghost in list(self.ghosts.values()):
ghost.integrate()
def flush_ghosts(self):
if self.latest_entries:
- for ghost in self.ghosts.values():
+ for ghost in list(self.ghosts.values()):
ghost.disintegrate()
self.latest_entries.clear()
self.dragonlist = None
@@ -2282,7 +2282,7 @@ class Sheep(RandomBonus):
vy = 0
while delta or slist:
ndelta = {}
- for p, dp in delta.items():
+ for p, dp in list(delta.items()):
if dp:
d1 = max(-250, min(250, dp))
p.givepoints(d1)
@@ -2379,7 +2379,7 @@ class Donut(RandomBonus):
b.kill()
-Classes = [c for c in globals().values()
+Classes = [c for c in list(globals().values())
if type(c)==type(RandomBonus) and issubclass(c, RandomBonus)]
Classes.remove(RandomBonus)
Classes.remove(TemporaryBonus)
@@ -2500,5 +2500,5 @@ def __cheat(c):
c[0] = globals()[c[0]]
assert issubclass(c[0], Bonus)
Cheat.append(tuple(c))
-import __builtin__
-__builtin__.__cheat = __cheat
+import builtins
+builtins.__cheat = __cheat
diff --git a/bubbob/bubbles.py b/bubbob/bubbles.py
index 9734826..523c64c 100644
--- a/bubbob/bubbles.py
+++ b/bubbob/bubbles.py
@@ -1,4 +1,4 @@
-from __future__ import generators
+
import random, math
import gamesrv
import images
@@ -19,7 +19,7 @@ bubble_wind = {
class Bubble(ActiveSprite):
- exploding_bubbles = range(131,136)
+ exploding_bubbles = list(range(131,136))
red_bubbles = [156, 157, 156, 155]
white_bubbles = [164, 165, 164, 163]
pink_bubbles = [172, 173, 172, 171]
@@ -233,7 +233,7 @@ class Bubble(ActiveSprite):
ico = icons[1]
yfrac = 0.0
self.dragon_jumped = False
- for i in xrange(timeout):
+ for i in range(timeout):
hspeed = random.randrange(2, 4)
if ico is not icons[1]:
icotimeout += 1
@@ -410,7 +410,8 @@ class DragonBubble(Bubble):
hspeed = -hspeed
self.gen.append(self.throw_bubble(hspeed, special_bubble, (acos,asin)))
- def throw_bubble(self, hspeed, special_bubble=None, (acos,asin)=(1,0)):
+ def throw_bubble(self, hspeed, special_bubble=None, xxx_todo_changeme=(1,0)):
+ (acos,asin) = xxx_todo_changeme
from monsters import Monster
nx = self.x
ny = self.y
@@ -680,7 +681,7 @@ class BonusBubble(Bubble):
def findhole(self, testline):
holes = [x for x in range(len(testline)-1) if testline[x:x+2]==' ']
if not holes:
- holes = range(2, len(testline)-3)
+ holes = list(range(2, len(testline)-3))
return random.choice(holes) * CELL
def thrown_bubble(self, x, y, hspeed, acossin):
@@ -688,7 +689,8 @@ class BonusBubble(Bubble):
self.move(x, y)
self.gen = [self.throwing_bubble(hspeed, acossin, self.imgsetter)]
- def throwing_bubble(self, hspeed, (acos,asin), restore_img):
+ def throwing_bubble(self, hspeed, xxx_todo_changeme1, restore_img):
+ (acos,asin) = xxx_todo_changeme1
nx = self.x
ny = self.y
while abs(hspeed) >= 4.0:
@@ -962,7 +964,7 @@ class WaterCell(ActiveSprite):
ActiveSprite.kill(self)
if not self.watercells[None].alive:
del self.watercells[None]
- for s in self.watercells.values():
+ for s in list(self.watercells.values()):
if s.alive:
s.in_charge()
break
@@ -974,7 +976,7 @@ class WaterCell(ActiveSprite):
new = []
nwatercells = {None: self}
- for key, s in watercells.items():
+ for key, s in list(watercells.items()):
if key:
x, y, dir = key
if s.repeat:
@@ -1012,7 +1014,7 @@ class WaterCell(ActiveSprite):
for args in new:
WaterCell(*args)
- for key, s in watercells.items():
+ for key, s in list(watercells.items()):
if key:
x, y, dir = key
flag = 0
diff --git a/bubbob/command.py b/bubbob/command.py
index 71239ed..a438e23 100644
--- a/bubbob/command.py
+++ b/bubbob/command.py
@@ -7,4 +7,4 @@ for ext in ['.py', '.bin']:
break
sys.argv[1] = levelfile
-execfile('bb.py')
+exec(compile(open('bb.py', "rb").read(), 'bb.py', 'exec'))
diff --git a/bubbob/images.py b/bubbob/images.py
index 4de0b56..0aeb858 100644
--- a/bubbob/images.py
+++ b/bubbob/images.py
@@ -1,4 +1,4 @@
-from __future__ import generators
+
import gamesrv, os
from sprmap import sprmap as original_sprmap
from patmap import patmap
@@ -69,7 +69,7 @@ class ActiveSprite(gamesrv.Sprite):
# common generators
def cyclic(self, nimages, speed=5):
images = [sprget(n) for n in nimages]
- speed = range(speed)
+ speed = list(range(speed))
while 1:
for img in images:
self.seticon(img)
@@ -148,7 +148,7 @@ class ActiveSprite(gamesrv.Sprite):
try:
for g in glist:
if self.alive:
- g.next()
+ next(g)
except StopIteration:
try:
self.gen.remove(g)
@@ -157,7 +157,7 @@ class ActiveSprite(gamesrv.Sprite):
for g in glist[glist.index(g)+1:]:
if self.alive:
try:
- g.next()
+ next(g)
except StopIteration:
pass
yield None
@@ -166,7 +166,7 @@ def touching(x1, y1, w1, h1, margin=0):
touch = {}
x1 = int(x1)
y1 = int(y1)
- xrange = range(x1>>5, (x1+w1+31)>>5)
+ xrange = list(range(x1>>5, (x1+w1+31)>>5))
for y in range(y1>>4, (y1+h1+15)>>4):
for x in xrange:
touch.update(SpritesByLoc.get((x,y), {}))
@@ -181,7 +181,7 @@ def action(sprlist, len=len):
try:
for g in glist:
if self.alive:
- g.next()
+ next(g)
except StopIteration:
try:
self.gen.remove(g)
@@ -190,7 +190,7 @@ def action(sprlist, len=len):
for g in glist[glist.index(g)+1:]:
if self.alive:
try:
- g.next()
+ next(g)
except StopIteration:
pass
if self.touchable and self.alive:
@@ -202,7 +202,7 @@ def action(sprlist, len=len):
for key in self.ranges:
del key[self]
del self.ranges[:]
- xrange = range(x>>5, (x+self.ico.w+38)>>5)
+ xrange = list(range(x>>5, (x+self.ico.w+38)>>5))
for y in range(y>>4, (y+self.ico.h+22)>>4):
for x in xrange:
key = SpritesByLoc.setdefault((x,y), {})
@@ -303,7 +303,8 @@ def loadpattern(n, keycol=None):
bitmap = gamesrv.getbitmap(filename, keycol)
return bitmap, rect
-def makebkgndpattern(bitmap, (x,y,w,h), darker={}):
+def makebkgndpattern(bitmap, xxx_todo_changeme, darker={}):
+ (x,y,w,h) = xxx_todo_changeme
from boards import CELL
try:
nbitmap, hscale, vscale = darker[bitmap]
@@ -329,7 +330,7 @@ def computebiggericon(ico, bigger={}):
bigger[ico] = None, pixmap.imagezoomer(*ico.getimage())
return None
if computing is not None:
- result = computing.next() or computing.next() or computing.next()
+ result = next(computing) or next(computing) or next(computing)
if not result:
return None # still computing
w, h, data = result
@@ -456,12 +457,12 @@ def generate_sprmap():
# check and maybe regenerate the colored image files
file = os.path.join('images', 'buildcolors.py')
g = {'__name__': '__auto__', '__file__': file}
- execfile(file, g)
+ exec(compile(open(file, "rb").read(), file, 'exec'), g)
# replace the entries 'filename_%d.ppm' by a family of entries,
# one for each color
sprmap = {}
- for n, (filename, rect) in (original_sprmap.items() +
- extramap.items() + hatmap.items()):
+ for n, (filename, rect) in (list(original_sprmap.items()) +
+ list(extramap.items()) + list(hatmap.items())):
if filename.find('%d') >= 0:
for i in range(MAX):
sprmap[n+1000*i] = (os.path.join('images',filename % i), rect)
diff --git a/bubbob/macbinary.py b/bubbob/macbinary.py
index 616bce0..a485290 100644
--- a/bubbob/macbinary.py
+++ b/bubbob/macbinary.py
@@ -43,16 +43,16 @@ class TypeList:
return self.resources()[id]
def keys(self):
- return self.resources().keys()
+ return list(self.resources().keys())
def values(self):
- return self.resources().values()
+ return list(self.resources().values())
def items(self):
- return self.resources().items()
+ return list(self.resources().items())
def namedict(self):
- return dict([(r.name, r) for r in self.resources().values() if r.name is not None])
+ return dict([(r.name, r) for r in list(self.resources().values()) if r.name is not None])
class MacBinary:
@@ -93,22 +93,22 @@ class MacBinary:
return self.dtypes
def keys(self):
- return self.dtypes.keys()
+ return list(self.dtypes.keys())
def values(self):
- return self.dtypes.values()
+ return list(self.dtypes.values())
def items(self):
- return self.dtypes.items()
+ return list(self.dtypes.items())
class Subfile:
def __init__(self, f, start, length):
if start < 0:
- raise ValueError, 'negative position'
+ raise ValueError('negative position')
if isinstance(f, Subfile):
if start + length > f.length:
- raise ValueError, 'subfile out of bounds'
+ raise ValueError('subfile out of bounds')
f, start = f.f, f.start+start
self.f = f
self.start = start
@@ -124,7 +124,7 @@ class Subfile:
return self.f.read(size)
def seek(self, npos):
if npos < 0:
- raise ValueError, 'negative position'
+ raise ValueError('negative position')
self.position = npos
@@ -186,7 +186,7 @@ class ppatResource(Resource):
f = self.subfile()
pattype, patmap, patdata = struct.unpack(">Hll", f.read(10))
if pattype != 1:
- raise ValueError, 'Pattern type not supported'
+ raise ValueError('Pattern type not supported')
f.seek(patmap)
(rowBytes, h, w, packType, packSize,
pixelType, pixelSize, cmpCount, cmpSize, pmTable) = (
@@ -194,9 +194,9 @@ class ppatResource(Resource):
isBitmap = (rowBytes & 0x8000) != 0
rowBytes &= 0x3FFF
if packType != 0:
- raise ValueError, 'packed image not supported'
+ raise ValueError('packed image not supported')
if pixelType != 0 or cmpCount != 1:
- raise ValueError, 'direct RGB image not supported'
+ raise ValueError('direct RGB image not supported')
assert cmpSize == pixelSize and pixelSize in [1,2,4,8]
f.seek(pmTable)
colormap = loadcolormap(f)
diff --git a/bubbob/mnstrmap.py b/bubbob/mnstrmap.py
index 88e531d..9dbc4ed 100644
--- a/bubbob/mnstrmap.py
+++ b/bubbob/mnstrmap.py
@@ -7,7 +7,7 @@ class Monster1:
self.player = player
def nrange(start,n):
- return range(start,start+n)
+ return list(range(start,start+n))
class Nasty(Monster1):
right = nrange(239,4)
@@ -289,11 +289,11 @@ class birange:
self.a = a
self.n = n
def __getitem__(self, pn):
- return range(self.a + 1000*pn, self.a + 1000*pn + self.n)
+ return list(range(self.a + 1000*pn, self.a + 1000*pn + self.n))
class bidict:
def __init__(self, a,b):
- self.a = a.items()
+ self.a = list(a.items())
def __getitem__(self, pn):
pn *= 1000
d = {}
diff --git a/bubbob/monsters.py b/bubbob/monsters.py
index 88983d0..f38823b 100644
--- a/bubbob/monsters.py
+++ b/bubbob/monsters.py
@@ -1,4 +1,4 @@
-from __future__ import generators
+
import random
import gamesrv
import images
@@ -780,7 +780,7 @@ class Blitzy(Monster):
self.no_shoot_before = BubPlayer.FrameCounter + 29
return 0
-MonsterClasses = [c for c in globals().values()
+MonsterClasses = [c for c in list(globals().values())
if type(c)==type(Monster) and issubclass(c, Monster)]
MonsterClasses.remove(Monster)
diff --git a/bubbob/player.py b/bubbob/player.py
index 3a336a9..e4d99fe 100644
--- a/bubbob/player.py
+++ b/bubbob/player.py
@@ -1,4 +1,4 @@
-from __future__ import generators
+
import random, math, time
import gamesrv
import images
@@ -123,7 +123,7 @@ class Dragon(ActiveSprite):
outcome=bonus.buildoutcome())
elif self.bubber.letters and random.random() > 0.59 and can_loose_letter:
# loose a letter
- lst = range(6)
+ lst = list(range(6))
random.shuffle(lst)
for l in lst:
lettername = bubbles.extend_name(l)
@@ -758,7 +758,7 @@ class BubPlayer(gamesrv.Player):
icons = self.transformedicons[flip]
if flip == 'fish':
for dir in (-1, 1):
- for key, value in self.FISH_MODE_MAP.items():
+ for key, value in list(self.FISH_MODE_MAP.items()):
if value == 'black':
flip = ''
else:
@@ -768,7 +768,7 @@ class BubPlayer(gamesrv.Player):
flip = flip or 'hflip'
icons[key, dir] = images.sprget((flip, value))
else:
- for key, value in self.iconnames.items():
+ for key, value in list(self.iconnames.items()):
icons[key] = images.sprget((flip, value))
def setplayername(self, name):
@@ -793,9 +793,9 @@ class BubPlayer(gamesrv.Player):
self.loadicons(flip='')
self.keepalive = None
if self.points or self.letters:
- print 'New player continues at position #%d.' % n
+ print('New player continues at position #%d.' % n)
else:
- print 'New player is at position #%d.' % n
+ print('New player is at position #%d.' % n)
self.reset()
self.key_left = 0
self.key_right = 0
@@ -810,7 +810,7 @@ class BubPlayer(gamesrv.Player):
#BubPlayer.LatestLetsGo = BubPlayer.FrameCounter
def playerleaves(self):
- print 'Closing position #%d.' % self.pn
+ print('Closing position #%d.' % self.pn)
self.savecaps()
self.zarkoff()
self.keepalive = time.time() + KEEPALIVE
@@ -831,7 +831,7 @@ class BubPlayer(gamesrv.Player):
self.pcap = {}
dragons = self.dragons
if dragons:
- for key, minimum in Dragon.SAVE_CAP.items():
+ for key, minimum in list(Dragon.SAVE_CAP.items()):
self.pcap[key] = max(minimum,
max([d.dcap[key] for d in dragons]))
@@ -874,7 +874,7 @@ class BubPlayer(gamesrv.Player):
else:
break
self.dragons.append(Dragon(self, x, y, dir))
- for key in self.pcap.keys():
+ for key in list(self.pcap.keys()):
if key not in ('teleport', 'jumpdown'):
del self.pcap[key]
@@ -1022,7 +1022,7 @@ def scoreboard(reset=0, inplace=0, compresslimittime=0):
if reset:
for p in BubPlayer.PlayerList:
if inplace:
- for s in p.letters.values():
+ for s in list(p.letters.values()):
if isinstance(s, ActiveSprite):
s.kill()
if len(p.letters) == 6:
@@ -1155,7 +1155,7 @@ def scoreboard(reset=0, inplace=0, compresslimittime=0):
lst.append((x0+9*CELL-ico.w, y0-ico.h+16, ico))
y0 -= 5*HALFCELL
for p in BubPlayer.PlayerList:
- for name, s in p.letters.items():
+ for name, s in list(p.letters.items()):
if isinstance(s, ActiveSprite) and s not in bubblesshown:
p.letters[name] = 2
s.kill()
@@ -1208,6 +1208,6 @@ def scoreboard(reset=0, inplace=0, compresslimittime=0):
# initialize global board data
def reset_global_board_state():
- for key, value in BubPlayer.INIT_BOARD_CAP.items():
+ for key, value in list(BubPlayer.INIT_BOARD_CAP.items()):
setattr(BubPlayer, key, value)
reset_global_board_state()
diff --git a/bubbob/ranking.py b/bubbob/ranking.py
index d4a4d22..c81c90c 100644
--- a/bubbob/ranking.py
+++ b/bubbob/ranking.py
@@ -1,4 +1,4 @@
-from __future__ import generators
+
import random
import boards, images, gamesrv
from boards import CELL, HALFCELL
@@ -168,7 +168,7 @@ def display(lines, timeleft, bgen=None, black=0):
t = boards.normal_frame()
else:
try:
- t = bgen.next()
+ t = next(bgen)
except StopIteration:
timeleft = 0.0
break
@@ -180,13 +180,13 @@ def display(lines, timeleft, bgen=None, black=0):
def ranking_picture(results, maximum, givepoints):
if maximum is None:
maximum = 0
- for n in results.values():
+ for n in list(results.values()):
maximum += n
maximum = maximum or 1
ranking = []
teamrank = [0, 0]
teamplayers = [[], []]
- for p, n in results.items():
+ for p, n in list(results.items()):
if p.team != -1:
teamrank[p.team] += n
teamplayers[p.team].append((n,p))
@@ -205,7 +205,7 @@ def ranking_picture(results, maximum, givepoints):
nbpoints = givepoints and ((len(ranking)+1)//2)*10000
lines = []
- for (n, dummy, bubber), i in zip(ranking, range(len(ranking))):
+ for (n, dummy, bubber), i in zip(ranking, list(range(len(ranking)))):
pic = RPicture()
if isinstance(bubber, list):
fraction = (nbpoints//(10*len(bubber))) * 10
@@ -253,7 +253,7 @@ def screen_monster():
pairs = []
for p in BubPlayer.PlayerList:
catch = p.stats.get('monster', {})
- for p2, count in catch.items():
+ for p2, count in list(catch.items()):
if count:
pairs.append((count, p, p2))
random.shuffle(pairs)
@@ -277,7 +277,7 @@ def screen_catch():
pairs = []
for p in BubPlayer.PlayerList:
catch = p.stats.get('catch', {})
- for p2, count in catch.items():
+ for p2, count in list(catch.items()):
if count:
pairs.append((count, p, p2))
random.shuffle(pairs)
@@ -301,7 +301,7 @@ def screen_bonus():
pairs = []
for p in BubPlayer.PlayerList:
catch = p.stats.get('bonus', {})
- for p2, count in catch.items():
+ for p2, count in list(catch.items()):
if count > 1:
pairs.append((count, p, p2))
random.shuffle(pairs)
diff --git a/bubbob/save_rnglevel.py b/bubbob/save_rnglevel.py
index 8b09571..7df8536 100644
--- a/bubbob/save_rnglevel.py
+++ b/bubbob/save_rnglevel.py
@@ -22,7 +22,7 @@ while idx < len(sys.argv):
if arg == '-seed':
arg = sys.argv[idx]
idx += 1
- print "# Using seed: " + arg + "\n"
+ print("# Using seed: " + arg + "\n")
random.seed(arg)
def printlvl(level):
@@ -41,7 +41,7 @@ def printlvl(level):
else:
dir = 'R'
s = dir + m.cls.__name__
- if tmpmons.has_key(s):
+ if s in tmpmons:
tmpmons[s].append(wm)
else:
tmpmons[s] = [wm]
@@ -61,7 +61,7 @@ def printlvl(level):
for x in range(0,level.WIDTH):
wm = level.wmap[y][x]
if wm >= 'a':
- if monconv.has_key(wm):
+ if wm in monconv:
walls += monconv[wm]
else:
walls += '?'
@@ -84,42 +84,42 @@ def printlvl(level):
winds += "\n"
for m in mons:
- print " " + m + " = " + mons[m]
+ print(" " + m + " = " + mons[m])
if level.letter:
- print " letter = 1"
+ print(" letter = 1")
if level.fire:
- print " fire = 1"
+ print(" fire = 1")
if level.lightning:
- print " lightning = 1"
+ print(" lightning = 1")
if level.water:
- print " water = 1"
+ print(" water = 1")
if level.top:
- print " top = 1"
+ print(" top = 1")
- print " walls = \"\"\"\n" + walls + "\"\"\""
- print " winds = \"\"\"\n" + winds + "\"\"\""
+ print(" walls = \"\"\"\n" + walls + "\"\"\"")
+ print(" winds = \"\"\"\n" + winds + "\"\"\"")
for i in range(n_lvls):
- print """
+ print("""
import boarddef, mnstrmap, random
from boarddef import LNasty, LMonky, LGhosty, LFlappy
from boarddef import LSpringy, LOrcy, LGramy, LBlitzy
from boarddef import RNasty, RMonky, RGhosty, RFlappy
from boarddef import RSpringy, ROrcy, RGramy, RBlitzy
-"""
+""")
d = {'__name__': 'RandomLevels'}
- execfile('levels/RandomLevels.py', d)
+ exec(compile(open('levels/RandomLevels.py', "rb").read(), 'levels/RandomLevels.py', 'exec'), d)
for i, Lvl in enumerate(d['GenerateLevels']()):
level = Lvl(i)
if level.monsters:
- print "\n\nclass level%02d(boarddef.Level):" % (i+1)
+ print("\n\nclass level%02d(boarddef.Level):" % (i+1))
else:
- print "\n\nclass levelFinal(boarddef.Level):"
+ print("\n\nclass levelFinal(boarddef.Level):")
printlvl(level)
- print
+ print()
diff --git a/bubbob/statesaver.py b/bubbob/statesaver.py
index 85d3425..72be9cd 100644
--- a/bubbob/statesaver.py
+++ b/bubbob/statesaver.py
@@ -27,7 +27,7 @@ def copy_custom_instance(x, memo):
except KeyError:
y = x.inst_build()
memo[id(x)] = y
- for key, value in x.__dict__.items():
+ for key, value in list(x.__dict__.items()):
y.__dict__[key] = copyrec(value, memo)
return y
@@ -50,25 +50,25 @@ def copy_dict(x, memo):
except KeyError:
y = {}
memo[id(x)] = y
- for key, value in x.items():
+ for key, value in list(x.items()):
y[copyrec(key, memo)] = copyrec(value, memo)
return y
def copy_function(x, memo):
- if not x.func_defaults:
+ if not x.__defaults__:
return x # not copied
try:
return memo[id(x)]
except KeyError:
- y = types.FunctionType(x.func_code, x.func_globals, x.func_name)
+ y = types.FunctionType(x.__code__, x.__globals__, x.__name__)
memo[id(x)] = y
- y.func_defaults = copyrec(x.func_defaults, memo)
+ y.__defaults__ = copyrec(x.__defaults__, memo)
return y
def copy_method(x, memo):
- return types.MethodType(copyrec(x.im_func, memo),
- copyrec(x.im_self, memo),
- x.im_class)
+ return types.MethodType(copyrec(x.__func__, memo),
+ copyrec(x.__self__, memo),
+ x.__self__.__class__)
def copy_generator(x, memo):
try:
diff --git a/bubbob/test_rnglevel.py b/bubbob/test_rnglevel.py
index 6b65514..fa743e1 100644
--- a/bubbob/test_rnglevel.py
+++ b/bubbob/test_rnglevel.py
@@ -31,12 +31,12 @@ while idx < len(sys.argv):
if arg == '-seed':
arg = sys.argv[idx]
idx += 1
- print "Using seed: " + arg + "\n"
+ print("Using seed: " + arg + "\n")
random.seed(arg)
def printlvl(level):
if show_lvl:
- print "\n\n"
+ print("\n\n")
for y in range(level.HEIGHT):
str = ""
if show_lvl & 1:
@@ -45,12 +45,12 @@ def printlvl(level):
if str:
str += " | "
str += level.winds[y]
- print str
+ print(str)
for i in range(n_lvls):
- print '%4d:' % i,
+ print('%4d:' % i, end=' ')
d = {'__name__': 'RandomLevels'}
- execfile('levels/RandomLevels.py', d)
+ exec(compile(open('levels/RandomLevels.py', "rb").read(), 'levels/RandomLevels.py', 'exec'), d)
for i, Lvl in enumerate(d['GenerateLevels']()):
level = Lvl(i)
printlvl(level)
@@ -60,5 +60,5 @@ for i in range(n_lvls):
break
else:
for line in level.walls:
- print line
+ print(line)
raise AssertionError("full height wall in column %d" % x)
diff --git a/bubbob/test_statesaver.py b/bubbob/test_statesaver.py
index 3fadcd7..fdb099b 100644
--- a/bubbob/test_statesaver.py
+++ b/bubbob/test_statesaver.py
@@ -68,32 +68,32 @@ def test_generator():
yield lst.pop()
yield lst.pop()
g = gfunc()
- assert g.next() == 6
+ assert next(g) == 6
g1 = statesaver.copy(g)
- assert g.next() == 5
- py.test.raises(StopIteration, g.next)
- assert g1.next() == 5
- py.test.raises(StopIteration, g1.next)
+ assert next(g) == 5
+ py.test.raises(StopIteration, g.__next__)
+ assert next(g1) == 5
+ py.test.raises(StopIteration, g1.__next__)
def test_exhausted_gen():
def gfunc():
yield 5
g = gfunc()
for i in g:
- print i
+ print(i)
g1 = statesaver.copy(g)
assert iter(g1) is g1
- py.test.raises(StopIteration, g1.next)
+ py.test.raises(StopIteration, g1.__next__)
g2 = statesaver.copy(g1)
assert iter(g2) is g2
- py.test.raises(StopIteration, g2.next)
+ py.test.raises(StopIteration, g2.__next__)
def test_seqiter():
- from UserList import UserList
+ from collections import UserList
seq = UserList([2, 4, 6, 8])
it = iter(seq)
- assert it.next() == 2
- assert it.next() == 4
+ assert next(it) == 2
+ assert next(it) == 4
it1 = statesaver.copy(it)
assert list(it) == [6, 8]
assert list(it1) == [6, 8]
@@ -101,8 +101,8 @@ def test_seqiter():
def test_tupleiter():
tup = (2, 4, 6, 8)
it = iter(tup)
- assert it.next() == 2
- assert it.next() == 4
+ assert next(it) == 2
+ assert next(it) == 4
it1 = statesaver.copy(it)
assert list(it) == [6, 8]
assert list(it1) == [6, 8]
@@ -110,8 +110,8 @@ def test_tupleiter():
def test_listiter():
lst = [2, 4, 6, 8]
it = iter(lst)
- assert it.next() == 2
- assert it.next() == 4
+ assert next(it) == 2
+ assert next(it) == 4
it1 = statesaver.copy(it)
lst.append(10)
assert list(it) == [6, 8, 10]
@@ -120,8 +120,8 @@ def test_listiter():
def test_stringiter():
s = "hello"
it = iter(s)
- assert it.next() == 'h'
- assert it.next() == 'e'
+ assert next(it) == 'h'
+ assert next(it) == 'e'
it1 = statesaver.copy(it)
assert list(it) == ['l', 'l', 'o']
assert list(it1) == ['l', 'l', 'o']
diff --git a/common/gamesrv.py b/common/gamesrv.py
index bb27d66..ecf6cdc 100644
--- a/common/gamesrv.py
+++ b/common/gamesrv.py
@@ -1,10 +1,10 @@
-from __future__ import generators
+
from socket import *
from select import select
from struct import pack, unpack
-import zlib, os, random, struct, md5, sys
+import zlib, os, random, struct, hashlib, sys
from time import time, ctime
-from msgstruct import *
+from common.msgstruct import *
from errno import EWOULDBLOCK
@@ -37,7 +37,7 @@ class Icon:
framemsgappend(self.msgdef)
def getimage(self):
- import pixmap
+ from . import pixmap
bitmap, x, y = self.origin
image = pixmap.decodepixmap(bitmap.read())
return pixmap.cropimage(image, (x, y, self.w, self.h))
@@ -111,7 +111,7 @@ class Bitmap(DataChunk):
return ico
def geticonlist(self, w, h, count):
- return map(lambda i, fn=self.geticon, w=w, h=h: fn(i*w, 0, w, h), range(count))
+ return list(map(lambda i, fn=self.geticon, w=w, h=h: fn(i*w, 0, w, h), list(range(count))))
def getmsgdef(self, data):
if self.colorkey is not None:
@@ -121,7 +121,7 @@ class Bitmap(DataChunk):
def defall(self, client):
DataChunk.defall(self, client)
- for i in self.icons.values():
+ for i in list(self.icons.values()):
client.msgl.append(i.msgdef)
@@ -214,7 +214,7 @@ class Music(DataChunk):
self.md5msgs = {}
DataChunk.__init__(self)
- def read(self, (start, length)):
+ def read(self, start, length):
self.f.seek(start)
return self.f.read(length)
@@ -264,7 +264,7 @@ def compactsprites(insert_new=None, insert_before=None):
insert_before = None
newsprites = ['']
newd = {}
- l = sprites_by_n.items()
+ l = list(sprites_by_n.items())
l.sort()
for n, s in l:
if n == insert_before:
@@ -371,7 +371,7 @@ class Sprite:
n1 = 1
if self.alive > n1:
if n1 in sprites_by_n:
- keys = sprites_by_n.keys()
+ keys = list(sprites_by_n.keys())
keys.remove(self.alive)
keys.sort()
keys = keys[keys.index(n1):]
@@ -452,7 +452,7 @@ class Client:
self.activity = self.last_ping = time()
self.force_ping_delay = 0.6
for c in clients:
- for id in c.players.keys():
+ for id in list(c.players.keys()):
self.msgl.append(message(MSG_PLAYER_JOIN, id, c is self))
def emit(self, udpdata, broadcast_extras):
@@ -465,10 +465,10 @@ class Client:
if self.udpsocket is not None:
if self.sounds:
if broadcast_extras is None or self not in broadcast_clients:
- udpdata = ''.join(self.sounds.keys() + [udpdata])
+ udpdata = ''.join(list(self.sounds.keys()) + [udpdata])
else:
broadcast_extras.update(self.sounds)
- for key, value in self.sounds.items():
+ for key, value in list(self.sounds.items()):
if value:
self.sounds[key] = value-1
else:
@@ -481,8 +481,8 @@ class Client:
for udpdata in udpdatas:
try:
self.udpsockcounter += self.udpsocket.send(udpdata)
- except error, e:
- print >> sys.stderr, 'ignored:', str(e)
+ except error as e:
+ print('ignored:', str(e), file=sys.stderr)
pass # ignore UDP send errors (buffer full, etc.)
if self.has_music > 1 and NOW >= self.musicstreamer:
self.musicstreamer += 0.99
@@ -559,7 +559,7 @@ class Client:
def send_buffer(self, buffer):
try:
count = self.socket.send(buffer[:self.SEND_BOUND_PER_FRAME])
- except error, e:
+ except error as e:
if e.args[0] != EWOULDBLOCK:
self.msgl = []
self.initialdata = ""
@@ -588,7 +588,7 @@ class Client:
if fn:
fn(self, *values[1:])
else:
- print "unknown message from", self.addr, ":", values
+ print("unknown message from", self.addr, ":", values)
self.buf = data
except struct.error:
import traceback
@@ -608,7 +608,7 @@ then use the following address:
def input_handler(self):
try:
data = self.socket.recv(2048)
- except error, e:
+ except error as e:
self.disconnect(e, "socket.recv")
else:
if data:
@@ -628,9 +628,9 @@ then use the following address:
extra = ""
if infn:
extra += " in " + infn
- print 'Disconnected by', self.addr, extra
+ print('Disconnected by', self.addr, extra)
self.log('disconnected' + extra)
- for p in self.players.values():
+ for p in list(self.players.values()):
p._playerleaves()
try:
del broadcast_clients[self]
@@ -646,7 +646,7 @@ then use the following address:
game.FnDisconnected()
def killplayer(self, player):
- for id, p in self.players.items():
+ for id, p in list(self.players.items()):
if p is player:
framemsgappend(message(MSG_PLAYER_KILL, id))
del self.players[id]
@@ -654,19 +654,19 @@ then use the following address:
game.updateplayers()
def joinplayer(self, id, *rest):
- if self.players.has_key(id):
- print "Note: player %s is already playing" % (self.addr+(id,),)
+ if id in self.players:
+ print("Note: player %s is already playing" % (self.addr+(id,),))
return
if game is None:
return # refusing new player before the game starts
p = game.FnPlayers()[id]
if p is None:
- print "Too many players. New player %s refused." % (self.addr+(id,),)
+ print("Too many players. New player %s refused." % (self.addr+(id,),))
self.msgl.append(message(MSG_PLAYER_KILL, id))
elif p.isplaying():
- print "Note: player %s is already played by another client" % (self.addr+(id,),)
+ print("Note: player %s is already played by another client" % (self.addr+(id,),))
else:
- print "New player %s" % (self.addr+(id,),)
+ print("New player %s" % (self.addr+(id,),))
p._client = self
p.playerjoin()
p.setplayername('')
@@ -679,7 +679,7 @@ then use the following address:
try:
p = self.players[id]
except KeyError:
- print "Note: player %s is not playing" % (self.addr+(id,),)
+ print("Note: player %s is not playing" % (self.addr+(id,),))
else:
p._playerleaves()
@@ -700,7 +700,7 @@ then use the following address:
if port == MSG_INLINE_FRAME or port == 0:
# client requests data in-line on the TCP stream
self.dyncompress = None
- import udpovertcp
+ from . import udpovertcp
self.udpsocket = udpovertcp.SocketMarshaller(self.socket, self)
s = self.udpsocket.tcpsock
self.log('set_udp_port: udp-over-tcp')
@@ -714,10 +714,10 @@ then use the following address:
self.udpsocket.setblocking(0)
addr = addr or self.addr[0]
self.udpsocket.connect((addr, port))
- except error, e:
- print >> sys.stderr, "Cannot set UDP socket to", addr, str(e)
+ except error as e:
+ print("Cannot set UDP socket to", addr, str(e), file=sys.stderr)
self.udpsocket = None
- self.udpsockcounter = sys.maxint
+ self.udpsockcounter = sys.maxsize
else:
if self.proto >= 3:
self.setup_dyncompress()
@@ -726,15 +726,15 @@ then use the following address:
if s:
try:
s.setsockopt(SOL_IP, IP_TOS, 0x10) # IPTOS_LOWDELAY
- except error, e:
- print >> sys.stderr, "Cannot set IPTOS_LOWDELAY:", str(e)
+ except error as e:
+ print("Cannot set IPTOS_LOWDELAY:", str(e), file=sys.stderr)
def enable_sound(self, sound_mode=1, *rest):
if sound_mode != self.has_sound:
self.sounds = {}
self.has_sound = sound_mode
if self.has_sound > 0:
- for snd in samples.values():
+ for snd in list(samples.values()):
snd.defall(self)
#self.log('enable_sound %s' % sound_mode)
@@ -766,10 +766,10 @@ then use the following address:
if self.initialized < 2:
# send all current bitmap data
self.initialized = 2
- for b in bitmaps.values():
+ for b in list(bitmaps.values()):
b.defall(self)
self.finishinit(game)
- for id, p in game.FnPlayers().items():
+ for id, p in list(game.FnPlayers().items()):
if p.standardplayericon is not None:
self.msgl.append(message(MSG_PLAYER_ICON, id, p.standardplayericon.code))
self.msgl.append(message(MSG_PONG, *rest))
@@ -781,7 +781,7 @@ then use the following address:
pass
def log(self, message):
- print self.addr, message
+ print(self.addr, message)
def protocol_version(self, version, *rest):
self.proto = version
@@ -980,7 +980,7 @@ def opentcpsocket(port=None):
except error:
if port == INADDR_ANY:
for i in range(10):
- port = random.choice(xrange(8000, 12000))
+ port = random.choice(range(8000, 12000))
try:
s.bind(('', port))
s.listen(1)
@@ -989,7 +989,7 @@ def opentcpsocket(port=None):
else:
break
else:
- raise error, "server cannot find a free TCP socket port"
+ raise error("server cannot find a free TCP socket port")
else:
raise
@@ -1004,13 +1004,13 @@ def openpingsocket(only_port=None):
only_port = only_port or PORTS.get('PING', None)
s = findsocket('PING')
if s is None:
- import hostchooser
+ from . import hostchooser
s = hostchooser.serverside_ping(only_port)
if s is None:
return None
def pingsocket_handler(s=s):
global game
- import hostchooser
+ from . import hostchooser
if game is not None:
args = game.FnDesc, ('', game.address[1]), game.FnExtraDesc()
else:
@@ -1032,7 +1032,7 @@ def openhttpsocket(ServerClass=None, HandlerClass=None,
s = findsocket('HTTP')
if s is None:
if ServerClass is None:
- from BaseHTTPServer import HTTPServer as ServerClass
+ from http.server import HTTPServer as ServerClass
if HandlerClass is None:
import javaserver
from httpserver import MiniHandler as HandlerClass
@@ -1044,8 +1044,8 @@ def openhttpsocket(ServerClass=None, HandlerClass=None,
server_address = ('', INADDR_ANY)
try:
httpd = ServerClass(server_address, HandlerClass)
- except error, e:
- print >> sys.stderr, "cannot start HTTP server", str(e)
+ except error as e:
+ print("cannot start HTTP server", str(e), file=sys.stderr)
return None
else:
raise
@@ -1053,7 +1053,7 @@ def openhttpsocket(ServerClass=None, HandlerClass=None,
addsocket('HTTP', s, httpd.handle_request)
return s
-BROADCAST_PORT_RANGE = xrange(18000, 19000)
+BROADCAST_PORT_RANGE = range(18000, 19000)
#BROADCAST_MESSAGE comes from msgstruct
BROADCAST_DELAY = 0.6180
BROADCAST_DELAY_INCR = 2.7183
@@ -1064,8 +1064,8 @@ def openbroadcastsocket(broadcastport=None):
try:
s = socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
- except error, e:
- print >> sys.stderr, "Cannot broadcast", str(e)
+ except error as e:
+ print("Cannot broadcast", str(e), file=sys.stderr)
return None
port = broadcastport or random.choice(BROADCAST_PORT_RANGE)
addsocket('BROADCAST', s, port=port)
@@ -1100,20 +1100,20 @@ class Game:
clearsprites()
game = self
if recording:
- for b in bitmaps.values():
+ for b in list(bitmaps.values()):
b.defall(recording)
self.pendingclients = []
def openserver(self):
ps = openpingsocket()
- print '%s server at %s:%d, Broadcast %d, UDP %d' % (
+ print('%s server at %s:%d, Broadcast %d, UDP %d' % (
self.FnDesc, self.address[0], self.address[1],
- displaysockport(self.broadcast_s), displaysockport(ps))
+ displaysockport(self.broadcast_s), displaysockport(ps)))
hs = openhttpsocket()
if hs:
- print 'HTTP server: http://%s:%d' % (
- self.address[0], displaysockport(hs))
+ print('HTTP server: http://%s:%d' % (
+ self.address[0], displaysockport(hs)))
try:
from localmsg import autonotify
@@ -1185,7 +1185,7 @@ class Game:
if recording:
recording.udpdata(udpdata)
if broadcast_extras is not None:
- udpdata = ''.join(broadcast_extras.keys() + [udpdata])
+ udpdata = ''.join(list(broadcast_extras.keys()) + [udpdata])
try:
self.broadcast_s.sendto(udpdata,
('<broadcast>', self.broadcast_port))
@@ -1212,18 +1212,18 @@ class Game:
def newclient(self, conn, addr):
if len(clients)==MAX_CLIENTS:
- print "Too many connections; refusing new connection from", addr
+ print("Too many connections; refusing new connection from", addr)
conn.close()
else:
try:
addrname = (gethostbyaddr(addr[0])[0],) + addr[1:]
except:
addrname = addr
- print 'Connected by', addrname
+ print('Connected by', addrname)
try:
c = FnClient(conn, addrname)
- except error, e:
- print 'Connexion already lost!', e
+ except error as e:
+ print('Connexion already lost!', e)
else:
if game is not None:
c.opengame(game)
@@ -1240,14 +1240,14 @@ def recursiveloop(endtime, extra_sockets):
delay = game.mainstep()
else:
delay = 5.0
- iwtd = extra_sockets + serversockets.keys()
+ iwtd = extra_sockets + list(serversockets.keys())
timediff = max(0.0, endtime - time())
iwtd, owtd, ewtd = select(iwtd, [], iwtd, min(delay, timediff))
if ewtd:
if game:
game.socketerrors(ewtd)
if ewtd:
- print >> sys.stderr, "Unexpected socket error reported"
+ print("Unexpected socket error reported", file=sys.stderr)
for s in iwtd:
if s in serversockets:
serversockets[s]() # call handler
@@ -1269,10 +1269,10 @@ def mainloop():
delay = game.mainstep()
else:
delay = SERVER_SHUTDOWN or 5.0
- iwtd = serversockets.keys()
+ iwtd = list(serversockets.keys())
try:
iwtd, owtd, ewtd = select(iwtd, [], iwtd, delay)
- except Exception, e:
+ except Exception as e:
from select import error as select_error
if not isinstance(e, select_error):
raise
@@ -1281,7 +1281,7 @@ def mainloop():
if game:
game.socketerrors(ewtd)
if ewtd:
- print >> sys.stderr, "Unexpected socket error reported"
+ print("Unexpected socket error reported", file=sys.stderr)
servertimeout = None
if iwtd:
for s in iwtd:
@@ -1291,13 +1291,13 @@ def mainloop():
elif SERVER_SHUTDOWN and not ewtd and not owtd:
SERVER_SHUTDOWN -= delay
if SERVER_SHUTDOWN <= 0.001:
- raise SystemExit, "Server shutdown requested."
+ raise SystemExit("Server shutdown requested.")
elif clients or getattr(game, 'autoreset', 0):
servertimeout = None
elif servertimeout is None:
servertimeout = time() + SERVER_TIMEOUT
elif time() > servertimeout:
- raise SystemExit, "No more server activity, timing out."
+ raise SystemExit("No more server activity, timing out.")
except KeyboardInterrupt:
if game is None or not game.FnExcHandler(1):
raise
@@ -1310,7 +1310,7 @@ def mainloop():
removesocket('LISTEN')
removesocket('PING')
if clients:
- print "Server crash -- waiting for clients to terminate..."
+ print("Server crash -- waiting for clients to terminate...")
while clients:
iwtd = [c.socket for c in clients]
try:
@@ -1325,12 +1325,12 @@ def mainloop():
elif c.socket in iwtd:
try:
data = c.socket.recv(2048)
- except error, e:
+ except error as e:
c.disconnect(e)
else:
if not data and not hasattr(c.socket, 'RECV_CAN_RETURN_EMPTY'):
c.disconnect("end of data")
- print "Server closed."
+ print("Server closed.")
def closeeverything():
global SERVER_SHUTDOWN
diff --git a/common/hostchooser.py b/common/hostchooser.py
index 3243e06..2953f4c 100644
--- a/common/hostchooser.py
+++ b/common/hostchooser.py
@@ -14,7 +14,7 @@ def serverside_ping(only_port=None):
s.bind(('', port))
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
return s
- except error, e:
+ except error as e:
if only_port is None:
s = socket(AF_INET, SOCK_DGRAM)
s.bind(('', INADDR_ANY))
@@ -25,28 +25,27 @@ def serverside_ping(only_port=None):
def answer_ping(s, descr, addr, extra='', httpport=''):
try:
data, source = s.recvfrom(100)
- except error, e:
- print >> sys.stderr, 'ping error:', str(e)
+ except error as e:
+ print('ping error:', str(e), file=sys.stderr)
return
if data == PING_MESSAGE:
- print >> sys.stderr, "ping by", source
+ print("ping by", source, file=sys.stderr)
answer = '%s:%s:%s:%s:%s:%s' % (PONG_MESSAGE, descr,
addr[0], addr[1], extra, httpport)
s.sendto(answer, source)
else:
- print >> sys.stderr, \
- "unexpected data on UDP port %d by" % UDP_PORT, source
+ print("unexpected data on UDP port %d by" % UDP_PORT, source, file=sys.stderr)
def pick(hostlist, delay=1):
s = socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
for host in hostlist:
- print >> sys.stderr, "* Looking for a server on %s... " % host
+ print("* Looking for a server on %s... " % host, file=sys.stderr)
try:
s.sendto(PING_MESSAGE, (host, UDP_PORT))
- except error, e:
- print >> sys.stderr, 'send:', str(e)
+ except error as e:
+ print('send:', str(e), file=sys.stderr)
continue
while 1:
iwtd, owtd, ewtd = select.select([s], [], [], delay)
@@ -54,9 +53,9 @@ def pick(hostlist, delay=1):
break
try:
data, answer_from = s.recvfrom(200)
- except error, e:
+ except error as e:
if e.args[0] != ETIMEDOUT:
- print >> sys.stderr, 'recv:', str(e)
+ print('recv:', str(e), file=sys.stderr)
continue
break
data = data.split(':')
@@ -68,20 +67,20 @@ def pick(hostlist, delay=1):
pass
else:
result = (hostname, port)
- print >> sys.stderr, "* Picking %r at" % data[1], result
+ print("* Picking %r at" % data[1], result, file=sys.stderr)
return result
- print >> sys.stderr, "got an unexpected answer", data, "from", answer_from
- print >> sys.stderr, "no server found."
+ print("got an unexpected answer", data, "from", answer_from, file=sys.stderr)
+ print("no server found.", file=sys.stderr)
raise SystemExit
def find_servers(hostlist=[('127.0.0.1', None), ('<broadcast>', None)],
tries=2, delay=0.5, verbose=1, port_needed=1):
- import gamesrv
+ from . import gamesrv
if verbose:
- print >> sys.stderr, 'Looking for servers in the following list:'
+ print('Looking for servers in the following list:', file=sys.stderr)
for host, udpport in hostlist:
- print >> sys.stderr, ' %s, UDP port %s' % (
- host, udpport or ("%s (default)" % UDP_PORT))
+ print(' %s, UDP port %s' % (
+ host, udpport or ("%s (default)" % UDP_PORT)), file=sys.stderr)
events = {}
replies = []
s = socket(AF_INET, SOCK_DGRAM)
@@ -93,21 +92,21 @@ def find_servers(hostlist=[('127.0.0.1', None), ('<broadcast>', None)],
if host != '<broadcast>':
try:
ipaddr = gethostbyname(host)
- except error, e:
- print >> sys.stderr, 'gethostbyname:', str(e)
+ except error as e:
+ print('gethostbyname:', str(e), file=sys.stderr)
s.sendto(PING_MESSAGE, (ipaddr, udpport or UDP_PORT))
hostsend, hostrecv = events.setdefault(ipaddr, ([], []))
hostsend.append(time.time())
- except error, e:
- print >> sys.stderr, 'send:', str(e)
+ except error as e:
+ print('send:', str(e), file=sys.stderr)
continue
endtime = time.time() + delay
while gamesrv.recursiveloop(endtime, [s]):
try:
data, answer_from = s.recvfrom(200)
- except error, e:
+ except error as e:
if e.args[0] != ETIMEDOUT:
- print >> sys.stderr, 'recv:', str(e)
+ print('recv:', str(e), file=sys.stderr)
continue
break
try:
@@ -134,7 +133,7 @@ def find_servers(hostlist=[('127.0.0.1', None), ('<broadcast>', None)],
server = ':'.join(data[1:2]+data[4:])
replies.append((hostname, realhostname, port, server, ipaddr))
else:
- print >> sys.stderr, "got an unexpected answer from", answer_from
+ print("got an unexpected answer from", answer_from, file=sys.stderr)
servers = {}
aliases = {}
timeout = time.time() + 2.0 # wait for gethostbyaddr() for 2 seconds
@@ -155,8 +154,8 @@ def find_servers(hostlist=[('127.0.0.1', None), ('<broadcast>', None)],
if replies:
time.sleep(0.08) # time for gethostbyaddr() to finish
if verbose:
- print >> sys.stderr, "%d answer(s):" % len(servers), servers.keys()
- for host, port in servers.keys():
+ print("%d answer(s):" % len(servers), list(servers.keys()), file=sys.stderr)
+ for host, port in list(servers.keys()):
ping = None
ipaddr = aliases[host]
if ipaddr in events:
@@ -176,7 +175,7 @@ def _lazygetter(hostname, resultlst):
try:
hostname = gethostbyaddr(hostname)[0]
if hostname == 'localhost':
- from msgstruct import HOSTNAME as hostname
+ from .msgstruct import HOSTNAME as hostname
except error:
pass
finally:
@@ -187,6 +186,6 @@ def lazy_gethostbyaddr(hostname):
return HOSTNAMECACHE[hostname]
except KeyError:
resultlst = HOSTNAMECACHE[hostname] = []
- import thread
- thread.start_new_thread(_lazygetter, (hostname, resultlst))
+ import _thread
+ _thread.start_new_thread(_lazygetter, (hostname, resultlst))
return resultlst
diff --git a/common/javaserver.py b/common/javaserver.py
index 15a586b..50bd7f0 100644
--- a/common/javaserver.py
+++ b/common/javaserver.py
@@ -1,5 +1,5 @@
import sys, os
-from cStringIO import StringIO
+from io import StringIO
import httpserver
PLAYERNAMES = ['Bub', 'Bob', 'Boob', 'Beb',
@@ -68,11 +68,11 @@ def indexloader(**options):
if 'cheat' in options:
for opt in options.pop('cheat'):
__cheat(opt)
- import gamesrv
+ from . import gamesrv
if gamesrv.game is None:
indexdata = EMPTY_PAGE
else:
- names = playernames(options).items()
+ names = list(playernames(options).items())
indexdata = INDEX_PAGE % {
'title': gamesrv.game.FnDesc,
'width': gamesrv.game.width,
@@ -114,16 +114,16 @@ def wav2au(data):
return data
def sampleloader(code=[], **options):
- import gamesrv
+ from . import gamesrv
try:
data = wave_cache[code[0]]
except KeyError:
- for key, snd in gamesrv.samples.items():
+ for key, snd in list(gamesrv.samples.items()):
if str(getattr(snd, 'code', '')) == code[0]:
data = wave_cache[code[0]] = wav2au(snd.read())
break
else:
- raise KeyError, code[0]
+ raise KeyError(code[0])
return StringIO(data), 'audio/wav'
diff --git a/common/msgstruct.py b/common/msgstruct.py
index 26389f0..93b6bea 100644
--- a/common/msgstruct.py
+++ b/common/msgstruct.py
@@ -12,37 +12,37 @@ except ImportError:
MSG_WELCOME = "Welcome to gamesrv.py(3) !\n"
-MSG_BROADCAST_PORT= "*"
-MSG_DEF_PLAYFIELD = "p"
-MSG_DEF_KEY = "k"
-MSG_DEF_ICON = "r"
-MSG_DEF_BITMAP = "m"
-MSG_DEF_SAMPLE = "w"
-MSG_DEF_MUSIC = "z"
-MSG_PLAY_MUSIC = "Z"
-MSG_FADEOUT = "f"
-MSG_PLAYER_JOIN = "+"
-MSG_PLAYER_KILL = "-"
-MSG_PLAYER_ICON = "i"
-MSG_PING = "g"
-MSG_PONG = "G"
-MSG_INLINE_FRAME = "\\"
+MSG_BROADCAST_PORT= b"*"
+MSG_DEF_PLAYFIELD = b"p"
+MSG_DEF_KEY = b"k"
+MSG_DEF_ICON = b"r"
+MSG_DEF_BITMAP = b"m"
+MSG_DEF_SAMPLE = b"w"
+MSG_DEF_MUSIC = b"z"
+MSG_PLAY_MUSIC = b"Z"
+MSG_FADEOUT = b"f"
+MSG_PLAYER_JOIN = b"+"
+MSG_PLAYER_KILL = b"-"
+MSG_PLAYER_ICON = b"i"
+MSG_PING = b"g"
+MSG_PONG = b"G"
+MSG_INLINE_FRAME = b"\\"
MSG_PATCH_FILE = MSG_DEF_MUSIC
-MSG_ZPATCH_FILE = "P"
-MSG_MD5_FILE = "M"
-MSG_RECORDED = "\x00"
+MSG_ZPATCH_FILE = b"P"
+MSG_MD5_FILE = b"M"
+MSG_RECORDED = b"\x00"
-CMSG_PROTO_VERSION= "v"
-CMSG_KEY = "k"
-CMSG_ADD_PLAYER = "+"
-CMSG_REMOVE_PLAYER= "-"
-CMSG_UDP_PORT = "<"
-CMSG_ENABLE_SOUND = "s"
-CMSG_ENABLE_MUSIC = "m"
-CMSG_PING = "g"
-CMSG_PONG = "G"
-CMSG_DATA_REQUEST = "M"
-CMSG_PLAYER_NAME = "n"
+CMSG_PROTO_VERSION= b"v"
+CMSG_KEY = b"k"
+CMSG_ADD_PLAYER = b"+"
+CMSG_REMOVE_PLAYER= b"-"
+CMSG_UDP_PORT = b"<"
+CMSG_ENABLE_SOUND = b"s"
+CMSG_ENABLE_MUSIC = b"m"
+CMSG_PING = b"g"
+CMSG_PONG = b"G"
+CMSG_DATA_REQUEST = b"M"
+CMSG_PLAYER_NAME = b"n"
BROADCAST_MESSAGE = "game!" # less than 6 bytes
@@ -60,7 +60,7 @@ def message(tp, *values):
typecodes = ''.join(typecodes)
assert len(typecodes) < 256
return pack(("!B%dsc" % len(typecodes)) + typecodes,
- len(typecodes), typecodes, tp, *values)
+ len(typecodes), typecodes.encode(), tp, *values)
def decodemessage(data):
if data:
diff --git a/common/pixmap.py b/common/pixmap.py
index 13142d5..51bfd8b 100644
--- a/common/pixmap.py
+++ b/common/pixmap.py
@@ -1,8 +1,8 @@
-from __future__ import generators
-import cStringIO
+
+import io
def decodepixmap(data):
- f = cStringIO.StringIO(data)
+ f = io.StringIO(data)
sig = f.readline().strip()
assert sig == "P6"
while 1:
@@ -10,7 +10,7 @@ def decodepixmap(data):
if not line.startswith('#'):
break
wh = line.split()
- w, h = map(int, wh)
+ w, h = list(map(int, wh))
sig = f.readline().strip()
assert sig == "255"
data = f.read()
@@ -20,7 +20,9 @@ def decodepixmap(data):
def encodepixmap(w, h, data):
return 'P6\n%d %d\n255\n%s' % (w, h, data)
-def cropimage((w, h, data), (x1, y1, w1, h1)):
+def cropimage(xxx_todo_changeme, xxx_todo_changeme1):
+ (w, h, data) = xxx_todo_changeme
+ (x1, y1, w1, h1) = xxx_todo_changeme1
assert 0 <= x1 <= x1+w1 <= w
assert 0 <= y1 <= y1+h1 <= h
scanline = w*3
@@ -80,10 +82,12 @@ translation_darker = ('\x00\x01' + '\x00'*126 +
''.join([chr(n//4) for n in range(0,128)]))
translation_dragon = translation_darker[:255] + '\xC0'
-def make_dark((w, h, data), translation):
+def make_dark(xxx_todo_changeme2, translation):
+ (w, h, data) = xxx_todo_changeme2
return w, h, data.translate(translation)
-def col((r, g, b)):
+def col(xxx_todo_changeme3):
+ (r, g, b) = xxx_todo_changeme3
r = ord(r)
g = ord(g)
b = ord(b)
diff --git a/common/stdlog.py b/common/stdlog.py
index 3d8063c..4abc280 100644
--- a/common/stdlog.py
+++ b/common/stdlog.py
@@ -24,7 +24,7 @@ class LogFile:
self.f.close()
self.f = None
- def __nonzero__(self):
+ def __bool__(self):
return self.f is not None
def _open(self, filename):
@@ -42,8 +42,8 @@ class LogFile:
return 0
self.filename = filename
if self.f.tell() > 0:
- print >> self.f
- print >> self.f, '='*44
+ print(file=self.f)
+ print('='*44, file=self.f)
return 1
def _check(self):
diff --git a/common/udpovertcp.py b/common/udpovertcp.py
index eae3d6b..f99b2b3 100644
--- a/common/udpovertcp.py
+++ b/common/udpovertcp.py
@@ -1,5 +1,5 @@
from socket import *
-from msgstruct import *
+from .msgstruct import *
#from fcntl import ioctl
#from termios import TIOCOUTQ
from zlib import compressobj, Z_SYNC_FLUSH
@@ -19,12 +19,12 @@ class SocketMarshaller:
# try to reduce TCP latency
try:
tcpsock.setsockopt(SOL_IP, IP_TOS, 0x10) # IPTOS_LOWDELAY
- except error, e:
- print "Cannot set IPTOS_LOWDELAY for client:", str(e)
+ except error as e:
+ print("Cannot set IPTOS_LOWDELAY for client:", str(e))
try:
tcpsock.setsockopt(SOL_TCP, TCP_NODELAY, 1)
- except error, e:
- print "Cannot set TCP_NODELAY for client:", str(e)
+ except error as e:
+ print("Cannot set TCP_NODELAY for client:", str(e))
compressor = compressobj(6)
self.compress = compressor.compress
self.compress_flush = compressor.flush
diff --git a/metaserver/metaclient.py b/metaserver/metaclient.py
index aedb99c..828d2dd 100644
--- a/metaserver/metaclient.py
+++ b/metaserver/metaclient.py
@@ -1,7 +1,7 @@
import sys, os, time, random
from select import select
from socket import *
-from metastruct import *
+from .metastruct import *
_SERVER = 'ctpug.org.za'
@@ -13,16 +13,16 @@ VERSION_TAG = 1601
def connect(failure=[]):
if len(failure) >= 2:
return None
- print >> sys.stderr, 'Connecting to the meta-server %s:%d...' % METASERVER
+ print('Connecting to the meta-server %s:%d...' % METASERVER, file=sys.stderr)
try:
s = socket(AF_INET, SOCK_STREAM)
s.connect(METASERVER)
- except error, e:
- print >> sys.stderr, '*** cannot contact meta-server:', str(e)
+ except error as e:
+ print('*** cannot contact meta-server:', str(e), file=sys.stderr)
failure.append(e)
return None
else:
- print >> sys.stderr, 'connected.'
+ print('connected.', file=sys.stderr)
return s
sys.setcheckinterval(4096)
@@ -30,7 +30,7 @@ sys.setcheckinterval(4096)
def float2str(f):
# don't trust locale issues and write a string with a '.'
- s = str(long(f*1000000.0))
+ s = str(int(f*1000000.0))
return s[:-6] + '.' + s[-6:]
def str2float(s):
@@ -76,19 +76,19 @@ class MetaClientSrv(MessageSocket):
import gamesrv
gamesrv.removesocket('META', self.s)
self.closed = 1
- print >> sys.stderr, 'disconnected from the meta-server'
+ print('disconnected from the meta-server', file=sys.stderr)
def send_traceback(self):
if not self.closed:
- import traceback, cStringIO, sys
- f = cStringIO.StringIO()
- print >> f, sys.version
- print >> f, 'platform: ', sys.platform
- print >> f, 'executable: ', sys.executable
- print >> f, 'argv: ', sys.argv
- print >> f, 'cwd: ', os.getcwd()
- print >> f, 'version tag:', VERSION_TAG
- print >> f
+ import traceback, io, sys
+ f = io.StringIO()
+ print(sys.version, file=f)
+ print('platform: ', sys.platform, file=f)
+ print('executable: ', sys.executable, file=f)
+ print('argv: ', sys.argv, file=f)
+ print('cwd: ', os.getcwd(), file=f)
+ print('version tag:', VERSION_TAG, file=f)
+ print(file=f)
traceback.print_exc(file = f)
self.s.sendall(message(MMSG_TRACEBACK, f.getvalue()))
@@ -100,37 +100,37 @@ class MetaClientSrv(MessageSocket):
if self.lastwakeup == wakeup:
sys.setcheckinterval(4096)
self.synsockets.clear()
- import thread
+ import _thread
self.lastwakeup = time.time()
- thread.start_new_thread(fastresponses, (self.lastwakeup,))
+ _thread.start_new_thread(fastresponses, (self.lastwakeup,))
def msg_connect(self, origin, port, *rest):
def connect(origin, port):
host, _ = origin.split(':')
addr = host, port
s = socket(AF_INET, SOCK_STREAM)
- print >> sys.stderr, 'backconnecting to', addr
+ print('backconnecting to', addr, file=sys.stderr)
try:
s.connect(addr)
- except error, e:
- print >> sys.stderr, 'backconnecting:', str(e)
+ except error as e:
+ print('backconnecting:', str(e), file=sys.stderr)
else:
self.game.newclient_threadsafe(s, addr)
- import thread
- thread.start_new_thread(connect, (origin, port))
+ import _thread
+ _thread.start_new_thread(connect, (origin, port))
def msg_udp_conn(self, origin, secret, port, *rest):
def connect(origin, secret, port):
host, _ = origin.split(':')
addr = host, port
s = socket(AF_INET, SOCK_DGRAM)
- print >> sys.stderr, 'udp connecting to', addr
+ print('udp connecting to', addr, file=sys.stderr)
s.connect(addr)
mysecret = random.randrange(0, 65536)
packet = ('B' + chr( secret & 0xFF) + chr( secret >> 8)
+ chr(mysecret & 0xFF) + chr(mysecret >> 8))
- from socketoverudp import SocketOverUdp
- from socketoverudp import SOU_RANGE_START, SOU_RANGE_STOP
+ from .socketoverudp import SocketOverUdp
+ from .socketoverudp import SOU_RANGE_START, SOU_RANGE_STOP
for i in range(5):
#print 'sending', repr(packet)
s.send(packet)
@@ -153,7 +153,7 @@ class MetaClientSrv(MessageSocket):
SOU_RANGE_START <= ord(inbuf[0]) < SOU_RANGE_STOP):
break
else:
- print >> sys.stderr, 'udp connecting: no answer, giving up'
+ print('udp connecting: no answer, giving up', file=sys.stderr)
return
sock = SocketOverUdp(s, (mysecret, secret))
data = sock._decode(inbuf)
@@ -163,13 +163,13 @@ class MetaClientSrv(MessageSocket):
#print 'waiting for more'
iwtd, owtd, ewtd = select([sock], [], [], 5.0)
if sock not in iwtd:
- print >> sys.stderr, 'udp connecting: timed out'
+ print('udp connecting: timed out', file=sys.stderr)
return
#print 'decoding more'
data += sock.recv()
#print 'now data is', repr(data)
if data[:-2] != expected:
- print >> sys.stderr, 'udp connecting: bad data'
+ print('udp connecting: bad data', file=sys.stderr)
return
sock.sendall('[bnb s->c]' + data[-2:])
sock.flush()
@@ -177,19 +177,19 @@ class MetaClientSrv(MessageSocket):
while 1:
iwtd, owtd, ewtd = select([sock], [], [], 5.0)
if sock not in iwtd:
- print >> sys.stderr, 'udp connecting: timed out'
+ print('udp connecting: timed out', file=sys.stderr)
return
data = sock.recv(200)
if data:
break
if data != '^':
- print >> sys.stderr, 'udp connecting: bad data'
+ print('udp connecting: bad data', file=sys.stderr)
return
#print 'done!'
self.game.newclient_threadsafe(sock, addr)
- import thread
- thread.start_new_thread(connect, (origin, secret, port))
+ import _thread
+ _thread.start_new_thread(connect, (origin, secret, port))
def msg_ping(self, origin, *rest):
# ping time1 --> pong time2 time1
@@ -213,15 +213,15 @@ class MetaClientSrv(MessageSocket):
#print 'sleep(%r)' % delay
if 0.0 <= delay <= 10.0:
time.sleep(delay)
- print >> sys.stderr, 'synconnecting to', addr
+ print('synconnecting to', addr, file=sys.stderr)
try:
s.connect(addr)
- except error, e:
- print >> sys.stderr, 'synconnecting:', str(e)
+ except error as e:
+ print('synconnecting:', str(e), file=sys.stderr)
else:
self.game.newclient_threadsafe(s, addr)
- import thread
- thread.start_new_thread(connect, (origin, clientport, connecttime, s))
+ import _thread
+ _thread.start_new_thread(connect, (origin, clientport, connecttime, s))
MESSAGES = {
RMSG_CONNECT: msg_connect,
@@ -266,8 +266,8 @@ def meta_unregister(game):
class Event:
def __init__(self):
- import thread
- self.lock = thread.allocate_lock()
+ import _thread
+ self.lock = _thread.allocate_lock()
self.lock.acquire()
def signal(self):
try:
@@ -288,24 +288,24 @@ class MetaClientCli:
self.threads = {}
def run(self):
- import thread
- print >> sys.stderr, 'Trying to connect to', self.serverkey
+ import _thread
+ print('Trying to connect to', self.serverkey, file=sys.stderr)
self.ev = Event()
self.ev2 = Event()
self.buffer = ""
- self.sendlock = thread.allocate_lock()
- self.recvlock = thread.allocate_lock()
+ self.sendlock = _thread.allocate_lock()
+ self.recvlock = _thread.allocate_lock()
self.inputmsgqueue = []
self.gotudpport = None
if not (PORTS.get('CLIENT') or PORTS.get('sendudpto')):
self.s = connect()
- thread.start_new_thread(self.acquire_udp_port, ())
+ _thread.start_new_thread(self.acquire_udp_port, ())
else:
self.s = None
self.ev2.signal()
self.startthread(self.try_udp_connect)
- thread.start_new_thread(self.bipbip, ())
+ _thread.start_new_thread(self.bipbip, ())
self.startthread(self.try_direct_connect, 0.75)
self.startthread(self.try_indirect_connect, 1.50)
while self.resultsocket is None:
@@ -323,7 +323,7 @@ class MetaClientCli:
self.ev.signal()
def startthread(self, fn, sleep=0.0, args=()):
- import thread
+ import _thread
def bootstrap(fn, atom, sleep, args):
try:
time.sleep(sleep)
@@ -334,21 +334,21 @@ class MetaClientCli:
self.ev.signal()
atom = object()
self.threads[atom] = time.time()
- thread.start_new_thread(bootstrap, (fn, atom, sleep, args))
+ _thread.start_new_thread(bootstrap, (fn, atom, sleep, args))
def threadsleft(self):
if self.fatalerror:
sys.exit(1)
now = time.time()
TIMEOUT = 11
- for starttime in self.threads.values():
+ for starttime in list(self.threads.values()):
if now < starttime + TIMEOUT:
break
else:
if self.threads:
- print >> sys.stderr, '*** time out, giving up.'
+ print('*** time out, giving up.', file=sys.stderr)
else:
- print >> sys.stderr, '*** failed to connect.'
+ print('*** failed to connect.', file=sys.stderr)
sys.exit(1)
def try_direct_connect(self):
@@ -357,14 +357,14 @@ class MetaClientCli:
s = socket(AF_INET, SOCK_STREAM)
try:
s.connect((host, port))
- except error, e:
- print >> sys.stderr, 'direct connexion failed:', str(e)
+ except error as e:
+ print('direct connexion failed:', str(e), file=sys.stderr)
else:
- print >> sys.stderr, 'direct connexion accepted.'
+ print('direct connexion accepted.', file=sys.stderr)
self.resultsocket = s
def try_indirect_connect(self):
- import thread, time
+ import _thread, time
if not self.s:
self.s = connect()
if not self.s:
@@ -413,8 +413,8 @@ class MetaClientCli:
self.gotudpport = msg[1], int(msg[2])
continue
if msg[0] == RMSG_NO_HOST and msg[1] == self.serverkey:
- print >> sys.stderr, ('*** server %r is not registered'
- ' on the meta-server' % (msg[1],))
+ print(('*** server %r is not registered'
+ ' on the meta-server' % (msg[1],)), file=sys.stderr)
self.fatalerror = True
sys.exit()
self.inputmsgqueue.append(msg)
@@ -425,7 +425,7 @@ class MetaClientCli:
return
data = self.s.recv(2048)
if not data:
- print >> sys.stderr, 'disconnected from the meta-server'
+ print('disconnected from the meta-server', file=sys.stderr)
sys.exit()
self.buffer += data
finally:
@@ -441,11 +441,11 @@ class MetaClientCli:
s1.listen(1)
_, port = s1.getsockname()
self.routemsg(RMSG_CONNECT, port)
- print >> sys.stderr, 'listening for backward connection'
+ print('listening for backward connection', file=sys.stderr)
iwtd, owtd, ewtd = select([s1], [], [], 7.5)
if s1 in iwtd:
s, addr = s1.accept()
- print >> sys.stderr, 'accepted backward connection from', addr
+ print('accepted backward connection from', addr, file=sys.stderr)
self.resultsocket = s
def send_ping(self):
@@ -459,11 +459,11 @@ class MetaClientCli:
remoteaddr = remotehost, remoteport
try:
s.connect(remoteaddr)
- except error, e:
- print >> sys.stderr, 'SYN connect failed:', str(e)
+ except error as e:
+ print('SYN connect failed:', str(e), file=sys.stderr)
return
- print >> sys.stderr, ('simultaneous SYN connect succeeded with %s:%d' %
- remoteaddr)
+ print(('simultaneous SYN connect succeeded with %s:%d' %
+ remoteaddr), file=sys.stderr)
self.resultsocket = s
def try_udp_connect(self):
@@ -500,7 +500,7 @@ class MetaClientCli:
for name in ('*udpsock*', 'CLIENT'):
if name in PORTS:
del PORTS[name]
- from socketoverudp import SocketOverUdp
+ from .socketoverudp import SocketOverUdp
sock = SocketOverUdp(s, (originalsecret, remotesecret))
#print 'sending', repr(packet)
sock.sendall(packet)
@@ -511,24 +511,24 @@ class MetaClientCli:
#print 'waiting'
iwtd, owtd, ewtd = select([sock], [], [], 2.5)
if sock not in iwtd:
- print >> sys.stderr, 'socket-over-udp timed out'
+ print('socket-over-udp timed out', file=sys.stderr)
return
#print 'we get:'
data += sock.recv()
#print repr(data)
if data != expected:
- print >> sys.stderr, 'bad udp data from', addr
+ print('bad udp data from', addr, file=sys.stderr)
else:
sock.sendall('^')
sock.flush()
- print 'udp connexion handshake succeeded'
+ print('udp connexion handshake succeeded')
self.resultsocket = sock
def acquire_udp_port(self):
try:
s = socket(AF_INET, SOCK_DGRAM)
s.bind(('', INADDR_ANY))
- randomdata = hex(random.randrange(0, sys.maxint))
+ randomdata = hex(random.randrange(0, sys.maxsize))
for i in range(5):
s.sendto(randomdata, METASERVER_UDP)
time.sleep(0.05)
@@ -538,9 +538,9 @@ class MetaClientCli:
if self.gotudpport:
PORTS['*udpsock*'] = s, self.gotudpport
udphost, udpport = self.gotudpport
- print >> sys.stderr, ('udp port %d is visible from '
+ print(('udp port %d is visible from '
'outside on %s:%d' % (
- s.getsockname()[1], udphost, udpport))
+ s.getsockname()[1], udphost, udpport)), file=sys.stderr)
self.startthread(self.try_udp_connect)
break
finally:
@@ -568,13 +568,13 @@ def print_server_list():
assert msg[0] == RMSG_LIST
entries = decodedict(msg[1])
if not entries:
- print >> sys.stderr, 'No registered server.'
+ print('No registered server.', file=sys.stderr)
else:
- print
- print ' %-25s | %-30s | %s' % (
- 'server', 'game', 'players')
- print '-'*27+'+'+'-'*32+'+'+'-'*11
- for key, value in entries.items():
+ print()
+ print(' %-25s | %-30s | %s' % (
+ 'server', 'game', 'players'))
+ print('-'*27+'+'+'-'*32+'+'+'-'*11)
+ for key, value in list(entries.items()):
if ':' in key:
try:
addr, _, _ = gethostbyaddr(key[:key.index(':')])
@@ -585,12 +585,12 @@ def print_server_list():
if len(addr) < 28: addr += '|'
addr = '%-60s' % (addr,)
if len(addr) < 61: addr += '|'
- print addr
+ print(addr)
value = decodedict(value)
- print ' %-25s | %-30s | %s' % (
+ print(' %-25s | %-30s | %s' % (
key, value.get('desc', '<no description>'),
- value.get('extradesc', ''))
- print
+ value.get('extradesc', '')))
+ print()
if __name__ == '__main__':
print_server_list()
diff --git a/metaserver/metaserver.py b/metaserver/metaserver.py
index cb4ea19..73c6ee3 100644
--- a/metaserver/metaserver.py
+++ b/metaserver/metaserver.py
@@ -1,9 +1,9 @@
from socket import *
import os, sys, time, random
from select import select
-from cStringIO import StringIO
+from io import StringIO
from weakref import WeakValueDictionary
-from metastruct import *
+from .metastruct import *
from common import httpserver, stdlog
if __name__ == '__main__':
@@ -40,14 +40,14 @@ class MetaServer:
def detach(self):
pid = os.fork()
if pid:
- print pid
+ print(pid)
os._exit(0)
# in the child process
os.setsid()
logfile = stdlog.LogFile(limitsize=131072)
if logfile:
- print >> logfile
- print "Logging to", logfile.filename
+ print(file=logfile)
+ print("Logging to", logfile.filename)
fd = logfile.f.fileno()
try:
# detach from parent
@@ -59,7 +59,7 @@ class MetaServer:
logfile.close()
# record pid
f = open('pid', 'w')
- print >> f, os.getpid()
+ print(os.getpid(), file=f)
f.close()
def clientconnect(self):
@@ -77,7 +77,7 @@ class MetaServer:
raise OverflowError
self.ServersList.append(server)
self.ServersDict[key] = server
- print '+', key
+ print('+', key)
def unpublish(self, server):
key = server.serverkey
@@ -86,7 +86,7 @@ class MetaServer:
if current is server:
del self.ServersDict[key]
self.ServersList.remove(server)
- print '-', key
+ print('-', key)
def makelist(self):
items = {}
@@ -116,7 +116,7 @@ class Connexion(MessageSocket):
self.addr = addr
self.key = '%s:%d' % addr
self.serverkey = None
- print '[', self.key
+ print('[', self.key)
self.backlinks = WeakValueDictionary()
if len(serversockets) >= MAX_CONNEXIONS:
self.disconnect()
@@ -129,10 +129,10 @@ class Connexion(MessageSocket):
del serversockets[self.s]
except KeyError:
pass
- print ']', self.key
+ print(']', self.key)
def msg_serverinfo(self, info, *rest):
- print '|', self.key
+ print('|', self.key)
if len(info) > 15000:
raise OverflowError
info = decodedict(info)
@@ -169,7 +169,7 @@ class Connexion(MessageSocket):
def msg_traceback(self, tb, *rest):
f = stdlog.LogFile('tb-%s.log' % (self.addr[0],))
if f:
- print >> f, tb
+ print(tb, file=f)
f.close()
def msg_udp_addr(self, pattern, *rest):
@@ -198,9 +198,9 @@ class Connexion(MessageSocket):
# ____________________________________________________________
-import htmlentitydefs
+import html.entities
text_to_html = {}
-for key, value in htmlentitydefs.entitydefs.items():
+for key, value in list(html.entities.entitydefs.items()):
text_to_html[value] = '&' + key + ';'
for i in range(32):
text_to_html[chr(i)] = '?'
@@ -305,7 +305,7 @@ httpserver.register('mbub.png', httpserver.fileloader('mbub.png', 'image/png'))
httpserver.register('home.png', httpserver.fileloader('home.png', 'image/png'))
def openhttpsocket(port = META_SERVER_HTTP_PORT):
- from BaseHTTPServer import HTTPServer
+ from http.server import HTTPServer
class ServerClass(HTTPServer):
def get_request(self):
sock, addr = self.socket.accept()
@@ -322,19 +322,19 @@ def openhttpsocket(port = META_SERVER_HTTP_PORT):
def mainloop():
while 1:
- iwtd = serversockets.keys()
+ iwtd = list(serversockets.keys())
iwtd, owtd, ewtd = select(iwtd, [], iwtd)
#print iwtd, owtd, ewtd, serversockets
for s in iwtd:
if s in serversockets:
input, close = serversockets[s]
try:
- input()
+ eval(input())
except:
import traceback
- print "-"*60
+ print("-"*60)
traceback.print_exc()
- print "-"*60
+ print("-"*60)
for s in ewtd:
if s in serversockets:
input, close = serversockets[s]
@@ -342,9 +342,9 @@ def mainloop():
close()
except:
import traceback
- print "-"*60
+ print("-"*60)
traceback.print_exc()
- print "-"*60
+ print("-"*60)
if __name__ == '__main__':
@@ -353,13 +353,13 @@ if __name__ == '__main__':
metaserver.detach()
try:
openhttpsocket()
- print 'listening to client port tcp %d / http %d / udp %d.' % (
+ print('listening to client port tcp %d / http %d / udp %d.' % (
META_SERVER_PORT,
META_SERVER_HTTP_PORT,
- META_SERVER_UDP_PORT)
+ META_SERVER_UDP_PORT))
mainloop()
finally:
if metaserver.ServersList:
- print '*** servers still connected, waiting 5 seconds'
+ print('*** servers still connected, waiting 5 seconds')
time.sleep(5)
- print '*** leaving at', time.ctime()
+ print('*** leaving at', time.ctime())
diff --git a/metaserver/metastruct.py b/metaserver/metastruct.py
index 13240cc..e187b65 100644
--- a/metaserver/metastruct.py
+++ b/metaserver/metastruct.py
@@ -27,7 +27,7 @@ RMSG_NO_HOST = '?'
def encodedict(dict):
data = []
- for key, value in dict.items():
+ for key, value in list(dict.items()):
data.append(message('#', key, value))
return ''.join(data)
@@ -69,7 +69,7 @@ class MessageSocket:
if msg is None:
break
if msg[0] not in self.MESSAGES:
- print >> sys.stderr, 'unknown message %r' % (msg[0],)
+ print('unknown message %r' % (msg[0],), file=sys.stderr)
else:
fn = self.MESSAGES[msg[0]]
fn(self, *msg[1:])
diff --git a/metaserver/pipelayer.py b/metaserver/pipelayer.py
index 9baf78a..82a8cd9 100644
--- a/metaserver/pipelayer.py
+++ b/metaserver/pipelayer.py
@@ -209,7 +209,7 @@ class PipeLayer(object):
def bad_crc(self):
import sys
- print >> sys.stderr, "warning: bad crc on udp connexion"
+ print("warning: bad crc on udp connexion", file=sys.stderr)
self.in_outoforder.clear()
self.out_flags = FLAG_NAK
self.out_nextrepeattime = self.cur_time
@@ -217,15 +217,15 @@ class PipeLayer(object):
_dump_indent = 0
def dump(self, dir, rawdata):
in_flags, ack_seqid, in_seqid = struct.unpack("!BBH", rawdata[:4])
- print ' ' * self._dump_indent, dir,
+ print(' ' * self._dump_indent, dir, end=' ')
if in_flags == FLAG_NAK:
- print 'NAK',
+ print('NAK', end=' ')
elif in_flags == FLAG_NAK1:
- print 'NAK1',
+ print('NAK1', end=' ')
elif in_flags == FLAG_CFRM:
- print 'CFRM',
+ print('CFRM', end=' ')
#print ack_seqid, in_seqid, '(%d bytes)' % (len(rawdata)-4,)
- print ack_seqid, in_seqid, repr(rawdata[4:])
+ print(ack_seqid, in_seqid, repr(rawdata[4:]))
def pipe_over_udp(udpsock, send_fd=-1, recv_fd=-1,
@@ -281,11 +281,11 @@ def pipe_over_udp(udpsock, send_fd=-1, recv_fd=-1,
class PipeOverUdp(object):
def __init__(self, udpsock, timeout=1.0):
- import thread, os
+ import _thread, os
self.os = os
self.sendpipe = os.pipe()
self.recvpipe = os.pipe()
- thread.start_new_thread(pipe_over_udp, (udpsock,
+ _thread.start_new_thread(pipe_over_udp, (udpsock,
self.sendpipe[0],
self.recvpipe[1],
timeout))
diff --git a/metaserver/socketoverudp.py b/metaserver/socketoverudp.py
index 2df4a75..14565c8 100644
--- a/metaserver/socketoverudp.py
+++ b/metaserver/socketoverudp.py
@@ -1,6 +1,6 @@
from time import time as now
-from pipelayer import PipeLayer, InvalidPacket
-from pipelayer import FLAG_RANGE_START, FLAG_RANGE_STOP
+from .pipelayer import PipeLayer, InvalidPacket
+from .pipelayer import FLAG_RANGE_START, FLAG_RANGE_STOP
import socket, struct
SOU_RANGE_START = FLAG_RANGE_START