diff options
Diffstat (limited to 'display')
| -rw-r--r-- | display/Client.py | 62 | ||||
| -rw-r--r-- | display/caching.py | 28 | ||||
| -rw-r--r-- | display/dpy_gtk.py | 22 | ||||
| -rw-r--r-- | display/dpy_pygame.py | 10 | ||||
| -rwxr-xr-x | display/dpy_windows.py | 4 | ||||
| -rw-r--r-- | display/dpy_x.py | 11 | ||||
| -rw-r--r-- | display/modes.py | 31 | ||||
| -rw-r--r-- | display/pclient.py | 86 | ||||
| -rw-r--r-- | display/playback.py | 25 | ||||
| -rw-r--r-- | display/puremixer.py | 8 | ||||
| -rw-r--r-- | display/pythonxlibintf.py | 16 | ||||
| -rw-r--r-- | display/snd_linux.py | 20 | ||||
| -rw-r--r-- | display/snd_pygame.py | 6 | ||||
| -rw-r--r-- | display/snd_windows.py | 14 | 
14 files changed, 177 insertions, 166 deletions
diff --git a/display/Client.py b/display/Client.py index 3d1330d..275c663 100644 --- a/display/Client.py +++ b/display/Client.py @@ -16,8 +16,8 @@ LOCALDIR = os.path.dirname(os.path.abspath(LOCALDIR))  sys.path.insert(0, os.path.dirname(LOCALDIR))  sys.path.insert(0, LOCALDIR)  import common -import pclient -import modes +from . import pclient +from . import modes  UdpLookForServer = [ @@ -28,42 +28,42 @@ UdpLookForServer = [  def parse_cmdline(argv):      # parse command-line      def usage(): -        print >> sys.stderr, 'usage:' -        print >> sys.stderr, '  python Client.py [-d#] [-s#] [extra options] [host[:port]]' -        print >> sys.stderr -        print >> sys.stderr, 'options:' -        print >> sys.stderr, '  host              search for a game on the given machine' -        print >> sys.stderr, '  host:port         connect to the given game server' -        print >> sys.stderr, '                      (default search for any local server)' -        print >> sys.stderr, '  -d#  --display=#  graphic driver (see below)' -        print >> sys.stderr, '  -s#  --sound=#    sound driver (see below)' -        print >> sys.stderr, '       --music=no   disable background music' -        print >> sys.stderr, '  -h   --help       display this text' -        print >> sys.stderr, '  -m   --metaserver connect with the help of the metaserver' -        print >> sys.stderr, '                      (list servers with Client.py -m)' -        print >> sys.stderr, '  -t   --tcp        for slow or proxy connections' -        print >> sys.stderr, '  -u   --udp        for fast direct connections' -        print >> sys.stderr, '                      (default is to autodetect tcp or udp)' -        print >> sys.stderr, '  --port UDP=# or #:#   fixed inbound udp port or host:port' -        print >> sys.stderr, '  --port TCP=#          fixed inbound tcp port (-m only)' -        print >> sys.stderr -        print >> sys.stderr, 'graphic drivers:' +        print('usage:', file=sys.stderr) +        print('  python Client.py [-d#] [-s#] [extra options] [host[:port]]', file=sys.stderr) +        print(file=sys.stderr) +        print('options:', file=sys.stderr) +        print('  host              search for a game on the given machine', file=sys.stderr) +        print('  host:port         connect to the given game server', file=sys.stderr) +        print('                      (default search for any local server)', file=sys.stderr) +        print('  -d#  --display=#  graphic driver (see below)', file=sys.stderr) +        print('  -s#  --sound=#    sound driver (see below)', file=sys.stderr) +        print('       --music=no   disable background music', file=sys.stderr) +        print('  -h   --help       display this text', file=sys.stderr) +        print('  -m   --metaserver connect with the help of the metaserver', file=sys.stderr) +        print('                      (list servers with Client.py -m)', file=sys.stderr) +        print('  -t   --tcp        for slow or proxy connections', file=sys.stderr) +        print('  -u   --udp        for fast direct connections', file=sys.stderr) +        print('                      (default is to autodetect tcp or udp)', file=sys.stderr) +        print('  --port UDP=# or #:#   fixed inbound udp port or host:port', file=sys.stderr) +        print('  --port TCP=#          fixed inbound tcp port (-m only)', file=sys.stderr) +        print(file=sys.stderr) +        print('graphic drivers:', file=sys.stderr)          for info in modes.graphicmodeslist():              info.printline(sys.stderr) -        print >> sys.stderr -        print >> sys.stderr, 'sound drivers:' +        print(file=sys.stderr) +        print('sound drivers:', file=sys.stderr)          for info in modes.soundmodeslist():              info.printline(sys.stderr) -        print >> sys.stderr +        print(file=sys.stderr)          sys.exit(2)      shortopts = 'd:s:htum'      longopts = ['display=', 'sound=', 'music=', 'help', 'tcp', 'udp',                  'cfg=', 'metaserver', 'port=']      for info in modes.graphicmodeslist() + modes.soundmodeslist(): -        short, long = info.getformaloptions() +        short, int = info.getformaloptions()          shortopts += short -        longopts += long +        longopts += int      try:          from getopt import gnu_getopt as getopt      except ImportError: @@ -71,9 +71,9 @@ def parse_cmdline(argv):      from getopt import error      try:          opts, args = getopt(argv, shortopts, longopts) -    except error, e: -        print >> sys.stderr, 'Client.py: %s' % str(e) -        print >> sys.stderr +    except error as e: +        print('Client.py: %s' % str(e), file=sys.stderr) +        print(file=sys.stderr)          usage()      metaserver = 0 @@ -144,7 +144,7 @@ def parse_cmdline(argv):      return directconnect(server), mode  def directconnect(sockaddr): -    print "connecting to %s:%d..." % sockaddr +    print("connecting to %s:%d..." % sockaddr)      from socket import socket, AF_INET, SOCK_STREAM      s = socket(AF_INET, SOCK_STREAM)      s.connect(sockaddr) diff --git a/display/caching.py b/display/caching.py index 27d772c..bdbfdea 100644 --- a/display/caching.py +++ b/display/caching.py @@ -1,4 +1,4 @@ -from __future__ import generators +  import os, md5, sys  #import common.debug @@ -18,7 +18,7 @@ class FileCache:                  del self.cache[filename]          if filename not in self.cache:              if len(self.cache) >= FileCache.MAX_FILES: -                (time, mode, f), k = min([(v,k) for (k,v) in self.cache.items()]) +                (time, mode, f), k = min([(v,k) for (k,v) in list(self.cache.items())])                  f.close()                  del self.cache[k]              try: @@ -54,13 +54,13 @@ class FileBlock:      def overwrite(self, newdata):          self.memorydata = newdata          if self.readonly: -            print >> sys.stderr, "cannot overwrite file", self.filename +            print("cannot overwrite file", self.filename, file=sys.stderr)              return          try:              f = Data.Cache.access(self.filename, self.position, writing=1)              f.write(newdata)          except (IOError, OSError): -            print >> sys.stderr, "cache write error:", self.filename +            print("cache write error:", self.filename, file=sys.stderr)              return          self.complete = 1          del self.memorydata @@ -107,7 +107,7 @@ class Data:                  f.write(data)                  f.flush()              except (IOError, OSError): -                print >> sys.stderr, "cache write error:", self.backupfile +                print("cache write error:", self.backupfile, file=sys.stderr)      def loadfrom(self, filename, position, length, checksum):          """Try to load data from the given filename, with the given @@ -128,19 +128,19 @@ class Data:                      # correct data                      self.store(position, data, name, readonly)                      return 1 -        if self.content is not None and not self.content.has_key(position): +        if self.content is not None and position not in self.content:              self.content[position] = FileBlock(cachename, position, length,                                                 readonly=0, complete=0)          elif self.readonly: -            print >> sys.stderr, "Note: the music data has changed. You can get" -            print >> sys.stderr, "the server's version by deleting", directname +            print("Note: the music data has changed. You can get", file=sys.stderr) +            print("the server's version by deleting", directname, file=sys.stderr)              return 1   # incorrect data, but ignored          return 0      def read(self):          """Return the data as built so far."""          if self.content is not None: -            items = self.content.items() +            items = list(self.content.items())              items.sort()              result = ''              for position, block in items: @@ -155,7 +155,7 @@ class Data:      def fopen(self):          if self.content is not None: -            from cStringIO import StringIO +            from io import StringIO              return StringIO(self.read())          else:              return Data.Cache.access(self.backupfile, 0) @@ -166,19 +166,19 @@ class Data:          the file that we want."""          if not self.backupfile:              files = {} -            for position, block in self.content.items(): +            for position, block in list(self.content.items()):                  if not isinstance(block, FileBlock):                      break                  if block.complete:                      files[block.filename] = block              else:                  if len(files) == 1: -                    self.backupfile, block = files.items()[0] +                    self.backupfile, block = list(files.items())[0]                      self.readonly = block.readonly              if not self.backupfile:                  self.backupfile = mktemp(fileexthint)                  f = Data.Cache.access(self.backupfile, 0, writing=1) -                for position, block in self.content.items(): +                for position, block in list(self.content.items()):                      f.seek(position)                      f.write(block.read())                  f.flush() @@ -258,4 +258,4 @@ def enumtempfiles():          i += 1  def mktemp(fileext, gen = enumtempfiles()): -    return gen.next() + fileext +    return next(gen) + fileext diff --git a/display/dpy_gtk.py b/display/dpy_gtk.py index 7b73516..43d797f 100644 --- a/display/dpy_gtk.py +++ b/display/dpy_gtk.py @@ -4,8 +4,8 @@  ################################################  import os, sys, math -from modes import KeyPressed, KeyReleased -import caching +from .modes import KeyPressed, KeyReleased +from . import caching  def import_trickery():      global gtk, gdk @@ -59,7 +59,8 @@ class Display:          pb = self.pixmap(32, 32, ((pixel+hole)*16 + (hole+pixel)*16) * 16, 0x010101)          self.taskbkgnd = self.renderpixbuf(pb) -    def taskbar(self, (x, y, w, h)): +    def taskbar(self, xxx_todo_changeme): +        (x, y, w, h) = xxx_todo_changeme          scale = self.scale          x2 = x+w          y2 = y+h @@ -74,9 +75,9 @@ class Display:      def pixmap(self, w, h, data, colorkey=-1):          filename = self.tempppmfile          f = open(filename, 'wb') -        print >> f, 'P6' -        print >> f, w, h -        print >> f, 255 +        print('P6', file=f) +        print(w, h, file=f) +        print(255, file=f)          f.write(data)          f.close()          pb = gdk.pixbuf_new_from_file(filename) @@ -101,7 +102,8 @@ class Display:          else:              return (pixmap, self.gc, None) -    def getopticon(self, input, (x, y, w, h), ignored_alpha=255): +    def getopticon(self, input, xxx_todo_changeme1, ignored_alpha=255): +        (x, y, w, h) = xxx_todo_changeme1          if len(input) == 3:              return None          pb, = input @@ -116,7 +118,8 @@ class Display:          else:              return self.renderpixbuf((newpb,)) -    def getppm(self, (x, y, w, h), int=int, ceil=math.ceil): +    def getppm(self, xxx_todo_changeme2, int=int, ceil=math.ceil): +        (x, y, w, h) = xxx_todo_changeme2          scale = self.scale          if isinstance(scale, int):              x *= scale @@ -134,7 +137,8 @@ class Display:          bkgnd.draw_drawable(self.gc, self.offscreen, x, y, 0, 0, w, h)          return bkgnd, self.gc, None -    def putppm(self, x, y, (pixmap, gc, ignored), rect=None, int=int): +    def putppm(self, x, y, xxx_todo_changeme3, rect=None, int=int): +        (pixmap, gc, ignored) = xxx_todo_changeme3          if pixmap is None:              return          scale = self.scale diff --git a/display/dpy_pygame.py b/display/dpy_pygame.py index acfd200..30d7359 100644 --- a/display/dpy_pygame.py +++ b/display/dpy_pygame.py @@ -6,7 +6,7 @@  import os  import pygame  from pygame.locals import * -from modes import KeyPressed, KeyReleased +from .modes import KeyPressed, KeyReleased  class Display: @@ -136,7 +136,8 @@ class Display:      def clear(self):          self.offscreen.fill([0,0,0,]) -    def fixpos(self, (x, y)): +    def fixpos(self, xxx_todo_changeme): +        (x, y) = xxx_todo_changeme          if self.scale != 1:              x = int(x / self.scale)              y = int(y / self.scale) @@ -185,7 +186,8 @@ class Display:      def selectlist(self):          return [] -    def taskbar(self, (x, y, w, h)): +    def taskbar(self, xxx_todo_changeme1): +        (x, y, w, h) = xxx_todo_changeme1          tbs, tbh = self.tbcache          if tbh != h:              tbs = pygame.Surface((32, h)).convert_alpha(self.offscreen) @@ -223,7 +225,7 @@ def events_dispatch(handlers = EVENT_HANDLERS):          e = pygame.event.poll()          if e.type == NOEVENT:              break -        elif handlers.has_key(e.type): +        elif e.type in handlers:              handlers[e.type](e) diff --git a/display/dpy_windows.py b/display/dpy_windows.py index b01dfcf..c81c270 100755 --- a/display/dpy_windows.py +++ b/display/dpy_windows.py @@ -1,7 +1,7 @@  import sys  import wingame -from modes import BaseDisplay -from cStringIO import StringIO +from .modes import BaseDisplay +from io import StringIO  class Display(BaseDisplay): diff --git a/display/dpy_x.py b/display/dpy_x.py index ffca90f..6b8f4bb 100644 --- a/display/dpy_x.py +++ b/display/dpy_x.py @@ -1,7 +1,7 @@  import sys -import xshm -from modes import BaseDisplay -from cStringIO import StringIO +from . import xshm +from .modes import BaseDisplay +from io import StringIO  class Display(BaseDisplay): @@ -20,9 +20,8 @@ class Display(BaseDisplay):          self.mouseevents = xdpy.mouseevents          self.pointermotion = xdpy.pointermotion          if use_shm and not xdpy.shmmode(): -            print >> sys.stderr, \ -                  "Note: cannot use SHM extension (%dx%d), display will be slow." % \ -                  (width, height) +            print("Note: cannot use SHM extension (%dx%d), display will be slow." % \ +                  (width, height), file=sys.stderr)      def selectlist(self):          if hasattr(self.xdpy, 'fd'): diff --git a/display/modes.py b/display/modes.py index ad0c1c0..0ac680e 100644 --- a/display/modes.py +++ b/display/modes.py @@ -7,7 +7,8 @@ KeyReleased = 3  class BaseDisplay:      __taskbkgnd = None -    def taskbar(self, (x, y, w, h)): +    def taskbar(self, s): +        (x, y, w, h) = s          if self.__taskbkgnd is None:              pixel = "\x00\x00\x80"              hole  = "\x01\x01\x01" @@ -56,22 +57,22 @@ class Mode:              state = ' [%s]' % err          else:              state = '' -        print >> f, '  %-8s %s%s' % (self.name, self.descr, state) +        print('  %-8s %s%s' % (self.name, self.descr, state), file=f)          if self.url: -            print >> f, '             %s' % self.url +            print('             %s' % self.url, file=f)          for line in self.extraoptsdescr: -            print >> f, '             %s' % line +            print('             %s' % line, file=f)      def getformaloptions(self): -        return '', [c+'=' for c in self.options.keys()] +        return '', [c+'=' for c in list(self.options.keys())]      def setoptions(self, options): -        for key in self.options.keys(): -            if options.has_key('--'+key): +        for key in list(self.options.keys()): +            if '--'+key in options:                  self.options[key] = options['--'+key]      def currentdriver(self): -        lst = self.options.items() +        lst = list(self.options.items())          lst.sort()          lst = ['--%s=%s' % keyvalue for keyvalue in lst]          return ' '.join([self.name] + lst) @@ -146,22 +147,22 @@ def findmode(name, lst):                  return info          if last_chance is not None:              return last_chance -        raise KeyError, 'no driver available!' +        raise KeyError('no driver available!')      else:          # find mode by name          for info in lst:              if info.name.upper() == name.upper():                  err = info.imperror()                  if err: -                    raise KeyError, '%s: %s' % (info.name, err) +                    raise KeyError('%s: %s' % (info.name, err))                  return info -        raise KeyError, '%s: no such driver' % name +        raise KeyError('%s: no such driver' % name)  def findmode_err(*args):      try:          return findmode(*args) -    except KeyError, e: -        print >> sys.stderr, str(e) +    except KeyError as e: +        print(str(e), file=sys.stderr)          sys.exit(1)  def open_dpy(mode, width, height, title): @@ -169,7 +170,7 @@ def open_dpy(mode, width, height, title):      ginfo = findmode_err(driver, graphicmodeslist())      ginfo.setoptions(extraopts)      dpy = ginfo.getmodule().Display(width, height, title, **ginfo.options) -    print 'graphics driver:', ginfo.currentdriver() +    print('graphics driver:', ginfo.currentdriver())      return dpy  def open_snd(mode): @@ -183,7 +184,7 @@ def open_snd(mode):          if (sinfo.options['music'].startswith('n') or              sinfo.options['music'] == 'off'):              snd.has_music = 0 -        print 'sound driver:', sinfo.currentdriver() +        print('sound driver:', sinfo.currentdriver())          return snd      else:          return None diff --git a/display/pclient.py b/display/pclient.py index c6546ce..b7ade98 100644 --- a/display/pclient.py +++ b/display/pclient.py @@ -8,9 +8,9 @@ import time  from common.msgstruct import *  from common.pixmap import decodepixmap  from common import hostchooser -import modes -from modes import KeyPressed, KeyReleased -import caching +from . import modes +from .modes import KeyPressed, KeyReleased +from . import caching  #import psyco; psyco.full() @@ -44,13 +44,13 @@ class Icon:                      self.rect = None              return self.pixmap          elif attr in ('bmpcode', 'rect'): -            raise KeyError, attr +            raise KeyError(attr)          elif attr == 'originalrect':              self.originalrect = self.rect              return self.originalrect -        raise AttributeError, attr +        raise AttributeError(attr)      def clear(self): -        if self.__dict__.has_key('pixmap'): +        if 'pixmap' in self.__dict__:              del self.pixmap  class DataChunk(caching.Data): @@ -77,7 +77,7 @@ class DataChunk(caching.Data):          DataChunk.TOTAL += lendata          total = DataChunk.TOTAL >> 10          if total != prev: -            print "downloaded %dkb of data from server" % total +            print("downloaded %dkb of data from server" % total)          self.store(position, data)          try:              self.pending.remove((0, position)) @@ -104,24 +104,24 @@ class Playfield:          self.sockaddr = sockaddr          try:              self.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)          try:              self.s.setsockopt(SOL_TCP, TCP_NODELAY, 1) -        except error, e: -            print >> sys.stderr, "Cannot set TCP_NODELAY:", str(e) +        except error as e: +            print("Cannot set TCP_NODELAY:", str(e), file=sys.stderr)          initialbuf = ""          while 1:              t = self.s.recv(200)              if not t and not hasattr(self.s, 'RECV_CAN_RETURN_EMPTY'): -                raise error, "connexion closed" +                raise error("connexion closed")              initialbuf += t              if len(initialbuf) >= len(MSG_WELCOME):                  head = initialbuf[:len(MSG_WELCOME)]                  tail = initialbuf[len(MSG_WELCOME):]                  if head != MSG_WELCOME: -                    raise error, "connected to something not a game server" +                    raise error("connected to something not a game server")                  if '\n' in tail:                      break          n = tail.index('\n') @@ -135,7 +135,7 @@ class Playfield:  ##            if i >= 0:  ##                self.gameident, self.datapath = (self.gameident[:i].strip(),  ##                                                 self.gameident[i+1:-1]) -        print "connected to %r." % self.gameident +        print("connected to %r." % self.gameident)          self.s.sendall(message(CMSG_PROTO_VERSION, 3))      def setup(self, mode, udp_over_tcp): @@ -156,10 +156,10 @@ class Playfield:          self.playericons = {}          self.screenmode = mode          self.initlevel = 0 -        if mode[-1].has_key('udp_over_tcp'): +        if 'udp_over_tcp' in mode[-1]:              udp_over_tcp = mode[-1]['udp_over_tcp']          self.trackcfgmtime = None -        if mode[-1].has_key('cfgfile'): +        if 'cfgfile' in mode[-1]:              self.trackcfgfile = mode[-1]['cfgfile']          else:              self.trackcfgfile = os.path.join(DataChunk.SOURCEDIR, @@ -217,8 +217,8 @@ class Playfield:                      while self.udpsock in iwtd:                          try:                              udpdata = self.udpsock.recv(65535) -                        except error, e: -                            print >> sys.stderr, e +                        except error as e: +                            print(e, file=sys.stderr)                              errors += 1                              if errors > 10:                                  raise @@ -420,9 +420,9 @@ class Playfield:              t = time.time()              t, t0 = t-t0, t              if t: -                print "%.2f images per second,  %.1f kbytes per second" % ( +                print("%.2f images per second,  %.1f kbytes per second" % (                      float(n)/t, -                    float(self.tcpbytecounter+self.udpbytecounter)/1024/t) +                    float(self.tcpbytecounter+self.udpbytecounter)/1024/t))                  self.tcpbytecounter = -self.udpbytecounter              n = 0          self.painttimes = t0, n @@ -432,7 +432,7 @@ class Playfield:          iconlist = []          f = 1.5 * time.time()          f = f-int(f) -        pi = self.playericons.items() +        pi = list(self.playericons.items())          pi.sort()          xpos = 0          for id, ico in pi: @@ -460,7 +460,8 @@ class Playfield:                  self.animdelay = 0.04          return y0, iconlist -    def clic_taskbar(self, (cx,cy)): +    def clic_taskbar(self, xxx_todo_changeme): +        (cx,cy) = xxx_todo_changeme          y0, icons = self.get_taskbar()          if cy >= y0:              for x, y, ico, id in icons: @@ -480,13 +481,14 @@ class Playfield:                  pass          return y0, bkgnd -    def erase_taskbar(self, (y0, bkgnd)): +    def erase_taskbar(self, xxx_todo_changeme1): +        (y0, bkgnd) = xxx_todo_changeme1          self.dpy.putppm(0, y0, bkgnd)      def nextkeyname(self):          pid, df = self.keydefinition -        undef = [(num, keyname) for keyname, (num, icons) in self.keys.items() -                 if not df.has_key(keyname) and icons] +        undef = [(num, keyname) for keyname, (num, icons) in list(self.keys.items()) +                 if keyname not in df and icons]          if undef:              num, keyname = min(undef)              return keyname @@ -556,7 +558,7 @@ class Playfield:              pending = {}              for keysym, event in keyevents:                  pending[keysym] = event -            for keysym, event in pending.items(): +            for keysym, event in list(pending.items()):                  code = self.keycodes.get((keysym, event))                  if code and self.playing.get(code[0]) == 'l':                      if (code == self.last_key_event[0] and @@ -588,7 +590,7 @@ class Playfield:          self.taskbartimeout = None          if self.taskbarfree:              self.taskbarmode = (nmode or -                                'l' not in self.playing.values() or +                                'l' not in list(self.playing.values()) or                                  (self.keydefinition is not None))              if nmode:                  self.taskbartimeout = time.time() + 5.0 @@ -597,26 +599,26 @@ class Playfield:      def define_key(self, keysym):          clic_id, df = self.keydefinition -        if keysym in df.values(): +        if keysym in list(df.values()):              return          df[self.nextkeyname()] = keysym          if self.nextkeyname() is not None:              return          self.keydefinition = None          self.s.sendall(message(CMSG_ADD_PLAYER, clic_id)) -        for keyname, (num, icons) in self.keys.items(): +        for keyname, (num, icons) in list(self.keys.items()):              if keyname[:1] == '-':                  event = KeyReleased                  keyname = keyname[1:]              else:                  event = KeyPressed -            if df.has_key(keyname): +            if keyname in df:                  keysym = df[keyname]                  self.keycodes[keysym, event] = \                                        clic_id, message(CMSG_KEY, clic_id, num)      def msg_unknown(self, *rest): -        print >> sys.stderr, "?" +        print("?", file=sys.stderr)      def msg_player_join(self, id, local, *rest):          if local: @@ -628,7 +630,7 @@ class Playfield:      def msg_player_kill(self, id, *rest):          self.playing[id] = 0 -        for key, (pid, msg) in self.keycodes.items(): +        for key, (pid, msg) in list(self.keycodes.items()):              if pid == id:                  del self.keycodes[key] @@ -651,8 +653,8 @@ class Playfield:              self.udpsock2 = socket(AF_INET, SOCK_DGRAM)              self.udpsock2.bind(('', port))              self.udpsock2.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) -        except error, e: -            print "Cannot listen on the broadcast port %d" % port, str(e) +        except error as e: +            print("Cannot listen on the broadcast port %d" % port, str(e))              self.udpsock2 = None          else:              self.iwtd.append(self.udpsock2) @@ -664,7 +666,7 @@ class Playfield:          #    self.snd.close()          if self.dpy is not None:              # clear all pixmaps -            for ico in self.icons.values(): +            for ico in list(self.icons.values()):                  ico.clear()              self.pixmaps.clear()              self.dpy.close() @@ -726,7 +728,7 @@ class Playfield:              f.when_ready(ready)      def msg_patch_file(self, fileid, position, data, lendata=None, *rest): -        if self.fileids.has_key(fileid): +        if fileid in self.fileids:              f = self.fileids[fileid]          else:              f = self.fileids[fileid] = DataChunk(fileid) @@ -737,7 +739,7 @@ class Playfield:          self.msg_patch_file(fileid, position, data1, len(data), *rest)      def msg_md5_file(self, fileid, filename, position, length, checksum, *rest): -        if self.fileids.has_key(fileid): +        if fileid in self.fileids:              f = self.fileids[fileid]          else:              f = self.fileids[fileid] = DataChunk(fileid) @@ -777,13 +779,13 @@ class Playfield:                          f.close()                          d = eval(data or '{}', {}, {})                      except: -                        print >> sys.stderr, 'Invalid config file format' +                        print('Invalid config file format', file=sys.stderr)                      else:                          d = d.get(gethostname(), {})                          namemsg = '' -                        for id, local in self.playing.items(): +                        for id, local in list(self.playing.items()):                              keyid = 'player%d' % id -                            if local == 'l' and d.has_key(keyid): +                            if local == 'l' and keyid in d:                                  namemsg = namemsg + message(                                      CMSG_PLAYER_NAME, id, d[keyid])                          if namemsg: @@ -803,9 +805,9 @@ class Playfield:                  self.udpsock_low += 1                  if self.udpsock_low >= 3 and self.initlevel >= 1:                      # third time now -- that's too much -                    print "Note: routing UDP traffic over TCP", +                    print("Note: routing UDP traffic over TCP", end=' ')                      inp = self.udpbytecounter / (udpkbytes*1024.0) -                    print "(%d%% packet loss)" % int(100*(1.0-inp)) +                    print("(%d%% packet loss)" % int(100*(1.0-inp)))                      self.start_udp_over_tcp()                      self.s.sendall(message(CMSG_UDP_PORT, MSG_INLINE_FRAME))              else: diff --git a/display/playback.py b/display/playback.py index f0e698b..cbdb2ec 100644 --- a/display/playback.py +++ b/display/playback.py @@ -3,13 +3,13 @@  import sys, os, gzip  from socket import *  from select import select -import cStringIO, struct, zlib +import io, struct, zlib  import time  sys.path.insert(0, os.pardir)  from common.msgstruct import *  from common import hostchooser -import modes -from modes import KeyPressed, KeyReleased +from . import modes +from .modes import KeyPressed, KeyReleased  #import psyco; psyco.full() @@ -17,7 +17,7 @@ SOURCEDIR = os.pardir  def loadpixmap(dpy, data, colorkey=None): -    f = cStringIO.StringIO(data) +    f = io.StringIO(data)      sig = f.readline().strip()      assert sig == "P6"      while 1: @@ -25,7 +25,7 @@ def loadpixmap(dpy, data, colorkey=None):          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() @@ -38,7 +38,8 @@ def loadpixmap(dpy, data, colorkey=None):      return dpy.pixmap(w, h, data, colorkey)  class Icon: -    def __init__(self, bitmap, (x, y, w, h), alpha): +    def __init__(self, bitmap, xxx_todo_changeme, alpha): +        (x, y, w, h) = xxx_todo_changeme          self.rect = x, y, w, h          self.size = w, h          self.bitmap = bitmap @@ -70,7 +71,7 @@ class Playback:                  #print values[0],                  fn = Playback.MESSAGES.get(values[0], self.msg_unknown)                  fn(self, *values[1:]) -        print '%d frames in file.' % len(self.frames) +        print('%d frames in file.' % len(self.frames))          f.close()          assert self.width, "no playfield definition found in file" @@ -83,13 +84,13 @@ class Playback:      def buildicons(self):          bitmaps = {} -        for bmpcode, (data, colorkey) in self.defbitmaps.items(): +        for bmpcode, (data, colorkey) in list(self.defbitmaps.items()):              if isinstance(data, str):                  data = zlib.decompress(data)              else:                  data = self.deffiles[data]              bitmaps[bmpcode] = loadpixmap(self.dpy, data, colorkey) -        for icocode, (bmpcode, rect, alpha) in self.deficons.items(): +        for icocode, (bmpcode, rect, alpha) in list(self.deficons.items()):              self.icons[icocode] = Icon(bitmaps[bmpcode], rect, alpha)      def go(self, n): @@ -101,9 +102,9 @@ class Playback:          "shm only!"          w, h, data, reserved = self.dpy.getppm((0, 0, self.width, self.height))          f = open(filename or ('frame%d.ppm' % self.n), 'wb') -        print >> f, 'P6' -        print >> f, w, h -        print >> f, 255 +        print('P6', file=f) +        print(w, h, file=f) +        print(255, file=f)          for i in range(0, len(data), 4):              f.write(data[i+2]+data[i+1]+data[i])          f.close() diff --git a/display/puremixer.py b/display/puremixer.py index d0b567a..52d56d4 100644 --- a/display/puremixer.py +++ b/display/puremixer.py @@ -64,7 +64,7 @@ class PureMixer:              byteorder = self.byteorder          # done          if (freq, bytes, signed, channels, byteorder) != self.parameters: -            raise ValueError, 'sound sample conversion failed' +            raise ValueError('sound sample conversion failed')          return data      def wavesample(self, file): @@ -87,7 +87,7 @@ class PureMixer:          channels = mixer_channels[:]          channels.reverse()          for c in channels: -            if already_seen.has_key(c): +            if c in already_seen:                  data1 = ''              else:                  data1 = c.read(bufsize) @@ -114,10 +114,10 @@ def byteswap(data, byte):      elif byte == 4:          typecode = 'i'      else: -        raise ValueError, 'cannot convert endianness for samples of %d bytes' % byte +        raise ValueError('cannot convert endianness for samples of %d bytes' % byte)      import array      a = array.array(typecode, data)      if a.itemsize != byte: -        raise ValueError, 'endianness convertion failed' +        raise ValueError('endianness convertion failed')      a.byteswap()      return a.tostring() diff --git a/display/pythonxlibintf.py b/display/pythonxlibintf.py index 5e32715..04d85bb 100644 --- a/display/pythonxlibintf.py +++ b/display/pythonxlibintf.py @@ -51,7 +51,7 @@ class Display:                                       0x010101)      def pixmap(self, w, h, data, colorkey=-1): -        print >> sys.stderr, '.', +        print('.', end=' ', file=sys.stderr)          extent = w*h          depth = self.depth          if depth >= 24: @@ -72,7 +72,7 @@ class Display:          elif depth == 24 or depth == 32:              p_size = 8, 8, 8          else: -            raise ValueError, 'unsupported screen depth %d' % depth +            raise ValueError('unsupported screen depth %d' % depth)          imgdata = []          maskdata = [] @@ -82,9 +82,9 @@ class Display:              while plane >= (1<<(8-p_size[color])):                  src = 0                  for y in range(h): -                    imgline = 0L -                    maskline = 0L -                    shifter = 1L +                    imgline = 0 +                    maskline = 0 +                    shifter = 1                      for x in range(w):                          if data[src:src+3] == key:                              # transparent @@ -111,7 +111,8 @@ class Display:          image.size = w, h          return image -    def getppm(self, (x, y, w, h), bkgnd=None): +    def getppm(self, xxx_todo_changeme, bkgnd=None): +        (x, y, w, h) = xxx_todo_changeme          if bkgnd is None:              bkgnd = self.win.create_pixmap(w, h, self.depth)              bkgnd.mask = None @@ -191,7 +192,8 @@ class Display:          from socket import fromfd, AF_INET, SOCK_STREAM          return [fromfd(self.dpy.fileno(), AF_INET, SOCK_STREAM)] -    def taskbar(self, (x, y, w, h)): +    def taskbar(self, xxx_todo_changeme1): +        (x, y, w, h) = xxx_todo_changeme1          for j in range(y, y+h, 32):              for i in range(x, x+w, 32):                  self.putppm(i, j, self.taskbkgnd, diff --git a/display/snd_linux.py b/display/snd_linux.py index dae82e0..fd82619 100644 --- a/display/snd_linux.py +++ b/display/snd_linux.py @@ -1,7 +1,7 @@  import sys -from cStringIO import StringIO -import puremixer -from music1 import Music +from io import StringIO +from . import puremixer +from .music1 import Music  class Sound: @@ -30,10 +30,10 @@ class Sound:              if name == self.format:                  break          else: -            print >> sys.stderr, 'available sound formats:' +            print('available sound formats:', file=sys.stderr)              for name, bits, signed, byteorder in self.Formats: -                print >> sys.stderr, '  %-8s  %s' % (name, nicefmttext( -                    bits, signed, byteorder)) +                print('  %-8s  %s' % (name, nicefmttext( +                    bits, signed, byteorder)), file=sys.stderr)              sys.exit(2)          import linuxaudiodev @@ -41,9 +41,9 @@ class Sound:              f = linuxaudiodev.open('w')              f.setparameters(self.freq, p['bits'], 1,                              getattr(linuxaudiodev, 'AFMT_' + self.format)) -        except Exception, e: -            print >> sys.stderr, "sound disabled: %s: %s" % ( -                e.__class__.__name__, e) +        except Exception as e: +            print("sound disabled: %s: %s" % ( +                e.__class__.__name__, e), file=sys.stderr)              return          self.f = f          self.mixer = mixer = puremixer.PureMixer(**p) @@ -136,7 +136,7 @@ def nicefmttext(bits, signed, byteorder):      return s  def htmloptionstext(nameval): -    import modes +    from . import modes      l = ['<font size=-1>Sampling <%s>' % nameval('select', 'fmt')]      for name, bits, signed, byteorder in Sound.Formats:          l.append('<'+nameval('option', 'fmt', name, default='S16_NE')+'>'+ diff --git a/display/snd_pygame.py b/display/snd_pygame.py index e1a1455..3193775 100644 --- a/display/snd_pygame.py +++ b/display/snd_pygame.py @@ -1,5 +1,5 @@  import sys -from modes import musichtmloptiontext as htmloptionstext +from .modes import musichtmloptiontext as htmloptionstext  from pygame.locals import *  import pygame.mixer @@ -16,8 +16,8 @@ class Sound:      def __init__(self):          try:              pygame.mixer.init() -        except pygame.error, e: -            print >> sys.stderr, "sound disabled: %s" % str(e) +        except pygame.error as e: +            print("sound disabled: %s" % str(e), file=sys.stderr)          else:              self.has_sound = 1              try: diff --git a/display/snd_windows.py b/display/snd_windows.py index 3aea3bd..73d575c 100644 --- a/display/snd_windows.py +++ b/display/snd_windows.py @@ -1,8 +1,8 @@  import sys -from cStringIO import StringIO -import puremixer +from io import StringIO +from . import puremixer  import wingame -from music1 import Music +from .music1 import Music  class Sound: @@ -19,9 +19,9 @@ class Sound:          try:              self.audio = wingame.Audio(1, self.freq, self.bits, self.bufsize) -        except Exception, e: -            print >> sys.stderr, "sound disabled: %s: %s" % ( -                e.__class__.__name__, e) +        except Exception as e: +            print("sound disabled: %s: %s" % ( +                e.__class__.__name__, e), file=sys.stderr)              return          self.mixer = puremixer.PureMixer(self.freq, self.bits, self.bits==16,                                           byteorder='little') @@ -81,7 +81,7 @@ class Sound:  def htmloptionstext(nameval): -    import modes +    from . import modes      l = ['<font size=-1>Sampling <%s>' % nameval('select', 'bits')]      for bits in (8, 16):          l.append('<'+nameval('option', 'bits', str(bits), default='16')+'>'+  | 
