diff options
author | Diego Roversi <diegor@tiscali.it> | 2019-09-08 22:05:57 +0200 |
---|---|---|
committer | Diego Roversi <diegor@tiscali.it> | 2019-09-08 22:05:57 +0200 |
commit | c23b138ed72d794521b19ff7d8076b32b0b7bf46 (patch) | |
tree | c8e82a4ca4da05ba1ad28d4ff64a157bc1eb7952 /common | |
parent | 1d9925c287b318ec21343e2682b51ab6a36ae8db (diff) |
2to3
Diffstat (limited to 'common')
-rw-r--r-- | common/gamesrv.py | 132 | ||||
-rw-r--r-- | common/hostchooser.py | 59 | ||||
-rw-r--r-- | common/javaserver.py | 12 | ||||
-rw-r--r-- | common/msgstruct.py | 60 | ||||
-rw-r--r-- | common/pixmap.py | 18 | ||||
-rw-r--r-- | common/stdlog.py | 6 | ||||
-rw-r--r-- | common/udpovertcp.py | 10 |
7 files changed, 150 insertions, 147 deletions
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 |