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__['ostream'] = Notify.out()
__builtins__['run'] = simbase.run

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,7 +1,7 @@
from pandac.PandaModules import *
from direct.gui.DirectGui import *
from direct.showbase import DirectObject
import Avatar
from . import Avatar
from direct.distributed import DistributedObject
class AvatarPanel(DirectObject.DirectObject):
@ -27,7 +27,7 @@ class AvatarPanel(DirectObject.DirectObject):
self.avDisableName = avatar.uniqueName('disable')
self.avGenerateName = avatar.uniqueName('generate')
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]
else:
self.avDisableName = None

View file

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

View file

@ -133,10 +133,10 @@ class DistributedPlayer(DistributedAvatar.DistributedAvatar, PlayerBase.PlayerBa
self.displayWhisper(aboutId, 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):
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):
if toPlayer:
@ -191,7 +191,7 @@ class DistributedPlayer(DistributedAvatar.DistributedAvatar, PlayerBase.PlayerBa
return
def whisperSCEmoteTo(self, emoteId, sendToId, toPlayer):
print 'whisperSCEmoteTo %s %s %s' % (emoteId, sendToId, toPlayer)
print('whisperSCEmoteTo %s %s %s' % (emoteId, sendToId, toPlayer))
if toPlayer:
base.cr.playerFriendsManager.sendSCEmoteWhisper(sendToId, emoteId)
return
@ -253,7 +253,7 @@ class DistributedPlayer(DistributedAvatar.DistributedAvatar, PlayerBase.PlayerBa
return
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):
return chat

View file

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

View file

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

View file

@ -18,7 +18,7 @@ class SpeedMonitor:
taskMgr.remove(self._trackTask)
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):
token = self._allocToken()
@ -46,7 +46,7 @@ class SpeedMonitor:
(nodepath.getPos(), globalClock.getFrameTime() - SpeedMonitor.TrackingPeriod, 0.0)]
def _trackSpeedsTask(self, task = None):
for (token, nodepath) in self._nodepaths.iteritems():
for (token, nodepath) in self._nodepaths.items():
curT = globalClock.getFrameTime()
curPos = nodepath.getPos()
while len(self._prevPosQueue[token]) > 1:

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -10,7 +10,7 @@ class CentralLogger(DistributedObjectGlobal):
PlayersReportedThisSession = {}
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'):
if self.hasReportedPlayer(targetDISLId, targetAvId):

View file

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

View file

@ -20,7 +20,7 @@ class DistributedDistrict(DistributedObject):
def delete(self):
if base.cr.distributedDistrict is self:
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]
DistributedObject.delete(self)
messenger.send('shardInfoUpdated')

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -2,9 +2,9 @@ from pandac import PandaModules as PM
from otp.ai.AIBaseGlobal import *
from direct.distributed.ClockDelta import *
from direct.distributed import DistributedObjectAI
import Level
from . import Level
from direct.directnotify import DirectNotifyGlobal
import EntityCreatorAI
from . import EntityCreatorAI
from direct.showbase.PythonUtil import Functor, weightedChoice
class DistributedLevelAI(DistributedObjectAI.DistributedObjectAI, Level.Level):
@ -64,7 +64,7 @@ class DistributedLevelAI(DistributedObjectAI.DistributedObjectAI, Level.Level):
def initializeLevel(self, levelSpec):
self.startTime = globalClock.getRealTime()
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)
Level.Level.initializeLevel(self, self.doId, levelSpec, scenarioIndex)
if __dev__:

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -9,19 +9,19 @@ class EntityCreatorBase:
def createEntity(self, 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))
ent = self.doCreateEntity(self.entType2Ctor[entType], entId)
return ent
def getEntityTypes(self):
return self.entType2Ctor.keys()
return list(self.entType2Ctor.keys())
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.entType2Ctor[entType] = ctor
def privRegisterTypes(self, type2ctor):
for entType, ctor in type2ctor.items():
for entType, ctor in list(type2ctor.items()):
self.privRegisterType(entType, ctor)

View file

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

View file

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

View file

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

View file

@ -1,6 +1,6 @@
from toontown.toonbase.ToontownGlobals import *
from direct.directnotify import DirectNotifyGlobal
import BasicEntities
from . import BasicEntities
class EntrancePoint(BasicEntities.NodePathEntity):
@ -29,7 +29,7 @@ class EntrancePoint(BasicEntities.NodePathEntity):
def destroyEntrancePoint(self):
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]
if __dev__:

View file

@ -1,6 +1,6 @@
from direct.directnotify import DirectNotifyGlobal
import string
import LevelConstants
from . import LevelConstants
from direct.showbase.PythonUtil import lineInfo, uniqueElements
import types
@ -119,7 +119,7 @@ class Level:
def initializeEntity(self, entity):
entId = entity.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'):
continue
entity.setAttribInit(key, value)

View file

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

View file

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

View file

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

View file

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

View file

@ -1,5 +1,5 @@
import string
import LevelConstants
from . import LevelConstants
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 direct.directnotify import DirectNotifyGlobal

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -14,8 +14,8 @@ from otp.otpgui import OTPDialog
from otp.otpbase import OTPLocalizer
from otp.otpbase import OTPGlobals
from otp.uberdog.AccountDetailRecord import AccountDetailRecord, SubDetailRecord
import TTAccount
import GuiScreen
from . import TTAccount
from . import GuiScreen
class LoginScreen(StateData.StateData, GuiScreen.GuiScreen):
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
try:
error = self.loginInterface.authorize(self.userName, self.password)
except TTAccount.TTAccountException, e:
except TTAccount.TTAccountException as e:
self.fsm.request('showConnectionProblemDialog', [str(e)])
return

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,6 +1,6 @@
from direct.showbase.ShowBase import ShowBase
from pandac.PandaModules import Camera, TPLow, VBase4, ColorWriteAttrib, Filename, getModelPath, NodePath
import OTPRender
from . import OTPRender
import time
import math
import re
@ -157,7 +157,7 @@ class OTPBase(ShowBase):
while self.pixelZoomCamMovedList and self.pixelZoomCamMovedList[0][0] < now - self.pixelZoomCamHistory:
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
if speed < 5:
self.backgroundDrawable.setPixelZoom(4)

View file

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

View file

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

View file

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

View file

@ -1,4 +1,4 @@
import __builtin__
import builtins
import sys
__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
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:
enumerate = __builtin__.enumerate
enumerate = builtins.enumerate
def nonRepeatingRandomList(vals, max):
random.seed(time.time())
#first generate a set of random values
valueList=range(max)
valueList=list(range(max))
finalVals=[]
for i in range(vals):
index=int(random.random()*len(valueList))
@ -46,7 +46,7 @@ def recordCreationStack(cls):
def getCreationStackTraceCompactStr(self):
return self._creationStackTrace.compact()
def printCreationStackTrace(self):
print self._creationStackTrace
print(self._creationStackTrace)
cls.__init__ = __recordCreationStack_init__
cls.getCreationStackTrace = getCreationStackTrace
cls.getCreationStackTraceCompactStr = getCreationStackTraceCompactStr
@ -120,7 +120,7 @@ def pdir(obj, str = None, width = None,
# Remove redundant class entries
uniqueLineage = []
for l in getClassLineage(obj):
if type(l) == types.ClassType:
if type(l) == type:
if l in uniqueLineage:
break
uniqueLineage.append(l)
@ -128,7 +128,7 @@ def pdir(obj, str = None, width = None,
uniqueLineage.reverse()
for obj in uniqueLineage:
_pdir(obj, str, width, fTruncate, lineWidth, wantPrivate)
print
print()
def choice(condition, ifTrue, ifFalse):
# equivalent of C++ (condition ? ifTrue : ifFalse)
@ -153,6 +153,6 @@ def isClient():
return True
__builtin__.pdir = pdir
__builtin__.isClient = isClient
__builtin__.choice = choice
builtins.pdir = pdir
builtins.isClient = isClient
builtins.choice = choice

View file

@ -51,11 +51,11 @@ def rgb2yuv(r, g, b):
y = 0.299 * r + 0.587 * g + 0.114 * b
u = -.169 * r - 0.331 * g + 0.5 * 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):
r = y - 0.0009267 * (u - 0.5) + 1.4016868 * (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)
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:

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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