summaryrefslogtreecommitdiff
path: root/bubbob
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 /bubbob
parent1d9925c287b318ec21343e2682b51ab6a36ae8db (diff)
2to3
Diffstat (limited to 'bubbob')
-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
16 files changed, 201 insertions, 196 deletions
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']