otp: initial work on python 3.x support

This commit is contained in:
John Cote 2019-12-30 01:00:16 -05:00
parent a47d4ccd0e
commit cd932aa66e
110 changed files with 483 additions and 481 deletions

View file

@ -1,4 +1,4 @@
from AIBase import * from .AIBase import *
__builtins__['simbase'] = AIBase() __builtins__['simbase'] = AIBase()
__builtins__['ostream'] = Notify.out() __builtins__['ostream'] = Notify.out()
__builtins__['run'] = simbase.run __builtins__['run'] = simbase.run

View file

@ -73,10 +73,10 @@ AIMsgName2Id = {'STATESERVER_OBJECT_GENERATE_WITH_REQUIRED': 2001,
'SERVER_PING': 5002} 'SERVER_PING': 5002}
AIMsgId2Names = invertDictLossless(AIMsgName2Id) AIMsgId2Names = invertDictLossless(AIMsgName2Id)
if not isClient(): if not isClient():
print 'EXECWARNING AIMsgTypes: %s' % AIMsgName2Id print('EXECWARNING AIMsgTypes: %s' % AIMsgName2Id)
printStack() printStack()
for name, value in AIMsgName2Id.items(): for name, value in list(AIMsgName2Id.items()):
exec '%s = %s' % (name, value) exec('%s = %s' % (name, value))
del name del name
del value del value

View file

@ -42,7 +42,7 @@ class AIZoneDataObj:
output += '\n' output += '\n'
totalColliders = 0 totalColliders = 0
totalTraversers = 0 totalTraversers = 0
for currCollTrav in self._collTravs.values(): for currCollTrav in list(self._collTravs.values()):
totalTraversers += 1 totalTraversers += 1
totalColliders += currCollTrav.getNumColliders() totalColliders += currCollTrav.getNumColliders()
@ -117,7 +117,7 @@ class AIZoneDataObj:
return self._collTravs[name] return self._collTravs[name]
def removeCollTrav(self, name): def removeCollTrav(self, name):
if self._collTravs.has_key(name): if name in self._collTravs:
del self._collTravs[name] del self._collTravs[name]
def _getCTravTaskName(self, name = None): def _getCTravTaskName(self, name = None):
@ -185,7 +185,7 @@ class AIZoneDataStore:
self._zone2data = {} self._zone2data = {}
def destroy(self): def destroy(self):
for zone, data in self._zone2data.items(): for zone, data in list(self._zone2data.items()):
data.destroy() data.destroy()
del self._zone2data del self._zone2data

View file

@ -1,4 +1,4 @@
import urllib import urllib.request, urllib.parse, urllib.error
import os import os
from pandac.PandaModules import HTTPClient, Ramfile from pandac.PandaModules import HTTPClient, Ramfile
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
@ -23,7 +23,7 @@ class BanManagerAI:
parameters += '&event_name=%s' % self.EventName parameters += '&event_name=%s' % self.EventName
commentWithAvatarId = 'avId-%s ' % avatarId commentWithAvatarId = 'avId-%s ' % avatarId
commentWithAvatarId += comment commentWithAvatarId += comment
parameters += '&comments=%s' % urllib.quote(str(commentWithAvatarId)) parameters += '&comments=%s' % urllib.parse.quote(str(commentWithAvatarId))
baseUrlToUse = self.BanUrl baseUrlToUse = self.BanUrl
osBaseUrl = os.getenv('BAN_URL') osBaseUrl = os.getenv('BAN_URL')
if osBaseUrl: if osBaseUrl:

View file

@ -33,7 +33,7 @@ class GarbageLeakServerEventAggregator(DirectObject):
return return
def _sendLeaks(self, task = None): def _sendLeaks(self, task = None):
for desc, curNum in self._curLeakDesc2num.iteritems(): for desc, curNum in self._curLeakDesc2num.items():
self._sentLeakDesc2num.setdefault(desc, 0) self._sentLeakDesc2num.setdefault(desc, 0)
num = curNum - self._sentLeakDesc2num[desc] num = curNum - self._sentLeakDesc2num[desc]
if num > 0: if num > 0:

View file

@ -62,7 +62,7 @@ class MagicWordManager(DistributedObject.DistributedObject):
def doMagicWord(self, word, avId, zoneId): def doMagicWord(self, word, avId, zoneId):
wordIs = self.getWordIs(word) wordIs = self.getWordIs(word)
print word print(word)
if wordIs('~oobe'): if wordIs('~oobe'):
base.oobe() base.oobe()
elif wordIs('~oobeCull'): elif wordIs('~oobeCull'):
@ -141,7 +141,7 @@ class MagicWordManager(DistributedObject.DistributedObject):
self.forAnother(word, avId, zoneId) self.forAnother(word, avId, zoneId)
elif wordIs('~badname'): elif wordIs('~badname'):
word = '~for %s ~badname' % word[9:] word = '~for %s ~badname' % word[9:]
print 'word is %s' % word print('word is %s' % word)
self.forAnother(word, avId, zoneId) self.forAnother(word, avId, zoneId)
elif wordIs('~avId'): elif wordIs('~avId'):
self.setMagicWordResponse(str(localAvatar.doId)) self.setMagicWordResponse(str(localAvatar.doId))
@ -342,11 +342,11 @@ class MagicWordManager(DistributedObject.DistributedObject):
type2count[tn] += 1 type2count[tn] += 1
count2type = invertDictLossless(type2count) count2type = invertDictLossless(type2count)
counts = count2type.keys() counts = list(count2type.keys())
counts.sort() counts.sort()
counts.reverse() counts.reverse()
for count in counts: for count in counts:
print '%s: %s' % (count, count2type[count]) print('%s: %s' % (count, count2type[count]))
self.setMagicWordResponse('~aiobjecthg complete') self.setMagicWordResponse('~aiobjecthg complete')
elif wordIs('~containers'): elif wordIs('~containers'):
@ -455,10 +455,10 @@ class MagicWordManager(DistributedObject.DistributedObject):
base.cr.printObjectCount() base.cr.printObjectCount()
self.setMagicWordResponse('logging client distributed object count...') self.setMagicWordResponse('logging client distributed object count...')
elif wordIs('~taskmgr'): elif wordIs('~taskmgr'):
print taskMgr print(taskMgr)
self.setMagicWordResponse('logging client taskMgr...') self.setMagicWordResponse('logging client taskMgr...')
elif wordIs('~jobmgr'): elif wordIs('~jobmgr'):
print jobMgr print(jobMgr)
self.setMagicWordResponse('logging client jobMgr...') self.setMagicWordResponse('logging client jobMgr...')
elif wordIs('~jobtime'): elif wordIs('~jobtime'):
args = word.split() args = word.split()
@ -493,7 +493,7 @@ class MagicWordManager(DistributedObject.DistributedObject):
taskMgr.setTaskDurationWarningThreshold(threshold) taskMgr.setTaskDurationWarningThreshold(threshold)
self.setMagicWordResponse(response) self.setMagicWordResponse(response)
elif wordIs('~messenger'): elif wordIs('~messenger'):
print messenger print(messenger)
self.setMagicWordResponse('logging client messenger...') self.setMagicWordResponse('logging client messenger...')
elif wordIs('~clientcrash'): elif wordIs('~clientcrash'):
DelayedCall(Functor(self.notify.error, '~clientcrash: simulating a client crash')) DelayedCall(Functor(self.notify.error, '~clientcrash: simulating a client crash'))
@ -529,13 +529,13 @@ class MagicWordManager(DistributedObject.DistributedObject):
name = 'default' name = 'default'
p = Point3() p = Point3()
ts = time.time() ts = time.time()
for i in xrange(1000000): for i in range(1000000):
p.set(1, 2, 3) p.set(1, 2, 3)
tf = time.time() tf = time.time()
dt = tf - ts dt = tf - ts
response = 'prof(%s): %s secs' % (name, dt) response = 'prof(%s): %s secs' % (name, dt)
print response print(response)
self.setMagicWordResponse(response) self.setMagicWordResponse(response)
elif wordIs('~gptc'): elif wordIs('~gptc'):
args = word.split() args = word.split()
@ -632,7 +632,7 @@ class MagicWordManager(DistributedObject.DistributedObject):
def identifyDistributedObjects(self, name): def identifyDistributedObjects(self, name):
result = [] result = []
lowerName = string.lower(name) lowerName = string.lower(name)
for obj in self.cr.doId2do.values(): for obj in list(self.cr.doId2do.values()):
className = obj.__class__.__name__ className = obj.__class__.__name__
try: try:
name = obj.getName() name = obj.getName()
@ -697,7 +697,7 @@ class MagicWordManager(DistributedObject.DistributedObject):
else: else:
try: try:
bitmask |= BitMask32.bit(int(w)) bitmask |= BitMask32.bit(int(w))
print bitmask print(bitmask)
except ValueError: except ValueError:
invalid += ' ' + w invalid += ' ' + w
@ -871,5 +871,5 @@ def magicWord(mw):
messenger.send('magicWord', [mw]) messenger.send('magicWord', [mw])
import __builtin__ import builtins
__builtin__.magicWord = magicWord builtins.magicWord = magicWord

View file

@ -198,7 +198,7 @@ class TimeManager(DistributedObject.DistributedObject):
di.getCpuBrandIndex(), di.getCpuBrandIndex(),
'%0.03f,%0.03f' % cpuSpeed, '%0.03f,%0.03f' % cpuSpeed,
'%d,%d' % (numCpuCores, numLogicalCpus)) '%d,%d' % (numCpuCores, numLogicalCpus))
print 'cpu info: %s' % info print('cpu info: %s' % info)
self.sendUpdate('setCpuInfo', [info, cacheStatus]) self.sendUpdate('setCpuInfo', [info, cacheStatus])
def setFrameRateInterval(self, frameRateInterval): def setFrameRateInterval(self, frameRateInterval):
@ -270,7 +270,7 @@ class TimeManager(DistributedObject.DistributedObject):
'%0.03f,%0.03f' % cpuSpeed, '%0.03f,%0.03f' % cpuSpeed,
'%d,%d' % (numCpuCores, numLogicalCpus), '%d,%d' % (numCpuCores, numLogicalCpus),
apiName) apiName)
print 'frame rate: %s' % info print('frame rate: %s' % info)
self.sendUpdate('setFrameRate', [fps, self.sendUpdate('setFrameRate', [fps,
deviation, deviation,
numAvs, numAvs,
@ -335,7 +335,7 @@ class TimeManager(DistributedObject.DistributedObject):
bugfix, bugfix,
major, major,
minor) minor)
except Exception, e: except Exception as e:
self.notify.debug('getMacOsInfo %s' % str(e)) self.notify.debug('getMacOsInfo %s' % str(e))
self.notify.debug('getMacOsInfo returning %s' % str(result)) self.notify.debug('getMacOsInfo returning %s' % str(result))

View file

@ -1,7 +1,7 @@
from pandac.PandaModules import * from pandac.PandaModules import *
from direct.gui.DirectGui import * from direct.gui.DirectGui import *
from direct.showbase import DirectObject from direct.showbase import DirectObject
import Avatar from . import Avatar
from direct.distributed import DistributedObject from direct.distributed import DistributedObject
class AvatarPanel(DirectObject.DirectObject): class AvatarPanel(DirectObject.DirectObject):
@ -27,7 +27,7 @@ class AvatarPanel(DirectObject.DirectObject):
self.avDisableName = avatar.uniqueName('disable') self.avDisableName = avatar.uniqueName('disable')
self.avGenerateName = avatar.uniqueName('generate') self.avGenerateName = avatar.uniqueName('generate')
self.avHpChangeName = avatar.uniqueName('hpChange') self.avHpChangeName = avatar.uniqueName('hpChange')
if base.cr.doId2do.has_key(self.avId): if self.avId in base.cr.doId2do:
self.avatar = base.cr.doId2do[self.avId] self.avatar = base.cr.doId2do[self.avId]
else: else:
self.avDisableName = None self.avDisableName = None

View file

@ -13,8 +13,8 @@ from otp.speedchat import SCDecoders
from otp.chat import ChatGarbler from otp.chat import ChatGarbler
from otp.chat import ChatManager from otp.chat import ChatManager
import random import random
from Avatar import Avatar from .Avatar import Avatar
import AvatarDNA from . import AvatarDNA
class DistributedAvatar(DistributedActor, Avatar): class DistributedAvatar(DistributedActor, Avatar):
HpTextGenerator = TextNode('HpTextGenerator') HpTextGenerator = TextNode('HpTextGenerator')

View file

@ -133,10 +133,10 @@ class DistributedPlayer(DistributedAvatar.DistributedAvatar, PlayerBase.PlayerBa
self.displayWhisper(aboutId, chatString, whisperType) self.displayWhisper(aboutId, chatString, whisperType)
def displayWhisper(self, fromId, chatString, whisperType): def displayWhisper(self, fromId, chatString, whisperType):
print 'Whisper type %s from %s: %s' % (whisperType, fromId, chatString) print('Whisper type %s from %s: %s' % (whisperType, fromId, chatString))
def displayWhisperPlayer(self, playerId, chatString, whisperType): def displayWhisperPlayer(self, playerId, chatString, whisperType):
print 'WhisperPlayer type %s from %s: %s' % (whisperType, playerId, chatString) print('WhisperPlayer type %s from %s: %s' % (whisperType, playerId, chatString))
def whisperSCTo(self, msgIndex, sendToId, toPlayer): def whisperSCTo(self, msgIndex, sendToId, toPlayer):
if toPlayer: if toPlayer:
@ -191,7 +191,7 @@ class DistributedPlayer(DistributedAvatar.DistributedAvatar, PlayerBase.PlayerBa
return return
def whisperSCEmoteTo(self, emoteId, sendToId, toPlayer): def whisperSCEmoteTo(self, emoteId, sendToId, toPlayer):
print 'whisperSCEmoteTo %s %s %s' % (emoteId, sendToId, toPlayer) print('whisperSCEmoteTo %s %s %s' % (emoteId, sendToId, toPlayer))
if toPlayer: if toPlayer:
base.cr.playerFriendsManager.sendSCEmoteWhisper(sendToId, emoteId) base.cr.playerFriendsManager.sendSCEmoteWhisper(sendToId, emoteId)
return return
@ -253,7 +253,7 @@ class DistributedPlayer(DistributedAvatar.DistributedAvatar, PlayerBase.PlayerBa
return return
def displayTalkWhisper(self, fromId, avatarName, chatString, mods): def displayTalkWhisper(self, fromId, avatarName, chatString, mods):
print 'TalkWhisper from %s: %s' % (fromId, chatString) print('TalkWhisper from %s: %s' % (fromId, chatString))
def scrubTalk(self, chat, mods): def scrubTalk(self, chat, mods):
return chat return chat

View file

@ -10,7 +10,7 @@ class Emote:
return return
def isEnabled(self, index): def isEnabled(self, index):
if isinstance(index, types.StringType): if isinstance(index, bytes):
index = OTPLocalizer.EmoteFuncDict[index] index = OTPLocalizer.EmoteFuncDict[index]
if self.emoteFunc == None: if self.emoteFunc == None:
return 0 return 0

View file

@ -5,11 +5,11 @@ from direct.showbase.PythonUtil import *
from direct.interval.IntervalGlobal import * from direct.interval.IntervalGlobal import *
from direct.showbase.InputStateGlobal import inputState from direct.showbase.InputStateGlobal import inputState
from pandac.PandaModules import * from pandac.PandaModules import *
import Avatar from . import Avatar
from direct.controls import ControlManager from direct.controls import ControlManager
import DistributedAvatar from . import DistributedAvatar
from direct.task import Task from direct.task import Task
import PositionExaminer from . import PositionExaminer
from otp.otpbase import OTPGlobals from otp.otpbase import OTPGlobals
from otp.otpbase import OTPRender from otp.otpbase import OTPRender
import math import math
@ -572,21 +572,21 @@ class LocalAvatar(DistributedAvatar.DistributedAvatar, DistributedSmoothNode.Dis
self.nextCameraPos(1) self.nextCameraPos(1)
def printCameraPositions(self): def printCameraPositions(self):
print '[' print('[')
for i in range(len(self.cameraPositions)): for i in range(len(self.cameraPositions)):
self.printCameraPosition(i) self.printCameraPosition(i)
print ',' print(',')
print ']' print(']')
def printCameraPosition(self, index): def printCameraPosition(self, index):
cp = self.cameraPositions[index] cp = self.cameraPositions[index]
print '(Point3(%0.2f, %0.2f, %0.2f),' % (cp[0][0], cp[0][1], cp[0][2]) print('(Point3(%0.2f, %0.2f, %0.2f),' % (cp[0][0], cp[0][1], cp[0][2]))
print 'Point3(%0.2f, %0.2f, %0.2f),' % (cp[1][0], cp[1][1], cp[1][2]) print('Point3(%0.2f, %0.2f, %0.2f),' % (cp[1][0], cp[1][1], cp[1][2]))
print 'Point3(%0.2f, %0.2f, %0.2f),' % (cp[2][0], cp[2][1], cp[2][2]) print('Point3(%0.2f, %0.2f, %0.2f),' % (cp[2][0], cp[2][1], cp[2][2]))
print 'Point3(%0.2f, %0.2f, %0.2f),' % (cp[3][0], cp[3][1], cp[3][2]) print('Point3(%0.2f, %0.2f, %0.2f),' % (cp[3][0], cp[3][1], cp[3][2]))
print '%d,' % cp[4] print('%d,' % cp[4])
print ')', print(')', end=' ')
def posCamera(self, lerp, time): def posCamera(self, lerp, time):
if not lerp: if not lerp:
@ -1137,7 +1137,7 @@ class LocalAvatar(DistributedAvatar.DistributedAvatar, DistributedSmoothNode.Dis
node = base.camera.getParent() node = base.camera.getParent()
pos = base.cam.getPos(node) pos = base.cam.getPos(node)
hpr = base.cam.getHpr(node) hpr = base.cam.getHpr(node)
print 'cam pos = ', `pos`, ', cam hpr = ', `hpr` print('cam pos = ', repr(pos), ', cam hpr = ', repr(hpr))
def d_broadcastPositionNow(self): def d_broadcastPositionNow(self):
self.d_clearSmoothing() self.d_clearSmoothing()
@ -1208,7 +1208,7 @@ class LocalAvatar(DistributedAvatar.DistributedAvatar, DistributedSmoothNode.Dis
DistributedSmoothNode.DistributedSmoothNode.d_setParent(self, parentToken) DistributedSmoothNode.DistributedSmoothNode.d_setParent(self, parentToken)
def handlePlayerFriendWhisper(self, playerId, charMessage): def handlePlayerFriendWhisper(self, playerId, charMessage):
print 'handlePlayerFriendWhisper' print('handlePlayerFriendWhisper')
self.displayWhisperPlayer(playerId, charMessage, WhisperPopup.WTNormal) self.displayWhisperPlayer(playerId, charMessage, WhisperPopup.WTNormal)
def canChat(self): def canChat(self):

View file

@ -18,7 +18,7 @@ class SpeedMonitor:
taskMgr.remove(self._trackTask) taskMgr.remove(self._trackTask)
def _allocToken(self): def _allocToken(self):
return 'speedMonitorToken-%s-%s-%s' % (self._name, id(self), SpeedMonitor.SerialGen.next()) return 'speedMonitorToken-%s-%s-%s' % (self._name, id(self), next(SpeedMonitor.SerialGen))
def addNodepath(self, nodepath): def addNodepath(self, nodepath):
token = self._allocToken() token = self._allocToken()
@ -46,7 +46,7 @@ class SpeedMonitor:
(nodepath.getPos(), globalClock.getFrameTime() - SpeedMonitor.TrackingPeriod, 0.0)] (nodepath.getPos(), globalClock.getFrameTime() - SpeedMonitor.TrackingPeriod, 0.0)]
def _trackSpeedsTask(self, task = None): def _trackSpeedsTask(self, task = None):
for (token, nodepath) in self._nodepaths.iteritems(): for (token, nodepath) in self._nodepaths.items():
curT = globalClock.getFrameTime() curT = globalClock.getFrameTime()
curPos = nodepath.getPos() curPos = nodepath.getPos()
while len(self._prevPosQueue[token]) > 1: while len(self._prevPosQueue[token]) > 1:

View file

@ -100,19 +100,19 @@ class ChatInputNormal(DirectObject.DirectObject):
def __execMessage(self, message): def __execMessage(self, message):
if not ChatInputNormal.ExecNamespace: if not ChatInputNormal.ExecNamespace:
ChatInputNormal.ExecNamespace = {} ChatInputNormal.ExecNamespace = {}
exec 'from pandac.PandaModules import *' in globals(), self.ExecNamespace exec('from pandac.PandaModules import *', globals(), self.ExecNamespace)
self.importExecNamespace() self.importExecNamespace()
try: try:
if not isClient(): if not isClient():
print 'EXECWARNING ChatInputNormal eval: %s' % message print('EXECWARNING ChatInputNormal eval: %s' % message)
printStack() printStack()
return str(eval(message, globals(), ChatInputNormal.ExecNamespace)) return str(eval(message, globals(), ChatInputNormal.ExecNamespace))
except SyntaxError: except SyntaxError:
try: try:
if not isClient(): if not isClient():
print 'EXECWARNING ChatInputNormal exec: %s' % message print('EXECWARNING ChatInputNormal exec: %s' % message)
printStack() printStack()
exec message in globals(), ChatInputNormal.ExecNamespace exec(message, globals(), ChatInputNormal.ExecNamespace)
return 'ok' return 'ok'
except: except:
exception = sys.exc_info()[0] exception = sys.exc_info()[0]

View file

@ -82,7 +82,7 @@ class ChatInputTyped(DirectObject.DirectObject):
self.typedChatButton.hide() self.typedChatButton.hide()
self.typedChatBar.hide() self.typedChatBar.hide()
if self.whisperId: if self.whisperId:
print 'have id' print('have id')
if self.toPlayer: if self.toPlayer:
if not base.talkAssistant.checkWhisperTypedChatPlayer(self.whisperId): if not base.talkAssistant.checkWhisperTypedChatPlayer(self.whisperId):
messenger.send('Chat-Failed player typed chat test') messenger.send('Chat-Failed player typed chat test')
@ -127,19 +127,19 @@ class ChatInputTyped(DirectObject.DirectObject):
def __execMessage(self, message): def __execMessage(self, message):
if not ChatInputTyped.ExecNamespace: if not ChatInputTyped.ExecNamespace:
ChatInputTyped.ExecNamespace = {} ChatInputTyped.ExecNamespace = {}
exec 'from pandac.PandaModules import *' in globals(), self.ExecNamespace exec('from pandac.PandaModules import *', globals(), self.ExecNamespace)
self.importExecNamespace() self.importExecNamespace()
try: try:
if not isClient(): if not isClient():
print 'EXECWARNING ChatInputNormal eval: %s' % message print('EXECWARNING ChatInputNormal eval: %s' % message)
printStack() printStack()
return str(eval(message, globals(), ChatInputTyped.ExecNamespace)) return str(eval(message, globals(), ChatInputTyped.ExecNamespace))
except SyntaxError: except SyntaxError:
try: try:
if not isClient(): if not isClient():
print 'EXECWARNING ChatInputNormal exec: %s' % message print('EXECWARNING ChatInputNormal exec: %s' % message)
printStack() printStack()
exec message in globals(), ChatInputTyped.ExecNamespace exec(message, globals(), ChatInputTyped.ExecNamespace)
return 'ok' return 'ok'
except: except:
exception = sys.exc_info()[0] exception = sys.exc_info()[0]

View file

@ -285,19 +285,19 @@ class ChatInputWhiteListFrame(FSM.FSM, DirectFrame):
def __execMessage(self, message): def __execMessage(self, message):
if not ChatInputTyped.ExecNamespace: if not ChatInputTyped.ExecNamespace:
ChatInputTyped.ExecNamespace = {} ChatInputTyped.ExecNamespace = {}
exec 'from pandac.PandaModules import *' in globals(), self.ExecNamespace exec('from pandac.PandaModules import *', globals(), self.ExecNamespace)
self.importExecNamespace() self.importExecNamespace()
try: try:
if not isClient(): if not isClient():
print 'EXECWARNING ChatInputWhiteListFrame eval: %s' % message print('EXECWARNING ChatInputWhiteListFrame eval: %s' % message)
printStack() printStack()
return str(eval(message, globals(), ChatInputTyped.ExecNamespace)) return str(eval(message, globals(), ChatInputTyped.ExecNamespace))
except SyntaxError: except SyntaxError:
try: try:
if not isClient(): if not isClient():
print 'EXECWARNING ChatInputWhiteListFrame exec: %s' % message print('EXECWARNING ChatInputWhiteListFrame exec: %s' % message)
printStack() printStack()
exec message in globals(), ChatInputTyped.ExecNamespace exec(message, globals(), ChatInputTyped.ExecNamespace)
return 'ok' return 'ok'
except: except:
exception = sys.exc_info()[0] exception = sys.exc_info()[0]

View file

@ -272,7 +272,7 @@ class ChatManager(DirectObject.DirectObject):
playerName = None playerName = None
chatToToon = 1 chatToToon = 1
online = 0 online = 0
if self.cr.doId2do.has_key(avatarId): if avatarId in self.cr.doId2do:
online = 1 online = 1
elif self.cr.isFriend(avatarId): elif self.cr.isFriend(avatarId):
online = self.cr.isFriendOnline(avatarId) online = self.cr.isFriendOnline(avatarId)
@ -288,7 +288,7 @@ class ChatManager(DirectObject.DirectObject):
if av != None: if av != None:
avatarUnderstandable = av.isUnderstandable() avatarUnderstandable = av.isUnderstandable()
if playerId: if playerId:
if base.cr.playerFriendsManager.playerId2Info.has_key(playerId): if playerId in base.cr.playerFriendsManager.playerId2Info:
playerInfo = base.cr.playerFriendsManager.playerId2Info.get(playerId) playerInfo = base.cr.playerFriendsManager.playerId2Info.get(playerId)
playerName = playerInfo.playerName playerName = playerInfo.playerName
online = 1 online = 1

View file

@ -98,13 +98,13 @@ class TalkAssistant(DirectObject.DirectObject):
if message.getTalkType() == TALK_WHISPER and doId != localAvatar.doId: if message.getTalkType() == TALK_WHISPER and doId != localAvatar.doId:
self.lastWhisperDoId = doId self.lastWhisperDoId = doId
self.lastWhisper = self.lastWhisperDoId self.lastWhisper = self.lastWhisperDoId
if not self.historyByDoId.has_key(doId): if doId not in self.historyByDoId:
self.historyByDoId[doId] = [] self.historyByDoId[doId] = []
self.historyByDoId[doId].append(message) self.historyByDoId[doId].append(message)
if not self.shownWhiteListWarning and scrubbed and doId == localAvatar.doId: if not self.shownWhiteListWarning and scrubbed and doId == localAvatar.doId:
self.doWhiteListWarning() self.doWhiteListWarning()
self.shownWhiteListWarning = 1 self.shownWhiteListWarning = 1
if not self.floodDataByDoId.has_key(doId): if doId not in self.floodDataByDoId:
self.floodDataByDoId[doId] = [0.0, self.stampTime(), message] self.floodDataByDoId[doId] = [0.0, self.stampTime(), message]
else: else:
oldTime = self.floodDataByDoId[doId][1] oldTime = self.floodDataByDoId[doId][1]
@ -131,7 +131,7 @@ class TalkAssistant(DirectObject.DirectObject):
if message.getTalkType() == TALK_ACCOUNT and dISLId != base.cr.accountDetailRecord.playerAccountId: if message.getTalkType() == TALK_ACCOUNT and dISLId != base.cr.accountDetailRecord.playerAccountId:
self.lastWhisperPlayerId = dISLId self.lastWhisperPlayerId = dISLId
self.lastWhisper = self.lastWhisperPlayerId self.lastWhisper = self.lastWhisperPlayerId
if not self.historyByDISLId.has_key(dISLId): if dISLId not in self.historyByDISLId:
self.historyByDISLId[dISLId] = [] self.historyByDISLId[dISLId] = []
self.historyByDISLId[dISLId].append(message) self.historyByDISLId[dISLId].append(message)
@ -236,33 +236,33 @@ class TalkAssistant(DirectObject.DirectObject):
return return
def printHistoryComplete(self): def printHistoryComplete(self):
print 'HISTORY COMPLETE' print('HISTORY COMPLETE')
for message in self.historyComplete: for message in self.historyComplete:
print '%s %s %s\n%s\n' % (message.getTimeStamp(), print('%s %s %s\n%s\n' % (message.getTimeStamp(),
message.getSenderAvatarName(), message.getSenderAvatarName(),
message.getSenderAccountName(), message.getSenderAccountName(),
message.getBody()) message.getBody()))
def importExecNamespace(self): def importExecNamespace(self):
pass pass
def execMessage(self, message): def execMessage(self, message):
print 'execMessage %s' % message print('execMessage %s' % message)
if not TalkAssistant.ExecNamespace: if not TalkAssistant.ExecNamespace:
TalkAssistant.ExecNamespace = {} TalkAssistant.ExecNamespace = {}
exec 'from pandac.PandaModules import *' in globals(), self.ExecNamespace exec('from pandac.PandaModules import *', globals(), self.ExecNamespace)
self.importExecNamespace() self.importExecNamespace()
try: try:
if not isClient(): if not isClient():
print 'EXECWARNING TalkAssistant eval: %s' % message print('EXECWARNING TalkAssistant eval: %s' % message)
printStack() printStack()
return str(eval(message, globals(), TalkAssistant.ExecNamespace)) return str(eval(message, globals(), TalkAssistant.ExecNamespace))
except SyntaxError: except SyntaxError:
try: try:
if not isClient(): if not isClient():
print 'EXECWARNING TalkAssistant exec: %s' % message print('EXECWARNING TalkAssistant exec: %s' % message)
printStack() printStack()
exec message in globals(), TalkAssistant.ExecNamespace exec(message, globals(), TalkAssistant.ExecNamespace)
return 'ok' return 'ok'
except: except:
exception = sys.exc_info()[0] exception = sys.exc_info()[0]
@ -385,11 +385,11 @@ class TalkAssistant(DirectObject.DirectObject):
def receiveWhisperTalk(self, avatarId, avatarName, accountId, accountName, toId, toName, message, scrubbed = 0): def receiveWhisperTalk(self, avatarId, avatarName, accountId, accountName, toId, toName, message, scrubbed = 0):
error = None error = None
print 'receiveWhisperTalk %s %s %s %s %s' % (avatarId, print('receiveWhisperTalk %s %s %s %s %s' % (avatarId,
avatarName, avatarName,
accountId, accountId,
accountName, accountName,
message) message))
if not avatarName and avatarId: if not avatarName and avatarId:
avatarName = self.findAvatarName(avatarId) avatarName = self.findAvatarName(avatarId)
if not accountName and accountId: if not accountName and accountId:
@ -670,7 +670,7 @@ class TalkAssistant(DirectObject.DirectObject):
if self.checkGuildTypedChat(): if self.checkGuildTypedChat():
base.cr.guildManager.sendTalk(message) base.cr.guildManager.sendTalk(message)
else: else:
print 'Guild chat error' print('Guild chat error')
error = ERROR_NO_GUILD_CHAT error = ERROR_NO_GUILD_CHAT
return error return error
@ -740,7 +740,7 @@ class TalkAssistant(DirectObject.DirectObject):
if self.checkGuildSpeedChat(): if self.checkGuildSpeedChat():
base.cr.guildManager.sendSC(msgIndex) base.cr.guildManager.sendSC(msgIndex)
else: else:
print 'Guild Speedchat error' print('Guild Speedchat error')
error = ERROR_NO_GUILD_CHAT error = ERROR_NO_GUILD_CHAT
return error return error

View file

@ -10,7 +10,7 @@ class CentralLogger(DistributedObjectGlobal):
PlayersReportedThisSession = {} PlayersReportedThisSession = {}
def hasReportedPlayer(self, targetDISLId, targetAvId): def hasReportedPlayer(self, targetDISLId, targetAvId):
return self.PlayersReportedThisSession.has_key((targetDISLId, targetAvId)) return (targetDISLId, targetAvId) in self.PlayersReportedThisSession
def reportPlayer(self, category, targetDISLId, targetAvId, description = 'None'): def reportPlayer(self, category, targetDISLId, targetAvId, description = 'None'):
if self.hasReportedPlayer(targetDISLId, targetAvId): if self.hasReportedPlayer(targetDISLId, targetAvId):

View file

@ -34,7 +34,7 @@ class ClsendTracker:
self._trimClsend() self._trimClsend()
def _trimClsend(self): def _trimClsend(self):
for i in xrange(self._clsendFlushNum): for i in range(self._clsendFlushNum):
if self._logClsendOverflow: if self._logClsendOverflow:
self._logClsend(*self._clsendMsgs[0]) self._logClsend(*self._clsendMsgs[0])
self._clsendMsgs = self._clsendMsgs[1:] self._clsendMsgs = self._clsendMsgs[1:]

View file

@ -20,7 +20,7 @@ class DistributedDistrict(DistributedObject):
def delete(self): def delete(self):
if base.cr.distributedDistrict is self: if base.cr.distributedDistrict is self:
base.cr.distributedDistrict = None base.cr.distributedDistrict = None
if self.cr.activeDistrictMap.has_key(self.doId): if self.doId in self.cr.activeDistrictMap:
del self.cr.activeDistrictMap[self.doId] del self.cr.activeDistrictMap[self.doId]
DistributedObject.delete(self) DistributedObject.delete(self)
messenger.send('shardInfoUpdated') messenger.send('shardInfoUpdated')

View file

@ -46,7 +46,7 @@ from otp.uberdog import OtpAvatarManager
from otp.distributed import OtpDoGlobals from otp.distributed import OtpDoGlobals
from otp.distributed.TelemetryLimiter import TelemetryLimiter from otp.distributed.TelemetryLimiter import TelemetryLimiter
from otp.ai.GarbageLeakServerEventAggregator import GarbageLeakServerEventAggregator from otp.ai.GarbageLeakServerEventAggregator import GarbageLeakServerEventAggregator
from PotentialAvatar import PotentialAvatar from .PotentialAvatar import PotentialAvatar
class OTPClientRepository(ClientRepositoryBase): class OTPClientRepository(ClientRepositoryBase):
notify = directNotify.newCategory('OTPClientRepository') notify = directNotify.newCategory('OTPClientRepository')
@ -141,7 +141,7 @@ class OTPClientRepository(ClientRepositoryBase):
self.DISLToken += ('&WL_CHAT_ENABLED=%s' % config.GetString('fake-DISL-WLChatEnabled', 'YES') + self.DISLToken += ('&WL_CHAT_ENABLED=%s' % config.GetString('fake-DISL-WLChatEnabled', 'YES') +
'&valid=true') '&valid=true')
if base.logPrivateInfo: if base.logPrivateInfo:
print self.DISLToken print(self.DISLToken)
self.requiredLogin = config.GetString('required-login', 'auto') self.requiredLogin = config.GetString('required-login', 'auto')
if self.requiredLogin == 'auto': if self.requiredLogin == 'auto':
@ -518,7 +518,7 @@ class OTPClientRepository(ClientRepositoryBase):
def gotoFirstScreen(self): def gotoFirstScreen(self):
try: try:
self.accountServerConstants = AccountServerConstants.AccountServerConstants(self) self.accountServerConstants = AccountServerConstants.AccountServerConstants(self)
except TTAccount.TTAccountException, e: except TTAccount.TTAccountException as e:
self.notify.debug(str(e)) self.notify.debug(str(e))
self.loginFSM.request('failedToGetServerConstants', [e]) self.loginFSM.request('failedToGetServerConstants', [e])
return return
@ -781,7 +781,7 @@ class OTPClientRepository(ClientRepositoryBase):
@report(types=['args', 'deltaStamp'], dConfigParam='teleport') @report(types=['args', 'deltaStamp'], dConfigParam='teleport')
def _shardsAreReady(self): def _shardsAreReady(self):
for shard in self.activeDistrictMap.values(): for shard in list(self.activeDistrictMap.values()):
if shard.available: if shard.available:
return True return True
else: else:
@ -867,7 +867,7 @@ class OTPClientRepository(ClientRepositoryBase):
self.stopHeartbeat() self.stopHeartbeat()
self.stopReaderPollTask() self.stopReaderPollTask()
gameUsername = launcher.getValue('GAME_USERNAME', base.cr.userName) gameUsername = launcher.getValue('GAME_USERNAME', base.cr.userName)
if self.bootedIndex != None and OTPLocalizer.CRBootedReasons.has_key(self.bootedIndex): if self.bootedIndex != None and self.bootedIndex in OTPLocalizer.CRBootedReasons:
message = OTPLocalizer.CRBootedReasons[self.bootedIndex] % {'name': gameUsername} message = OTPLocalizer.CRBootedReasons[self.bootedIndex] % {'name': gameUsername}
elif self.bootedText != None: elif self.bootedText != None:
message = OTPLocalizer.CRBootedReasonUnknownCode % self.bootedIndex message = OTPLocalizer.CRBootedReasonUnknownCode % self.bootedIndex
@ -1315,11 +1315,11 @@ class OTPClientRepository(ClientRepositoryBase):
continue continue
else: else:
if hasattr(task, 'debugInitTraceback'): if hasattr(task, 'debugInitTraceback'):
print task.debugInitTraceback print(task.debugInitTraceback)
problems.append(task.name) problems.append(task.name)
if problems: if problems:
print taskMgr print(taskMgr)
msg = "You can't leave until you clean up your tasks: {" msg = "You can't leave until you clean up your tasks: {"
for task in problems: for task in problems:
msg += '\n ' + task msg += '\n ' + task
@ -1380,7 +1380,7 @@ class OTPClientRepository(ClientRepositoryBase):
try: try:
value = whoAccepts[obj] value = whoAccepts[obj]
callback = value[0] callback = value[0]
guiObj = callback.im_self guiObj = callback.__self__
if hasattr(guiObj, 'getCreationStackTraceCompactStr'): if hasattr(guiObj, 'getCreationStackTraceCompactStr'):
msg += '\n CREATIONSTACKTRACE:%s' % guiObj.getCreationStackTraceCompactStr() msg += '\n CREATIONSTACKTRACE:%s' % guiObj.getCreationStackTraceCompactStr()
except: except:
@ -1396,7 +1396,7 @@ class OTPClientRepository(ClientRepositoryBase):
def detectLeakedIntervals(self): def detectLeakedIntervals(self):
numIvals = ivalMgr.getNumIntervals() numIvals = ivalMgr.getNumIntervals()
if numIvals > 0: if numIvals > 0:
print "You can't leave until you clean up your intervals: {" print("You can't leave until you clean up your intervals: {")
for i in range(ivalMgr.getMaxIndex()): for i in range(ivalMgr.getMaxIndex()):
ival = None ival = None
if i < len(ivalMgr.ivals): if i < len(ivalMgr.ivals):
@ -1404,13 +1404,13 @@ class OTPClientRepository(ClientRepositoryBase):
if ival == None: if ival == None:
ival = ivalMgr.getCInterval(i) ival = ivalMgr.getCInterval(i)
if ival: if ival:
print ival print(ival)
if hasattr(ival, 'debugName'): if hasattr(ival, 'debugName'):
print ival.debugName print(ival.debugName)
if hasattr(ival, 'debugInitTraceback'): if hasattr(ival, 'debugInitTraceback'):
print ival.debugInitTraceback print(ival.debugInitTraceback)
print '}' print('}')
self.notify.info("You can't leave until you clean up your intervals.") self.notify.info("You can't leave until you clean up your intervals.")
return numIvals return numIvals
else: else:
@ -1547,7 +1547,7 @@ class OTPClientRepository(ClientRepositoryBase):
@report(types=['args', 'deltaStamp'], dConfigParam='teleport') @report(types=['args', 'deltaStamp'], dConfigParam='teleport')
def _removeAllOV(self): def _removeAllOV(self):
ownerDoIds = self.doId2ownerView.keys() ownerDoIds = list(self.doId2ownerView.keys())
for doId in ownerDoIds: for doId in ownerDoIds:
self.disableDoId(doId, ownerView=True) self.disableDoId(doId, ownerView=True)
@ -1672,7 +1672,7 @@ class OTPClientRepository(ClientRepositoryBase):
if not config.GetBool('astron-support', True): if not config.GetBool('astron-support', True):
def handlePlayGame(self, msgType, di): def handlePlayGame(self, msgType, di):
if self.notify.getDebug(): if self.notify.getDebug():
self.notify.debug('handle play game got message type: ' + `msgType`) self.notify.debug('handle play game got message type: ' + repr(msgType))
if msgType == CLIENT_CREATE_OBJECT_REQUIRED: if msgType == CLIENT_CREATE_OBJECT_REQUIRED:
self.handleGenerateWithRequired(di) self.handleGenerateWithRequired(di)
elif msgType == CLIENT_CREATE_OBJECT_REQUIRED_OTHER: elif msgType == CLIENT_CREATE_OBJECT_REQUIRED_OTHER:
@ -1700,7 +1700,7 @@ class OTPClientRepository(ClientRepositoryBase):
else: else:
def handlePlayGame(self, msgType, di): def handlePlayGame(self, msgType, di):
if self.notify.getDebug(): if self.notify.getDebug():
self.notify.debug('handle play game got message type: ' + `msgType`) self.notify.debug('handle play game got message type: ' + repr(msgType))
if self.__recordObjectMessage(msgType, di): if self.__recordObjectMessage(msgType, di):
return return
if msgType == CLIENT_ENTER_OBJECT_REQUIRED: if msgType == CLIENT_ENTER_OBJECT_REQUIRED:
@ -1826,13 +1826,13 @@ class OTPClientRepository(ClientRepositoryBase):
def getStartingDistrict(self): def getStartingDistrict(self):
district = None district = None
if len(self.activeDistrictMap.keys()) == 0: if len(list(self.activeDistrictMap.keys())) == 0:
self.notify.info('no shards') self.notify.info('no shards')
return return
if base.fillShardsToIdealPop: if base.fillShardsToIdealPop:
lowPop, midPop, highPop = base.getShardPopLimits() lowPop, midPop, highPop = base.getShardPopLimits()
self.notify.debug('low: %s mid: %s high: %s' % (lowPop, midPop, highPop)) self.notify.debug('low: %s mid: %s high: %s' % (lowPop, midPop, highPop))
for s in self.activeDistrictMap.values(): for s in list(self.activeDistrictMap.values()):
if s.available and s.avatarCount < lowPop: if s.available and s.avatarCount < lowPop:
self.notify.debug('%s: pop %s' % (s.name, s.avatarCount)) self.notify.debug('%s: pop %s' % (s.name, s.avatarCount))
if district is None: if district is None:
@ -1842,7 +1842,7 @@ class OTPClientRepository(ClientRepositoryBase):
if district is None: if district is None:
self.notify.debug('all shards over cutoff, picking lowest-population shard') self.notify.debug('all shards over cutoff, picking lowest-population shard')
for s in self.activeDistrictMap.values(): for s in list(self.activeDistrictMap.values()):
if s.available: if s.available:
self.notify.debug('%s: pop %s' % (s.name, s.avatarCount)) self.notify.debug('%s: pop %s' % (s.name, s.avatarCount))
if district is None or s.avatarCount < district.avatarCount: if district is None or s.avatarCount < district.avatarCount:
@ -1868,7 +1868,7 @@ class OTPClientRepository(ClientRepositoryBase):
def listActiveShards(self): def listActiveShards(self):
list = [] list = []
for s in self.activeDistrictMap.values(): for s in list(self.activeDistrictMap.values()):
if s.available: if s.available:
list.append((s.doId, list.append((s.doId,
s.name, s.name,
@ -1878,7 +1878,7 @@ class OTPClientRepository(ClientRepositoryBase):
return list return list
def getPlayerAvatars(self): def getPlayerAvatars(self):
return [ i for i in self.doId2do.values() if isinstance(i, DistributedPlayer) ] return [ i for i in list(self.doId2do.values()) if isinstance(i, DistributedPlayer) ]
def queryObjectField(self, dclassName, fieldName, doId, context = 0): def queryObjectField(self, dclassName, fieldName, doId, context = 0):
dclass = self.dclassesByName.get(dclassName) dclass = self.dclassesByName.get(dclassName)
@ -1942,7 +1942,7 @@ class OTPClientRepository(ClientRepositoryBase):
def refreshAccountServerDate(self, forceRefresh = 0): def refreshAccountServerDate(self, forceRefresh = 0):
try: try:
self.accountServerDate.grabDate(force=forceRefresh) self.accountServerDate.grabDate(force=forceRefresh)
except TTAccount.TTAccountException, e: except TTAccount.TTAccountException as e:
self.notify.debug(str(e)) self.notify.debug(str(e))
return 1 return 1
@ -2165,7 +2165,7 @@ class OTPClientRepository(ClientRepositoryBase):
@exceptionLogged(append=False) @exceptionLogged(append=False)
def handleDatagram(self, di): def handleDatagram(self, di):
if self.notify.getDebug(): if self.notify.getDebug():
print 'ClientRepository received datagram:' print('ClientRepository received datagram:')
di.getDatagram().dumpHex(ostream) di.getDatagram().dumpHex(ostream)
msgType = self.getMsgType() msgType = self.getMsgType()
if msgType == 65535: if msgType == 65535:
@ -2317,7 +2317,7 @@ class OTPClientRepository(ClientRepositoryBase):
# Determine whether or not we should add this generate # Determine whether or not we should add this generate
# to the pending generates, or just generate it right away. # to the pending generates, or just generate it right away.
for handle, interest in self._interests.items(): for handle, interest in list(self._interests.items()):
if parentId != interest.parentId: if parentId != interest.parentId:
continue continue

View file

@ -4,7 +4,7 @@ class TelemetryLimited:
Sng = SerialNumGen() Sng = SerialNumGen()
def __init__(self): def __init__(self):
self._telemetryLimiterId = self.Sng.next() self._telemetryLimiterId = next(self.Sng)
self._limits = set() self._limits = set()
def getTelemetryLimiterId(self): def getTelemetryLimiterId(self):

View file

@ -37,7 +37,7 @@ class TelemetryLimiter(DirectObject):
self.ignore(self._getDummyEventName(obj)) self.ignore(self._getDummyEventName(obj))
def _enforceLimits(self, task = None): def _enforceLimits(self, task = None):
for obj in self._objs.itervalues(): for obj in self._objs.values():
obj.enforceTelemetryLimits() obj.enforceTelemetryLimits()
return Task.cont return Task.cont
@ -106,7 +106,7 @@ class TLGatherAllAvs(DirectObject):
def destroy(self): def destroy(self):
self.ignoreAll() self.ignoreAll()
while len(self._avs): while len(self._avs):
self._handlePlayerLeave(self._avs.values()[0]) self._handlePlayerLeave(list(self._avs.values())[0])
del self._avs del self._avs
del self._limits del self._limits

View file

@ -437,7 +437,7 @@ class FriendSecret(DirectFrame, StateData.StateData):
self.ok2.show() self.ok2.show()
def __rejectAccountSecret(self, reason): def __rejectAccountSecret(self, reason):
print '## rejectAccountSecret: reason = ', reason print('## rejectAccountSecret: reason = ', reason)
self.ignore(OTPGlobals.PlayerFriendNewSecretEvent) self.ignore(OTPGlobals.PlayerFriendNewSecretEvent)
self.ignore(OTPGlobals.PlayerFriendRejectNewSecretEvent) self.ignore(OTPGlobals.PlayerFriendRejectNewSecretEvent)
self.nextText['text'] = OTPLocalizer.FriendSecretTooMany self.nextText['text'] = OTPLocalizer.FriendSecretTooMany
@ -515,7 +515,7 @@ class FriendSecret(DirectFrame, StateData.StateData):
self.__enteredSecret(1, 0) self.__enteredSecret(1, 0)
def __rejectUseAccountSecret(self, reason): def __rejectUseAccountSecret(self, reason):
print '## rejectUseAccountSecret: reason = ', reason print('## rejectUseAccountSecret: reason = ', reason)
self.ignore(OTPGlobals.PlayerFriendUpdateEvent) self.ignore(OTPGlobals.PlayerFriendUpdateEvent)
self.ignore(OTPGlobals.PlayerFriendRejectUseSecretEvent) self.ignore(OTPGlobals.PlayerFriendRejectUseSecretEvent)
if reason == RejectCode.RejectCode.FRIENDS_LIST_FULL: if reason == RejectCode.RejectCode.FRIENDS_LIST_FULL:

View file

@ -9,7 +9,7 @@ GUILDRANK_VETERAN = 4
GUILDRANK_GM = 3 GUILDRANK_GM = 3
GUILDRANK_OFFICER = 2 GUILDRANK_OFFICER = 2
GUILDRANK_MEMBER = 1 GUILDRANK_MEMBER = 1
import Queue import queue
class GuildMemberInfo(AvatarHandle): class GuildMemberInfo(AvatarHandle):
@ -227,18 +227,18 @@ class GuildManager(DistributedObjectGlobal):
base.localAvatar.guildNameChange(guildName, changeStatus) base.localAvatar.guildNameChange(guildName, changeStatus)
def guildNameUpdate(self, avatarId, guildName): def guildNameUpdate(self, avatarId, guildName):
print 'DEBUG - guildNameUpdate for ', avatarId, ' to ', guildName print('DEBUG - guildNameUpdate for ', avatarId, ' to ', guildName)
def invitationFrom(self, avatarId, avatarName, guildId, guildName): def invitationFrom(self, avatarId, avatarName, guildId, guildName):
print 'GM invitationFrom %s(%d)' % (avatarName, avatarId) print('GM invitationFrom %s(%d)' % (avatarName, avatarId))
if hasattr(base, 'localAvatar'): if hasattr(base, 'localAvatar'):
base.localAvatar.guiMgr.handleGuildInvitation(avatarId, avatarName, guildId, guildName) base.localAvatar.guiMgr.handleGuildInvitation(avatarId, avatarName, guildId, guildName)
def retractInvite(self, avatarId): def retractInvite(self, avatarId):
print 'GM retraction' print('GM retraction')
def guildAcceptInvite(self, avatarId): def guildAcceptInvite(self, avatarId):
print 'sending accept event' print('sending accept event')
messenger.send(OTPGlobals.GuildAcceptInviteEvent, [avatarId]) messenger.send(OTPGlobals.GuildAcceptInviteEvent, [avatarId])
def leaderboardTopTen(self, stuff): def leaderboardTopTen(self, stuff):

View file

@ -18,7 +18,7 @@ class PlayerFriendsManager(DistributedObjectGlobal):
self.ignoreAll() self.ignoreAll()
def sendRequestInvite(self, playerId): def sendRequestInvite(self, playerId):
print 'PFM sendRequestInvite id:%s' % playerId print('PFM sendRequestInvite id:%s' % playerId)
self.sendUpdate('requestInvite', [0, playerId, True]) self.sendUpdate('requestInvite', [0, playerId, True])
def sendRequestDecline(self, playerId): def sendRequestDecline(self, playerId):
@ -72,15 +72,15 @@ class PlayerFriendsManager(DistributedObjectGlobal):
messenger.send(OTPGlobals.PlayerFriendRejectRemoveEvent, [playerId, reason]) messenger.send(OTPGlobals.PlayerFriendRejectRemoveEvent, [playerId, reason])
def secretResponse(self, secret): def secretResponse(self, secret):
print 'secretResponse %s' % secret print('secretResponse %s' % secret)
messenger.send(OTPGlobals.PlayerFriendNewSecretEvent, [secret]) messenger.send(OTPGlobals.PlayerFriendNewSecretEvent, [secret])
def rejectSecret(self, reason): def rejectSecret(self, reason):
print 'rejectSecret %s' % reason print('rejectSecret %s' % reason)
messenger.send(OTPGlobals.PlayerFriendRejectNewSecretEvent, [reason]) messenger.send(OTPGlobals.PlayerFriendRejectNewSecretEvent, [reason])
def rejectUseSecret(self, reason): def rejectUseSecret(self, reason):
print 'rejectUseSecret %s' % reason print('rejectUseSecret %s' % reason)
messenger.send(OTPGlobals.PlayerFriendRejectUseSecretEvent, [reason]) messenger.send(OTPGlobals.PlayerFriendRejectUseSecretEvent, [reason])
def invitationResponse(self, playerId, respCode, context): def invitationResponse(self, playerId, respCode, context):
@ -98,7 +98,7 @@ class PlayerFriendsManager(DistributedObjectGlobal):
self.playerFriendsList.add(id) self.playerFriendsList.add(id)
self.playerId2Info[id] = info self.playerId2Info[id] = info
messenger.send(OTPGlobals.PlayerFriendAddEvent, [id, info, isNewFriend]) messenger.send(OTPGlobals.PlayerFriendAddEvent, [id, info, isNewFriend])
elif self.playerId2Info.has_key(id): elif id in self.playerId2Info:
if not self.playerId2Info[id].onlineYesNo and info.onlineYesNo: if not self.playerId2Info[id].onlineYesNo and info.onlineYesNo:
self.playerId2Info[id] = info self.playerId2Info[id] = info
messenger.send('playerOnline', [id]) messenger.send('playerOnline', [id])
@ -175,11 +175,11 @@ class PlayerFriendsManager(DistributedObjectGlobal):
def askAvatarOnline(self, avId): def askAvatarOnline(self, avId):
returnValue = 0 returnValue = 0
if self.cr.doId2do.has_key(avId): if avId in self.cr.doId2do:
returnValue = 1 returnValue = 1
if self.playerAvId2avInfo.has_key(avId): if avId in self.playerAvId2avInfo:
playerId = self.findPlayerIdFromAvId(avId) playerId = self.findPlayerIdFromAvId(avId)
if self.playerId2Info.has_key(playerId): if playerId in self.playerId2Info:
playerInfo = self.playerId2Info[playerId] playerInfo = self.playerId2Info[playerId]
if playerInfo.onlineYesNo: if playerInfo.onlineYesNo:
returnValue = 1 returnValue = 1
@ -194,7 +194,7 @@ class PlayerFriendsManager(DistributedObjectGlobal):
return count return count
def askTransientFriend(self, avId): def askTransientFriend(self, avId):
if self.playerAvId2avInfo.has_key(avId) and not base.cr.isAvatarFriend(avId): if avId in self.playerAvId2avInfo and not base.cr.isAvatarFriend(avId):
return 1 return 1
else: else:
return 0 return 0
@ -212,7 +212,7 @@ class PlayerFriendsManager(DistributedObjectGlobal):
return 0 return 0
def askAvatarKnownHere(self, avId): def askAvatarKnownHere(self, avId):
if self.playerAvId2avInfo.has_key(avId): if avId in self.playerAvId2avInfo:
return 1 return 1
else: else:
return 0 return 0
@ -228,7 +228,7 @@ class PlayerFriendsManager(DistributedObjectGlobal):
messenger.send('friendsListChanged') messenger.send('friendsListChanged')
def getAvHandleFromId(self, avId): def getAvHandleFromId(self, avId):
if self.playerAvId2avInfo.has_key(avId): if avId in self.playerAvId2avInfo:
return self.playerAvId2avInfo[avId] return self.playerAvId2avInfo[avId]
else: else:
return None return None
@ -254,7 +254,7 @@ class PlayerFriendsManager(DistributedObjectGlobal):
return returnList return returnList
def identifyAvatar(self, doId): def identifyAvatar(self, doId):
if base.cr.doId2do.has_key(doId): if doId in base.cr.doId2do:
return base.cr.doId2do[doId] return base.cr.doId2do[doId]
else: else:
return self.identifyFriend(doId) return self.identifyFriend(doId)

View file

@ -117,7 +117,7 @@ class DummyLauncherBase:
0, 0,
0]) 0])
if percentComplete >= 100.0: if percentComplete >= 100.0:
messenger.send('phaseComplete-' + `(task.phase)`) messenger.send('phaseComplete-' + repr((task.phase)))
return Task.done return Task.done
else: else:
return Task.cont return Task.cont

View file

@ -2,7 +2,7 @@ import sys
import os import os
import time import time
import string import string
import __builtin__ import builtins
from panda3d.core import * from panda3d.core import *
from direct.showbase.MessengerGlobal import * from direct.showbase.MessengerGlobal import *
from direct.showbase.DirectObject import DirectObject from direct.showbase.DirectObject import DirectObject
@ -132,32 +132,32 @@ class LauncherBase(DirectObject):
os.system('cat /proc/cpuinfo >>' + logfile) os.system('cat /proc/cpuinfo >>' + logfile)
os.system('cat /proc/meminfo >>' + logfile) os.system('cat /proc/meminfo >>' + logfile)
os.system('/sbin/ifconfig -a >>' + logfile) os.system('/sbin/ifconfig -a >>' + logfile)
print '\n\nStarting %s...' % self.GameName print('\n\nStarting %s...' % self.GameName)
print 'Current time: ' + time.asctime(time.localtime(time.time())) + ' ' + time.tzname[0] print('Current time: ' + time.asctime(time.localtime(time.time())) + ' ' + time.tzname[0])
print 'sys.path = ', sys.path print('sys.path = ', sys.path)
print 'sys.argv = ', sys.argv print('sys.argv = ', sys.argv)
if len(sys.argv) >= self.ArgCount: if len(sys.argv) >= self.ArgCount:
Configrc_args = sys.argv[self.ArgCount - 1] Configrc_args = sys.argv[self.ArgCount - 1]
print "generating configrc using: '" + Configrc_args + "'" print("generating configrc using: '" + Configrc_args + "'")
else: else:
Configrc_args = '' Configrc_args = ''
print 'generating standard configrc' print('generating standard configrc')
if os.environ.has_key('PRC_EXECUTABLE_ARGS'): if 'PRC_EXECUTABLE_ARGS' in os.environ:
print 'PRC_EXECUTABLE_ARGS is set to: ' + os.environ['PRC_EXECUTABLE_ARGS'] print('PRC_EXECUTABLE_ARGS is set to: ' + os.environ['PRC_EXECUTABLE_ARGS'])
print 'Resetting PRC_EXECUTABLE_ARGS' print('Resetting PRC_EXECUTABLE_ARGS')
ExecutionEnvironment.setEnvironmentVariable('PRC_EXECUTABLE_ARGS', '-stdout ' + Configrc_args) ExecutionEnvironment.setEnvironmentVariable('PRC_EXECUTABLE_ARGS', '-stdout ' + Configrc_args)
if os.environ.has_key('CONFIG_CONFIG'): if 'CONFIG_CONFIG' in os.environ:
print 'CONFIG_CONFIG is set to: ' + os.environ['CONFIG_CONFIG'] print('CONFIG_CONFIG is set to: ' + os.environ['CONFIG_CONFIG'])
print 'Resetting CONFIG_CONFIG' print('Resetting CONFIG_CONFIG')
os.environ['CONFIG_CONFIG'] = ':_:configdir_.:configpath_:configname_Configrc.exe:configexe_1:configargs_-stdout ' + Configrc_args os.environ['CONFIG_CONFIG'] = ':_:configdir_.:configpath_:configname_Configrc.exe:configexe_1:configargs_-stdout ' + Configrc_args
cpMgr = ConfigPageManager.getGlobalPtr() cpMgr = ConfigPageManager.getGlobalPtr()
cpMgr.reloadImplicitPages() cpMgr.reloadImplicitPages()
launcherConfig = getConfigExpress() launcherConfig = getConfigExpress()
__builtin__.config = launcherConfig builtins.config = launcherConfig
if config.GetBool('log-private-info', 0): if config.GetBool('log-private-info', 0):
print 'os.environ = ', os.environ print('os.environ = ', os.environ)
elif '__COMPAT_LAYER' in os.environ: elif '__COMPAT_LAYER' in os.environ:
print '__COMPAT_LAYER = %s' % (os.environ['__COMPAT_LAYER'],) print('__COMPAT_LAYER = %s' % (os.environ['__COMPAT_LAYER'],))
self.miniTaskMgr = MiniTaskManager() self.miniTaskMgr = MiniTaskManager()
self.VerifyFiles = self.getVerifyFiles() self.VerifyFiles = self.getVerifyFiles()
self.setServerVersion(launcherConfig.GetString('server-version', 'no_version_set')) self.setServerVersion(launcherConfig.GetString('server-version', 'no_version_set'))
@ -214,7 +214,7 @@ class LauncherBase(DirectObject):
self.fromCD = 0 self.fromCD = 0
else: else:
self.fromCD = tmpVal self.fromCD = tmpVal
self.notify.info('patch directory is ' + `(self.fromCD)`) self.notify.info('patch directory is ' + repr((self.fromCD)))
self.dbDir = self.topDir self.dbDir = self.topDir
self.patchDir = self.topDir self.patchDir = self.topDir
self.mfDir = self.topDir self.mfDir = self.topDir
@ -245,7 +245,7 @@ class LauncherBase(DirectObject):
0.003] 0.003]
phaseIdx = 0 phaseIdx = 0
for phase in self.LauncherPhases: for phase in self.LauncherPhases:
percentPhaseCompleteKey = 'PERCENT_PHASE_COMPLETE_' + `phase` percentPhaseCompleteKey = 'PERCENT_PHASE_COMPLETE_' + repr(phase)
self.setRegistry(percentPhaseCompleteKey, 0) self.setRegistry(percentPhaseCompleteKey, 0)
self.phaseComplete[phase] = 0 self.phaseComplete[phase] = 0
self.phaseNewDownload[phase] = 0 self.phaseNewDownload[phase] = 0
@ -917,7 +917,7 @@ class LauncherBase(DirectObject):
def getProgressSum(self, phase): def getProgressSum(self, phase):
sum = 0 sum = 0
for i in xrange(0, len(self.linesInProgress)): for i in range(0, len(self.linesInProgress)):
if self.linesInProgress[i].find(phase) > -1: if self.linesInProgress[i].find(phase) > -1:
nameSizeTuple = self.linesInProgress[i].split() nameSizeTuple = self.linesInProgress[i].split()
numSize = nameSizeTuple[1].split('L') numSize = nameSizeTuple[1].split('L')
@ -939,7 +939,7 @@ class LauncherBase(DirectObject):
token = 'phase_' token = 'phase_'
self.progressSum = self.getProgressSum(token) self.progressSum = self.getProgressSum(token)
self.progressSum -= self.getProgressSum(token + '2') self.progressSum -= self.getProgressSum(token + '2')
self.notify.info('total phases to be downloaded = ' + `(self.progressSum)`) self.notify.info('total phases to be downloaded = ' + repr((self.progressSum)))
self.checkClientDbExists() self.checkClientDbExists()
def prepareClient(self): def prepareClient(self):
@ -1045,7 +1045,7 @@ class LauncherBase(DirectObject):
self.notify.info('maybeStartGame: starting game') self.notify.info('maybeStartGame: starting game')
self.launcherMessage(self.Localizer.LauncherStartingGame) self.launcherMessage(self.Localizer.LauncherStartingGame)
self.background() self.background()
__builtin__.launcher = self builtins.launcher = self
self.startGame() self.startGame()
def _runTaskManager(self): def _runTaskManager(self):
@ -1106,7 +1106,7 @@ class LauncherBase(DirectObject):
return return
def updatePhase(self, phase): def updatePhase(self, phase):
self.notify.info('Updating multifiles in phase: ' + `phase`) self.notify.info('Updating multifiles in phase: ' + repr(phase))
self.setPercentPhaseComplete(self.currentPhase, 0) self.setPercentPhaseComplete(self.currentPhase, 0)
self.phaseMultifileNames = [] self.phaseMultifileNames = []
numfiles = self.dldb.getServerNumMultifiles() numfiles = self.dldb.getServerNumMultifiles()
@ -1128,7 +1128,7 @@ class LauncherBase(DirectObject):
for i in range(self.dldb.getServerNumMultifiles()): for i in range(self.dldb.getServerNumMultifiles()):
mfname = self.dldb.getServerMultifileName(i) mfname = self.dldb.getServerMultifileName(i)
phase = self.dldb.getServerMultifilePhase(mfname) phase = self.dldb.getServerMultifilePhase(mfname)
print i, mfname, phase print(i, mfname, phase)
self.handleGenericMultifileError() self.handleGenericMultifileError()
decompressedMfname = os.path.splitext(self.currentMfname)[0] decompressedMfname = os.path.splitext(self.currentMfname)[0]
@ -1141,10 +1141,10 @@ class LauncherBase(DirectObject):
vfs = VirtualFileSystem.getGlobalPtr() vfs = VirtualFileSystem.getGlobalPtr()
vfs.mount(localFilename, '.', VirtualFileSystem.MFReadOnly) vfs.mount(localFilename, '.', VirtualFileSystem.MFReadOnly)
self.setPercentPhaseComplete(self.currentPhase, 100) self.setPercentPhaseComplete(self.currentPhase, 100)
self.notify.info('Done updating multifiles in phase: ' + `(self.currentPhase)`) self.notify.info('Done updating multifiles in phase: ' + repr((self.currentPhase)))
self.progressSoFar += int(round(self.phaseOverallMap[self.currentPhase] * 100)) self.progressSoFar += int(round(self.phaseOverallMap[self.currentPhase] * 100))
self.notify.info('progress so far ' + `(self.progressSoFar)`) self.notify.info('progress so far ' + repr((self.progressSoFar)))
messenger.send('phaseComplete-' + `(self.currentPhase)`) messenger.send('phaseComplete-' + repr((self.currentPhase)))
if nextIndex < len(self.LauncherPhases): if nextIndex < len(self.LauncherPhases):
self.currentPhase = self.LauncherPhases[nextIndex] self.currentPhase = self.LauncherPhases[nextIndex]
self.currentPhaseIndex = nextIndex + 1 self.currentPhaseIndex = nextIndex + 1
@ -1360,7 +1360,7 @@ class LauncherBase(DirectObject):
self.patchMultifile() self.patchMultifile()
def getPatchFilename(self, fname, currentVersion): def getPatchFilename(self, fname, currentVersion):
return fname + '.v' + `currentVersion` + '.' + self.patchExtension return fname + '.v' + repr(currentVersion) + '.' + self.patchExtension
def downloadPatches(self): def downloadPatches(self):
if len(self.patchList) > 0: if len(self.patchList) > 0:
@ -1376,7 +1376,7 @@ class LauncherBase(DirectObject):
else: else:
self.download(serverPatchFilePath, localPatchFilename, self.downloadPatchDone, self.downloadPatchOverallProgress) self.download(serverPatchFilePath, localPatchFilename, self.downloadPatchDone, self.downloadPatchOverallProgress)
else: else:
self.notify.info('applyNextPatch: Done patching multifile: ' + `(self.currentPhase)`) self.notify.info('applyNextPatch: Done patching multifile: ' + repr((self.currentPhase)))
self.patchDone() self.patchDone()
def downloadPatchDone(self): def downloadPatchDone(self):
@ -1385,7 +1385,7 @@ class LauncherBase(DirectObject):
self.decompressFile(Filename(self.patchDir, Filename(self.currentPatch + '.pz')), self.decompressPatchDone) self.decompressFile(Filename(self.patchDir, Filename(self.currentPatch + '.pz')), self.decompressPatchDone)
def decompressPatchDone(self): def decompressPatchDone(self):
self.notify.info('decompressPatchDone: Patching file: ' + self.currentPatchee + ' from ver: ' + `(self.currentPatchVersion)`) self.notify.info('decompressPatchDone: Patching file: ' + self.currentPatchee + ' from ver: ' + repr((self.currentPatchVersion)))
patchFile = Filename(self.patchDir, Filename(self.currentPatch)) patchFile = Filename(self.patchDir, Filename(self.currentPatch))
patchFile.setBinary() patchFile.setBinary()
patchee = Filename(self.mfDir, Filename(self.currentPatchee)) patchee = Filename(self.mfDir, Filename(self.currentPatchee))
@ -1403,7 +1403,7 @@ class LauncherBase(DirectObject):
self.extract(self.currentMfname, localFilename, destDir, self.updateMultifileDone) self.extract(self.currentMfname, localFilename, destDir, self.updateMultifileDone)
def startReextractingFiles(self): def startReextractingFiles(self):
self.notify.info('startReextractingFiles: Reextracting ' + `(len(self.reextractList))` + ' files for multifile: ' + self.currentMfname) self.notify.info('startReextractingFiles: Reextracting ' + repr((len(self.reextractList))) + ' files for multifile: ' + self.currentMfname)
self.launcherMessage(self.Localizer.LauncherRecoverFiles) self.launcherMessage(self.Localizer.LauncherRecoverFiles)
self.currentMfile = Multifile() self.currentMfile = Multifile()
decompressedMfname = os.path.splitext(self.currentMfname)[0] decompressedMfname = os.path.splitext(self.currentMfname)[0]
@ -1422,12 +1422,12 @@ class LauncherBase(DirectObject):
self.notify.warning('reextractNextFile: Failure on reextract.') self.notify.warning('reextractNextFile: Failure on reextract.')
failure = 1 failure = 1
else: else:
self.notify.warning('reextractNextFile: File not found in multifile: ' + `currentReextractFile`) self.notify.warning('reextractNextFile: File not found in multifile: ' + repr(currentReextractFile))
failure = 1 failure = 1
if failure: if failure:
sys.exit() sys.exit()
self.notify.info('reextractNextFile: Done reextracting files for multifile: ' + `(self.currentPhase)`) self.notify.info('reextractNextFile: Done reextracting files for multifile: ' + repr((self.currentPhase)))
del self.currentMfile del self.currentMfile
self.updateMultifileDone() self.updateMultifileDone()
@ -1461,7 +1461,7 @@ class LauncherBase(DirectObject):
sys.exit() sys.exit()
return return
elif clientVer > 1: elif clientVer > 1:
self.notify.info('patchMultifile: Old version for multifile: ' + self.currentMfname + ' Client ver: ' + `clientVer`) self.notify.info('patchMultifile: Old version for multifile: ' + self.currentMfname + ' Client ver: ' + repr(clientVer))
self.maybeStartGame() self.maybeStartGame()
self.totalPatchDownload = 0 self.totalPatchDownload = 0
self.patchDownloadSoFar = 0 self.patchDownloadSoFar = 0
@ -1473,7 +1473,7 @@ class LauncherBase(DirectObject):
if self.currentPhase == 3: if self.currentPhase == 3:
self.totalPatchDownload += self.getProgressSum(patch) self.totalPatchDownload += self.getProgressSum(patch)
self.notify.info('total patch to be downloaded = ' + `(self.totalPatchDownload)`) self.notify.info('total patch to be downloaded = ' + repr((self.totalPatchDownload)))
self.downloadPatches() self.downloadPatches()
return return
@ -1612,7 +1612,7 @@ class LauncherBase(DirectObject):
percent, percent,
self.getBandwidth(), self.getBandwidth(),
self.byteRate]) self.byteRate])
percentPhaseCompleteKey = 'PERCENT_PHASE_COMPLETE_' + `phase` percentPhaseCompleteKey = 'PERCENT_PHASE_COMPLETE_' + repr(phase)
self.setRegistry(percentPhaseCompleteKey, percent) self.setRegistry(percentPhaseCompleteKey, percent)
self.overallComplete = int(round(percent * self.phaseOverallMap[phase])) + self.progressSoFar self.overallComplete = int(round(percent * self.phaseOverallMap[phase])) + self.progressSoFar
self.setRegistry('PERCENT_OVERALL_COMPLETE', self.overallComplete) self.setRegistry('PERCENT_OVERALL_COMPLETE', self.overallComplete)
@ -1792,29 +1792,29 @@ class LauncherBase(DirectObject):
def scanForHacks(self): def scanForHacks(self):
if not self.WIN32: if not self.WIN32:
return return
import _winreg import winreg
hacksInstalled = {} hacksInstalled = {}
hacksRunning = {} hacksRunning = {}
hackName = ['!xSpeed.net', 'A Speeder', 'Speed Gear'] hackName = ['!xSpeed.net', 'A Speeder', 'Speed Gear']
knownHacksRegistryKeys = { knownHacksRegistryKeys = {
hackName[0] : [ hackName[0] : [
[_winreg.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion\\Run\\!xSpeed'], [winreg.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion\\Run\\!xSpeed'],
[_winreg.HKEY_CURRENT_USER, 'Software\\!xSpeednethy'], [winreg.HKEY_CURRENT_USER, 'Software\\!xSpeednethy'],
[_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\MenuOrder\\Start Menu\\Programs\\!xSpeednet'], [winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\MenuOrder\\Start Menu\\Programs\\!xSpeednet'],
[_winreg.HKEY_LOCAL_MACHINE, 'Software\\Gentee\\Paths\\!xSpeednet'], [winreg.HKEY_LOCAL_MACHINE, 'Software\\Gentee\\Paths\\!xSpeednet'],
[_winreg.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\!xSpeed.net 2.0']], [winreg.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\!xSpeed.net 2.0']],
hackName[1] : [ hackName[1] : [
[_winreg.HKEY_CURRENT_USER, 'Software\\aspeeder'], [winreg.HKEY_CURRENT_USER, 'Software\\aspeeder'],
[_winreg.HKEY_LOCAL_MACHINE, 'Software\\aspeeder'], [winreg.HKEY_LOCAL_MACHINE, 'Software\\aspeeder'],
[_winreg.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\aspeeder']] [winreg.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\aspeeder']]
} }
try: try:
for prog in knownHacksRegistryKeys.keys(): for prog in list(knownHacksRegistryKeys.keys()):
for key in knownHacksRegistryKeys[prog]: for key in knownHacksRegistryKeys[prog]:
try: try:
h = _winreg.OpenKey(key[0], key[1]) h = winreg.OpenKey(key[0], key[1])
hacksInstalled[prog] = 1 hacksInstalled[prog] = 1
_winreg.CloseKey(h) winreg.CloseKey(h)
break break
except: except:
pass pass
@ -1823,9 +1823,9 @@ class LauncherBase(DirectObject):
knownHacksMUI = {'!xspeednet': hackName[0], 'aspeeder': hackName[1], 'speed gear': hackName[2]} knownHacksMUI = {'!xspeednet': hackName[0], 'aspeeder': hackName[1], 'speed gear': hackName[2]}
i = 0 i = 0
try: try:
rh = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\ShellNoRoam\\MUICache') rh = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\ShellNoRoam\\MUICache')
while 1: while 1:
name, value, type = _winreg.EnumValue(rh, i) name, value, type = winreg.EnumValue(rh, i)
i += 1 i += 1
if type == 1: if type == 1:
val = value.lower() val = value.lower()
@ -1833,7 +1833,7 @@ class LauncherBase(DirectObject):
if val.find(hackprog) != -1: if val.find(hackprog) != -1:
hacksInstalled[knownHacksMUI[hackprog]] = 1 hacksInstalled[knownHacksMUI[hackprog]] = 1
break break
_winreg.CloseKey(rh) winreg.CloseKey(rh)
except: except:
pass pass
@ -1846,19 +1846,19 @@ class LauncherBase(DirectObject):
try: try:
for p in procapi.getProcessList(): for p in procapi.getProcessList():
pname = p.name pname = p.name
if knownHacksExe.has_key(pname): if pname in knownHacksExe:
hacksRunning[knownHacksExe[pname]] = 1 hacksRunning[knownHacksExe[pname]] = 1
except: except:
pass pass
if len(hacksInstalled) > 0: if len(hacksInstalled) > 0:
self.notify.info("Third party programs installed:") self.notify.info("Third party programs installed:")
for hack in hacksInstalled.keys(): for hack in list(hacksInstalled.keys()):
self.notify.info(hack) self.notify.info(hack)
if len(hacksRunning) > 0: if len(hacksRunning) > 0:
self.notify.info("Third party programs running:") self.notify.info("Third party programs running:")
for hack in hacksRunning.keys(): for hack in list(hacksRunning.keys()):
self.notify.info(hack) self.notify.info(hack)
self.setPandaErrorCode(8) self.setPandaErrorCode(8)
sys.exit() sys.exit()

View file

@ -1,5 +1,5 @@
from direct.interval.IntervalGlobal import * from direct.interval.IntervalGlobal import *
import BasicEntities from . import BasicEntities
import random import random
class AmbientSound(BasicEntities.NodePathEntity): class AmbientSound(BasicEntities.NodePathEntity):

View file

@ -1,5 +1,5 @@
import Entity from . import Entity
import DistributedEntity from . import DistributedEntity
from pandac.PandaModules import NodePath from pandac.PandaModules import NodePath
class NodePathEntityBase: class NodePathEntityBase:

View file

@ -1,7 +1,7 @@
from pandac.PandaModules import * from pandac.PandaModules import *
from otp.otpbase import OTPGlobals from otp.otpbase import OTPGlobals
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import BasicEntities from . import BasicEntities
class CollisionSolidEntity(BasicEntities.NodePathEntity): class CollisionSolidEntity(BasicEntities.NodePathEntity):
notify = DirectNotifyGlobal.directNotify.newCategory('CollisionSolidEntity') notify = DirectNotifyGlobal.directNotify.newCategory('CollisionSolidEntity')
@ -41,5 +41,5 @@ class CollisionSolidEntity(BasicEntities.NodePathEntity):
if __dev__: if __dev__:
def attribChanged(self, attrib, value): def attribChanged(self, attrib, value):
print 'attribChanged' print('attribChanged')
self.initSolid() self.initSolid()

View file

@ -1,6 +1,6 @@
from direct.showbase import DirectObject from direct.showbase import DirectObject
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import BasicEntities from . import BasicEntities
from pandac.PandaModules import * from pandac.PandaModules import *
from pandac.PandaModules import * from pandac.PandaModules import *
from direct.interval.IntervalGlobal import * from direct.interval.IntervalGlobal import *

View file

@ -1,5 +1,5 @@
from direct.distributed import DistributedObject from direct.distributed import DistributedObject
import Entity from . import Entity
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
class DistributedEntity(DistributedObject.DistributedObject, Entity.Entity): class DistributedEntity(DistributedObject.DistributedObject, Entity.Entity):

View file

@ -1,5 +1,5 @@
from direct.distributed import DistributedObjectAI from direct.distributed import DistributedObjectAI
import Entity from . import Entity
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
class DistributedEntityAI(DistributedObjectAI.DistributedObjectAI, Entity.Entity): class DistributedEntityAI(DistributedObjectAI.DistributedObjectAI, Entity.Entity):

View file

@ -2,7 +2,7 @@ from pandac.PandaModules import *
from direct.distributed.ClockDelta import * from direct.distributed.ClockDelta import *
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM from direct.fsm import ClassicFSM
import DistributedEntity from . import DistributedEntity
class DistributedInteractiveEntity(DistributedEntity.DistributedEntity): class DistributedInteractiveEntity(DistributedEntity.DistributedEntity):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedInteractiveEntity') notify = DirectNotifyGlobal.directNotify.newCategory('DistributedInteractiveEntity')

View file

@ -6,13 +6,13 @@ from toontown.distributed.ToontownMsgTypes import *
from toontown.toonbase import ToontownGlobals from toontown.toonbase import ToontownGlobals
from otp.otpbase import OTPGlobals from otp.otpbase import OTPGlobals
from direct.distributed import DistributedObject from direct.distributed import DistributedObject
import Level from . import Level
import LevelConstants from . import LevelConstants
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import EntityCreator from . import EntityCreator
from direct.gui import OnscreenText from direct.gui import OnscreenText
from direct.task import Task from direct.task import Task
import LevelUtil from . import LevelUtil
import random import random
class DistributedLevel(DistributedObject.DistributedObject, Level.Level): class DistributedLevel(DistributedObject.DistributedObject, Level.Level):
@ -96,7 +96,7 @@ class DistributedLevel(DistributedObject.DistributedObject, Level.Level):
def setSpecBlob(specBlob, blobSender = blobSender, self = self): def setSpecBlob(specBlob, blobSender = blobSender, self = self):
blobSender.sendAck() blobSender.sendAck()
from LevelSpec import LevelSpec from .LevelSpec import LevelSpec
spec = eval(specBlob) spec = eval(specBlob)
if spec is None: if spec is None:
spec = self.candidateSpec spec = self.candidateSpec
@ -114,7 +114,7 @@ class DistributedLevel(DistributedObject.DistributedObject, Level.Level):
def privGotSpec(self, levelSpec): def privGotSpec(self, levelSpec):
Level.Level.initializeLevel(self, self.doId, levelSpec, self.scenarioIndex) Level.Level.initializeLevel(self, self.doId, levelSpec, self.scenarioIndex)
modelZoneNums = self.zoneNums modelZoneNums = self.zoneNums
specZoneNums = self.zoneNum2zoneId.keys() specZoneNums = list(self.zoneNum2zoneId.keys())
if not sameElements(modelZoneNums, specZoneNums): if not sameElements(modelZoneNums, specZoneNums):
self.reportModelSpecSyncError('model zone nums (%s) do not match spec zone nums (%s)' % (modelZoneNums, specZoneNums)) self.reportModelSpecSyncError('model zone nums (%s) do not match spec zone nums (%s)' % (modelZoneNums, specZoneNums))
self.initVisibility() self.initVisibility()
@ -165,14 +165,14 @@ class DistributedLevel(DistributedObject.DistributedObject, Level.Level):
levelMgr = self.getEntity(LevelConstants.LevelMgrEntId) levelMgr = self.getEntity(LevelConstants.LevelMgrEntId)
self.geom = levelMgr.geom self.geom = levelMgr.geom
self.zoneNum2node = LevelUtil.getZoneNum2Node(self.geom) self.zoneNum2node = LevelUtil.getZoneNum2Node(self.geom)
self.zoneNums = self.zoneNum2node.keys() self.zoneNums = list(self.zoneNum2node.keys())
self.zoneNums.sort() self.zoneNums.sort()
self.zoneNumDict = list2dict(self.zoneNums) self.zoneNumDict = list2dict(self.zoneNums)
DistributedLevel.notify.debug('zones from model: %s' % self.zoneNums) DistributedLevel.notify.debug('zones from model: %s' % self.zoneNums)
self.fixupLevelModel() self.fixupLevelModel()
def fixupLevelModel(self): def fixupLevelModel(self):
for zoneNum, zoneNode in self.zoneNum2node.items(): for zoneNum, zoneNode in list(self.zoneNum2node.items()):
if zoneNum == LevelConstants.UberZoneEntId: if zoneNum == LevelConstants.UberZoneEntId:
continue continue
allColls = zoneNode.findAllMatches('**/+CollisionNode') allColls = zoneNode.findAllMatches('**/+CollisionNode')
@ -247,7 +247,7 @@ class DistributedLevel(DistributedObject.DistributedObject, Level.Level):
else: else:
DistributedLevel.notify.debug('entity %s requesting reparent to %s, not yet created' % (entity, parentId)) DistributedLevel.notify.debug('entity %s requesting reparent to %s, not yet created' % (entity, parentId))
entity.reparentTo(hidden) entity.reparentTo(hidden)
if not self.parent2pendingChildren.has_key(parentId): if parentId not in self.parent2pendingChildren:
self.parent2pendingChildren[parentId] = [] self.parent2pendingChildren[parentId] = []
def doReparent(parentId = parentId, self = self, wrt = wrt): def doReparent(parentId = parentId, self = self, wrt = wrt):
@ -403,7 +403,7 @@ class DistributedLevel(DistributedObject.DistributedObject, Level.Level):
removedZoneNums = [] removedZoneNums = []
allVZ = dict(visibleZoneNums) allVZ = dict(visibleZoneNums)
allVZ.update(self.curVisibleZoneNums) allVZ.update(self.curVisibleZoneNums)
for vz, dummy in allVZ.items(): for vz, dummy in list(allVZ.items()):
new = vz in visibleZoneNums new = vz in visibleZoneNums
old = vz in self.curVisibleZoneNums old = vz in self.curVisibleZoneNums
if new and old: if new and old:
@ -426,7 +426,7 @@ class DistributedLevel(DistributedObject.DistributedObject, Level.Level):
self.hideZone(rz) self.hideZone(rz)
if vizZonesChanged or self.fForceSetZoneThisFrame: if vizZonesChanged or self.fForceSetZoneThisFrame:
self.setVisibility(visibleZoneNums.keys()) self.setVisibility(list(visibleZoneNums.keys()))
self.fForceSetZoneThisFrame = 0 self.fForceSetZoneThisFrame = 0
self.curZoneNum = zoneNum self.curZoneNum = zoneNum
self.curVisibleZoneNums = visibleZoneNums self.curVisibleZoneNums = visibleZoneNums
@ -448,7 +448,7 @@ class DistributedLevel(DistributedObject.DistributedObject, Level.Level):
def resetVisibility(self): def resetVisibility(self):
self.curVisibleZoneNums = list2dict(self.zoneNums) self.curVisibleZoneNums = list2dict(self.zoneNums)
del self.curVisibleZoneNums[LevelConstants.UberZoneEntId] del self.curVisibleZoneNums[LevelConstants.UberZoneEntId]
for vz, dummy in self.curVisibleZoneNums.items(): for vz, dummy in list(self.curVisibleZoneNums.items()):
self.showZone(vz) self.showZone(vz)
self.updateVisibility() self.updateVisibility()

View file

@ -2,9 +2,9 @@ from pandac import PandaModules as PM
from otp.ai.AIBaseGlobal import * from otp.ai.AIBaseGlobal import *
from direct.distributed.ClockDelta import * from direct.distributed.ClockDelta import *
from direct.distributed import DistributedObjectAI from direct.distributed import DistributedObjectAI
import Level from . import Level
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import EntityCreatorAI from . import EntityCreatorAI
from direct.showbase.PythonUtil import Functor, weightedChoice from direct.showbase.PythonUtil import Functor, weightedChoice
class DistributedLevelAI(DistributedObjectAI.DistributedObjectAI, Level.Level): class DistributedLevelAI(DistributedObjectAI.DistributedObjectAI, Level.Level):
@ -64,7 +64,7 @@ class DistributedLevelAI(DistributedObjectAI.DistributedObjectAI, Level.Level):
def initializeLevel(self, levelSpec): def initializeLevel(self, levelSpec):
self.startTime = globalClock.getRealTime() self.startTime = globalClock.getRealTime()
self.startTimestamp = globalClockDelta.localToNetworkTime(self.startTime, bits=32) self.startTimestamp = globalClockDelta.localToNetworkTime(self.startTime, bits=32)
lol = zip([1] * levelSpec.getNumScenarios(), range(levelSpec.getNumScenarios())) lol = list(zip([1] * levelSpec.getNumScenarios(), list(range(levelSpec.getNumScenarios()))))
scenarioIndex = weightedChoice(lol) scenarioIndex = weightedChoice(lol)
Level.Level.initializeLevel(self, self.doId, levelSpec, scenarioIndex) Level.Level.initializeLevel(self, self.doId, levelSpec, scenarioIndex)
if __dev__: if __dev__:

View file

@ -1,4 +1,4 @@
import EditMgrBase from . import EditMgrBase
class EditMgr(EditMgrBase.EditMgrBase): class EditMgr(EditMgrBase.EditMgrBase):
pass pass

View file

@ -1,7 +1,7 @@
import EditMgrBase from . import EditMgrBase
if __dev__: if __dev__:
from direct.showbase.PythonUtil import list2dict from direct.showbase.PythonUtil import list2dict
import EditorGlobals from . import EditorGlobals
class EditMgrAI(EditMgrBase.EditMgrBase): class EditMgrAI(EditMgrBase.EditMgrBase):
if __dev__: if __dev__:
@ -15,8 +15,8 @@ class EditMgrAI(EditMgrBase.EditMgrBase):
self.lastAllocatedEntId = allocRange[0] self.lastAllocatedEntId = allocRange[0]
idChosen = 0 idChosen = 0
while not idChosen: while not idChosen:
for id in xrange(self.lastAllocatedEntId, allocRange[1]): for id in range(self.lastAllocatedEntId, allocRange[1]):
print id print(id)
if id not in entIdDict: if id not in entIdDict:
idChosen = 1 idChosen = 1
break break

View file

@ -1,4 +1,4 @@
import Entity from . import Entity
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
class EditMgrBase(Entity.Entity): class EditMgrBase(Entity.Entity):

View file

@ -1,19 +1,19 @@
import CutScene from . import CutScene
import EntityCreatorBase from . import EntityCreatorBase
import BasicEntities from . import BasicEntities
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import EditMgr from . import EditMgr
import EntrancePoint from . import EntrancePoint
import LevelMgr from . import LevelMgr
import LogicGate from . import LogicGate
import ZoneEntity from . import ZoneEntity
import ModelEntity from . import ModelEntity
import PathEntity from . import PathEntity
import VisibilityExtender from . import VisibilityExtender
import PropSpinner from . import PropSpinner
import AmbientSound from . import AmbientSound
import LocatorEntity from . import LocatorEntity
import CollisionSolidEntity from . import CollisionSolidEntity
def nothing(*args): def nothing(*args):
return 'nothing' return 'nothing'

View file

@ -1,8 +1,8 @@
import EntityCreatorBase from . import EntityCreatorBase
import LogicGate from . import LogicGate
import EditMgrAI from . import EditMgrAI
import LevelMgrAI from . import LevelMgrAI
import ZoneEntityAI from . import ZoneEntityAI
from direct.showbase.PythonUtil import Functor from direct.showbase.PythonUtil import Functor
def createDistributedEntity(AIclass, level, entId, zoneId): def createDistributedEntity(AIclass, level, entId, zoneId):

View file

@ -9,19 +9,19 @@ class EntityCreatorBase:
def createEntity(self, entId): def createEntity(self, entId):
entType = self.level.getEntityType(entId) entType = self.level.getEntityType(entId)
if not self.entType2Ctor.has_key(entType): if entType not in self.entType2Ctor:
self.notify.error('unknown entity type: %s (ent%s)' % (entType, entId)) self.notify.error('unknown entity type: %s (ent%s)' % (entType, entId))
ent = self.doCreateEntity(self.entType2Ctor[entType], entId) ent = self.doCreateEntity(self.entType2Ctor[entType], entId)
return ent return ent
def getEntityTypes(self): def getEntityTypes(self):
return self.entType2Ctor.keys() return list(self.entType2Ctor.keys())
def privRegisterType(self, entType, ctor): def privRegisterType(self, entType, ctor):
if self.entType2Ctor.has_key(entType): if entType in self.entType2Ctor:
self.notify.debug('replacing %s ctor %s with %s' % (entType, self.entType2Ctor[entType], ctor)) self.notify.debug('replacing %s ctor %s with %s' % (entType, self.entType2Ctor[entType], ctor))
self.entType2Ctor[entType] = ctor self.entType2Ctor[entType] = ctor
def privRegisterTypes(self, type2ctor): def privRegisterTypes(self, type2ctor):
for entType, ctor in type2ctor.items(): for entType, ctor in list(type2ctor.items()):
self.privRegisterType(entType, ctor) self.privRegisterType(entType, ctor)

View file

@ -1,5 +1,5 @@
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import AttribDesc from . import AttribDesc
from direct.showbase.PythonUtil import mostDerivedLast from direct.showbase.PythonUtil import mostDerivedLast
class EntityTypeDesc: class EntityTypeDesc:
@ -17,10 +17,10 @@ class EntityTypeDesc:
self.attribDescDict[attribName] = desc self.attribDescDict[attribName] = desc
def isConcrete(self): def isConcrete(self):
return not self.__class__.__dict__.has_key('abstract') return 'abstract' not in self.__class__.__dict__
def isPermanent(self): def isPermanent(self):
return self.__class__.__dict__.has_key('permanent') return 'permanent' in self.__class__.__dict__
def getOutputType(self): def getOutputType(self):
return self.output return self.output
@ -33,7 +33,7 @@ class EntityTypeDesc:
def getAttribsOfType(self, type): def getAttribsOfType(self, type):
names = [] names = []
for attribName, desc in self.attribDescDict.items(): for attribName, desc in list(self.attribDescDict.items()):
if desc.getDatatype() == type: if desc.getDatatype() == type:
names.append(attribName) names.append(attribName)
@ -41,7 +41,7 @@ class EntityTypeDesc:
@staticmethod @staticmethod
def privCompileAttribDescs(entTypeClass): def privCompileAttribDescs(entTypeClass):
if entTypeClass.__dict__.has_key('_attribDescs'): if '_attribDescs' in entTypeClass.__dict__:
return return
c = entTypeClass c = entTypeClass
EntityTypeDesc.notify.debug('compiling attrib descriptors for %s' % c.__name__) EntityTypeDesc.notify.debug('compiling attrib descriptors for %s' % c.__name__)
@ -64,7 +64,7 @@ class EntityTypeDesc:
baseADs.append(desc) baseADs.append(desc)
attribDescs = [] attribDescs = []
if c.__dict__.has_key('attribs'): if 'attribs' in c.__dict__:
for attrib in c.attribs: for attrib in c.attribs:
desc = AttribDesc.AttribDesc(*attrib) desc = AttribDesc.AttribDesc(*attrib)
if desc.getName() == 'type' and entTypeClass.__name__ != 'Entity': if desc.getName() == 'type' and entTypeClass.__name__ != 'Entity':

View file

@ -1,11 +1,12 @@
from pandac.PandaModules import * from pandac.PandaModules import *
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import types import types
import AttribDesc from . import AttribDesc
import EntityTypeDesc from . import EntityTypeDesc
from direct.showbase.PythonUtil import mostDerivedLast from direct.showbase.PythonUtil import mostDerivedLast
import os import os
import string import string
import importlib
class EntityTypeRegistry: class EntityTypeRegistry:
notify = DirectNotifyGlobal.directNotify.newCategory('EntityTypeRegistry') notify = DirectNotifyGlobal.directNotify.newCategory('EntityTypeRegistry')
@ -13,9 +14,9 @@ class EntityTypeRegistry:
def __init__(self, entityTypeModule): def __init__(self, entityTypeModule):
self.entTypeModule = entityTypeModule self.entTypeModule = entityTypeModule
hv = HashVal() hv = HashVal()
import EntityTypes from . import EntityTypes
reload(EntityTypes) importlib.reload(EntityTypes)
reload(self.entTypeModule) importlib.reload(self.entTypeModule)
def getPyExtVersion(filename): def getPyExtVersion(filename):
base, ext = os.path.splitext(filename) base, ext = os.path.splitext(filename)
@ -33,21 +34,21 @@ class EntityTypeRegistry:
self.hashStr = s self.hashStr = s
getPyExtVersion = None getPyExtVersion = None
classes = [] classes = []
for key, value in entityTypeModule.__dict__.items(): for key, value in list(entityTypeModule.__dict__.items()):
if type(value) is types.ClassType: if type(value) is type:
if issubclass(value, EntityTypeDesc.EntityTypeDesc): if issubclass(value, EntityTypeDesc.EntityTypeDesc):
classes.append(value) classes.append(value)
self.entTypeName2typeDesc = {} self.entTypeName2typeDesc = {}
mostDerivedLast(classes) mostDerivedLast(classes)
for c in classes: for c in classes:
if c.__dict__.has_key('type'): if 'type' in c.__dict__:
if self.entTypeName2typeDesc.has_key(c.type): if c.type in self.entTypeName2typeDesc:
EntityTypeRegistry.notify.debug("replacing %s with %s for entity type '%s'" % (self.entTypeName2typeDesc[c.type].__class__, c, c.type)) EntityTypeRegistry.notify.debug("replacing %s with %s for entity type '%s'" % (self.entTypeName2typeDesc[c.type].__class__, c, c.type))
self.entTypeName2typeDesc[c.type] = c() self.entTypeName2typeDesc[c.type] = c()
self.output2typeNames = {} self.output2typeNames = {}
for typename, typeDesc in self.entTypeName2typeDesc.items(): for typename, typeDesc in list(self.entTypeName2typeDesc.items()):
if typeDesc.isConcrete(): if typeDesc.isConcrete():
if hasattr(typeDesc, 'output'): if hasattr(typeDesc, 'output'):
outputType = typeDesc.output outputType = typeDesc.output
@ -55,14 +56,14 @@ class EntityTypeRegistry:
self.output2typeNames[outputType].append(typename) self.output2typeNames[outputType].append(typename)
self.permanentTypeNames = [] self.permanentTypeNames = []
for typename, typeDesc in self.entTypeName2typeDesc.items(): for typename, typeDesc in list(self.entTypeName2typeDesc.items()):
if typeDesc.isPermanent(): if typeDesc.isPermanent():
self.permanentTypeNames.append(typename) self.permanentTypeNames.append(typename)
self.typeName2derivedTypeNames = {} self.typeName2derivedTypeNames = {}
for typename, typeDesc in self.entTypeName2typeDesc.items(): for typename, typeDesc in list(self.entTypeName2typeDesc.items()):
typenames = [] typenames = []
for tn, td in self.entTypeName2typeDesc.items(): for tn, td in list(self.entTypeName2typeDesc.items()):
if td.isConcrete(): if td.isConcrete():
if issubclass(td.__class__, typeDesc.__class__): if issubclass(td.__class__, typeDesc.__class__):
typenames.append(tn) typenames.append(tn)
@ -72,7 +73,7 @@ class EntityTypeRegistry:
return return
def getAllTypeNames(self): def getAllTypeNames(self):
return self.entTypeName2typeDesc.keys() return list(self.entTypeName2typeDesc.keys())
def getTypeDesc(self, entTypeName): def getTypeDesc(self, entTypeName):
return self.entTypeName2typeDesc[entTypeName] return self.entTypeName2typeDesc[entTypeName]

View file

@ -1,4 +1,4 @@
from EntityTypeDesc import EntityTypeDesc from .EntityTypeDesc import EntityTypeDesc
from toontown.coghq.SpecImports import * from toontown.coghq.SpecImports import *
class Entity(EntityTypeDesc): class Entity(EntityTypeDesc):

View file

@ -1,6 +1,6 @@
from toontown.toonbase.ToontownGlobals import * from toontown.toonbase.ToontownGlobals import *
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import BasicEntities from . import BasicEntities
class EntrancePoint(BasicEntities.NodePathEntity): class EntrancePoint(BasicEntities.NodePathEntity):
@ -29,7 +29,7 @@ class EntrancePoint(BasicEntities.NodePathEntity):
def destroyEntrancePoint(self): def destroyEntrancePoint(self):
if self.entranceId >= 0: if self.entranceId >= 0:
if self.level.entranceId2entity.has_key(self.entranceId): if self.entranceId in self.level.entranceId2entity:
del self.level.entranceId2entity[self.entranceId] del self.level.entranceId2entity[self.entranceId]
if __dev__: if __dev__:

View file

@ -1,6 +1,6 @@
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import string import string
import LevelConstants from . import LevelConstants
from direct.showbase.PythonUtil import lineInfo, uniqueElements from direct.showbase.PythonUtil import lineInfo, uniqueElements
import types import types
@ -119,7 +119,7 @@ class Level:
def initializeEntity(self, entity): def initializeEntity(self, entity):
entId = entity.entId entId = entity.entId
spec = self.levelSpec.getEntitySpec(entId) spec = self.levelSpec.getEntitySpec(entId)
for key, value in spec.items(): for key, value in list(spec.items()):
if key in ('type', 'name', 'comment'): if key in ('type', 'name', 'comment'):
continue continue
entity.setAttribInit(key, value) entity.setAttribInit(key, value)

View file

@ -1,5 +1,5 @@
from direct.showbase.PythonUtil import Functor from direct.showbase.PythonUtil import Functor
import LevelMgrBase from . import LevelMgrBase
class LevelMgr(LevelMgrBase.LevelMgrBase): class LevelMgr(LevelMgrBase.LevelMgrBase):

View file

@ -1,5 +1,5 @@
from direct.showbase.PythonUtil import Functor from direct.showbase.PythonUtil import Functor
import LevelMgrBase from . import LevelMgrBase
class LevelMgrAI(LevelMgrBase.LevelMgrBase): class LevelMgrAI(LevelMgrBase.LevelMgrBase):
@ -26,7 +26,7 @@ class LevelMgrAI(LevelMgrBase.LevelMgrBase):
self.privCreateSortedZoneIdList() self.privCreateSortedZoneIdList()
def privCreateSortedZoneIdList(self): def privCreateSortedZoneIdList(self):
zoneNums = self.level.zoneNum2zoneId.keys() zoneNums = list(self.level.zoneNum2zoneId.keys())
zoneNums.sort() zoneNums.sort()
self.level.zoneIds = [] self.level.zoneIds = []
for zoneNum in zoneNums: for zoneNum in zoneNums:

View file

@ -1,4 +1,4 @@
import Entity from . import Entity
class LevelMgrBase(Entity.Entity): class LevelMgrBase(Entity.Entity):

View file

@ -2,8 +2,9 @@ from pandac import PandaModules as PM
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
from direct.showbase.PythonUtil import list2dict, uniqueElements from direct.showbase.PythonUtil import list2dict, uniqueElements
import string import string
import LevelConstants from . import LevelConstants
import types import types
import importlib
if __dev__: if __dev__:
import os import os
@ -15,11 +16,11 @@ class LevelSpec:
newSpec = 0 newSpec = 0
if type(spec) is types.ModuleType: if type(spec) is types.ModuleType:
if __dev__: if __dev__:
reload(spec) importlib.reload(spec)
self.specDict = spec.levelSpec self.specDict = spec.levelSpec
if __dev__: if __dev__:
self.setFilename(spec.__file__) self.setFilename(spec.__file__)
elif type(spec) is types.DictType: elif type(spec) is dict:
self.specDict = spec self.specDict = spec
elif spec is None: elif spec is None:
if __dev__: if __dev__:
@ -34,8 +35,8 @@ class LevelSpec:
self.setScenario(scenario) self.setScenario(scenario)
if __dev__: if __dev__:
if newSpec: if newSpec:
import EntityTypes from . import EntityTypes
import EntityTypeRegistry from . import EntityTypeRegistry
etr = EntityTypeRegistry.EntityTypeRegistry(EntityTypes) etr = EntityTypeRegistry.EntityTypeRegistry(EntityTypes)
self.setEntityTypeReg(etr) self.setEntityTypeReg(etr)
entId = LevelConstants.UberZoneEntId entId = LevelConstants.UberZoneEntId
@ -68,19 +69,19 @@ class LevelSpec:
return self.scenario return self.scenario
def getGlobalEntIds(self): def getGlobalEntIds(self):
return self.privGetGlobalEntityDict().keys() return list(self.privGetGlobalEntityDict().keys())
def getScenarioEntIds(self, scenario = None): def getScenarioEntIds(self, scenario = None):
if scenario is None: if scenario is None:
scenario = self.scenario scenario = self.scenario
return self.privGetScenarioEntityDict(scenario).keys() return list(self.privGetScenarioEntityDict(scenario).keys())
def getAllEntIds(self): def getAllEntIds(self):
return self.getGlobalEntIds() + self.getScenarioEntIds() return self.getGlobalEntIds() + self.getScenarioEntIds()
def getAllEntIdsFromAllScenarios(self): def getAllEntIdsFromAllScenarios(self):
entIds = self.getGlobalEntIds() entIds = self.getGlobalEntIds()
for scenario in xrange(self.getNumScenarios()): for scenario in range(self.getNumScenarios()):
entIds.extend(self.getScenarioEntIds(scenario)) entIds.extend(self.getScenarioEntIds(scenario))
return entIds return entIds
@ -92,10 +93,10 @@ class LevelSpec:
def getCopyOfSpec(self, spec): def getCopyOfSpec(self, spec):
specCopy = {} specCopy = {}
if not isClient(): if not isClient():
print 'EXECWARNING LevelSpec exec: %s' % self.getSpecImportsModuleName() print('EXECWARNING LevelSpec exec: %s' % self.getSpecImportsModuleName())
printStack() printStack()
exec 'from %s import *' % self.getSpecImportsModuleName() exec('from %s import *' % self.getSpecImportsModuleName())
for key in spec.keys(): for key in list(spec.keys()):
specCopy[key] = eval(repr(spec[key])) specCopy[key] = eval(repr(spec[key]))
return specCopy return specCopy
@ -138,7 +139,7 @@ class LevelSpec:
zoneIds.sort() zoneIds.sort()
for zoneNum in zoneIds: for zoneNum in zoneIds:
spec = self.getEntitySpec(zoneNum) spec = self.getEntitySpec(zoneNum)
print 'zone %s: %s' % (zoneNum, spec['name']) print('zone %s: %s' % (zoneNum, spec['name']))
if __dev__: if __dev__:
@ -155,7 +156,7 @@ class LevelSpec:
type = self.getEntityType(entId) type = self.getEntityType(entId)
typeDesc = self.entTypeReg.getTypeDesc(type) typeDesc = self.entTypeReg.getTypeDesc(type)
attribDescDict = typeDesc.getAttribDescDict() attribDescDict = typeDesc.getAttribDescDict()
for attribName, desc in attribDescDict.iteritems(): for attribName, desc in attribDescDict.items():
if attribName not in spec: if attribName not in spec:
spec[attribName] = desc.getDefaultValue() spec[attribName] = desc.getDefaultValue()
@ -187,7 +188,7 @@ class LevelSpec:
globalEnts[entId] = {} globalEnts[entId] = {}
spec = globalEnts[entId] spec = globalEnts[entId]
attribDescs = self.entTypeReg.getTypeDesc(entType).getAttribDescDict() attribDescs = self.entTypeReg.getTypeDesc(entType).getAttribDescDict()
for name, desc in attribDescs.items(): for name, desc in list(attribDescs.items()):
spec[name] = desc.getDefaultValue() spec[name] = desc.getDefaultValue()
spec['type'] = entType spec['type'] = entType
@ -240,7 +241,7 @@ class LevelSpec:
backupFilename = self.privGetBackupFilename(filename) backupFilename = self.privGetBackupFilename(filename)
self.privRemoveFile(backupFilename) self.privRemoveFile(backupFilename)
os.rename(filename, backupFilename) os.rename(filename, backupFilename)
except OSError, e: except OSError as e:
LevelSpec.notify.warning('error during backup: %s' % str(e)) LevelSpec.notify.warning('error during backup: %s' % str(e))
LevelSpec.notify.info("writing to '%s'" % filename) LevelSpec.notify.info("writing to '%s'" % filename)
@ -301,9 +302,9 @@ class LevelSpec:
firstTypes = ('levelMgr', 'editMgr', 'zone') firstTypes = ('levelMgr', 'editMgr', 'zone')
firstAttribs = ('type', 'name', 'comment', 'parentEntId', 'pos', 'x', 'y', 'z', 'hpr', 'h', 'p', 'r', 'scale', 'sx', 'sy', 'sz', 'color', 'model') firstAttribs = ('type', 'name', 'comment', 'parentEntId', 'pos', 'x', 'y', 'z', 'hpr', 'h', 'p', 'r', 'scale', 'sx', 'sy', 'sz', 'color', 'model')
str = t(0) + '%s = {\n' % name str = t(0) + '%s = {\n' % name
entIds = dict.keys() entIds = list(dict.keys())
entType2ids = self.getEntType2ids(entIds) entType2ids = self.getEntType2ids(entIds)
types = sortList(entType2ids.keys(), firstTypes) types = sortList(list(entType2ids.keys()), firstTypes)
for type in types: for type in types:
str += t(1) + '# %s\n' % string.upper(type) str += t(1) + '# %s\n' % string.upper(type)
entIds = entType2ids[type] entIds = entType2ids[type]
@ -311,7 +312,7 @@ class LevelSpec:
for entId in entIds: for entId in entIds:
str += t(1) + '%s: {\n' % entId str += t(1) + '%s: {\n' % entId
spec = dict[entId] spec = dict[entId]
attribs = sortList(spec.keys(), firstAttribs) attribs = sortList(list(spec.keys()), firstAttribs)
for attrib in attribs: for attrib in attribs:
str += t(2) + "'%s': %s,\n" % (attrib, repr(spec[attrib])) str += t(2) + "'%s': %s,\n" % (attrib, repr(spec[attrib]))
@ -364,7 +365,7 @@ class LevelSpec:
s += '\nBAD VALUE(%s): %s != %s\n' % (key, strd1, strd2) s += '\nBAD VALUE(%s): %s != %s\n' % (key, strd1, strd2)
errorCount += 1 errorCount += 1
print s print(s)
if errorCount == 0: if errorCount == 0:
return 1 return 1
else: else:
@ -374,9 +375,9 @@ class LevelSpec:
if prettyString is None: if prettyString is None:
prettyString = self.getPrettyString() prettyString = self.getPrettyString()
if not isClient(): if not isClient():
print 'EXECWARNING LevelSpec exec 2: %s' % prettyString print('EXECWARNING LevelSpec exec 2: %s' % prettyString)
printStack() printStack()
exec prettyString exec(prettyString)
if self._recurKeyTest(levelSpec, self.specDict): if self._recurKeyTest(levelSpec, self.specDict):
return 1 return 1
return return
@ -396,13 +397,13 @@ class LevelSpec:
typeDesc = self.entTypeReg.getTypeDesc(entType) typeDesc = self.entTypeReg.getTypeDesc(entType)
attribNames = typeDesc.getAttribNames() attribNames = typeDesc.getAttribNames()
attribDescs = typeDesc.getAttribDescDict() attribDescs = typeDesc.getAttribDescDict()
for attrib in spec.keys(): for attrib in list(spec.keys()):
if attrib not in attribNames: if attrib not in attribNames:
LevelSpec.notify.warning("entId %s (%s): unknown attrib '%s', omitting" % (entId, spec['type'], attrib)) LevelSpec.notify.warning("entId %s (%s): unknown attrib '%s', omitting" % (entId, spec['type'], attrib))
del spec[attrib] del spec[attrib]
for attribName in attribNames: for attribName in attribNames:
if not spec.has_key(attribName): if attribName not in spec:
LevelSpec.notify.warning("entId %s (%s): missing attrib '%s'" % (entId, spec['type'], attribName)) LevelSpec.notify.warning("entId %s (%s): missing attrib '%s'" % (entId, spec['type'], attribName))
return return

View file

@ -1,5 +1,5 @@
import string import string
import LevelConstants from . import LevelConstants
def getZoneNum2Node(levelModel, logFunc = lambda str: str): def getZoneNum2Node(levelModel, logFunc = lambda str: str):

View file

@ -1,4 +1,4 @@
import Entity, BasicEntities from . import Entity, BasicEntities
from pandac.PandaModules import NodePath from pandac.PandaModules import NodePath
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal

View file

@ -1,6 +1,6 @@
from direct.showbase import DirectObject from direct.showbase import DirectObject
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import Entity from . import Entity
def andTest(self, a, b): def andTest(self, a, b):
if b: if b:

View file

@ -1,6 +1,6 @@
from toontown.toonbase.ToontownGlobals import * from toontown.toonbase.ToontownGlobals import *
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import BasicEntities from . import BasicEntities
class ModelEntity(BasicEntities.NodePathEntity): class ModelEntity(BasicEntities.NodePathEntity):
LoadFuncs = {'loadModelCopy': loader.loadModelCopy, LoadFuncs = {'loadModelCopy': loader.loadModelCopy,

View file

@ -1,7 +1,7 @@
from toontown.toonbase.ToontownGlobals import * from toontown.toonbase.ToontownGlobals import *
from direct.interval.IntervalGlobal import * from direct.interval.IntervalGlobal import *
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import BasicEntities from . import BasicEntities
from toontown.suit import GoonPathData from toontown.suit import GoonPathData
class PathEntity(BasicEntities.NodePathEntity): class PathEntity(BasicEntities.NodePathEntity):

View file

@ -1,6 +1,6 @@
import string import string
from direct.interval.IntervalGlobal import * from direct.interval.IntervalGlobal import *
from Entity import Entity from .Entity import Entity
from pandac.PandaModules import Vec3 from pandac.PandaModules import Vec3
class PropSpinner(Entity): class PropSpinner(Entity):
@ -28,7 +28,7 @@ class PropSpinner(Entity):
try: try:
rate = int(nameParts[3]) rate = int(nameParts[3])
except: except:
print 'invalid prop rotate string: %s' % name print('invalid prop rotate string: %s' % name)
if neg: if neg:
rate = -rate rate = -rate
@ -40,7 +40,7 @@ class PropSpinner(Entity):
elif axis == 'Z': elif axis == 'Z':
hpr = Vec3(0, 0, rate * 360) hpr = Vec3(0, 0, rate * 360)
else: else:
print 'error', axis print('error', axis)
spinTracks.append(LerpHprInterval(prop, 60, hpr)) spinTracks.append(LerpHprInterval(prop, 60, hpr))
spinTracks.loop() spinTracks.loop()

View file

@ -1,4 +1,4 @@
import Entity from . import Entity
class VisibilityBlocker: class VisibilityBlocker:

View file

@ -1,4 +1,4 @@
import Entity from . import Entity
class VisibilityExtender(Entity.Entity): class VisibilityExtender(Entity.Entity):

View file

@ -1,5 +1,5 @@
import ZoneEntityBase from . import ZoneEntityBase
import BasicEntities from . import BasicEntities
class ZoneEntity(ZoneEntityBase.ZoneEntityBase, BasicEntities.NodePathAttribs): class ZoneEntity(ZoneEntityBase.ZoneEntityBase, BasicEntities.NodePathAttribs):
@ -24,7 +24,7 @@ class ZoneEntity(ZoneEntityBase.ZoneEntityBase, BasicEntities.NodePathAttribs):
return self.nodePath return self.nodePath
def getVisibleZoneNums(self): def getVisibleZoneNums(self):
return self.visibleZoneNums.keys() return list(self.visibleZoneNums.keys())
def incrementRefCounts(self, zoneNumList): def incrementRefCounts(self, zoneNumList):
for zoneNum in zoneNumList: for zoneNum in zoneNumList:

View file

@ -1,4 +1,4 @@
import ZoneEntityBase from . import ZoneEntityBase
class ZoneEntityAI(ZoneEntityBase.ZoneEntityBase): class ZoneEntityAI(ZoneEntityBase.ZoneEntityBase):

View file

@ -1,5 +1,5 @@
import Entity from . import Entity
import LevelConstants from . import LevelConstants
class ZoneEntityBase(Entity.Entity): class ZoneEntityBase(Entity.Entity):

View file

@ -1,8 +1,8 @@
from pandac.PandaModules import * from pandac.PandaModules import *
from RemoteValueSet import * from .RemoteValueSet import *
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import TTAccount from . import TTAccount
import HTTPUtil from . import HTTPUtil
class AccountServerConstants(RemoteValueSet): class AccountServerConstants(RemoteValueSet):
notify = DirectNotifyGlobal.directNotify.newCategory('AccountServerConstants') notify = DirectNotifyGlobal.directNotify.newCategory('AccountServerConstants')

View file

@ -1,5 +1,5 @@
import anydbm import dbm
import dumbdbm import dbm.dumb
import json import json
import sys import sys
import time import time
@ -273,7 +273,7 @@ class GetAvatarsOperation(AvatarOperation):
def __handleSendAvatars(self): def __handleSendAvatars(self):
potentialAvatars = [] potentialAvatars = []
for avId, fields in self.avatarFields.items(): for avId, fields in list(self.avatarFields.items()):
index = self.avList.index(avId) index = self.avList.index(avId)
wishNameState = fields.get('WishNameState', [''])[0] wishNameState = fields.get('WishNameState', [''])[0]
name = fields['setName'][0] name = fields['setName'][0]
@ -706,7 +706,7 @@ class AstronLoginManagerUD(DistributedObjectGlobalUD):
return return
# Is the sender already logging in? # Is the sender already logging in?
if sender in self.sender2loginOperation.keys(): if sender in list(self.sender2loginOperation.keys()):
# TODO kill connection # TODO kill connection
return return

View file

@ -7,8 +7,8 @@ from direct.fsm import ClassicFSM
from direct.fsm import State from direct.fsm import State
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
from otp.otpbase import OTPLocalizer from otp.otpbase import OTPLocalizer
import TTAccount from . import TTAccount
import GuiScreen from . import GuiScreen
from otp.otpbase import OTPGlobals from otp.otpbase import OTPGlobals
from direct.distributed.MsgTypes import * from direct.distributed.MsgTypes import *
@ -158,7 +158,7 @@ class CreateAccountScreen(StateData.StateData, GuiScreen.GuiScreen):
if referrer is not None: if referrer is not None:
data['referrer'] = referrer data['referrer'] = referrer
error = self.loginInterface.createAccount(self.userName, self.password, data) error = self.loginInterface.createAccount(self.userName, self.password, data)
except TTAccount.TTAccountException, e: except TTAccount.TTAccountException as e:
error = str(e) error = str(e)
self.notify.info(error) self.notify.info(error)
self.dialog.setMessage(error + OTPLocalizer.CreateAccountScreenConnectionErrorSuffix) self.dialog.setMessage(error + OTPLocalizer.CreateAccountScreenConnectionErrorSuffix)

View file

@ -28,14 +28,14 @@ class GuiScreen:
self.__startFrameStartTask() self.__startFrameStartTask()
self.userGlobalFocusHandler = globalFocusHandler self.userGlobalFocusHandler = globalFocusHandler
self.focusHandlerAbsorbCounts = {} self.focusHandlerAbsorbCounts = {}
for i in xrange(len(self.focusList)): for i in range(len(self.focusList)):
item = self.focusList[i] item = self.focusList[i]
if isinstance(item, DirectEntry): if isinstance(item, DirectEntry):
self.focusHandlerAbsorbCounts[item] = 0 self.focusHandlerAbsorbCounts[item] = 0
self.userFocusHandlers = {} self.userFocusHandlers = {}
self.userCommandHandlers = {} self.userCommandHandlers = {}
for i in xrange(len(self.focusList)): for i in range(len(self.focusList)):
item = self.focusList[i] item = self.focusList[i]
if isinstance(item, DirectEntry): if isinstance(item, DirectEntry):
self.userFocusHandlers[item] = (item['focusInCommand'], item['focusInExtraArgs']) self.userFocusHandlers[item] = (item['focusInCommand'], item['focusInExtraArgs'])
@ -50,10 +50,10 @@ class GuiScreen:
item['extraArgs'] = [i] item['extraArgs'] = [i]
self.enterPressHandlers = {} self.enterPressHandlers = {}
for i in xrange(len(self.focusList)): for i in range(len(self.focusList)):
item = self.focusList[i] item = self.focusList[i]
behavior = enterPressBehavior behavior = enterPressBehavior
if overrides.has_key(item): if item in overrides:
behavior = overrides[item] behavior = overrides[item]
if callable(behavior): if callable(behavior):
self.enterPressHandlers[item] = behavior self.enterPressHandlers[item] = behavior
@ -150,15 +150,15 @@ class GuiScreen:
if userHandler: if userHandler:
if isinstance(item, DirectEntry): if isinstance(item, DirectEntry):
enteredText = item.get() enteredText = item.get()
apply(userHandler, [enteredText] + userHandlerArgs) userHandler(*[enteredText] + userHandlerArgs)
elif isinstance(item, DirectScrolledList): elif isinstance(item, DirectScrolledList):
apply(userHandler, userHandlerArgs) userHandler(*userHandlerArgs)
def __chainToUserFocusHandler(self, item): def __chainToUserFocusHandler(self, item):
if isinstance(item, DirectEntry): if isinstance(item, DirectEntry):
userHandler, userHandlerArgs = self.userFocusHandlers[item] userHandler, userHandlerArgs = self.userFocusHandlers[item]
if userHandler: if userHandler:
apply(userHandler, userHandlerArgs) userHandler(*userHandlerArgs)
def __handleTab(self): def __handleTab(self):
self.tabPressed = 1 self.tabPressed = 1

View file

@ -29,7 +29,7 @@ def getHTTPResponse(url, http, body = ''):
stream = hd.openReadBody() stream = hd.openReadBody()
sr = StreamReader(stream, 1) sr = StreamReader(stream, 1)
response = sr.readlines() response = sr.readlines()
for i in xrange(len(response)): for i in range(len(response)):
if response[i][-1] == '\n': if response[i][-1] == '\n':
response[i] = response[i][:-1] response[i] = response[i][:-1]

View file

@ -1,7 +1,7 @@
from direct.showbase.ShowBaseGlobal import * from direct.showbase.ShowBaseGlobal import *
from direct.distributed.MsgTypes import * from direct.distributed.MsgTypes import *
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import LoginBase from . import LoginBase
from direct.distributed.PyDatagram import PyDatagram from direct.distributed.PyDatagram import PyDatagram
class LoginDISLTokenAccount(LoginBase.LoginBase): class LoginDISLTokenAccount(LoginBase.LoginBase):

View file

@ -1,7 +1,7 @@
from pandac.PandaModules import * from pandac.PandaModules import *
from direct.distributed.MsgTypes import * from direct.distributed.MsgTypes import *
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import LoginBase from . import LoginBase
from direct.distributed.PyDatagram import PyDatagram from direct.distributed.PyDatagram import PyDatagram
class LoginGSAccount(LoginBase.LoginBase): class LoginGSAccount(LoginBase.LoginBase):

View file

@ -1,7 +1,7 @@
from pandac.PandaModules import * from pandac.PandaModules import *
from direct.distributed.MsgTypes import * from direct.distributed.MsgTypes import *
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import LoginBase from . import LoginBase
from direct.distributed.PyDatagram import PyDatagram from direct.distributed.PyDatagram import PyDatagram
class LoginGoAccount(LoginBase.LoginBase): class LoginGoAccount(LoginBase.LoginBase):

View file

@ -14,8 +14,8 @@ from otp.otpgui import OTPDialog
from otp.otpbase import OTPLocalizer from otp.otpbase import OTPLocalizer
from otp.otpbase import OTPGlobals from otp.otpbase import OTPGlobals
from otp.uberdog.AccountDetailRecord import AccountDetailRecord, SubDetailRecord from otp.uberdog.AccountDetailRecord import AccountDetailRecord, SubDetailRecord
import TTAccount from . import TTAccount
import GuiScreen from . import GuiScreen
class LoginScreen(StateData.StateData, GuiScreen.GuiScreen): class LoginScreen(StateData.StateData, GuiScreen.GuiScreen):
AutoLoginName = base.config.GetString('%s-auto-login%s' % (game.name, os.getenv('otp_client', '')), '') AutoLoginName = base.config.GetString('%s-auto-login%s' % (game.name, os.getenv('otp_client', '')), '')
@ -201,7 +201,7 @@ class LoginScreen(StateData.StateData, GuiScreen.GuiScreen):
self.cr.password = self.password self.cr.password = self.password
try: try:
error = self.loginInterface.authorize(self.userName, self.password) error = self.loginInterface.authorize(self.userName, self.password)
except TTAccount.TTAccountException, e: except TTAccount.TTAccountException as e:
self.fsm.request('showConnectionProblemDialog', [str(e)]) self.fsm.request('showConnectionProblemDialog', [str(e)])
return return

View file

@ -1,9 +1,9 @@
from pandac.PandaModules import * from pandac.PandaModules import *
from direct.distributed.MsgTypes import * from direct.distributed.MsgTypes import *
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import LoginBase from . import LoginBase
import TTAccount from . import TTAccount
from TTAccount import TTAccountException from .TTAccount import TTAccountException
from direct.distributed.PyDatagram import PyDatagram from direct.distributed.PyDatagram import PyDatagram
class LoginTTAccount(LoginBase.LoginBase, TTAccount.TTAccount): class LoginTTAccount(LoginBase.LoginBase, TTAccount.TTAccount):
@ -74,7 +74,7 @@ class LoginTTAccount(LoginBase.LoginBase, TTAccount.TTAccount):
if self.response.getInt('errorCode') in (5, 72): if self.response.getInt('errorCode') in (5, 72):
return (0, None) return (0, None)
return (0, errorMsg) return (0, errorMsg)
except TTAccountException, e: except TTAccountException as e:
return (0, str(e)) return (0, str(e))
elif self.useTTSpecificLogin: elif self.useTTSpecificLogin:
@ -85,7 +85,7 @@ class LoginTTAccount(LoginBase.LoginBase, TTAccount.TTAccount):
if self.response.getInt('errorCode') in (5, 72): if self.response.getInt('errorCode') in (5, 72):
return (0, None) return (0, None)
return (0, errorMsg) return (0, errorMsg)
except TTAccountException, e: except TTAccountException as e:
return (0, str(e)) return (0, str(e))
else: else:
@ -101,7 +101,7 @@ class LoginTTAccount(LoginBase.LoginBase, TTAccount.TTAccount):
if self.response.getInt('errorCode') in (5, 72): if self.response.getInt('errorCode') in (5, 72):
return (0, None) return (0, None)
return (0, errorMsg) return (0, errorMsg)
except TTAccountException, e: except TTAccountException as e:
return (0, str(e)) return (0, str(e))
else: else:

View file

@ -1,9 +1,9 @@
from pandac.PandaModules import * from pandac.PandaModules import *
from direct.distributed.MsgTypes import * from direct.distributed.MsgTypes import *
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import LoginTTAccount from . import LoginTTAccount
from direct.distributed.PyDatagram import PyDatagram from direct.distributed.PyDatagram import PyDatagram
from TTAccount import TTAccountException from .TTAccount import TTAccountException
class LoginTTSpecificDevAccount(LoginTTAccount.LoginTTAccount): class LoginTTSpecificDevAccount(LoginTTAccount.LoginTTAccount):
notify = DirectNotifyGlobal.directNotify.newCategory('LoginTTSpecificDevAccount') notify = DirectNotifyGlobal.directNotify.newCategory('LoginTTSpecificDevAccount')

View file

@ -1,6 +1,6 @@
from pandac.PandaModules import * from pandac.PandaModules import *
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import LoginTTAccount from . import LoginTTAccount
class LoginWebPlayTokenAccount(LoginTTAccount.LoginTTAccount): class LoginWebPlayTokenAccount(LoginTTAccount.LoginTTAccount):
notify = DirectNotifyGlobal.directNotify.newCategory('LoginWebPlayTokenAccount') notify = DirectNotifyGlobal.directNotify.newCategory('LoginWebPlayTokenAccount')
@ -39,7 +39,7 @@ class LoginWebPlayTokenAccount(LoginTTAccount.LoginTTAccount):
pass pass
def getErrorCode(self): def getErrorCode(self):
if not self.has_key('response'): if 'response' not in self:
return 0 return 0
return self.response.getInt('errorCode', 0) return self.response.getInt('errorCode', 0)

View file

@ -1,7 +1,7 @@
from pandac.PandaModules import * from pandac.PandaModules import *
from otp.otpbase.OTPGlobals import * from otp.otpbase.OTPGlobals import *
from direct.gui.DirectGui import * from direct.gui.DirectGui import *
from MultiPageTextFrame import * from .MultiPageTextFrame import *
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
from otp.otpbase import OTPLocalizer from otp.otpbase import OTPLocalizer
from otp.otpgui import OTPDialog from otp.otpgui import OTPDialog

View file

@ -1,6 +1,6 @@
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
import TTAccount from . import TTAccount
import HTTPUtil from . import HTTPUtil
class RemoteValueSet: class RemoteValueSet:
notify = DirectNotifyGlobal.directNotify.newCategory('RemoteValueSet') notify = DirectNotifyGlobal.directNotify.newCategory('RemoteValueSet')
@ -22,7 +22,7 @@ class RemoteValueSet:
continue continue
try: try:
name, value = line.split('=', 1) name, value = line.split('=', 1)
except ValueError, e: except ValueError as e:
errMsg = 'unexpected response: %s' % response errMsg = 'unexpected response: %s' % response
self.notify.warning(errMsg) self.notify.warning(errMsg)
onUnexpectedResponse(errMsg) onUnexpectedResponse(errMsg)
@ -34,7 +34,7 @@ class RemoteValueSet:
self.dict[name] = value self.dict[name] = value
for name in expectedFields: for name in expectedFields:
if not self.dict.has_key(name): if name not in self.dict:
errMsg = "missing expected field '%s'" % name errMsg = "missing expected field '%s'" % name
self.notify.warning(errMsg) self.notify.warning(errMsg)
onUnexpectedResponse(errMsg) onUnexpectedResponse(errMsg)
@ -46,7 +46,7 @@ class RemoteValueSet:
return 'RemoteValueSet:%s' % str(self.dict) return 'RemoteValueSet:%s' % str(self.dict)
def hasKey(self, key): def hasKey(self, key):
return self.dict.has_key(key) return key in self.dict
def getBool(self, name, default = None): def getBool(self, name, default = None):
return self.__getValue(name, lambda x: int(x) != 0, default) return self.__getValue(name, lambda x: int(x) != 0, default)

View file

@ -1,7 +1,7 @@
from pandac.PandaModules import * from pandac.PandaModules import *
from otp.otpbase.OTPGlobals import * from otp.otpbase.OTPGlobals import *
from direct.gui.DirectGui import * from direct.gui.DirectGui import *
from MultiPageTextFrame import * from .MultiPageTextFrame import *
from otp.otpbase import OTPLocalizer from otp.otpbase import OTPLocalizer
from otp.otpgui import OTPDialog from otp.otpgui import OTPDialog

View file

@ -3,19 +3,19 @@ from pandac.PandaModules import *
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
from direct.showbase import PythonUtil from direct.showbase import PythonUtil
from otp.otpbase import OTPLocalizer from otp.otpbase import OTPLocalizer
import HTTPUtil from . import HTTPUtil
import RemoteValueSet from . import RemoteValueSet
import copy import copy
accountServer = '' accountServer = ''
accountServer = launcher.getAccountServer() accountServer = launcher.getAccountServer()
print 'TTAccount: accountServer from launcher: ', accountServer print('TTAccount: accountServer from launcher: ', accountServer)
configAccountServer = base.config.GetString('account-server', '') configAccountServer = base.config.GetString('account-server', '')
if configAccountServer: if configAccountServer:
accountServer = configAccountServer accountServer = configAccountServer
print 'TTAccount: overriding accountServer from config: ', accountServer print('TTAccount: overriding accountServer from config: ', accountServer)
if not accountServer: if not accountServer:
accountServer = 'https://toontown.go.com' accountServer = 'https://toontown.go.com'
print 'TTAccount: default accountServer: ', accountServer print('TTAccount: default accountServer: ', accountServer)
accountServer = URLSpec(accountServer, 1) accountServer = URLSpec(accountServer, 1)
def getAccountServer(): def getAccountServer():
@ -55,7 +55,7 @@ class TTAccount:
if self.response.getInt('errorCode') in (5, 72): if self.response.getInt('errorCode') in (5, 72):
return (0, None) return (0, None)
return (0, errorMsg) return (0, errorMsg)
except TTAccountException, e: except TTAccountException as e:
return (0, str(e)) return (0, str(e))
return None return None
@ -71,7 +71,7 @@ class TTAccount:
if self.response.getInt('errorCode') in (5, 72): if self.response.getInt('errorCode') in (5, 72):
return (0, None) return (0, None)
return (0, errorMsg) return (0, errorMsg)
except TTAccountException, e: except TTAccountException as e:
return (0, str(e)) return (0, str(e))
return None return None
@ -85,7 +85,7 @@ class TTAccount:
if self.response.getInt('errorCode') in (5, 72): if self.response.getInt('errorCode') in (5, 72):
return (0, None) return (0, None)
return (0, errorMsg) return (0, errorMsg)
except TTAccountException, e: except TTAccountException as e:
return (0, str(e)) return (0, str(e))
return None return None
@ -117,8 +117,8 @@ class TTAccount:
'l2': 'addr2', 'l2': 'addr2',
'l3': 'addr3'} 'l3': 'addr3'}
dict = self.accountData.dict dict = self.accountData.dict
for fieldName in dict.keys(): for fieldName in list(dict.keys()):
if fieldNameMap.has_key(fieldName): if fieldName in fieldNameMap:
dict[fieldNameMap[fieldName]] = dict[fieldName] dict[fieldNameMap[fieldName]] = dict[fieldName]
del dict[fieldName] del dict[fieldName]
@ -154,7 +154,7 @@ class TTAccount:
def talk(self, operation, data = {}): def talk(self, operation, data = {}):
self.notify.debug('TTAccount.talk()') self.notify.debug('TTAccount.talk()')
for key in data.keys(): for key in list(data.keys()):
data[key] = str(data[key]) data[key] = str(data[key])
if operation in ('play', 'get', 'cancel', 'authenticateParentPassword', 'authenticateDelete', 'authenticateParentPasswordNewStyle', 'authenticateDeleteNewStyle'): if operation in ('play', 'get', 'cancel', 'authenticateParentPassword', 'authenticateDelete', 'authenticateParentPasswordNewStyle', 'authenticateDeleteNewStyle'):
@ -170,7 +170,7 @@ class TTAccount:
elif operation == 'create': elif operation == 'create':
pass pass
elif operation == 'purchase': elif operation == 'purchase':
if data.has_key('newPassword'): if 'newPassword' in data:
pass pass
else: else:
self.notify.error("Internal TTAccount error: need to add 'required data' checking for %s operation" % operation) self.notify.error("Internal TTAccount error: need to add 'required data' checking for %s operation" % operation)
@ -194,7 +194,7 @@ class TTAccount:
else: else:
url.setPath('/%s.php' % op2Php[operation]) url.setPath('/%s.php' % op2Php[operation])
body = '' body = ''
if data.has_key('accountName'): if 'accountName' in data:
if operation not in newWebOperations: if operation not in newWebOperations:
url.setQuery('n=%s' % URLSpec.quote(data['accountName'])) url.setQuery('n=%s' % URLSpec.quote(data['accountName']))
serverFields = {'accountName': 'n', serverFields = {'accountName': 'n',
@ -224,14 +224,14 @@ class TTAccount:
'userid': 'userid'} 'userid': 'userid'}
ignoredFields = ('ccType',) ignoredFields = ('ccType',)
outBoundFields = {} outBoundFields = {}
for fieldName in data.keys(): for fieldName in list(data.keys()):
if not serverFields.has_key(fieldName): if fieldName not in serverFields:
if fieldName not in ignoredFields: if fieldName not in ignoredFields:
self.notify.error('unknown data field: %s' % fieldName) self.notify.error('unknown data field: %s' % fieldName)
else: else:
outBoundFields[serverFields[fieldName]] = data[fieldName] outBoundFields[serverFields[fieldName]] = data[fieldName]
orderedFields = outBoundFields.keys() orderedFields = list(outBoundFields.keys())
orderedFields.sort() orderedFields.sort()
for fieldName in orderedFields: for fieldName in orderedFields:
if len(body): if len(body):
@ -274,7 +274,7 @@ class TTAccount:
if self.response.getInt('errorCode') in (5, 72): if self.response.getInt('errorCode') in (5, 72):
return (0, None) return (0, None)
return (0, errorMsg) return (0, errorMsg)
except TTAccountException, e: except TTAccountException as e:
return (0, str(e)) return (0, str(e))
return None return None

View file

@ -3,7 +3,7 @@ from libotp import CMover
from direct.directnotify import DirectNotifyGlobal from direct.directnotify import DirectNotifyGlobal
from otp.movement.PyVec3 import PyVec3 from otp.movement.PyVec3 import PyVec3
from direct.showbase import PythonUtil from direct.showbase import PythonUtil
import __builtin__ import builtins
class Mover(CMover): class Mover(CMover):
notify = DirectNotifyGlobal.directNotify.newCategory('Mover') notify = DirectNotifyGlobal.directNotify.newCategory('Mover')
@ -26,7 +26,7 @@ class Mover(CMover):
self.pscInt = PStatCollector(Mover.PSCInt) self.pscInt = PStatCollector(Mover.PSCInt)
def destroy(self): def destroy(self):
for name, impulse in self.impulses.items(): for name, impulse in list(self.impulses.items()):
Mover.notify.debug('removing impulse: %s' % name) Mover.notify.debug('removing impulse: %s' % name)
self.removeImpulse(name) self.removeImpulse(name)
@ -52,12 +52,12 @@ class Mover(CMover):
if Mover.Profile and not profile: if Mover.Profile and not profile:
def func(doMove = self.move): def func(doMove = self.move):
for i in xrange(10000): for i in range(10000):
doMove(dt, profile=1) doMove(dt, profile=1)
__builtin__.func = func builtins.func = func
PythonUtil.startProfile(cmd='func()', filename='profile', sorts=['cumulative'], callInfo=0) PythonUtil.startProfile(cmd='func()', filename='profile', sorts=['cumulative'], callInfo=0)
del __builtin__.func del builtins.func
return return
if Mover.Pstats: if Mover.Pstats:
self.pscCpp.start() self.pscCpp.start()
@ -65,7 +65,7 @@ class Mover(CMover):
if Mover.Pstats: if Mover.Pstats:
self.pscCpp.stop() self.pscCpp.stop()
self.pscPy.start() self.pscPy.start()
for impulse in self.impulses.values(): for impulse in list(self.impulses.values()):
impulse._process(self.getDt()) impulse._process(self.getDt())
if Mover.Pstats: if Mover.Pstats:

View file

@ -4,7 +4,7 @@ import math
class PyVec3: class PyVec3:
Epsilon = 0.0001 Epsilon = 0.0001
ScalarTypes = (types.FloatType, types.IntType, types.LongType) ScalarTypes = (float, int, int)
def __init__(self, *args): def __init__(self, *args):
self.assign(*args) self.assign(*args)

View file

@ -87,7 +87,7 @@ def checkName(name, otherCheckFuncs = [], font = None):
tn = TextNode('NameCheck') tn = TextNode('NameCheck')
tn.setFont(font) tn.setFont(font)
for c in name: for c in name:
if not tn.hasCharacter(unicode(c)): if not tn.hasCharacter(str(c)):
notify.info('name contains bad char: %s' % TextEncoder().encodeWtext(c)) notify.info('name contains bad char: %s' % TextEncoder().encodeWtext(c))
return OTPLocalizer.NCBadCharacter % TextEncoder().encodeWtext(c) return OTPLocalizer.NCBadCharacter % TextEncoder().encodeWtext(c)
@ -224,7 +224,7 @@ def checkName(name, otherCheckFuncs = [], font = None):
letters = justLetters(name) letters = justLetters(name)
if len(letters) > 2: if len(letters) > 2:
upperLetters = TextEncoder().decodeText(TextEncoder.upper(TextEncoder().encodeWtext(letters))) upperLetters = TextEncoder().decodeText(TextEncoder.upper(TextEncoder().encodeWtext(letters)))
for i in xrange(len(upperLetters)): for i in range(len(upperLetters)):
if not upperLetters[0].isupper(): if not upperLetters[0].isupper():
return return
@ -242,11 +242,11 @@ def checkName(name, otherCheckFuncs = [], font = None):
return OTPLocalizer.NCMixedCase return OTPLocalizer.NCMixedCase
def checkJapanese(name): def checkJapanese(name):
asciiSpace = range(32, 33) asciiSpace = list(range(32, 33))
asciiDigits = range(48, 64) asciiDigits = list(range(48, 64))
hiragana = range(12353, 12448) hiragana = list(range(12353, 12448))
katakana = range(12449, 12544) katakana = list(range(12449, 12544))
halfwidthKatakana = range(65381, 65440) halfwidthKatakana = list(range(65381, 65440))
halfwidthCharacter = set(asciiSpace + halfwidthKatakana) halfwidthCharacter = set(asciiSpace + halfwidthKatakana)
allowedUtf8 = set(asciiSpace + hiragana + katakana + halfwidthKatakana) allowedUtf8 = set(asciiSpace + hiragana + katakana + halfwidthKatakana)
@ -260,7 +260,7 @@ def checkName(name, otherCheckFuncs = [], font = None):
return OTPLocalizer.NCNoDigits return OTPLocalizer.NCNoDigits
else: else:
notify.info('name contains not allowed utf8 char: 0x%04x' % char) notify.info('name contains not allowed utf8 char: 0x%04x' % char)
return OTPLocalizer.NCBadCharacter % te.encodeWtext(unichr(char)) return OTPLocalizer.NCBadCharacter % te.encodeWtext(chr(char))
elif char in halfwidthCharacter: elif char in halfwidthCharacter:
dc += 0.5 dc += 0.5
else: else:
@ -316,7 +316,7 @@ def checkName(name, otherCheckFuncs = [], font = None):
nName = name[:] nName = name[:]
bName.reverse() bName.reverse()
problem = check(bName) problem = check(bName)
print 'problem = %s' % problem print('problem = %s' % problem)
if problem: if problem:
return problem return problem
@ -325,7 +325,7 @@ def checkName(name, otherCheckFuncs = [], font = None):
severity = notify.getSeverity() severity = notify.getSeverity()
notify.setSeverity(NSError) notify.setSeverity(NSError)
for i in xrange(32): for i in range(32):
pass pass
for c in '!"#$%&()*+/:;<=>?@[\\]^_`{|}~': for c in '!"#$%&()*+/:;<=>?@[\\]^_`{|}~':

View file

@ -15,11 +15,11 @@ class PickANamePattern:
def getNameString(self, pattern, gender): def getNameString(self, pattern, gender):
nameParts = self._getNameParts(gender) nameParts = self._getNameParts(gender)
invNameParts = [] invNameParts = []
for i in xrange(len(nameParts)): for i in range(len(nameParts)):
invNameParts.append(invertDict(nameParts[i])) invNameParts.append(invertDict(nameParts[i]))
name = '' name = ''
for i in xrange(len(pattern)): for i in range(len(pattern)):
if pattern[i] != -1: if pattern[i] != -1:
if len(name): if len(name):
name += ' ' name += ' '
@ -111,9 +111,9 @@ class PickANamePatternTwoPartLastName(PickANamePattern):
combinedIndex2indices = {} combinedIndex2indices = {}
lastNamePrefixesCapped = set(self._getLastNameCapPrefixes()) lastNamePrefixesCapped = set(self._getLastNameCapPrefixes())
k = 0 k = 0
for first, i in nameParts[-2].iteritems(): for first, i in nameParts[-2].items():
capitalize = first in lastNamePrefixesCapped capitalize = first in lastNamePrefixesCapped
for second, j in nameParts[-1].iteritems(): for second, j in nameParts[-1].items():
combinedLastName = first combinedLastName = first
if capitalize: if capitalize:
combinedLastName += second.capitalize() combinedLastName += second.capitalize()

View file

@ -1,6 +1,6 @@
from direct.showbase.ShowBase import ShowBase from direct.showbase.ShowBase import ShowBase
from pandac.PandaModules import Camera, TPLow, VBase4, ColorWriteAttrib, Filename, getModelPath, NodePath from pandac.PandaModules import Camera, TPLow, VBase4, ColorWriteAttrib, Filename, getModelPath, NodePath
import OTPRender from . import OTPRender
import time import time
import math import math
import re import re
@ -157,7 +157,7 @@ class OTPBase(ShowBase):
while self.pixelZoomCamMovedList and self.pixelZoomCamMovedList[0][0] < now - self.pixelZoomCamHistory: while self.pixelZoomCamMovedList and self.pixelZoomCamMovedList[0][0] < now - self.pixelZoomCamHistory:
del self.pixelZoomCamMovedList[0] del self.pixelZoomCamMovedList[0]
dist = sum(map(lambda pair: pair[1], self.pixelZoomCamMovedList)) dist = sum([pair[1] for pair in self.pixelZoomCamMovedList])
speed = dist / self.pixelZoomCamHistory speed = dist / self.pixelZoomCamHistory
if speed < 5: if speed < 5:
self.backgroundDrawable.setPixelZoom(4) self.backgroundDrawable.setPixelZoom(4)

View file

@ -132,8 +132,8 @@ def setFancyFont(path):
def getNametagFont(index): def getNametagFont(index):
global NametagFontPaths global NametagFontPaths
global NametagFonts global NametagFonts
if not NametagFonts.has_key(index) or NametagFonts[index] == None: if index not in NametagFonts or NametagFonts[index] == None:
if not NametagFontPaths.has_key(index) or NametagFontPaths[index] == None: if index not in NametagFontPaths or NametagFontPaths[index] == None:
InterfaceFont = TextNode.getDefaultFont() InterfaceFont = TextNode.getDefaultFont()
NametagFonts[index] = TextNode.getDefaultFont() NametagFonts[index] = TextNode.getDefaultFont()
else: else:

View file

@ -13,34 +13,34 @@ def getLanguage():
return language return language
print 'OTPLocalizer: Running in language: %s' % language print('OTPLocalizer: Running in language: %s' % language)
if language == 'english': if language == 'english':
_languageModule = 'otp.otpbase.OTPLocalizer' + string.capitalize(language) _languageModule = 'otp.otpbase.OTPLocalizer' + string.capitalize(language)
else: else:
checkLanguage = 1 checkLanguage = 1
_languageModule = 'otp.otpbase.OTPLocalizer_' + language _languageModule = 'otp.otpbase.OTPLocalizer_' + language
print 'from ' + _languageModule + ' import *' print('from ' + _languageModule + ' import *')
from otp.otpbase.OTPLocalizerEnglish import * from otp.otpbase.OTPLocalizerEnglish import *
if checkLanguage: if checkLanguage:
l = {} l = {}
g = {} g = {}
englishModule = __import__('otp.otpbase.OTPLocalizerEnglish', g, l) englishModule = __import__('otp.otpbase.OTPLocalizerEnglish', g, l)
foreignModule = __import__(_languageModule, g, l) foreignModule = __import__(_languageModule, g, l)
for key, val in englishModule.__dict__.items(): for key, val in list(englishModule.__dict__.items()):
if not foreignModule.__dict__.has_key(key): if key not in foreignModule.__dict__:
print 'WARNING: Foreign module: %s missing key: %s' % (_languageModule, key) print('WARNING: Foreign module: %s missing key: %s' % (_languageModule, key))
locals()[key] = val locals()[key] = val
elif isinstance(val, types.DictType): elif isinstance(val, dict):
fval = foreignModule.__dict__.get(key) fval = foreignModule.__dict__.get(key)
for dkey, dval in val.items(): for dkey, dval in list(val.items()):
if not fval.has_key(dkey): if dkey not in fval:
print 'WARNING: Foreign module: %s missing key: %s.%s' % (_languageModule, key, dkey) print('WARNING: Foreign module: %s missing key: %s.%s' % (_languageModule, key, dkey))
fval[dkey] = dval fval[dkey] = dval
for dkey in fval.keys(): for dkey in list(fval.keys()):
if not val.has_key(dkey): if dkey not in val:
print 'WARNING: Foreign module: %s extra key: %s.%s' % (_languageModule, key, dkey) print('WARNING: Foreign module: %s extra key: %s.%s' % (_languageModule, key, dkey))
for key in foreignModule.__dict__.keys(): for key in list(foreignModule.__dict__.keys()):
if not englishModule.__dict__.has_key(key): if key not in englishModule.__dict__:
print 'WARNING: Foreign module: %s extra key: %s' % (_languageModule, key) print('WARNING: Foreign module: %s extra key: %s' % (_languageModule, key))

View file

@ -33,16 +33,16 @@ class ObjectCount(Job):
yield None yield None
count2type = invertDictLossless(type2count) count2type = invertDictLossless(type2count)
yield None yield None
counts = count2type.keys() counts = list(count2type.keys())
yield None yield None
counts.sort() counts.sort()
yield None yield None
counts.reverse() counts.reverse()
yield None yield None
print '===== ObjectCount: \'%s\' =====' % (self.getJobName()) print('===== ObjectCount: \'%s\' =====' % (self.getJobName()))
for count in counts: for count in counts:
types = count2type[count] types = count2type[count]
for type in types: for type in types:
print '%s: %s' % (count, type) print('%s: %s' % (count, type))
yield None yield None
yield Job.Done yield Job.Done

View file

@ -1,4 +1,4 @@
import __builtin__ import builtins
import sys import sys
__all__ = ['enumerate', 'nonRepeatingRandomList', 'describeException', 'pdir', 'choice'] __all__ = ['enumerate', 'nonRepeatingRandomList', 'describeException', 'pdir', 'choice']
@ -14,16 +14,16 @@ if not hasattr(__builtin__, 'enumerate'):
implementation that returns a list of tuples that is completely implementation that returns a list of tuples that is completely
constructed every time enumerate() is called. constructed every time enumerate() is called.
""" """
return zip(xrange(len(L)), L) return list(zip(list(range(len(L))), L))
__builtin__.enumerate = enumerate builtins.enumerate = enumerate
else: else:
enumerate = __builtin__.enumerate enumerate = builtins.enumerate
def nonRepeatingRandomList(vals, max): def nonRepeatingRandomList(vals, max):
random.seed(time.time()) random.seed(time.time())
#first generate a set of random values #first generate a set of random values
valueList=range(max) valueList=list(range(max))
finalVals=[] finalVals=[]
for i in range(vals): for i in range(vals):
index=int(random.random()*len(valueList)) index=int(random.random()*len(valueList))
@ -46,7 +46,7 @@ def recordCreationStack(cls):
def getCreationStackTraceCompactStr(self): def getCreationStackTraceCompactStr(self):
return self._creationStackTrace.compact() return self._creationStackTrace.compact()
def printCreationStackTrace(self): def printCreationStackTrace(self):
print self._creationStackTrace print(self._creationStackTrace)
cls.__init__ = __recordCreationStack_init__ cls.__init__ = __recordCreationStack_init__
cls.getCreationStackTrace = getCreationStackTrace cls.getCreationStackTrace = getCreationStackTrace
cls.getCreationStackTraceCompactStr = getCreationStackTraceCompactStr cls.getCreationStackTraceCompactStr = getCreationStackTraceCompactStr
@ -120,7 +120,7 @@ def pdir(obj, str = None, width = None,
# Remove redundant class entries # Remove redundant class entries
uniqueLineage = [] uniqueLineage = []
for l in getClassLineage(obj): for l in getClassLineage(obj):
if type(l) == types.ClassType: if type(l) == type:
if l in uniqueLineage: if l in uniqueLineage:
break break
uniqueLineage.append(l) uniqueLineage.append(l)
@ -128,7 +128,7 @@ def pdir(obj, str = None, width = None,
uniqueLineage.reverse() uniqueLineage.reverse()
for obj in uniqueLineage: for obj in uniqueLineage:
_pdir(obj, str, width, fTruncate, lineWidth, wantPrivate) _pdir(obj, str, width, fTruncate, lineWidth, wantPrivate)
print print()
def choice(condition, ifTrue, ifFalse): def choice(condition, ifTrue, ifFalse):
# equivalent of C++ (condition ? ifTrue : ifFalse) # equivalent of C++ (condition ? ifTrue : ifFalse)
@ -153,6 +153,6 @@ def isClient():
return True return True
__builtin__.pdir = pdir builtins.pdir = pdir
__builtin__.isClient = isClient builtins.isClient = isClient
__builtin__.choice = choice builtins.choice = choice

View file

@ -51,11 +51,11 @@ def rgb2yuv(r, g, b):
y = 0.299 * r + 0.587 * g + 0.114 * b y = 0.299 * r + 0.587 * g + 0.114 * b
u = -.169 * r - 0.331 * g + 0.5 * b + 0.5 u = -.169 * r - 0.331 * g + 0.5 * b + 0.5
v = 0.5 * r - 0.419 * g - 0.081 * b + 0.5 v = 0.5 * r - 0.419 * g - 0.081 * b + 0.5
return tuple(map(lambda x: min(max(x, 0), 1), (y, u, v))) return tuple([min(max(x, 0), 1) for x in (y, u, v)])
def yuv2rgb(y, u, v): def yuv2rgb(y, u, v):
r = y - 0.0009267 * (u - 0.5) + 1.4016868 * (v - 0.5) r = y - 0.0009267 * (u - 0.5) + 1.4016868 * (v - 0.5)
g = y - 0.3436954 * (u - 0.5) - 0.714169 * (v - 0.5) g = y - 0.3436954 * (u - 0.5) - 0.714169 * (v - 0.5)
b = y + 1.7721604 * (u - 0.5) + 0.0009902 * (v - 0.5) b = y + 1.7721604 * (u - 0.5) + 0.0009902 * (v - 0.5)
return tuple(map(lambda x: min(max(x, 0), 1), (r, g, b))) return tuple([min(max(x, 0), 1) for x in (r, g, b)])

View file

@ -1,4 +1,4 @@
from ColorSpace import * from .ColorSpace import *
class SCColorScheme: class SCColorScheme:

View file

@ -1,5 +1,5 @@
from SCMenu import SCMenu from .SCMenu import SCMenu
from SCCustomTerminal import SCCustomTerminal from .SCCustomTerminal import SCCustomTerminal
from otp.otpbase.OTPLocalizer import CustomSCStrings from otp.otpbase.OTPLocalizer import CustomSCStrings
class SCCustomMenu(SCMenu): class SCCustomMenu(SCMenu):
@ -20,5 +20,5 @@ class SCCustomMenu(SCMenu):
return return
for msgIndex in lt.customMessages: for msgIndex in lt.customMessages:
if CustomSCStrings.has_key(msgIndex): if msgIndex in CustomSCStrings:
self.append(SCCustomTerminal(msgIndex)) self.append(SCCustomTerminal(msgIndex))

View file

@ -1,4 +1,4 @@
from SCTerminal import SCTerminal from .SCTerminal import SCTerminal
from otp.otpbase.OTPLocalizer import CustomSCStrings from otp.otpbase.OTPLocalizer import CustomSCStrings
SCCustomMsgEvent = 'SCCustomMsg' SCCustomMsgEvent = 'SCCustomMsg'

View file

@ -1,3 +1,3 @@
from SCStaticTextTerminal import decodeSCStaticTextMsg from .SCStaticTextTerminal import decodeSCStaticTextMsg
from SCCustomTerminal import decodeSCCustomMsg from .SCCustomTerminal import decodeSCCustomMsg
from SCEmoteTerminal import decodeSCEmoteWhisperMsg from .SCEmoteTerminal import decodeSCEmoteWhisperMsg

View file

@ -1,8 +1,8 @@
from pandac.PandaModules import * from pandac.PandaModules import *
from direct.gui.DirectGui import * from direct.gui.DirectGui import *
from direct.task import Task from direct.task import Task
from SCConstants import * from .SCConstants import *
from SCObject import SCObject from .SCObject import SCObject
from direct.showbase.PythonUtil import boolEqual from direct.showbase.PythonUtil import boolEqual
from otp.otpbase import OTPGlobals from otp.otpbase import OTPGlobals
@ -137,7 +137,7 @@ class SCElement(SCObject, NodePath):
del self.button del self.button
halfHeight = self.height / 2.0 halfHeight = self.height / 2.0
textX = 0 textX = 0
if dbArgs.has_key('text_align'): if 'text_align' in dbArgs:
if dbArgs['text_align'] == TextNode.ACenter: if dbArgs['text_align'] == TextNode.ACenter:
textX = self.width / 2.0 textX = self.width / 2.0
args = {'text': self.getDisplayText(), args = {'text': self.getDisplayText(),

View file

@ -1,5 +1,5 @@
from SCMenu import SCMenu from .SCMenu import SCMenu
from SCEmoteTerminal import SCEmoteTerminal from .SCEmoteTerminal import SCEmoteTerminal
class SCEmoteMenu(SCMenu): class SCEmoteMenu(SCMenu):

View file

@ -1,5 +1,5 @@
from direct.gui.DirectGui import * from direct.gui.DirectGui import *
from SCTerminal import SCTerminal from .SCTerminal import SCTerminal
from otp.otpbase.OTPLocalizer import EmoteList, EmoteWhispers from otp.otpbase.OTPLocalizer import EmoteList, EmoteWhispers
from otp.avatar import Emote from otp.avatar import Emote
SCEmoteMsgEvent = 'SCEmoteMsg' SCEmoteMsgEvent = 'SCEmoteMsg'

View file

@ -1,4 +1,4 @@
from SCTerminal import SCTerminal from .SCTerminal import SCTerminal
from otp.speedchat import SpeedChatGMHandler from otp.speedchat import SpeedChatGMHandler
SCGMTextMsgEvent = 'SCGMTextMsg' SCGMTextMsgEvent = 'SCGMTextMsg'

View file

@ -1,9 +1,9 @@
from pandac.PandaModules import * from pandac.PandaModules import *
from direct.gui.DirectGui import * from direct.gui.DirectGui import *
from direct.task import Task from direct.task import Task
from SCConstants import * from .SCConstants import *
from direct.interval.IntervalGlobal import * from direct.interval.IntervalGlobal import *
from SCObject import SCObject from .SCObject import SCObject
from direct.showbase.PythonUtil import makeTuple from direct.showbase.PythonUtil import makeTuple
import types import types
@ -94,14 +94,14 @@ class SCMenu(SCObject, NodePath):
self.appendFromStructure(structure) self.appendFromStructure(structure)
def appendFromStructure(self, structure): def appendFromStructure(self, structure):
from SpeedChatTypes import SCMenuHolder, SCStaticTextTerminal, SCGMTextTerminal from .SpeedChatTypes import SCMenuHolder, SCStaticTextTerminal, SCGMTextTerminal
from otp.otpbase import OTPLocalizer from otp.otpbase import OTPLocalizer
def addChildren(menu, childList): def addChildren(menu, childList):
for child in childList: for child in childList:
emote = None emote = None
if type(child) == type({}): if type(child) == type({}):
item = child.keys()[0] item = list(child.keys())[0]
emote = child[item] emote = child[item]
child = item child = item
if type(child) == type(0): if type(child) == type(0):
@ -119,7 +119,7 @@ class SCMenu(SCObject, NodePath):
subMenu = menuType() subMenu = menuType()
subMenuChildren = child[2:] subMenuChildren = child[2:]
if emote: if emote:
print 'warning: tried to link emote %s to a menu holder' % emote print('warning: tried to link emote %s to a menu holder' % emote)
holder = SCMenuHolder(holderTitle, menu=subMenu) holder = SCMenuHolder(holderTitle, menu=subMenu)
menu.append(holder) menu.append(holder)
addChildren(subMenu, subMenuChildren) addChildren(subMenu, subMenuChildren)
@ -293,7 +293,7 @@ class SCMenu(SCObject, NodePath):
maxWidth = max(maxWidth, widthToCover) maxWidth = max(maxWidth, widthToCover)
memberWidth, memberHeight = maxWidth, maxHeight memberWidth, memberHeight = maxWidth, maxHeight
self.width = maxWidth self.width = maxWidth
for i in xrange(len(visibleMembers)): for i in range(len(visibleMembers)):
member = visibleMembers[i] member = visibleMembers[i]
member.setPos(0, 0, -i * maxHeight) member.setPos(0, 0, -i * maxHeight)
member.setDimensions(memberWidth, memberHeight) member.setDimensions(memberWidth, memberHeight)
@ -347,7 +347,7 @@ class SCMenu(SCObject, NodePath):
return return
def append(self, element): def append(self, element):
if isinstance(self.__members, types.TupleType): if isinstance(self.__members, tuple):
self.__members = list(self.__members) self.__members = list(self.__members)
self.__members.append(element) self.__members.append(element)
self.privMemberListChanged(added=[element]) self.privMemberListChanged(added=[element])
@ -365,40 +365,40 @@ class SCMenu(SCObject, NodePath):
return self.__members[index] return self.__members[index]
def __setitem__(self, index, value): def __setitem__(self, index, value):
if isinstance(self.__members, types.TupleType): if isinstance(self.__members, tuple):
self.__members = list(self.__members) self.__members = list(self.__members)
removedMember = self.__members[index] removedMember = self.__members[index]
self.__members[index] = value self.__members[index] = value
self.privMemberListChanged(added=[value], removed=[removedMember]) self.privMemberListChanged(added=[value], removed=[removedMember])
def __delitem__(self, index): def __delitem__(self, index):
if isinstance(self.__members, types.TupleType): if isinstance(self.__members, tuple):
self.__members = list(self.__members) self.__members = list(self.__members)
removedMember = self.__members[index] removedMember = self.__members[index]
del self.__members[index] del self.__members[index]
self.privMemberListChanged(removed=[removedMember]) self.privMemberListChanged(removed=[removedMember])
def __getslice__(self, i, j): def __getslice__(self, i, j):
if isinstance(self.__members, types.TupleType): if isinstance(self.__members, tuple):
self.__members = list(self.__members) self.__members = list(self.__members)
return self.__members[i:j] return self.__members[i:j]
def __setslice__(self, i, j, s): def __setslice__(self, i, j, s):
if isinstance(self.__members, types.TupleType): if isinstance(self.__members, tuple):
self.__members = list(self.__members) self.__members = list(self.__members)
removedMembers = self.__members[i:j] removedMembers = self.__members[i:j]
self.__members[i:j] = list(s) self.__members[i:j] = list(s)
self.privMemberListChanged(added=list(s), removed=removedMembers) self.privMemberListChanged(added=list(s), removed=removedMembers)
def __delslice__(self, i, j): def __delslice__(self, i, j):
if isinstance(self.__members, types.TupleType): if isinstance(self.__members, tuple):
self.__members = list(self.__members) self.__members = list(self.__members)
removedMembers = self.__members[i:j] removedMembers = self.__members[i:j]
del self.__members[i:j] del self.__members[i:j]
self.privMemberListChanged(removed=removedMembers) self.privMemberListChanged(removed=removedMembers)
def __iadd__(self, other): def __iadd__(self, other):
if isinstance(self.__members, types.TupleType): if isinstance(self.__members, tuple):
self.__members = list(self.__members) self.__members = list(self.__members)
if isinstance(other, SCMenu): if isinstance(other, SCMenu):
otherMenu = other otherMenu = other

View file

@ -1,8 +1,8 @@
from pandac.PandaModules import * from pandac.PandaModules import *
from direct.gui.DirectGui import * from direct.gui.DirectGui import *
from SCObject import SCObject from .SCObject import SCObject
from SCElement import SCElement from .SCElement import SCElement
from SCMenu import SCMenu from .SCMenu import SCMenu
import types import types
class SCMenuHolder(SCElement): class SCMenuHolder(SCElement):

Some files were not shown because too many files have changed in this diff Show more