diff --git a/.gitignore b/.gitignore index 4f5ffa74b..0b616ce0e 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,4 @@ pip-delete-this-directory.txt # IDEA pycharm/intellij .idea/ +.DS_Store diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..a2b5774ee --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "discord.removeRemoteRepository": true, + "discord.lowerDetailsEditing": "line: {current_line}" +} \ No newline at end of file diff --git a/dependencies/astron/darwin/astrond b/dependencies/astron/darwin/astrond new file mode 100755 index 000000000..3cf36c183 Binary files /dev/null and b/dependencies/astron/darwin/astrond differ diff --git a/dependencies/astron/darwin/astrond-arm b/dependencies/astron/darwin/astrond-arm new file mode 100755 index 000000000..e7fbef77d Binary files /dev/null and b/dependencies/astron/darwin/astrond-arm differ diff --git a/dependencies/astron/darwin/libbson-1.0.0.0.0.dylib b/dependencies/astron/darwin/libbson-1.0.0.0.0.dylib new file mode 100644 index 000000000..80e369dd7 Binary files /dev/null and b/dependencies/astron/darwin/libbson-1.0.0.0.0.dylib differ diff --git a/dependencies/astron/darwin/libbsoncxx.3.6.5.dylib b/dependencies/astron/darwin/libbsoncxx.3.6.5.dylib new file mode 100644 index 000000000..94de9573e Binary files /dev/null and b/dependencies/astron/darwin/libbsoncxx.3.6.5.dylib differ diff --git a/dependencies/astron/darwin/libmongoc-1.0.0.0.0.dylib b/dependencies/astron/darwin/libmongoc-1.0.0.0.0.dylib new file mode 100644 index 000000000..f88e22fa2 Binary files /dev/null and b/dependencies/astron/darwin/libmongoc-1.0.0.0.0.dylib differ diff --git a/dependencies/astron/darwin/libmongocxx.3.6.5.dylib b/dependencies/astron/darwin/libmongocxx.3.6.5.dylib new file mode 100644 index 000000000..0e62739a3 Binary files /dev/null and b/dependencies/astron/darwin/libmongocxx.3.6.5.dylib differ diff --git a/dependencies/astron/darwin/libuv.1.dylib b/dependencies/astron/darwin/libuv.1.dylib new file mode 100644 index 000000000..c58bd0647 Binary files /dev/null and b/dependencies/astron/darwin/libuv.1.dylib differ diff --git a/dependencies/astron/darwin/libyaml-cpp.0.6.3.dylib b/dependencies/astron/darwin/libyaml-cpp.0.6.3.dylib new file mode 100644 index 000000000..6853d013a Binary files /dev/null and b/dependencies/astron/darwin/libyaml-cpp.0.6.3.dylib differ diff --git a/dependencies/config/general.prc b/dependencies/config/general.prc index 6b79e4128..e6b402c43 100644 --- a/dependencies/config/general.prc +++ b/dependencies/config/general.prc @@ -11,7 +11,7 @@ notify-level-DistributedNPCScientistAI info want-pstats #f # Audio: -audio-library-name p3fmod_audio +audio-library-name p3openal_audio # Graphics: aux-display pandagl diff --git a/otp/ai/AIZoneData.py b/otp/ai/AIZoneData.py index 266dd795c..054eb0a9c 100644 --- a/otp/ai/AIZoneData.py +++ b/otp/ai/AIZoneData.py @@ -42,7 +42,7 @@ def __str__(self): output += '\n' totalColliders = 0 totalTraversers = 0 - for currCollTrav in self._collTravs.values(): + for currCollTrav in list(self._collTravs.values()): totalTraversers += 1 totalColliders += currCollTrav.getNumColliders() @@ -183,7 +183,7 @@ def __init__(self): 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 diff --git a/otp/ai/BanManagerAI.py b/otp/ai/BanManagerAI.py index da17455a3..a1f64ff49 100644 --- a/otp/ai/BanManagerAI.py +++ b/otp/ai/BanManagerAI.py @@ -7,7 +7,7 @@ from otp.ai.MagicWordGlobal import * from direct.showbase.DirectObject import DirectObject import threading -import httplib +import http.client class BanFSM(FSM): @@ -23,7 +23,7 @@ def __init__(self, air, avId): def performBan(self): self.ejectPlayer() - print(self.accountId) + print((self.accountId)) def ejectPlayer(self): av = self.air.doId2do.get(self.avId) diff --git a/otp/ai/GarbageLeakServerEventAggregator.py b/otp/ai/GarbageLeakServerEventAggregator.py index f6d413797..41196a5aa 100644 --- a/otp/ai/GarbageLeakServerEventAggregator.py +++ b/otp/ai/GarbageLeakServerEventAggregator.py @@ -31,7 +31,7 @@ def _stopSending(self): self._doLaterName = None def _sendLeaks(self, task = None): - for desc, curNum in self._curLeakDesc2num.iteritems(): + for desc, curNum in list(self._curLeakDesc2num.items()): self._sentLeakDesc2num.setdefault(desc, 0) num = curNum - self._sentLeakDesc2num[desc] if num > 0: diff --git a/otp/ai/MagicWordGlobal.py b/otp/ai/MagicWordGlobal.py index 6d829a50a..c7dadad9f 100644 --- a/otp/ai/MagicWordGlobal.py +++ b/otp/ai/MagicWordGlobal.py @@ -107,8 +107,8 @@ def __init__(self, name, func, types, access, doc): self.doc = doc def parseArgs(self, string): - maxArgs = self.func.func_code.co_argcount - minArgs = maxArgs - (len(self.func.func_defaults) if self.func.func_defaults else 0) + maxArgs = self.func.__code__.co_argcount + minArgs = maxArgs - (len(self.func.__defaults__) if self.func.__defaults__ else 0) args = string.split(None, maxArgs-1)[:maxArgs] if len(args) < minArgs: @@ -153,7 +153,7 @@ def __call__(self, mw): name = self.name if name is None: - name = mw.func_name + name = mw.__name__ word = MagicWord(name, mw, self.types, self.access, mw.__doc__) spellbook.addWord(word) diff --git a/otp/ai/MagicWordManagerAI.py b/otp/ai/MagicWordManagerAI.py index 750ad21f7..9d0397192 100644 --- a/otp/ai/MagicWordManagerAI.py +++ b/otp/ai/MagicWordManagerAI.py @@ -49,7 +49,7 @@ def sendMagicWord(self, word, targetId): if not os.path.exists('user/logs/mw'): os.makedirs('user/logs/mw') - print("%s | %s : %s\n" % (now, invokerId, word)) + print(("%s | %s : %s\n" % (now, invokerId, word))) if os.getenv('DISTRICT_NAME', 'Test Canvas') == "Test Canvas": return @@ -60,7 +60,7 @@ def sendMagicWord(self, word, targetId): @magicWord(category=CATEGORY_COMMUNITY_MANAGER, types=[str]) def help(wordName=None): - print 'help called with %s' % (wordName) + print(('help called with %s' % (wordName))) if not wordName: return "What were you interested getting help for?" word = spellbook.words.get(wordName.lower()) # look it up by its lower case value diff --git a/otp/ai/TimeManager.py b/otp/ai/TimeManager.py index d7bf967ec..8de0cba61 100644 --- a/otp/ai/TimeManager.py +++ b/otp/ai/TimeManager.py @@ -272,7 +272,7 @@ def d_setFrameRate(self, fps, deviation, numAvs, locationCode, timeInLocation, t '%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, @@ -337,7 +337,7 @@ def getMacOsInfo(self, defaultOsInfo): 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)) diff --git a/otp/avatar/DistributedAvatar.py b/otp/avatar/DistributedAvatar.py index 1696e2cc3..7884a082a 100644 --- a/otp/avatar/DistributedAvatar.py +++ b/otp/avatar/DistributedAvatar.py @@ -4,7 +4,7 @@ from toontown.toonbase import ToonPythonUtil as PythonUtil from direct.task import Task from pandac.PandaModules import * -from Avatar import Avatar +from .Avatar import Avatar from otp.ai.MagicWordGlobal import * from otp.otpbase import OTPGlobals from toontown.battle.BattleProps import globalPropPool diff --git a/otp/avatar/DistributedPlayer.py b/otp/avatar/DistributedPlayer.py index 697360210..75e07b2ca 100644 --- a/otp/avatar/DistributedPlayer.py +++ b/otp/avatar/DistributedPlayer.py @@ -136,10 +136,10 @@ def setSystemMessage(self, aboutId, chatString, whisperType = WTSystem): 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): messenger.send('wakeup') @@ -239,7 +239,7 @@ def setTalkWhisper(self, fromAV, fromAC, avatarName, chat, mods, flags): base.talkAssistant.receiveWhisperTalk(fromAV, avatarName, fromAC, None, self.doId, self.getName(), newText, scrubbed) 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 diff --git a/otp/avatar/DistributedPlayerAI.py b/otp/avatar/DistributedPlayerAI.py index a1dbe188d..5dd76fc39 100644 --- a/otp/avatar/DistributedPlayerAI.py +++ b/otp/avatar/DistributedPlayerAI.py @@ -278,7 +278,7 @@ def accessLevel(accessLevel, storage='PERSISTENT', showGM=1): if accessLevel not in accessName2Id: return 'Invalid access level!' accessLevel = accessName2Id[accessLevel] - if accessLevel not in accessName2Id.values(): + if accessLevel not in list(accessName2Id.values()): return 'Invalid access level!' target = spellbook.getTarget() invoker = spellbook.getInvoker() diff --git a/otp/avatar/Emote.py b/otp/avatar/Emote.py index 2a6e89372..e0e656807 100644 --- a/otp/avatar/Emote.py +++ b/otp/avatar/Emote.py @@ -10,7 +10,7 @@ def __init__(self): return def isEnabled(self, index): - if isinstance(index, types.StringType): + if isinstance(index, bytes): index = OTPLocalizer.EmoteFuncDict[index] if self.emoteFunc == None: return 0 diff --git a/otp/avatar/LocalAvatar.py b/otp/avatar/LocalAvatar.py index 4c9598f94..6aad29aa1 100644 --- a/otp/avatar/LocalAvatar.py +++ b/otp/avatar/LocalAvatar.py @@ -591,22 +591,7 @@ def removeCameraPosition(self): self.cameraPositions.remove(camPos) self.nextCameraPos(1) - def printCameraPositions(self): - print '[' - for i in xrange(len(self.cameraPositions)): - self.printCameraPosition(i) - 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 ')', + def posCamera(self, lerp, time): if not lerp: @@ -1165,7 +1150,7 @@ def printCamPos(self): 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() @@ -1232,7 +1217,7 @@ def d_setParent(self, parentToken): DistributedSmoothNode.DistributedSmoothNode.d_setParent(self, parentToken) def handlePlayerFriendWhisper(self, playerId, charMessage): - print 'handlePlayerFriendWhisper' + print('handlePlayerFriendWhisper') self.displayWhisperPlayer(playerId, charMessage, WTNormal) def canChat(self): diff --git a/otp/chat/ChatAgentAI.py b/otp/chat/ChatAgentAI.py index c77f561e5..7ca7b711b 100644 --- a/otp/chat/ChatAgentAI.py +++ b/otp/chat/ChatAgentAI.py @@ -6,7 +6,7 @@ from direct.distributed.MsgTypes import * from time import gmtime, strftime import json -import httplib +import http.client import six def to_bool(boolorstr): @@ -58,7 +58,7 @@ def chatMessage(self, message, fakeChatMode): self.sendUpdate('chatMessageAiToUd', [sender, message, chatMode]) def chatMessageResponse(self, sender, message, modifications, chatMode): - if sender not in self.air.doId2do.keys(): + if sender not in list(self.air.doId2do.keys()): # found an invalid sender! return diff --git a/otp/chat/ChatGarbler.py b/otp/chat/ChatGarbler.py index 56a2883ad..034c1ceb5 100644 --- a/otp/chat/ChatGarbler.py +++ b/otp/chat/ChatGarbler.py @@ -8,7 +8,7 @@ def garble(self, avatar, message): newMessage = '' numWords = random.randint(1, 7) wordlist = OTPLocalizer.ChatGarblerDefault - for i in xrange(1, numWords + 1): + for i in range(1, numWords + 1): wordIndex = random.randint(0, len(wordlist) - 1) newMessage = newMessage + wordlist[wordIndex] if i < numWords: @@ -20,7 +20,7 @@ def garbleSingle(self, avatar, message): newMessage = '' numWords = 1 wordlist = OTPLocalizer.ChatGarblerDefault - for i in xrange(1, numWords + 1): + for i in range(1, numWords + 1): wordIndex = random.randint(0, len(wordlist) - 1) newMessage = newMessage + wordlist[wordIndex] if i < numWords: diff --git a/otp/chat/TalkAssistant.py b/otp/chat/TalkAssistant.py index 1cb13e144..85cf26fb0 100644 --- a/otp/chat/TalkAssistant.py +++ b/otp/chat/TalkAssistant.py @@ -229,12 +229,12 @@ def fillWithTestText(self): self.floodThreshold = hold 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 checkOpenTypedChat(self): if base.localAvatar.commonChatFlags & OTPGlobals.CommonChat: @@ -653,7 +653,7 @@ def sendGuildTalk(self, message): if self.checkGuildTypedChat(): base.cr.guildManager.sendTalk(message) else: - print 'Guild chat error' + print('Guild chat error') error = ERROR_NO_GUILD_CHAT return error @@ -722,7 +722,7 @@ def sendGuildSpeedChat(self, type, msgIndex): if self.checkGuildSpeedChat(): base.cr.guildManager.sendSC(msgIndex) else: - print 'Guild Speedchat error' + print('Guild Speedchat error') error = ERROR_NO_GUILD_CHAT return error diff --git a/otp/distributed/ClientRepositoryBaseOR.py b/otp/distributed/ClientRepositoryBaseOR.py index 99e2650ea..f93af4084 100644 --- a/otp/distributed/ClientRepositoryBaseOR.py +++ b/otp/distributed/ClientRepositoryBaseOR.py @@ -516,7 +516,7 @@ def getObjectsOfClass(self, objClass): """ returns dict of doId:object, containing all objects that inherit from 'class'. returned dict is safely mutable. """ doDict = {} - for doId, do in self.doId2do.items(): + for doId, do in list(self.doId2do.items()): if isinstance(do, objClass): doDict[doId] = do return doDict @@ -526,7 +526,7 @@ def getObjectsOfExactClass(self, objClass): are exactly of type 'class' (neglecting inheritance). returned dict is safely mutable. """ doDict = {} - for doId, do in self.doId2do.items(): + for doId, do in list(self.doId2do.items()): if do.__class__ == objClass: doDict[doId] = do return doDict @@ -604,6 +604,6 @@ def _removeDelayDeletedDO(self, do): def printDelayDeletes(self): print('DelayDeletes:') print('=============') - for obj in self._delayDeletedDOs.values(): - print('%s\t%s (%s)\tdelayDeletes=%s' % ( - obj.doId, safeRepr(obj), itype(obj), obj.getDelayDeleteNames())) \ No newline at end of file + for obj in list(self._delayDeletedDOs.values()): + print(('%s\t%s (%s)\tdelayDeletes=%s' % ( + obj.doId, safeRepr(obj), itype(obj), obj.getDelayDeleteNames()))) \ No newline at end of file diff --git a/otp/distributed/ClsendTracker.py b/otp/distributed/ClsendTracker.py index 83c99844f..408b77147 100644 --- a/otp/distributed/ClsendTracker.py +++ b/otp/distributed/ClsendTracker.py @@ -34,7 +34,7 @@ def trackClientSendMsg(self, dataStr): 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:] diff --git a/otp/distributed/ConnectionRepository_override.py b/otp/distributed/ConnectionRepository_override.py index 269a451f4..9ae0ea83f 100644 --- a/otp/distributed/ConnectionRepository_override.py +++ b/otp/distributed/ConnectionRepository_override.py @@ -245,7 +245,7 @@ def readDCFile(self, dcFileNames=None): if not readResult: self.notify.error("Could not read dc file.") self.hashVal = dcFile.getHash() - for n in xrange(dcFile.getNumImportModules()): + for n in range(dcFile.getNumImportModules()): moduleName = dcFile.getImportModule(n)[:] suffix = moduleName.split('/') moduleName = suffix[0] @@ -255,7 +255,7 @@ def readDCFile(self, dcFileNames=None): elif self.dcSuffix == 'UD' and 'AI' in suffix: #HACK: moduleName += 'AI' importSymbols = [] - for i in xrange(dcFile.getNumImportSymbols(n)): + for i in range(dcFile.getNumImportSymbols(n)): symbolName = dcFile.getImportSymbol(n, i) suffix = symbolName.split('/') symbolName = suffix[0] @@ -266,7 +266,7 @@ def readDCFile(self, dcFileNames=None): symbolName += 'AI' importSymbols.append(symbolName) self.importModule(dcImports, moduleName, importSymbols) - for i in xrange(dcFile.getNumClasses()): + for i in range(dcFile.getNumClasses()): dclass = dcFile.getClass(i) number = dclass.getNumber() className = dclass.getName() + self.dcSuffix @@ -286,7 +286,7 @@ def readDCFile(self, dcFileNames=None): continue classDef = getattr(classDef, className) - if type(classDef) != types.ClassType and type(classDef) != types.TypeType: + if type(classDef) != type and type(classDef) != type: self.notify.error("Symbol %s is not a class name." % (className)) else: dclass.setClassDef(classDef) @@ -297,7 +297,7 @@ def readDCFile(self, dcFileNames=None): if self.hasOwnerView(): ownerDcSuffix = self.dcSuffix + 'OV' ownerImportSymbols = {} - for n in xrange(dcFile.getNumImportModules()): + for n in range(dcFile.getNumImportModules()): moduleName = dcFile.getImportModule(n) suffix = moduleName.split('/') moduleName = suffix[0] @@ -305,7 +305,7 @@ def readDCFile(self, dcFileNames=None): if ownerDcSuffix in suffix: moduleName = moduleName + ownerDcSuffix importSymbols = [] - for i in xrange(dcFile.getNumImportSymbols(n)): + for i in range(dcFile.getNumImportSymbols(n)): symbolName = dcFile.getImportSymbol(n, i) suffix = symbolName.split('/') symbolName = suffix[0] @@ -315,7 +315,7 @@ def readDCFile(self, dcFileNames=None): importSymbols.append(symbolName) ownerImportSymbols[symbolName] = None self.importModule(dcImports, moduleName, importSymbols) - for i in xrange(dcFile.getNumClasses()): + for i in range(dcFile.getNumClasses()): dclass = dcFile.getClass(i) if ((dclass.getName()+ownerDcSuffix) in ownerImportSymbols): number = dclass.getNumber() @@ -347,7 +347,7 @@ def importModule(self, dcImports, moduleName, importSymbols): if hasattr(module, "__all__"): importSymbols = module.__all__ else: - importSymbols = module.__dict__.keys() + importSymbols = list(module.__dict__.keys()) for symbolName in importSymbols: if hasattr(module, symbolName): diff --git a/otp/distributed/DoCollectionManagerOR.py b/otp/distributed/DoCollectionManagerOR.py index 6acd90505..677f531e8 100644 --- a/otp/distributed/DoCollectionManagerOR.py +++ b/otp/distributed/DoCollectionManagerOR.py @@ -56,7 +56,7 @@ def doFind(self, str): """ Returns list of distributed objects with matching str in value. """ - for value in self.doId2do.values(): + for value in list(self.doId2do.values()): if repr(value).find(str) >= 0: return value @@ -65,7 +65,7 @@ def doFindAll(self, str): Returns list of distributed objects with matching str in value. """ matches = [] - for value in self.doId2do.values(): + for value in list(self.doId2do.values()): if repr(value).find(str) >= 0: matches.append(value) return matches @@ -75,7 +75,7 @@ def doFindAllMatching(self, str): Returns list of distributed objects with matching str in value. """ matches = [] - for value in self.doId2do.values(): + for value in list(self.doId2do.values()): if re.search(str,repr(value)): matches.append(value) return matches @@ -86,14 +86,14 @@ def doFindAllOfType(self, query): for objects of a particular type """ matches = [] - for value in self.doId2do.values(): + for value in list(self.doId2do.values()): if query in str(value.__class__): matches.append(value) return matches, len(matches) def doFindAllInstances(self, cls): matches = [] - for value in self.doId2do.values(): + for value in list(self.doId2do.values()): if isinstance(value, cls): matches.append(value) return matches @@ -124,26 +124,26 @@ def dosByDistance(self): def doByDistance(self): objs = self.dosByDistance() for obj in objs: - print('%s\t%s\t%s' % (obj.doId, self._getDistanceFromLA(obj), - obj.dclass.getName())) + print(('%s\t%s\t%s' % (obj.doId, self._getDistanceFromLA(obj), + obj.dclass.getName()))) if __debug__: def printObjects(self): format="%10s %10s %10s %30s %20s" title=format%("parentId", "zoneId", "doId", "dclass", "name") print(title) - print('-'*len(title)) - for distObj in self.doId2do.values(): - print(format%( + print(('-'*len(title))) + for distObj in list(self.doId2do.values()): + print((format%( distObj.__dict__.get("parentId"), distObj.__dict__.get("zoneId"), distObj.__dict__.get("doId"), distObj.dclass.getName(), - distObj.__dict__.get("name"))) + distObj.__dict__.get("name")))) def _printObjects(self, table): class2count = {} - for obj in self.getDoTable(ownerView=False).values(): + for obj in list(self.getDoTable(ownerView=False).values()): className = obj.__class__.__name__ class2count.setdefault(className, 0) class2count[className] += 1 @@ -154,13 +154,13 @@ def _printObjects(self, table): for count in counts: count2classes[count].sort() for name in count2classes[count]: - print('%s %s' % (count, name)) + print(('%s %s' % (count, name))) print('') def _returnObjects(self, table): class2count = {} stringToReturn = '' - for obj in self.getDoTable(ownerView=False).values(): + for obj in list(self.getDoTable(ownerView=False).values()): className = obj.__class__.__name__ class2count.setdefault(className, 0) class2count[className] += 1 @@ -224,7 +224,7 @@ def hasOwnerViewDoId(self, doId): def getOwnerViewDoList(self, classType): assert self.hasOwnerView() l = [] - for obj in self.doId2ownerView.values(): + for obj in list(self.doId2ownerView.values()): if isinstance(obj, classType): l.append(obj) return l @@ -232,7 +232,7 @@ def getOwnerViewDoList(self, classType): def getOwnerViewDoIdList(self, classType): assert self.hasOwnerView() l = [] - for doId, obj in self.doId2ownerView.items(): + for doId, obj in list(self.doId2ownerView.items()): if isinstance(obj, classType): l.append(doId) return l @@ -243,7 +243,7 @@ def countObjects(self, classType): repository (for testing purposes) """ count = 0 - for dobj in self.doId2do.values(): + for dobj in list(self.doId2do.values()): if isinstance(dobj, classType): count += 1 return count @@ -253,14 +253,14 @@ def getAllOfType(self, type): # Returns a list of all DistributedObjects in the repository # of a particular type. result = [] - for obj in self.doId2do.values(): + for obj in list(self.doId2do.values()): if isinstance(obj, type): result.append(obj) return result def findAnyOfType(self, type): # Searches the repository for any object of the given type. - for obj in self.doId2do.values(): + for obj in list(self.doId2do.values()): if isinstance(obj, type): return obj return None @@ -269,7 +269,7 @@ def findAnyOfType(self, type): def deleteDistributedObjects(self): # Get rid of all the distributed objects - for doId in self.doId2do.keys(): + for doId in list(self.doId2do.keys()): # Look up the object do = self.doId2do[doId] self.deleteDistObject(do) diff --git a/otp/distributed/OTPClientRepository.py b/otp/distributed/OTPClientRepository.py index 8e048fb81..04762f320 100644 --- a/otp/distributed/OTPClientRepository.py +++ b/otp/distributed/OTPClientRepository.py @@ -126,7 +126,7 @@ def __init__(self, serverVersion, launcher = None, playGame = None): '&CHAT_CODE_CREATION_RULE=%s' % config.GetString('fake-DISL-ChatCodeCreation', 'YES') + '&FAMILY_MEMBERS=%s' % config.GetString('fake-DISL-FamilyMembers') + '&PIRATES_SUB_COUNT=%s' % subCount) - for i in xrange(subCount): + for i in range(subCount): self.DISLToken += ('&PIRATES_SUB_%s_ACCESS=%s' % (i, config.GetString('fake-DISL-Sub-%s-Access' % i, 'FULL')) + '&PIRATES_SUB_%s_ACTIVE=%s' % (i, config.GetString('fake-DISL-Sub-%s-Active' % i, 'YES')) + '&PIRATES_SUB_%s_ID=%s' % (i, config.GetInt('fake-DISL-Sub-%s-Id' % i, playerAccountId) + config.GetInt('fake-DISL-Sub-Id-Offset', 0)) + @@ -140,7 +140,7 @@ def __init__(self, serverVersion, launcher = None, playGame = None): 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') @@ -760,7 +760,7 @@ def _wantShardListComplete(self): @report(types = ['args', 'deltaStamp'], dConfigParam = 'teleport') def _shardsAreReady(self): maxPop = config.GetInt('shard-mid-pop', 300) - for shard in self.activeDistrictMap.values(): + for shard in list(self.activeDistrictMap.values()): if shard.available: if shard.avatarCount < maxPop: return True @@ -1115,11 +1115,11 @@ def detectLeakedTasks(self, extraTasks = None): 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 @@ -1185,7 +1185,7 @@ def detectLeakedEvents(self, extraHooks = None): 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: @@ -1200,21 +1200,21 @@ def detectLeakedEvents(self, extraHooks = None): def detectLeakedIntervals(self): numIvals = ivalMgr.getNumIntervals() if numIvals > 0: - print "You can't leave until you clean up your intervals: {" - for i in xrange(ivalMgr.getMaxIndex()): + print("You can't leave until you clean up your intervals: {") + for i in range(ivalMgr.getMaxIndex()): ival = None if i < len(ivalMgr.ivals): ival = ivalMgr.ivals[i] 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: @@ -1330,7 +1330,7 @@ def _removeLocalAvFromStateServer(self): @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) @@ -1457,7 +1457,7 @@ def moveOnFromUberZone(self): 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_ENTER_OBJECT_REQUIRED: self.handleGenerateWithRequired(di) @@ -1587,14 +1587,14 @@ def logAccountInfo(self): def getStartingDistrict(self): district = None - if len(self.activeDistrictMap.keys()) == 0: + if len(list(self.activeDistrictMap.keys())) == 0: self.notify.info('no shards') return maxPop = config.GetInt('shard-mid-pop', 300) # Join the least populated district. - for shard in self.activeDistrictMap.values(): + for shard in list(self.activeDistrictMap.values()): if district: if shard.avatarCount < district.avatarCount and shard.available: if shard.avatarCount < maxPop: @@ -1622,7 +1622,7 @@ def isShardAvailable(self, shardId): 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, s.avatarCount, s.newAvatarCount, s.invasionStatus)) @@ -1630,7 +1630,7 @@ def listActiveShards(self): 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) @@ -1842,7 +1842,7 @@ def replayDeferredGenerate(self, msgType, extra): @exceptionLogged(append = False) def handleDatagram(self, di): if self.notify.getDebug(): - print 'ClientRepository received datagram:' + print('ClientRepository received datagram:') di.getDatagram().getMessage().dumpHex(ostream) msgType = self.getMsgType() @@ -1917,7 +1917,7 @@ def handleGenerateWithRequired(self, di, other = False): parentId = di.getUint32() zoneId = di.getUint32() classId = di.getUint16() - for handle, interest in self._interests.items(): + for handle, interest in list(self._interests.items()): if parentId != interest.parentId: continue if isinstance(interest.zoneIdList, list): diff --git a/otp/distributed/TelemetryLimited.py b/otp/distributed/TelemetryLimited.py index 9a20b5e36..4680ddf59 100644 --- a/otp/distributed/TelemetryLimited.py +++ b/otp/distributed/TelemetryLimited.py @@ -3,7 +3,7 @@ class TelemetryLimited: Sng = SerialNumGen() def __init__(self): - self._telemetryLimiterId = self.Sng.next() + self._telemetryLimiterId = next(self.Sng) self._limits = set() def getTelemetryLimiterId(self): diff --git a/otp/distributed/TelemetryLimiter.py b/otp/distributed/TelemetryLimiter.py index 0e16c81da..e5a451a5d 100644 --- a/otp/distributed/TelemetryLimiter.py +++ b/otp/distributed/TelemetryLimiter.py @@ -41,7 +41,7 @@ def removeObj(self, obj): self.ignore(self._getDummyEventName(obj)) def _enforceLimits(self, task = None): - for obj in self._objs.itervalues(): + for obj in list(self._objs.values()): obj.enforceTelemetryLimits() return Task.cont @@ -113,7 +113,7 @@ def _handlePlayerLeave(self, av): 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 diff --git a/otp/friends/FriendManagerAI.py b/otp/friends/FriendManagerAI.py index e84472160..1d9ef3f17 100644 --- a/otp/friends/FriendManagerAI.py +++ b/otp/friends/FriendManagerAI.py @@ -27,7 +27,7 @@ def trueFriendDatabase(self): self.air.dbGlobalCursor.trueFriendCodes.ensure_index('date', expireAfterSeconds = OTPGlobals.TF_CODE_EXPIRE) def getRandomCharSequence(self, count): - return ''.join(random.choice(string.ascii_lowercase + string.digits) for i in xrange(count)) + return ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(count)) def getCode(self): code = 'TTPA %s %s' % (self.getRandomCharSequence(3), self.getRandomCharSequence(3)) @@ -55,7 +55,7 @@ def requestTrueFriendCode(self): def useTrueFriendCode(self, code): avId = self.air.getAvatarIdFromSender() - print("%s entered code %s" %(avId, code)) + print(("%s entered code %s" %(avId, code))) if avId in self.trueFriendFSMs: self.sendUpdateToAvatarId(avId, 'trueFriendResponse', [OTPGlobals.TF_CALM_DOWN_PLEASE, '']) return @@ -231,7 +231,7 @@ def __gotAvatar(self, dclass, fields): if avId in trueFriendsList: self.manager.sendUpdateToAvatarId(avId, 'trueFriendResponse', [OTPGlobals.TF_ALREADY_FRIENDS, name]) - print('%s is already tf with %s (%s)'%(avId, self.targetId, name)) + print(('%s is already tf with %s (%s)'%(avId, self.targetId, name))) return elif avId not in friendsList: if len(friendsList) >= OTPGlobals.MaxFriends: diff --git a/otp/friends/FriendSecret.py b/otp/friends/FriendSecret.py index 0fabd7f2f..4e0be9763 100644 --- a/otp/friends/FriendSecret.py +++ b/otp/friends/FriendSecret.py @@ -426,7 +426,7 @@ def __gotAccountSecret(self, secret): 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 @@ -505,7 +505,7 @@ def __useAccountSecret(self, avId, friendInfo): 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: diff --git a/otp/friends/GuildManager.py b/otp/friends/GuildManager.py index e13b33cbb..66578df81 100644 --- a/otp/friends/GuildManager.py +++ b/otp/friends/GuildManager.py @@ -9,7 +9,7 @@ GUILDRANK_GM = 3 GUILDRANK_OFFICER = 2 GUILDRANK_MEMBER = 1 -import Queue +import queue class GuildMemberInfo(AvatarHandle): @@ -227,18 +227,18 @@ def guildNameChange(self, guildName, changeStatus): 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): diff --git a/otp/friends/PlayerFriendsManager.py b/otp/friends/PlayerFriendsManager.py index ec8c85428..568deda04 100644 --- a/otp/friends/PlayerFriendsManager.py +++ b/otp/friends/PlayerFriendsManager.py @@ -18,7 +18,7 @@ def delete(self): 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 @@ def rejectRemove(self, playerId, reason): 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): diff --git a/otp/launcher/DummyLauncherBase.py b/otp/launcher/DummyLauncherBase.py index db845cfa9..fbfce521e 100644 --- a/otp/launcher/DummyLauncherBase.py +++ b/otp/launcher/DummyLauncherBase.py @@ -116,7 +116,7 @@ def fakeDownloadPhaseTask(self, task): 0, 0]) if percentComplete >= 100.0: - messenger.send('phaseComplete-' + `(task.phase)`) + messenger.send('phaseComplete-' + repr((task.phase))) return Task.done else: return Task.cont diff --git a/otp/launcher/LauncherBase.py b/otp/launcher/LauncherBase.py index 9034f9169..3e65381a1 100644 --- a/otp/launcher/LauncherBase.py +++ b/otp/launcher/LauncherBase.py @@ -2,7 +2,7 @@ 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,25 +132,25 @@ def __init__(self): 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' + print('generating standard configrc') 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')) @@ -207,7 +207,7 @@ def __init__(self): 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 @@ -238,7 +238,7 @@ def __init__(self): 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 @@ -795,7 +795,7 @@ def extract(self, mfname, localFilename, destDir, callback): self.notify.info('extract: Unable to open multifile %s' % task.localFilename.cStr()) sys.exit() numFiles = self.dldb.getServerNumFiles(mfname) - for i in xrange(numFiles): + for i in range(numFiles): subfile = self.dldb.getServerFileName(mfname, i) if not task.extractor.requestSubfile(Filename(subfile)): self.setPandaErrorCode(6) @@ -910,7 +910,7 @@ def patchTask(self, task): 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') @@ -932,7 +932,7 @@ def readProgressFile(self): 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): @@ -1038,7 +1038,7 @@ def maybeStartGame(self): self.notify.info('maybeStartGame: starting game') self.launcherMessage(self.Localizer.LauncherStartingGame) self.background() - __builtin__.launcher = self + builtins.launcher = self self.startGame() def _runTaskManager(self): @@ -1099,11 +1099,11 @@ def mainLoop(self): 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() - for i in xrange(self.dldb.getServerNumMultifiles()): + for i in range(self.dldb.getServerNumMultifiles()): mfname = self.dldb.getServerMultifileName(i) if self.dldb.getServerMultifilePhase(mfname) == phase: self.phaseMultifileNames.append(mfname) @@ -1118,10 +1118,10 @@ def updateNextMultifile(self): else: if self.currentMfname is None: self.notify.warning('no multifile found! See below for debug info:') - for i in xrange(self.dldb.getServerNumMultifiles()): + 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] @@ -1134,10 +1134,10 @@ def updateNextMultifile(self): 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 @@ -1187,7 +1187,7 @@ def getMultifile(self, mfname): compressedFilename.unlink() extractedOk = True numFiles = self.dldb.getServerNumFiles(mfname) - for i in xrange(numFiles): + for i in range(numFiles): subfile = self.dldb.getServerFileName(mfname, i) fn = Filename(self.mfDir, Filename(subfile)) if fn.compareTimestamps(decompressedFilename) <= 0: @@ -1270,7 +1270,7 @@ def getMultifile(self, mfname): compressedFilename.unlink() extractedOk = True numFiles = self.dldb.getServerNumFiles(mfname) - for i in xrange(numFiles): + for i in range(numFiles): subfile = self.dldb.getServerFileName(mfname, i) fn = Filename(self.mfDir, Filename(subfile)) if fn.compareTimestamps(decompressedFilename) <= 0: @@ -1353,7 +1353,7 @@ def extractMultifileDone(self): 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: @@ -1369,7 +1369,7 @@ def downloadPatches(self): 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): @@ -1378,7 +1378,7 @@ def downloadPatchDone(self): 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)) @@ -1396,7 +1396,7 @@ def patchDone(self): 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] @@ -1415,12 +1415,12 @@ def reextractNextFile(self): 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() @@ -1454,11 +1454,11 @@ def patchMultifile(self): 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 - for ver in xrange(1, clientVer): + for ver in range(1, clientVer): patch = self.getPatchFilename(decompressedMfname, ver + 1) patchee = decompressedMfname patchVersion = ver + 1 @@ -1466,7 +1466,7 @@ def patchMultifile(self): 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 @@ -1605,7 +1605,7 @@ def setPercentPhaseComplete(self, phase, percent): 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) @@ -1784,29 +1784,29 @@ def cleanup(self): 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 @@ -1815,9 +1815,9 @@ def scanForHacks(self): 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() @@ -1825,7 +1825,7 @@ def scanForHacks(self): if val.find(hackprog) != -1: hacksInstalled[knownHacksMUI[hackprog]] = 1 break - _winreg.CloseKey(rh) + winreg.CloseKey(rh) except: pass @@ -1845,12 +1845,12 @@ def scanForHacks(self): 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() diff --git a/otp/level/CollisionSolidEntity.py b/otp/level/CollisionSolidEntity.py index 074c94012..588e4fbf1 100644 --- a/otp/level/CollisionSolidEntity.py +++ b/otp/level/CollisionSolidEntity.py @@ -39,5 +39,5 @@ def destroySolid(self): if __dev__: def attribChanged(self, attrib, value): - print 'attribChanged' + print('attribChanged') self.initSolid() \ No newline at end of file diff --git a/otp/level/DistributedLevel.py b/otp/level/DistributedLevel.py index 07fc0312c..fc1d110f8 100644 --- a/otp/level/DistributedLevel.py +++ b/otp/level/DistributedLevel.py @@ -98,7 +98,7 @@ def setSpecSenderDoId(self, doId): 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 @@ -116,7 +116,7 @@ def setSpecBlob(specBlob, blobSender = blobSender, self = self): 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() @@ -168,14 +168,14 @@ def __handleLevelMgrCreated(self): 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') @@ -400,7 +400,7 @@ def updateVisibility(self, zoneNum = None): 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: @@ -423,7 +423,7 @@ def updateVisibility(self, zoneNum = None): 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 @@ -444,7 +444,7 @@ def setVisibility(self, vizList): 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() diff --git a/otp/level/DistributedLevelAI.py b/otp/level/DistributedLevelAI.py index e2ae455bf..4c4948b0e 100644 --- a/otp/level/DistributedLevelAI.py +++ b/otp/level/DistributedLevelAI.py @@ -62,7 +62,7 @@ def delete(self, deAllocZone = True): 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__: diff --git a/otp/level/EditMgrAI.py b/otp/level/EditMgrAI.py index 840144187..28b354265 100644 --- a/otp/level/EditMgrAI.py +++ b/otp/level/EditMgrAI.py @@ -2,7 +2,7 @@ if __dev__: from toontown.toonbase.ToonPythonUtil import list2dict - import EditorGlobals + from . import EditorGlobals class EditMgrAI(EditMgrBase.EditMgrBase): if __dev__: @@ -16,8 +16,8 @@ def setRequestNewEntity(self, data): 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 diff --git a/otp/level/EntityCreator.py b/otp/level/EntityCreator.py index 60d7d9e93..0dd55b0a4 100644 --- a/otp/level/EntityCreator.py +++ b/otp/level/EntityCreator.py @@ -18,7 +18,7 @@ def nothing(*args): return 'nothing' -def nonlocal(*args): +def _nonlocal(*args): return 'nonlocal' class EntityCreator(EntityCreatorBase.EntityCreatorBase): diff --git a/otp/level/EntityCreatorBase.py b/otp/level/EntityCreatorBase.py index 904e78ce2..a3fc9349f 100644 --- a/otp/level/EntityCreatorBase.py +++ b/otp/level/EntityCreatorBase.py @@ -15,7 +15,7 @@ def createEntity(self, entId): return ent def getEntityTypes(self): - return self.entType2Ctor.keys() + return list(self.entType2Ctor.keys()) def privRegisterType(self, entType, ctor): if entType in self.entType2Ctor: @@ -23,5 +23,5 @@ def privRegisterType(self, 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) diff --git a/otp/level/EntityTypeDesc.py b/otp/level/EntityTypeDesc.py index e609a31b2..b7ab9761a 100644 --- a/otp/level/EntityTypeDesc.py +++ b/otp/level/EntityTypeDesc.py @@ -33,7 +33,7 @@ def getAttribDescDict(self): 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) diff --git a/otp/level/EntityTypeRegistry.py b/otp/level/EntityTypeRegistry.py index 1e8bf5988..8613f042f 100644 --- a/otp/level/EntityTypeRegistry.py +++ b/otp/level/EntityTypeRegistry.py @@ -6,6 +6,7 @@ from otp.level import AttribDesc from otp.level import EntityTypeDesc from toontown.toonbase.ToonPythonUtil import mostDerivedLast +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,8 +34,8 @@ def getPyExtVersion(filename): 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) @@ -47,7 +48,7 @@ def getPyExtVersion(filename): 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 @@ def getPyExtVersion(filename): 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) @@ -70,7 +71,7 @@ def getPyExtVersion(filename): self.typeName2derivedTypeNames[typename] = typenames def getAllTypeNames(self): - return self.entTypeName2typeDesc.keys() + return list(self.entTypeName2typeDesc.keys()) def getTypeDesc(self, entTypeName): return self.entTypeName2typeDesc[entTypeName] diff --git a/otp/level/Level.py b/otp/level/Level.py index baf11d1b0..af9f7923f 100644 --- a/otp/level/Level.py +++ b/otp/level/Level.py @@ -116,7 +116,7 @@ def createEntity(self, entId): 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) diff --git a/otp/level/LevelMgr.py b/otp/level/LevelMgr.py index f7075e944..09f050d84 100644 --- a/otp/level/LevelMgr.py +++ b/otp/level/LevelMgr.py @@ -37,7 +37,7 @@ def handleZoneDestroy(self, entId): def privAssignZoneIds(self): self.zoneNums.sort() - for i in xrange(len(self.zoneNums)): + for i in range(len(self.zoneNums)): zoneNum = self.zoneNums[i] zoneEnt = self.level.getEntity(zoneNum) zoneId = self.level.zoneIds[i] diff --git a/otp/level/LevelMgrAI.py b/otp/level/LevelMgrAI.py index 0ff86d8e6..e5940d163 100644 --- a/otp/level/LevelMgrAI.py +++ b/otp/level/LevelMgrAI.py @@ -26,7 +26,7 @@ def handleZoneDestroy(self, entId): 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: diff --git a/otp/level/LevelSpec.py b/otp/level/LevelSpec.py index 9b17aaa09..efc8de9a1 100644 --- a/otp/level/LevelSpec.py +++ b/otp/level/LevelSpec.py @@ -4,6 +4,7 @@ from direct.directnotify import DirectNotifyGlobal from toontown.toonbase.ToonPythonUtil import list2dict, uniqueElements from otp.level import LevelConstants +import importlib if __dev__: import os @@ -15,11 +16,11 @@ def __init__(self, spec = None, scenario = 0): 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__: @@ -28,14 +29,14 @@ def __init__(self, spec = None, scenario = 0): 'scenarios': [{}]} self.entId2specDict = {} self.entId2specDict.update(list2dict(self.getGlobalEntIds(), value=self.privGetGlobalEntityDict())) - for i in xrange(self.getNumScenarios()): + for i in range(self.getNumScenarios()): self.entId2specDict.update(list2dict(self.getScenarioEntIds(i), value=self.privGetScenarioEntityDict(i))) 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 @@ -67,19 +68,19 @@ def getScenario(self): 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 @@ -129,7 +130,7 @@ def printZones(self): 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__: @@ -146,7 +147,7 @@ def setEntityTypeReg(self, entTypeReg): type = self.getEntityType(entId) typeDesc = self.entTypeReg.getTypeDesc(type) attribDescDict = typeDesc.getAttribDescDict() - for attribName, desc in attribDescDict.iteritems(): + for attribName, desc in list(attribDescDict.items()): if attribName not in spec: spec[attribName] = desc.getDefaultValue() @@ -178,7 +179,7 @@ def insertEntity(self, entId, entType, parentEntId = 'unspecified'): 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 @@ -231,7 +232,7 @@ def saveToDisk(self, filename = None, makeBackup = 1): 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) @@ -292,9 +293,9 @@ def sortList(lst, firstElements = []): 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' % type.upper() entIds = entType2ids[type] @@ -302,7 +303,7 @@ def sortList(lst, firstElements = []): 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])) @@ -319,7 +320,7 @@ def t(n): str = t(0) + '%s = {\n' % topLevelName str += t(1) + "'globalEntities': %s,\n" % globalEntitiesName str += t(1) + "'scenarios': [\n" - for i in xrange(self.getNumScenarios()): + for i in range(self.getNumScenarios()): str += t(2) + '%s,\n' % (scenarioEntitiesName % i) str += t(2) + '],\n' @@ -331,7 +332,7 @@ def t(n): str += getPrettyEntityDictStr('GlobalEntities', self.privGetGlobalEntityDict()) str += '\n' numScenarios = self.getNumScenarios() - for i in xrange(numScenarios): + for i in range(numScenarios): str += getPrettyEntityDictStr('Scenario%s' % i, self.privGetScenarioEntityDict(i)) str += '\n' @@ -355,7 +356,7 @@ def _recurKeyTest(self, dict1, dict2): s += '\nBAD VALUE(%s): %s != %s\n' % (key, strd1, strd2) errorCount += 1 - print s + print(s) if errorCount == 0: return 1 else: @@ -367,7 +368,7 @@ def testPrettyString(self, prettyString=None): def checkSpecIntegrity(self): entIds = self.getGlobalEntIds() entIds = list2dict(entIds) - for i in xrange(self.getNumScenarios()): + for i in range(self.getNumScenarios()): for id in self.getScenarioEntIds(i): entIds[id] = None @@ -379,7 +380,7 @@ def checkSpecIntegrity(self): 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] diff --git a/otp/level/PathEntity.py b/otp/level/PathEntity.py index 19a75b003..f7911a1fd 100644 --- a/otp/level/PathEntity.py +++ b/otp/level/PathEntity.py @@ -32,7 +32,7 @@ def makePathTrack(self, node, velocity, name, turnTime = 1, lookAroundNode = Non track.append(WaitInterval(1.0)) return track path = self.path + [self.path[0]] - for pointIndex in xrange(len(path) - 1): + for pointIndex in range(len(path) - 1): startPoint = Point3(path[pointIndex]) * self.pathScale endPoint = Point3(path[pointIndex + 1]) * self.pathScale v = startPoint - endPoint diff --git a/otp/level/PropSpinner.py b/otp/level/PropSpinner.py index 5a4dbaefb..f45db876c 100644 --- a/otp/level/PropSpinner.py +++ b/otp/level/PropSpinner.py @@ -28,7 +28,7 @@ def initProps(self): 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 @@ def initProps(self): elif axis == 'Z': hpr = Vec3(0, 0, rate * 360) else: - print 'error', axis + print(('error', axis)) spinTracks.append(LerpHprInterval(prop, 60, hpr)) spinTracks.loop() diff --git a/otp/level/ZoneEntity.py b/otp/level/ZoneEntity.py index 0073e8c2a..9687d0d20 100644 --- a/otp/level/ZoneEntity.py +++ b/otp/level/ZoneEntity.py @@ -23,7 +23,7 @@ def getNodePath(self): return self.nodePath def getVisibleZoneNums(self): - return self.visibleZoneNums.keys() + return list(self.visibleZoneNums.keys()) def incrementRefCounts(self, zoneNumList): for zoneNum in zoneNumList: diff --git a/otp/login/GuiScreen.py b/otp/login/GuiScreen.py index 69a83dcf2..47f587cff 100644 --- a/otp/login/GuiScreen.py +++ b/otp/login/GuiScreen.py @@ -28,14 +28,14 @@ def startFocusMgmt(self, startFocus = 0, enterPressBehavior = DGG.ENTERPRESS_ADV 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,7 +50,7 @@ def startFocusMgmt(self, startFocus = 0, enterPressBehavior = DGG.ENTERPRESS_ADV 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 item in overrides: @@ -150,15 +150,15 @@ def __chainToUserCommandHandler(self, item): 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 diff --git a/otp/login/HTTPUtil.py b/otp/login/HTTPUtil.py index 6d8600b19..181fd4445 100644 --- a/otp/login/HTTPUtil.py +++ b/otp/login/HTTPUtil.py @@ -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] diff --git a/otp/login/RemoteValueSet.py b/otp/login/RemoteValueSet.py index 5f8304828..1c82bbc27 100644 --- a/otp/login/RemoteValueSet.py +++ b/otp/login/RemoteValueSet.py @@ -22,7 +22,7 @@ def __init__(self, url, http, body = '', expectedHeader = None, expectedFields = 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) diff --git a/otp/login/TTAccount.py b/otp/login/TTAccount.py index 1ca950d9e..f11e4a317 100644 --- a/otp/login/TTAccount.py +++ b/otp/login/TTAccount.py @@ -8,14 +8,14 @@ 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(): @@ -54,7 +54,7 @@ def authenticateParentPassword(self, loginName, password, parentPassword): 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 @@ -70,7 +70,7 @@ def authenticateDelete(self, loginName, password): 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 @@ -84,7 +84,7 @@ def enableSecretFriends(self, loginName, password, parentPassword, enable = 1): 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 @@ -116,7 +116,7 @@ def getAccountData(self, loginName, password): 'l2': 'addr2', 'l3': 'addr3'} dict = self.accountData.dict - for fieldName in dict.keys(): + for fieldName in list(dict.keys()): if fieldName in fieldNameMap: dict[fieldNameMap[fieldName]] = dict[fieldName] del dict[fieldName] @@ -153,7 +153,7 @@ def makeLoginDict(self, loginName, password, data = None): 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'): @@ -223,14 +223,14 @@ def talk(self, operation, data = {}): 'userid': 'userid'} ignoredFields = ('ccType',) outBoundFields = {} - for fieldName in data.keys(): + 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): @@ -273,7 +273,7 @@ def authenticateParentUsernameAndPassword(self, loginName, password, parentUsern 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 diff --git a/otp/movement/Mover.py b/otp/movement/Mover.py index d65cbeddc..306304f44 100644 --- a/otp/movement/Mover.py +++ b/otp/movement/Mover.py @@ -2,7 +2,7 @@ from direct.directnotify import DirectNotifyGlobal from otp.movement.PyVec3 import PyVec3 from toontown.toonbase import ToonPythonUtil as PythonUtil -import __builtin__ +import builtins class Mover: notify = DirectNotifyGlobal.directNotify.newCategory('Mover') @@ -20,7 +20,7 @@ def __init__(self, objNodePath, fwdSpeed = 1, rotSpeed = 1): self.pscPy = PStatCollector(Mover.PSCPy) 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) @@ -39,17 +39,17 @@ def move(self, dt = -1, profile = 0): 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.pscPy.start() - for impulse in self.impulses.values(): + for impulse in list(self.impulses.values()): impulse._process(self.getDt()) if Mover.Pstats: self.pscPy.stop() diff --git a/otp/movement/PyVec3.py b/otp/movement/PyVec3.py index c889a43bc..ad4732c87 100644 --- a/otp/movement/PyVec3.py +++ b/otp/movement/PyVec3.py @@ -4,7 +4,7 @@ class PyVec3: Epsilon = 0.0001 - ScalarTypes = (types.FloatType, types.IntType, types.LongType) + ScalarTypes = (float, int, int) def __init__(self, *args): self.assign(*args) diff --git a/otp/namepanel/NameCheck.py b/otp/namepanel/NameCheck.py index 79f7d0fef..5d2bcb711 100644 --- a/otp/namepanel/NameCheck.py +++ b/otp/namepanel/NameCheck.py @@ -88,7 +88,7 @@ def fontHasCharacters(name, font = font): tn.setFont(font) for c in name: try: - 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) except: @@ -229,7 +229,7 @@ def allCaps(name): 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 @@ -247,11 +247,11 @@ def mixedCase(name): 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) @@ -265,7 +265,7 @@ def checkJapanese(name): 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: @@ -321,7 +321,7 @@ def repeatedChars(name): nName = name[:] bName.reverse() problem = check(bName) - print 'problem = %s' % problem + print(('problem = %s' % problem)) if problem: return problem @@ -330,7 +330,7 @@ def repeatedChars(name): severity = notify.getSeverity() notify.setSeverity(NSError) -for i in xrange(32): +for i in range(32): pass for c in '!"#$%&()*+/:;<=>?@[\\]^_`{|}~': diff --git a/otp/namepanel/PickANamePattern.py b/otp/namepanel/PickANamePattern.py index 3b02a4340..476cb1df6 100644 --- a/otp/namepanel/PickANamePattern.py +++ b/otp/namepanel/PickANamePattern.py @@ -14,11 +14,11 @@ def getNamePattern(self): 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 += ' ' @@ -108,9 +108,9 @@ def _compute(self, nameStr, gender): combinedIndex2indices = {} lastNamePrefixesCapped = set(self._getLastNameCapPrefixes()) k = 0 - for first, i in nameParts[-2].iteritems(): + for first, i in list(nameParts[-2].items()): capitalize = first in lastNamePrefixesCapped - for second, j in nameParts[-1].iteritems(): + for second, j in list(nameParts[-1].items()): combinedLastName = first if capitalize: combinedLastName += second.capitalize() diff --git a/otp/otpbase/OTPBase.py b/otp/otpbase/OTPBase.py index 1ac83c597..f3b9d1d52 100644 --- a/otp/otpbase/OTPBase.py +++ b/otp/otpbase/OTPBase.py @@ -159,7 +159,7 @@ def __chasePixelZoom(self, task): 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) diff --git a/otp/otpbase/OTPLocalizer.py b/otp/otpbase/OTPLocalizer.py index 0f61a2038..4bc9d23e6 100644 --- a/otp/otpbase/OTPLocalizer.py +++ b/otp/otpbase/OTPLocalizer.py @@ -14,34 +14,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' + language.capitalize() 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(): + for key, val in list(englishModule.__dict__.items()): if key not in foreignModule.__dict__: - print 'WARNING: Foreign module: %s missing key: %s' % (_languageModule, key) + print(('WARNING: Foreign module: %s missing key: %s' % (_languageModule, key))) locals()[key] = val - elif isinstance(val, types.DictType): + elif isinstance(val, dict): fval = foreignModule.__dict__.get(key) - for dkey, dval in val.items(): + for dkey, dval in list(val.items()): if dkey not in fval: - print 'WARNING: Foreign module: %s missing key: %s.%s' % (_languageModule, key, dkey) + print(('WARNING: Foreign module: %s missing key: %s.%s' % (_languageModule, key, dkey))) fval[dkey] = dval - for dkey in fval.keys(): + for dkey in list(fval.keys()): if dkey not in val: - print 'WARNING: Foreign module: %s extra key: %s.%s' % (_languageModule, key, dkey) + print(('WARNING: Foreign module: %s extra key: %s.%s' % (_languageModule, key, dkey))) - for key in foreignModule.__dict__.keys(): + for key in list(foreignModule.__dict__.keys()): if key not in englishModule.__dict__: - print 'WARNING: Foreign module: %s extra key: %s' % (_languageModule, key) + print(('WARNING: Foreign module: %s extra key: %s' % (_languageModule, key))) diff --git a/otp/speedchat/ColorSpace.py b/otp/speedchat/ColorSpace.py index 854b19d1f..c078bfdb8 100644 --- a/otp/speedchat/ColorSpace.py +++ b/otp/speedchat/ColorSpace.py @@ -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)]) diff --git a/otp/speedchat/SCEmoteMenu.py b/otp/speedchat/SCEmoteMenu.py index 6dc571919..ddacc7242 100644 --- a/otp/speedchat/SCEmoteMenu.py +++ b/otp/speedchat/SCEmoteMenu.py @@ -18,6 +18,6 @@ def __emoteAccessChanged(self): except: return - for i in xrange(len(lt.emoteAccess)): + for i in range(len(lt.emoteAccess)): if lt.emoteAccess[i]: self.append(SCEmoteTerminal(i)) \ No newline at end of file diff --git a/otp/speedchat/SCMenu.py b/otp/speedchat/SCMenu.py index 8910defbb..d5c4040dd 100644 --- a/otp/speedchat/SCMenu.py +++ b/otp/speedchat/SCMenu.py @@ -92,14 +92,14 @@ def rebuildFromStructure(self, structure, title = None): 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): @@ -117,7 +117,7 @@ def addChildren(menu, childList): 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) @@ -283,7 +283,7 @@ def finalize(self): 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) @@ -336,7 +336,7 @@ def finalize(self): self.inFinalize = 0 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]) @@ -354,40 +354,40 @@ def __getitem__(self, index): 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 @@ -415,7 +415,7 @@ def privMemberListChanged(self, added = None, removed = None): if self.holder is not None: self.holder.updateViewability() - for i in xrange(len(self.__members)): + for i in range(len(self.__members)): self.__members[i].posInParentMenu = i self.invalidate() diff --git a/otp/speedchat/SCTerminal.py b/otp/speedchat/SCTerminal.py index ad6e6204b..eee807dfe 100644 --- a/otp/speedchat/SCTerminal.py +++ b/otp/speedchat/SCTerminal.py @@ -125,7 +125,7 @@ def getEmoteIconColor(self): def updateEmoteIcon(self): if hasattr(self, 'button'): self.lastEmoteIconColor = self.getEmoteIconColor() - for i in xrange(self.button['numStates']): + for i in range(self.button['numStates']): self.button['image%s_image' % i].setColorScale(*self.lastEmoteIconColor) else: diff --git a/otp/speedchat/SpeedChatGMHandler.py b/otp/speedchat/SpeedChatGMHandler.py index d54841aa6..bc43e3098 100644 --- a/otp/speedchat/SpeedChatGMHandler.py +++ b/otp/speedchat/SpeedChatGMHandler.py @@ -14,13 +14,13 @@ def generateSCStructure(self): SpeedChatGMHandler.scStructure = [OTPLocalizer.PSCMenuGM] phraseCount = 0 numGMCategories = base.config.GetInt('num-gm-categories', 0) - for i in xrange(0, numGMCategories): + for i in range(0, numGMCategories): categoryName = base.config.GetString('gm-category-%d' % i, '') if categoryName == '': continue categoryStructure = [categoryName] numCategoryPhrases = base.config.GetInt('gm-category-%d-phrases' % i, 0) - for j in xrange(0, numCategoryPhrases): + for j in range(0, numCategoryPhrases): phrase = base.config.GetString('gm-category-%d-phrase-%d' % (i, j), '') if phrase != '': idx = 'gm%d' % phraseCount @@ -31,7 +31,7 @@ def generateSCStructure(self): SpeedChatGMHandler.scStructure.append(categoryStructure) numGMPhrases = base.config.GetInt('num-gm-phrases', 0) - for i in xrange(0, numGMPhrases): + for i in range(0, numGMPhrases): phrase = base.config.GetString('gm-phrase-%d' % i, '') if phrase != '': idx = 'gm%d' % phraseCount diff --git a/otp/uberdog/AccountDetailRecord.py b/otp/uberdog/AccountDetailRecord.py index 8c62cf995..454c5126b 100644 --- a/otp/uberdog/AccountDetailRecord.py +++ b/otp/uberdog/AccountDetailRecord.py @@ -73,7 +73,7 @@ def __str__(self): s += 'NumFamilyMembers: %d\n' % self.numFamilyMembers s += 'FamilyMembers: %s\n' % self.familyMembers s += 'NumSubs: %s\n' % self.numSubs - for subDetails in self.subDetails.values(): + for subDetails in list(self.subDetails.values()): s += str(subDetails) s += '================================\n' diff --git a/otp/uberdog/OtpAvatarManager.py b/otp/uberdog/OtpAvatarManager.py index fa0988240..0e8accf16 100644 --- a/otp/uberdog/OtpAvatarManager.py +++ b/otp/uberdog/OtpAvatarManager.py @@ -1,4 +1,4 @@ -from cPickle import loads, dumps +from pickle import loads, dumps from direct.distributed import DistributedObject from direct.directnotify import DirectNotifyGlobal diff --git a/otp/web/SettingsMgrBase.py b/otp/web/SettingsMgrBase.py index 4f5fe9a87..7786130c9 100644 --- a/otp/web/SettingsMgrBase.py +++ b/otp/web/SettingsMgrBase.py @@ -16,7 +16,7 @@ def _initSettings(self): pass def _iterSettingNames(self): - for name in self._settings.iterkeys(): + for name in list(self._settings.keys()): yield name def _addSettings(self, *settings): diff --git a/scripts/ai-darwin.sh b/scripts/ai-darwin.sh new file mode 100644 index 000000000..1dc586793 --- /dev/null +++ b/scripts/ai-darwin.sh @@ -0,0 +1,18 @@ +#!/bin/sh +cd ../ + +# Define some constants for our AI server: +MAX_CHANNELS=999999 +STATESERVER=4002 +ASTRON_IP="127.0.0.1:7100" +EVENTLOGGER_IP="127.0.0.1:7198" +DISTRICT_NAME=Nuttyriver +BASE_CHANNEL=402000000 + +while [ true ] +do + python3.9 -m toontown.ai.ServiceStart --base-channel $BASE_CHANNEL \ + --max-channels $MAX_CHANNELS --stateserver $STATESERVER \ + --astron-ip $ASTRON_IP --eventlogger-ip $EVENTLOGGER_IP \ + --district-name $DISTRICT_NAME +done diff --git a/scripts/astron_yaml-darwin-arm.sh b/scripts/astron_yaml-darwin-arm.sh new file mode 100644 index 000000000..636fc9a46 --- /dev/null +++ b/scripts/astron_yaml-darwin-arm.sh @@ -0,0 +1,4 @@ +cd "../dependencies/astron/" + +chmod +x darwin/astrond-arm +darwin/astrond-arm --loglevel info config/cluster-yaml.yml diff --git a/scripts/astron_yaml-darwin.sh b/scripts/astron_yaml-darwin.sh new file mode 100644 index 000000000..538606624 --- /dev/null +++ b/scripts/astron_yaml-darwin.sh @@ -0,0 +1,4 @@ +cd "../dependencies/astron/" + +chmod +x darwin/astrond +darwin/astrond --loglevel info config/cluster-yaml.yml diff --git a/scripts/uberdog-darwin.sh b/scripts/uberdog-darwin.sh new file mode 100644 index 000000000..a7b8b1bff --- /dev/null +++ b/scripts/uberdog-darwin.sh @@ -0,0 +1,16 @@ +#!/bin/sh +cd ../ + +# Define some constants for our AI server: +MAX_CHANNELS=999999 +STATESERVER=4002 +ASTRON_IP="127.0.0.1:7100" +EVENTLOGGER_IP="127.0.0.1:7198" + +# Get the user input: +BASE_CHANNEL=${BASE_CHANNEL:-1000000} + + +python3.9 -m toontown.uberdog.ServiceStart --base-channel $BASE_CHANNEL \ + --max-channels $MAX_CHANNELS --stateserver $STATESERVER \ + --astron-ip $ASTRON_IP --eventlogger-ip $EVENTLOGGER_IP diff --git a/start_darwin.sh b/start_darwin.sh new file mode 100644 index 000000000..8915a6606 --- /dev/null +++ b/start_darwin.sh @@ -0,0 +1,88 @@ +#!/bin/sh +clear +echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = +echo What do you want to do! +echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = +echo 1 - Run Project Altis +echo + + +while true; do + read -p "Selection: " sel + case $sel in + [1]* ) + clear + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo What do you want to launch! + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo 1 - Locally Host a Server + echo 2 - Connect to an Existing Server + echo + while true; do + read -p "Selection: " sel2 + case $sel2 in + [1]* ) + clear + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo Starting Localhost! + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + cd scripts + echo Launching the AI Server... + open -a Terminal "`pwd`" -e "sh ai-darwin.sh & " + echo Launching Astron... + open -a Terminal "`pwd`" -e "sh astron_yaml-darwin.sh &" + echo Launching the Uberdog Server... + open -a Terminal "`pwd`" -e "sh uberdog-darwin.sh &" + cd .. + export TT_GAMESERVER=127.0.0.1 + clear + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo Username [!] This does get stored in your source code so beware! + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + read -p "Username: " ttUsername + read -p "Password: " ttPassowrd + export TT_PLAYCOOKIE=$ttUsername$ttPassowrd + clear + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo Welcome to Project Altis, $ttUsername! + echo The Tooniverse Awaits You! + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + while [ true ] + do + python3.9 -m toontown.toonbase.ClientStart + read -r -p "Press any key to continue..." key + done + ;; + [2]* ) + clear + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo What Server are you connecting to! + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + read -p "Server IP: " TT_GAMESERVER + TT_GAMESERVER=${TT_GAMESERVER:-"127.0.0.1"} + export TT_GAMESERVER=$TT_GAMESERVER + clear + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo Username [!] This does get stored in your source code so beware! + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + read -p "Username: " ttUsername + read -p "Password: " ttPassowrd + export TT_PLAYCOOKIE=$ttUsername$ttPassowrd + clear + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo Welcome to Project Altis, $ttUsername! + echo The Tooniverse Awaits You! + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + while [ true ] + do + python3.9 -m toontown.toonbase.ClientStart + read -r -p "Press any key to continue..." key + done + ;; + * ) echo "";; + esac + done + ;; + * );; + esac +done diff --git a/start_darwin_arm.sh b/start_darwin_arm.sh new file mode 100644 index 000000000..ea6a2d240 --- /dev/null +++ b/start_darwin_arm.sh @@ -0,0 +1,88 @@ +#!/bin/sh +clear +echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = +echo What do you want to do! +echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = +echo 1 - Run Project Altis +echo + + +while true; do + read -p "Selection: " sel + case $sel in + [1]* ) + clear + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo What do you want to launch! + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo 1 - Locally Host a Server + echo 2 - Connect to an Existing Server + echo + while true; do + read -p "Selection: " sel2 + case $sel2 in + [1]* ) + clear + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo Starting Localhost! + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + cd scripts + echo Launching the AI Server... + open -a Terminal "`pwd`" -e "sh ai-darwin.sh & " + echo Launching Astron... + open -a Terminal "`pwd`" -e "sh astron_yaml-darwin-arm.sh &" + echo Launching the Uberdog Server... + open -a Terminal "`pwd`" -e "sh uberdog-darwin.sh &" + cd .. + export TT_GAMESERVER=127.0.0.1 + clear + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo Username [!] This does get stored in your source code so beware! + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + read -p "Username: " ttUsername + read -p "Password: " ttPassowrd + export TT_PLAYCOOKIE=$ttUsername$ttPassowrd + clear + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo Welcome to Project Altis, $ttUsername! + echo The Tooniverse Awaits You! + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + while [ true ] + do + python3.9 -m toontown.toonbase.ClientStart + read -r -p "Press any key to continue..." key + done + ;; + [2]* ) + clear + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo What Server are you connecting to! + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + read -p "Server IP: " TT_GAMESERVER + TT_GAMESERVER=${TT_GAMESERVER:-"127.0.0.1"} + export TT_GAMESERVER=$TT_GAMESERVER + clear + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo Username [!] This does get stored in your source code so beware! + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + read -p "Username: " ttUsername + read -p "Password: " ttPassowrd + export TT_PLAYCOOKIE=$ttUsername$ttPassowrd + clear + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + echo Welcome to Project Altis, $ttUsername! + echo The Tooniverse Awaits You! + echo = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = + while [ true ] + do + python3.9 -m toontown.toonbase.ClientStart + read -r -p "Press any key to continue..." key + done + ;; + * ) echo "";; + esac + done + ;; + * );; + esac +done diff --git a/toontown/achievements/AchievementGui.py b/toontown/achievements/AchievementGui.py index c9652cbb5..19163b8ac 100644 --- a/toontown/achievements/AchievementGui.py +++ b/toontown/achievements/AchievementGui.py @@ -1,4 +1,4 @@ -import AchievementsGlobals +from . import AchievementsGlobals from direct.gui.DirectGui import DirectFrame, DirectLabel from direct.interval.IntervalGlobal import * from direct.interval.LerpInterval import * diff --git a/toontown/ai/CertificateManagerAI.py b/toontown/ai/CertificateManagerAI.py index 1d88a8916..58a4f37ad 100644 --- a/toontown/ai/CertificateManagerAI.py +++ b/toontown/ai/CertificateManagerAI.py @@ -1,5 +1,5 @@ import random -import httplib +import http.client class CertificateManagerAI(): def __init__(self, air): @@ -17,7 +17,7 @@ def addCode(self, av, code): def generateCode(self): code = '' - for i in xrange(12): + for i in range(12): number = random.randint(0, 9) code += str(number) if (i - 3) % 4 == 0 and i != 11: @@ -27,6 +27,6 @@ def generateCode(self): def sendCode(self, code): domain = str(ConfigVariableString('ws-domain', 'localhost')) key = str(ConfigVariableString('ws-key', 'secretkey')) - request = httplib.HTTPSConnection(domain) + request = http.client.HTTPSConnection(domain) request.request('GET', '/api/addbetacert/%s/%s' % (key, code)) - print request.getresponse().read() + print((request.getresponse().read())) diff --git a/toontown/ai/CogPageManagerAI.py b/toontown/ai/CogPageManagerAI.py index 883bd1a31..1d8544729 100644 --- a/toontown/ai/CogPageManagerAI.py +++ b/toontown/ai/CogPageManagerAI.py @@ -39,12 +39,12 @@ def toonKilledCogs(self, toon, killedCogs, zoneId): toon.b_setCogStatus(cogs) newCogRadar = toon.cogRadar newBuildingRadar = toon.buildingRadar - for dept in xrange(len(SuitDNA.suitDepts)): + for dept in range(len(SuitDNA.suitDepts)): if newBuildingRadar[dept] == 1: continue cogRadar = 1 buildingRadar = 1 - for cog in xrange(SuitDNA.suitsPerDept): + for cog in range(SuitDNA.suitsPerDept): status = toon.cogs[dept*SuitDNA.suitsPerDept + cog] if status != COG_COMPLETE2: buildingRadar = 0 diff --git a/toontown/ai/DatabaseObject.py b/toontown/ai/DatabaseObject.py index d334ee6f9..f33c27fab 100644 --- a/toontown/ai/DatabaseObject.py +++ b/toontown/ai/DatabaseObject.py @@ -87,7 +87,7 @@ def getFieldsResponse(self, di): return count = di.getUint16() fields = [] - for i in xrange(count): + for i in range(count): name = di.getString() fields.append(name) @@ -96,11 +96,11 @@ def getFieldsResponse(self, di): self.notify.warning('Failed to retrieve data for object %d' % self.doId) else: values = [] - for i in xrange(count): + for i in range(count): value = di.getString() values.append(value) - for i in xrange(count): + for i in range(count): found = di.getUint8() if not found: self.notify.info('field %s is not found' % fields[i]) @@ -124,7 +124,7 @@ def setFields(self, values): dg.addServerHeader(DBSERVER_ID, self.air.ourChannel, DBSERVER_SET_STORED_VALUES) dg.addUint32(self.doId) dg.addUint16(len(values)) - items = values.items() + items = list(values.items()) for field, value in items: dg.addString(field) @@ -135,7 +135,7 @@ def setFields(self, values): def getDatabaseFields(self, dclass): fields = [] - for i in xrange(dclass.getNumInheritedFields()): + for i in range(dclass.getNumInheritedFields()): dcf = dclass.getInheritedField(i) af = dcf.asAtomicField() if af: @@ -146,7 +146,7 @@ def getDatabaseFields(self, dclass): def fillin(self, do, dclass): do.doId = self.doId - for field, value in self.values.items(): + for field, value in list(self.values.items()): if field == 'setZonesVisited' and value.getLength() == 1: self.notify.warning('Ignoring broken setZonesVisited') else: @@ -166,7 +166,7 @@ def reload(self, do, dclass, fields): def createObject(self, objectType): values = {} - for key, value in values.items(): + for key, value in list(values.items()): values[key] = PyDatagram(str(value)) context = self.air.dbObjContext @@ -179,10 +179,10 @@ def createObject(self, objectType): dg.addString('') dg.addUint16(objectType) dg.addUint16(len(values)) - for field in values.keys(): + for field in list(values.keys()): dg.addString(field) - for value in values.values(): + for value in list(values.values()): dg.addString(value.getMessage()) self.air.send(dg) @@ -202,5 +202,5 @@ def deleteObject(self): dg = PyDatagram() dg.addServerHeader(DBSERVER_ID, self.air.ourChannel, DBSERVER_DELETE_STORED_OBJECT) dg.addUint32(self.doId) - dg.addUint32(3735928559L) + dg.addUint32(3735928559) self.air.send(dg) \ No newline at end of file diff --git a/toontown/ai/DistributedWinterCarolingTarget.py b/toontown/ai/DistributedWinterCarolingTarget.py index 52a2540ec..bd421e184 100644 --- a/toontown/ai/DistributedWinterCarolingTarget.py +++ b/toontown/ai/DistributedWinterCarolingTarget.py @@ -19,7 +19,7 @@ def announceGenerate(self): def phraseSaid(self, phraseId): self.notify.debug('Checking if phrase was said') helpPhrases = [] - for i in xrange(6): + for i in range(6): helpPhrases.append(30220 + i) def reset(): diff --git a/toontown/ai/FishManagerAI.py b/toontown/ai/FishManagerAI.py index 40c313af9..b620af1b1 100644 --- a/toontown/ai/FishManagerAI.py +++ b/toontown/ai/FishManagerAI.py @@ -21,7 +21,7 @@ def creditFishTank(self, av): if trophies > curTrophies: av.b_setMaxHp(av.getMaxHp() + trophies - curTrophies) av.toonUp(av.getMaxHp()) - av.b_setFishingTrophies(range(trophies)) + av.b_setFishingTrophies(list(range(trophies))) return True return False diff --git a/toontown/ai/HolidayDecorator.py b/toontown/ai/HolidayDecorator.py index 2de1bc9cb..b72e4d674 100644 --- a/toontown/ai/HolidayDecorator.py +++ b/toontown/ai/HolidayDecorator.py @@ -41,7 +41,7 @@ def getSwapVisibleIval(self, wait = 5.0, tFadeOut = 3.0, tFadeIn = 3.0): loader = base.cr.playGame.hood.loader npl = render.findAllMatches('**/=DNARoot=holiday_prop;+s') p = Parallel() - for i in xrange(npl.getNumPaths()): + for i in range(npl.getNumPaths()): np = npl.getPath(i) np.setTransparency(TransparencyAttrib.MDual, 1) if not np.hasTag('DNACode'): @@ -59,7 +59,7 @@ def getSwapVisibleIval(self, wait = 5.0, tFadeOut = 3.0, tFadeIn = 3.0): index = int(np.getTag('transformIndex')) transform = loader.holidayPropTransforms.get(index, TransformState.makeIdentity()) newNP.setTransform(NodePath(), transform) - newNP.setTag('transformIndex', `index`) + newNP.setTag('transformIndex', repr(index)) s = Sequence(Wait(wait), np.colorScaleInterval(tFadeOut, Vec4(1, 1, 1, 0), startColorScale=Vec4(1, 1, 1, 1), blendType='easeInOut'), Func(np.detachNode), Func(np.clearTransparency), newNP.colorScaleInterval(tFadeOut, Vec4(1, 1, 1, 1), startColorScale=Vec4(1, 1, 1, 0), blendType='easeInOut'), Func(newNP.clearTransparency), Func(newNP.clearColorScale)) p.append(s) diff --git a/toontown/ai/HolidayManagerAI.py b/toontown/ai/HolidayManagerAI.py index 7690861aa..f3d4e3701 100644 --- a/toontown/ai/HolidayManagerAI.py +++ b/toontown/ai/HolidayManagerAI.py @@ -1,7 +1,7 @@ from direct.directnotify import DirectNotifyGlobal from toontown.toonbase import ToontownGlobals from datetime import datetime -from HolidayGlobals import * +from .HolidayGlobals import * from direct.showbase.DirectObject import DirectObject class HolidayManagerAI(DirectObject): diff --git a/toontown/ai/NewsManager.py b/toontown/ai/NewsManager.py index e7fcea0b1..d5e3a0e58 100644 --- a/toontown/ai/NewsManager.py +++ b/toontown/ai/NewsManager.py @@ -44,7 +44,7 @@ def __init__(self, cr): try: self.decorationHolidayIds.append(decorationHolidays[int(HID)]) except: - print 'holidayId value error: "%s"... skipping' %HID + print(('holidayId value error: "%s"... skipping' %HID)) self.holidayDecorator = None self.holidayIdList = [] @@ -397,11 +397,11 @@ def isEnding(id): def isStarting(id): return id not in self.holidayIdList - toEnd = filter(isEnding, self.holidayIdList) + toEnd = list(filter(isEnding, self.holidayIdList)) for endingHolidayId in toEnd: self.endHoliday(endingHolidayId) - toStart = filter(isStarting, holidayIdList) + toStart = list(filter(isStarting, holidayIdList)) for startingHolidayId in toStart: self.startHoliday(startingHolidayId) @@ -538,11 +538,11 @@ def setBlackCatHolidayEnd(self): def setSpookyBlackCatHolidayStart(self): base.localAvatar.setSystemMessage(0, TTLocalizer.SpookyBlackCatHolidayStart) - for currToon in base.cr.toons.values(): + for currToon in list(base.cr.toons.values()): currToon.setDNA(currToon.style.clone()) def setSpookyBlackCatHolidayEnd(self): - for currToon in base.cr.toons.values(): + for currToon in list(base.cr.toons.values()): currToon.setDNA(currToon.style.clone()) def setTopToonsMarathonStart(self): @@ -657,7 +657,7 @@ def getRelativelyHolidaysForDate(self, theDate): self.weekDaysInMonth = [] self.numDaysCorMatrix = [(28, 0), (29, 1), (30, 2), (31, 3)] - for i in xrange(7): + for i in range(7): self.weekDaysInMonth.append((i, 4)) for holidayItem in self.relativelyCalendarHolidays: @@ -723,18 +723,18 @@ def dayForWeekday(self, year, month, weekday, repNum): return monthDays[repNum - 1][weekday] def initRepMatrix(self, year, month): - for i in xrange(7): + for i in range(7): self.weekDaysInMonth[i] = (i, 4) startingWeekDay, numDays = calendar.monthrange(year, month) if startingWeekDay > 6: import pdb pdb.set_trace() - for i in xrange(4): + for i in range(4): if numDays == self.numDaysCorMatrix[i][0]: break - for j in xrange(self.numDaysCorMatrix[i][1]): + for j in range(self.numDaysCorMatrix[i][1]): self.weekDaysInMonth[startingWeekDay] = (self.weekDaysInMonth[startingWeekDay][0], self.weekDaysInMonth[startingWeekDay][1] + 1) startingWeekDay = (startingWeekDay + 1) % 7 diff --git a/toontown/ai/NewsManagerAI.py b/toontown/ai/NewsManagerAI.py index 3e1d757dc..142e73636 100644 --- a/toontown/ai/NewsManagerAI.py +++ b/toontown/ai/NewsManagerAI.py @@ -2,7 +2,7 @@ from direct.distributed.DistributedObjectAI import DistributedObjectAI from toontown.toonbase import ToontownGlobals from otp.ai.MagicWordGlobal import * -from HolidayGlobals import * +from .HolidayGlobals import * class NewsManagerAI(DistributedObjectAI): notify = directNotify.newCategory('NewsManagerAI') diff --git a/toontown/ai/PromotionManagerAI.py b/toontown/ai/PromotionManagerAI.py index ef63c4ac3..1767a199f 100644 --- a/toontown/ai/PromotionManagerAI.py +++ b/toontown/ai/PromotionManagerAI.py @@ -6,6 +6,7 @@ from toontown.toonbase.ToontownBattleGlobals import getInvasionMultiplier from toontown.toonbase import ToontownGlobals from toontown.hood.ZoneUtil import isCogHQZone +from functools import reduce MeritMultiplier = 1.0 class PromotionManagerAI: @@ -24,7 +25,7 @@ def recoverMerits(self, av, cogList, zoneId, multiplier = 1, extraMerits = None) extraMerits = [0, 0, 0, 0, 0] if self.air.suitInvasionManager.getInvading() or isCogHQZone(zoneId): multiplier *= getInvasionMultiplier() - for i in xrange(len(extraMerits)): + for i in range(len(extraMerits)): if CogDisguiseGlobals.isSuitComplete(av.getCogParts(), i): meritsRecovered[i] += extraMerits[i] self.notify.debug('recoverMerits: extra merits = %s' % extraMerits[i]) @@ -53,7 +54,7 @@ def recoverMerits(self, av, cogList, zoneId, multiplier = 1, extraMerits = None) if meritsRecovered != [0, 0, 0, 0, 0]: actualCounted = [0, 0, 0, 0, 0] merits = av.getCogMerits() - for i in xrange(len(meritsRecovered)): + for i in range(len(meritsRecovered)): max = CogDisguiseGlobals.getTotalMerits(av, i) if max: if merits[i] + meritsRecovered[i] <= max: diff --git a/toontown/ai/QuestManagerAI.py b/toontown/ai/QuestManagerAI.py index 513167cdf..77d358741 100644 --- a/toontown/ai/QuestManagerAI.py +++ b/toontown/ai/QuestManagerAI.py @@ -41,7 +41,7 @@ def requestInteract(self, avId, npc): avTrackProgress = av.getTrackProgress() # Iterate through their quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i:i + 5] questId, fromNpcId, toNpcId, rewardId, toonProgress = questDesc questClass = Quests.getQuest(questId) @@ -180,7 +180,7 @@ def nextQuest(self, av, npc, questId): questList = [] # Iterate through their current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i:i + 5] if questDesc[QuestIdIndex] == questId: @@ -198,7 +198,7 @@ def completeQuest(self, av, completeQuestId): avQuests = av.getQuests() # Iterate through their current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i:i + 5] questId, fromNpcId, toNpcId, rewardId, toonProgress = questDesc questClass = Quests.getQuest(questId) @@ -255,7 +255,7 @@ def toonPlayedMinigame(self, av, toons): questList = [] # Iterate through their current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) if isinstance(questClass, Quests.TrolleyQuest): @@ -275,7 +275,7 @@ def toonMadeFriend(self, avId): questList = [] # Iterate through their current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) if isinstance(questClass, Quests.FriendQuest): @@ -295,7 +295,7 @@ def toonUsedPhone(self, avId): questList = [] # Iterate through their current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) if isinstance(questClass, Quests.PhoneQuest): @@ -311,7 +311,7 @@ def toonCaughtFishingItem(self, av): questList = [] # Iterate through their current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) if fishingItem != -1: @@ -339,7 +339,7 @@ def hasTailorClothingTicket(self, av, npc): avQuests = av.getQuests() # Iterate through their current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) if isinstance(questClass, Quests.DeliverItemQuest): @@ -353,7 +353,7 @@ def removeClothingTicket(self, av, npc): avQuests = av.getQuests() # Iterate through their current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) if isinstance(questClass, Quests.DeliverItemQuest): @@ -370,7 +370,7 @@ def recoverItems(self, toon, suitsKilled, zoneId): Index 0: a list of recovered items. Index 1: a list of unrecovered items. """ - recovered, notRecovered = ([] for i in xrange(2)) + recovered, notRecovered = ([] for i in range(2)) for index, quest in enumerate(self.__toonQuestsList2Quests(toon.quests)): if isinstance(quest, Quests.RecoverItemQuest): isComplete = quest.getCompletionStatus(toon, toon.quests[index]) @@ -410,7 +410,7 @@ def toonKilledBuilding(self, av, type, difficulty, floors, zoneId, activeToons): zoneId = ZoneUtil.getBranchZone(zoneId) # Iterate through the avatars current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) if questClass.getCompletionStatus(av, questDesc) == Quests.INCOMPLETE: @@ -433,7 +433,7 @@ def toonKilledCogdo(self, av, type, difficulty, zoneId, activeToons): zoneId = ZoneUtil.getBranchZone(zoneId) # Iterate through the avatars current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) if questClass.getCompletionStatus(av, questDesc) == Quests.INCOMPLETE: @@ -452,7 +452,7 @@ def toonCollectedExp(self, av, expArray): questList = [] # Iterate through the avatars current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) if isinstance(questClass, Quests.TrackExpQuest): @@ -468,7 +468,7 @@ def toonDefeatedFactory(self, av, factoryId, activeVictors): questList = [] # Iterate through the avatars current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) if isinstance(questClass, Quests.FactoryQuest): @@ -484,7 +484,7 @@ def toonDefeatedMint(self, av, mintId, activeVictors): questList = [] # Iterate through the avatars current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) if isinstance(questClass, Quests.MintQuest): @@ -498,7 +498,7 @@ def toonDefeatedStage(self, av, stageId, activeVictors): # Get the avatars current quests. avQuests = av.getQuests() questList = [] - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) if isinstance(questClass, Quests.StageQuest): @@ -512,7 +512,7 @@ def toonDefeatedCountryClub(self, av, clubId, activeVictors): # Get the avatars current quests. avQuests = av.getQuests() questList = [] - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) if isinstance(questClass, Quests.ClubQuest): @@ -526,7 +526,7 @@ def toonDefeatedBoss(self, av, zone, dept, activeVictors): # Get the avatars current quests. avQuests = av.getQuests() questList = [] - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) if isinstance(questClass, Quests.VPQuest): @@ -569,7 +569,7 @@ def toonKilledCogs(self, av, suitsKilled, zoneId, activeToonList): activeToonDoIds = [toon.doId for toon in activeToonList if not None] # Iterate through the avatar's current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i : i + 5] questClass = Quests.getQuest(questDesc[QuestIdIndex]) @@ -597,7 +597,7 @@ def quests(command, arg0=0, arg1=0): currQuests = invoker.getQuests() currentQuestIds = [] - for i in xrange(0, len(currQuests), 5): + for i in range(0, len(currQuests), 5): currentQuestIds.append(currQuests[i]) pocketSize = invoker.getQuestCarryLimit() @@ -616,7 +616,7 @@ def quests(command, arg0=0, arg1=0): elif command == 'add': if arg0: if canCarry: - if arg0 in Quests.QuestDict.keys(): + if arg0 in list(Quests.QuestDict.keys()): quest = Quests.getQuest(arg0) invoker.addQuest(quest, 0) return 'Added QuestID %s'%(arg0) @@ -664,7 +664,7 @@ def quests(command, arg0=0, arg1=0): questList = [] wantedQuestId = currentQuestIds[arg0 - 1] - for i in xrange(0, len(currQuests), 5): + for i in range(0, len(currQuests), 5): questDesc = currQuests[i : i + 5] if questDesc[0] == wantedQuestId: @@ -674,11 +674,11 @@ def quests(command, arg0=0, arg1=0): invoker.b_setQuests(questList) return 'Set quest slot %s progress to %s'%(arg0, arg1) - elif arg0 in Quests.QuestDict.keys(): + elif arg0 in list(Quests.QuestDict.keys()): if arg0 in currentQuestIds: questList = [] - for i in xrange(0, len(currQuests), 5): + for i in range(0, len(currQuests), 5): questDesc = currQuests[i : i + 5] if questDesc[0] == arg0: diff --git a/toontown/ai/ServerEventBuffer.py b/toontown/ai/ServerEventBuffer.py index 9720938a2..b28dad290 100644 --- a/toontown/ai/ServerEventBuffer.py +++ b/toontown/ai/ServerEventBuffer.py @@ -54,7 +54,7 @@ def flush(self): if not len(self.events): return msg = '' - eventNames = self.events.keys() + eventNames = list(self.events.keys()) eventNames.sort() for eventName in eventNames: msg += '%s:%s' % (eventName, self.events[eventName]) diff --git a/toontown/ai/ServiceStart.py b/toontown/ai/ServiceStart.py index a188b0a68..bdc80ab96 100644 --- a/toontown/ai/ServiceStart.py +++ b/toontown/ai/ServiceStart.py @@ -1,8 +1,8 @@ -import __builtin__ +import builtins -__builtin__.process = 'ai' +builtins.process = 'ai' -__builtin__.__dict__.update(__import__('panda3d.core', fromlist = ['*']).__dict__) +builtins.__dict__.update(__import__('panda3d.core', fromlist = ['*']).__dict__) from direct.extensions_native import HTTPChannel_extensions diff --git a/toontown/ai/ToontownAIRepository.py b/toontown/ai/ToontownAIRepository.py index 7fff0462e..34e0d4df3 100644 --- a/toontown/ai/ToontownAIRepository.py +++ b/toontown/ai/ToontownAIRepository.py @@ -1,4 +1,4 @@ -import httplib, json +import http.client, json from direct.distributed.PyDatagram import * from panda3d.core import * from otp.ai.AIZoneData import AIZoneDataStore diff --git a/toontown/battle/BattleCalculatorAI.py b/toontown/battle/BattleCalculatorAI.py index 74dc1b3d7..ddf8cb416 100644 --- a/toontown/battle/BattleCalculatorAI.py +++ b/toontown/battle/BattleCalculatorAI.py @@ -113,7 +113,7 @@ def __calcToonAtkHit(self, attackIndex, atkTargets): return (0, 0) elif atkTrack == DROP: allLured = True - for i in xrange(len(atkTargets)): + for i in range(len(atkTargets)): if self.__suitIsLured(atkTargets[i].getDoId()): pass else: @@ -130,7 +130,7 @@ def __calcToonAtkHit(self, attackIndex, atkTargets): for currTarget in atkTargets: thisSuitDef = self.__targetDefense(currTarget, atkTrack) if self.__isWet(currTarget.getDoId()): - if currTarget.getDoId() in self.currentlyWetSuits.keys(): + if currTarget.getDoId() in list(self.currentlyWetSuits.keys()): if self.currentlyWetSuits[currTarget.getDoId()][2]: thisSuitDef -= 20 if debug: @@ -324,7 +324,7 @@ def __suitTrapDamage(self, suitId): def addTrainTrapForJoiningSuit(self, suitId): self.notify.debug('addTrainTrapForJoiningSuit suit=%d self.traps=%s' % (suitId, self.traps)) trapInfoToUse = None - for trapInfo in self.traps.values(): + for trapInfo in list(self.traps.values()): if trapInfo[0] == UBER_GAG_LEVEL_INDEX: trapInfoToUse = trapInfo break @@ -393,7 +393,7 @@ def __removeSuitTrap(self, suitId): def __clearTrapCreator(self, creatorId, suitId = None): if suitId == None: - for currTrap in self.traps.keys(): + for currTrap in list(self.traps.keys()): if creatorId == self.traps[currTrap][1]: self.traps[currTrap][1] = 0 @@ -408,7 +408,7 @@ def __trapCreator(self, suitId): def __initTraps(self): self.trainTrapTriggered = False - keysList = self.traps.keys() + keysList = list(self.traps.keys()) for currTrap in keysList: if self.traps[currTrap][0] == TRAP_CONFLICT: del self.traps[currTrap] @@ -424,7 +424,7 @@ def __calcToonAtkHp(self, toonId): validTargetAvail = 0 lureDidDamage = 0 currLureId = -1 - for currTarget in xrange(len(targetList)): + for currTarget in range(len(targetList)): attackLevel = -1 attackTrack = None attackDamage = 0 @@ -547,7 +547,7 @@ def __calcToonAtkHp(self, toonId): toon.addStat(ToontownGlobals.STATS_FIRES, amount=costToFire) if costToFire > abilityToFire: simbase.air.writeServerEvent('suspicious', avId=toonId, issue='Toon attempting to fire a %s cost cog with %s pinkslips' % (costToFire, abilityToFire)) - print 'Not enough PinkSlips to fire cog - print a warning here' + print('Not enough PinkSlips to fire cog - print a warning here') else: suit.skeleRevives = 0 attackDamage = suit.getHP() @@ -704,12 +704,12 @@ def __isRaining(self, toon): return False def checkIfStreetZone(self, toon): - try: + try: if ZoneUtil.getWhereName(toon.zoneId, True) == 'street' and not ZoneUtil.isDynamicZone(toon.zoneId): return True else: return False - except: + except: return False def __attackDamageForTgt(self, attack, tgtPos, suit = 0): @@ -721,7 +721,7 @@ def __attackDamageForTgt(self, attack, tgtPos, suit = 0): def __calcToonAccBonus(self, attackKey): numPrevHits = 0 attackIdx = self.toonAtkOrder.index(attackKey) - for currPrevAtk in xrange(attackIdx - 1, -1, -1): + for currPrevAtk in range(attackIdx - 1, -1, -1): attack = self.battle.toonAttacks[attackKey] atkTrack, atkLevel = self.__getActualTrackLevel(attack) prevAttackKey = self.toonAtkOrder[currPrevAtk] @@ -742,7 +742,7 @@ def __applyToonAttackDamages(self, toonId, hpbonus = 0, kbbonus = 0): track = self.__getActualTrack(attack) if track != NO_ATTACK and track != SOS and track != TRAP and track != NPCSOS: targets = self.__getToonTargets(attack) - for position in xrange(len(targets)): + for position in range(len(targets)): if hpbonus: if targets[position] in self.__createToonTargetList(toonId): damageDone = attack[TOON_HPBONUS_COL] @@ -902,7 +902,7 @@ def __processBonuses(self, hp = 1): self.notify.debug('Processing kbBonuses: ' + repr(self.kbBonuses)) tgtPos = 0 for currTgt in bonusList: - for currAtkType in currTgt.keys(): + for currAtkType in list(currTgt.keys()): if len(currTgt[currAtkType]) > 1 or not hp and len(currTgt[currAtkType]) > 0: totalDmgs = 0 for currDmg in currTgt[currAtkType]: @@ -958,7 +958,7 @@ def __clearAttack(self, attackIdx, toon = 1): self.battle.toonAttacks[attackIdx] = getToonAttack(attackIdx) longest = max(len(self.battle.activeToons), len(self.battle.activeSuits)) taList = self.battle.toonAttacks - for j in xrange(longest): + for j in range(longest): taList[attackIdx][TOON_HP_COL].append(-1) taList[attackIdx][TOON_KBBONUS_COL].append(-1) @@ -1184,18 +1184,18 @@ def __calcSuitTarget(self, attackIndex): suitId = attack[SUIT_ID_COL] if suitId in self.SuitAttackers and random.randint(0, 99) < 75: totalDamage = 0 - for currToon in self.SuitAttackers[suitId].keys(): + for currToon in list(self.SuitAttackers[suitId].keys()): totalDamage += self.SuitAttackers[suitId][currToon] dmgs = [] - for currToon in self.SuitAttackers[suitId].keys(): + for currToon in list(self.SuitAttackers[suitId].keys()): dmgs.append(self.SuitAttackers[suitId][currToon] / totalDamage * 100) dmgIdx = SuitBattleGlobals.pickFromFreqList(dmgs) if dmgIdx == None: toonId = self.__pickRandomToon(suitId) else: - toonId = self.SuitAttackers[suitId].keys()[dmgIdx] + toonId = list(self.SuitAttackers[suitId].keys())[dmgIdx] if toonId == -1 or toonId not in self.battle.activeToons: return -1 self.notify.debug('Suit attacking back at toon ' + str(toonId)) @@ -1264,7 +1264,7 @@ def __createSuitTargetList(self, attackIndex): def __calcSuitAtkHp(self, attackIndex): targetList = self.__createSuitTargetList(attackIndex) attack = self.battle.suitAttacks[attackIndex] - for currTarget in xrange(len(targetList)): + for currTarget in range(len(targetList)): toonId = targetList[currTarget] toon = self.battle.getToon(toonId) result = 0 @@ -1330,7 +1330,7 @@ def __updateSuitAtkStat(self, toonId): def __printSuitAtkStats(self): self.notify.debug('Suit Atk Stats:') - for currTgt in self.suitAtkStats.keys(): + for currTgt in list(self.suitAtkStats.keys()): if currTgt not in self.battle.activeToons: continue tgtPos = self.battle.activeToons.index(currTgt) @@ -1339,7 +1339,7 @@ def __printSuitAtkStats(self): self.notify.debug('\n') def __calculateSuitAttacks(self): - for i in xrange(len(self.battle.suitAttacks)): + for i in range(len(self.battle.suitAttacks)): if i < len(self.battle.activeSuits): suitId = self.battle.activeSuits[i].doId self.battle.suitAttacks[i][SUIT_ID_COL] = suitId @@ -1391,7 +1391,7 @@ def __updateLureTimeouts(self): self.notify.debug('__updateLureTimeouts()') self.notify.debug('Lured suits: ' + str(self.currentlyLuredSuits)) noLongerLured = [] - for currLuredSuit in self.currentlyLuredSuits.keys(): + for currLuredSuit in list(self.currentlyLuredSuits.keys()): self.__incLuredCurrRound(currLuredSuit) if self.__luredMaxRoundsReached(currLuredSuit) or self.__luredWakeupTime(currLuredSuit): noLongerLured.append(currLuredSuit) @@ -1407,7 +1407,7 @@ def __updateWetTimeouts(self): self.notify.debug('__updateWetTimeouts()') self.notify.debug('Wet suits: ' + str(self.currentlyWetSuits)) noLongerWet = [] - for currentlyWetSuit in self.currentlyWetSuits.keys(): + for currentlyWetSuit in list(self.currentlyWetSuits.keys()): self.__incWetCurrRound(currentlyWetSuit) if self.__wetMaxRoundsReached(currentlyWetSuit): noLongerWet.append(currentlyWetSuit) @@ -1430,7 +1430,7 @@ def __initRound(self): for atk in attacks: self.toonAtkOrder.append(atk[TOON_ID_COL]) - for track in xrange(HEAL, DROP + 1): + for track in range(HEAL, DROP + 1): attacks = findToonAttack(self.battle.activeToons, self.battle.toonAttacks, track) if track == TRAP: sortedTraps = [] @@ -1492,12 +1492,12 @@ def __initRound(self): def calculateRound(self): longest = max(len(self.battle.activeToons), len(self.battle.activeSuits)) for t in self.battle.activeToons: - for j in xrange(longest): + for j in range(longest): self.battle.toonAttacks[t][TOON_HP_COL].append(-1) self.battle.toonAttacks[t][TOON_KBBONUS_COL].append(-1) - for i in xrange(4): - for j in xrange(len(self.battle.activeToons)): + for i in range(4): + for j in range(len(self.battle.activeToons)): self.battle.suitAttacks[i][SUIT_HP_COL].append(-1) toonsHit, cogsMiss = self.__initRound() @@ -1540,7 +1540,7 @@ def toonLeftBattle(self, toonId): del self.suitAtkStats[toonId] if not CLEAR_SUIT_ATTACKERS: oldSuitIds = [] - for s in self.SuitAttackers.keys(): + for s in list(self.SuitAttackers.keys()): if toonId in self.SuitAttackers[s]: del self.SuitAttackers[s][toonId] if len(self.SuitAttackers[s]) == 0: @@ -1565,8 +1565,8 @@ def __updateActiveToons(self): self.notify.debug('updateActiveToons()') if not CLEAR_SUIT_ATTACKERS: oldSuitIds = [] - for s in self.SuitAttackers.keys(): - for t in self.SuitAttackers[s].keys(): + for s in list(self.SuitAttackers.keys()): + for t in list(self.SuitAttackers[s].keys()): if t not in self.battle.activeToons: del self.SuitAttackers[s][t] if len(self.SuitAttackers[s]) == 0: @@ -1575,7 +1575,7 @@ def __updateActiveToons(self): for oldSuitId in oldSuitIds: del self.SuitAttackers[oldSuitId] - for trap in self.traps.keys(): + for trap in list(self.traps.keys()): if self.traps[trap][1] not in self.battle.activeToons: self.notify.debug('Trap for toon ' + str(self.traps[trap][1]) + ' will no longer give exp') self.traps[trap][1] = 0 @@ -1584,7 +1584,7 @@ def getSkillGained(self, toonId, track): return BattleExperienceAI.getSkillGained(self.toonSkillPtsGained, toonId, track) def getLuredSuits(self): - luredSuits = self.currentlyLuredSuits.keys() + luredSuits = list(self.currentlyLuredSuits.keys()) self.notify.debug('Lured suits reported to battle: ' + repr(luredSuits)) return luredSuits @@ -1599,11 +1599,11 @@ def __suitIsWet(self, suitId, prevRound = 0): return inList def __findAvailLureId(self, lurerId): - luredSuits = self.currentlyLuredSuits.keys() + luredSuits = list(self.currentlyLuredSuits.keys()) lureIds = [] for currLured in luredSuits: lurerInfo = self.currentlyLuredSuits[currLured][3] - lurers = lurerInfo.keys() + lurers = list(lurerInfo.keys()) for currLurer in lurers: currId = lurerInfo[currLurer][1] if currLurer == lurerId and currId not in lureIds: @@ -1645,7 +1645,7 @@ def __addLuredSuitInfo(self, suitId, currRounds, maxRounds, wakeChance, lurer, l def __getLurers(self, suitId): if self.__suitIsLured(suitId): - return self.currentlyLuredSuits[suitId][3].keys() + return list(self.currentlyLuredSuits[suitId][3].keys()) return [] def __getLuredExpInfo(self, suitId): @@ -1663,10 +1663,10 @@ def __getLuredExpInfo(self, suitId): return returnInfo def __clearLurer(self, lurerId, lureId = -1): - luredSuits = self.currentlyLuredSuits.keys() + luredSuits = list(self.currentlyLuredSuits.keys()) for currLured in luredSuits: lurerInfo = self.currentlyLuredSuits[currLured][3] - lurers = lurerInfo.keys() + lurers = list(lurerInfo.keys()) for currLurer in lurers: if currLurer == lurerId and (lureId == -1 or lureId == lurerInfo[currLurer][1]): del lurerInfo[currLurer] diff --git a/toontown/battle/BattleExperienceAI.py b/toontown/battle/BattleExperienceAI.py index 742dded8a..9eb85ef24 100644 --- a/toontown/battle/BattleExperienceAI.py +++ b/toontown/battle/BattleExperienceAI.py @@ -1,5 +1,5 @@ from direct.directnotify import DirectNotifyGlobal -import httplib +import http.client from toontown.toonbase import ToontownBattleGlobals, ToontownGlobals from toontown.suit import SuitDNA import random @@ -21,7 +21,7 @@ def getBattleExperience(numToons, activeToons, toonExp, toonSkillPtsGained, toon if helpfulToonsList == None: BattleExperienceAINotify.warning('=============\nERROR ERROR helpfulToons=None in assignRewards , tell Red') p = [] - for k in xrange(numToons): + for k in range(numToons): toon = None if k < len(activeToons): toonId = activeToons[k] @@ -40,7 +40,7 @@ def getBattleExperience(numToons, activeToons, toonExp, toonSkillPtsGained, toon p.append(toonId) origExp = toonExp[toonId] earnedExp = [] - for i in xrange(len(ToontownBattleGlobals.Tracks)): + for i in range(len(ToontownBattleGlobals.Tracks)): earnedExp.append(getSkillGained(toonSkillPtsGained, toonId, i)) p.append(origExp) @@ -59,7 +59,7 @@ def getBattleExperience(numToons, activeToons, toonExp, toonSkillPtsGained, toon deathList = [] toonIndices = {} - for i in xrange(len(activeToons)): + for i in range(len(activeToons)): toonIndices[activeToons[i]] = i for deathRecord in suitsKilled: @@ -114,14 +114,14 @@ def getToonUberStatus(toons, numToons): if toon == None: fieldList.append(-1) else: - for trackIndex in xrange(ToontownBattleGlobals.MAX_TRACK_INDEX + 1): + for trackIndex in range(ToontownBattleGlobals.MAX_TRACK_INDEX + 1): toonList.append(toon.inventory.numItem(trackIndex, uberIndex)) fieldList.append(ToontownBattleGlobals.encodeUber(toonList)) lenDif = numToons - len(toons) if lenDif > 0: - for index in xrange(lenDif): + for index in range(lenDif): fieldList.append(-1) return fieldList @@ -140,7 +140,7 @@ def assignRewards(activeToons, toonSkillPtsGained, suitsKilled, zoneId, helpfulT toonExp = 0 expArray = [] numElites = 0 - for i in xrange(len(ToontownBattleGlobals.Tracks)): + for i in range(len(ToontownBattleGlobals.Tracks)): uberIndex = ToontownBattleGlobals.LAST_REGULAR_GAG_LEVEL + 1 exp = getSkillGained(toonSkillPtsGained, toon.doId, i) expArray.append(exp) diff --git a/toontown/battle/BattleProps.py b/toontown/battle/BattleProps.py index 60001bec3..91a0bc8e8 100644 --- a/toontown/battle/BattleProps.py +++ b/toontown/battle/BattleProps.py @@ -272,7 +272,7 @@ def __init__(self): self.propStrings[propName] = (self.getPath(5, 'half-windsor'),) self.propTypes[propName] = 'model' splatAnimFileName = self.getPath(3.5, 'splat-chan') - for splat in Splats.keys(): + for splat in list(Splats.keys()): propName = 'splat-' + splat self.propStrings[propName] = (self.getPath(3.5, 'splat-mod'), splatAnimFileName) self.propTypes[propName] = 'actor' @@ -344,7 +344,7 @@ def makeVariant(self, name): self.props[name].setTexture(tex, 1) elif name == 'dust': bin = 110 - for cloudNum in xrange(1, 12): + for cloudNum in range(1, 12): cloudName = '**/cloud' + str(cloudNum) cloud = self.props[name].find(cloudName) cloud.setBin('fixed', bin) @@ -385,7 +385,7 @@ def makeVariant(self, name): self.props[name] = self.props[name].find('**/trolley_car') def unloadProps(self): - for p in self.props.values(): + for p in list(self.props.values()): if type(p) != type(()): self.__delProp(p) diff --git a/toontown/battle/BattleSounds.py b/toontown/battle/BattleSounds.py index ea8aa4a82..e70458224 100644 --- a/toontown/battle/BattleSounds.py +++ b/toontown/battle/BattleSounds.py @@ -40,7 +40,7 @@ def getSound(self, name): found = vfs.resolveFilename(filename, self.sfxSearchPath) if not found: self.notify.warning('%s not found on:' % name) - print self.sfxSearchPath + print((self.sfxSearchPath)) else: return self.mgr.getSound(filename.getFullpath()) return self.mgr.getNullSound() diff --git a/toontown/battle/DistributedBattleBase.py b/toontown/battle/DistributedBattleBase.py index 707acc407..81b85205b 100644 --- a/toontown/battle/DistributedBattleBase.py +++ b/toontown/battle/DistributedBattleBase.py @@ -105,7 +105,7 @@ def storeInterval(self, interval, name): self.activeIntervals[name] = interval def __cleanupIntervals(self): - for interval in self.activeIntervals.values(): + for interval in list(self.activeIntervals.values()): interval.finish() DelayDelete.cleanupDelayDeletes(interval) diff --git a/toontown/battle/DistributedBattleBaseAI.py b/toontown/battle/DistributedBattleBaseAI.py index cc4914b0e..e1d939242 100644 --- a/toontown/battle/DistributedBattleBaseAI.py +++ b/toontown/battle/DistributedBattleBaseAI.py @@ -129,7 +129,7 @@ def delete(self): del suit.battleTrap del self.finishCallback - for petProxy in self.pets.values(): + for petProxy in list(self.pets.values()): petProxy.requestDelete() DistributedObjectAI.DistributedObjectAI.delete(self) @@ -859,7 +859,7 @@ def __removeAdjustingResponse(self, toonId): def __addJoinResponse(self, avId, taskName, toon = 0): if toon == 1: - for jr in self.joinResponses.values(): + for jr in list(self.joinResponses.values()): jr[avId] = 0 self.joinResponses[avId] = {} @@ -871,7 +871,7 @@ def __addJoinResponse(self, avId, taskName, toon = 0): def __removeJoinResponses(self, avId): self.__removeJoinResponse(avId) removedOne = 0 - for j in self.joinResponses.values(): + for j in list(self.joinResponses.values()): if avId in j: del j[avId] removedOne = 1 @@ -895,7 +895,7 @@ def __allToonsRespondedJoin(self, avId): return 1 def __cleanupJoinResponses(self): - for jr in self.joinResponses.values(): + for jr in list(self.joinResponses.values()): taskMgr.remove(jr['taskName']) del jr @@ -1516,7 +1516,7 @@ def __movieDone(self): deadSuits.append(target) self.exitedToons = [] - for suitKey in trapDict.keys(): + for suitKey in list(trapDict.keys()): attackList = trapDict[suitKey] attack = attackList[0] target = self.findSuit(attack[TOON_TGT_COL]) @@ -1709,7 +1709,7 @@ def enterResume(self): eventMsg[msgName] = 1 msgText = '' - for msgName, count in eventMsg.items(): + for msgName, count in list(eventMsg.items()): if msgText != '': msgText += ',' msgText += '%s%s' % (count, msgName) diff --git a/toontown/battle/DistributedBattleDiners.py b/toontown/battle/DistributedBattleDiners.py index a16efd050..0cc0dd46a 100644 --- a/toontown/battle/DistributedBattleDiners.py +++ b/toontown/battle/DistributedBattleDiners.py @@ -40,7 +40,7 @@ def doInitialSuitsJoining(self, ts, name, callback): def moveSuitsToInitialPos(self): battlePts = self.suitPoints[len(self.suitPendingPoints) - 1] - for i in xrange(len(self.suits)): + for i in range(len(self.suits)): suit = self.suits[i] suit.reparentTo(self) destPos, destHpr = self.getActorPosHpr(suit, self.suits) diff --git a/toontown/battle/DistributedBattleWaiters.py b/toontown/battle/DistributedBattleWaiters.py index 400675e0d..756d86cb9 100644 --- a/toontown/battle/DistributedBattleWaiters.py +++ b/toontown/battle/DistributedBattleWaiters.py @@ -43,7 +43,7 @@ def doInitialSuitsJoining(self, ts, name, callback): def moveSuitsToInitialPos(self): battlePts = self.suitPoints[len(self.suitPendingPoints) - 1] - for i in xrange(len(self.suits)): + for i in range(len(self.suits)): suit = self.suits[i] suit.reparentTo(self) destPos, destHpr = self.getActorPosHpr(suit, self.suits) diff --git a/toontown/battle/FireCogPanel.py b/toontown/battle/FireCogPanel.py index a7618112c..0d4fa797f 100644 --- a/toontown/battle/FireCogPanel.py +++ b/toontown/battle/FireCogPanel.py @@ -26,7 +26,7 @@ def load(self): self.textFrame = DirectFrame(parent=self.frame, relief=None, image=gui.find('**/PckMn_Select_Tab'), image_color=Vec4(1, 1, 0, 1), image_scale=(1.0, 1.0, 2.0), text='', text_fg=Vec4(0, 0, 0, 1), text_pos=(0, 0.02, 0), text_scale=TTLocalizer.FCPtextFrame, pos=(-0.013, 0, 0.013)) self.textFrame['text'] = TTLocalizer.FireCogTitle % localAvatar.getPinkSlips() self.avatarButtons = [] - for i in xrange(4): + for i in range(4): button = DirectButton(parent=self.frame, relief=None, text='', text_fg=Vec4(0, 0, 0, 1), text_scale=0.067, text_pos=(0, -0.015, 0), textMayChange=1, image_scale=(1.0, 1.0, 1.0), image=(gui.find('**/PckMn_Arrow_Up'), gui.find('**/PckMn_Arrow_Dn'), gui.find('**/PckMn_Arrow_Rlvr')), command=self.__handleAvatar, extraArgs=[i]) button.setScale(1, 1, 1) button.setPos(0, 0, 0.2) @@ -88,7 +88,7 @@ def adjustToons(self, numToons, localNum): def __placeButtons(self, numAvatars, invalidTargets, localNum, fireCosts): canfire = 0 - for i in xrange(4): + for i in range(4): if numAvatars > i and i not in invalidTargets and i != localNum: self.avatarButtons[i].show() self.avatarButtons[i]['text'] = '' diff --git a/toontown/battle/Movie.py b/toontown/battle/Movie.py index a7ab824dd..2432259c1 100644 --- a/toontown/battle/Movie.py +++ b/toontown/battle/Movie.py @@ -123,14 +123,14 @@ def restore(self): legsParts = toon.getLegsParts() partsList = [headParts, torsoParts, legsParts] for parts in partsList: - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): nextPart = parts.getPath(partNum) nextPart.clearColorScale() nextPart.clearTransparency() if self.restoreHips == 1: parts = toon.getHipsParts() - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): nextPart = parts.getPath(partNum) props = nextPart.getChildren() for prop in props: @@ -145,7 +145,7 @@ def restore(self): if self.restoreToonScale == 1: toon.setScale(1) headParts = toon.getHeadParts() - for partNum in xrange(0, headParts.getNumPaths()): + for partNum in range(0, headParts.getNumPaths()): part = headParts.getPath(partNum) part.setHpr(0, 0, 0) part.setPos(0, 0, 0) @@ -153,7 +153,7 @@ def restore(self): arms = toon.findAllMatches('**/arms') sleeves = toon.findAllMatches('**/sleeves') hands = toon.findAllMatches('**/hands') - for partNum in xrange(0, arms.getNumPaths()): + for partNum in range(0, arms.getNumPaths()): armPart = arms.getPath(partNum) sleevePart = sleeves.getPath(partNum) handsPart = hands.getPath(partNum) @@ -728,7 +728,7 @@ def __genToonAttackDicts(self, toons, suits, toonAttacks): else: suitIndex = self.battle.activeSuits.index(target) leftSuits = [] - for si in xrange(0, suitIndex): + for si in range(0, suitIndex): asuit = self.battle.activeSuits[si] if self.battle.isSuitLured(asuit) == 0: leftSuits.append(asuit) @@ -736,7 +736,7 @@ def __genToonAttackDicts(self, toons, suits, toonAttacks): lenSuits = len(self.battle.activeSuits) rightSuits = [] if lenSuits > suitIndex + 1: - for si in xrange(suitIndex + 1, lenSuits): + for si in range(suitIndex + 1, lenSuits): asuit = self.battle.activeSuits[si] if self.battle.isSuitLured(asuit) == 0: rightSuits.append(asuit) @@ -854,13 +854,13 @@ def __genSuitAttackDicts(self, toons, suits, suitAttacks): tdict['died'] = toonDied toonIndex = self.battle.activeToons.index(target) rightToons = [] - for ti in xrange(0, toonIndex): + for ti in range(0, toonIndex): rightToons.append(self.battle.activeToons[ti]) lenToons = len(self.battle.activeToons) leftToons = [] if lenToons > toonIndex + 1: - for ti in xrange(toonIndex + 1, lenToons): + for ti in range(toonIndex + 1, lenToons): leftToons.append(self.battle.activeToons[ti]) tdict['leftToons'] = leftToons diff --git a/toontown/battle/MovieCamera.py b/toontown/battle/MovieCamera.py index b3fe5e620..83dfe8364 100644 --- a/toontown/battle/MovieCamera.py +++ b/toontown/battle/MovieCamera.py @@ -37,7 +37,7 @@ def chooseHealOpenShot(heals, attackDuration, isUber = 0): if isUber: duration = 5.0 shotChoices = [toonGroupShot] - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -48,7 +48,7 @@ def chooseHealMidShot(heals, attackDuration, isUber = 0): if isUber: duration = 2.1 shotChoices = [toonGroupHighShot] - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -58,7 +58,7 @@ def chooseHealCloseShot(heals, openDuration, openName, attackDuration, isUber = shotChoices = [toonGroupShot] if isUber: shotChoices = [allGroupLowShot] - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -78,7 +78,7 @@ def chooseTrapOpenShot(traps, attackDuration): av = None duration = 3.0 shotChoices = [allGroupLowShot] - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -86,7 +86,7 @@ def chooseTrapCloseShot(traps, openDuration, openName, attackDuration): av = None duration = attackDuration - openDuration shotChoices = [allGroupLowShot] - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -106,7 +106,7 @@ def chooseLureOpenShot(lures, attackDuration): av = None duration = 3.0 shotChoices = [allGroupLowShot] - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -124,7 +124,7 @@ def chooseLureCloseShot(lures, openDuration, openName, attackDuration): av = lures[0]['toon'] else: shotChoices = [allGroupLowShot] - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track def avatarTrainShot(avatar, duration): @@ -161,7 +161,7 @@ def chooseSoundOpenShot(sounds, targets, attackDuration): shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot] else: notify.error('Bad number of sounds: %s' % numSounds) - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -179,7 +179,7 @@ def chooseSoundCloseShot(sounds, targets, openDuration, openName, attackDuration shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot] else: notify.error('Bad number of suits: %s' % numSuits) - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -209,7 +209,7 @@ def chooseThrowOpenShot(throws, suitThrowsDict, attackDuration): shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot] else: notify.error('Bad number of throws: %s' % numThrows) - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -218,7 +218,7 @@ def chooseThrowCloseShot(throws, suitThrowsDict, openDuration, openName, attackD av = None duration = attackDuration - openDuration if numSuits == 1: - av = base.cr.doId2do[suitThrowsDict.keys()[0]] + av = base.cr.doId2do[list(suitThrowsDict.keys())[0]] shotChoices = [avatarCloseUpThrowShot, avatarCloseUpThreeQuarterLeftShot, allGroupLowShot, @@ -227,7 +227,7 @@ def chooseThrowCloseShot(throws, suitThrowsDict, openDuration, openName, attackD shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot] else: notify.error('Bad number of suits: %s' % numSuits) - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -255,7 +255,7 @@ def chooseSquirtOpenShot(squirts, suitSquirtsDict, attackDuration): shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot] else: notify.error('Bad number of squirts: %s' % numSquirts) - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -264,7 +264,7 @@ def chooseSquirtCloseShot(squirts, suitSquirtsDict, openDuration, openName, atta av = None duration = attackDuration - openDuration if numSuits == 1: - av = base.cr.doId2do[suitSquirtsDict.keys()[0]] + av = base.cr.doId2do[list(suitSquirtsDict.keys())[0]] shotChoices = [avatarCloseUpThrowShot, avatarCloseUpThreeQuarterLeftShot, allGroupLowShot, @@ -273,7 +273,7 @@ def chooseSquirtCloseShot(squirts, suitSquirtsDict, openDuration, openName, atta shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot] else: notify.error('Bad number of suits: %s' % numSuits) - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track def chooseZapShot(zaps, attackDuration, enterDuration = 0.0, exitDuration = 0.0): @@ -292,7 +292,7 @@ def chooseZapOpenShot(zaps, attackDuration): av = None duration = 3.0 shotChoices = [avatarBehindShot, allGroupLowShot] - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -302,7 +302,7 @@ def chooseZapCloseShot(zaps, openDuration, openName, attackDuration): hasTrainTrackTrap = False battle = zaps[0]['battle'] shotChoices = [avatarBehindShot] - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -332,7 +332,7 @@ def chooseDropOpenShot(drops, suitDropsDict, attackDuration): shotChoices = [allGroupLowShot, suitGroupThreeQuarterLeftBehindShot] else: notify.error('Bad number of drops: %s' % numDrops) - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -341,7 +341,7 @@ def chooseDropCloseShot(drops, suitDropsDict, openDuration, openName, attackDura av = None duration = attackDuration - openDuration if numSuits == 1: - av = base.cr.doId2do[suitDropsDict.keys()[0]] + av = base.cr.doId2do[list(suitDropsDict.keys())[0]] shotChoices = [avatarCloseUpThrowShot, avatarCloseUpThreeQuarterLeftShot, allGroupLowShot, @@ -359,7 +359,7 @@ def chooseNPCEnterShot(enters, entersDuration): av = None duration = entersDuration shotChoices = [toonGroupShot] - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -367,7 +367,7 @@ def chooseNPCExitShot(exits, exitsDuration): av = None duration = exitsDuration shotChoices = [toonGroupShot] - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -590,7 +590,7 @@ def chooseSuitCloseShot(attack, openDuration, openName, attackDuration): diedTrack = pbpText.getToonsDiedInterval(diedTextList, duration) else: notify.error('Bad groupStatus: %s' % groupStatus) - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) if diedTrack == None: return track else: @@ -636,7 +636,7 @@ def chooseSOSShot(av, duration): avatarBehindShot, avatarBehindHighShot, suitGroupThreeQuarterLeftBehindShot] - track = apply(random.choice(shotChoices), [av, duration]) + track = random.choice(shotChoices)(*[av, duration]) return track @@ -746,7 +746,7 @@ def shakeCameraTrack(intensity, shakeWaitInterval = shakeWaitInterval, quake = q vertShakeTrack = Sequence(Wait(shakeWaitInterval), Func(camera.setZ, camera.getZ() + intensity / 2), Wait(shakeDuration / 2), Func(camera.setZ, camera.getZ() - intensity), Wait(shakeDuration / 2), Func(camera.setZ, camera.getZ() + intensity / 2)) horizShakeTrack = Sequence(Wait(shakeWaitInterval - shakeDuration / 2), Func(camera.setY, camera.getY() + intensity / 4), Wait(shakeDuration / 2), Func(camera.setY, camera.getY() - intensity / 2), Wait(shakeDuration / 2), Func(camera.setY, camera.getY() + intensity / 4), Wait(shakeDuration / 2), Func(camera.lookAt, Point3(0, 0, 0))) shakeTrack = Sequence() - for i in xrange(0, numShakes): + for i in range(0, numShakes): if quake == 0: shakeTrack.append(vertShakeTrack) else: @@ -961,7 +961,7 @@ def randomCameraSelection(suit, attack, attackDuration, openShotDuration): if openShotDuration > attackDuration: openShotDuration = attackDuration closeShotDuration = attackDuration - openShotDuration - openShot = apply(random.choice(shotChoices), [suit, openShotDuration]) + openShot = random.choice(shotChoices)(*[suit, openShotDuration]) closeShot = chooseSuitCloseShot(attack, closeShotDuration, openShot.getName(), attackDuration) return Sequence(openShot, closeShot) @@ -1014,8 +1014,8 @@ def chooseFireOpenShot(throws, suitThrowsDict, attackDuration): else: notify.error('Bad number of throws: %s' % numThrows) shotChoice = random.choice(shotChoices) - track = apply(shotChoice, [av, duration]) - print 'chooseFireOpenShot %s' % shotChoice + track = shotChoice(*[av, duration]) + print(('chooseFireOpenShot %s' % shotChoice)) return track @@ -1024,7 +1024,7 @@ def chooseFireCloseShot(throws, suitThrowsDict, openDuration, openName, attackDu av = None duration = attackDuration - openDuration if numSuits == 1: - av = base.cr.doId2do[suitThrowsDict.keys()[0]] + av = base.cr.doId2do[list(suitThrowsDict.keys())[0]] shotChoices = [avatarCloseUpFireShot, avatarCloseUpThreeQuarterLeftFireShot, allGroupLowShot, @@ -1034,8 +1034,8 @@ def chooseFireCloseShot(throws, suitThrowsDict, openDuration, openName, attackDu else: notify.error('Bad number of suits: %s' % numSuits) shotChoice = random.choice(shotChoices) - track = apply(shotChoice, [av, duration]) - print 'chooseFireOpenShot %s' % shotChoice + track = shotChoice(*[av, duration]) + print(('chooseFireOpenShot %s' % shotChoice)) return track diff --git a/toontown/battle/MovieDrop.py b/toontown/battle/MovieDrop.py index bf873d34b..e4d3b20e5 100644 --- a/toontown/battle/MovieDrop.py +++ b/toontown/battle/MovieDrop.py @@ -60,7 +60,7 @@ def doDrops(drops): else: suitDropsDict[suitId] = [(drop, target)] - suitDrops = suitDropsDict.values() + suitDrops = list(suitDropsDict.values()) def compFunc(a, b): if len(a) > len(b): @@ -165,7 +165,7 @@ def __doGroupDrops(groupDrops): numTargets = len(targets) closestTarget = -1 nearestDistance = 100000.0 - for i in xrange(numTargets): + for i in range(numTargets): suit = drop['target'][i]['suit'] suitPos = suit.getPos(battle) displacement = Vec3(centerPos) @@ -197,7 +197,7 @@ def __dropGroupObject(drop, delay, closestTarget, alreadyDodged, alreadyTeased): npcDrops = {} npcs = [] returnedParallel = __dropObject(drop, delay, objName, level, alreadyDodged, alreadyTeased, npcs, target, npcDrops) - for i in xrange(len(drop['target'])): + for i in range(len(drop['target'])): target = drop['target'][i] suitTrack = __createSuitTrack(drop, delay, level, alreadyDodged, alreadyTeased, target, npcs) if suitTrack: diff --git a/toontown/battle/MovieFire.py b/toontown/battle/MovieFire.py index 0a645f408..06b6441a7 100644 --- a/toontown/battle/MovieFire.py +++ b/toontown/battle/MovieFire.py @@ -51,7 +51,7 @@ def doFires(fires): else: suitFiresDict[suitId] = [fire] - suitFires = suitFiresDict.values() + suitFires = list(suitFiresDict.values()) def compFunc(a, b): if len(a) > len(b): return 1 @@ -153,7 +153,7 @@ def __doSuitFires(fires): showSuitCannon = 0 else: suitList.remove(fire['target'][i]['suit']) - for x in xrange(len(fire['target'])): + for x in range(len(fire['target'])): tracks = __throwPie(fire, i, delay, hitCount, showSuitCannon) i = i + 1 if tracks: @@ -209,7 +209,7 @@ def __propPreflight(props, suit, toon, battle): toon.update(0) prop.wrtReparentTo(battle) props[1].reparentTo(hidden) - for ci in xrange(prop.getNumChildren()): + for ci in range(prop.getNumChildren()): prop.getChild(ci).setHpr(0, -90, 0) targetPnt = MovieUtil.avatarFacePoint(suit, other=battle) @@ -221,7 +221,7 @@ def __propPreflightGroup(props, suits, toon, battle): toon.update(0) prop.wrtReparentTo(battle) props[1].reparentTo(hidden) - for ci in xrange(prop.getNumChildren()): + for ci in range(prop.getNumChildren()): prop.getChild(ci).setHpr(0, -90, 0) avgTargetPt = Point3(0, 0, 0) diff --git a/toontown/battle/MovieLure.py b/toontown/battle/MovieLure.py index e9f2e3f74..f0b6b0802 100644 --- a/toontown/battle/MovieLure.py +++ b/toontown/battle/MovieLure.py @@ -167,7 +167,7 @@ def __createMagnetMultiTrack(lure, magnet, pos, hpr, scale, isSmallMagnet = 1, n suitTrack.append(Func(suit.loop, 'neutral')) suitTrack.append(Wait(suitDelay)) suitTrack.append(ActorInterval(suit, 'landing', startTime=2.37, endTime=1.82)) - for i in xrange(0, numShakes): + for i in range(0, numShakes): suitTrack.append(ActorInterval(suit, 'landing', startTime=1.82, endTime=1.16, duration=shakeDuration)) suitTrack.append(ActorInterval(suit, 'landing', startTime=1.16, endTime=0.7)) @@ -237,8 +237,8 @@ def __createHypnoGogglesMultiTrack(lure, npcs = []): if revived != 0: suitTrack.append(MovieUtil.createSuitReviveTrack(suit, toon, battle, npcs)) elif died != 0: - print trapProp - print suit + print(trapProp) + print(suit) if trapProp: if not (trapProp.getName() == 'tnt' and suit.maxHP <= 42): suitTrack.append(MovieUtil.createSuitDeathTrack(suit, toon, battle, npcs)) @@ -525,7 +525,7 @@ def getSplicedLerpAnimsTrack(object, animName, origDuration, newDuration, startT numIvals = origDuration * fps timeInterval = newDuration / numIvals animInterval = origDuration / numIvals - for i in xrange(0, int(numIvals)): + for i in range(0, int(numIvals)): track.append(Wait(timeInterval)) track.append(ActorInterval(object, animName, startTime=startTime + addition, duration=animInterval)) addition += animInterval diff --git a/toontown/battle/MovieSquirt.py b/toontown/battle/MovieSquirt.py index 5885f7142..0fa60f32a 100644 --- a/toontown/battle/MovieSquirt.py +++ b/toontown/battle/MovieSquirt.py @@ -50,7 +50,7 @@ def doSquirts(squirts): else: suitSquirtsDict[suitId] = [squirt] - suitSquirts = suitSquirtsDict.values() + suitSquirts = list(suitSquirtsDict.values()) def compFunc(a, b): if len(a) > len(b): @@ -224,7 +224,7 @@ def __getSuitTrack(suit, tContact, tDodge, hp, hpbonus, kbbonus, anim, died, lef def say(statement): - print statement + print(statement) def __getSoundTrack(level, hitSuit, delay, node = None): @@ -642,7 +642,7 @@ def getCloudTrack(cloud, suit, cloudPosPoint, scaleUpPoint, rainEffects, rainDel delay = trickleDuration = cloudHold * 0.25 trickleTrack = Sequence(Func(battle.movie.needRestoreParticleEffect, trickleEffect), ParticleInterval(trickleEffect, cloud, worldRelative=0, duration=trickleDuration, cleanup=True), Func(battle.movie.clearRestoreParticleEffect, trickleEffect)) track.append(trickleTrack) - for i in xrange(0, 3): + for i in range(0, 3): dur = cloudHold - 2 * trickleDuration ptrack.append(Sequence(Func(battle.movie.needRestoreParticleEffect, rainEffects[i]), Wait(delay), ParticleInterval(rainEffects[i], cloud, worldRelative=0, duration=dur, cleanup=True), Func(battle.movie.clearRestoreParticleEffect, rainEffects[i]))) delay += effectDelay @@ -716,13 +716,13 @@ def getGeyserTrack(geyser, suit, geyserPosPoint, scaleUpPoint, rainEffects, rain geyserMound = MovieUtil.copyProp(geyser) geyserRemoveM = geyserMound.findAllMatches('**/Splash*') geyserRemoveM.addPathsFrom(geyserMound.findAllMatches('**/spout')) - for i in xrange(geyserRemoveM.getNumPaths()): + for i in range(geyserRemoveM.getNumPaths()): geyserRemoveM[i].removeNode() geyserWater = MovieUtil.copyProp(geyser) geyserRemoveW = geyserWater.findAllMatches('**/hole') geyserRemoveW.addPathsFrom(geyserWater.findAllMatches('**/shadow')) - for i in xrange(geyserRemoveW.getNumPaths()): + for i in range(geyserRemoveW.getNumPaths()): geyserRemoveW[i].removeNode() track = Sequence(Wait(rainDelay), Func(MovieUtil.showProp, geyserMound, battle, suit.getPos(battle)), Func(MovieUtil.showProp, geyserWater, battle, suit.getPos(battle)), LerpScaleInterval(geyserWater, 1.0, scaleUpPoint, startScale=MovieUtil.PNT3_NEARZERO), Wait(geyserHold * 0.5), LerpScaleInterval(geyserWater, 0.5, MovieUtil.PNT3_NEARZERO, startScale=scaleUpPoint)) diff --git a/toontown/battle/MovieSuitAttacks.py b/toontown/battle/MovieSuitAttacks.py index 61d80433d..06674ccb4 100644 --- a/toontown/battle/MovieSuitAttacks.py +++ b/toontown/battle/MovieSuitAttacks.py @@ -555,7 +555,7 @@ def getToonTrack(attack, damageDelay = 1e-06, damageAnimNames = None, dodgeDelay def getToonTracks(attack, damageDelay = 1e-06, damageAnimNames = None, dodgeDelay = 1e-06, dodgeAnimNames = None, splicedDamageAnims = None, splicedDodgeAnims = None, showDamageExtraTime = 0.01, showMissedExtraTime = 0.5): toonTracks = Parallel() targets = attack['target'] - for i in xrange(len(targets)): + for i in range(len(targets)): tgt = targets[i] toonTracks.append(getToonTrack(attack, damageDelay, damageAnimNames, dodgeDelay, dodgeAnimNames, splicedDamageAnims, splicedDodgeAnims, target=tgt, showDamageExtraTime=showDamageExtraTime, showMissedExtraTime=showMissedExtraTime)) @@ -632,7 +632,7 @@ def getPropThrowTrack(attack, prop, hitPoints = [], missPoints = [], hitDuration battle = attack['battle'] def getLambdas(list, prop, toon): - for i in xrange(len(list)): + for i in range(len(list)): if list[i] == 'face': list[i] = lambda toon = toon: __toonFacePoint(toon) elif list[i] == 'miss': @@ -654,12 +654,12 @@ def getLambdas(list, prop, toon): if lookAt != 'none': propTrack.append(Func(prop.lookAt, lookAt)) if dmg > 0: - for i in xrange(len(hitPoints)): + for i in range(len(hitPoints)): pos = hitPoints[i] propTrack.append(LerpPosInterval(prop, hitDuration, pos=pos)) else: - for i in xrange(len(missPoints)): + for i in range(len(missPoints)): pos = missPoints[i] propTrack.append(LerpPosInterval(prop, missDuration, pos=pos)) @@ -761,7 +761,7 @@ def getSplicedLerpAnims(animName, origDuration, newDuration, startTime = 0, fps animInterval = origDuration / numAnims if reverse == 1: animInterval = -animInterval - for i in xrange(0, int(numAnims)): + for i in range(0, int(numAnims)): anims.append([animName, timeInterval, startTime + addition, @@ -913,7 +913,7 @@ def doFillWithLead(attack): def colorParts(parts): track = Parallel() - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): nextPart = parts.getPath(partNum) track.append(Func(nextPart.setColorScale, Vec4(0, 0, 0, 1))) @@ -921,7 +921,7 @@ def colorParts(parts): def resetParts(parts): track = Parallel() - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): nextPart = parts.getPath(partNum) track.append(Func(nextPart.clearColorScale)) @@ -988,13 +988,13 @@ def prepSplash(splash, targetPoint): splashTrack = Sequence(Func(battle.movie.needRestoreRenderProp, splash), Wait(1.65), Func(prepSplash, splash, __toonFacePoint(toon)), ActorInterval(splash, 'splash-from-splat'), Func(MovieUtil.removeProp, splash), Func(battle.movie.clearRenderProp, splash)) headParts = toon.getHeadParts() splashTrack.append(Func(battle.movie.needRestoreColor)) - for partNum in xrange(0, headParts.getNumPaths()): + for partNum in range(0, headParts.getNumPaths()): nextPart = headParts.getPath(partNum) splashTrack.append(Func(nextPart.setColorScale, Vec4(0, 0, 0, 1))) splashTrack.append(Func(MovieUtil.removeProp, splash)) splashTrack.append(Wait(2.6)) - for partNum in xrange(0, headParts.getNumPaths()): + for partNum in range(0, headParts.getNumPaths()): nextPart = headParts.getPath(partNum) splashTrack.append(Func(nextPart.clearColorScale)) @@ -1046,7 +1046,7 @@ def doRubOut(attack): def hideParts(parts): track = Parallel() - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): nextPart = parts.getPath(partNum) track.append(Func(nextPart.setTransparency, 1)) track.append(LerpFunctionInterval(nextPart.setAlphaScale, fromData=1, toData=0, duration=0.2)) @@ -1055,7 +1055,7 @@ def hideParts(parts): def showParts(parts): track = Parallel() - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): nextPart = parts.getPath(partNum) track.append(Func(nextPart.clearColorScale)) track.append(Func(nextPart.clearTransparency)) @@ -1334,7 +1334,7 @@ def doBuzzWord(attack): 'buzzwords-main', 'buzzwords-over', 'buzzwords-syn'] - for i in xrange(0, 5): + for i in range(0, 5): effect = BattleParticles.createParticleEffect('BuzzWord') if random.random() > 0.5: BattleParticles.setEffectTexture(effect, texturesList[i], color=Vec4(1, 0.94, 0.02, 1)) @@ -1600,10 +1600,10 @@ def doReOrg(attack): partTrack = getPartTrack(sprayEffect, 1.0, 1.9, [sprayEffect, suit, 0]) if dmg > 0: headParts = toon.getHeadParts() - print '***********headParts pos=', headParts[0].getPos() - print '***********headParts hpr=', headParts[0].getHpr() + print(('***********headParts pos=', headParts[0].getPos())) + print(('***********headParts hpr=', headParts[0].getHpr())) headTracks = Parallel() - for partNum in xrange(0, headParts.getNumPaths()): + for partNum in range(0, headParts.getNumPaths()): part = headParts.getPath(partNum) x = part.getX() y = part.getY() @@ -1621,8 +1621,8 @@ def getChestTrack(part, attackDelay = attackDelay): arms = toon.findAllMatches('**/arms') sleeves = toon.findAllMatches('**/sleeves') hands = toon.findAllMatches('**/hands') - print '*************arms hpr=', arms[0].getHpr() - for partNum in xrange(0, arms.getNumPaths()): + print(('*************arms hpr=', arms[0].getHpr())) + for partNum in range(0, arms.getNumPaths()): chestTracks.append(getChestTrack(arms.getPath(partNum))) chestTracks.append(getChestTrack(sleeves.getPath(partNum))) chestTracks.append(getChestTrack(hands.getPath(partNum))) @@ -1710,7 +1710,7 @@ def doGlowerPower(attack): battle = attack['battle'] leftKnives = [] rightKnives = [] - for i in xrange(0, 3): + for i in range(0, 3): leftKnives.append(globalPropPool.getProp('dagger')) rightKnives.append(globalPropPool.getProp('dagger')) @@ -1727,7 +1727,7 @@ def doGlowerPower(attack): rightPosPoints = [Point3(-0.4, 3.8, 3.7), MovieUtil.PNT3_ZERO] leftKnifeTracks = Parallel() rightKnifeTracks = Parallel() - for i in xrange(0, 3): + for i in range(0, 3): knifeDelay = 0.11 leftTrack = Sequence() leftTrack.append(Wait(1.1)) @@ -1832,7 +1832,7 @@ def doHeadShrink(attack): def scaleHeadParallel(scale, duration, headParts = headParts): headTracks = Parallel() - for partNum in xrange(0, headParts.getNumPaths()): + for partNum in range(0, headParts.getNumPaths()): nextPart = headParts.getPath(partNum) headTracks.append(LerpScaleInterval(nextPart, duration, Point3(scale, scale, scale))) @@ -2190,7 +2190,7 @@ def doHotAir(attack): def changeColor(parts): track = Parallel() - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): nextPart = parts.getPath(partNum) track.append(Func(nextPart.setColorScale, Vec4(0, 0, 0, 1))) @@ -2198,7 +2198,7 @@ def changeColor(parts): def resetColor(parts): track = Parallel() - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): nextPart = parts.getPath(partNum) track.append(Func(nextPart.clearColorScale)) @@ -2275,7 +2275,7 @@ def doCigarSmoke(attack): def changeColor(parts): track = Parallel() - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): nextPart = parts.getPath(partNum) track.append(Func(nextPart.setColorScale, Vec4(0, 0, 0, 1))) @@ -2283,7 +2283,7 @@ def changeColor(parts): def resetColor(parts): track = Parallel() - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): nextPart = parts.getPath(partNum) track.append(Func(nextPart.clearColorScale)) @@ -2332,7 +2332,7 @@ def doFilibuster(attack): sprayTrack3 = getPartTrack(sprayEffect3, partDelay + 1.6, partDuration, [sprayEffect3, suit, 0]) sprayTrack4 = getPartTrack(sprayEffect4, partDelay + 2.4, partDuration, [sprayEffect4, suit, 0]) damageAnims = [] - for i in xrange(0, 4): + for i in range(0, 4): damageAnims.append(['cringe', 1e-05, 0.3, @@ -2356,7 +2356,7 @@ def doSchmooze(attack): 'schmooze-instant', 'schmooze-master', 'schmooze-viz'] - for i in xrange(0, 4): + for i in range(0, 4): upperEffect = BattleParticles.createParticleEffect(file='schmoozeUpperSpray') lowerEffect = BattleParticles.createParticleEffect(file='schmoozeLowerSpray') BattleParticles.setEffectTexture(upperEffect, textureNames[i], color=Vec4(0, 0, 1, 1)) @@ -2380,12 +2380,12 @@ def doSchmooze(attack): suitTrack = getSuitTrack(attack) upperPartTracks = Parallel() lowerPartTracks = Parallel() - for i in xrange(0, 4): + for i in range(0, 4): upperPartTracks.append(getPartTrack(upperEffects[i], partDelay + i * 0.65, 0.8, [upperEffects[i], suit, 0])) lowerPartTracks.append(getPartTrack(lowerEffects[i], partDelay + i * 0.65 + 0.7, 1.0, [lowerEffects[i], suit, 0])) damageAnims = [] - for i in xrange(0, 3): + for i in range(0, 3): damageAnims.append(['conked', 0.01, 0.3, @@ -2471,7 +2471,7 @@ def doRedTape(attack): dmg = target['hp'] tape = globalPropPool.getProp('redtape') tubes = [] - for i in xrange(0, 3): + for i in range(0, 3): tubes.append(globalPropPool.getProp('redtape-tube')) suitTrack = getSuitTrack(attack) @@ -2505,7 +2505,7 @@ def doRedTape(attack): tubePosPoints = [Point3(0, 0, tubeHeight), MovieUtil.PNT3_ZERO] tubeTracks = Parallel() tubeTracks.append(Func(battle.movie.needRestoreHips)) - for partNum in xrange(0, hips.getNumPaths()): + for partNum in range(0, hips.getNumPaths()): nextPart = hips.getPath(partNum) tubeTracks.append(getPropTrack(tubes[partNum], nextPart, tubePosPoints, 3.25, 3.17, scaleUpPoint=scaleUpPoint)) @@ -2563,7 +2563,7 @@ def doParadigmShift(attack): shakeTrack.append(Wait(damageDelay + 0.25)) shakeTrack.append(Func(shadow.hide)) shakeTrack.append(LerpPosInterval(toon, 1.1, risePoint)) - for i in xrange(0, 17): + for i in range(0, 17): shakeTrack.append(LerpPosInterval(toon, 0.03, shakeLeft)) shakeTrack.append(LerpPosInterval(toon, 0.03, shakeRight)) @@ -2779,7 +2779,7 @@ def doFired(attack): def changeColor(parts): track = Parallel() - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): nextPart = parts.getPath(partNum) track.append(Func(nextPart.setColorScale, Vec4(0, 0, 0, 1))) @@ -2787,7 +2787,7 @@ def changeColor(parts): def resetColor(parts): track = Parallel() - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): nextPart = parts.getPath(partNum) track.append(Func(nextPart.clearColorScale)) @@ -2962,7 +2962,7 @@ def doCrunch(attack): numberSpillTrack2 = getPartTrack(numberSpill2, 1.5, 1.0, [numberSpill2, suit, 0]) numberSprayTracks = Parallel() numOfNumbers = random.randint(5, 9) - for i in xrange(0, numOfNumbers - 1): + for i in range(0, numOfNumbers - 1): nextSpray = BattleParticles.createParticleEffect(file='numberSpray') nextTexture = random.choice(numberNames) BattleParticles.setEffectTexture(nextSpray, 'audit-' + nextTexture) @@ -2972,7 +2972,7 @@ def doCrunch(attack): numberSprayTracks.append(nextSprayTrack) numberTracks = Parallel() - for i in xrange(0, numOfNumbers): + for i in range(0, numOfNumbers): texture = random.choice(numberNames) next = MovieUtil.copyProp(BattleParticles.getParticle('audit-' + texture)) next.reparentTo(suit.getRightHand()) @@ -3385,7 +3385,7 @@ def doWithdrawal(attack): def changeColor(parts): track = Parallel() - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): nextPart = parts.getPath(partNum) track.append(Func(nextPart.setColorScale, Vec4(0, 0, 0, 1))) @@ -3393,7 +3393,7 @@ def changeColor(parts): def resetColor(parts): track = Parallel() - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): nextPart = parts.getPath(partNum) track.append(Func(nextPart.clearColorScale)) @@ -3676,7 +3676,7 @@ def doPeckingOrder(attack): numBirds = random.randint(4, 7) birdTracks = Parallel() propDelay = 1.5 - for i in xrange(0, numBirds): + for i in range(0, numBirds): next = globalPropPool.getProp('bird') next.setScale(0.01) next.reparentTo(suit.getRightHand()) diff --git a/toontown/battle/MovieThrow.py b/toontown/battle/MovieThrow.py index d74191f80..973d9d14c 100644 --- a/toontown/battle/MovieThrow.py +++ b/toontown/battle/MovieThrow.py @@ -43,7 +43,7 @@ def doThrows(throws): else: suitThrowsDict[suitId] = [throw] - suitThrows = suitThrowsDict.values() + suitThrows = list(suitThrowsDict.values()) def compFunc(a, b): if len(a) > len(b): @@ -58,7 +58,7 @@ def compFunc(a, b): groupHitDict = {} for throw in throws: if attackAffectsGroup(throw['track'], throw['level']): - for i in xrange(len(throw['target'])): + for i in range(len(throw['target'])): target = throw['target'][i] suitId = target['suit'].doId if target['hp'] > 0: @@ -168,7 +168,7 @@ def __propPreflight(props, suit, toon, battle): toon.update(0) prop.wrtReparentTo(battle) props[1].reparentTo(hidden) - for ci in xrange(prop.getNumChildren()): + for ci in range(prop.getNumChildren()): prop.getChild(ci).setHpr(0, -90, 0) targetPnt = MovieUtil.avatarFacePoint(suit, other=battle) @@ -180,7 +180,7 @@ def __propPreflightGroup(props, suits, toon, battle): toon.update(0) prop.wrtReparentTo(battle) props[1].reparentTo(hidden) - for ci in xrange(prop.getNumChildren()): + for ci in range(prop.getNumChildren()): prop.getChild(ci).setHpr(0, -90, 0) avgTargetPt = Point3(0, 0, 0) @@ -413,7 +413,7 @@ def __createWeddingCakeFlight(throw, groupHitDict, pie, pies): splatName = 'splat-birthday-cake' splat = globalPropPool.getProp(splatName) splats = [splat] - for i in xrange(numTargets - 1): + for i in range(numTargets - 1): splats.append(MovieUtil.copyProp(splat)) splatType = globalPropPool.getPropType(splatName) @@ -438,7 +438,7 @@ def __createWeddingCakeFlight(throw, groupHitDict, pie, pies): [cakeParts[3]]] cakePartDivToUse = cakePartDivisions[len(throw['target'])] groupPieTracks = Parallel() - for i in xrange(numTargets): + for i in range(numTargets): target = throw['target'][i] suit = target['suit'] hitSuit = target['hp'] > 0 @@ -507,7 +507,7 @@ def __throwGroupPie(throw, delay, groupHitDict, npcs): if not 'npc' in throw: toonTrack.append(Func(toon.setHpr, battle, origHpr)) suits = [] - for i in xrange(numTargets): + for i in range(numTargets): suits.append(throw['target'][i]['suit']) pieName = pieNames[level] @@ -529,7 +529,7 @@ def __throwGroupPie(throw, delay, groupHitDict, npcs): notify.error('unhandled throw level %d' % level) pieTrack.append(groupPieTracks) didThrowHitAnyone = False - for i in xrange(numTargets): + for i in range(numTargets): target = throw['target'][i] hitSuit = target['hp'] > 0 if hitSuit: @@ -537,7 +537,7 @@ def __throwGroupPie(throw, delay, groupHitDict, npcs): soundTrack = __getSoundTrack(level, didThrowHitAnyone, toon) groupSuitResponseTrack = Parallel() - for i in xrange(numTargets): + for i in range(numTargets): target = throw['target'][i] suit = target['suit'] hitSuit = target['hp'] > 0 @@ -591,7 +591,7 @@ def __throwGroupPie(throw, delay, groupHitDict, npcs): singleSuitResponseTrack.append(Func(suit.loop, 'neutral')) singleSuitResponseTrack = Parallel(singleSuitResponseTrack, bonusTrack) else: - groupHitValues = groupHitDict.values() + groupHitValues = list(groupHitDict.values()) if groupHitValues.count(0) == len(groupHitValues): singleSuitResponseTrack = MovieUtil.createSuitDodgeMultitrack(delay + tSuitDodges, suit, leftSuits, rightSuits) else: diff --git a/toontown/battle/MovieToonVictory.py b/toontown/battle/MovieToonVictory.py index 5e41d29e5..40f043574 100644 --- a/toontown/battle/MovieToonVictory.py +++ b/toontown/battle/MovieToonVictory.py @@ -83,7 +83,7 @@ def doToonVictory(localToonActive, toons, rewardToonIds, rewardDicts, deathList, countToons = 0 uberListNew = [] for t in toons: - if isinstance(t, types.IntType): + if isinstance(t, int): t = base.cr.doId2do.get(t) if t: toonList.append(t) @@ -101,7 +101,7 @@ def doToonVictory(localToonActive, toons, rewardToonIds, rewardDicts, deathList, skipper = ToonVictorySkipper(len(toonList), noSkip) lastListenIndex = 0 track.append(skipper.getSetupFunc(lastListenIndex)) - for tIndex in xrange(len(toonList)): + for tIndex in range(len(toonList)): t = toonList[tIndex] rdict = __findToonReward(rewardDicts, t) if rdict != None: diff --git a/toontown/battle/MovieTrap.py b/toontown/battle/MovieTrap.py index 490b94046..c4ff2ec22 100644 --- a/toontown/battle/MovieTrap.py +++ b/toontown/battle/MovieTrap.py @@ -43,11 +43,11 @@ def doTraps(traps): if suit.battleTrap != NO_TRAP: hasUberTrapConflict = True - suitTrapLists = suitTrapsDict.values() + suitTrapLists = list(suitTrapsDict.values()) mtrack = Parallel() for trapList in suitTrapLists: trapPropList = [] - for i in xrange(len(trapList)): + for i in range(len(trapList)): trap = trapList[i] level = trap['level'] if level == 0: @@ -85,7 +85,7 @@ def doTraps(traps): mtrack.append(ival) else: subMtrack = Parallel() - for i in xrange(len(trapList)): + for i in range(len(trapList)): trap = trapList[i] trapProps = trapPropList[i] ival = __doTrapLevel(trap, trapProps, explode=1) diff --git a/toontown/battle/MovieUtil.py b/toontown/battle/MovieUtil.py index e515034a7..09f3c1c44 100644 --- a/toontown/battle/MovieUtil.py +++ b/toontown/battle/MovieUtil.py @@ -241,7 +241,7 @@ def virtualize(deathsuit): actorNode = deathsuit.find('**/__Actor_modelRoot') actorCollection = actorNode.findAllMatches('*') parts = () - for thingIndex in xrange(0, actorCollection.getNumPaths()): + for thingIndex in range(0, actorCollection.getNumPaths()): thing = actorCollection[thingIndex] if thing.getName() not in ('joint_attachMeter', 'joint_nameTag', 'def_nameTag'): thing.setColorScale(1.0, 0.0, 0.0, 1.0) @@ -718,7 +718,7 @@ def calcAvgSuitPos(throw): battle = throw['battle'] avgSuitPos = Point3(0, 0, 0) numTargets = len(throw['target']) - for i in xrange(numTargets): + for i in range(numTargets): suit = throw['target'][i]['suit'] avgSuitPos += suit.getPos(battle) diff --git a/toontown/battle/MovieZap.py b/toontown/battle/MovieZap.py index dbbedfd27..53227edee 100644 --- a/toontown/battle/MovieZap.py +++ b/toontown/battle/MovieZap.py @@ -54,7 +54,7 @@ def doZaps(zaps): else: suitZapsDict[suitId] = [zap] - suitZaps = suitZapsDict.values() + suitZaps = list(suitZapsDict.values()) def compFunc(a, b): if len(a) > len(b): @@ -225,7 +225,7 @@ def shortCircuitTrack(suit, battle): def say(statement): - print statement + print(statement) def __getSoundTrack(level, hitSuit, delay, node = None): diff --git a/toontown/battle/ParticleDefs.py b/toontown/battle/ParticleDefs.py index 6fb5f84ba..71e4d4e19 100644 --- a/toontown/battle/ParticleDefs.py +++ b/toontown/battle/ParticleDefs.py @@ -4,7 +4,7 @@ ParticleTable = {} def particle(func): - ParticleTable[func.func_name] = func + ParticleTable[func.__name__] = func @particle def gearExplosion(self): diff --git a/toontown/battle/RewardPanel.py b/toontown/battle/RewardPanel.py index 538c680b5..f880c87ae 100644 --- a/toontown/battle/RewardPanel.py +++ b/toontown/battle/RewardPanel.py @@ -239,7 +239,7 @@ def initGagFrame(self, toon, expList, meritList, noSkip = False): self.missedItemFrame.hide() trackBarOffset = 0 self.skipButton['state'] = DGG.DISABLED if noSkip else DGG.NORMAL - for i in xrange(len(SuitDNA.suitDepts)): + for i in range(len(SuitDNA.suitDepts)): meritBar = self.meritBars[i] meritLabel = self.meritLabels[i] totalMerits = CogDisguiseGlobals.getTotalMerits(toon, i) @@ -268,7 +268,7 @@ def initGagFrame(self, toon, expList, meritList, noSkip = False): meritBar.hide() meritLabel.hide() - for i in xrange(len(expList)): + for i in range(len(expList)): curExp = expList[i] trackBar = self.trackBars[i] trackLabel = self.trackLabels[i] @@ -351,7 +351,7 @@ def resetMeritBarColor(self, dept): def getRandomCongratsPair(self, toon): congratsStrings = TTLocalizer.RewardPanelCongratsStrings numStrings = len(congratsStrings) - indexList = range(numStrings) + indexList = list(range(numStrings)) index1 = random.choice(indexList) indexList.remove(index1) index2 = random.choice(indexList) @@ -495,7 +495,7 @@ def showMeritIncLabel(self, dept, earnedMerits): def getTrackIntervalList(self, toon, track, origSkill, earnedSkill, hasUber, guestWaste = 0): self.notify.debug("getTrackIntervalList() was called!") if hasUber < 0: - print (toon.doId, 'Reward Panel received an invalid hasUber from an uberList') + print((toon.doId, 'Reward Panel received an invalid hasUber from an uberList')) tickDelay = 1.0 / 60 intervalList = [] if origSkill + earnedSkill >= ToontownBattleGlobals.UnpaidMaxSkills[track] and toon.getGameAccess() != OTPGlobals.AccessFull: @@ -505,7 +505,7 @@ def getTrackIntervalList(self, toon, track, origSkill, earnedSkill, hasUber, gue intervalList.append(Func(self.showTrackIncLabel, track, earnedSkill)) barTime = 0.5 numTicks = int(math.ceil(barTime / tickDelay)) - for i in xrange(numTicks): + for i in range(numTicks): t = (i + 1) / float(numTicks) newValue = int(origSkill + t * earnedSkill + 0.5) intervalList.append(Func(self.incrementExp, track, newValue, toon)) @@ -539,7 +539,7 @@ def getTrackIntervalList(self, toon, track, origSkill, earnedSkill, hasUber, gue if displayedSkillDiff > ToontownBattleGlobals.UberSkill: displayedSkillDiff = ToontownBattleGlobals.UberSkill intervalList.append(Func(self.showTrackIncLabel, track, -displayedSkillDiff)) - for i in xrange(numTicks): + for i in range(numTicks): t = (i + 1) / float(numTicks) newValue = int(currentSkill - t * skillDiff + 0.5) intervalList.append(Func(self.incrementExp, track, newValue, toon)) @@ -559,7 +559,7 @@ def getMeritIntervalList(self, toon, dept, origMerits, earnedMerits): intervalList.append(Func(self.showMeritIncLabel, dept, min(neededMerits, earnedMerits))) barTime = 0.5 numTicks = int(math.ceil(barTime / tickDelay)) - for i in xrange(numTicks): + for i in range(numTicks): t = (i + 1) / float(numTicks) newValue = int(origMerits + t * earnedMerits + 0.5) intervalList.append(Func(self.incrementMerits, toon, dept, newValue, totalMerits)) @@ -628,13 +628,13 @@ def getQuestIntervalList(self, toon, deathList, toonList, origQuestsList, itemLi toonShortList.append(t) cogList = [] - for i in xrange(0, len(deathList), 4): + for i in range(0, len(deathList), 4): cogIndex = deathList[i] cogLevel = deathList[i + 1] activeToonBits = deathList[i + 2] flags = deathList[i + 3] activeToonIds = [] - for j in xrange(8): + for j in range(8): if activeToonBits & 1 << j: if toonList[j] is not None: activeToonIds.append(toonList[j].getDoId()) @@ -670,10 +670,10 @@ def getQuestIntervalList(self, toon, deathList, toonList, origQuestsList, itemLi zoneId = 0 avQuests = [] - for i in xrange(0, len(origQuestsList), 5): + for i in range(0, len(origQuestsList), 5): avQuests.append(origQuestsList[i:i + 5]) - for i in xrange(len(avQuests)): + for i in range(len(avQuests)): questDesc = avQuests[i] questId, npcId, toNpcId, rewardId, toonProgress = questDesc quest = Quests.getQuest(questId) @@ -719,7 +719,7 @@ def getQuestIntervalList(self, toon, deathList, toonList, origQuestsList, itemLi if earned > 0 or base.localAvatar.tutorialAck == 0 and num == 1: barTime = 0.5 numTicks = int(math.ceil(barTime / tickDelay)) - for i in xrange(numTicks): + for i in range(numTicks): t = (i + 1) / float(numTicks) newValue = int(orig + t * earned + 0.5) questDesc[4] = newValue @@ -817,7 +817,7 @@ def getExpTrack(self, toon, origExp, earnedExp, deathList, origQuestsList, itemL questList = self.getQuestIntervalList(toon, deathList, toonList, origQuestsList, itemList, helpfulToonsList, earnedExp) if questList: avQuests = [] - for i in xrange(0, len(origQuestsList), 5): + for i in range(0, len(origQuestsList), 5): avQuests.append(origQuestsList[i:i + 5]) track.append(Func(self.initQuestFrame, toon, copy.deepcopy(avQuests))) @@ -828,7 +828,7 @@ def getExpTrack(self, toon, origExp, earnedExp, deathList, origQuestsList, itemL if trackEnded: track.append(Func(self.vanishFrames)) track.append(Fanfare.makeFanfare(0, toon)[0]) - for i in xrange(len(endTracks)): + for i in range(len(endTracks)): if endTracks[i] is 1: track += self.getEndTrackIntervalList(toon, toonList, i) diff --git a/toontown/battle/SuitBattleGlobals.py b/toontown/battle/SuitBattleGlobals.py index 1a379145f..ae488ef1f 100644 --- a/toontown/battle/SuitBattleGlobals.py +++ b/toontown/battle/SuitBattleGlobals.py @@ -88,14 +88,14 @@ def pickSuitAttack(attacks, suitLevel): if configAttackName == 'random': return attackNum elif configAttackName == 'sequence': - for i in xrange(len(attacks)): + for i in range(len(attacks)): if attacks[i] not in debugAttackSequence: debugAttackSequence[attacks[i]] = 1 return i return attackNum else: - for i in xrange(len(attacks)): + for i in range(len(attacks)): if attacks[i][0] == configAttackName: return i @@ -113,7 +113,7 @@ def getSuitAttack(suitName, suitLevel, attackNum = -1): adict['suitName'] = suitName name = attack[0] adict['name'] = name - adict['id'] = SuitAttacks.keys().index(name) + adict['id'] = list(SuitAttacks.keys()).index(name) adict['animName'] = SuitAttacks[name][0] adict['hp'] = attack[1][suitLevel] adict['acc'] = attack[2][suitLevel] @@ -7115,75 +7115,75 @@ def getSuitAttack(suitName, suitLevel, attackNum = -1): 'Withdrawal': ('magic1', ATK_TGT_SINGLE), 'WriteOff': ('hold-pencil', ATK_TGT_SINGLE), 'Overdraft': ('hold-pencil', ATK_TGT_SINGLE)} -ACID_RAIN = SuitAttacks.keys().index('AcidRain') -AUDIT = SuitAttacks.keys().index('Audit') -BITE = SuitAttacks.keys().index('Bite') -BOUNCE_CHECK = SuitAttacks.keys().index('BounceCheck') -BRAIN_STORM = SuitAttacks.keys().index('BrainStorm') -BUZZ_WORD = SuitAttacks.keys().index('BuzzWord') -CALCULATE = SuitAttacks.keys().index('Calculate') -CANNED = SuitAttacks.keys().index('Canned') -CHOMP = SuitAttacks.keys().index('Chomp') -CIGAR_SMOKE = SuitAttacks.keys().index('CigarSmoke') -CLIPON_TIE = SuitAttacks.keys().index('ClipOnTie') -CRUNCH = SuitAttacks.keys().index('Crunch') -DEMOTION = SuitAttacks.keys().index('Demotion') -DOWNSIZE = SuitAttacks.keys().index('Downsize') -DOUBLE_TALK = SuitAttacks.keys().index('DoubleTalk') -EVICTION_NOTICE = SuitAttacks.keys().index('EvictionNotice') -EVIL_EYE = SuitAttacks.keys().index('EvilEye') -FILIBUSTER = SuitAttacks.keys().index('Filibuster') -FILL_WITH_LEAD = SuitAttacks.keys().index('FillWithLead') -FINGER_WAG = SuitAttacks.keys().index('FingerWag') -FIRED = SuitAttacks.keys().index('Fired') -FIVE_O_CLOCK_SHADOW = SuitAttacks.keys().index('FiveOClockShadow') -FLOOD_THE_MARKET = SuitAttacks.keys().index('FloodTheMarket') -FOUNTAIN_PEN = SuitAttacks.keys().index('FountainPen') -FREEZE_ASSETS = SuitAttacks.keys().index('FreezeAssets') -GAVEL = SuitAttacks.keys().index('Gavel') -GLOWER_POWER = SuitAttacks.keys().index('GlowerPower') -GUILT_TRIP = SuitAttacks.keys().index('GuiltTrip') -HALF_WINDSOR = SuitAttacks.keys().index('HalfWindsor') -HANG_UP = SuitAttacks.keys().index('HangUp') -HEAD_SHRINK = SuitAttacks.keys().index('HeadShrink') -HOT_AIR = SuitAttacks.keys().index('HotAir') -JARGON = SuitAttacks.keys().index('Jargon') -LEGALESE = SuitAttacks.keys().index('Legalese') -LIQUIDATE = SuitAttacks.keys().index('Liquidate') -MARKET_CRASH = SuitAttacks.keys().index('MarketCrash') -MUMBO_JUMBO = SuitAttacks.keys().index('MumboJumbo') -PARADIGM_SHIFT = SuitAttacks.keys().index('ParadigmShift') -PECKING_ORDER = SuitAttacks.keys().index('PeckingOrder') -PICK_POCKET = SuitAttacks.keys().index('PickPocket') -PINK_SLIP = SuitAttacks.keys().index('PinkSlip') -PLAY_HARDBALL = SuitAttacks.keys().index('PlayHardball') -POUND_KEY = SuitAttacks.keys().index('PoundKey') -POWER_TIE = SuitAttacks.keys().index('PowerTie') -POWER_TRIP = SuitAttacks.keys().index('PowerTrip') -QUAKE = SuitAttacks.keys().index('Quake') -RAZZLE_DAZZLE = SuitAttacks.keys().index('RazzleDazzle') -RED_TAPE = SuitAttacks.keys().index('RedTape') -RE_ORG = SuitAttacks.keys().index('ReOrg') -RESTRAINING_ORDER = SuitAttacks.keys().index('RestrainingOrder') -ROLODEX = SuitAttacks.keys().index('Rolodex') -RUBBER_STAMP = SuitAttacks.keys().index('RubberStamp') -RUB_OUT = SuitAttacks.keys().index('RubOut') -SACKED = SuitAttacks.keys().index('Sacked') -SANDTRAP = SuitAttacks.keys().index('SandTrap') -SCHMOOZE = SuitAttacks.keys().index('Schmooze') -SHAKE = SuitAttacks.keys().index('Shake') -SHRED = SuitAttacks.keys().index('Shred') -SONG_AND_DANCE = SuitAttacks.keys().index('SongAndDance') -SPIN = SuitAttacks.keys().index('Spin') -SYNERGY = SuitAttacks.keys().index('Synergy') -TABULATE = SuitAttacks.keys().index('Tabulate') -TEE_OFF = SuitAttacks.keys().index('TeeOff') -THROW_BOOK = SuitAttacks.keys().index('ThrowBook') -TREMOR = SuitAttacks.keys().index('Tremor') -WATERCOOLER = SuitAttacks.keys().index('Watercooler') -WITHDRAWAL = SuitAttacks.keys().index('Withdrawal') -WRITE_OFF = SuitAttacks.keys().index('WriteOff') -OVERDRAFT = SuitAttacks.keys().index('Overdraft') +ACID_RAIN = list(SuitAttacks.keys()).index('AcidRain') +AUDIT = list(SuitAttacks.keys()).index('Audit') +BITE = list(SuitAttacks.keys()).index('Bite') +BOUNCE_CHECK = list(SuitAttacks.keys()).index('BounceCheck') +BRAIN_STORM = list(SuitAttacks.keys()).index('BrainStorm') +BUZZ_WORD = list(SuitAttacks.keys()).index('BuzzWord') +CALCULATE = list(SuitAttacks.keys()).index('Calculate') +CANNED = list(SuitAttacks.keys()).index('Canned') +CHOMP = list(SuitAttacks.keys()).index('Chomp') +CIGAR_SMOKE = list(SuitAttacks.keys()).index('CigarSmoke') +CLIPON_TIE = list(SuitAttacks.keys()).index('ClipOnTie') +CRUNCH = list(SuitAttacks.keys()).index('Crunch') +DEMOTION = list(SuitAttacks.keys()).index('Demotion') +DOWNSIZE = list(SuitAttacks.keys()).index('Downsize') +DOUBLE_TALK = list(SuitAttacks.keys()).index('DoubleTalk') +EVICTION_NOTICE = list(SuitAttacks.keys()).index('EvictionNotice') +EVIL_EYE = list(SuitAttacks.keys()).index('EvilEye') +FILIBUSTER = list(SuitAttacks.keys()).index('Filibuster') +FILL_WITH_LEAD = list(SuitAttacks.keys()).index('FillWithLead') +FINGER_WAG = list(SuitAttacks.keys()).index('FingerWag') +FIRED = list(SuitAttacks.keys()).index('Fired') +FIVE_O_CLOCK_SHADOW = list(SuitAttacks.keys()).index('FiveOClockShadow') +FLOOD_THE_MARKET = list(SuitAttacks.keys()).index('FloodTheMarket') +FOUNTAIN_PEN = list(SuitAttacks.keys()).index('FountainPen') +FREEZE_ASSETS = list(SuitAttacks.keys()).index('FreezeAssets') +GAVEL = list(SuitAttacks.keys()).index('Gavel') +GLOWER_POWER = list(SuitAttacks.keys()).index('GlowerPower') +GUILT_TRIP = list(SuitAttacks.keys()).index('GuiltTrip') +HALF_WINDSOR = list(SuitAttacks.keys()).index('HalfWindsor') +HANG_UP = list(SuitAttacks.keys()).index('HangUp') +HEAD_SHRINK = list(SuitAttacks.keys()).index('HeadShrink') +HOT_AIR = list(SuitAttacks.keys()).index('HotAir') +JARGON = list(SuitAttacks.keys()).index('Jargon') +LEGALESE = list(SuitAttacks.keys()).index('Legalese') +LIQUIDATE = list(SuitAttacks.keys()).index('Liquidate') +MARKET_CRASH = list(SuitAttacks.keys()).index('MarketCrash') +MUMBO_JUMBO = list(SuitAttacks.keys()).index('MumboJumbo') +PARADIGM_SHIFT = list(SuitAttacks.keys()).index('ParadigmShift') +PECKING_ORDER = list(SuitAttacks.keys()).index('PeckingOrder') +PICK_POCKET = list(SuitAttacks.keys()).index('PickPocket') +PINK_SLIP = list(SuitAttacks.keys()).index('PinkSlip') +PLAY_HARDBALL = list(SuitAttacks.keys()).index('PlayHardball') +POUND_KEY = list(SuitAttacks.keys()).index('PoundKey') +POWER_TIE = list(SuitAttacks.keys()).index('PowerTie') +POWER_TRIP = list(SuitAttacks.keys()).index('PowerTrip') +QUAKE = list(SuitAttacks.keys()).index('Quake') +RAZZLE_DAZZLE = list(SuitAttacks.keys()).index('RazzleDazzle') +RED_TAPE = list(SuitAttacks.keys()).index('RedTape') +RE_ORG = list(SuitAttacks.keys()).index('ReOrg') +RESTRAINING_ORDER = list(SuitAttacks.keys()).index('RestrainingOrder') +ROLODEX = list(SuitAttacks.keys()).index('Rolodex') +RUBBER_STAMP = list(SuitAttacks.keys()).index('RubberStamp') +RUB_OUT = list(SuitAttacks.keys()).index('RubOut') +SACKED = list(SuitAttacks.keys()).index('Sacked') +SANDTRAP = list(SuitAttacks.keys()).index('SandTrap') +SCHMOOZE = list(SuitAttacks.keys()).index('Schmooze') +SHAKE = list(SuitAttacks.keys()).index('Shake') +SHRED = list(SuitAttacks.keys()).index('Shred') +SONG_AND_DANCE = list(SuitAttacks.keys()).index('SongAndDance') +SPIN = list(SuitAttacks.keys()).index('Spin') +SYNERGY = list(SuitAttacks.keys()).index('Synergy') +TABULATE = list(SuitAttacks.keys()).index('Tabulate') +TEE_OFF = list(SuitAttacks.keys()).index('TeeOff') +THROW_BOOK = list(SuitAttacks.keys()).index('ThrowBook') +TREMOR = list(SuitAttacks.keys()).index('Tremor') +WATERCOOLER = list(SuitAttacks.keys()).index('Watercooler') +WITHDRAWAL = list(SuitAttacks.keys()).index('Withdrawal') +WRITE_OFF = list(SuitAttacks.keys()).index('WriteOff') +OVERDRAFT = list(SuitAttacks.keys()).index('Overdraft') def getFaceoffTaunt(suitName, doId): if suitName in SuitFaceoffTaunts: diff --git a/toontown/betaevent/DistributedBetaEventAI.py b/toontown/betaevent/DistributedBetaEventAI.py index 1b556ad2f..062f83ec8 100644 --- a/toontown/betaevent/DistributedBetaEventAI.py +++ b/toontown/betaevent/DistributedBetaEventAI.py @@ -1,4 +1,4 @@ -from DistributedEventAI import DistributedEventAI +from .DistributedEventAI import DistributedEventAI from direct.interval.IntervalGlobal import * from toontown.toonbase import ToontownGlobals diff --git a/toontown/betaevent/DistributedBetaEventTTCAI.py b/toontown/betaevent/DistributedBetaEventTTCAI.py index 5f64740e5..24299339d 100644 --- a/toontown/betaevent/DistributedBetaEventTTCAI.py +++ b/toontown/betaevent/DistributedBetaEventTTCAI.py @@ -1,4 +1,4 @@ -from DistributedEventAI import DistributedEventAI +from .DistributedEventAI import DistributedEventAI from direct.interval.IntervalGlobal import * from toontown.toonbase import ToontownGlobals from direct.task.TaskManagerGlobal import taskMgr @@ -34,11 +34,11 @@ def setupDNA(self, suitPlanner): visGroups[zone] = self.air.allocateZone() visGroup.name = str(visGroups[zone]) - for suitEdges in suitPlanner.dnaStore.suitEdges.values(): + for suitEdges in list(suitPlanner.dnaStore.suitEdges.values()): for suitEdge in suitEdges: suitEdge.setZoneId(visGroups[suitEdge.zoneId]) - self.setVisGroups(visGroups.values()) + self.setVisGroups(list(visGroups.values())) suitPlanner.initDNAInfo() def systemMessageAll(self, text): diff --git a/toontown/betaevent/DistributedEventAI.py b/toontown/betaevent/DistributedEventAI.py index 01ccfc9ae..00844c7c4 100644 --- a/toontown/betaevent/DistributedEventAI.py +++ b/toontown/betaevent/DistributedEventAI.py @@ -43,7 +43,7 @@ def betaeventttc(state): def betaevent(state): invoker = spellbook.getInvoker() invasion = None - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): if isinstance(do, DistributedEventAI): invasion = do invasion.b_setState(state) diff --git a/toontown/building/BoardingGroupShow.py b/toontown/building/BoardingGroupShow.py index d463f21cb..c1b314538 100644 --- a/toontown/building/BoardingGroupShow.py +++ b/toontown/building/BoardingGroupShow.py @@ -176,7 +176,7 @@ def __isRunPathClear(self, elevatorModel, offsetWrtRender): base.cTrav.traverse(render) queue.sortEntries() if queue.getNumEntries(): - for entryNum in xrange(queue.getNumEntries()): + for entryNum in range(queue.getNumEntries()): entry = queue.getEntry(entryNum) hitObject = entry.getIntoNodePath() if hitObject.getNetTag('pieCode') != '3': diff --git a/toontown/building/DistributedBossElevatorAI.py b/toontown/building/DistributedBossElevatorAI.py index 40c48ba03..ab09e966e 100644 --- a/toontown/building/DistributedBossElevatorAI.py +++ b/toontown/building/DistributedBossElevatorAI.py @@ -22,7 +22,7 @@ def elevatorClosed(self): numPlayers = self.countFullSeats() if numPlayers > 0: bossZone = self.bldg.createBossOffice(self.seats) - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] if avId: self.sendUpdateToAvatarId(avId, 'setBossOfficeZone', [bossZone]) diff --git a/toontown/building/DistributedBuilding.py b/toontown/building/DistributedBuilding.py index 5870427ae..b173a0d0d 100644 --- a/toontown/building/DistributedBuilding.py +++ b/toontown/building/DistributedBuilding.py @@ -283,7 +283,7 @@ def exitCogdo(self): def getNodePaths(self): nodePath = [] npc = self.townTopLevel.findAllMatches('**/?b' + str(self.block) + ':*_DNARoot;+s') - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): nodePath.append(npc.getPath(i)) return nodePath @@ -295,7 +295,7 @@ def loadElevator(self, newNP, cogdo = False): else: self.elevatorModel = loader.loadModel('phase_4/models/modules/elevator') npc = self.elevatorModel.findAllMatches('**/floor_light_?;+s') - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): np = npc.getPath(i) floor = int(np.getName()[-1:]) - 1 if len(self.floorIndicator) != floor: @@ -746,7 +746,7 @@ def getVictoryRunTrack(self): delayDeletes.append(DelayDelete.DelayDelete(toon, 'getVictoryRunTrack')) toon.stopSmooth() toon.setParent(ToontownGlobals.SPHidden) - origPosTrack.append(Func(toon.setPosHpr, self.elevatorNodePath, apply(Point3, ElevatorPoints[i]), Point3(180, 0, 0))) + origPosTrack.append(Func(toon.setPosHpr, self.elevatorNodePath, Point3(*ElevatorPoints[i]), Point3(180, 0, 0))) origPosTrack.append(Func(toon.setParent, ToontownGlobals.SPRender)) i += 1 @@ -818,7 +818,7 @@ def createBounceTrack(self, nodeObj, numBounces, startScale, totalTime, slowInit currTime = bounceTime realScale = nodeObj.getScale() currScaleDiff = startScale - realScale[2] - for currBounceScale in xrange(numBounces): + for currBounceScale in range(numBounces): if currBounceScale == numBounces - 1: currScale = realScale[2] elif currBounceScale % 2: @@ -861,7 +861,7 @@ def setToSuit(self): i.stash() npc = hidden.findAllMatches(self.getSbSearchString()) - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): nodePath = npc.getPath(i) self.adjustSbNodepathScale(nodePath) self.notify.debug('net transform = %s' % str(nodePath.getNetTransform())) @@ -896,7 +896,7 @@ def setToCogdo(self): np.setColorScale(0.6, 0.6, 0.6, 1.0) npc = hidden.findAllMatches(self.getSbSearchString()) - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): nodePath = npc.getPath(i) self.adjustSbNodepathScale(nodePath) self.notify.debug('net transform = %s' % str(nodePath.getNetTransform())) diff --git a/toontown/building/DistributedBuildingAI.py b/toontown/building/DistributedBuildingAI.py index e19493223..7b4bc0805 100644 --- a/toontown/building/DistributedBuildingAI.py +++ b/toontown/building/DistributedBuildingAI.py @@ -234,7 +234,7 @@ def setVictorList(self, victorList): self.victorList = victorList def findVictorIndex(self, avId): - for i in xrange(len(self.victorList)): + for i in range(len(self.victorList)): if self.victorList[i] == avId: return i @@ -308,7 +308,7 @@ def enterWaitForVictors(self, victorList, savedBy): self.air.questManager.toonKilledBuilding(toon, self.track, self.difficulty, self.numFloors, self.zoneId, activeToons) toon.addStat(ToontownGlobals.STATS_BLDGS) self.air.achievementsManager.bldg(t) - for i in xrange(0, 4): + for i in range(0, 4): victor = victorList[i] if (victor is None) or (victor not in self.air.doId2do): victorList[i] = 0 @@ -362,7 +362,7 @@ def enterWaitForVictorsFromCogdo(self, victorList, savedBy): victorList.extend([None, None, None, None]) for i in range(0, 4): victor = victorList[i] - if victor == None or not self.air.doId2do.has_key(victor): + if victor == None or victor not in self.air.doId2do: victorList[i] = 0 continue event = self.air.getAvatarExitEvent(victor) diff --git a/toontown/building/DistributedBuildingMgrAI.py b/toontown/building/DistributedBuildingMgrAI.py index 8cecc6f72..7ac0eacc1 100644 --- a/toontown/building/DistributedBuildingMgrAI.py +++ b/toontown/building/DistributedBuildingMgrAI.py @@ -21,7 +21,7 @@ def __init__(self, air, branchId, dnaStore, trophyMgr): self.findAllLandmarkBuildings() def cleanup(self): - for building in self.__buildings.values(): + for building in list(self.__buildings.values()): building.cleanup() self.__buildings = {} @@ -35,21 +35,21 @@ def isSuitBlock(self, blockNumber): def getSuitBlocks(self): blocks = [] - for blockNumber, building in self.__buildings.items(): + for blockNumber, building in list(self.__buildings.items()): if building.isSuitBlock(): blocks.append(blockNumber) return blocks def getEstablishedSuitBlocks(self): blocks = [] - for blockNumber, building in self.__buildings.items(): + for blockNumber, building in list(self.__buildings.items()): if building.isEstablishedSuitBlock(): blocks.append(blockNumber) return blocks def getToonBlocks(self): blocks = [] - for blockNumber, building in self.__buildings.items(): + for blockNumber, building in list(self.__buildings.items()): if isinstance(building, HQBuildingAI.HQBuildingAI): continue if isinstance(building, GagshopBuildingAI.GagshopBuildingAI): @@ -63,7 +63,7 @@ def getToonBlocks(self): return blocks def getBuildings(self): - return self.__buildings.values() + return list(self.__buildings.values()) def getFrontDoorPoint(self, blockNumber): if self.isValidBlockNumber(blockNumber): @@ -88,7 +88,7 @@ def getDNABlockLists(self): petshopBlocks = [] kartshopBlocks = [] animBldgBlocks = [] - for i in xrange(self.dnaStore.getNumBlockNumbers()): + for i in range(self.dnaStore.getNumBlockNumbers()): blockNumber = self.dnaStore.getBlockNumberAt(i) buildingType = self.dnaStore.getBlockBuildingType(blockNumber) if buildingType == 'hq': diff --git a/toontown/building/DistributedClubElevator.py b/toontown/building/DistributedClubElevator.py index 3528ffa3a..d62380b4d 100644 --- a/toontown/building/DistributedClubElevator.py +++ b/toontown/building/DistributedClubElevator.py @@ -307,7 +307,7 @@ def getElevatorModel(self): def kickEveryoneOut(self): bailFlag = 0 - for avId, slot in self.boardedAvIds.items(): + for avId, slot in list(self.boardedAvIds.items()): self.emptySlot(slot, avId, bailFlag, globalClockDelta.getRealNetworkTime()) if avId == base.localAvatar.doId: pass diff --git a/toontown/building/DistributedClubElevatorAI.py b/toontown/building/DistributedClubElevatorAI.py index 48c7dd388..01dd0b5b6 100644 --- a/toontown/building/DistributedClubElevatorAI.py +++ b/toontown/building/DistributedClubElevatorAI.py @@ -64,7 +64,7 @@ def generateWithRequired(self, zoneId): DistributedElevatorFSMAI.DistributedElevatorFSMAI.generateWithRequired(self, self.zoneId) def delete(self): - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] if avId: self.clearFullNow(seatIndex) @@ -148,9 +148,9 @@ def waitEmptyTask(self, task): def enterWaitEmpty(self): self.lastState = self.state - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): self.seats[i] = None - print self.seats + print((self.seats)) if self.wantState == 'closed': self.demand('Closing') else: @@ -212,7 +212,7 @@ def elevatorClosed(self): if i not in [None, 0]: players.append(i) sittingAvIds = [] - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] if avId: sittingAvIds.append(avId) diff --git a/toontown/building/DistributedElevator.py b/toontown/building/DistributedElevator.py index 41b8d3889..00d900b1f 100644 --- a/toontown/building/DistributedElevator.py +++ b/toontown/building/DistributedElevator.py @@ -88,7 +88,7 @@ def disable(self): if self.bldgRequest: self.cr.relatedObjectMgr.abortRequest(self.bldgRequest) self.bldgRequest = None - for request in self.toonRequests.values(): + for request in list(self.toonRequests.values()): self.cr.relatedObjectMgr.abortRequest(request) self.toonRequests = {} @@ -228,8 +228,8 @@ def fillSlot(self, index, avId, wantBoardingShow = 0): else: animInFunc = Sequence(Func(toon.setAnimState, 'run', 1.0)) animFunc = Func(toon.setAnimState, 'neutral', 1.0) - toon.headsUp(self.getElevatorModel(), apply(Point3, self.elevatorPoints[index])) - track = Sequence(animInFunc, LerpPosInterval(toon, TOON_BOARD_ELEVATOR_TIME * 0.75, apply(Point3, self.elevatorPoints[index]), other=self.getElevatorModel()), LerpHprInterval(toon, TOON_BOARD_ELEVATOR_TIME * 0.25, Point3(180, 0, 0), other=self.getElevatorModel()), Func(self.clearToonTrack, avId), animFunc, name=toon.uniqueName('fillElevator'), autoPause=1) + toon.headsUp(self.getElevatorModel(), Point3(*self.elevatorPoints[index])) + track = Sequence(animInFunc, LerpPosInterval(toon, TOON_BOARD_ELEVATOR_TIME * 0.75, Point3(*self.elevatorPoints[index]), other=self.getElevatorModel()), LerpHprInterval(toon, TOON_BOARD_ELEVATOR_TIME * 0.25, Point3(180, 0, 0), other=self.getElevatorModel()), Func(self.clearToonTrack, avId), animFunc, name=toon.uniqueName('fillElevator'), autoPause=1) if wantBoardingShow: boardingTrack, boardingTrackType = self.getBoardingTrack(toon, index, False) track = Sequence(boardingTrack, track) @@ -424,7 +424,7 @@ def exitClosing(self): pass def onDoorCloseFinish(self): - for avId in self.boardedAvIds.keys(): + for avId in list(self.boardedAvIds.keys()): av = self.cr.doId2do.get(avId) if av is not None: if av.getParent().compareTo(self.getElevatorModel()) == 0: @@ -555,11 +555,11 @@ def getOffsetPos(self, seatIndex = 0): return self.JumpOutOffsets[seatIndex] def getOffsetPosWrtToonParent(self, toon, seatIndex = 0): - self.offsetNP.setPos(apply(Point3, self.getOffsetPos(seatIndex))) + self.offsetNP.setPos(Point3(*self.getOffsetPos(seatIndex))) return self.offsetNP.getPos(toon.getParent()) def getOffsetPosWrtRender(self, seatIndex = 0): - self.offsetNP.setPos(apply(Point3, self.getOffsetPos(seatIndex))) + self.offsetNP.setPos(Point3(*self.getOffsetPos(seatIndex))) return self.offsetNP.getPos(render) def canHideBoardingQuitBtn(self, avId): diff --git a/toontown/building/DistributedElevatorAI.py b/toontown/building/DistributedElevatorAI.py index 686504ae6..f08172049 100644 --- a/toontown/building/DistributedElevatorAI.py +++ b/toontown/building/DistributedElevatorAI.py @@ -27,7 +27,7 @@ def __init__(self, air, bldg, numSeats = 4, antiShuffle = 0, minLaff = 0): simbase.air.elevatorTripId += 1 else: self.elevatorTripId = 0 - for seat in xrange(numSeats): + for seat in range(numSeats): self.seats.append(None) self.accepting = 0 @@ -59,12 +59,12 @@ def getBldgDoId(self): return self.bldgDoId def findAvailableSeat(self): - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): if self.seats[i] == None: return i def findAvatar(self, avId): - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): if self.seats[i] == avId: return i @@ -77,7 +77,7 @@ def countFullSeats(self): def countOpenSeats(self): openSeats = 0 - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): if self.seats[i] is None: openSeats += 1 return openSeats @@ -206,7 +206,7 @@ def enterOff(self): self.timeOfBoarding = None self.timeOfGroupBoarding = None if hasattr(self, 'doId'): - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): taskMgr.remove(self.uniqueName('clearEmpty-' + str(seatIndex))) def exitOff(self): diff --git a/toontown/building/DistributedElevatorExtAI.py b/toontown/building/DistributedElevatorExtAI.py index eea0552c6..aa4ac77ad 100644 --- a/toontown/building/DistributedElevatorExtAI.py +++ b/toontown/building/DistributedElevatorExtAI.py @@ -17,7 +17,7 @@ def __init__(self, air, bldg, numSeats = 4, antiShuffle = 0, minLaff = 0): self.boardingParty = None def delete(self): - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] if avId: self.clearFullNow(seatIndex) @@ -153,7 +153,7 @@ def elevatorClosed(self): numPlayers = self.countFullSeats() if numPlayers > 0: self._createInterior() - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] if avId: self.clearFullNow(seatIndex) diff --git a/toontown/building/DistributedElevatorFSM.py b/toontown/building/DistributedElevatorFSM.py index 0754bd980..0ff7bb779 100644 --- a/toontown/building/DistributedElevatorFSM.py +++ b/toontown/building/DistributedElevatorFSM.py @@ -100,7 +100,7 @@ def disable(self): if self.bldgRequest: self.cr.relatedObjectMgr.abortRequest(self.bldgRequest) self.bldgRequest = None - for request in self.toonRequests.values(): + for request in list(self.toonRequests.values()): self.cr.relatedObjectMgr.abortRequest(request) self.toonRequests = {} @@ -213,8 +213,8 @@ def fillSlot(self, index, avId): else: toon.setAnimState('run', 1.0) animFunc = Func(toon.setAnimState, 'neutral', 1.0) - toon.headsUp(self.getElevatorModel(), apply(Point3, self.getScaledPoint(index))) - track = Sequence(LerpPosInterval(toon, TOON_BOARD_ELEVATOR_TIME * 0.75, apply(Point3, self.getScaledPoint(index)), other=self.getElevatorModel()), LerpHprInterval(toon, TOON_BOARD_ELEVATOR_TIME * 0.25, Point3(180, 0, 0), other=self.getElevatorModel()), animFunc, name=toon.uniqueName('fillElevator'), autoPause=1) + toon.headsUp(self.getElevatorModel(), Point3(*self.getScaledPoint(index))) + track = Sequence(LerpPosInterval(toon, TOON_BOARD_ELEVATOR_TIME * 0.75, Point3(*self.getScaledPoint(index)), other=self.getElevatorModel()), LerpHprInterval(toon, TOON_BOARD_ELEVATOR_TIME * 0.25, Point3(180, 0, 0), other=self.getElevatorModel()), animFunc, name=toon.uniqueName('fillElevator'), autoPause=1) track.start() self.boardedAvIds[avId] = index @@ -246,7 +246,7 @@ def notifyToonOffElevator(self, toon): if self.cr: toon.setAnimState('neutral', 1.0) if toon == base.localAvatar: - print 'moving the local toon off the elevator' + print('moving the local toon off the elevator') doneStatus = {'where': 'exit'} elevator = self.getPlaceElevator() elevator.signalDone(doneStatus) @@ -256,7 +256,7 @@ def notifyToonOffElevator(self, toon): return def emptySlot(self, index, avId, bailFlag, timestamp): - print 'Emptying slot: %d for %d' % (index, avId) + print(('Emptying slot: %d for %d' % (index, avId))) if avId == 0: pass elif not self.isSetup: @@ -284,7 +284,7 @@ def emptySlot(self, index, avId, bailFlag, timestamp): if self.offTrack[index].isPlaying(): self.offTrack[index].finish() self.offTrack[index] = None - self.offTrack[index] = Sequence(LerpPosInterval(toon, TOON_EXIT_ELEVATOR_TIME, Point3(0, -ElevatorData[self.type]['collRadius'], 0), startPos=apply(Point3, self.getScaledPoint(index)), other=self.getElevatorModel()), animFunc, Func(self.notifyToonOffElevator, toon), name=toon.uniqueName('emptyElevator'), autoPause=1) + self.offTrack[index] = Sequence(LerpPosInterval(toon, TOON_EXIT_ELEVATOR_TIME, Point3(0, -ElevatorData[self.type]['collRadius'], 0), startPos=Point3(*self.getScaledPoint(index)), other=self.getElevatorModel()), animFunc, Func(self.notifyToonOffElevator, toon), name=toon.uniqueName('emptyElevator'), autoPause=1) if avId == base.localAvatar.getDoId(): messenger.send('exitElevator') scale = base.localAvatar.getScale() @@ -297,7 +297,7 @@ def emptySlot(self, index, avId, bailFlag, timestamp): def handleEnterSphere(self, collEntry): self.notify.debug('Entering Elevator Sphere....') - print 'FSMhandleEnterSphere elevator%s avatar%s' % (self.elevatorTripId, localAvatar.lastElevatorLeft) + print(('FSMhandleEnterSphere elevator%s avatar%s' % (self.elevatorTripId, localAvatar.lastElevatorLeft))) if self.elevatorTripId and localAvatar.lastElevatorLeft == self.elevatorTripId: self.rejectBoard(base.localAvatar.doId, REJECT_SHUFFLE) elif base.localAvatar.hp > 0: @@ -306,7 +306,7 @@ def handleEnterSphere(self, collEntry): self.sendUpdate('requestBoard', []) def rejectBoard(self, avId, reason = 0): - print 'rejectBoard %s' % reason + print(('rejectBoard %s' % reason)) if hasattr(base.localAvatar, 'elevatorNotifier'): if reason == REJECT_SHUFFLE: base.localAvatar.elevatorNotifier.showMe(TTLocalizer.ElevatorHoppedOff) @@ -372,7 +372,7 @@ def onDoorOpenFinish(self): pass def onDoorCloseFinish(self): - for avId in self.boardedAvIds.keys(): + for avId in list(self.boardedAvIds.keys()): av = self.cr.doId2do.get(avId) if av is not None: if av.getParent().compareTo(self.getElevatorModel()) == 0: diff --git a/toontown/building/DistributedElevatorFSMAI.py b/toontown/building/DistributedElevatorFSMAI.py index 6f783ba0b..8781410fa 100644 --- a/toontown/building/DistributedElevatorFSMAI.py +++ b/toontown/building/DistributedElevatorFSMAI.py @@ -45,7 +45,7 @@ def __init__(self, air, bldg, numSeats = 4, antiShuffle = 0, minLaff = 0): self.bldg = bldg self.bldgDoId = bldg.getDoId() self.seats = [] - for seat in xrange(numSeats): + for seat in range(numSeats): self.seats.append(None) self.accepting = 0 self.setAntiShuffle(antiShuffle) @@ -72,12 +72,12 @@ def getBldgDoId(self): return self.bldgDoId def findAvailableSeat(self): - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): if self.seats[i] == None: return i def findAvatar(self, avId): - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): if self.seats[i] == avId: return i @@ -90,7 +90,7 @@ def countFullSeats(self): def countOpenSeats(self): openSeats = 0 - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): if self.seats[i] == None: openSeats += 1 return openSeats @@ -194,7 +194,7 @@ def enterOff(self): self.accepting = 0 self.timeOfBoarding = None if hasattr(self, 'doId'): - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): taskMgr.remove(self.uniqueName('clearEmpty-' + str(seatIndex))) def exitOff(self): @@ -239,16 +239,16 @@ def exitClosing(self): def enterClosed(self): if hasattr(self, 'doId'): - print self.doId + print((self.doId)) self.d_setState('Closed') def exitClosed(self): pass def enterWaitEmpty(self): - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): self.seats[i] = None - print self.seats + print((self.seats)) self.d_setState('WaitEmpty') self.accepting = 1 diff --git a/toontown/building/DistributedElevatorFloor.py b/toontown/building/DistributedElevatorFloor.py index cebb13d70..8e1a3c42f 100644 --- a/toontown/building/DistributedElevatorFloor.py +++ b/toontown/building/DistributedElevatorFloor.py @@ -263,7 +263,7 @@ def getElevatorModel(self): def kickEveryoneOut(self): bailFlag = 0 - for avId, slot in self.boardedAvIds.items(): + for avId, slot in list(self.boardedAvIds.items()): self.emptySlot(slot, avId, bailFlag, globalClockDelta.getRealNetworkTime()) if avId == base.localAvatar.doId: pass diff --git a/toontown/building/DistributedElevatorFloorAI.py b/toontown/building/DistributedElevatorFloorAI.py index 996b761e2..23da018b7 100644 --- a/toontown/building/DistributedElevatorFloorAI.py +++ b/toontown/building/DistributedElevatorFloorAI.py @@ -63,7 +63,7 @@ def generateWithRequired(self, zoneId): DistributedElevatorFSMAI.DistributedElevatorFSMAI.generateWithRequired(self, self.zoneId) def delete(self): - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] if avId: self.clearFullNow(seatIndex) @@ -147,9 +147,9 @@ def waitEmptyTask(self, task): def enterWaitEmpty(self): self.lastState = self.state - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): self.seats[i] = None - print self.seats + print((self.seats)) if self.wantState == 'closed': self.demand('Closing') else: @@ -212,7 +212,7 @@ def elevatorClosed(self): players.append(i) continue sittingAvIds = [] - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] if avId: sittingAvIds.append(avId) diff --git a/toontown/building/DistributedGagshopInterior.py b/toontown/building/DistributedGagshopInterior.py index 5feb8fdf0..318f8ed68 100644 --- a/toontown/building/DistributedGagshopInterior.py +++ b/toontown/building/DistributedGagshopInterior.py @@ -39,7 +39,7 @@ def randomDNAItem(self, category, findFunc): def replaceRandomInModel(self, model): baseTag = 'random_' npc = model.findAllMatches('**/' + baseTag + '???_*') - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): np = npc.getPath(i) name = np.getName() b = len(baseTag) diff --git a/toontown/building/DistributedHQInterior.py b/toontown/building/DistributedHQInterior.py index bcab52c0a..3a0afd775 100644 --- a/toontown/building/DistributedHQInterior.py +++ b/toontown/building/DistributedHQInterior.py @@ -1,4 +1,4 @@ -import cPickle +import pickle import random from toontown.building import ToonInteriorColors from direct.directnotify import DirectNotifyGlobal @@ -66,7 +66,7 @@ def buildLeaderBoard(self): self.nameTextNodes = [] self.scoreTextNodes = [] self.trophyStars = [] - for i in xrange(self.numLeaders): + for i in range(self.numLeaders): (row, nameText, scoreText, trophyStar) = self.buildLeaderRow() self.nameTextNodes.append(nameText) self.scoreTextNodes.append(scoreText) @@ -77,13 +77,13 @@ def buildLeaderBoard(self): def updateLeaderBoard(self): taskMgr.remove(self.uniqueName('starSpinHQ')) - for i in xrange(len(self.leaderNames)): + for i in range(len(self.leaderNames)): name = self.leaderNames[i] score = self.leaderScores[i] self.nameTextNodes[i].setText(name) self.scoreTextNodes[i].setText(str(score)) self.updateTrophyStar(self.trophyStars[i], score) - for i in xrange(len(self.leaderNames), self.numLeaders): + for i in range(len(self.leaderNames), self.numLeaders): self.nameTextNodes[i].setText('-') self.scoreTextNodes[i].setText('-') self.trophyStars[i].hide() @@ -121,7 +121,7 @@ def buildLeaderRow(self): return (row, nameText, scoreText, trophyStar) def setLeaderBoard(self, leaderData): - (avIds, names, scores) = cPickle.loads(leaderData) + (avIds, names, scores) = pickle.loads(leaderData) self.notify.debug('setLeaderBoard: avIds: %s, names: %s, scores: %s' % (avIds, names, scores)) self.leaderAvIds = avIds self.leaderNames = names @@ -144,7 +144,7 @@ def setupDoors(self): door = self.chooseDoor() doorOrigins = render.findAllMatches('**/door_origin*') numDoorOrigins = doorOrigins.getNumPaths() - for npIndex in xrange(numDoorOrigins): + for npIndex in range(numDoorOrigins): doorOrigin = doorOrigins[npIndex] doorOriginNPName = doorOrigin.getName() doorOriginIndexStr = doorOriginNPName[len('door_origin_'):] diff --git a/toontown/building/DistributedHQInteriorAI.py b/toontown/building/DistributedHQInteriorAI.py index 4c940d7e6..f3d9e0241 100644 --- a/toontown/building/DistributedHQInteriorAI.py +++ b/toontown/building/DistributedHQInteriorAI.py @@ -1,4 +1,4 @@ -import cPickle +import pickle from direct.distributed.DistributedObjectAI import DistributedObjectAI class DistributedHQInteriorAI(DistributedObjectAI): @@ -36,11 +36,11 @@ def sendNewLeaderBoard(self): if self.air: self.isDirty = False self.sendUpdate('setLeaderBoard', - [cPickle.dumps(self.air.trophyMgr.getLeaderInfo(), 1)] + [pickle.dumps(self.air.trophyMgr.getLeaderInfo(), 1)] ) def getLeaderBoard(self): - return cPickle.dumps(self.air.trophyMgr.getLeaderInfo(), 1) + return pickle.dumps(self.air.trophyMgr.getLeaderInfo(), 1) def getTutorial(self): return self.tutorial diff --git a/toontown/building/DistributedPetshopInterior.py b/toontown/building/DistributedPetshopInterior.py index 9c68550bc..86d7a5434 100644 --- a/toontown/building/DistributedPetshopInterior.py +++ b/toontown/building/DistributedPetshopInterior.py @@ -32,7 +32,7 @@ def randomDNAItem(self, category, findFunc): def replaceRandomInModel(self, model): baseTag = 'random_' npc = model.findAllMatches('**/' + baseTag + '???_*') - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): np = npc.getPath(i) name = np.getName() b = len(baseTag) diff --git a/toontown/building/DistributedSuitInterior.py b/toontown/building/DistributedSuitInterior.py index 059ecdf2e..225a3cccd 100644 --- a/toontown/building/DistributedSuitInterior.py +++ b/toontown/building/DistributedSuitInterior.py @@ -76,7 +76,7 @@ def generate(self): def setElevatorLights(self, elevatorModel): npc = elevatorModel.findAllMatches('**/floor_light_?;+s') - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): np = npc.getPath(i) floor = int(np.getName()[-1:]) - 1 if floor == self.currentFloor: @@ -146,7 +146,7 @@ def __finishInterval(self, name): interval.finish() def __cleanupIntervals(self): - for interval in self.activeIntervals.values(): + for interval in list(self.activeIntervals.values()): interval.finish() self.activeIntervals = {} @@ -212,7 +212,7 @@ def setSuits(self, suitIds, reserveIds, values): self.notify.warning('setSuits() - no suit: %d' % suitId) self.reserveSuits = [] - for index in xrange(len(reserveIds)): + for index in range(len(reserveIds)): suitId = reserveIds[index] if suitId in self.cr.doId2do: suit = self.cr.doId2do[suitId] @@ -278,7 +278,7 @@ def __playElevator(self, ts, name, callback): self.skyModel.setZ(-100) self.skyBoxLoop = self.skyModel.hprInterval(300, Vec3(360, 0, 0)) self.skyBoxLoop.loop() - for index in xrange(len(self.suits)): + for index in range(len(self.suits)): self.suits[index].setPos(SuitPositions[index]) if len(self.suits) > 2: self.suits[index].setH(SuitHs[index]) diff --git a/toontown/building/DistributedToonHallInterior.py b/toontown/building/DistributedToonHallInterior.py index dd3e86352..f7acf01eb 100644 --- a/toontown/building/DistributedToonHallInterior.py +++ b/toontown/building/DistributedToonHallInterior.py @@ -1,4 +1,4 @@ -import cPickle +import pickle import random import time from toontown.toonbase.ToonBaseGlobal import * @@ -7,7 +7,7 @@ from direct.showbase import Audio3DManager from toontown.toonbase import ToontownGlobals from toontown.dna.DNAParser import DNADoor -from DistributedToonInterior import DistributedToonInterior +from .DistributedToonInterior import DistributedToonInterior from direct.directnotify import DirectNotifyGlobal from direct.fsm import ClassicFSM, State from direct.distributed import DistributedObject diff --git a/toontown/building/DistributedToonInterior.py b/toontown/building/DistributedToonInterior.py index be8ccf407..b4c422e57 100644 --- a/toontown/building/DistributedToonInterior.py +++ b/toontown/building/DistributedToonInterior.py @@ -1,4 +1,4 @@ -import cPickle +import pickle import random from toontown.building import ToonInterior from toontown.building import ToonInteriorColors @@ -58,7 +58,7 @@ def randomDNAItem(self, category, findFunc): def replaceRandomInModel(self, model): baseTag = 'random_' npc = model.findAllMatches('**/' + baseTag + '???_*') - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): np = npc.getPath(i) name = np.getName() b = len(baseTag) @@ -145,7 +145,7 @@ def setZoneIdAndBlock(self, zoneId, block): self.block = block def setToonData(self, toonData): - savedBy = cPickle.loads(toonData) + savedBy = pickle.loads(toonData) self.savedBy = savedBy def buildTrophy(self): @@ -165,7 +165,7 @@ def buildTrophy(self): def buildFrame(self, name, dnaTuple): frame = loader.loadModel('phase_3.5/models/modules/trophy_frame') dna = ToonDNA.ToonDNA() - apply(dna.newToonFromProperties, dnaTuple) + dna.newToonFromProperties(*dnaTuple) head = ToonHead.ToonHead() head.setupHead(dna) head.setPosHprScale(0, -0.05, -0.05, 180, 0, 0, 0.55, 0.02, 0.55) diff --git a/toontown/building/DistributedToonInteriorAI.py b/toontown/building/DistributedToonInteriorAI.py index 9c5ef66c2..c704bdeea 100644 --- a/toontown/building/DistributedToonInteriorAI.py +++ b/toontown/building/DistributedToonInteriorAI.py @@ -1,4 +1,4 @@ -import cPickle +import pickle from direct.distributed import DistributedObjectAI from direct.distributed.ClockDelta import * from direct.fsm import ClassicFSM, State @@ -42,7 +42,7 @@ def getZoneIdAndBlock(self): return [self.zoneId, self.block] def getToonData(self): - return cPickle.dumps(self.building.savedBy, 1) + return pickle.dumps(self.building.savedBy, 1) def getState(self): return [self.fsm.getCurrentState().getName(), globalClockDelta.getRealNetworkTime()] diff --git a/toontown/building/DistributedTrophyMgrAI.py b/toontown/building/DistributedTrophyMgrAI.py index 3c152d25e..bf53e0381 100644 --- a/toontown/building/DistributedTrophyMgrAI.py +++ b/toontown/building/DistributedTrophyMgrAI.py @@ -74,7 +74,7 @@ def updateTrophyScore(self, avId, trophyScore): def reorganize(self): # Sort the leader info: - leaderInfo = zip(*reversed(self.leaderInfo)) + leaderInfo = list(zip(*reversed(self.leaderInfo))) leaderInfo.sort(reverse=True) # Construct the new, truncated leader info: diff --git a/toontown/building/DistributedTutorialInterior.py b/toontown/building/DistributedTutorialInterior.py index 3213ae701..8d6dbb81e 100644 --- a/toontown/building/DistributedTutorialInterior.py +++ b/toontown/building/DistributedTutorialInterior.py @@ -49,7 +49,7 @@ def randomDNAItem(self, category, findFunc): def replaceRandomInModel(self, model): baseTag = 'random_' npc = model.findAllMatches('**/' + baseTag + '???_*') - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): np = npc.getPath(i) name = np.getName() b = len(baseTag) @@ -119,7 +119,7 @@ def setup(self): del self.dnaStore del self.randomGenerator self.interior.flattenMedium() - npcOrigin = self.interior.find('**/npc_origin_' + `(self.cr.doId2do[self.npcId].posIndex)`) + npcOrigin = self.interior.find('**/npc_origin_' + repr((self.cr.doId2do[self.npcId].posIndex))) if not npcOrigin.isEmpty(): self.cr.doId2do[self.npcId].reparentTo(npcOrigin) self.cr.doId2do[self.npcId].clearMat() diff --git a/toontown/building/PetshopBuildingAI.py b/toontown/building/PetshopBuildingAI.py index 685da26dc..bae4017e7 100644 --- a/toontown/building/PetshopBuildingAI.py +++ b/toontown/building/PetshopBuildingAI.py @@ -1,6 +1,6 @@ -import DistributedDoorAI -import DistributedPetshopInteriorAI -import DoorTypes +from . import DistributedDoorAI +from . import DistributedPetshopInteriorAI +from . import DoorTypes from panda3d.core import * from panda3d.direct import * from toontown.hood import ZoneUtil diff --git a/toontown/building/SuitInterior.py b/toontown/building/SuitInterior.py index cc199cdb5..e4688479a 100644 --- a/toontown/building/SuitInterior.py +++ b/toontown/building/SuitInterior.py @@ -68,7 +68,7 @@ def load(self): self.parentFSM.getStateNamed('suitInterior').addChild(self.fsm) self.townBattle = TownBattle.TownBattle('town-battle-done') self.townBattle.load() - for i in xrange(1, 3): + for i in range(1, 3): Suit.loadSuits(i) def unload(self): @@ -82,7 +82,7 @@ def unload(self): self.townBattle.unload() self.townBattle.cleanup() del self.townBattle - for i in xrange(1, 3): + for i in range(1, 3): Suit.unloadSuits(i) def setState(self, state, battleEvent = None): diff --git a/toontown/building/SuitPlannerInteriorAI.py b/toontown/building/SuitPlannerInteriorAI.py index a80b8664c..faab4f7f8 100644 --- a/toontown/building/SuitPlannerInteriorAI.py +++ b/toontown/building/SuitPlannerInteriorAI.py @@ -21,7 +21,7 @@ def __init__(self, numFloors, bldgLevel, bldgTrack, zone): self.dbg_defaultSuitType = None else: self.dbg_defaultSuitType = SuitDNA.getSuitType(dbg_defaultSuitName) - if isinstance(bldgLevel, types.StringType): + if isinstance(bldgLevel, bytes): self.notify.warning('bldgLevel is a string!') bldgLevel = int(bldgLevel) @@ -29,7 +29,7 @@ def __init__(self, numFloors, bldgLevel, bldgTrack, zone): def __genJoinChances(self, num): joinChances = [] - for currChance in xrange(num): + for currChance in range(num): joinChances.append(random.randint(1, 100)) joinChances.sort(cmp) @@ -38,7 +38,7 @@ def __genJoinChances(self, num): def _genSuitInfos(self, numFloors, bldgLevel, bldgTrack): self.suitInfos = [] self.notify.debug('\n\ngenerating suitsInfos with numFloors (' + str(numFloors) + ') bldgLevel (' + str(bldgLevel) + '+1) and bldgTrack (' + str(bldgTrack) + ')') - for currFloor in xrange(numFloors): + for currFloor in range(numFloors): infoDict = {} lvls = self.__genLevelList(bldgLevel, currFloor, numFloors) activeDicts = [] @@ -60,7 +60,7 @@ def _genSuitInfos(self, numFloors, bldgLevel, bldgTrack): revives = bldgInfo[SuitBuildingGlobals.SUIT_BLDG_INFO_REVIVES][0] else: revives = 0 - for currActive in xrange(numActive - 1, -1, -1): + for currActive in range(numActive - 1, -1, -1): level = lvls[currActive] type = self.__genNormalSuitType(level) activeDict = {} @@ -78,7 +78,7 @@ def _genSuitInfos(self, numFloors, bldgLevel, bldgTrack): reserveDicts = [] numReserve = len(lvls) - numActive joinChances = self.__genJoinChances(numReserve) - for currReserve in xrange(numReserve): + for currReserve in range(numReserve): level = lvls[currReserve + numActive] type = self.__genNormalSuitType(level) reserveDict = {} @@ -170,11 +170,11 @@ def myPrint(self): for currInfo in suitInfos: whichSuitInfo = suitInfos.index(currInfo) + 1 self.notify.debug(' Floor ' + str(whichSuitInfo) + ' has ' + str(len(currInfo[0])) + ' active suits.') - for currActive in xrange(len(currInfo[0])): + for currActive in range(len(currInfo[0])): self.notify.debug(' Active suit ' + str(currActive + 1) + ' is of type ' + str(currInfo[0][currActive][0]) + ' and of track ' + str(currInfo[0][currActive][1]) + ' and of level ' + str(currInfo[0][currActive][2])) self.notify.debug(' Floor ' + str(whichSuitInfo) + ' has ' + str(len(currInfo[1])) + ' reserve suits.') - for currReserve in xrange(len(currInfo[1])): + for currReserve in range(len(currInfo[1])): self.notify.debug(' Reserve suit ' + str(currReserve + 1) + ' is of type ' + str(currInfo[1][currReserve][0]) + ' and of track ' + str(currInfo[1][currReserve][1]) + ' and of lvel ' + str(currInfo[1][currReserve][2]) + ' and has ' + str(currInfo[1][currReserve][3]) + '% join restriction.') def genFloorSuits(self, floor): @@ -196,7 +196,7 @@ def genFloorSuits(self, floor): def genSuits(self): suitHandles = [] - for floor in xrange(len(self.suitInfos)): + for floor in range(len(self.suitInfos)): floorSuitHandles = self.genFloorSuits(floor) suitHandles.append(floorSuitHandles) diff --git a/toontown/building/ToonInterior.py b/toontown/building/ToonInterior.py index c4fb0d4b3..b9c6f4a2a 100644 --- a/toontown/building/ToonInterior.py +++ b/toontown/building/ToonInterior.py @@ -132,7 +132,7 @@ def enterDFACallback(self, requestStatus, doneStatus): elif ds == 'incomplete': self.fsm.request('DFAReject') else: - self.notify.error('Unknown done status for DownloadForceAcknowledge: ' + `doneStatus`) + self.notify.error('Unknown done status for DownloadForceAcknowledge: ' + repr(doneStatus)) def enterNPCFA(self, requestStatus): self.acceptOnce(self.npcfaDoneEvent, self.enterNPCFACallback, [requestStatus]) @@ -153,7 +153,7 @@ def enterNPCFACallback(self, requestStatus, doneStatus): elif doneStatus['mode'] == 'incomplete': self.fsm.request('NPCFAReject') else: - self.notify.error('Unknown done status for NPCForceAcknowledge: ' + `doneStatus`) + self.notify.error('Unknown done status for NPCForceAcknowledge: ' + repr(doneStatus)) def enterNPCFAReject(self): self.fsm.request('walk') @@ -180,7 +180,7 @@ def enterHFACallback(self, requestStatus, doneStatus): elif doneStatus['mode'] == 'incomplete': self.fsm.request('HFAReject') else: - self.notify.error('Unknown done status for HealthForceAcknowledge: ' + `doneStatus`) + self.notify.error('Unknown done status for HealthForceAcknowledge: ' + repr(doneStatus)) def enterHFAReject(self): self.fsm.request('walk') diff --git a/toontown/catalog/CatalogAccessoryItem.py b/toontown/catalog/CatalogAccessoryItem.py index 463066ba7..ec15da532 100644 --- a/toontown/catalog/CatalogAccessoryItem.py +++ b/toontown/catalog/CatalogAccessoryItem.py @@ -73,7 +73,7 @@ def reachedPurchaseLimit(self, avatar): if hat[0] == defn[0] and hat[1] == defn[1] and hat[2] == defn[2]: return 1 l = avatar.hatList - for i in xrange(0, len(l), 3): + for i in range(0, len(l), 3): if l[i] == defn[0] and l[i + 1] == defn[1] and l[i + 2] == defn[2]: return 1 @@ -83,7 +83,7 @@ def reachedPurchaseLimit(self, avatar): if glasses[0] == defn[0] and glasses[1] == defn[1] and glasses[2] == defn[2]: return 1 l = avatar.glassesList - for i in xrange(0, len(l), 3): + for i in range(0, len(l), 3): if l[i] == defn[0] and l[i + 1] == defn[1] and l[i + 2] == defn[2]: return 1 @@ -93,7 +93,7 @@ def reachedPurchaseLimit(self, avatar): if backpack[0] == defn[0] and backpack[1] == defn[1] and backpack[2] == defn[2]: return 1 l = avatar.backpackList - for i in xrange(0, len(l), 3): + for i in range(0, len(l), 3): if l[i] == defn[0] and l[i + 1] == defn[1] and l[i + 2] == defn[2]: return 1 @@ -103,7 +103,7 @@ def reachedPurchaseLimit(self, avatar): if shoes[0] == defn[0] and shoes[1] == defn[1] and shoes[2] == defn[2]: return 1 l = avatar.shoesList - for i in xrange(0, len(l), 3): + for i in range(0, len(l), 3): if l[i] == defn[0] and l[i + 1] == defn[1] and l[i + 2] == defn[2]: return 1 @@ -228,7 +228,7 @@ def getPicture(self, avatar): def applyColor(self, model, color): if model == None or color == None: return - if isinstance(color, types.StringType): + if isinstance(color, bytes): tex = loader.loadTexture(color) tex.setMinfilter(Texture.FTLinearMipmapLinear) tex.setMagfilter(Texture.FTLinear) diff --git a/toontown/catalog/CatalogChatItem.py b/toontown/catalog/CatalogChatItem.py index 2317736ba..00dbf50ec 100644 --- a/toontown/catalog/CatalogChatItem.py +++ b/toontown/catalog/CatalogChatItem.py @@ -86,7 +86,7 @@ def requestPurchase(self, phone, callback): def showMessagePicker(self, phone, callback): self.phone = phone self.callback = callback - import CatalogChatItemPicker + from . import CatalogChatItemPicker self.messagePicker = CatalogChatItemPicker.CatalogChatItemPicker(self.__handlePickerDone, self.customIndex) self.messagePicker.show() @@ -94,12 +94,12 @@ def showMessagePickerOnAccept(self, mailbox, index, callback): self.mailbox = mailbox self.callback = callback self.index = index - import CatalogChatItemPicker + from . import CatalogChatItemPicker self.messagePicker = CatalogChatItemPicker.CatalogChatItemPicker(self.__handlePickerOnAccept, self.customIndex) self.messagePicker.show() def __handlePickerOnAccept(self, status, pickedMessage = None): - print 'Picker Status%s' % status + print(('Picker Status%s' % status)) if status == 'pick': self.mailbox.acceptItem(self, self.index, self.callback, pickedMessage) else: @@ -133,7 +133,7 @@ def getPicture(self, avatar): def getChatRange(fromIndex, toIndex, *otherRanges): - list = [] + _list = [] froms = [fromIndex] tos = [toIndex] i = 0 @@ -142,9 +142,9 @@ def getChatRange(fromIndex, toIndex, *otherRanges): tos.append(otherRanges[i + 1]) i += 2 - for chatId in OTPLocalizer.CustomSCStrings.keys(): + for chatId in list(OTPLocalizer.CustomSCStrings.keys()): for fromIndex, toIndex in zip(froms, tos): if chatId >= fromIndex and chatId <= toIndex and chatId not in bannedPhrases: - list.append(CatalogChatItem(chatId)) + _list.append(CatalogChatItem(chatId)) - return list + return _list diff --git a/toontown/catalog/CatalogClothingItem.py b/toontown/catalog/CatalogClothingItem.py index 95c639a18..b44cc5261 100644 --- a/toontown/catalog/CatalogClothingItem.py +++ b/toontown/catalog/CatalogClothingItem.py @@ -359,7 +359,7 @@ def reachedPurchaseLimit(self, avatar): if dna.topTex == defn[0] and dna.topTexColor == defn[2][self.colorIndex][0] and dna.sleeveTex == defn[1] and dna.sleeveTexColor == defn[2][self.colorIndex][1]: return 1 l = avatar.clothesTopsList - for i in xrange(0, len(l), 4): + for i in range(0, len(l), 4): if l[i] == defn[0] and l[i + 1] == defn[2][self.colorIndex][0] and l[i + 2] == defn[1] and l[i + 3] == defn[2][self.colorIndex][1]: return 1 @@ -368,7 +368,7 @@ def reachedPurchaseLimit(self, avatar): if dna.botTex == defn[0] and dna.botTexColor == defn[1][self.colorIndex]: return 1 l = avatar.clothesBottomsList - for i in xrange(0, len(l), 2): + for i in range(0, len(l), 2): if l[i] == defn[0] and l[i + 1] == defn[1][self.colorIndex]: return 1 @@ -597,7 +597,7 @@ def getAllClothes(*clothingTypes): for clothingType in clothingTypes: base = CatalogClothingItem(clothingType, 0) list.append(base) - for n in xrange(1, len(base.getColorChoices())): + for n in range(1, len(base.getColorChoices())): list.append(CatalogClothingItem(clothingType, n)) return list diff --git a/toontown/catalog/CatalogFlooringItem.py b/toontown/catalog/CatalogFlooringItem.py index 346d6e748..f94f2aba6 100644 --- a/toontown/catalog/CatalogFlooringItem.py +++ b/toontown/catalog/CatalogFlooringItem.py @@ -101,7 +101,7 @@ def getColor(self): if colorIndex < len(colors): return colors[colorIndex] else: - print 'Warning: colorIndex not in colors. Returning white.' + print('Warning: colorIndex not in colors. Returning white.') return CT_WHITE else: return CT_WHITE @@ -141,7 +141,7 @@ def getAllFloorings(*indexList): for index in indexList: colors = FlooringTypes[index][FTColor] if colors: - for n in xrange(len(colors)): + for n in range(len(colors)): list.append(CatalogFlooringItem(index, n)) else: @@ -160,12 +160,12 @@ def getFlooringRange(fromIndex, toIndex, *otherRanges): tos.append(otherRanges[i + 1]) i += 2 - for patternIndex in FlooringTypes.keys(): + for patternIndex in list(FlooringTypes.keys()): for fromIndex, toIndex in zip(froms, tos): if patternIndex >= fromIndex and patternIndex <= toIndex: colors = FlooringTypes[patternIndex][FTColor] if colors: - for n in xrange(len(colors)): + for n in range(len(colors)): list.append(CatalogFlooringItem(patternIndex, n)) else: diff --git a/toontown/catalog/CatalogFurnitureItem.py b/toontown/catalog/CatalogFurnitureItem.py index 48e85cbc1..229a9c795 100644 --- a/toontown/catalog/CatalogFurnitureItem.py +++ b/toontown/catalog/CatalogFurnitureItem.py @@ -77,7 +77,7 @@ 1350: 45000 } MoneyToBank = {} -for bankId, maxMoney in BankToMoney.items(): +for bankId, maxMoney in list(BankToMoney.items()): MoneyToBank[maxMoney] = bankId @@ -93,7 +93,7 @@ 516: 25, 518: 50} ClothesToCloset = {} -for closetId, maxClothes in ClosetToClothes.items(): +for closetId, maxClothes in list(ClosetToClothes.items()): if maxClothes not in ClothesToCloset: ClothesToCloset[maxClothes] = (closetId,) else: @@ -1076,7 +1076,7 @@ def loadModel(self): self.applyColor(model, type[FTColor]) if type[FTColorOptions] != None: if self.colorOption == None: - option = random.choice(type[FTColorOptions].values()) + option = random.choice(list(type[FTColorOptions].values())) else: option = type[FTColorOptions].get(self.colorOption) self.applyColor(model, option) @@ -1159,7 +1159,7 @@ def getMaxClosets(): def getAllClosets(): list = [] - for closetId in ClosetToClothes.keys(): + for closetId in list(ClosetToClothes.keys()): list.append(CatalogFurnitureItem(closetId)) return list @@ -1188,7 +1188,7 @@ def getMaxTrunks(): def getAllFurnitures(index): list = [] colors = FurnitureTypes[index][FTColorOptions] - for n in xrange(len(colors)): + for n in range(len(colors)): list.append(CatalogFurnitureItem(index, n)) return list @@ -1205,6 +1205,6 @@ def nextAvailableBank(avatar, duplicateItems): def getAllBanks(): list = [] - for bankid in BankToMoney.keys(): + for bankid in list(BankToMoney.keys()): list.append(CatalogFurnitureItem(bankId)) return list \ No newline at end of file diff --git a/toontown/catalog/CatalogGardenStarterItem.py b/toontown/catalog/CatalogGardenStarterItem.py index fd37bce03..95cdcb99d 100644 --- a/toontown/catalog/CatalogGardenStarterItem.py +++ b/toontown/catalog/CatalogGardenStarterItem.py @@ -38,7 +38,7 @@ def recordPurchase(self, avatar, optional): if av: av.b_setGardenStarted(1) else: - print 'starter garden-- something not there' + print('starter garden-- something not there') return ToontownGlobals.P_ItemAvailable def getPicture(self, avatar): diff --git a/toontown/catalog/CatalogGenerator.py b/toontown/catalog/CatalogGenerator.py index ef0c27810..3dfa30452 100644 --- a/toontown/catalog/CatalogGenerator.py +++ b/toontown/catalog/CatalogGenerator.py @@ -1502,7 +1502,7 @@ def generateBackCatalog(self, avatar, week, previousWeek, weeklyCatalog): lastBackCatalog = avatar.backCatalog[:] thisWeek = min(len(WeeklySchedule), week - 1) lastWeek = min(len(WeeklySchedule), previousWeek) - for week in xrange(thisWeek, lastWeek, -1): + for week in range(thisWeek, lastWeek, -1): self.notify.debug('Adding items from week %s to back catalog' % week) schedule = WeeklySchedule[week - 1] if not isinstance(schedule, Sale): @@ -1596,9 +1596,9 @@ def __selectItem(self, avatar, item, duplicateItems, saleItem = 0): saleItem = 1 if callable(item): item = item(avatar, duplicateItems) - if isinstance(item, types.TupleType): + if isinstance(item, tuple): chooseCount, item = item - if isinstance(item, types.IntType): + if isinstance(item, int): item = MetaItems[item] selection = [] if isinstance(item, CatalogItem.CatalogItem): @@ -1607,7 +1607,7 @@ def __selectItem(self, avatar, item, duplicateItems, saleItem = 0): selection.append(item) elif item != None: list = item[:] - for i in xrange(chooseCount): + for i in range(chooseCount): if len(list) == 0: return selection item = self.__chooseFromList(avatar, list, duplicateItems) @@ -1633,7 +1633,7 @@ def __chooseFromList(self, avatar, list, duplicateItems): def outputSchedule(self, filename): out = open(Filename(filename).toOsSpecific(), 'w') sched = self.generateScheduleDictionary() - items = sched.keys() + items = list(sched.keys()) items.sort() for item in items: weeklist, maybeWeeklist = sched[item] @@ -1641,7 +1641,7 @@ def outputSchedule(self, filename): seriesDict = {} self.__determineSeries(seriesDict, weeklist) self.__determineSeries(seriesDict, maybeWeeklist) - seriesList = seriesDict.keys() + seriesList = list(seriesDict.keys()) seriesList.sort() series = str(seriesList)[1:-1] week = self.__formatWeeklist(weeklist) @@ -1667,7 +1667,7 @@ def __formatColor(self, color): def __determineSeries(self, seriesDict, weeklist): for week in weeklist: - if isinstance(week, types.IntType): + if isinstance(week, int): series = (week - 1) / ToontownGlobals.CatalogNumWeeksPerSeries + 1 seriesDict[series] = None @@ -1680,7 +1680,7 @@ def __formatWeeklist(self, weeklist): def generateScheduleDictionary(self): sched = {} - for index in xrange(len(WeeklySchedule)): + for index in range(len(WeeklySchedule)): week = index + 1 schedule = WeeklySchedule[index] if isinstance(schedule, Sale): @@ -1722,9 +1722,9 @@ def __recordSchedule(self, sched, weekCode, schedule): else: self.notify.warning("Don't know how to interpret function " % repr(name)) item = None - elif isinstance(item, types.TupleType): + elif isinstance(item, tuple): item = item[1] - if isinstance(item, types.IntType): + if isinstance(item, int): item = MetaItems[item] if isinstance(item, CatalogItem.CatalogItem): self.__recordScheduleItem(sched, weekCode, None, item) diff --git a/toontown/catalog/CatalogItem.py b/toontown/catalog/CatalogItem.py index 52170d922..624f008cc 100644 --- a/toontown/catalog/CatalogItem.py +++ b/toontown/catalog/CatalogItem.py @@ -328,17 +328,17 @@ def applyColor(self, model, colorDesc): matches = model.findAllMatches(partName) if color == None: matches.hide() - elif isinstance(color, types.StringType): + elif isinstance(color, bytes): tex = loader.loadTexture(color) tex.setMinfilter(Texture.FTLinearMipmapLinear) tex.setMagfilter(Texture.FTLinear) - for i in xrange(matches.getNumPaths()): + for i in range(matches.getNumPaths()): matches.getPath(i).setTexture(tex, 1) else: needsAlpha = color[3] != 1 color = VBase4(color[0], color[1], color[2], color[3]) - for i in xrange(matches.getNumPaths()): + for i in range(matches.getNumPaths()): matches.getPath(i).setColorScale(color, 1) if needsAlpha: matches.getPath(i).setTransparency(1) @@ -397,7 +397,7 @@ def getDaysToGo(self, avatar): def encodeCatalogItem(dg, item, store): - import CatalogItemTypes + from . import CatalogItemTypes flags = item.getTypeCode() if item.isSaleItem(): flags |= CatalogItemTypes.CatalogItemSaleFlag @@ -414,10 +414,10 @@ def encodeCatalogItem(dg, item, store): def decodeCatalogItem(di, versionNumber, store): global CatalogReverseType - import CatalogItemTypes + from . import CatalogItemTypes if CatalogReverseType == None: CatalogReverseType = {} - for itemClass, index in CatalogItemTypes.CatalogItemTypes.items(): + for itemClass, index in list(CatalogItemTypes.CatalogItemTypes.items()): CatalogReverseType[index] = itemClass startIndex = di.getCurrentIndex() @@ -431,11 +431,11 @@ def decodeCatalogItem(di, versionNumber, store): code = di.getUint8() itemClass = CatalogReverseType[typeIndex] item = itemClass(di, versionNumber, store=store) - except Exception, e: + except Exception as e: CatalogItem.notify.warning('Invalid catalog item in stream: %s, %s' % (sys.exc_info()[0], e)) d = Datagram(di.getDatagram().getMessage()[startIndex:]) d.dumpHex(Notify.out()) - import CatalogInvalidItem + from . import CatalogInvalidItem return CatalogInvalidItem.CatalogInvalidItem() if flags & CatalogItemTypes.CatalogItemSaleFlag: @@ -451,8 +451,8 @@ def getItem(blob, store = 0): try: versionNumber = di.getUint8() return decodeCatalogItem(di, versionNumber, store) - except Exception, e: + except Exception as e: CatalogItem.notify.warning('Invalid catalog item: %s, %s' % (sys.exc_info()[0], e)) dg.dumpHex(Notify.out()) - import CatalogInvalidItem + from . import CatalogInvalidItem return CatalogInvalidItem.CatalogInvalidItem() diff --git a/toontown/catalog/CatalogItemList.py b/toontown/catalog/CatalogItemList.py index 40a811e58..2a11ad60b 100644 --- a/toontown/catalog/CatalogItemList.py +++ b/toontown/catalog/CatalogItemList.py @@ -1,4 +1,4 @@ -import CatalogItem +from . import CatalogItem from pandac.PandaModules import * import types from direct.distributed.PyDatagram import PyDatagram @@ -10,9 +10,9 @@ def __init__(self, source = None, store = 0): self.store = store self.__blob = None self.__list = None - if isinstance(source, types.StringType): + if isinstance(source, bytes): self.__blob = source - elif isinstance(source, types.ListType): + elif isinstance(source, list): self.__list = source[:] elif isinstance(source, CatalogItemList): if source.store == store: diff --git a/toontown/catalog/CatalogItemPanel.py b/toontown/catalog/CatalogItemPanel.py index 9dd1a9ce1..ca289ade2 100644 --- a/toontown/catalog/CatalogItemPanel.py +++ b/toontown/catalog/CatalogItemPanel.py @@ -3,14 +3,14 @@ from toontown.toonbase import ToontownGlobals from toontown.toontowngui import TTDialog from toontown.toonbase import TTLocalizer -import CatalogItemTypes -import CatalogItem -from CatalogWallpaperItem import getAllWallpapers -from CatalogFlooringItem import getAllFloorings -from CatalogMouldingItem import getAllMouldings -from CatalogWainscotingItem import getAllWainscotings -from CatalogFurnitureItem import getAllFurnitures -from CatalogFurnitureItem import FLTrunk +from . import CatalogItemTypes +from . import CatalogItem +from .CatalogWallpaperItem import getAllWallpapers +from .CatalogFlooringItem import getAllFloorings +from .CatalogMouldingItem import getAllMouldings +from .CatalogWainscotingItem import getAllWainscotings +from .CatalogFurnitureItem import getAllFurnitures +from .CatalogFurnitureItem import FLTrunk from toontown.toontowngui.TeaserPanel import TeaserPanel from otp.otpbase import OTPGlobals CATALOG_PANEL_WORDWRAP = 10 diff --git a/toontown/catalog/CatalogManagerAI.py b/toontown/catalog/CatalogManagerAI.py index 87324bb0f..ada52d46d 100644 --- a/toontown/catalog/CatalogManagerAI.py +++ b/toontown/catalog/CatalogManagerAI.py @@ -1,5 +1,5 @@ from direct.distributed.DistributedObjectAI import DistributedObjectAI -from CatalogGenerator import CatalogGenerator +from .CatalogGenerator import CatalogGenerator from toontown.toonbase import ToontownGlobals import time diff --git a/toontown/catalog/CatalogMouldingItem.py b/toontown/catalog/CatalogMouldingItem.py index 31941f7cb..ca976d024 100644 --- a/toontown/catalog/CatalogMouldingItem.py +++ b/toontown/catalog/CatalogMouldingItem.py @@ -1,4 +1,4 @@ -from CatalogSurfaceItem import * +from .CatalogSurfaceItem import * MTTextureName = 0 MTColor = 1 MTBasePrice = 2 @@ -85,7 +85,7 @@ def getColor(self): if colorIndex < len(colors): return colors[colorIndex] else: - print 'Warning: colorIndex not in colors. Returning white.' + print('Warning: colorIndex not in colors. Returning white.') return CT_WHITE else: return CT_WHITE @@ -119,7 +119,7 @@ def getAllMouldings(*indexList): for index in indexList: colors = MouldingTypes[index][MTColor] if colors: - for n in xrange(len(colors)): + for n in range(len(colors)): list.append(CatalogMouldingItem(index, n)) else: @@ -138,12 +138,12 @@ def getMouldingRange(fromIndex, toIndex, *otherRanges): tos.append(otherRanges[i + 1]) i += 2 - for patternIndex in MouldingTypes.keys(): + for patternIndex in list(MouldingTypes.keys()): for fromIndex, toIndex in zip(froms, tos): if patternIndex >= fromIndex and patternIndex <= toIndex: colors = MouldingTypes[patternIndex][MTColor] if colors: - for n in xrange(len(colors)): + for n in range(len(colors)): list.append(CatalogMouldingItem(patternIndex, n)) else: diff --git a/toontown/catalog/CatalogNametagItem.py b/toontown/catalog/CatalogNametagItem.py index f1981aca6..628b03bcc 100644 --- a/toontown/catalog/CatalogNametagItem.py +++ b/toontown/catalog/CatalogNametagItem.py @@ -1,4 +1,4 @@ -import CatalogItem +from . import CatalogItem from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer from otp.otpbase import OTPLocalizer diff --git a/toontown/catalog/CatalogPetTrickItem.py b/toontown/catalog/CatalogPetTrickItem.py index 68282efd9..2ef1fae6f 100644 --- a/toontown/catalog/CatalogPetTrickItem.py +++ b/toontown/catalog/CatalogPetTrickItem.py @@ -1,4 +1,4 @@ -import CatalogItem +from . import CatalogItem from toontown.pets import PetTricks from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer @@ -96,8 +96,8 @@ def encodeDatagram(self, dg, store): def getAllPetTricks(): - list = [] - for trickId in PetTricks.TrickId2scIds.keys(): - list.append(CatalogPetTrickItem(trickId)) + _list = [] + for trickId in list(PetTricks.TrickId2scIds.keys()): + _list.append(CatalogPetTrickItem(trickId)) - return list \ No newline at end of file + return _list \ No newline at end of file diff --git a/toontown/catalog/CatalogPoleItem.py b/toontown/catalog/CatalogPoleItem.py index eec084d34..ba9e99650 100644 --- a/toontown/catalog/CatalogPoleItem.py +++ b/toontown/catalog/CatalogPoleItem.py @@ -1,4 +1,4 @@ -import CatalogItem +from . import CatalogItem from toontown.toonbase import ToontownGlobals from toontown.fishing import FishGlobals from direct.actor import Actor @@ -101,7 +101,7 @@ def nextAvailablePole(avatar, duplicateItems): def getAllPoles(): list = [] - for rodId in xrange(0, FishGlobals.MaxRodId + 1): + for rodId in range(0, FishGlobals.MaxRodId + 1): list.append(CatalogPoleItem(rodId)) return list diff --git a/toontown/catalog/CatalogRentalItem.py b/toontown/catalog/CatalogRentalItem.py index 32ef0cea8..e2221b976 100644 --- a/toontown/catalog/CatalogRentalItem.py +++ b/toontown/catalog/CatalogRentalItem.py @@ -1,4 +1,4 @@ -import CatalogItem +from . import CatalogItem import time from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer diff --git a/toontown/catalog/CatalogScreen.py b/toontown/catalog/CatalogScreen.py index e63424d91..e4aeae7a3 100644 --- a/toontown/catalog/CatalogScreen.py +++ b/toontown/catalog/CatalogScreen.py @@ -4,18 +4,18 @@ from direct.gui.DirectScrolledList import * from toontown.toonbase import ToontownGlobals from toontown.toontowngui import TTDialog -import CatalogItem -import CatalogInvalidItem -import CatalogFurnitureItem +from . import CatalogItem +from . import CatalogInvalidItem +from . import CatalogFurnitureItem from toontown.toonbase import TTLocalizer -import CatalogItemPanel -import CatalogItemTypes +from . import CatalogItemPanel +from . import CatalogItemTypes from direct.actor import Actor import random from toontown.toon import DistributedToon from direct.directnotify import DirectNotifyGlobal from toontown.nametag import NametagGlobals -import CatalogChatBalloon +from . import CatalogChatBalloon from toontown.toontowngui import FeatureComingSoonDialog NUM_CATALOG_ROWS = 3 @@ -271,11 +271,11 @@ def showPageItems(self): pIndex = 0 randGen = random.Random() randGen.seed(base.localAvatar.catalogScheduleCurrentWeek + (self.pageIndex << 8) + (newOrBackOrLoyalty << 16)) - for i in xrange(NUM_CATALOG_ROWS): - for j in xrange(NUM_CATALOG_COLS): + for i in range(NUM_CATALOG_ROWS): + for j in range(NUM_CATALOG_COLS): if pIndex < len(self.visiblePanels): type = self.visiblePanels[pIndex]['item'].getTypeCode() - self.squares[i][j].setColor(CatalogPanelColors.values()[randGen.randint(0, len(CatalogPanelColors) - 1)]) + self.squares[i][j].setColor(list(CatalogPanelColors.values())[randGen.randint(0, len(CatalogPanelColors) - 1)]) cs = 0.7 + 0.3 * randGen.random() self.squares[i][j].setColorScale(0.7 + 0.3 * randGen.random(), 0.7 + 0.3 * randGen.random(), 0.7 + 0.3 * randGen.random(), 1) else: @@ -308,7 +308,7 @@ def showPageItems(self): def adjustForSound(self): numEmoteItems = 0 emotePanels = [] - for visIndex in xrange(len(self.visiblePanels)): + for visIndex in range(len(self.visiblePanels)): panel = self.visiblePanels[visIndex] item = panel['item'] catalogType = item.getTypeCode() @@ -510,7 +510,7 @@ def load(self, guiItems, guiButton, guiBack): self.__chooseFriend(self.ffList[0][0], self.ffList[0][1]) self.update() self.createdGiftGui = 1 - for i in xrange(4): + for i in range(4): self.newCatalogButton.component('text%d' % i).setR(90) self.newCatalogButton2.component('text%d' % i).setR(90) self.backCatalogButton.component('text%d' % i).setR(90) @@ -523,8 +523,8 @@ def load(self, guiItems, guiButton, guiBack): [], [], []] - for i in xrange(NUM_CATALOG_ROWS): - for j in xrange(NUM_CATALOG_COLS): + for i in range(NUM_CATALOG_ROWS): + for j in range(NUM_CATALOG_COLS): square = guiItems.find('**/square%d%db' % (i + 1, j + 1)) label = DirectLabel(self.base, image=square, relief=None, state='normal') self.squares[i].append(label) diff --git a/toontown/catalog/CatalogSurfaceItem.py b/toontown/catalog/CatalogSurfaceItem.py index 35c00cb0c..2ef79581f 100644 --- a/toontown/catalog/CatalogSurfaceItem.py +++ b/toontown/catalog/CatalogSurfaceItem.py @@ -1,8 +1,8 @@ -import CatalogItem -import CatalogAtticItem +from . import CatalogItem +from . import CatalogAtticItem from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer -from CatalogSurfaceColors import * +from .CatalogSurfaceColors import * STWallpaper = 0 diff --git a/toontown/catalog/CatalogToonStatueItem.py b/toontown/catalog/CatalogToonStatueItem.py index ca0f69e2b..7416720a5 100644 --- a/toontown/catalog/CatalogToonStatueItem.py +++ b/toontown/catalog/CatalogToonStatueItem.py @@ -1,4 +1,4 @@ -import CatalogGardenItem +from . import CatalogGardenItem from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer from otp.otpbase import OTPLocalizer @@ -49,7 +49,7 @@ def compareTo(self, other): def getAllToonStatues(self): self.statueList = [] - for index in xrange(self.startPoseIndex, self.endPoseIndex + 1): + for index in range(self.startPoseIndex, self.endPoseIndex + 1): self.statueList.append(CatalogToonStatueItem(index, 1, endPoseIndex=index)) return self.statueList diff --git a/toontown/catalog/CatalogWainscotingItem.py b/toontown/catalog/CatalogWainscotingItem.py index 8c37e4b25..b6b9cadd6 100644 --- a/toontown/catalog/CatalogWainscotingItem.py +++ b/toontown/catalog/CatalogWainscotingItem.py @@ -1,4 +1,4 @@ -from CatalogSurfaceItem import * +from .CatalogSurfaceItem import * WSTTextureName = 0 WSTColor = 1 WSTBasePrice = 2 @@ -76,7 +76,7 @@ def getColor(self): if colorIndex < len(colors): return colors[colorIndex] else: - print 'Warning: colorIndex not in colors. Returning white.' + print('Warning: colorIndex not in colors. Returning white.') return CT_WHITE else: return CT_WHITE @@ -110,7 +110,7 @@ def getAllWainscotings(*indexList): for index in indexList: colors = WainscotingTypes[index][WSTColor] if colors: - for n in xrange(len(colors)): + for n in range(len(colors)): list.append(CatalogWainscotingItem(index, n)) else: @@ -129,12 +129,12 @@ def getWainscotingRange(fromIndex, toIndex, *otherRanges): tos.append(otherRanges[i + 1]) i += 2 - for patternIndex in WainscotingTypes.keys(): + for patternIndex in list(WainscotingTypes.keys()): for fromIndex, toIndex in zip(froms, tos): if patternIndex >= fromIndex and patternIndex <= toIndex: colors = WainscotingTypes[patternIndex][WSTColor] if colors: - for n in xrange(len(colors)): + for n in range(len(colors)): list.append(CatalogWainscotingItem(patternIndex, n)) else: diff --git a/toontown/catalog/CatalogWallpaperItem.py b/toontown/catalog/CatalogWallpaperItem.py index 2adf2ecc9..ba2760f75 100644 --- a/toontown/catalog/CatalogWallpaperItem.py +++ b/toontown/catalog/CatalogWallpaperItem.py @@ -1,4 +1,4 @@ -from CatalogSurfaceItem import * +from .CatalogSurfaceItem import * WTTextureName = 0 WTColor = 1 @@ -722,9 +722,9 @@ def getAllWallpapers(*typeList): numBorderColors = len(borderData[BDColor]) else: numBorderColors = 1 - for borderColorIndex in xrange(numBorderColors): + for borderColorIndex in range(numBorderColors): colors = WallpaperTypes[index][WTColor] - for n in xrange(len(colors)): + for n in range(len(colors)): list.append(CatalogWallpaperItem(index, n, borderKey, borderColorIndex)) return list @@ -737,7 +737,7 @@ def getWallpaperRange(fromIndex, toIndex, *otherRanges): froms.append(otherRanges[i]) tos.append(otherRanges[i + 1]) i += 2 - for patternIndex in WallpaperTypes.keys(): + for patternIndex in list(WallpaperTypes.keys()): for fromIndex, toIndex in zip(froms, tos): if patternIndex >= fromIndex and patternIndex <= toIndex: borderKeys = WallpaperTypes[patternIndex][WTBorderList] @@ -747,8 +747,8 @@ def getWallpaperRange(fromIndex, toIndex, *otherRanges): numBorderColors = len(borderData[BDColor]) else: numBorderColors = 1 - for borderColorIndex in xrange(numBorderColors): + for borderColorIndex in range(numBorderColors): colors = WallpaperTypes[patternIndex][WTColor] - for n in xrange(len(colors)): + for n in range(len(colors)): list.append(CatalogWallpaperItem(patternIndex, n, borderKey, borderColorIndex)) return list diff --git a/toontown/catalog/CatalogWindowItem.py b/toontown/catalog/CatalogWindowItem.py index cd2f45046..d1d1f17d6 100644 --- a/toontown/catalog/CatalogWindowItem.py +++ b/toontown/catalog/CatalogWindowItem.py @@ -1,6 +1,6 @@ from pandac.PandaModules import * -import CatalogAtticItem -import CatalogItem +from . import CatalogAtticItem +from . import CatalogItem from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer WVTModelName = 0 diff --git a/toontown/catalog/MailboxScreen.py b/toontown/catalog/MailboxScreen.py index 43e3ef6cf..20cda98e4 100644 --- a/toontown/catalog/MailboxScreen.py +++ b/toontown/catalog/MailboxScreen.py @@ -44,9 +44,9 @@ def hide(self): else: self.notify.warning('hide called, but frame is deleted, self.frame deleted in:') if hasattr(self, 'frameDelStackTrace'): - print self.frameDelStackTrace + print((self.frameDelStackTrace)) self.notify.warning('current stackTrace =') - print StackTrace() + print((StackTrace())) self.notify.warning('crash averted, but root cause unknown') def load(self): @@ -237,7 +237,7 @@ def __acceptItemCallback(self, retcode, item, index): if not hasattr(self, 'frame'): return if retcode == ToontownGlobals.P_UserCancelled: - print 'mailbox screen user canceled' + print('mailbox screen user canceled') self.acceptingIndex = None self.__updateItems() return @@ -285,7 +285,7 @@ def __acceptOk(self, index, buttonValue = None): self.dialogBox = None self.items = self.getItems() if self.itemIndex > index or self.itemIndex >= len(self.items): - print 'adjusting item index -1' + print('adjusting item index -1') self.itemIndex -= 1 if len(self.items) < 1: self.__handleExit() @@ -303,10 +303,10 @@ def __updateItems(self): self.dialogBox = None self.items = self.getItems() if self.itemIndex >= len(self.items): - print 'adjusting item index -1' + print('adjusting item index -1') self.itemIndex = len(self.items) - 1 if len(self.items) == 0: - print 'exiting due to lack of items' + print('exiting due to lack of items') self.__handleExit() return self.itemCountLabel['text'] = (self.__getNumberOfItemsText(),) diff --git a/toontown/char/Char.py b/toontown/char/Char.py index 20ef24008..22479a905 100644 --- a/toontown/char/Char.py +++ b/toontown/char/Char.py @@ -222,14 +222,14 @@ def generateChar(self): self.loadDialogue(dna.name) self.ears = [] if self.name == 'mickey' or self.name == 'vampire_mickey' or self.name == 'minnie': - for bundle in self.getPartBundleDict().values(): + for bundle in list(self.getPartBundleDict().values()): bundle = bundle['modelRoot'].getBundle() earNull = bundle.findChild('sphere3') if not earNull: earNull = bundle.findChild('*sphere3') earNull.clearNetTransforms() - for bundle in self.getPartBundleDict().values(): + for bundle in list(self.getPartBundleDict().values()): charNodepath = bundle['modelRoot'].partBundleNP bundle = bundle['modelRoot'].getBundle() earNull = bundle.findChild('sphere3') @@ -399,7 +399,7 @@ def getNametagJoints(self): def loadChatterDialogue(self, name, audioIndexArray, loadPath, language): chatterTypes = ['greetings', 'comments', 'goodbyes'] - for categoryIndex in xrange(len(audioIndexArray)): + for categoryIndex in range(len(audioIndexArray)): chatterType = chatterTypes[categoryIndex] for fileIndex in audioIndexArray[categoryIndex]: if fileIndex: @@ -419,7 +419,7 @@ def loadDialogue(self, char): language = base.config.GetString('language', 'english') if char == 'mk': dialogueFile = base.loader.loadSfx('phase_3/audio/dial/mickey.ogg') - for i in xrange(0, 6): + for i in range(0, 6): self.dialogueArray.append(dialogueFile) if language == 'japanese': @@ -434,7 +434,7 @@ def loadDialogue(self, char): self.loadChatterDialogue('mickey', chatterIndexArray, 'phase_3/audio/dial', language) elif char == 'vmk': dialogueFile = base.loader.loadSfx('phase_3/audio/dial/mickey.ogg') - for i in xrange(0, 6): + for i in range(0, 6): self.dialogueArray.append(dialogueFile) if language == 'japanese': @@ -449,7 +449,7 @@ def loadDialogue(self, char): self.loadChatterDialogue('mickey', chatterIndexArray, 'phase_3/audio/dial', language) elif char == 'mn' or char == 'wmn': dialogueFile = base.loader.loadSfx('phase_3/audio/dial/minnie.ogg') - for i in xrange(0, 6): + for i in range(0, 6): self.dialogueArray.append(dialogueFile) if language == 'japanese': @@ -473,7 +473,7 @@ def loadDialogue(self, char): self.loadChatterDialogue('minnie', chatterIndexArray, 'phase_3/audio/dial', language) elif char == 'dd' or char == 'shdd': dialogueFile = base.loader.loadSfx('phase_4/audio/dial/daisy.ogg') - for i in xrange(0, 6): + for i in range(0, 6): self.dialogueArray.append(dialogueFile) if language == 'japanese': @@ -495,7 +495,7 @@ def loadDialogue(self, char): self.loadChatterDialogue('daisy', chatterIndexArray, 'phase_8/audio/dial', language) elif char == 'g' or char == 'sg': dialogueFile = base.loader.loadSfx('phase_6/audio/dial/goofy.ogg') - for i in xrange(0, 6): + for i in range(0, 6): self.dialogueArray.append(dialogueFile) if language == 'japanese': @@ -517,7 +517,7 @@ def loadDialogue(self, char): self.loadChatterDialogue('goofy', chatterIndexArray, 'phase_6/audio/dial', language) elif char == 'd' or char == 'dw' or char == 'fd': dialogueFile = base.loader.loadSfx('phase_6/audio/dial/donald.ogg') - for i in xrange(0, 6): + for i in range(0, 6): self.dialogueArray.append(dialogueFile) if char == 'd': @@ -539,32 +539,32 @@ def loadDialogue(self, char): self.loadChatterDialogue('donald', chatterIndexArray, 'phase_6/audio/dial', language) elif char == 'p' or char == 'wp': dialogueFile = base.loader.loadSfx('phase_3.5/audio/dial/AV_dog_med.ogg') - for i in xrange(0, 6): + for i in range(0, 6): self.dialogueArray.append(dialogueFile) elif char == 'cl': dialogueFile = base.loader.loadSfx('phase_3.5/audio/dial/AV_dog_med.ogg') - for i in xrange(0, 6): + for i in range(0, 6): self.dialogueArray.append(dialogueFile) elif char == 'ch': dialogueFile = base.loader.loadSfx('phase_6/audio/dial/chip.ogg') - for i in xrange(0, 6): + for i in range(0, 6): self.dialogueArray.append(dialogueFile) elif char == 'da': dialogueFile = base.loader.loadSfx('phase_6/audio/dial/dale.ogg') - for i in xrange(0, 6): + for i in range(0, 6): self.dialogueArray.append(dialogueFile) elif char == 'pch': dialogueFile = base.loader.loadSfx('phase_6/audio/dial/chip.ogg') - for i in xrange(0, 6): + for i in range(0, 6): self.dialogueArray.append(dialogueFile) elif char == 'jda': dialogueFile = base.loader.loadSfx('phase_6/audio/dial/dale.ogg') - for i in xrange(0, 6): + for i in range(0, 6): self.dialogueArray.append(dialogueFile) else: diff --git a/toontown/chat/ResistanceChat.py b/toontown/chat/ResistanceChat.py index 110c10144..c42ea844b 100644 --- a/toontown/chat/ResistanceChat.py +++ b/toontown/chat/ResistanceChat.py @@ -162,7 +162,7 @@ def doEffect(textId, speakingToon, nearbyToons): 'particles-4': (0, 0, 1, 1), 'particles-5': (1, 0, 1, 1) } - for name, color in colors.items(): + for name, color in list(colors.items()): node = bean.copyTo(NodePath()) node.setColorScale(*color) p = effect.getParticlesNamed(name) @@ -175,13 +175,13 @@ def doEffect(textId, speakingToon, nearbyToons): invModel.flattenLight() icons = [] if itemValue != -1: - for item in xrange(6): + for item in range(6): iconName = ToontownBattleGlobals.AvPropsNew[itemValue][item] icons.append(invModel.find('**/%s' % iconName)) else: - tracks = range(8) + tracks = list(range(8)) random.shuffle(tracks) - for i in xrange(6): + for i in range(6): track = tracks[i] item = random.randint(0, 5) iconName = ToontownBattleGlobals.AvPropsNew[track][item] @@ -194,7 +194,7 @@ def doEffect(textId, speakingToon, nearbyToons): 'particles-5': icons[4], 'particles-6': icons[5] } - for name, icon in iconDict.items(): + for name, icon in list(iconDict.items()): p = effect.getParticlesNamed(name) p.renderer.setFromNode(icon) fadeColor = VBase4(0, 0, 1, 1) diff --git a/toontown/chat/TTChatInputSpeedChat.py b/toontown/chat/TTChatInputSpeedChat.py index 0158866f2..ebf4d3d30 100644 --- a/toontown/chat/TTChatInputSpeedChat.py +++ b/toontown/chat/TTChatInputSpeedChat.py @@ -466,8 +466,8 @@ def selectionMade(self = self): scZ = -0.04 self.speedChat.setPos(0.283, 0, scZ) if not self.firstTime: - self.speedChat.setPos(-99, -99, -99) - self.firstTime = 1 + self.speedChat.setPos(-99, -99, -99) + self.firstTime = 1 self.speedChat.setWhisperMode(self.whisperAvatarId != None) self.speedChat.enter() diff --git a/toontown/chat/TTSCWhiteListTerminal.py b/toontown/chat/TTSCWhiteListTerminal.py index dfff6c7d6..49891f282 100644 --- a/toontown/chat/TTSCWhiteListTerminal.py +++ b/toontown/chat/TTSCWhiteListTerminal.py @@ -13,7 +13,7 @@ def __init__(self, textId, parentMenu = None): self.parentClass = parentMenu self.textId = textId self.text = SpeedChatStaticText[self.textId] - print 'SpeedText %s %s' % (self.textId, self.text) + print(('SpeedText %s %s' % (self.textId, self.text))) def handleSelect(self): SCTerminal.handleSelect(self) diff --git a/toontown/chat/ToonChatGarbler.py b/toontown/chat/ToonChatGarbler.py index 9cb0213ce..bb2ee7773 100644 --- a/toontown/chat/ToonChatGarbler.py +++ b/toontown/chat/ToonChatGarbler.py @@ -29,7 +29,7 @@ def garble(self, toon, message): else: wordlist = ToonChatGarbler.animalSounds['default'] numWords = random.randint(1, 7) - for i in xrange(1, numWords + 1): + for i in range(1, numWords + 1): wordIndex = random.randint(0, len(wordlist) - 1) newMessage = newMessage + wordlist[wordIndex] if i < numWords: @@ -45,7 +45,7 @@ def garbleSingle(self, toon, message): else: wordlist = ToonChatGarbler.animalSounds['default'] numWords = 1 - for i in xrange(1, numWords + 1): + for i in range(1, numWords + 1): wordIndex = random.randint(0, len(wordlist) - 1) newMessage = newMessage + wordlist[wordIndex] if i < numWords: diff --git a/toontown/chat/ToontownChatManager.py b/toontown/chat/ToontownChatManager.py index c5a178861..458294282 100644 --- a/toontown/chat/ToontownChatManager.py +++ b/toontown/chat/ToontownChatManager.py @@ -9,9 +9,9 @@ from direct.gui.DirectGui import * from pandac.PandaModules import * from otp.chat import ChatManager -from TTChatInputSpeedChat import TTChatInputSpeedChat -from TTChatInputNormal import TTChatInputNormal -from TTChatInputWhiteList import TTChatInputWhiteList +from .TTChatInputSpeedChat import TTChatInputSpeedChat +from .TTChatInputNormal import TTChatInputNormal +from .TTChatInputWhiteList import TTChatInputWhiteList class HackedDirectRadioButton(DirectCheckButton): diff --git a/toontown/classicchars/CCharPaths.py b/toontown/classicchars/CCharPaths.py index 8f4edef19..f69d6aec5 100644 --- a/toontown/classicchars/CCharPaths.py +++ b/toontown/classicchars/CCharPaths.py @@ -438,7 +438,7 @@ def getPointsFromTo(fromNode, toNode, paths): def getWalkDuration(fromNode, toNode, velocity, paths): posPoints = getPointsFromTo(fromNode, toNode, paths) duration = 0 - for pointIndex in xrange(len(posPoints) - 1): + for pointIndex in range(len(posPoints) - 1): startPoint = posPoints[pointIndex] endPoint = posPoints[pointIndex + 1] distance = Vec3(endPoint - startPoint).length() @@ -450,7 +450,7 @@ def getWalkDuration(fromNode, toNode, velocity, paths): def getWalkDistance(fromNode, toNode, velocity, paths): posPoints = getPointsFromTo(fromNode, toNode, paths) retval = 0 - for pointIndex in xrange(len(posPoints) - 1): + for pointIndex in range(len(posPoints) - 1): startPoint = posPoints[pointIndex] endPoint = posPoints[pointIndex + 1] distance = Vec3(endPoint - startPoint).length() diff --git a/toontown/classicchars/CharStateDatas.py b/toontown/classicchars/CharStateDatas.py index 140abde51..d94c4e6dd 100644 --- a/toontown/classicchars/CharStateDatas.py +++ b/toontown/classicchars/CharStateDatas.py @@ -89,7 +89,7 @@ def makePathTrack(self, nodePath, posPoints, velocity, raycast = 0): if raycast: track.append(Func(nodePath.enableRaycast, 1)) startHpr = nodePath.getHpr() - for pointIndex in xrange(len(posPoints) - 1): + for pointIndex in range(len(posPoints) - 1): startPoint = posPoints[pointIndex] endPoint = posPoints[pointIndex + 1] track.append(Func(nodePath.setPos, startPoint)) diff --git a/toontown/classicchars/DistributedFrankenDonald.py b/toontown/classicchars/DistributedFrankenDonald.py index d4891ff9b..880a2955f 100644 --- a/toontown/classicchars/DistributedFrankenDonald.py +++ b/toontown/classicchars/DistributedFrankenDonald.py @@ -1,7 +1,7 @@ from pandac.PandaModules import * from direct.interval.IntervalGlobal import * from toontown.classicchars import DistributedCCharBase -import DistributedDonald +from . import DistributedDonald from direct.directnotify import DirectNotifyGlobal from direct.fsm import ClassicFSM, State from direct.fsm import State diff --git a/toontown/coderedemption/TTCodeRedemptionMgr.py b/toontown/coderedemption/TTCodeRedemptionMgr.py index e39655eb3..ace02520b 100644 --- a/toontown/coderedemption/TTCodeRedemptionMgr.py +++ b/toontown/coderedemption/TTCodeRedemptionMgr.py @@ -18,7 +18,7 @@ def __init__(self, cr): def announceGenerate(self): DistributedObject.announceGenerate(self) base.cr.codeRedemptionMgr = self - self._contextGen = SerialMaskedGen(4294967295L) + self._contextGen = SerialMaskedGen(4294967295) self._context2callback = {} def delete(self): @@ -31,8 +31,8 @@ def delete(self): DistributedObject.delete(self) def redeemCode(self, code, callback): - context = self._contextGen.next() - print(datetime.now()) + context = next(self._contextGen) + print((datetime.now())) self._context2callback[context] = callback self.notify.debug('redeemCode(%s, %s)' % (context, code)) self.sendUpdate('redeemCode', [context, code]) diff --git a/toontown/cogdominium/CogdoBarrelRoom.py b/toontown/cogdominium/CogdoBarrelRoom.py index 19a06fb8a..70c77b19a 100644 --- a/toontown/cogdominium/CogdoBarrelRoom.py +++ b/toontown/cogdominium/CogdoBarrelRoom.py @@ -49,7 +49,7 @@ def load(self): self.fog.setColor(CogdoBarrelRoomConsts.BarrelRoomFogColor) self.fog.setLinearRange(*CogdoBarrelRoomConsts.BarrelRoomFogLinearRange) self.brBarrel = render.attachNewNode('@@CogdoBarrels') - for i in xrange(len(CogdoBarrelRoomConsts.BarrelProps)): + for i in range(len(CogdoBarrelRoomConsts.BarrelProps)): self.bPath = self.brBarrel.attachNewNode('%s%s'% (CogdoBarrelRoomConsts.BarrelPathName, i)) self.bPath.setPos(CogdoBarrelRoomConsts.BarrelProps[i]['pos']) self.bPath.setH(CogdoBarrelRoomConsts.BarrelProps[i]['heading']) @@ -117,11 +117,11 @@ def deactivate(self): self.timer.stash() def placeToonsAtEntrance(self, toons): - for i in xrange(len(toons)): + for i in range(len(toons)): toons[i].setPosHpr(self.entranceNode, *CogdoBarrelRoomConsts.BarrelRoomPlayerSpawnPoints[i]) def placeToonsNearBattle(self, toons): - for i in xrange(len(toons)): + for i in range(len(toons)): toons[i].setPosHpr(self.nearBattleNode, *CogdoBarrelRoomConsts.BarrelRoomPlayerSpawnPoints[i]) def showBattleAreaLight(self, visible = True): diff --git a/toontown/cogdominium/CogdoBarrelRoomConsts.py b/toontown/cogdominium/CogdoBarrelRoomConsts.py index 9c9731403..a1e503600 100644 --- a/toontown/cogdominium/CogdoBarrelRoomConsts.py +++ b/toontown/cogdominium/CogdoBarrelRoomConsts.py @@ -96,7 +96,7 @@ BarrelGrabSound = 'phase_4/audio/sfx/SZ_DD_treasure.ogg' BarrelAvailableTexture = 'phase_5/maps/tt_t_ara_cbr_Barrel_notUsed.jpg' BarrelUsedTexture = 'phase_5/maps/tt_t_ara_cbr_Barrel_Used.jpg' -StateHidden, StateAvailable, StateUsed, StateCrushed = range(4) +StateHidden, StateAvailable, StateUsed, StateCrushed = list(range(4)) def numBarrels(): return len(BarrelProps) diff --git a/toontown/cogdominium/CogdoBarrelRoomMovies.py b/toontown/cogdominium/CogdoBarrelRoomMovies.py index 5d77c2079..0e091316e 100644 --- a/toontown/cogdominium/CogdoBarrelRoomMovies.py +++ b/toontown/cogdominium/CogdoBarrelRoomMovies.py @@ -10,7 +10,7 @@ from toontown.toonbase import TTLocalizer from toontown.suit import Suit, SuitDNA from toontown.toon import Toon, ToonHead, ToonDNA -from DistributedCogdoInterior import * +from .DistributedCogdoInterior import * from toontown.cogdominium.CogdoUtil import CogdoGameMovie from toontown.cogdominium import CogdoBarrelRoomConsts, CogdoUtil diff --git a/toontown/cogdominium/CogdoBarrelRoomRewardPanel.py b/toontown/cogdominium/CogdoBarrelRoomRewardPanel.py index 678b5c2a9..7fc7a4fd6 100644 --- a/toontown/cogdominium/CogdoBarrelRoomRewardPanel.py +++ b/toontown/cogdominium/CogdoBarrelRoomRewardPanel.py @@ -12,7 +12,7 @@ def __init__(self): self.initialiseoptions(CogdoBarrelRoomRewardPanel) self.avNameLabel = DirectLabel(parent=self, relief=None, pos=(0, 0, 0.3), text='Toon Ups', text_scale=0.08) self.rewardLines = [] - for i in xrange(CogdoBarrelRoomConsts.MaxToons): + for i in range(CogdoBarrelRoomConsts.MaxToons): rewardLine = {} rewardLine['frame'] = DirectFrame(parent=self, relief=None, frameSize=(-0.5, 0.5, diff --git a/toontown/cogdominium/CogdoCraneGameConsts.py b/toontown/cogdominium/CogdoCraneGameConsts.py index 21d8251a8..a4aa8cbf4 100644 --- a/toontown/cogdominium/CogdoCraneGameConsts.py +++ b/toontown/cogdominium/CogdoCraneGameConsts.py @@ -55,5 +55,5 @@ 180, 0, 0]] -for i in xrange(len(MoneyBagPosHprs)): +for i in range(len(MoneyBagPosHprs)): MoneyBagPosHprs[i][2] += 6 \ No newline at end of file diff --git a/toontown/cogdominium/CogdoEntityCreator.py b/toontown/cogdominium/CogdoEntityCreator.py index c9d37159c..1b2d2b7cc 100644 --- a/toontown/cogdominium/CogdoEntityCreator.py +++ b/toontown/cogdominium/CogdoEntityCreator.py @@ -9,7 +9,7 @@ class CogdoEntityCreator(EntityCreator.EntityCreator): def __init__(self, level): EntityCreator.EntityCreator.__init__(self, level) nothing = EntityCreator.nothing - nonlocal = EntityCreator.nonlocal + _nonlocal = EntityCreator._nonlocal self.privRegisterTypes({'levelMgr': CogdoLevelMgr, 'cogdoBoardroomGameSettings': Functor(self._createCogdoSettings, CogdoBoardroomGameConsts.Settings), 'cogdoCraneGameSettings': Functor(self._createCogdoSettings, CogdoCraneGameConsts.Settings), diff --git a/toontown/cogdominium/CogdoFlyingCameraManager.py b/toontown/cogdominium/CogdoFlyingCameraManager.py index 1c5518a2d..7b056ed8b 100644 --- a/toontown/cogdominium/CogdoFlyingCameraManager.py +++ b/toontown/cogdominium/CogdoFlyingCameraManager.py @@ -166,7 +166,7 @@ def _updateCollisions(self): if np not in nodesInBetween: nodesInBetween[np] = np.getParent() - for np in nodesInBetween.keys(): + for np in list(nodesInBetween.keys()): if np in self._betweenCamAndToon: del self._betweenCamAndToon[np] else: @@ -181,7 +181,7 @@ def _updateCollisions(self): if not node.isEmpty(): node.hide() - for np, parent in self._betweenCamAndToon.items(): + for np, parent in list(self._betweenCamAndToon.items()): np.wrtReparentTo(parent) np.setTransparency(False) if np.getName().find('lightFixture') >= 0: diff --git a/toontown/cogdominium/CogdoFlyingGameGuis.py b/toontown/cogdominium/CogdoFlyingGameGuis.py index 95aa0615b..99a055bc1 100644 --- a/toontown/cogdominium/CogdoFlyingGameGuis.py +++ b/toontown/cogdominium/CogdoFlyingGameGuis.py @@ -63,7 +63,7 @@ def _getToonMarker(self, toon): return type def update(self): - for toon, marker in self._toonMarkers.items(): + for toon, marker in list(self._toonMarkers.items()): progress = clamp((toon.getY() - self._levelStartY) / self._levelDistance, self._levelStartY, self._levelEndY) marker.setZ(clamp(self._lineStart + self._lineDistance * progress, self._lineStart, self._lineEnd)) @@ -147,13 +147,13 @@ def setBlades(self, fuelState): return numBlades = fuelState - 1 if len(self.activeBlades) != numBlades: - for i in xrange(len(self.activeBlades)): + for i in range(len(self.activeBlades)): blade = self.activeBlades.pop() blade.stash() if numBlades > len(self.blades): numBlades = len(self.blades) - for i in xrange(numBlades): + for i in range(numBlades): blade = self.blades[i] self.activeBlades.append(blade) blade.unstash() diff --git a/toontown/cogdominium/CogdoFlyingLegalEagle.py b/toontown/cogdominium/CogdoFlyingLegalEagle.py index 1b1962703..bc248afef 100644 --- a/toontown/cogdominium/CogdoFlyingLegalEagle.py +++ b/toontown/cogdominium/CogdoFlyingLegalEagle.py @@ -15,7 +15,7 @@ from toontown.cogdominium import CogdoUtil from toontown.cogdominium import CogdoFlyingGameGlobals as Globals -class CogdoFlyingLegalEagle(DirectObject, FSM): +class CogdoFlyingLegalEagle(FSM, DirectObject): CollSphereName = 'CogdoFlyingLegalEagleSphere' CollisionEventName = 'CogdoFlyingLegalEagleCollision' InterestCollName = 'CogdoFlyingLegalEagleInterestCollision' diff --git a/toontown/cogdominium/CogdoFlyingLevel.py b/toontown/cogdominium/CogdoFlyingLevel.py index 1447f914e..ec1194482 100644 --- a/toontown/cogdominium/CogdoFlyingLevel.py +++ b/toontown/cogdominium/CogdoFlyingLevel.py @@ -157,7 +157,7 @@ def _switchToQuadrant(self, quadNum): if quadNum >= 0: if quadNum > 0: self.quadrants[max(quadNum - self.quadVisibiltyBehind, 0)].onstage() - for i in xrange(quadNum, min(quadNum + self.quadVisibiltyAhead + 1, self._numQuads)): + for i in range(quadNum, min(quadNum + self.quadVisibiltyAhead + 1, self._numQuads)): self.quadrants[i].onstage() self.visibleQuadIndices.append(i) if i == 0: @@ -166,7 +166,7 @@ def _switchToQuadrant(self, quadNum): self.endPlatform.onstage() self._currentQuadNum = quadNum - for i in range(0, max(self._currentQuadNum - self.quadVisibiltyBehind, 0)) + range(min(self._currentQuadNum + self.quadVisibiltyAhead + 1, self._numQuads), self._numQuads): + for i in list(range(0, max(self._currentQuadNum - self.quadVisibiltyBehind, 0))) + list(range(min(self._currentQuadNum + self.quadVisibiltyAhead + 1, self._numQuads), self._numQuads)): self.quadrants[i].offstage() if i == 0: self.startPlatform.offstage() diff --git a/toontown/cogdominium/CogdoFlyingLevelQuadrant.py b/toontown/cogdominium/CogdoFlyingLevelQuadrant.py index 185b1791d..08396d8de 100644 --- a/toontown/cogdominium/CogdoFlyingLevelQuadrant.py +++ b/toontown/cogdominium/CogdoFlyingLevelQuadrant.py @@ -11,7 +11,7 @@ def __init__(self, serialNum, model, level, parent): self.serialNum = serialNum self._model = model self._level = level - self._root = NodePath('Quadrant' + `serialNum`) + self._root = NodePath('Quadrant' + repr(serialNum)) self._model.reparentTo(self._root) self._root.reparentTo(parent) self._visible = True @@ -65,7 +65,7 @@ def _initPlatforms(self, parent): self.platforms[platform.getName()] = platform def _destroyPlatforms(self): - for platform in self.platforms.values(): + for platform in list(self.platforms.values()): platform.destroy() del self.platforms @@ -138,7 +138,7 @@ def generatePropellers(): gatherable.removeNode() def generatePowerUps(): - for powerupType, locName in Globals.Level.PowerupType2Loc.iteritems(): + for powerupType, locName in list(Globals.Level.PowerupType2Loc.items()): gatherables = gatherableModel.findAllMatches('**/%s' % locName) for gatherable in gatherables: pickup = self._level.gatherableFactory.createPowerup(powerupType) diff --git a/toontown/cogdominium/CogdoFlyingLocalPlayer.py b/toontown/cogdominium/CogdoFlyingLocalPlayer.py index 0d127f4e6..f9172f3fb 100644 --- a/toontown/cogdominium/CogdoFlyingLocalPlayer.py +++ b/toontown/cogdominium/CogdoFlyingLocalPlayer.py @@ -13,14 +13,14 @@ from toontown.minigame.OrthoDrive import OrthoDrive from toontown.minigame.OrthoWalk import OrthoWalk from toontown.toonbase import TTLocalizer -from CogdoFlyingCollisions import CogdoFlyingCollisions -from CogdoFlyingPlayer import CogdoFlyingPlayer -from CogdoFlyingGuiManager import CogdoFlyingGuiManager -from CogdoFlyingInputManager import CogdoFlyingInputManager -from CogdoFlyingCameraManager import CogdoFlyingCameraManager -from CogdoFlyingObjects import CogdoFlyingPlatform, CogdoFlyingGatherable -from CogdoFlyingLegalEagle import CogdoFlyingLegalEagle -import CogdoFlyingGameGlobals as Globals +from .CogdoFlyingCollisions import CogdoFlyingCollisions +from .CogdoFlyingPlayer import CogdoFlyingPlayer +from .CogdoFlyingGuiManager import CogdoFlyingGuiManager +from .CogdoFlyingInputManager import CogdoFlyingInputManager +from .CogdoFlyingCameraManager import CogdoFlyingCameraManager +from .CogdoFlyingObjects import CogdoFlyingPlatform, CogdoFlyingGatherable +from .CogdoFlyingLegalEagle import CogdoFlyingLegalEagle +from . import CogdoFlyingGameGlobals as Globals class CogdoFlyingLocalPlayer(CogdoFlyingPlayer): notify = DirectNotifyGlobal.directNotify.newCategory('CogdoFlyingLocalPlayer') diff --git a/toontown/cogdominium/CogdoFlyingObjects.py b/toontown/cogdominium/CogdoFlyingObjects.py index 78063e783..8a9e747d8 100644 --- a/toontown/cogdominium/CogdoFlyingObjects.py +++ b/toontown/cogdominium/CogdoFlyingObjects.py @@ -19,7 +19,7 @@ def __init__(self): self._memoModel = CogdoUtil.loadModel('memo', 'shared').find('**/memo') self._propellerModel = CogdoUtil.loadFlyingModel('propellers').find('**/mesh') self._powerUpModels = {} - for type, modelName in Globals.Level.PowerupType2Model.items(): + for type, modelName in list(Globals.Level.PowerupType2Model.items()): model = CogdoUtil.loadFlyingModel(modelName).find('**/' + Globals.Level.PowerupType2Node[type]) self._powerUpModels[type] = model model.setTransparency(True) @@ -80,7 +80,7 @@ def destroy(self): del self._memoModel self._propellerModel.removeNode() del self._propellerModel - for model in self._powerUpModels.values(): + for model in list(self._powerUpModels.values()): model.removeNode() del self._powerUpModels diff --git a/toontown/cogdominium/CogdoFlyingPlayer.py b/toontown/cogdominium/CogdoFlyingPlayer.py index 7e2b84803..74758c68f 100644 --- a/toontown/cogdominium/CogdoFlyingPlayer.py +++ b/toontown/cogdominium/CogdoFlyingPlayer.py @@ -233,14 +233,14 @@ def setBlades(self, fuelState): return numBlades = fuelState - 1 if len(self.activeBlades) != numBlades: - for i in xrange(len(self.activeBlades)): + for i in range(len(self.activeBlades)): blade = self.activeBlades.pop() blade.stash() if numBlades > len(self.blades): numBlades = len(self.blades) if numBlades > 0: - for i in xrange(numBlades): + for i in range(numBlades): blade = self.blades[i] self.activeBlades.append(blade) blade.unstash() diff --git a/toontown/cogdominium/CogdoGameAudioManager.py b/toontown/cogdominium/CogdoGameAudioManager.py index 1a80dac36..159cc1c0b 100644 --- a/toontown/cogdominium/CogdoGameAudioManager.py +++ b/toontown/cogdominium/CogdoGameAudioManager.py @@ -42,7 +42,7 @@ def __init__(self, musicFiles, sfxFiles, listener, cutoff = 75): self._cutoff = cutoff self.currentMusic = None self._music = {} - for name, filePath in musicFiles.items(): + for name, filePath in list(musicFiles.items()): self._music[name] = base.loader.loadMusic(filePath) self._audioSounds = [] diff --git a/toontown/cogdominium/CogdoInterior.py b/toontown/cogdominium/CogdoInterior.py index f015d481a..41f18134c 100644 --- a/toontown/cogdominium/CogdoInterior.py +++ b/toontown/cogdominium/CogdoInterior.py @@ -77,7 +77,7 @@ def load(self): self.townBattle = TownBattle.TownBattle('town-battle-done') self.townBattle.load() - for i in xrange(1, 3): + for i in range(1, 3): Suit.loadSuits(i) def unload(self): @@ -92,7 +92,7 @@ def unload(self): self.townBattle.cleanup() del self.townBattle - for i in xrange(1, 3): + for i in range(1, 3): Suit.unloadSuits(i) def setState(self, state, battleEvent = None): diff --git a/toontown/cogdominium/CogdoLevelGameBase.py b/toontown/cogdominium/CogdoLevelGameBase.py index a21aedf54..070fe43b8 100644 --- a/toontown/cogdominium/CogdoLevelGameBase.py +++ b/toontown/cogdominium/CogdoLevelGameBase.py @@ -12,7 +12,7 @@ def getLevelSpec(self): def startHandleEdits(self): fcs = [] Consts = self.getConsts() - for item in Consts.__dict__.itervalues(): + for item in list(Consts.__dict__.values()): if isinstance(item, EntityStateVarSet): for attribName in item._getAttributeNames(): handler = getattr(self, '_handle%sChanged' % attribName, None) diff --git a/toontown/cogdominium/CogdoMaze.py b/toontown/cogdominium/CogdoMaze.py index 2bccf156e..faa316104 100644 --- a/toontown/cogdominium/CogdoMaze.py +++ b/toontown/cogdominium/CogdoMaze.py @@ -100,17 +100,17 @@ def createCogdoMaze(self, flattenModel = True): def _gatherQuadrantData(self): self.openBarriers = [] - barrierItems = range(Globals.TotalBarriers) + barrierItems = list(range(Globals.TotalBarriers)) self._rng.shuffle(barrierItems) for i in barrierItems[0:len(barrierItems) - Globals.NumBarriers]: self.openBarriers.append(i) self.quadrantData = [] - quadrantKeys = self._cogdoMazeData.QuadrantCollisions.keys() + quadrantKeys = list(self._cogdoMazeData.QuadrantCollisions.keys()) self._rng.shuffle(quadrantKeys) i = 0 - for y in xrange(self.height): - for x in xrange(self.width): + for y in range(self.height): + for x in range(self.width): key = quadrantKeys[i] collTable = self._cogdoMazeData.QuadrantCollisions[key] angle = self._cogdoMazeData.QuadrantAngles[self._rng.randint(0, len(self._cogdoMazeData.QuadrantAngles) - 1)] @@ -121,9 +121,9 @@ def _gatherQuadrantData(self): def _generateBarrierData(self): data = [] - for y in xrange(self.height): + for y in range(self.height): data.append([]) - for x in xrange(self.width): + for x in range(self.width): if x == self.width - 1: ax = -1 else: @@ -204,12 +204,12 @@ def _generateMazeData(self): self._data['originX'] = int(self._data['width'] / 2) self._data['originY'] = int(self._data['height'] / 2) collisionTable = [] - horizontalWall = [ 1 for x in xrange(self._data['width']) ] + horizontalWall = [ 1 for x in range(self._data['width']) ] collisionTable.append(horizontalWall) - for i in xrange(0, len(self.quadrantData), self.width): - for y in xrange(self.quadrantSize): + for i in range(0, len(self.quadrantData), self.width): + for y in range(self.quadrantSize): row = [1] - for x in xrange(i, i + self.width): + for x in range(i, i + self.width): if x == 1 and y < self.quadrantSize / 2 - 2: newData = [] for j in self.quadrantData[x][1][y]: @@ -227,17 +227,17 @@ def _generateMazeData(self): collisionTable.append(horizontalWall[:]) barriers = Globals.MazeBarriers - for i in xrange(len(barriers)): + for i in range(len(barriers)): for coords in barriers[i]: collisionTable[coords[1]][coords[0]] = 0 y = self._data['originY'] - for x in xrange(len(collisionTable[y])): + for x in range(len(collisionTable[y])): if collisionTable[y][x] == 0: collisionTable[y][x] = 2 x = self._data['originX'] - for y in xrange(len(collisionTable)): + for y in range(len(collisionTable)): if collisionTable[y][x] == 0: collisionTable[y][x] = 2 @@ -254,8 +254,8 @@ def _loadAndBuildMazeModel(self, flatten = False): halfWidth = int(self.width / 2) halfHeight = int(self.height / 2) i = 0 - for y in xrange(self.height): - for x in xrange(self.width): + for y in range(self.height): + for x in range(self.width): ax = (x - halfWidth) * size ay = (y - halfHeight) * size extension = '' @@ -272,7 +272,7 @@ def _loadAndBuildMazeModel(self, flatten = False): quadrantHalfUnitSize = quadrantUnitSize * 0.5 barrierModel = CogdoUtil.loadMazeModel('grouping_blockerDivider').find('**/divider') y = 3 - for x in xrange(self.width): + for x in range(self.width): if x == (self.width - 1) / 2: continue ax = (x - halfWidth) * size @@ -284,7 +284,7 @@ def _loadAndBuildMazeModel(self, flatten = False): offset = self.cellWidth - 0.5 for x in (0, 3): - for y in xrange(self.height): + for y in range(self.height): ax = (x - halfWidth) * size - quadrantHalfUnitSize - frameActualSize + offset ay = (y - halfHeight) * size b = NodePath('barrier') diff --git a/toontown/cogdominium/CogdoMazeGame.py b/toontown/cogdominium/CogdoMazeGame.py index b136c2d78..5bdeaadb4 100644 --- a/toontown/cogdominium/CogdoMazeGame.py +++ b/toontown/cogdominium/CogdoMazeGame.py @@ -49,20 +49,20 @@ def load(self, cogdoMazeFactory, numSuits, bossCode): self.lastBalloonTimestamp = None difficulty = self.distGame.getDifficulty() serialNum = 0 - for i in xrange(numSuits[0]): + for i in range(numSuits[0]): suitRng = RandomNumGen(self.distGame.doId + serialNum * 10) suit = CogdoMazeBossSuit(serialNum, self.maze, suitRng, difficulty, startTile=suitSpawnSpot[0][i]) self.addSuit(suit) self.guiMgr.mazeMapGui.addSuit(suit.suit) serialNum += 1 - for i in xrange(numSuits[1]): + for i in range(numSuits[1]): suitRng = RandomNumGen(self.distGame.doId + serialNum * 10) suit = CogdoMazeFastMinionSuit(serialNum, self.maze, suitRng, difficulty, startTile=suitSpawnSpot[1][i]) self.addSuit(suit) serialNum += 1 - for i in xrange(numSuits[2]): + for i in range(numSuits[2]): suitRng = RandomNumGen(self.distGame.doId + serialNum * 10) suit = CogdoMazeSlowMinionSuit(serialNum, self.maze, suitRng, difficulty, startTile=suitSpawnSpot[2][i]) self.addSuit(suit) @@ -127,7 +127,7 @@ def unload(self): suit.destroy() del self.suits - for id in self.drops.keys(): + for id in list(self.drops.keys()): self.cleanupDrop(id) self.__stopUpdateTask() @@ -302,7 +302,7 @@ def __updateTask(self, task): def __updateGags(self): remove = [] - for i in xrange(len(self.gags)): + for i in range(len(self.gags)): balloon = self.gags[i] if balloon.isSingleton(): remove.append(i) @@ -353,7 +353,7 @@ def dropMemos(self, suit): start = math.radians(random.randint(0, 360)) step = math.radians(360.0 / numDrops) radius = 2.0 - for i in xrange(numDrops): + for i in range(numDrops): angle = start + i * step x = radius * math.cos(angle) + suit.suit.getX() y = radius * math.sin(angle) + suit.suit.getY() @@ -377,7 +377,7 @@ def handleBossShake(self, suit, strength): def randomDrop(self, centerTX, centerTY, radius): dropArray = [] - for i in xrange(1, distance): + for i in range(1, distance): dropArray.append(i) dropArray.append(-1 * i) @@ -401,7 +401,7 @@ def createDrop(self, x, y): return drop.getDropIval() def cleanupDrop(self, id): - if id in self.drops.keys(): + if id in list(self.drops.keys()): drop = self.drops[id] drop.destroy() del self.drops[id] @@ -470,7 +470,7 @@ def handleToonMeetsGag(self, playerId, gag): self.distGame.b_toonHitByGag(playerId) def toonHitByGag(self, toonId, hitToon, elapsedTime = 0.0): - if toonId not in self.toonId2Player.keys() or hitToon not in self.toonId2Player.keys(): + if toonId not in list(self.toonId2Player.keys()) or hitToon not in list(self.toonId2Player.keys()): return player = self.toonId2Player[hitToon] player.hitByGag() @@ -483,7 +483,7 @@ def handleLocalSuitMeetsGag(self, suitType, suitNum, gag): def suitHitByGag(self, toonId, suitType, suitNum, elapsedTime = 0.0): if suitType == Globals.SuitTypes.Boss: self.guiMgr.showBossHit(suitNum) - if suitNum in self.suitsById.keys(): + if suitNum in list(self.suitsById.keys()): suit = self.suitsById[suitNum] suit.hitByGag() @@ -568,13 +568,13 @@ def handleToonWentSad(self, toonId): for player in self.players: player.removeGag() - elif toonId in self.toonId2Player.keys(): + elif toonId in list(self.toonId2Player.keys()): player = self.toonId2Player[toonId] player.removeGag() def handleToonDisconnected(self, toonId): if toonId == self.localPlayer.toon.doId: pass - elif toonId in self.toonId2Player.keys(): + elif toonId in list(self.toonId2Player.keys()): player = self.toonId2Player[toonId] self._removePlayer(player) diff --git a/toontown/cogdominium/CogdoMazeGameGuis.py b/toontown/cogdominium/CogdoMazeGameGuis.py index 2d798189c..eb5f0e608 100644 --- a/toontown/cogdominium/CogdoMazeGameGuis.py +++ b/toontown/cogdominium/CogdoMazeGameGuis.py @@ -22,7 +22,7 @@ def __init__(self, mazeCollTable): self.setScale(Globals.MapGuiScale) def destroy(self): - for marker in self._suit2marker.values(): + for marker in list(self._suit2marker.values()): marker.removeNode() del self._suit2marker @@ -187,7 +187,7 @@ def _initModel(self): self._openDoor.stash() spacingX = codeFrameWidth + codeFrameGap startX = -0.5 * ((self._codeLength - 1) * spacingX - codeFrameGap) - for i in xrange(self._codeLength): + for i in range(self._codeLength): marker = CogdoMazeBossCodeFrame(i, self._code[i], bossCard) marker.reparentTo(self) marker.setPos(bossCard, startX + spacingX * i, 0, 0) diff --git a/toontown/cogdominium/CogdoMazeSuits.py b/toontown/cogdominium/CogdoMazeSuits.py index 7790a929a..748b36a3d 100644 --- a/toontown/cogdominium/CogdoMazeSuits.py +++ b/toontown/cogdominium/CogdoMazeSuits.py @@ -239,8 +239,8 @@ def destroy(self): def pickRandomValidSpot(self, r = 5): validSpots = [] - for x in xrange(self.TX - r, self.TX + r): - for y in xrange(self.TY - r, self.TY + r): + for x in range(self.TX - r, self.TX + r): + for y in range(self.TY - r, self.TY + r): if self.maze.isWalkable(x, y): validSpots.append([x, y]) diff --git a/toontown/cogdominium/CogdoUtil.py b/toontown/cogdominium/CogdoUtil.py index 24eebd4ee..4f6c47d88 100644 --- a/toontown/cogdominium/CogdoUtil.py +++ b/toontown/cogdominium/CogdoUtil.py @@ -114,9 +114,9 @@ def rotateTable(table, angle): t = [] width = len(table[0]) height = len(table) - for j in xrange(width): + for j in range(width): row = [] - for i in xrange(height): + for i in range(height): row.append(table[height - 1 - i][j]) t.append(row) @@ -131,9 +131,9 @@ def rotateTable(table, angle): t = [] width = len(table[0]) height = len(table) - for j in xrange(width): + for j in range(width): row = [] - for i in xrange(height): + for i in range(height): row.append(table[i][width - 1 - j]) t.append(row) diff --git a/toontown/cogdominium/DistCogdoCrane.py b/toontown/cogdominium/DistCogdoCrane.py index 2f8a8c283..e956a52b4 100644 --- a/toontown/cogdominium/DistCogdoCrane.py +++ b/toontown/cogdominium/DistCogdoCrane.py @@ -232,7 +232,7 @@ def __deactivatePhysics(self): self.physicsActivated = 0 def __straightenCable(self): - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): an, anp, cnp = self.activeLinks[linkNum] an.getPhysicsObject().setVelocity(0, 0, 0) z = float(linkNum + 1) / float(self.numLinks) * self.cableLength @@ -255,7 +255,7 @@ def setupCable(self): self.links = [] self.links.append((self.topLink, Point3(0, 0, 0))) anchor = self.topLink - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): anchor = self.__makeLink(anchor, linkNum) self.collisions.stash() @@ -550,7 +550,7 @@ def __deactivateSniffer(self): def startFlicker(self): self.magnetSoundInterval.start() self.lightning = [] - for i in xrange(4): + for i in range(4): t = float(i) / 3.0 - 0.5 l = self.craneGame.lightning.copyTo(self.gripper) l.setScale(random.choice([1, -1]), 1, 5) @@ -679,7 +679,7 @@ def reloadPosition(self): self.armSmoother.setPos(self.crane.getPos()) self.armSmoother.setHpr(self.arm.getHpr()) self.armSmoother.setPhonyTimestamp() - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): smoother = self.linkSmoothers[linkNum] an, anp, cnp = self.activeLinks[linkNum] smoother.clearPositions(0) @@ -688,7 +688,7 @@ def reloadPosition(self): def doSmoothTask(self, task): self.armSmoother.computeAndApplySmoothPosHpr(self.crane, self.arm) - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): smoother = self.linkSmoothers[linkNum] anp = self.activeLinks[linkNum][1] smoother.computeAndApplySmoothPos(anp) @@ -715,7 +715,7 @@ def forceToTruePosition(self): self.armSmoother.applySmoothPos(self.crane) self.armSmoother.applySmoothHpr(self.arm) self.armSmoother.clearPositions(1) - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): smoother = self.linkSmoothers[linkNum] an, anp, cnp = self.activeLinks[linkNum] if smoother.getLatestPosition(): @@ -731,7 +731,7 @@ def setCablePos(self, changeSeq, y, h, links, timestamp): self.armSmoother.setH(h) self.armSmoother.setTimestamp(local) self.armSmoother.markPosition() - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): smoother = self.linkSmoothers[linkNum] lp = links[linkNum] smoother.setPos(*lp) @@ -744,7 +744,7 @@ def setCablePos(self, changeSeq, y, h, links, timestamp): def d_sendCablePos(self): timestamp = globalClockDelta.getFrameNetworkTime() links = [] - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): an, anp, cnp = self.activeLinks[linkNum] p = anp.getPos() links.append((p[0], p[1], p[2])) diff --git a/toontown/cogdominium/DistCogdoCraneGame.py b/toontown/cogdominium/DistCogdoCraneGame.py index 9a151df39..73de29de2 100644 --- a/toontown/cogdominium/DistCogdoCraneGame.py +++ b/toontown/cogdominium/DistCogdoCraneGame.py @@ -101,7 +101,7 @@ def replaceCollisionPolysWithPlanes(self, model): self.notify.warning('Not a collision node: %s' % repr(cnp)) break newCollideMask = newCollideMask | cn.getIntoCollideMask() - for i in xrange(cn.getNumSolids()): + for i in range(cn.getNumSolids()): solid = cn.getSolid(i) if isinstance(solid, PM.CollisionPolygon): plane = PM.Plane(solid.getPlane()) @@ -194,17 +194,17 @@ def _handleGravityChanged(self, gravity): self._gravityForceNode.addForce(self._gravityForce) def _handleEmptyFrictionCoefChanged(self, coef): - for crane in self.cranes.itervalues(): + for crane in list(self.cranes.values()): crane._handleEmptyFrictionCoefChanged(coef) def _handleRopeLinkMassChanged(self, mass): - for crane in self.cranes.itervalues(): + for crane in list(self.cranes.values()): crane._handleRopeLinkMassChanged(mass) def _handleMagnetMassChanged(self, mass): - for crane in self.cranes.itervalues(): + for crane in list(self.cranes.values()): crane._handleMagnetMassChanged(mass) def _handleMoneyBagGrabHeightChanged(self, height): - for moneyBag in self.moneyBags.itervalues(): + for moneyBag in list(self.moneyBags.values()): moneyBag._handleMoneyBagGrabHeightChanged(height) \ No newline at end of file diff --git a/toontown/cogdominium/DistCogdoCraneGameAI.py b/toontown/cogdominium/DistCogdoCraneGameAI.py index b75fa1285..318ba6148 100644 --- a/toontown/cogdominium/DistCogdoCraneGameAI.py +++ b/toontown/cogdominium/DistCogdoCraneGameAI.py @@ -25,7 +25,7 @@ def announceGenerate(self): self.finishEvent = self.uniqueName('CogdoCraneGameDone') self.gameOverEvent = self.uniqueName('CogdoCraneGameLose') - for index in xrange(4): + for index in range(4): crane = DistCogdoCraneAI(self.air, self.doId) crane.setIndex(index) crane.generateWithRequired(self.zoneId) diff --git a/toontown/cogdominium/DistCogdoCraneObject.py b/toontown/cogdominium/DistCogdoCraneObject.py index 809f4efaa..721dffac1 100644 --- a/toontown/cogdominium/DistCogdoCraneObject.py +++ b/toontown/cogdominium/DistCogdoCraneObject.py @@ -126,12 +126,12 @@ def __hitBoss(self, entry): vel.normalize() impact = vel[1] if impact >= self.getMinImpact(): - print 'hit! %s' % impact + print(('hit! %s' % impact)) self.hitBossSoundInterval.start() self.doHitBoss(impact) else: self.touchedBossSoundInterval.start() - print '--not hard enough: %s' % impact + print(('--not hard enough: %s' % impact)) def doHitBoss(self, impact): self.d_hitBoss(impact) @@ -141,7 +141,7 @@ def __hitDropPlane(self, entry): self.fellOut() def fellOut(self): - raise StandardError, 'fellOut unimplented' + raise Exception('fellOut unimplented') def getMinImpact(self): return 0 @@ -202,7 +202,7 @@ def d_hitBoss(self, impact): def defaultFilter(self, request, args): if self.craneGame == None: - raise FSM.RequestDenied, request + raise FSM.RequestDenied(request) return FSM.FSM.defaultFilter(self, request, args) def enterOff(self): diff --git a/toontown/cogdominium/DistCogdoMazeGame.py b/toontown/cogdominium/DistCogdoMazeGame.py index 42f2011f1..d5bb7874b 100644 --- a/toontown/cogdominium/DistCogdoMazeGame.py +++ b/toontown/cogdominium/DistCogdoMazeGame.py @@ -43,7 +43,7 @@ def enterLoaded(self): bossCode = None if self._numSuits[0] > 0: bossCode = '' - for u in xrange(self._numSuits[0]): + for u in range(self._numSuits[0]): bossCode += '%X' % self.randomNumGen.randint(0, 15) self.game.load(mazeFactory, self._numSuits, bossCode) diff --git a/toontown/cogdominium/DistCogdoMazeGameAI.py b/toontown/cogdominium/DistCogdoMazeGameAI.py index d7e3271eb..d5623b16b 100644 --- a/toontown/cogdominium/DistCogdoMazeGameAI.py +++ b/toontown/cogdominium/DistCogdoMazeGameAI.py @@ -104,7 +104,7 @@ def requestGag(self, coolerIndex): def hitSuitAI(self, suitType, suitNum): cogKey = None - for cogNum in self.suitTypes[suitType].keys(): + for cogNum in list(self.suitTypes[suitType].keys()): if cogNum == suitNum: cogKey = cogNum break diff --git a/toontown/cogdominium/DistributedCogdoInterior.py b/toontown/cogdominium/DistributedCogdoInterior.py index 6149ef751..3296f222a 100644 --- a/toontown/cogdominium/DistributedCogdoInterior.py +++ b/toontown/cogdominium/DistributedCogdoInterior.py @@ -168,7 +168,7 @@ def __makeShopOwnerNpc(self): def setElevatorLights(self, elevatorModel): npc = elevatorModel.findAllMatches('**/floor_light_?;+s') - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): np = npc.getPath(i) np.setDepthOffset(120) floor = int(np.getName()[-1:]) - 1 @@ -283,7 +283,7 @@ def __finishInterval(self, name): interval.finish() def __cleanupIntervals(self): - for interval in self.activeIntervals.values(): + for interval in list(self.activeIntervals.values()): interval.finish() self.activeIntervals = {} @@ -361,7 +361,7 @@ def setSuits(self, suitIds, reserveIds, values): self.notify.warning('setSuits() - no suit: %d' % suitId) self.reserveSuits = [] - for index in xrange(len(reserveIds)): + for index in range(len(reserveIds)): suitId = reserveIds[index] if suitId in self.cr.doId2do: suit = self.cr.doId2do[suitId] @@ -453,7 +453,7 @@ def __playElevator(self, ts, name, callback): self.cageDoor.wrtReparentTo(self.cage) if self.FOType: paintingModelName = PAINTING_DICT.get(self.FOType) - for i in xrange(4): + for i in range(4): paintingModel = loader.loadModel('phase_5/models/cogdominium/%s' % paintingModelName) loc = self.floorModel.find('**/loc_painting%d' % (i + 1)) paintingModel.reparentTo(loc) @@ -782,13 +782,13 @@ def displayBadges(self): else: self.notify.warning('Invalid floor number for display badges.') - for player in xrange(len(self.toons)): + for player in range(len(self.toons)): goldBadge = loader.loadModel('phase_5/models/cogdominium/tt_m_ara_crg_goldTrophy') goldBadge.setScale(1.2) goldNode = render.find('**/gold_0' + str(player + 1)) goldBadge.reparentTo(goldNode) - for floor in xrange(numFloors): + for floor in range(numFloors): silverBadge = loader.loadModel('phase_5/models/cogdominium/tt_m_ara_crg_silverTrophy.bam') silverBadge.setScale(1.2) silverNode = render.find('**/silver_0' + str(floor * 4 + (player + 1))) diff --git a/toontown/cogdominium/DistributedCogdoInteriorAI.py b/toontown/cogdominium/DistributedCogdoInteriorAI.py index e0f6a190d..26efa9ec3 100644 --- a/toontown/cogdominium/DistributedCogdoInteriorAI.py +++ b/toontown/cogdominium/DistributedCogdoInteriorAI.py @@ -7,10 +7,10 @@ from toontown.building.ElevatorConstants import * from toontown.toonbase.ToontownGlobals import * from toontown.toonbase.ToontownBattleGlobals import * -import DistCogdoMazeGameAI, CogdoMazeGameGlobals, DistributedCogdoElevatorIntAI -import DistCogdoFlyingGameAI, DistributedCogdoBarrelAI -from DistributedCogdoBattleBldgAI import DistributedCogdoBattleBldgAI -from SuitPlannerCogdoInteriorAI import SuitPlannerCogdoInteriorAI +from . import DistCogdoMazeGameAI, CogdoMazeGameGlobals, DistributedCogdoElevatorIntAI +from . import DistCogdoFlyingGameAI, DistributedCogdoBarrelAI +from .DistributedCogdoBattleBldgAI import DistributedCogdoBattleBldgAI +from .SuitPlannerCogdoInteriorAI import SuitPlannerCogdoInteriorAI from toontown.cogdominium import CogdoBarrelRoomConsts from toontown.toon import InventoryBase from toontown.battle import BattleExperienceAI @@ -37,7 +37,7 @@ class DistributedCogdoInteriorAI(DistributedObjectAI, FSM.FSM): def __init__(self, air, exterior): DistributedObjectAI.__init__(self, air) FSM.FSM.__init__(self, 'CogdoInteriorAIFSM') - self.toons = filter(None, exterior.elevator.seats[:]) + self.toons = [_f for _f in exterior.elevator.seats[:] if _f] self.responses = {} self.bldgDoId = exterior.doId self.numFloors = NUM_FLOORS_DICT[exterior.track] @@ -90,7 +90,7 @@ def __init__(self, air, exterior): self.maxToonLevels = 77 def __generateSOS(self, difficulty): - g = lambda: random.choice(NPCToons.FOnpcFriends.keys()) + g = lambda: random.choice(list(NPCToons.FOnpcFriends.keys())) v = g() getStars = lambda x: NPCToons.getNPCTrackLevelHpRarity(x)[-1] maxStars = min(2, int(math.ceil(difficulty / 5.))) @@ -191,7 +191,7 @@ def setAvatarJoined(self): def addToon(self, avId): if not avId in self.toons: self.toons.append(avId) - if self.air.doId2do.has_key(avId): + if avId in self.air.doId2do: event = self.air.getAvatarExitEvent(avId) self.accept(event, self.__handleUnexpectedExit, [avId]) @@ -244,7 +244,7 @@ def barrelIntroDone(self): if not self.air: return self.b_setState('CollectBarrels') - for i in xrange(len(CogdoBarrelRoomConsts.BarrelProps)): + for i in range(len(CogdoBarrelRoomConsts.BarrelProps)): barrel = DistributedCogdoBarrelAI.DistributedCogdoBarrelAI(self.air, i) barrel.generateWithRequired(self.zoneId) self.barrels.append(barrel) @@ -283,7 +283,7 @@ def handleAllAboard(self, seats): for toon in self.toons: if toon not in seats: self.removeToon(toon) - self.toons = filter(None, seats) + self.toons = [_f for _f in seats if _f] self.d_setToons() self.request('Elevator') @@ -484,8 +484,8 @@ def giveCogSummonReward(self, toon, prefDeptIndex, prefSummonType): foundOne = True break - possibleCogLevel = range(SuitDNA.suitsPerDept) - possibleDeptIndex = range(len(SuitDNA.suitDepts)-1) + possibleCogLevel = list(range(SuitDNA.suitsPerDept)) + possibleDeptIndex = list(range(len(SuitDNA.suitDepts)-1)) possibleSummonType = ['single'] typeWeights = ['single'] * 70 if not foundOne: diff --git a/toontown/cogdominium/SuitPlannerCogdoInteriorAI.py b/toontown/cogdominium/SuitPlannerCogdoInteriorAI.py index f61847383..eae8b7455 100644 --- a/toontown/cogdominium/SuitPlannerCogdoInteriorAI.py +++ b/toontown/cogdominium/SuitPlannerCogdoInteriorAI.py @@ -34,7 +34,7 @@ def __init__(self, layout, difficulty, track, zoneId, numFloors = 1): self.respectInvasions = 1 - if isinstance(difficulty, types.StringType): + if isinstance(difficulty, bytes): self.notify.warning('difficulty is a string!') difficulty = int(difficulty) @@ -168,9 +168,9 @@ def myPrint(self): actives = currInfo['activeSuits'] reserves = currInfo['reserveSuits'] for idx, currActive in enumerate(actives): - type, track, level, revives = map(lambda x: currActive[x], ('type', 'track', 'level', 'revives')) + type, track, level, revives = [currActive[x] for x in ('type', 'track', 'level', 'revives')] for idx, currReserve in enumerate(reserves): - type, track, level, revives, res = map(lambda x: currReserve[x], ('type', 'track', 'level', 'revives', 'joinChance')) + type, track, level, revives, res = [currReserve[x] for x in ('type', 'track', 'level', 'revives', 'joinChance')] def genFloorSuits(self, floor): suitHandles = {} diff --git a/toontown/coghq/BoardbotCogHQLoader.py b/toontown/coghq/BoardbotCogHQLoader.py index 4ff3271e7..ef5bf6769 100644 --- a/toontown/coghq/BoardbotCogHQLoader.py +++ b/toontown/coghq/BoardbotCogHQLoader.py @@ -1,13 +1,13 @@ from direct.directnotify import DirectNotifyGlobal from direct.fsm import StateData -import CogHQLoader +from . import CogHQLoader from toontown.toonbase import ToontownGlobals from direct.gui import DirectGui from toontown.toonbase import TTLocalizer from toontown.toon import Toon from direct.fsm import State -import BoardbotHQExterior -import BoardbotOfficeExterior +from . import BoardbotHQExterior +from . import BoardbotOfficeExterior from toontown.coghq.boardbothq import BoardOfficeInterior from toontown.coghq import CashbotHQBossBattle diff --git a/toontown/coghq/BoardbotHQExterior.py b/toontown/coghq/BoardbotHQExterior.py index 9ae614d34..18fb99c71 100644 --- a/toontown/coghq/BoardbotHQExterior.py +++ b/toontown/coghq/BoardbotHQExterior.py @@ -22,16 +22,16 @@ def enter(self, requestStatus): # Collect all of the vis group zone IDs: self.zoneVisDict = {} - for i in xrange(dnaStore.getNumDNAVisGroupsAI()): + for i in range(dnaStore.getNumDNAVisGroupsAI()): groupFullName = dnaStore.getDNAVisGroupName(i) visGroup = dnaStore.getDNAVisGroupAI(i) visZoneId = int(base.cr.hoodMgr.extractGroupName(groupFullName)) visZoneId = ZoneUtil.getTrueZoneId(visZoneId, self.zoneId) visibles = [] - for i in xrange(visGroup.getNumVisibles()): + for i in range(visGroup.getNumVisibles()): visibles.append(int(visGroup.visibles[i])) visibles.append(ZoneUtil.getBranchZone(visZoneId)) self.zoneVisDict[visZoneId] = visibles # Next, we want interest in all vis groups due to this being a Cog HQ: - base.cr.sendSetZoneMsg(self.zoneId, self.zoneVisDict.values()[0]) + base.cr.sendSetZoneMsg(self.zoneId, list(self.zoneVisDict.values())[0]) diff --git a/toontown/coghq/BossbotHQExterior.py b/toontown/coghq/BossbotHQExterior.py index 1cf022619..13cac2319 100644 --- a/toontown/coghq/BossbotHQExterior.py +++ b/toontown/coghq/BossbotHQExterior.py @@ -69,16 +69,16 @@ def enter(self, requestStatus): # Collect all of the vis group zone IDs: self.zoneVisDict = {} - for i in xrange(dnaStore.getNumDNAVisGroupsAI()): + for i in range(dnaStore.getNumDNAVisGroupsAI()): groupFullName = dnaStore.getDNAVisGroupName(i) visGroup = dnaStore.getDNAVisGroupAI(i) visZoneId = int(base.cr.hoodMgr.extractGroupName(groupFullName)) visZoneId = ZoneUtil.getTrueZoneId(visZoneId, self.zoneId) visibles = [] - for i in xrange(visGroup.getNumVisibles()): + for i in range(visGroup.getNumVisibles()): visibles.append(int(visGroup.visibles[i])) visibles.append(ZoneUtil.getBranchZone(visZoneId)) self.zoneVisDict[visZoneId] = visibles # Next, we want interest in all vis groups due to this being a Cog HQ: - base.cr.sendSetZoneMsg(self.zoneId, self.zoneVisDict.values()[0]) + base.cr.sendSetZoneMsg(self.zoneId, list(self.zoneVisDict.values())[0]) diff --git a/toontown/coghq/CashbotHQExterior.py b/toontown/coghq/CashbotHQExterior.py index 655edb2f8..19a8ea8b0 100644 --- a/toontown/coghq/CashbotHQExterior.py +++ b/toontown/coghq/CashbotHQExterior.py @@ -64,19 +64,19 @@ def enter(self, requestStatus): # Collect all of the vis group zone IDs: self.zoneVisDict = {} - for i in xrange(dnaStore.getNumDNAVisGroupsAI()): + for i in range(dnaStore.getNumDNAVisGroupsAI()): groupFullName = dnaStore.getDNAVisGroupName(i) visGroup = dnaStore.getDNAVisGroupAI(i) visZoneId = int(base.cr.hoodMgr.extractGroupName(groupFullName)) visZoneId = ZoneUtil.getTrueZoneId(visZoneId, self.zoneId) visibles = [] - for i in xrange(visGroup.getNumVisibles()): + for i in range(visGroup.getNumVisibles()): visibles.append(int(visGroup.visibles[i])) visibles.append(ZoneUtil.getBranchZone(visZoneId)) self.zoneVisDict[visZoneId] = visibles # Next, we want interest in all vis groups due to this being a Cog HQ: - base.cr.sendSetZoneMsg(self.zoneId, self.zoneVisDict.values()[0]) + base.cr.sendSetZoneMsg(self.zoneId, list(self.zoneVisDict.values())[0]) def exit(self): CogHQExterior.CogHQExterior.exit(self) diff --git a/toontown/coghq/CogDisguiseGlobals.py b/toontown/coghq/CogDisguiseGlobals.py index 003e3c23f..f06f8c6c3 100644 --- a/toontown/coghq/CogDisguiseGlobals.py +++ b/toontown/coghq/CogDisguiseGlobals.py @@ -255,7 +255,7 @@ def getTotalMerits(toon, index): def getTotalParts(bitString, shiftWidth = 40): sum = 0 - for shift in xrange(0, shiftWidth): + for shift in range(0, shiftWidth): sum = sum + (bitString >> shift & 1) return sum @@ -274,7 +274,7 @@ def asBitstring(number): shift += 1 str = '' - for i in xrange(0, len(array)): + for i in range(0, len(array)): str = str + array[i] return str @@ -282,7 +282,7 @@ def asBitstring(number): def asNumber(bitstring): num = 0 - for i in xrange(0, len(bitstring)): + for i in range(0, len(bitstring)): if bitstring[i] == '1': num += pow(2, len(bitstring) - 1 - i) @@ -290,6 +290,6 @@ def asNumber(bitstring): def dept2deptIndex(dept): - if type(dept) == types.StringType: + if type(dept) == bytes: dept = SuitDNA.suitDepts.index(dept) return dept \ No newline at end of file diff --git a/toontown/coghq/CogHQBossBattle.py b/toontown/coghq/CogHQBossBattle.py index a54969723..cdeeeae37 100644 --- a/toontown/coghq/CogHQBossBattle.py +++ b/toontown/coghq/CogHQBossBattle.py @@ -88,7 +88,7 @@ def load(self): BattlePlace.BattlePlace.load(self) self.parentFSM.getStateNamed('cogHQBossBattle').addChild(self.fsm) self.townBattle = self.loader.townBattle - for i in xrange(1, 3): + for i in range(1, 3): Suit.loadSuits(i) def unload(self): @@ -97,7 +97,7 @@ def unload(self): del self.parentFSM del self.fsm self.ignoreAll() - for i in xrange(1, 3): + for i in range(1, 3): Suit.unloadSuits(i) def getTaskZoneId(self): diff --git a/toontown/coghq/ConveyorBelt.py b/toontown/coghq/ConveyorBelt.py index 949b22010..84d2bd972 100644 --- a/toontown/coghq/ConveyorBelt.py +++ b/toontown/coghq/ConveyorBelt.py @@ -21,7 +21,7 @@ def initBelt(self): self.numTreads = int(self.length / self.treadLength) + 3 self.beltNode = self.attachNewNode('belt') self.treads = [] - for i in xrange(self.numTreads): + for i in range(self.numTreads): mp = MovingPlatform.MovingPlatform() mp.parentingNode = render.attachNewNode('parentTarget') mp.setupCopyModel('conv%s-%s' % (self.getParentToken(), i), treadModel, self.floorName, parentingNode=mp.parentingNode) @@ -47,7 +47,7 @@ def start(self): treadsIval = Parallel(name='treads') treadPeriod = self.treadLength / abs(self.speed) startY = -self.treadLength - for i in xrange(self.numTreads): + for i in range(self.numTreads): periodsToEnd = self.numTreads - i periodsFromStart = self.numTreads - periodsToEnd ival = Sequence() diff --git a/toontown/coghq/CountryClubLayout.py b/toontown/coghq/CountryClubLayout.py index f47812af4..75fd70bf4 100644 --- a/toontown/coghq/CountryClubLayout.py +++ b/toontown/coghq/CountryClubLayout.py @@ -6,33 +6,33 @@ from toontown.toonbase.ToonPythonUtil import normalDistrib, lerp def printAllBossbotInfo(): - print 'roomId: roomName' - for roomId, roomName in CountryClubRoomSpecs.BossbotCountryClubRoomId2RoomName.items(): - print '%s: %s' % (roomId, roomName) + print('roomId: roomName') + for roomId, roomName in list(CountryClubRoomSpecs.BossbotCountryClubRoomId2RoomName.items()): + print(('%s: %s' % (roomId, roomName))) - print '\nroomId: numBattles' - for roomId, numBattles in CountryClubRoomSpecs.roomId2numBattles.items(): - print '%s: %s' % (roomId, numBattles) + print('\nroomId: numBattles') + for roomId, numBattles in list(CountryClubRoomSpecs.roomId2numBattles.items()): + print(('%s: %s' % (roomId, numBattles))) - print '\ncountryClubId floor roomIds' + print('\ncountryClubId floor roomIds') printCountryClubRoomIds() - print '\ncountryClubId floor numRooms' + print('\ncountryClubId floor numRooms') printNumRooms() - print '\ncountryClubId floor numForcedBattles' + print('\ncountryClubId floor numForcedBattles') printNumBattles() def iterateBossbotCountryClubs(func): from toontown.toonbase import ToontownGlobals for countryClubId in [ToontownGlobals.BossbotCountryClubIntA, ToontownGlobals.BossbotCountryClubIntB, ToontownGlobals.BossbotCountryClubIntC]: - for floorNum in xrange(ToontownGlobals.CountryClubNumFloors[countryClubId]): + for floorNum in range(ToontownGlobals.CountryClubNumFloors[countryClubId]): func(CountryClubLayout(countryClubId, floorNum)) def printCountryClubInfo(): def func(ml): - print ml + print(ml) iterateBossbotCountryClubs(func) @@ -40,7 +40,7 @@ def func(ml): def printCountryClubRoomIds(): def func(ml): - print ml.getCountryClubId(), ml.getFloorNum(), ml.getRoomIds() + print((ml.getCountryClubId(), ml.getFloorNum(), ml.getRoomIds())) iterateBossbotCountryClubs(func) @@ -48,7 +48,7 @@ def func(ml): def printCountryClubRoomNames(): def func(ml): - print ml.getCountryClubId(), ml.getFloorNum(), ml.getRoomNames() + print((ml.getCountryClubId(), ml.getFloorNum(), ml.getRoomNames())) iterateBossbotCountryClubs(func) @@ -56,7 +56,7 @@ def func(ml): def printNumRooms(): def func(ml): - print ml.getCountryClubId(), ml.getFloorNum(), ml.getNumRooms() + print((ml.getCountryClubId(), ml.getFloorNum(), ml.getNumRooms())) iterateBossbotCountryClubs(func) @@ -64,7 +64,7 @@ def func(ml): def printNumBattles(): def func(ml): - print ml.getCountryClubId(), ml.getFloorNum(), ml.getNumBattles() + print((ml.getCountryClubId(), ml.getFloorNum(), ml.getNumBattles())) iterateBossbotCountryClubs(func) @@ -151,7 +151,7 @@ def __init__(self, countryClubId, floorNum, layoutIndex): self.roomIds = countryClubLayouts[layoutIndex][floorNum] hallwayRng = self.getRng() connectorRoomNames = CountryClubRoomSpecs.BossbotCountryClubConnectorRooms - for i in xrange(self.numHallways): + for i in range(self.numHallways): self.hallways.append(hallwayRng.choice(connectorRoomNames)) def _genFloorLayout(self): @@ -171,7 +171,7 @@ def _genFloorLayout(self): numBattles2middleRoomIds = invertDictLossless(CountryClubRoomSpecs.middleRoomId2numBattles) allBattleRooms = [] - for num, roomIds in numBattles2middleRoomIds.items(): + for num, roomIds in list(numBattles2middleRoomIds.items()): if num > 0: allBattleRooms.extend(roomIds) while 1: @@ -189,7 +189,7 @@ def _genFloorLayout(self): if middleRoomsLeft > 0: actionRoomIds = numBattles2middleRoomIds[0] - for i in xrange(middleRoomsLeft): + for i in range(middleRoomsLeft): roomId = rng.choice(actionRoomIds) actionRoomIds.remove(roomId) middleRoomIds.append(roomId) @@ -199,7 +199,7 @@ def _genFloorLayout(self): roomIds.append(rng.choice(startingRoomIDs)) middleRoomIds.sort() - print 'middleRoomIds=%s' % middleRoomIds + print(('middleRoomIds=%s' % middleRoomIds)) roomIds.extend(middleRoomIds) roomIds.append(finalRoomId) diff --git a/toontown/coghq/CountryClubManagerAI.py b/toontown/coghq/CountryClubManagerAI.py index 22c9a0b9c..ed5074e5f 100644 --- a/toontown/coghq/CountryClubManagerAI.py +++ b/toontown/coghq/CountryClubManagerAI.py @@ -40,7 +40,7 @@ def createCountryClub(self, countryClubId, players): for avId in players: if bboard.has('countryClubRoom-%s' % avId): roomId = bboard.get('countryClubRoom-%s' % avId) - for i in xrange(numFloors): + for i in range(numFloors): layout = CountryClubLayout.CountryClubLayout(countryClubId, i) if roomId in layout.getRoomIds(): floor = i diff --git a/toontown/coghq/CountryClubRoomBase.py b/toontown/coghq/CountryClubRoomBase.py index 764c0d79e..ff40c3271 100644 --- a/toontown/coghq/CountryClubRoomBase.py +++ b/toontown/coghq/CountryClubRoomBase.py @@ -18,7 +18,7 @@ def getCogTrack(self): if __dev__: def getCountryClubEntityTypeReg(self): - import FactoryEntityTypes + from . import FactoryEntityTypes from otp.level import EntityTypeRegistry typeReg = EntityTypeRegistry.EntityTypeRegistry(FactoryEntityTypes) return typeReg diff --git a/toontown/coghq/CountryClubRoomSpecs.py b/toontown/coghq/CountryClubRoomSpecs.py index e8e9f4f43..e5caaf9b7 100644 --- a/toontown/coghq/CountryClubRoomSpecs.py +++ b/toontown/coghq/CountryClubRoomSpecs.py @@ -57,7 +57,7 @@ def getNumBattles(roomId): BossbotCountryClubFinalRoomIDs = (18,) BossbotCountryClubConnectorRooms = ('phase_12/models/bossbotHQ/Connector_Tunnel_A', 'phase_12/models/bossbotHQ/Connector_Tunnel_B') CashbotMintSpecModules = {} -for roomName, roomId in BossbotCountryClubRoomName2RoomId.items(): +for roomName, roomId in list(BossbotCountryClubRoomName2RoomId.items()): CashbotMintSpecModules[roomId] = locals()[roomName] CogSpecModules = {'BossbotCountryClubEntrance_Action00': BossbotCountryClubEntrance_Action00_Cogs, @@ -68,7 +68,7 @@ def getNumBattles(roomId): 'BossbotCountryClubKartRoom_Battle00': BossbotCountryClubKartRoom_Battle00_Cogs, 'BossbotCountryClubPresidentRoom_Battle00': BossbotCountryClubPresidentRoom_Battle00_Cogs} roomId2numBattles = {} -for roomName, roomId in BossbotCountryClubRoomName2RoomId.items(): +for roomName, roomId in list(BossbotCountryClubRoomName2RoomId.items()): if roomName not in CogSpecModules: roomId2numBattles[roomId] = 0 else: diff --git a/toontown/coghq/DinerStatusIndicator.py b/toontown/coghq/DinerStatusIndicator.py index 15ff9c316..3e578f4cd 100644 --- a/toontown/coghq/DinerStatusIndicator.py +++ b/toontown/coghq/DinerStatusIndicator.py @@ -105,7 +105,7 @@ def createMeterInterval(self, icon, meter, time): flashDuration = 10 if time > flashDuration: flashingTrack.append(Wait(time - flashDuration)) - for i in xrange(10): + for i in range(10): flashingTrack.append(Parallel(LerpColorScaleInterval(icon, 0.5, VBase4(1, 0, 0, 1)), icon.scaleInterval(0.5, 1.25))) flashingTrack.append(Parallel(LerpColorScaleInterval(icon, 0.5, VBase4(1, 1, 1, 1)), icon.scaleInterval(0.5, 1))) diff --git a/toontown/coghq/DistributedBanquetTable.py b/toontown/coghq/DistributedBanquetTable.py index ebcc34ce6..60fc57687 100644 --- a/toontown/coghq/DistributedBanquetTable.py +++ b/toontown/coghq/DistributedBanquetTable.py @@ -101,11 +101,11 @@ def delete(self): DistributedObject.DistributedObject.delete(self) self.boss = None self.ignoreAll() - for indicator in self.dinerStatusIndicators.values(): + for indicator in list(self.dinerStatusIndicators.values()): indicator.delete() self.dinerStatusIndicators = {} - for diner in self.diners.values(): + for diner in list(self.diners.values()): diner.delete() self.diners = {} @@ -153,7 +153,7 @@ def setNumDiners(self, numDiners): def setDinerInfo(self, hungryDurations, eatingDurations, dinerLevels, dinerDept): self.dinerInfo = {} - for i in xrange(len(hungryDurations)): + for i in range(len(hungryDurations)): hungryDur = hungryDurations[i] eatingDur = eatingDurations[i] dinerLevel = dinerLevels[i] @@ -177,7 +177,7 @@ def loadAssets(self): self.pitcherMoveSfx = base.loader.loadSfx('phase_4/audio/sfx/MG_cannon_adjust.ogg') def setupDiners(self): - for i in xrange(self.numDiners): + for i in range(self.numDiners): newDiner = self.createDiner(i) self.diners[i] = newDiner self.dinerStatus[i] = self.HUNGRY @@ -227,7 +227,7 @@ def createDiner(self, i): return diner def setupChairCols(self): - for i in xrange(self.numDiners): + for i in range(self.numDiners): chairCol = self.tableGroup.find('**/collision_chair_%d' % (i + 1)) colName = 'ChairCol-%d-%d' % (self.index, i) chairCol.setTag('chairIndex', str(i)) @@ -279,7 +279,7 @@ def setDinerStatus(self, chairIndex, status): def removeFoodModel(self, chairIndex): serviceLoc = self.serviceLocs.get(chairIndex) if serviceLoc: - for i in xrange(serviceLoc.getNumChildren()): + for i in range(serviceLoc.getNumChildren()): serviceLoc.getChild(0).removeNode() def changeDinerToEating(self, chairIndex): @@ -390,37 +390,37 @@ def changeDinerToHidden(self, chairIndex): def setAllDinersToSitNeutral(self): startFrame = 0 - for diner in self.diners.values(): + for diner in list(self.diners.values()): if not diner.isHidden(): diner.loop('sit', fromFrame=startFrame) startFrame += 1 def cleanupIntervals(self): - for interval in self.activeIntervals.values(): + for interval in list(self.activeIntervals.values()): interval.finish() self.activeIntervals = {} def clearInterval(self, name, finish = 1): - if self.activeIntervals.has_key(name): + if name in self.activeIntervals: ival = self.activeIntervals[name] if finish: ival.finish() else: ival.pause() - if self.activeIntervals.has_key(name): + if name in self.activeIntervals: del self.activeIntervals[name] else: self.notify.debug('interval: %s already cleared' % name) def finishInterval(self, name): - if self.activeIntervals.has_key(name): + if name in self.activeIntervals: interval = self.activeIntervals[name] interval.finish() def getNotDeadInfo(self): notDeadList = [] - for i in xrange(self.numDiners): + for i in range(self.numDiners): if self.dinerStatus[i] != self.DEAD: notDeadList.append((self.index, i, 12)) @@ -433,7 +433,7 @@ def exitOn(self): pass def enterInactive(self): - for chairIndex in xrange(self.numDiners): + for chairIndex in range(self.numDiners): indicator = self.dinerStatusIndicators.get(chairIndex) if indicator: indicator.request('Inactive') @@ -469,17 +469,17 @@ def touchedTable(self, colEntry): def prepareForPhaseFour(self): if not self.preparedForPhaseFour: - for i in xrange(8): + for i in range(8): chair = self.tableGroup.find('**/chair_%d' % (i + 1)) if not chair.isEmpty(): chair.hide() colChairs = self.tableGroup.findAllMatches('**/ChairCol*') - for i in xrange(colChairs.getNumPaths()): + for i in range(colChairs.getNumPaths()): col = colChairs.getPath(i) col.stash() colChairs = self.tableGroup.findAllMatches('**/collision_chair*') - for i in xrange(colChairs.getNumPaths()): + for i in range(colChairs.getNumPaths()): col = colChairs.getPath(i) col.stash() @@ -981,7 +981,7 @@ def __endFireWater(self): def __updateWaterPower(self, task): if not self.powerBar: - print '### no power bar!!!' + print('### no power bar!!!') return task.done newPower = self.__getWaterPower(globalClock.getFrameTime()) self.power = newPower @@ -1098,10 +1098,10 @@ def __killUpdateKeyPressRateTask(self): def __updateKeyPressRateTask(self, task): if self.state not in 'Controlled': return Task.done - for i in xrange(len(self.keyTTL)): + for i in range(len(self.keyTTL)): self.keyTTL[i] -= 0.1 - for i in xrange(len(self.keyTTL)): + for i in range(len(self.keyTTL)): if self.keyTTL[i] <= 0: a = self.keyTTL[0:i] del self.keyTTL diff --git a/toontown/coghq/DistributedBanquetTableAI.py b/toontown/coghq/DistributedBanquetTableAI.py index b1b16739b..7a4c44adb 100644 --- a/toontown/coghq/DistributedBanquetTableAI.py +++ b/toontown/coghq/DistributedBanquetTableAI.py @@ -17,7 +17,7 @@ def __init__(self, air, boss, index, numDiners, dinerLevel): self.numChairs = 8 self.dinerStatus = {} self.dinerInfo = {} - for i in xrange(self.numDiners): + for i in range(self.numDiners): self.dinerStatus[i] = self.INACTIVE diffSettings = ToontownGlobals.BossbotBossDifficultySettings[self.boss.battleDifficulty] hungryDuration = diffSettings[4] @@ -67,7 +67,7 @@ def getDinerInfo(self): eatingDurations = [] dinerLevels = [] dinerSuitDept = [] - for i in xrange(self.numDiners): + for i in range(self.numDiners): hungryDurations.append(self.dinerInfo[i][0]) eatingDurations.append(self.dinerInfo[i][1]) dinerLevels.append(self.dinerInfo[i][2]) @@ -160,7 +160,7 @@ def goFlat(self): def getNotDeadInfo(self): notDeadList = [] - for i in xrange(self.numDiners): + for i in range(self.numDiners): if self.dinerStatus[i] != self.DEAD: notDeadList.append((self.index, i, self.dinerInfo[i][2], self.dinerInfo[i][3])) @@ -207,7 +207,7 @@ def __getTableId(self, avId): return 0 def enterOn(self): - for i in xrange(self.numDiners): + for i in range(self.numDiners): self.b_setDinerStatus(i, self.HUNGRY) def exitOn(slef): @@ -220,7 +220,7 @@ def exitOff(self): pass def enterInactive(self): - for task in self.transitionTasks.values(): + for task in list(self.transitionTasks.values()): self.removeTask(task) self.transitionTasks = {} diff --git a/toontown/coghq/DistributedCashbotBossCrane.py b/toontown/coghq/DistributedCashbotBossCrane.py index c8b99382e..15c1b9841 100644 --- a/toontown/coghq/DistributedCashbotBossCrane.py +++ b/toontown/coghq/DistributedCashbotBossCrane.py @@ -231,7 +231,7 @@ def __deactivatePhysics(self): self.physicsActivated = 0 def __straightenCable(self): - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): an, anp, cnp = self.activeLinks[linkNum] an.getPhysicsObject().setVelocity(0, 0, 0) z = float(linkNum + 1) / float(self.numLinks) * self.cableLength @@ -254,7 +254,7 @@ def setupCable(self): self.links = [] self.links.append((self.topLink, Point3(0, 0, 0))) anchor = self.topLink - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): anchor = self.__makeLink(anchor, linkNum) self.collisions.stash() @@ -564,7 +564,7 @@ def __deactivateSniffer(self): def startFlicker(self): self.magnetSoundInterval.start() self.lightning = [] - for i in xrange(4): + for i in range(4): t = float(i) / 3.0 - 0.5 l = self.boss.lightning.copyTo(self.gripper) l.setScale(random.choice([1, -1]), 1, 5) @@ -695,7 +695,7 @@ def reloadPosition(self): self.armSmoother.setPos(self.crane.getPos()) self.armSmoother.setHpr(self.arm.getHpr()) self.armSmoother.setPhonyTimestamp() - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): smoother = self.linkSmoothers[linkNum] an, anp, cnp = self.activeLinks[linkNum] smoother.clearPositions(0) @@ -704,7 +704,7 @@ def reloadPosition(self): def doSmoothTask(self, task): self.armSmoother.computeAndApplySmoothPosHpr(self.crane, self.arm) - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): smoother = self.linkSmoothers[linkNum] anp = self.activeLinks[linkNum][1] smoother.computeAndApplySmoothPos(anp) @@ -731,7 +731,7 @@ def forceToTruePosition(self): self.armSmoother.applySmoothPos(self.crane) self.armSmoother.applySmoothHpr(self.arm) self.armSmoother.clearPositions(1) - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): smoother = self.linkSmoothers[linkNum] an, anp, cnp = self.activeLinks[linkNum] if smoother.getLatestPosition(): @@ -750,7 +750,7 @@ def setCablePos(self, changeSeq, y, h, links, timestamp): self.armSmoother.setH(h) self.armSmoother.setTimestamp(local) self.armSmoother.markPosition() - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): smoother = self.linkSmoothers[linkNum] lp = links[linkNum] smoother.setPos(*lp) @@ -764,7 +764,7 @@ def setCablePos(self, changeSeq, y, h, links, timestamp): def d_sendCablePos(self): timestamp = globalClockDelta.getFrameNetworkTime() links = [] - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): an, anp, cnp = self.activeLinks[linkNum] p = anp.getPos() links.append((p[0], p[1], p[2])) diff --git a/toontown/coghq/DistributedCashbotBossObject.py b/toontown/coghq/DistributedCashbotBossObject.py index 8f0eb9d65..596bef1fd 100644 --- a/toontown/coghq/DistributedCashbotBossObject.py +++ b/toontown/coghq/DistributedCashbotBossObject.py @@ -125,12 +125,12 @@ def __hitBoss(self, entry): vel.normalize() impact = vel[1] if impact >= self.getMinImpact(): - print 'hit! %s' % impact + print(('hit! %s' % impact)) self.hitBossSoundInterval.start() self.doHitBoss(impact) else: self.touchedBossSoundInterval.start() - print '--not hard enough: %s' % impact + print(('--not hard enough: %s' % impact)) def doHitBoss(self, impact): self.d_hitBoss(impact) @@ -140,7 +140,7 @@ def __hitDropPlane(self, entry): self.fellOut() def fellOut(self): - raise StandardError, 'fellOut unimplented' + raise Exception('fellOut unimplented') def getMinImpact(self): return 0 @@ -200,7 +200,7 @@ def d_hitBoss(self, impact): def defaultFilter(self, request, args): if self.boss == None: - raise FSM.RequestDenied, request + raise FSM.RequestDenied(request) return FSM.FSM.defaultFilter(self, request, args) def enterOff(self): diff --git a/toontown/coghq/DistributedCogKart.py b/toontown/coghq/DistributedCogKart.py index efced645d..c3d0841d8 100644 --- a/toontown/coghq/DistributedCogKart.py +++ b/toontown/coghq/DistributedCogKart.py @@ -347,7 +347,7 @@ def startCountdownClock(self, countdownTime, ts): self.clock.setH(self.clock.getH() + 180) def rejectBoard(self, avId, reason = 0): - print 'rejectBoard %s' % reason + print(('rejectBoard %s' % reason)) if hasattr(base.localAvatar, 'elevatorNotifier'): if reason == ElevatorConstants.REJECT_SHUFFLE: base.localAvatar.elevatorNotifier.showMe(TTLocalizer.ElevatorHoppedOff) diff --git a/toontown/coghq/DistributedCogKartAI.py b/toontown/coghq/DistributedCogKartAI.py index 79a1aab45..c3bd53e9b 100644 --- a/toontown/coghq/DistributedCogKartAI.py +++ b/toontown/coghq/DistributedCogKartAI.py @@ -32,7 +32,7 @@ def elevatorClosed(self): if i not in [None, 0]: players.append(i) countryClubZone = self.bldg.createCountryClub(self.countryClubId, players) - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] if avId: self.sendUpdateToAvatarId(avId, 'setCountryClubInteriorZone', [ diff --git a/toontown/coghq/DistributedCountryClub.py b/toontown/coghq/DistributedCountryClub.py index b4a9e4eec..7b8961b85 100644 --- a/toontown/coghq/DistributedCountryClub.py +++ b/toontown/coghq/DistributedCountryClub.py @@ -221,7 +221,7 @@ def setBossConfronted(self, avId): base.localAvatar.setSystemMessage(avId, TTLocalizer.CountryClubBossConfrontedMsg % av.getName()) def warpToRoom(self, roomId): - for i in xrange(len(self.rooms)): + for i in range(len(self.rooms)): room = self.rooms[i] if room.roomId == roomId: break diff --git a/toontown/coghq/DistributedCountryClubAI.py b/toontown/coghq/DistributedCountryClubAI.py index 2f9044742..611c79081 100644 --- a/toontown/coghq/DistributedCountryClubAI.py +++ b/toontown/coghq/DistributedCountryClubAI.py @@ -20,7 +20,7 @@ def __init__(self, air, countryClubId, zoneId, floorNum, avIds, layoutIndex, bat self.elevatorList = [] self.battleExpAggreg = battleExpAggreg self.layout = CountryClubLayout.CountryClubLayout(self.countryClubId, self.floorNum, self.layoutIndex) - for i in xrange(self.layout.getNumRooms()): + for i in range(self.layout.getNumRooms()): if i: self.blockedRooms.append(i) @@ -30,7 +30,7 @@ def generate(self): self.rooms = [] if self.battleExpAggreg is None: self.battleExpAggreg = BattleExperienceAggregatorAI.BattleExperienceAggregatorAI() - for i in xrange(self.layout.getNumRooms()): + for i in range(self.layout.getNumRooms()): room = DistributedCountryClubRoomAI.DistributedCountryClubRoomAI(self.air, self.countryClubId, self.doId, self.zoneId, self.layout.getRoomId(i), i * 2, self.avIds, self.battleExpAggreg) room.generateWithRequired(self.zoneId) self.rooms.append(room) diff --git a/toontown/coghq/DistributedCountryClubRoom.py b/toontown/coghq/DistributedCountryClubRoom.py index e1df063e4..71a9bbcbe 100644 --- a/toontown/coghq/DistributedCountryClubRoom.py +++ b/toontown/coghq/DistributedCountryClubRoom.py @@ -155,7 +155,7 @@ def printPos(self = self): pos = base.localAvatar.getPos(thisZone) h = base.localAvatar.getH(thisZone) roomName = CountryClubRoomSpecs.BossbotCountryClubRoomId2RoomName[self.roomId] - print 'countryClub pos: %s, h: %s, room: %s' % (repr(pos), h, roomName) + print(('countryClub pos: %s, h: %s, room: %s' % (repr(pos), h, roomName))) if self.countryClub is not None: floorNum = self.countryClub.floorNum else: diff --git a/toontown/coghq/DistributedCrate.py b/toontown/coghq/DistributedCrate.py index b4dc645ad..40c943aeb 100644 --- a/toontown/coghq/DistributedCrate.py +++ b/toontown/coghq/DistributedCrate.py @@ -1,7 +1,7 @@ from pandac.PandaModules import * from direct.interval.IntervalGlobal import * from toontown.toonbase.ToontownGlobals import * -from CrateGlobals import * +from .CrateGlobals import * from toontown.toonbase.ToonPythonUtil import fitSrcAngle2Dest from direct.distributed import DistributedObject from direct.directnotify import DirectNotifyGlobal @@ -185,7 +185,7 @@ def __stickTask(self, task): return Task.cont def getCrateSide(self, crateNormal): - for i in xrange(len(CrateNormals)): + for i in range(len(CrateNormals)): dotP = CrateNormals[i].dot(crateNormal) if dotP > 0.9: self.crateSide = i diff --git a/toontown/coghq/DistributedCrateAI.py b/toontown/coghq/DistributedCrateAI.py index 01170dc97..b47970d40 100644 --- a/toontown/coghq/DistributedCrateAI.py +++ b/toontown/coghq/DistributedCrateAI.py @@ -1,4 +1,4 @@ -from CrateGlobals import * +from .CrateGlobals import * from direct.directnotify import DirectNotifyGlobal from toontown.coghq import DistributedCrushableEntityAI from direct.task import Task diff --git a/toontown/coghq/DistributedDoorEntity.py b/toontown/coghq/DistributedDoorEntity.py index 6173f383b..750d582b7 100644 --- a/toontown/coghq/DistributedDoorEntity.py +++ b/toontown/coghq/DistributedDoorEntity.py @@ -35,7 +35,7 @@ def takedown(self): self.track.pause() self.track = None - for i in self.states.keys(): + for i in list(self.states.keys()): del self.states[i] self.states = [] @@ -156,7 +156,7 @@ def takedown(self): self.locks = [] self.fsm = None - for i in self.states.keys(): + for i in list(self.states.keys()): del self.states[i] self.states = [] @@ -276,7 +276,7 @@ def setupDoor(self): door = doorway.find('doortop') if door.isEmpty(): - print 'doortop hack' + print('doortop hack') door = doorway.attachNewNode('doortop') doorway.find('doortop1').reparentTo(door) doorway.find('doortop2').reparentTo(door) @@ -304,7 +304,7 @@ def setupDoor(self): door = doorway.find('doorbottom') if door.isEmpty(): - print 'doorbottom hack' + print('doorbottom hack') door = doorway.attachNewNode('doorbottom') doorway.find('doorbottom1').reparentTo(door) doorway.find('doorbottom2').reparentTo(door) diff --git a/toontown/coghq/DistributedElevatorMarker.py b/toontown/coghq/DistributedElevatorMarker.py index fe5177af9..e8684c5c5 100644 --- a/toontown/coghq/DistributedElevatorMarker.py +++ b/toontown/coghq/DistributedElevatorMarker.py @@ -1,7 +1,7 @@ import math from pandac.PandaModules import * from direct.interval.IntervalGlobal import * -from StomperGlobals import * +from .StomperGlobals import * from direct.distributed import ClockDelta from toontown.toonbase.ToonPythonUtil import lerp from otp.level import DistributedEntity diff --git a/toontown/coghq/DistributedFactory.py b/toontown/coghq/DistributedFactory.py index 2b31dbc15..6077bbd35 100644 --- a/toontown/coghq/DistributedFactory.py +++ b/toontown/coghq/DistributedFactory.py @@ -96,7 +96,7 @@ def handleFirstSetZoneDone(): def printPos(self = self): pos = base.localAvatar.getPos(self.getZoneNode(self.lastToonZone)) h = base.localAvatar.getH(self.getZoneNode(self.lastToonZone)) - print 'factory pos: %s, h: %s, zone %s' % (repr(pos), h, self.lastToonZone) + print(('factory pos: %s, h: %s, zone %s' % (repr(pos), h, self.lastToonZone))) posStr = 'X: %.3f' % pos[0] + '\nY: %.3f' % pos[1] + '\nZ: %.3f' % pos[2] + '\nH: %.3f' % h + '\nZone: %s' % str(self.lastToonZone) base.localAvatar.setChatAbsolute(posStr, CFThought | CFTimeout) diff --git a/toontown/coghq/DistributedFactoryAI.py b/toontown/coghq/DistributedFactoryAI.py index 7a8cd79da..7245c8c34 100644 --- a/toontown/coghq/DistributedFactoryAI.py +++ b/toontown/coghq/DistributedFactoryAI.py @@ -1,6 +1,6 @@ from otp.level import DistributedLevelAI from direct.directnotify import DirectNotifyGlobal -import cPickle +import pickle from toontown.coghq import LevelSuitPlannerAI from toontown.coghq import FactoryBase from direct.task import Task diff --git a/toontown/coghq/DistributedFactoryElevatorExtAI.py b/toontown/coghq/DistributedFactoryElevatorExtAI.py index 14e17b55a..dba1655ed 100644 --- a/toontown/coghq/DistributedFactoryElevatorExtAI.py +++ b/toontown/coghq/DistributedFactoryElevatorExtAI.py @@ -26,7 +26,7 @@ def elevatorClosed(self): players.append(i) factoryZone = self.bldg.createFactory(self.factoryId, self.entranceId, players) - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] if avId: self.sendUpdateToAvatarId(avId, 'setFactoryInteriorZone', [factoryZone]) diff --git a/toontown/coghq/DistributedFoodBelt.py b/toontown/coghq/DistributedFoodBelt.py index 9d040e1bb..e8075118e 100644 --- a/toontown/coghq/DistributedFoodBelt.py +++ b/toontown/coghq/DistributedFoodBelt.py @@ -77,26 +77,26 @@ def setState(self, state): def enterOn(self): self.beltSoundInterval.loop() - for i in xrange(len(self.foodNodes)): + for i in range(len(self.foodNodes)): self.doMethodLater(self.foodWaitTimes[i], self.startFoodMoving, 'start-%d-%d' % (self.index, i), extraArgs=[i]) def exitOn(self): self.beltSoundInterval.finish() - for i in xrange(len(self.foodNodes)): + for i in range(len(self.foodNodes)): taskName = 'start-%d-%d' % (self.index, i) self.removeTask(taskName) def enterToonup(self): self.beltSound.setPlayRate(self.ToonupBeltSpeed / self.BeltSpeed) self.beltSoundInterval.loop() - for i in xrange(len(self.foodNodes)): + for i in range(len(self.foodNodes)): self.removeFood(i) self.beltActor.setPlayRate(self.ToonupBeltActorPlayRate, 'idle') self.doMethodLater(self.toonupWaitTimes[i], self.startToonupMoving, 'startToonup-%d-%d' % (self.index, i), extraArgs=[i]) def exitToonup(self): self.beltSoundInterval.finish() - for i in xrange(len(self.foodNodes)): + for i in range(len(self.foodNodes)): taskName = 'startToonup-%d-%d' % (self.index, i) self.removeTask(taskName) @@ -107,7 +107,7 @@ def enterInactive(self): for ival in self.toonupIvals: ival.finish() - for i in xrange(len(self.foodNodes)): + for i in range(len(self.foodNodes)): self.removeFood(i) self.removeToonup(i) @@ -170,11 +170,11 @@ def loadAssets(self): self.beltSoundInterval = SoundInterval(self.beltSound, node=self.beltModel, listenerNode=base.localAvatar, seamlessLoop=True, volume=0.25, cutOff=100) def cleanup(self): - for i in xrange(len(self.foodNodes)): + for i in range(len(self.foodNodes)): taskName = 'start-%d-%d' % (self.index, i) self.removeTask(taskName) - for i in xrange(len(self.foodNodes)): + for i in range(len(self.foodNodes)): taskName = 'startToonup-%d-%d' % (self.index, i) self.removeTask(taskName) @@ -193,7 +193,7 @@ def cleanup(self): self.ignoreAll() def setupFoodNodes(self): - for i in xrange(self.NumFoodNodes): + for i in range(self.NumFoodNodes): newPosIndex = self.NumFoodNodes - 1 - i yPos = -(self.beltLength / 2.0) + newPosIndex * self.distBetweenFoodNodes newFoodNode = NodePath('foodNode-%d-%d' % (self.index, i)) @@ -207,7 +207,7 @@ def setupFoodNodes(self): self.foodNodes.append(newFoodNode) def setupFoodIvals(self): - for i in xrange(len(self.foodNodes)): + for i in range(len(self.foodNodes)): foodIval = self.createOneFoodIval(self.foodNodes[i]) self.foodIvals.append(foodIval) @@ -275,7 +275,7 @@ def touchedFood(self, colEntry): self.boss.localToonTouchedBeltFood(beltIndex, foodIndex, foodNum) def setupToonupIvals(self): - for i in xrange(len(self.foodNodes)): + for i in range(len(self.foodNodes)): toonupIval = self.createOneToonupIval(self.foodNodes[i]) self.toonupIvals.append(toonupIval) diff --git a/toontown/coghq/DistributedGagBarrel.py b/toontown/coghq/DistributedGagBarrel.py index bc0e9446b..69f1094a1 100644 --- a/toontown/coghq/DistributedGagBarrel.py +++ b/toontown/coghq/DistributedGagBarrel.py @@ -26,9 +26,9 @@ def applyLabel(self): invModel = loader.loadModel('phase_3.5/models/gui/inventory_icons') self.invModels = [] from toontown.toonbase import ToontownBattleGlobals - for gagTrack in xrange(len(ToontownBattleGlobals.AvPropsNew)): + for gagTrack in range(len(ToontownBattleGlobals.AvPropsNew)): itemList = [] - for item in xrange(len(ToontownBattleGlobals.AvPropsNew[gagTrack])): + for item in range(len(ToontownBattleGlobals.AvPropsNew[gagTrack])): itemList.append(invModel.find('**/' + ToontownBattleGlobals.AvPropsNew[gagTrack][item])) self.invModels.append(itemList) diff --git a/toontown/coghq/DistributedGolfGreenGame.py b/toontown/coghq/DistributedGolfGreenGame.py index cec55cbc8..066a80429 100644 --- a/toontown/coghq/DistributedGolfGreenGame.py +++ b/toontown/coghq/DistributedGolfGreenGame.py @@ -23,7 +23,7 @@ from math import pi import math import random -import cPickle +import pickle from toontown.distributed import DelayDelete from toontown.toon import ToonHeadFrame from toontown.battle import BattleParticles @@ -164,9 +164,9 @@ def setup(self): self.controlOffsetX = 0.0 self.controlOffsetZ = 0.0 self.grid = [] - for countX in xrange(0, self.gridDimX): + for countX in range(0, self.gridDimX): newRow = [] - for countZ in xrange(self.gridDimZ): + for countZ in range(self.gridDimZ): offset = 0 margin = self.cellSizeX * 0.4375 if countZ % 2 == 0: @@ -226,19 +226,19 @@ def setup(self): def printGrid(self): printout = ' ' - for columnIndex in xrange(self.gridDimX - 1, -1, -1): + for columnIndex in range(self.gridDimX - 1, -1, -1): if columnIndex < 10: printout += '%s ' % columnIndex else: printout += '%s ' % columnIndex - print printout - for rowIndex in xrange(self.gridDimZ - 1, -1, -1): + print(printout) + for rowIndex in range(self.gridDimZ - 1, -1, -1): if rowIndex < 10: printout = 'row %s ' % rowIndex else: printout = 'row %s ' % rowIndex - for columnIndex in xrange(self.gridDimX - 1, -1, -1): + for columnIndex in range(self.gridDimX - 1, -1, -1): hasSprite = '_' if self.grid[columnIndex][rowIndex][0]: hasSprite = 'X' @@ -247,18 +247,18 @@ def printGrid(self): else: printout += '%s ' % hasSprite - print printout + print(printout) count = 0 for sprite in self.sprites: - print 'count %s X %s Z %s Color %s' % (count, + print(('count %s X %s Z %s Color %s' % (count, sprite.gridPosX, sprite.gridPosZ, - sprite.colorType) + sprite.colorType))) count += 1 def pickLevelPattern(self): - self.boardIndex = random.choice(range(0, len(self.boardData))) + self.boardIndex = random.choice(list(range(0, len(self.boardData)))) self.board = self.boardData[self.boardIndex] self.attackPattern = self.attackPatterns[self.boardIndex] self.attackCounter = 0 @@ -575,8 +575,8 @@ def __leaveGame(self): def findGrid(self, x, z, force = 0): currentClosest = None currentDist = 10000000 - for countX in xrange(self.gridDimX): - for countZ in xrange(self.gridDimZ): + for countX in range(self.gridDimX): + for countZ in range(self.gridDimZ): testDist = self.testPointDistanceSquare(x, z, self.grid[countX][countZ][1], self.grid[countX][countZ][2]) if self.grid[countX][countZ][0] == None and testDist < currentDist and (force or self.hasNeighbor(countX, countZ) != None): currentClosest = self.grid[countX][countZ] @@ -619,7 +619,7 @@ def clearFloaters(self): self.grounded = [] self.unknown = [] groundZ = self.gridDimZ - 1 - for indexX in xrange(0, self.gridDimX): + for indexX in range(0, self.gridDimX): gridCell = self.grid[indexX][groundZ] if gridCell[0]: self.grounded.append((indexX, groundZ)) @@ -998,7 +998,7 @@ def addSprite(self, image, size = 3.0, posX = 0, posZ = 0, found = 0, color = No size = self.radiusBall * 2.0 facing = 1 if color == None: - colorChoice = random.choice(range(0, 3)) + colorChoice = random.choice(list(range(0, 3))) else: colorChoice = color newSprite = GameSprite3D.GameSprite(spriteBase, size, colorChoice, found, facing) @@ -1077,7 +1077,7 @@ def __run(self, cont = 1): while self.controlSprite == None and self.attackPattern: if self.attackCounter > len(self.attackPattern) - 1: self.attackCounter = 0 - print 'Pattern %s Place %s Type %s' % (self.attackPattern, self.attackCounter, self.attackPattern[self.attackCounter]) + print(('Pattern %s Place %s Type %s' % (self.attackPattern, self.attackCounter, self.attackPattern[self.attackCounter]))) if self.standbySprite.holdType != None: color = self.standbySprite.holdType sprite = self.addControlSprite(self.newBallX, self.newBallZ + self.spriteNotchPos * self.cellSizeZ, color) @@ -1166,8 +1166,8 @@ def __colTest(self): if self.tick > 5: self.tick = 0 sizeSprites = len(self.sprites) - for movingSpriteIndex in xrange(len(self.sprites)): - for testSpriteIndex in xrange(movingSpriteIndex, len(self.sprites)): + for movingSpriteIndex in range(len(self.sprites)): + for testSpriteIndex in range(movingSpriteIndex, len(self.sprites)): movingSprite = self.getSprite(movingSpriteIndex) testSprite = self.getSprite(testSpriteIndex) if testSprite and movingSprite: @@ -1339,13 +1339,13 @@ def acceptJoin(self, time, timeStamp, avIds): self.joinedToons.append(avId) index = self.everJoinedToons.index(avId) if index > 3: - print 'ERROR! green game has had more than 4 players, we are about to crash\n %s' % self.everJoinedToons - print 'Joining Toon is %s index is %s' % (avId, index) + print(('ERROR! green game has had more than 4 players, we are about to crash\n %s' % self.everJoinedToons)) + print(('Joining Toon is %s index is %s' % (avId, index))) toon = base.cr.doId2do.get(avId) selfPos = self.getPos(render) offset = self.toonPoints[index] if index > 3: - print 'odd... we should have crashed by now' + print('odd... we should have crashed by now') standPoint = render.getRelativePoint(self, offset) if toon: toon.stopSmooth() @@ -1415,7 +1415,7 @@ def scoreData(self, total = 2, closed = 1, scoreList = 'hello world'): panel = self.toonPanels[panelIndex] panel.extraData['text'] = TTLocalizer.GolfGreenGamePlayerScore % 0 - for entryIndex in xrange(len(scoreList)): + for entryIndex in range(len(scoreList)): entry = scoreList[entryIndex] if entry[0] in self.toonPanels: panel = self.toonPanels[entry[0]] diff --git a/toontown/coghq/DistributedGolfGreenGameAI.py b/toontown/coghq/DistributedGolfGreenGameAI.py index d73fe10e8..785365b1a 100644 --- a/toontown/coghq/DistributedGolfGreenGameAI.py +++ b/toontown/coghq/DistributedGolfGreenGameAI.py @@ -8,7 +8,7 @@ from toontown.coghq import BattleBlockerAI from direct.distributed.ClockDelta import * from toontown.toonbase import ToontownBattleGlobals -from GolfGreenGameGlobals import * +from .GolfGreenGameGlobals import * import random import time @@ -58,9 +58,9 @@ def announceGenerate(self): if hasattr(self, 'level'): numToons = len(self.level.presentAvIds) numBoards = self.puzzleBase + numToons * self.puzzlePerPlayer - boardSelect = range(0, len(gameBoards)) + boardSelect = list(range(0, len(gameBoards))) didGetLast = 1 - for index in xrange(numBoards): + for index in range(numBoards): choice = random.choice(boardSelect) if not didGetLast: didGetLast = 1 @@ -79,8 +79,8 @@ def announceGenerate(self): def processPreData(self): for board in self.preData: x = [] - for rowIndex in xrange(1, len(board)): - for columnIndex in xrange(len(board[rowIndex])): + for rowIndex in range(1, len(board)): + for columnIndex in range(len(board[rowIndex])): color = self.translateData.get(board[rowIndex][columnIndex]) if color != None: x.append((len(board[rowIndex]) - (columnIndex + 1), rowIndex - 1, color)) @@ -93,9 +93,9 @@ def processPreData(self): for ball in attackString: color = self.translateData.get(ball) if color or color == 0: - place = random.choice(range(0, len(attackPattern) + 1)) + place = random.choice(list(range(0, len(attackPattern) + 1))) attackPattern.insert(place, color) - place = random.choice(range(0, len(attackPattern) + 1)) + place = random.choice(list(range(0, len(attackPattern) + 1))) attackPattern.insert(place, color) self.attackPatterns.append(attackPattern) @@ -106,7 +106,7 @@ def startTimer(self): self.sendUpdate('setTimerStart', [self.totalTime, self.startTime]) def __printTime(self, task): - print 'Time Left %s' % self.getTimeLeft() + print(('Time Left %s' % self.getTimeLeft())) taskMgr.doMethodLater(1.0, self.__printTime, self.taskName('GolfGreenGameTimeout Print')) return task.done @@ -127,14 +127,14 @@ def choosePattern(self): dataSize = len(self.boardData) indexChoice = int(random.random() * dataSize) boardToAssign = None - for boardIndex in xrange(len(self.boardList)): + for boardIndex in range(len(self.boardList)): board = self.boardList[boardIndex] if self.boardList[boardIndex][0] == 'closed': pass elif boardToAssign == None or len(self.boardList[boardIndex][0]) < len(self.boardList[boardToAssign][0]): boardToAssign = boardIndex elif len(self.boardList[boardIndex][0]) == len(self.boardList[boardToAssign][0]): - choice = random.choice(range(2)) + choice = random.choice(list(range(2))) if choice: boardToAssign = boardIndex @@ -143,7 +143,7 @@ def choosePattern(self): return boardToAssign def checkForAssigned(self, avId): - for index in xrange(len(self.boardList)): + for index in range(len(self.boardList)): board = self.boardList[index] if board[0] == 'closed': pass diff --git a/toontown/coghq/DistributedGolfSpot.py b/toontown/coghq/DistributedGolfSpot.py index 5fd4a79e8..2e5fcb747 100644 --- a/toontown/coghq/DistributedGolfSpot.py +++ b/toontown/coghq/DistributedGolfSpot.py @@ -116,7 +116,7 @@ def cleanup(self): if self.releaseTrack: self.releaseTrack.finish() self.releaseTrack = None - flyTracks = self.flyBallTracks.values() + flyTracks = list(self.flyBallTracks.values()) for track in flyTracks: track.finish() @@ -458,7 +458,7 @@ def __endFireBall(self): def __updateBallPower(self, task): if not self.powerBar: - print '### no power bar!!!' + print('### no power bar!!!') return task.done newPower = self.__getBallPower(globalClock.getFrameTime()) self.power = newPower @@ -671,7 +671,7 @@ def getFlyBallBubble(self): return self.__flyBallBubble def __flyBallHit(self, entry): - print entry + print(entry) def flyBallFinishedFlying(self, sequence): if sequence in self.flyBallTracks: diff --git a/toontown/coghq/DistributedGrid.py b/toontown/coghq/DistributedGrid.py index ad4c0523c..808a62ddf 100644 --- a/toontown/coghq/DistributedGrid.py +++ b/toontown/coghq/DistributedGrid.py @@ -48,7 +48,7 @@ def loadModel(self): long = self.numRow short = self.numCol h = 90 - self.model.setScale(scale * long, scale * short, 1) + self.model.setScale(scale * int, scale * short, 1) self.model.setHpr(h, 180, 0) self.model.setPos(self.cellSize * self.numCol / 2.0, self.cellSize * self.numRow / 2.0, 0.025) self.model.setColor(0.588, 0.588, 0.459, 0.4) diff --git a/toontown/coghq/DistributedGridAI.py b/toontown/coghq/DistributedGridAI.py index ffd85109d..ba5acc99e 100644 --- a/toontown/coghq/DistributedGridAI.py +++ b/toontown/coghq/DistributedGridAI.py @@ -21,9 +21,9 @@ def initializeGrid(self): if not self.initialized: self.objPos = {} self.gridCells = [None] * self.numRow - for i in xrange(len(self.gridCells)): + for i in range(len(self.gridCells)): self.gridCells[i] = [None] * self.numCol - for j in xrange(len(self.gridCells[i])): + for j in range(len(self.gridCells[i])): self.gridCells[i][j] = [] self.initialized = 1 @@ -222,9 +222,9 @@ def __isEmpty(self, row, col): def printGrid(self): if not __debug__: return - for i in xrange(len(self.gridCells)): + for i in range(len(self.gridCells)): str = '' - for j in xrange(len(self.gridCells[i])): + for j in range(len(self.gridCells[i])): col = self.gridCells[i][j] active = 0 for cell in self.activeCellList: @@ -241,6 +241,6 @@ def printGrid(self): else: str += ' . ' - print str + ' : %d' % i + print((str + ' : %d' % i)) - print '' + print('') diff --git a/toontown/coghq/DistributedInGameEditor.py b/toontown/coghq/DistributedInGameEditor.py index 415d7f4c4..628059c50 100644 --- a/toontown/coghq/DistributedInGameEditor.py +++ b/toontown/coghq/DistributedInGameEditor.py @@ -19,10 +19,10 @@ def __init__(self): def attribChanged(self, attrib, value): Entity.Entity.attribChanged(self, attrib, value) - print 'attribChange: %s %s, %s = %s' % (self.level.getEntityType(self.entId), + print(('attribChange: %s %s, %s = %s' % (self.level.getEntityType(self.entId), self.entId, attrib, - repr(value)) + repr(value)))) def getTypeName(self): return self.level.getEntityType(self.entId) @@ -123,7 +123,7 @@ class InGameEditorEntityCreator(EntCreatorClass): def __init__(self, editor): EntCreatorClass.__init__(self, editor) - entTypes = self.entType2Ctor.keys() + entTypes = list(self.entType2Ctor.keys()) for type in entTypes: self.entType2Ctor[type] = InGameEditorEntity @@ -206,7 +206,7 @@ def gotCurrentSpec(self, curSpec): self.entTypes = entCreator.getEntityTypes() self.selectedEntity = None base.startTk() - import InGameEditor + from . import InGameEditor doneEvent = self.uniqueName('editorDone') saveAsEvent = self.uniqueName('saveSpec') requestSaveEvent = self.uniqueName('requestSpecSave') @@ -317,7 +317,7 @@ def insertEntityIntoTree(self, entId): def buildEntityTree(self): self.setChildren([]) - entIds = self.entities.keys() + entIds = list(self.entities.keys()) entIds.sort() for entId in entIds: ent = self.getEntity(entId) @@ -488,7 +488,7 @@ def setEntCreateHandler(self = self, handler = setNewEntityId): def setEntityCreatorUsername(self, entId, editUsername): Level.Level.setEntityCreatorUsername(self, entId, editUsername) if editUsername == self.getEditUsername(): - print 'entity %s about to be created; we requested it' % entId + print(('entity %s about to be created; we requested it' % entId)) callback = self.entCreateHandlerQ[0] del self.entCreateHandlerQ[:1] callback(entId) @@ -533,12 +533,12 @@ def doRemoveEntity(self, entId): oldAttribs = [] spec = self.levelSpec.getEntitySpecCopy(entId) del spec['type'] - for attrib, value in spec.items(): + for attrib, value in list(spec.items()): oldAttribs.append((attrib, value)) def setNewEntityId(entId, self = self, removeAction = removeAction, oldAttribs = oldAttribs): removeAction[2]['entId'] = entId - for attrib, value in spec.items(): + for attrib, value in list(spec.items()): self.privSendAttribEdit(entId, attrib, value) def setEntCreateHandler(self = self, handler = setNewEntityId): @@ -576,7 +576,7 @@ def makeCopyOfEntName(self, name): if oldName[i] != ' ': hasSuffix = False else: - print 'numString: %s' % numString + print(('numString: %s' % numString)) copyNum = int(numString) + 1 if hasSuffix: newName = oldName[:i] + suffix % copyNum @@ -602,13 +602,13 @@ def duplicateSelectedEntity(self): copyAttribs['name'] = self.makeCopyOfEntName(copyAttribs['name']) typeDesc = self.entTypeReg.getTypeDesc(copyAttribs['type']) attribDescs = typeDesc.getAttribDescDict() - for attribName, attribDesc in attribDescs.items(): + for attribName, attribDesc in list(attribDescs.items()): if attribDesc.getDatatype() == 'const': del copyAttribs[attribName] def setNewEntityId(entId, self = self, removeAction = removeAction, copyAttribs = copyAttribs): removeAction[2]['entId'] = entId - for attribName, value in copyAttribs.items(): + for attribName, value in list(copyAttribs.items()): self.privSendAttribEdit(entId, attribName, value) def setEntCreateHandler(self = self, handler = setNewEntityId): @@ -620,13 +620,13 @@ def setEntCreateHandler(self = self, handler = setNewEntityId): self.setUndoableAttribEdit(old2new, new2old) def specPrePickle(self, spec): - for attribName, value in spec.items(): + for attribName, value in list(spec.items()): spec[attribName] = repr(value) return spec def specPostUnpickle(self, spec): - for attribName, value in spec.items(): + for attribName, value in list(spec.items()): spec[attribName] = eval(value) return spec @@ -638,8 +638,8 @@ def handleImportEntities(self): self.editor.showWarning('Please select a valid entity first.', 'error') return - import tkFileDialog - filename = tkFileDialog.askopenfilename(parent=self.editor.parent, defaultextension='.egroup', filetypes=[('Entity Group', '.egroup'), ('All Files', '*')]) + import tkinter.filedialog + filename = tkinter.filedialog.askopenfilename(parent=self.editor.parent, defaultextension='.egroup', filetypes=[('Entity Group', '.egroup'), ('All Files', '*')]) if len(filename) == 0: return try: @@ -647,7 +647,7 @@ def handleImportEntities(self): f = open(filename, 'r') eTree = pickle.load(f) eGroup = pickle.load(f) - for entId, spec in eGroup.items(): + for entId, spec in list(eGroup.items()): eGroup[entId] = self.specPostUnpickle(spec) except: @@ -657,13 +657,13 @@ def handleImportEntities(self): oldEntId2new = {} def addEntities(treeEntry, parentEntId, eGroup = eGroup): - for entId, children in treeEntry.items(): + for entId, children in list(treeEntry.items()): spec = eGroup[entId] entType = spec['type'] del spec['type'] del spec['parentEntId'] typeDesc = self.entTypeReg.getTypeDesc(entType) - for attribName, attribDesc in typeDesc.getAttribDescDict().items(): + for attribName, attribDesc in list(typeDesc.getAttribDescDict().items()): if attribDesc.getDatatype() == 'const': if attribName in spec: del spec[attribName] @@ -690,14 +690,14 @@ def handleExportEntity(self): self.editor.showWarning('Please select a valid entity first.', 'error') return - import tkFileDialog - filename = tkFileDialog.asksaveasfilename(parent=self.editor.parent, defaultextension='.egroup', filetypes=[('Entity Group', '.egroup'), ('All Files', '*')]) + import tkinter.filedialog + filename = tkinter.filedialog.asksaveasfilename(parent=self.editor.parent, defaultextension='.egroup', filetypes=[('Entity Group', '.egroup'), ('All Files', '*')]) if len(filename) == 0: return eTree = {selectedEntId: {}} eGroup = {} eGroup[selectedEntId] = self.levelSpec.getEntitySpecCopy(selectedEntId) - for entId, spec in eGroup.items(): + for entId, spec in list(eGroup.items()): eGroup[entId] = self.specPrePickle(spec) try: @@ -716,8 +716,8 @@ def handleExportEntityTree(self): self.editor.showWarning('Please select a valid entity first.', 'error') return - import tkFileDialog - filename = tkFileDialog.asksaveasfilename(parent=self.editor.parent, defaultextension='.egroup', filetypes=[('Entity Group', '.egroup'), ('All Files', '*')]) + import tkinter.filedialog + filename = tkinter.filedialog.asksaveasfilename(parent=self.editor.parent, defaultextension='.egroup', filetypes=[('Entity Group', '.egroup'), ('All Files', '*')]) if len(filename) == 0: return eTree = {} @@ -731,7 +731,7 @@ def addEntity(entId, treeEntry): addEntity(child.entId, treeEntry[entId]) addEntity(selectedEntId, eTree) - for entId, spec in eGroup.items(): + for entId, spec in list(eGroup.items()): eGroup[entId] = self.specPrePickle(spec) try: @@ -767,7 +767,7 @@ def requestSpecSave(self): def setAttribChange(self, entId, attrib, valueStr, username): if username == self.editUsername: - print 'we got our own edit back!' + print('we got our own edit back!') value = eval(valueStr) self.levelSpec.setAttribChange(entId, attrib, value, username) diff --git a/toontown/coghq/DistributedLaserField.py b/toontown/coghq/DistributedLaserField.py index a64d7b015..fe0c83215 100644 --- a/toontown/coghq/DistributedLaserField.py +++ b/toontown/coghq/DistributedLaserField.py @@ -1,6 +1,6 @@ from pandac.PandaModules import * from direct.interval.IntervalGlobal import * -from StomperGlobals import * +from .StomperGlobals import * from direct.distributed import ClockDelta from toontown.toonbase.ToonPythonUtil import lerp import math @@ -488,11 +488,11 @@ def genTrace(self): sizeTrace = len(self.tracePath) chainTrace = sizeTrace - 1 previousTrace = 1 - for countVertex in xrange(0, sizeTrace): + for countVertex in range(0, sizeTrace): self.traceWireTris.addVertex(countVertex + 1) self.traceWireTris.closePrimitive() - for countVertex in xrange(0, chainTrace): + for countVertex in range(0, chainTrace): self.traceBeamTris.addVertex(0) self.traceBeamTris.addVertex(countVertex + 1) self.traceBeamTris.addVertex(countVertex + 2) @@ -528,17 +528,17 @@ def createGrid(self): self.beamVertexWriter.addData3f(self.projector[0], self.projector[1], self.projector[2]) self.beamColorWriter.addData4f(0.0, 0.0, 0.0, 0.0) border = 0.4 - for column in xrange(0, self.gridNumX): + for column in range(0, self.gridNumX): columnLeft = 0.0 + gridScaleX * column columnRight = columnLeft + gridScaleX rowBottom = 0 - for row in xrange(0, self.gridNumY): + for row in range(0, self.gridNumY): rowTop = rowBottom + gridScaleY if self.gridData[column][row] and self.gridData[column][row] < len(self.gridSymbols): gridColor = self.gridSymbols[self.gridData[column][row]][1] gridSymbol = self.gridSymbols[self.gridData[column][row]][2] sizeSymbol = len(gridSymbol) - for iVertex in xrange(sizeSymbol): + for iVertex in range(sizeSymbol): vertex = gridSymbol[iVertex] self.gridVertexWriter.addData3f(columnLeft + vertex[0] * gridScaleX, rowBottom + vertex[1] * gridScaleY, self.zFloat) self.gridColorWriter.addData4f(gridColor[0] * red, gridColor[1] * green, gridColor[2] * blue, alpha) @@ -551,7 +551,7 @@ def createGrid(self): gridSymbol = self.symbolSelect[1] gridColor = self.symbolSelect[0] sizeSymbol = len(gridSymbol) - for iVertex in xrange(sizeSymbol): + for iVertex in range(sizeSymbol): vertex = gridSymbol[iVertex] self.gridVertexWriter.addData3f(self.toonX * gridScaleX + vertex[0] * gridScaleX, self.toonY * gridScaleY + vertex[1] * gridScaleY, self.zFloat) self.gridColorWriter.addData4f(gridColor[0] * red, gridColor[1] * green, gridColor[2] * blue, alpha) @@ -561,16 +561,16 @@ def createGrid(self): self.gridTris = GeomLinestrips(Geom.UHDynamic) self.beamTris = GeomTriangles(Geom.UHDynamic) vertexCounter = 1 - for column in xrange(0, self.gridNumX): - for row in xrange(0, self.gridNumY): + for column in range(0, self.gridNumX): + for row in range(0, self.gridNumY): if self.gridData[column][row] and self.gridData[column][row] < len(self.gridSymbols): gridSymbol = self.gridSymbols[self.gridData[column][row]][2] sizeSymbol = len(gridSymbol) - for iVertex in xrange(sizeSymbol): + for iVertex in range(sizeSymbol): self.gridTris.addVertex(vertexCounter + iVertex) self.gridTris.closePrimitive() - for iVertex in xrange(sizeSymbol - 1): + for iVertex in range(sizeSymbol - 1): self.beamTris.addVertex(0) self.beamTris.addVertex(vertexCounter + iVertex + 0) self.beamTris.addVertex(vertexCounter + iVertex + 1) @@ -581,11 +581,11 @@ def createGrid(self): if self.isToonIn: gridSymbol = self.symbolSelect[1] sizeSymbol = len(gridSymbol) - for iVertex in xrange(sizeSymbol): + for iVertex in range(sizeSymbol): self.gridTris.addVertex(vertexCounter + iVertex) self.gridTris.closePrimitive() - for iVertex in xrange(sizeSymbol - 1): + for iVertex in range(sizeSymbol - 1): self.beamTris.addVertex(0) self.beamTris.addVertex(vertexCounter + iVertex + 0) self.beamTris.addVertex(vertexCounter + iVertex + 1) @@ -602,7 +602,7 @@ def setGrid(self, gridNumX, gridNumY): self.gridNumX = gridNumX self.gridNumY = gridNumY self.gridData = [] - for i in xrange(0, gridNumX): + for i in range(0, gridNumX): self.gridData.append([0] * gridNumY) self.genGrid() @@ -628,8 +628,8 @@ def setField(self, fieldData): if fieldData[0] != self.gridNumX or fieldData[1] != self.gridNumY: self.setGrid(fieldData[0], fieldData[1]) fieldCounter = 2 - for column in xrange(0, self.gridNumX): - for row in xrange(0, self.gridNumY): + for column in range(0, self.gridNumX): + for row in range(0, self.gridNumY): if len(fieldData) > fieldCounter: self.gridData[column][row] = fieldData[fieldCounter] fieldCounter += 1 @@ -641,8 +641,8 @@ def getField(self): fieldData.append(self.game.gridNumX) fieldData.append(self.game.gridNumY) fieldData = [] - for column in xrange(0, self.game.gridNumX): - for row in xrange(0, self.game.gridNumY): + for column in range(0, self.game.gridNumX): + for row in range(0, self.game.gridNumY): fieldData.append(self.game.gridData[column][row]) return fieldData @@ -650,8 +650,8 @@ def getField(self): def setSeed(self, seed): self.gridSeed = seed random.seed(seed) - for column in xrange(0, self.gridNumX): - for row in xrange(0, self.gridNumY): + for column in range(0, self.gridNumX): + for row in range(0, self.gridNumY): rint = random.randint(0, 2) self.gridData[column][row] = rint @@ -694,7 +694,7 @@ def showSuit(self, suitIdarray): suit.setVirtual() def initCollisionGeom(self): - print 'Laser Field initCollisionGeom' + print('Laser Field initCollisionGeom') self.blockerX = self.gridScaleX * 0.5 self.blockerY = self.gridScaleY self.cSphere = CollisionSphere(0, 0, 0, self.blockerX) diff --git a/toontown/coghq/DistributedLaserFieldAI.py b/toontown/coghq/DistributedLaserFieldAI.py index 9c4eeb3e7..bca4e1de3 100644 --- a/toontown/coghq/DistributedLaserFieldAI.py +++ b/toontown/coghq/DistributedLaserFieldAI.py @@ -88,8 +88,8 @@ def getField(self): fieldData = [] fieldData.append(self.game.gridNumX) fieldData.append(self.game.gridNumY) - for column in xrange(0, self.game.gridNumX): - for row in xrange(0, self.game.gridNumY): + for column in range(0, self.game.gridNumX): + for row in range(0, self.game.gridNumY): fieldData.append(self.game.gridData[column][row]) return fieldData @@ -142,13 +142,13 @@ def trapFire(self): self.playedSound = 1 def setBattleFinished(self): - print 'battle Finished' + print('battle Finished') BattleBlockerAI.BattleBlockerAI.setBattleFinished(self) messenger.send(self.getOutputEventName(), [1]) self.switchFire() def switchFire(self): - print 'switchFire' + print('switchFire') if self.switchId != 0: switch = self.level.getEntity(self.switchId) if switch: @@ -197,5 +197,5 @@ def showSuits(self): self.hasShownSuits = 1 def addSuit(self, suit): - print 'Adding Suit %s' % suit.doId + print(('Adding Suit %s' % suit.doId)) BattleBlockerAI.BattleBlockerAI.addSuit(self, suit) diff --git a/toontown/coghq/DistributedLawOfficeAI.py b/toontown/coghq/DistributedLawOfficeAI.py index abf682e56..d39a4a2f1 100644 --- a/toontown/coghq/DistributedLawOfficeAI.py +++ b/toontown/coghq/DistributedLawOfficeAI.py @@ -1,4 +1,4 @@ -import cPickle +import pickle from toontown.coghq import CogDisguiseGlobals from toontown.coghq import FactoryEntityCreatorAI from toontown.coghq import FactorySpecs @@ -98,14 +98,14 @@ def exchangeElevators(self): def startNextFloor(self): if self.avIds: - print self.avIds + print((self.avIds)) self.currentFloor += 1 specModule = self.layout.getFloorSpec(self.currentFloor) self.level.requestDelete() self.level = DistributedLawOfficeFloorAI.DistributedLawOfficeFloorAI(self.air, self.lawOfficeId, self.zoneId, self.entranceId, self.avIds, specModule) self.level.setLevelSpec(LevelSpec.LevelSpec(specModule)) self.level.generateWithRequired(self.zoneId) - print 'exchanging elevators' + print('exchanging elevators') self.exchangeElevators() self.startSignal() diff --git a/toontown/coghq/DistributedLawOfficeElevatorExtAI.py b/toontown/coghq/DistributedLawOfficeElevatorExtAI.py index f40713b33..a63e5f020 100644 --- a/toontown/coghq/DistributedLawOfficeElevatorExtAI.py +++ b/toontown/coghq/DistributedLawOfficeElevatorExtAI.py @@ -27,7 +27,7 @@ def elevatorClosed(self): players.append(i) continue lawOfficeZone = self.bldg.createLawOffice(self.lawOfficeId, self.entranceId, players) - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] if avId: self.sendUpdateToAvatarId(avId, 'setLawOfficeInteriorZone', [lawOfficeZone]) diff --git a/toontown/coghq/DistributedLawOfficeElevatorIntAI.py b/toontown/coghq/DistributedLawOfficeElevatorIntAI.py index df11b73ec..6723944d8 100644 --- a/toontown/coghq/DistributedLawOfficeElevatorIntAI.py +++ b/toontown/coghq/DistributedLawOfficeElevatorIntAI.py @@ -25,20 +25,20 @@ def elevatorClosed(self): if i not in [None, 0]: players.append(i) sittingAvIds = [] - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] if avId: sittingAvIds.append(avId) for avId in self.avIds: if avId not in sittingAvIds: - print 'THIS AV ID %s IS NOT ON BOARD' % avId + print(('THIS AV ID %s IS NOT ON BOARD' % avId)) self.bldg.startNextFloor() else: self.notify.warning('The elevator left, but was empty.') self.fsm.request('closed') def enterClosed(self): - print 'DistributedLawOfficeElevatorIntAI.elevatorClosed %s' % self.doId + print(('DistributedLawOfficeElevatorIntAI.elevatorClosed %s' % self.doId)) DistributedElevatorFloorAI.DistributedElevatorFloorAI.enterClosed(self) if not (self.hasOpenedLocked) or not (self.isLocked): self.fsm.request('opening') diff --git a/toontown/coghq/DistributedLawOfficeFloor.py b/toontown/coghq/DistributedLawOfficeFloor.py index 8dc3026c7..ad494fb5e 100644 --- a/toontown/coghq/DistributedLawOfficeFloor.py +++ b/toontown/coghq/DistributedLawOfficeFloor.py @@ -96,7 +96,7 @@ def handleFirstSetZoneDone(): def printPos(self = self): pos = base.localAvatar.getPos(self.getZoneNode(self.lastToonZone)) h = base.localAvatar.getH(self.getZoneNode(self.lastToonZone)) - print 'factory pos: %s, h: %s, zone %s' % (repr(pos), h, self.lastToonZone) + print(('factory pos: %s, h: %s, zone %s' % (repr(pos), h, self.lastToonZone))) posStr = 'X: %.3f' % pos[0] + '\nY: %.3f' % pos[1] + '\nZ: %.3f' % pos[2] + '\nH: %.3f' % h + '\nZone: %s' % str(self.lastToonZone) base.localAvatar.setChat(posStr, CFThought, 0) diff --git a/toontown/coghq/DistributedLawOfficeFloorAI.py b/toontown/coghq/DistributedLawOfficeFloorAI.py index afb85d836..a1a75c31c 100644 --- a/toontown/coghq/DistributedLawOfficeFloorAI.py +++ b/toontown/coghq/DistributedLawOfficeFloorAI.py @@ -1,4 +1,4 @@ -import cPickle +import pickle from toontown.coghq import CogDisguiseGlobals from toontown.coghq import FactoryEntityCreatorAI from toontown.coghq import FactorySpecs diff --git a/toontown/coghq/DistributedLawbotBossGavel.py b/toontown/coghq/DistributedLawbotBossGavel.py index 7199d7c70..2c0948d7e 100644 --- a/toontown/coghq/DistributedLawbotBossGavel.py +++ b/toontown/coghq/DistributedLawbotBossGavel.py @@ -135,7 +135,7 @@ def enterOn(self): seqName = 'LawbotBossGavel-%s' % self.doId self.ival = Sequence(name=seqName) downAngle = -80 - for index in xrange(len(myHeadings)): + for index in range(len(myHeadings)): nextIndex = index + 1 if nextIndex == len(myHeadings): nextIndex = 0 diff --git a/toontown/coghq/DistributedLawbotCannon.py b/toontown/coghq/DistributedLawbotCannon.py index e10b6c214..b93e452d4 100644 --- a/toontown/coghq/DistributedLawbotCannon.py +++ b/toontown/coghq/DistributedLawbotCannon.py @@ -269,7 +269,7 @@ def __makeGui(self): if self.flashingLabel: self.flashingLabel.stop() flashingTrack = Sequence() - for i in xrange(10): + for i in range(10): flashingTrack.append(LerpColorScaleInterval(self.cannonBallLabel, 0.5, VBase4(1, 0, 0, 1))) flashingTrack.append(LerpColorScaleInterval(self.cannonBallLabel, 0.5, VBase4(1, 1, 1, 1))) @@ -771,7 +771,7 @@ def __handleCannonHit(self, collisionEntry): if self.localToonShooting: pass chairlist = ['trigger-chair'] - for index in xrange(len(ToontownGlobals.LawbotBossChairPosHprs)): + for index in range(len(ToontownGlobals.LawbotBossChairPosHprs)): chairlist.append('Chair-%s' % index) if hitNode in chairlist: diff --git a/toontown/coghq/DistributedLawbotChair.py b/toontown/coghq/DistributedLawbotChair.py index ed57b938a..73a8408e0 100644 --- a/toontown/coghq/DistributedLawbotChair.py +++ b/toontown/coghq/DistributedLawbotChair.py @@ -310,7 +310,7 @@ def enterOn(self): seqName = 'LawbotBossChair-%s' % self.doId self.ival = Sequence(name=seqName) downAngle = -80 - for index in xrange(len(myHeadings)): + for index in range(len(myHeadings)): nextIndex = index + 1 if nextIndex == len(myHeadings): nextIndex = 0 diff --git a/toontown/coghq/DistributedLevelBattle.py b/toontown/coghq/DistributedLevelBattle.py index c262985c3..331efecdf 100644 --- a/toontown/coghq/DistributedLevelBattle.py +++ b/toontown/coghq/DistributedLevelBattle.py @@ -35,8 +35,8 @@ def doPlacement(levelList, self = self): spec = self.level.getBattleCellSpec(self.battleCellId) self.level.requestReparent(self, spec['parentEntId']) self.setPos(spec['pos']) - print 'spec = %s' % spec - print 'h = %s' % spec.get('h') + print(('spec = %s' % spec)) + print(('h = %s' % spec.get('h'))) self.wrtReparentTo(render) return diff --git a/toontown/coghq/DistributedLift.py b/toontown/coghq/DistributedLift.py index 1e041cad0..f73352c90 100644 --- a/toontown/coghq/DistributedLift.py +++ b/toontown/coghq/DistributedLift.py @@ -82,7 +82,7 @@ def initPlatform(self): 'back': '**/wall_back', 'left': '**/wall_left', 'right': '**/wall_right'} - for side in side2srch.values(): + for side in list(side2srch.values()): np = self.platformModel.find(side) if not np.isEmpty(): np.setScale(1.0, 1.0, 2.0) diff --git a/toontown/coghq/DistributedMaze.py b/toontown/coghq/DistributedMaze.py index 491747550..e3208389e 100644 --- a/toontown/coghq/DistributedMaze.py +++ b/toontown/coghq/DistributedMaze.py @@ -70,7 +70,7 @@ def gotRoom(self, rooms): 270] self.getRng().shuffle(rotations) self.numSections = 0 - for i in xrange(0, 4): + for i in range(0, 4): maze = room.getGeom().find('**/Maze_Inside_%d' % i) if not maze.isEmpty(): self.numSections += 1 diff --git a/toontown/coghq/DistributedMint.py b/toontown/coghq/DistributedMint.py index 3e6829c2d..2c2b77764 100644 --- a/toontown/coghq/DistributedMint.py +++ b/toontown/coghq/DistributedMint.py @@ -166,7 +166,7 @@ def setBossConfronted(self, avId): base.localAvatar.setSystemMessage(avId, TTLocalizer.MintBossConfrontedMsg % av.getName()) def warpToRoom(self, roomId): - for i in xrange(len(self.rooms)): + for i in range(len(self.rooms)): room = self.rooms[i] if room.roomId == roomId: break diff --git a/toontown/coghq/DistributedMintAI.py b/toontown/coghq/DistributedMintAI.py index b670602b7..5aa6f3f29 100644 --- a/toontown/coghq/DistributedMintAI.py +++ b/toontown/coghq/DistributedMintAI.py @@ -21,7 +21,7 @@ def generate(self): self.layout = MintLayout.MintLayout(self.mintId, self.floorNum) self.rooms = [] self.battleExpAggreg = BattleExperienceAggregatorAI.BattleExperienceAggregatorAI() - for i in xrange(self.layout.getNumRooms()): + for i in range(self.layout.getNumRooms()): room = DistributedMintRoomAI.DistributedMintRoomAI(self.air, self.mintId, self.doId, self.zoneId, self.layout.getRoomId(i), i * 2, self.avIds, self.battleExpAggreg) room.generateWithRequired(self.zoneId) self.rooms.append(room) diff --git a/toontown/coghq/DistributedMintElevatorExtAI.py b/toontown/coghq/DistributedMintElevatorExtAI.py index b460af2b1..5ea4e5940 100644 --- a/toontown/coghq/DistributedMintElevatorExtAI.py +++ b/toontown/coghq/DistributedMintElevatorExtAI.py @@ -34,7 +34,7 @@ def elevatorClosed(self): players.append(i) mintZone = self.bldg.createMint(self.mintId, players) - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] if avId: self.sendUpdateToAvatarId(avId, 'setMintInteriorZone', [mintZone]) diff --git a/toontown/coghq/DistributedMintRoom.py b/toontown/coghq/DistributedMintRoom.py index 24c34e9dd..950169fa5 100644 --- a/toontown/coghq/DistributedMintRoom.py +++ b/toontown/coghq/DistributedMintRoom.py @@ -151,7 +151,7 @@ def printPos(self = self): pos = base.localAvatar.getPos(thisZone) h = base.localAvatar.getH(thisZone) roomName = MintRoomSpecs.CashbotMintRoomId2RoomName[self.roomId] - print 'mint pos: %s, h: %s, room: %s' % (repr(pos), h, roomName) + print(('mint pos: %s, h: %s, room: %s' % (repr(pos), h, roomName))) if self.mint is not None: floorNum = self.mint.floorNum else: diff --git a/toontown/coghq/DistributedMoleField.py b/toontown/coghq/DistributedMoleField.py index f1187ec19..7467505d4 100644 --- a/toontown/coghq/DistributedMoleField.py +++ b/toontown/coghq/DistributedMoleField.py @@ -44,7 +44,7 @@ def __init__(self, cr): def disable(self): self.cleanupTimer() - for ival in self.toonHitTracks.values(): + for ival in list(self.toonHitTracks.values()): ival.finish() self.toonHitTracks = {} @@ -99,8 +99,8 @@ def calcDimensions(self): def loadModel(self): moleIndex = 0 self.moleHills = [] - for indexY in xrange(self.numSquaresY): - for indexX in xrange(self.numSquaresX): + for indexY in range(self.numSquaresY): + for indexX in range(self.numSquaresX): xPos = indexX * self.spacingX yPos = indexY * self.spacingY newMoleHill = MoleHill.MoleHill(xPos, yPos, 0, self, moleIndex) @@ -339,7 +339,7 @@ def __showToonHitByBomb(self, avId, moleIndex, timestamp = 0): oldTrack.finish() toon.setPos(curPos) toon.setZ(self.getZ()) - parentNode = render.attachNewNode('mazeFlyToonParent-' + `avId`) + parentNode = render.attachNewNode('mazeFlyToonParent-' + repr(avId)) parentNode.setPos(toon.getPos(render)) toon.reparentTo(parentNode) toon.setPos(0, 0, 0) @@ -385,7 +385,7 @@ def camTask(task, zenith = zenith, flyNode = toon, startCamPos = startCamPos, ca camera.lookAt(toon) return Task.cont - camTaskName = 'mazeToonFlyCam-' + `avId` + camTaskName = 'mazeToonFlyCam-' + repr(avId) taskMgr.add(camTask, camTaskName, priority=20) def cleanupCamTask(self = self, toon = toon, camTaskName = camTaskName, startCamPos = startCamPos): diff --git a/toontown/coghq/DistributedMover.py b/toontown/coghq/DistributedMover.py index ca34ac1e2..a010c965b 100644 --- a/toontown/coghq/DistributedMover.py +++ b/toontown/coghq/DistributedMover.py @@ -111,7 +111,7 @@ def startMove(self, timeStamp): firstIVal = LerpPosHprInterval(self.moverNode, timeJump, Vec3(target.getPos(self)[0], target.getPos(self)[1], target.getPos(self)[2]), Vec3(target.getHpr(self)[0], target.getHpr(self)[1], target.getHpr(self)[2]), blendType=myBlend, fluid=1) self.moverIval.append(firstIVal) if self.cycleType in 'linear': - for linearCycle in xrange(10): + for linearCycle in range(10): self.moverIval.append(firstIVal) if self.cycleType != 'oneWay': diff --git a/toontown/coghq/DistributedSecurityCamera.py b/toontown/coghq/DistributedSecurityCamera.py index 9adc8ecb8..bef1d3c5a 100644 --- a/toontown/coghq/DistributedSecurityCamera.py +++ b/toontown/coghq/DistributedSecurityCamera.py @@ -1,6 +1,6 @@ from pandac.PandaModules import * from direct.interval.IntervalGlobal import * -from StomperGlobals import * +from .StomperGlobals import * from direct.distributed import ClockDelta from toontown.toonbase.ToonPythonUtil import lerp import math @@ -26,7 +26,7 @@ def circleY(angle, radius, centerX, centerY): def getCirclePoints(segCount, centerX, centerY, radius, wideX = 1.0, wideY = 1.0): returnShape = [] - for seg in xrange(0, int(segCount)): + for seg in range(0, int(segCount)): coordX = wideX * circleX(pi * 2.0 * float(float(seg) / float(segCount)), radius, centerX, centerY) coordY = wideY * circleY(pi * 2.0 * float(float(seg) / float(segCount)), radius, centerX, centerY) returnShape.append((coordX, coordY, 1)) @@ -153,7 +153,7 @@ def setTarget(self, targetHash): self.target = None while targetCount >= 0 and sanity > 0: sanity -= 1 - for index in xrange(1, 4): + for index in range(1, 4): if self.trackTargetList[index]: if targetCount == 0: self.target = self.trackTargetList[index] @@ -357,7 +357,7 @@ def genTrack(self): self.trackFloorTris = GeomTrifans(Geom.UHStatic) sizeTrack = len(self.trackShape) self.trackBeamTris.addVertex(0) - for countVertex in xrange(1, sizeTrack + 1): + for countVertex in range(1, sizeTrack + 1): self.trackBeamTris.addVertex(countVertex) self.trackBeamTris.addVertex(1) @@ -367,7 +367,7 @@ def genTrack(self): self.trackBeamGN.addGeom(self.trackBeamGeom) sizeTrack = len(self.trackShapeFloor) self.trackFloorTris.addVertex(0) - for countVertex in xrange(1, sizeTrack + 1): + for countVertex in range(1, sizeTrack + 1): self.trackFloorTris.addVertex(countVertex) self.trackFloorTris.addVertex(1) diff --git a/toontown/coghq/DistributedStage.py b/toontown/coghq/DistributedStage.py index e3d8fbbd1..516c1a32e 100644 --- a/toontown/coghq/DistributedStage.py +++ b/toontown/coghq/DistributedStage.py @@ -118,7 +118,7 @@ def handleCameraRayFloorCollision(collEntry, self = self): DistributedLevel.notify.warning('Invalid zone floor collision node: %s' % name) else: self.camEnterRoom(roomNum) - print collEntry + print(collEntry) self.accept('on-floor', handleCameraRayFloorCollision) if bboard.has('stageRoom'): @@ -213,7 +213,7 @@ def setBossConfronted(self, avId): return def warpToRoom(self, roomId): - for i in xrange(len(self.rooms)): + for i in range(len(self.rooms)): room = self.rooms[i] if room.roomId == roomId: break diff --git a/toontown/coghq/DistributedStageAI.py b/toontown/coghq/DistributedStageAI.py index 873008ec9..d90cf2617 100644 --- a/toontown/coghq/DistributedStageAI.py +++ b/toontown/coghq/DistributedStageAI.py @@ -28,7 +28,7 @@ def generate(self): self.rooms = [] if self.battleExpAggreg is None: self.battleExpAggreg = BattleExperienceAggregatorAI.BattleExperienceAggregatorAI() - for i in xrange(self.layout.getNumRooms()): + for i in range(self.layout.getNumRooms()): room = DistributedStageRoomAI.DistributedStageRoomAI(self.air, self.stageId, self.doId, self.zoneId, self.layout.getRoomId(i), i * 2, self.avIds, self.battleExpAggreg) room.generateWithRequired(self.zoneId) self.rooms.append(room) diff --git a/toontown/coghq/DistributedStageRoom.py b/toontown/coghq/DistributedStageRoom.py index 1aef4d04f..e8c66a618 100644 --- a/toontown/coghq/DistributedStageRoom.py +++ b/toontown/coghq/DistributedStageRoom.py @@ -151,7 +151,7 @@ def printPos(self = self): pos = base.localAvatar.getPos(thisZone) h = base.localAvatar.getH(thisZone) roomName = StageRoomSpecs.CashbotStageRoomId2RoomName[self.roomId] - print 'stage pos: %s, h: %s, room: %s' % (repr(pos), h, roomName) + print(('stage pos: %s, h: %s, room: %s' % (repr(pos), h, roomName))) if self.stage is not None: floorNum = self.stage.floorNum else: diff --git a/toontown/coghq/DistributedStomper.py b/toontown/coghq/DistributedStomper.py index c970f3422..c224df02d 100644 --- a/toontown/coghq/DistributedStomper.py +++ b/toontown/coghq/DistributedStomper.py @@ -1,6 +1,6 @@ from pandac.PandaModules import * from direct.interval.IntervalGlobal import * -from StomperGlobals import * +from .StomperGlobals import * from direct.distributed import ClockDelta from toontown.toonbase.ToonPythonUtil import lerp import math @@ -110,11 +110,11 @@ def loadModel(self): if self.removeHeadFloor: floorHeadNp.stash() else: - for i in xrange(floorHead.getNumSolids()): + for i in range(floorHead.getNumSolids()): floorHead.modifySolid(i).setEffectiveNormal(Vec3(0.0, -1.0, 0.0)) floorShaft = model.find('**/shaft_collisions/**/collDownFloor').node() - for i in xrange(floorShaft.getNumSolids()): + for i in range(floorShaft.getNumSolids()): floorShaft.modifySolid(i).setEffectiveNormal(Vec3(0.0, -1.0, 0.0)) self.accept(self.crushMsg, self.checkSquashedToon) diff --git a/toontown/coghq/DistributedStomperPair.py b/toontown/coghq/DistributedStomperPair.py index 2a16233df..d04f5a782 100644 --- a/toontown/coghq/DistributedStomperPair.py +++ b/toontown/coghq/DistributedStomperPair.py @@ -36,7 +36,7 @@ def listenForChildren(self): def checkSquashedToon(self): tPos = base.localAvatar.getPos(self) - print 'tpos = %s' % tPos + print(('tpos = %s' % tPos)) yRange = 3.0 xRange = 3.0 if tPos[1] < yRange and tPos[1] > -yRange and tPos[0] < xRange and tPos[0] > -xRange: diff --git a/toontown/coghq/FactoryBase.py b/toontown/coghq/FactoryBase.py index 106273d43..108f9a3ff 100644 --- a/toontown/coghq/FactoryBase.py +++ b/toontown/coghq/FactoryBase.py @@ -21,7 +21,7 @@ def getFactoryType(self): if __dev__: def getEntityTypeReg(self): - import FactoryEntityTypes + from . import FactoryEntityTypes from otp.level import EntityTypeRegistry typeReg = EntityTypeRegistry.EntityTypeRegistry(FactoryEntityTypes) return typeReg diff --git a/toontown/coghq/FactoryCameraViews.py b/toontown/coghq/FactoryCameraViews.py index 884360fef..beed79f8a 100644 --- a/toontown/coghq/FactoryCameraViews.py +++ b/toontown/coghq/FactoryCameraViews.py @@ -24,7 +24,7 @@ def __init__(self, factory): Point3(0.0, 1.5, -3.9375), 1), []]] camHeight = av.getClampedAvatarHeight() - for i in xrange(len(self.views)): + for i in range(len(self.views)): camPos = self.views[i][1] av.auxCameraPositions.append(camPos) factory.accept('enter' + self.views[i][0], Functor(self.switchCamPos, i)) @@ -34,7 +34,7 @@ def __init__(self, factory): return def delete(self): - for i in xrange(len(self.views)): + for i in range(len(self.views)): base.localAvatar.auxCameraPositions.remove(self.views[i][1]) self.factory.ignore('enter' + self.views[i][0]) self.factory.ignore('exit' + self.views[i][0]) diff --git a/toontown/coghq/FactoryEntityCreator.py b/toontown/coghq/FactoryEntityCreator.py index 59d54a9f0..b0b5a39e2 100644 --- a/toontown/coghq/FactoryEntityCreator.py +++ b/toontown/coghq/FactoryEntityCreator.py @@ -19,43 +19,43 @@ class FactoryEntityCreator(EntityCreator.EntityCreator): def __init__(self, level): EntityCreator.EntityCreator.__init__(self, level) nothing = EntityCreator.nothing - nonlocal = EntityCreator.nonlocal - self.privRegisterTypes({'activeCell': nonlocal, - 'crusherCell': nonlocal, - 'battleBlocker': nonlocal, - 'beanBarrel': nonlocal, - 'button': nonlocal, + _nonlocal = EntityCreator._nonlocal + self.privRegisterTypes({'activeCell': _nonlocal, + 'crusherCell': _nonlocal, + 'battleBlocker': _nonlocal, + 'beanBarrel': _nonlocal, + 'button': _nonlocal, 'conveyorBelt': ConveyorBelt.ConveyorBelt, - 'crate': nonlocal, - 'door': nonlocal, - 'directionalCell': nonlocal, - 'gagBarrel': nonlocal, + 'crate': _nonlocal, + 'door': _nonlocal, + 'directionalCell': _nonlocal, + 'gagBarrel': _nonlocal, 'gear': GearEntity.GearEntity, - 'goon': nonlocal, - 'gridGoon': nonlocal, - 'golfGreenGame': nonlocal, + 'goon': _nonlocal, + 'gridGoon': _nonlocal, + 'golfGreenGame': _nonlocal, 'goonClipPlane': GoonClipPlane.GoonClipPlane, - 'grid': nonlocal, - 'healBarrel': nonlocal, + 'grid': _nonlocal, + 'healBarrel': _nonlocal, 'levelMgr': FactoryLevelMgr.FactoryLevelMgr, - 'lift': nonlocal, + 'lift': _nonlocal, 'mintProduct': MintProduct.MintProduct, 'mintProductPallet': MintProductPallet.MintProductPallet, 'mintShelf': MintShelf.MintShelf, 'boardOfficeProduct': BoardOfficeProduct.BoardOfficeProduct, 'boardOfficeProductPallet': BoardOfficeProductPallet.BoardOfficeProductPallet, 'boardOfficeShelf': BoardOfficeShelf.BoardOfficeShelf, - 'mover': nonlocal, + 'mover': _nonlocal, 'paintMixer': PaintMixer.PaintMixer, 'pathMaster': PathMasterEntity.PathMasterEntity, 'rendering': RenderingEntity.RenderingEntity, 'platform': PlatformEntity.PlatformEntity, - 'sinkingPlatform': nonlocal, - 'stomper': nonlocal, - 'stomperPair': nonlocal, - 'laserField': nonlocal, - 'securityCamera': nonlocal, - 'elevatorMarker': nonlocal, - 'trigger': nonlocal, - 'moleField': nonlocal, - 'maze': nonlocal}) + 'sinkingPlatform': _nonlocal, + 'stomper': _nonlocal, + 'stomperPair': _nonlocal, + 'laserField': _nonlocal, + 'securityCamera': _nonlocal, + 'elevatorMarker': _nonlocal, + 'trigger': _nonlocal, + 'moleField': _nonlocal, + 'maze': _nonlocal}) diff --git a/toontown/coghq/FactoryExterior.py b/toontown/coghq/FactoryExterior.py index fdf12fb84..b868239de 100644 --- a/toontown/coghq/FactoryExterior.py +++ b/toontown/coghq/FactoryExterior.py @@ -72,19 +72,19 @@ def enter(self, requestStatus): # Collect all of the vis group zone IDs: self.zoneVisDict = {} - for i in xrange(dnaStore.getNumDNAVisGroupsAI()): + for i in range(dnaStore.getNumDNAVisGroupsAI()): groupFullName = dnaStore.getDNAVisGroupName(i) visGroup = dnaStore.getDNAVisGroupAI(i) visZoneId = int(base.cr.hoodMgr.extractGroupName(groupFullName)) visZoneId = ZoneUtil.getTrueZoneId(visZoneId, self.zoneId) visibles = [] - for i in xrange(visGroup.getNumVisibles()): + for i in range(visGroup.getNumVisibles()): visibles.append(int(visGroup.visibles[i])) visibles.append(ZoneUtil.getBranchZone(visZoneId)) self.zoneVisDict[visZoneId] = visibles # Next, we want interest in all vis groups due to this being a Cog HQ: - base.cr.sendSetZoneMsg(self.zoneId, self.zoneVisDict.values()[0]) + base.cr.sendSetZoneMsg(self.zoneId, list(self.zoneVisDict.values())[0]) BattlePlace.BattlePlace.enter(self) self.fsm.enterInitialState() diff --git a/toontown/coghq/FactorySpecs.py b/toontown/coghq/FactorySpecs.py index 3e0eed896..7c7e6af23 100644 --- a/toontown/coghq/FactorySpecs.py +++ b/toontown/coghq/FactorySpecs.py @@ -17,7 +17,7 @@ def getCogSpecModule(factoryId): CogSpecModules = {ToontownGlobals.SellbotFactoryInt: SellbotLegFactoryCogs, ToontownGlobals.LawbotOfficeInt: LawbotLegFactoryCogs} if __dev__: - import FactoryMockupSpec + from . import FactoryMockupSpec FactorySpecModules[ToontownGlobals.MockupFactoryId] = FactoryMockupSpec - import FactoryMockupCogs + from . import FactoryMockupCogs CogSpecModules[ToontownGlobals.MockupFactoryId] = FactoryMockupCogs diff --git a/toontown/coghq/InGameEditor.py b/toontown/coghq/InGameEditor.py index 87bda609d..881dc3997 100644 --- a/toontown/coghq/InGameEditor.py +++ b/toontown/coghq/InGameEditor.py @@ -3,12 +3,12 @@ from direct.showbase.TkGlobal import * from direct.tkwidgets.Tree import * from direct.tkwidgets import Slider, Floater -from tkSimpleDialog import askstring -from tkMessageBox import showwarning, askyesno -from Tkinter import * +from tkinter.simpledialog import askstring +from tkinter.messagebox import showwarning, askyesno +from tkinter import * from toontown.toonbase.ToonPythonUtil import Functor, list2dict from direct.gui.DirectGui import DGG -import tkFileDialog +import tkinter.filedialog from direct.showbase import DirectObject import math import operator @@ -85,11 +85,11 @@ def createMenuBar(self): menuBar.addmenuitem('Entity', 'separator') permanentTypes = self.level.entTypeReg.getPermanentTypeNames() entTypes = list(self.level.entTypes) - map(entTypes.remove, permanentTypes) + list(map(entTypes.remove, permanentTypes)) entTypes.sort() numEntities = len(entTypes) cascadeMenu = '' - for index in xrange(numEntities): + for index in range(numEntities): type = entTypes[index] if index % 10 == 0: lastIndex = min(index + 9, numEntities - 1) @@ -355,7 +355,7 @@ def addChoiceWidget(self, levelSpec, entSpec, entId, attribName, params): attribDesc = typeDesc.getAttribDescDict()[attribName] attributeValue = attribDesc.getDefaultValue() valueDict = params.get('valueDict', {}) - for key, value in valueDict.items(): + for key, value in list(valueDict.items()): if value == attributeValue: attributeValue = key break @@ -371,10 +371,10 @@ def radioCommand(radioVar = radioVar): label = Label(frame, text=attribName, width=15, anchor=W, justify=LEFT) label.pack(side=LEFT, expand=0) for choice in params.get('choiceSet', []): - if type(choice) is types.StringType: + if type(choice) is bytes: choiceStr = choice else: - choiceStr = `choice` + choiceStr = repr(choice) if choiceStr not in valueDict: valueDict[choiceStr] = choice choiceButton = Radiobutton(frame, text=choiceStr, value=choiceStr, variable=radioVar, command=radioCommand) @@ -384,7 +384,7 @@ def radioCommand(radioVar = radioVar): self.attribWidgets.append(frame) def setRadioVar(attributeValue): - for key, value in valueDict.items(): + for key, value in list(valueDict.items()): if value == attributeValue: attributeValue = key break @@ -410,22 +410,22 @@ def addMultiChoiceWidget(self, levelSpec, entSpec, entId, attribName, params): def cbCommand(var, trueValue = trueValue): vd = self.cbDict[attribName] - print vd + print(vd) if var.get(): - print 'got it', trueValue, vd + print(('got it', trueValue, vd)) vd[trueValue] = 1 else: - print 'not it', trueValue, vd + print(('not it', trueValue, vd)) if trueValue in vd: del vd[trueValue] - value = vd.keys() - print 'SENDING', value + value = list(vd.keys()) + print(('SENDING', value)) self.level.setAttribEdit(entId, attribName, value) - if type(choice) is types.StringType: + if type(choice) is bytes: labelStr = choice else: - labelStr = `choice` + labelStr = repr(choice) func = Functor(cbCommand, cbVar) choiceButton = Checkbutton(frame, text=labelStr, variable=cbVar, command=lambda : func()) choiceButton.pack(side=LEFT, expand=0) @@ -435,8 +435,8 @@ def cbCommand(var, trueValue = trueValue): self.attribWidgets.append(frame) def setCheckbuttonVar(attributeValueList): - print 'COMING BACK', attributeValueList - for attributeValue, cb in checkbuttonDict.items(): + print(('COMING BACK', attributeValueList)) + for attributeValue, cb in list(checkbuttonDict.items()): if attributeValue in attributeValueList: cb.set(1) else: @@ -542,7 +542,7 @@ def askFilename(callback = handleReturn): initialDir = Filename.expandFrom('$TTMODELS/built/').toOsSpecific() else: initialDir = Filename.expandFrom('$TTMODELS/built/%s' % text.get()[1:-1]).toOsSpecific() - print text, text.get()[1:-1], initialDir + print((text, text.get()[1:-1], initialDir)) rawFilename = askopenfilename(defaultextension='*', initialdir=initialDir, filetypes=(('Bam Files', '*.bam'), ('Egg Files', '*.egg'), ('Maya Binaries', '*.mb'), @@ -550,7 +550,7 @@ def askFilename(callback = handleReturn): if rawFilename != '': filename = Filename.fromOsSpecific(rawFilename) filename.findOnSearchpath(getModelPath().getValue()) - text.set("'%s'" % `filename`) + text.set("'%s'" % repr(filename)) handleReturn(None) return @@ -657,10 +657,10 @@ def handleMenu(id): idDict[eType] = self.level.entType2ids.get(eType, []) else: - for eType in self.level.entType2ids.keys(): + for eType in list(self.level.entType2ids.keys()): idDict[eType] = self.level.entType2ids.get(eType, []) - typeKeys = idDict.keys() + typeKeys = list(idDict.keys()) typeKeys.sort() def getChildEntIds(entity): @@ -787,7 +787,7 @@ def onDestroy(self, event): self.ignore('DIRECT_manipulateObjectCleanup') self.ignore('DIRECT_undo') self.ignore('DIRECT_redo') - print 'InGameEditor.onDestroy()' + print('InGameEditor.onDestroy()') if self.visZonesEditor: self.visZonesEditor.destroy() self.explorer._node.destroy() @@ -798,7 +798,7 @@ def handleRequestSave(self): messenger.send(self.requestSaveEvent) def handleSaveAs(self): - filename = tkFileDialog.asksaveasfilename(parent=self.parent, defaultextension='.py', filetypes=[('Python Source Files', '.py'), ('All Files', '*')]) + filename = tkinter.filedialog.asksaveasfilename(parent=self.parent, defaultextension='.py', filetypes=[('Python Source Files', '.py'), ('All Files', '*')]) if len(filename) > 0: messenger.send(self.saveAsEvent, [filename]) diff --git a/toontown/coghq/LaserGameAvoid.py b/toontown/coghq/LaserGameAvoid.py index b43d0cb40..3ff945ad6 100644 --- a/toontown/coghq/LaserGameAvoid.py +++ b/toontown/coghq/LaserGameAvoid.py @@ -39,8 +39,8 @@ def endTask(self): def startGrid(self): LaserGameBase.LaserGameBase.startGrid(self) - for column in xrange(0, self.gridNumX): - for row in xrange(0, self.gridNumY): + for column in range(0, self.gridNumX): + for row in range(0, self.gridNumY): tile = random.choice([ 0, 14, @@ -55,8 +55,8 @@ def _LaserGameAvoid__cycle(self, taskMgrFooler = 0): if not hasattr(self, 'gridNumX'): return Task.done - for column in xrange(0, self.gridNumX): - for row in xrange(0, self.gridNumY): + for column in range(0, self.gridNumX): + for row in range(0, self.gridNumY): if self.gridData[column][row] == 0: tile = random.choice([ 0, diff --git a/toontown/coghq/LaserGameBase.py b/toontown/coghq/LaserGameBase.py index a678bca21..eab74f780 100644 --- a/toontown/coghq/LaserGameBase.py +++ b/toontown/coghq/LaserGameBase.py @@ -28,7 +28,7 @@ def setGridSize(self, x, y): def blankGrid(self): self.gridData = [] - for i in xrange(0, self.gridNumX): + for i in range(0, self.gridNumX): self.gridData.append([ 0] * self.gridNumY) diff --git a/toontown/coghq/LaserGameDrag.py b/toontown/coghq/LaserGameDrag.py index 5476ca7f9..3d64fd750 100644 --- a/toontown/coghq/LaserGameDrag.py +++ b/toontown/coghq/LaserGameDrag.py @@ -28,11 +28,11 @@ def lose(self): def startGrid(self): LaserGameBase.LaserGameBase.startGrid(self) - for column in xrange(0, self.gridNumX): - for row in xrange(0, self.gridNumY): + for column in range(0, self.gridNumX): + for row in range(0, self.gridNumY): tile = 0 self.gridData[column][row] = tile - for column in xrange(0, self.gridNumX): + for column in range(0, self.gridNumX): self.gridData[column][self.gridNumY - 1] = 12 for symbol in self.symbolList: finished = 0 @@ -75,8 +75,8 @@ def hit(self, hitX, hitY, oldx = -1, oldy = -1): def checkFor3(self, index): numInARow = 0 - for posX in xrange(0, self.gridNumX): - for posY in xrange(0, self.gridNumY): + for posX in range(0, self.gridNumX): + for posY in range(0, self.gridNumY): if self.gridData[posX][posY] == index: numInARow += 1 if numInARow >= 3: @@ -86,8 +86,8 @@ def checkFor3(self, index): numInARow = 0 numInARow = 0 - for posY in xrange(0, self.gridNumY): - for posX in xrange(0, self.gridNumX): + for posY in range(0, self.gridNumY): + for posX in range(0, self.gridNumX): if self.gridData[posX][posY] == index: numInARow += 1 if numInARow >= 3: @@ -98,14 +98,14 @@ def checkFor3(self, index): return 0 def clearIndex(self, index): - for posX in xrange(0, self.gridNumX): - for posY in xrange(0, self.gridNumY): + for posX in range(0, self.gridNumX): + for posY in range(0, self.gridNumY): if self.gridData[posX][posY] == index: self.gridData[posX][posY] = 0 def checkForClear(self, index): - for posX in xrange(0, self.gridNumX): - for posY in xrange(0, self.gridNumY): + for posX in range(0, self.gridNumX): + for posY in range(0, self.gridNumY): if self.gridData[posX][posY] == index: return 0 return 1 diff --git a/toontown/coghq/LaserGameMineSweeper.py b/toontown/coghq/LaserGameMineSweeper.py index 0f0847775..1987b28f2 100644 --- a/toontown/coghq/LaserGameMineSweeper.py +++ b/toontown/coghq/LaserGameMineSweeper.py @@ -30,7 +30,7 @@ def lose(self): def startGrid(self): LaserGameBase.LaserGameBase.startGrid(self) self.hiddenData = [] - for i in xrange(0, self.gridNumX): + for i in range(0, self.gridNumX): self.hiddenData.append([ 0] * self.gridNumY) @@ -48,8 +48,8 @@ def startGrid(self): bomb += 1 continue - for column in xrange(0, self.gridNumX): - for row in xrange(0, self.gridNumY): + for column in range(0, self.gridNumX): + for row in range(0, self.gridNumY): if self.hiddenData[column][row] == 12: self.gridData[column][row] = 11 continue @@ -70,8 +70,8 @@ def hit(self, hitX, hitY, oldx = -1, oldy = -1): def revealAll(self): - for column in xrange(0, self.gridNumX): - for row in xrange(0, self.gridNumY): + for column in range(0, self.gridNumX): + for row in range(0, self.gridNumY): self.neighborReveal(column, row, 1) @@ -115,7 +115,7 @@ def neighborReveal(self, hitX, hitY, showBomb = 0): def rowSum(self, y): sum = 0 - for i in xrange(0, self.gridNumX - 1): + for i in range(0, self.gridNumX - 1): if self.hiddenData[i][y] == 12: sum += 1 continue diff --git a/toontown/coghq/LaserGameRoll.py b/toontown/coghq/LaserGameRoll.py index a33d3260a..330cee5e6 100644 --- a/toontown/coghq/LaserGameRoll.py +++ b/toontown/coghq/LaserGameRoll.py @@ -27,15 +27,15 @@ def lose(self): def startGrid(self): LaserGameBase.LaserGameBase.startGrid(self) - for column in xrange(0, self.gridNumX): - for row in xrange(0, self.gridNumY): + for column in range(0, self.gridNumX): + for row in range(0, self.gridNumY): tile = random.choice([ 10, 13]) self.gridData[column][row] = tile - for column in xrange(0, self.gridNumX): + for column in range(0, self.gridNumX): self.gridData[column][self.gridNumY - 1] = 12 @@ -58,8 +58,8 @@ def hit(self, hitX, hitY, oldx = -1, oldy = -1): def checkForWin(self): count1 = 0 count2 = 0 - for column in xrange(0, self.gridNumX): - for row in xrange(0, self.gridNumY): + for column in range(0, self.gridNumX): + for row in range(0, self.gridNumY): if self.gridData[column][row] == 10: count1 += 1 continue diff --git a/toontown/coghq/LawOfficeFloorSpecs.py b/toontown/coghq/LawOfficeFloorSpecs.py index 2cd64c177..5da87a5a0 100644 --- a/toontown/coghq/LawOfficeFloorSpecs.py +++ b/toontown/coghq/LawOfficeFloorSpecs.py @@ -21,14 +21,14 @@ def getNumBattles(floorId): LawbotOfficeEntranceIDs = (0, 1) LawbotOfficeFloorIDs = (0, 1) LawbotOfficeSpecModules = {} -for roomName, roomId in LawbotOfficeFloorName2FloorId.items(): +for roomName, roomId in list(LawbotOfficeFloorName2FloorId.items()): LawbotOfficeSpecModules[roomId] = __import__('toontown.coghq.' + roomName) CogSpecModules = { 'CashbotMintBoilerRoom_Battle00': LabotOfficeFloor_01a_Cogs, 'CashbotMintBoilerRoom_Battle01': LabotOfficeFloor_01b_Cogs } floorId2numBattles = { } -for (roomName, roomId) in LawbotOfficeFloorName2FloorId.items(): +for (roomName, roomId) in list(LawbotOfficeFloorName2FloorId.items()): if roomName not in CogSpecModules: floorId2numBattles[roomId] = 0 continue diff --git a/toontown/coghq/LawOfficeLayout.py b/toontown/coghq/LawOfficeLayout.py index a6438c10f..42726ba30 100644 --- a/toontown/coghq/LawOfficeLayout.py +++ b/toontown/coghq/LawOfficeLayout.py @@ -12,7 +12,7 @@ 0: 'LawOffice_Spec_Tier0_a', 1: 'LawOffice_Spec_Tier0_b' } LawbotFloorSpecs = {} -for floorIndex, floorSpec in Index2Spec.items(): +for floorIndex, floorSpec in list(Index2Spec.items()): LawbotFloorSpecs[floorIndex] = __import__('toontown.coghq.' + floorSpec) diff --git a/toontown/coghq/LawOfficeManagerAI.py b/toontown/coghq/LawOfficeManagerAI.py index 69b27fe26..c97da7f60 100644 --- a/toontown/coghq/LawOfficeManagerAI.py +++ b/toontown/coghq/LawOfficeManagerAI.py @@ -35,7 +35,7 @@ def createLawOffice(self, StageId, entranceId, players): if bboard.has('stageRoom-%s' % avId): roomId = bboard.get('stageRoom-%s' % avId) for lt in StageId2Layouts[StageId]: - for i in xrange(StageLayout.getNumFloors(lt)): + for i in range(StageLayout.getNumFloors(lt)): layout = StageLayout.StageLayout(StageId, i, stageLayout = lt) if roomId in layout.getRoomIds(): layoutIndex = lt diff --git a/toontown/coghq/LawbotHQExterior.py b/toontown/coghq/LawbotHQExterior.py index 126c5b3c2..2e78c1dc8 100644 --- a/toontown/coghq/LawbotHQExterior.py +++ b/toontown/coghq/LawbotHQExterior.py @@ -22,16 +22,16 @@ def enter(self, requestStatus): # Collect all of the vis group zone IDs: self.zoneVisDict = {} - for i in xrange(dnaStore.getNumDNAVisGroupsAI()): + for i in range(dnaStore.getNumDNAVisGroupsAI()): groupFullName = dnaStore.getDNAVisGroupName(i) visGroup = dnaStore.getDNAVisGroupAI(i) visZoneId = int(base.cr.hoodMgr.extractGroupName(groupFullName)) visZoneId = ZoneUtil.getTrueZoneId(visZoneId, self.zoneId) visibles = [] - for i in xrange(visGroup.getNumVisibles()): + for i in range(visGroup.getNumVisibles()): visibles.append(int(visGroup.visibles[i])) visibles.append(ZoneUtil.getBranchZone(visZoneId)) self.zoneVisDict[visZoneId] = visibles # Next, we want interest in all vis groups due to this being a Cog HQ: - base.cr.sendSetZoneMsg(self.zoneId, self.zoneVisDict.values()[0]) + base.cr.sendSetZoneMsg(self.zoneId, list(self.zoneVisDict.values())[0]) diff --git a/toontown/coghq/LawbotOfficeBoilerRoom_Action01_Cogs.py b/toontown/coghq/LawbotOfficeBoilerRoom_Action01_Cogs.py index b3392ef39..fb539a76d 100644 --- a/toontown/coghq/LawbotOfficeBoilerRoom_Action01_Cogs.py +++ b/toontown/coghq/LawbotOfficeBoilerRoom_Action01_Cogs.py @@ -1,4 +1,4 @@ -from SpecImports import * +from .SpecImports import * from toontown.toonbase import ToontownGlobals import random CogParent = 20000 diff --git a/toontown/coghq/LevelBattleManagerAI.py b/toontown/coghq/LevelBattleManagerAI.py index 12d709c41..5d897ff56 100644 --- a/toontown/coghq/LevelBattleManagerAI.py +++ b/toontown/coghq/LevelBattleManagerAI.py @@ -15,11 +15,11 @@ def __init__(self, air, level, battleCtor, battleExpAggreg = None): self.battleExpAggreg = battleExpAggreg def destroyBattleMgr(self): - battles = self.cellId2battle.values() + battles = list(self.cellId2battle.values()) for battle in battles: self.destroy(battle) - for cellId, battleBlocker in self.battleBlockers.items(): + for cellId, battleBlocker in list(self.battleBlockers.items()): if battleBlocker is not None: battleBlocker.deactivate() diff --git a/toontown/coghq/LevelSuitPlannerAI.py b/toontown/coghq/LevelSuitPlannerAI.py index dbf03bf10..bfbd2ab73 100644 --- a/toontown/coghq/LevelSuitPlannerAI.py +++ b/toontown/coghq/LevelSuitPlannerAI.py @@ -22,7 +22,7 @@ def __init__(self, air, level, cogCtor, battleCtor, cogSpecs, reserveCogSpecs, b self.__genSuitInfos(self.level.getCogLevel(), self.level.getCogTrack()) self.battleMgr = LevelBattleManagerAI.LevelBattleManagerAI(self.air, self.level, battleCtor, battleExpAggreg) self.battleCellId2suits = {} - for id in self.battleCellSpecs.keys(): + for id in list(self.battleCellSpecs.keys()): self.battleCellId2suits[id] = [] def destroy(self): @@ -37,7 +37,7 @@ def destroy(self): def __genJoinChances(self, num): joinChances = [] - for currChance in xrange(num): + for currChance in range(num): joinChances.append(random.randint(1, 100)) joinChances.sort(cmp) @@ -60,14 +60,14 @@ def getSuitDict(spec, cogId, level = level, track = track): self.suitInfos = {} self.suitInfos['activeSuits'] = [] - for i in xrange(len(self.cogSpecs)): + for i in range(len(self.cogSpecs)): spec = self.cogSpecs[i] self.suitInfos['activeSuits'].append(getSuitDict(spec, i)) numReserve = len(self.reserveCogSpecs) joinChances = self.__genJoinChances(numReserve) self.suitInfos['reserveSuits'] = [] - for i in xrange(len(self.reserveCogSpecs)): + for i in range(len(self.reserveCogSpecs)): spec = self.reserveCogSpecs[i] suitDict = getSuitDict(spec, i) suitDict['joinChance'] = joinChances[i] @@ -207,7 +207,7 @@ def suitBattleCellChange(self, suit, oldCell, newCell): if oldCell in self.battleCellId2suits: self.battleCellId2suits[oldCell].remove(suit) else: - self.notify.warning('FIXME crash bandaid suitBattleCellChange suit.doId =%s, oldCell=%s not in battleCellId2Suits.keys %s' % (suit.doId, oldCell, self.battleCellId2suits.keys())) + self.notify.warning('FIXME crash bandaid suitBattleCellChange suit.doId =%s, oldCell=%s not in battleCellId2Suits.keys %s' % (suit.doId, oldCell, list(self.battleCellId2suits.keys()))) blocker = self.battleMgr.battleBlockers.get(oldCell) if blocker: blocker.removeSuit(suit) diff --git a/toontown/coghq/MintLayout.py b/toontown/coghq/MintLayout.py index e6f5a4a40..284d9f13c 100644 --- a/toontown/coghq/MintLayout.py +++ b/toontown/coghq/MintLayout.py @@ -6,33 +6,33 @@ import random def printAllCashbotInfo(): - print 'roomId: roomName' - for roomId, roomName in MintRoomSpecs.CashbotMintRoomId2RoomName.items(): - print '%s: %s' % (roomId, roomName) + print('roomId: roomName') + for roomId, roomName in list(MintRoomSpecs.CashbotMintRoomId2RoomName.items()): + print(('%s: %s' % (roomId, roomName))) - print '\nroomId: numBattles' - for roomId, numBattles in MintRoomSpecs.roomId2numBattles.items(): - print '%s: %s' % (roomId, numBattles) + print('\nroomId: numBattles') + for roomId, numBattles in list(MintRoomSpecs.roomId2numBattles.items()): + print(('%s: %s' % (roomId, numBattles))) - print '\nmintId floor roomIds' + print('\nmintId floor roomIds') printMintRoomIds() - print '\nmintId floor numRooms' + print('\nmintId floor numRooms') printNumRooms() - print '\nmintId floor numForcedBattles' + print('\nmintId floor numForcedBattles') printNumBattles() def iterateCashbotMints(func): from toontown.toonbase import ToontownGlobals for mintId in [ToontownGlobals.CashbotMintIntA, ToontownGlobals.CashbotMintIntB, ToontownGlobals.CashbotMintIntC]: - for floorNum in xrange(ToontownGlobals.MintNumFloors[mintId]): + for floorNum in range(ToontownGlobals.MintNumFloors[mintId]): func(MintLayout(mintId, floorNum)) def printMintInfo(): def func(ml): - print ml + print(ml) iterateCashbotMints(func) @@ -40,7 +40,7 @@ def func(ml): def printMintRoomIds(): def func(ml): - print ml.getMintId(), ml.getFloorNum(), ml.getRoomIds() + print((ml.getMintId(), ml.getFloorNum(), ml.getRoomIds())) iterateCashbotMints(func) @@ -48,7 +48,7 @@ def func(ml): def printMintRoomNames(): def func(ml): - print ml.getMintId(), ml.getFloorNum(), ml.getRoomNames() + print((ml.getMintId(), ml.getFloorNum(), ml.getRoomNames())) iterateCashbotMints(func) @@ -56,7 +56,7 @@ def func(ml): def printNumRooms(): def func(ml): - print ml.getMintId(), ml.getFloorNum(), ml.getNumRooms() + print((ml.getMintId(), ml.getFloorNum(), ml.getNumRooms())) iterateCashbotMints(func) @@ -64,7 +64,7 @@ def func(ml): def printNumBattles(): def func(ml): - print ml.getMintId(), ml.getFloorNum(), ml.getNumBattles() + print((ml.getMintId(), ml.getFloorNum(), ml.getNumBattles())) iterateCashbotMints(func) @@ -723,7 +723,7 @@ def __init__(self, mintId, floorNum): self.roomIds = self._genFloorLayout() hallwayRng = self.getRng() connectorRoomNames = MintRoomSpecs.CashbotMintConnectorRooms - for i in xrange(self.numHallways): + for i in range(self.numHallways): self.hallways.append(hallwayRng.choice(connectorRoomNames)) def _genFloorLayout(self): @@ -743,7 +743,7 @@ def _genFloorLayout(self): numBattles2middleRoomIds = invertDictLossless(MintRoomSpecs.middleRoomId2numBattles) allBattleRooms = [] - for num, roomIds in numBattles2middleRoomIds.items(): + for num, roomIds in list(numBattles2middleRoomIds.items()): if num > 0: allBattleRooms.extend(roomIds) while 1: @@ -761,7 +761,7 @@ def _genFloorLayout(self): if middleRoomsLeft > 0: actionRoomIds = numBattles2middleRoomIds[0] - for i in xrange(middleRoomsLeft): + for i in range(middleRoomsLeft): roomId = rng.choice(actionRoomIds) actionRoomIds.remove(roomId) middleRoomIds.append(roomId) diff --git a/toontown/coghq/MintManagerAI.py b/toontown/coghq/MintManagerAI.py index 3b5fcbd12..7e51b7fed 100644 --- a/toontown/coghq/MintManagerAI.py +++ b/toontown/coghq/MintManagerAI.py @@ -1,5 +1,5 @@ from direct.directnotify import DirectNotifyGlobal -import DistributedMintAI +from . import DistributedMintAI from toontown.toonbase import ToontownGlobals from toontown.coghq import MintLayout from direct.showbase import DirectObject @@ -34,7 +34,7 @@ def createMint(self, mintId, players): for avId in players: if bboard.has('mintRoom-%s' % avId): roomId = bboard.get('mintRoom-%s' % avId) - for i in xrange(numFloors): + for i in range(numFloors): layout = MintLayout.MintLayout(mintId, i) if roomId in layout.getRoomIds(): floor = i diff --git a/toontown/coghq/MintRoomSpecs.py b/toontown/coghq/MintRoomSpecs.py index 2e11beb4e..1e1a431d9 100644 --- a/toontown/coghq/MintRoomSpecs.py +++ b/toontown/coghq/MintRoomSpecs.py @@ -98,7 +98,7 @@ def getNumBattles(roomId): CashbotMintFinalRoomIDs = (20, 21, 22, 23, 24, 25, 26, 27, 28) CashbotMintConnectorRooms = ('phase_10/models/cashbotHQ/connector_7cubeL2', 'phase_10/models/cashbotHQ/connector_7cubeR2') CashbotMintSpecModules = {} -for roomName, roomId in CashbotMintRoomName2RoomId.items(): +for roomName, roomId in list(CashbotMintRoomName2RoomId.items()): CashbotMintSpecModules[roomId] = locals()[roomName] CogSpecModules = {'CashbotMintBoilerRoom_Battle00': CashbotMintBoilerRoom_Battle00_Cogs, @@ -119,7 +119,7 @@ def getNumBattles(roomId): 'CashbotMintPipeRoom_Battle00': CashbotMintPipeRoom_Battle00_Cogs, 'CashbotMintPipeRoom_Battle01': CashbotMintPipeRoom_Battle01_Cogs} roomId2numBattles = {} -for roomName, roomId in CashbotMintRoomName2RoomId.items(): +for roomName, roomId in list(CashbotMintRoomName2RoomId.items()): if roomName not in CogSpecModules: roomId2numBattles[roomId] = 0 else: diff --git a/toontown/coghq/MoleFieldBase.py b/toontown/coghq/MoleFieldBase.py index 275e09beb..3bb2d52ba 100644 --- a/toontown/coghq/MoleFieldBase.py +++ b/toontown/coghq/MoleFieldBase.py @@ -31,7 +31,7 @@ def scheduleMoles(self): curTimeBetweenPopup = self.TimeBetweenPopupMax curStayUpTime = self.StayUpTimeMax curTime = 3 - eligibleMoles = range(self.numMoles) + eligibleMoles = list(range(self.numMoles)) self.getRng().shuffle(eligibleMoles) usedMoles = [] self.notify.debug('eligibleMoles=%s' % eligibleMoles) diff --git a/toontown/coghq/MovingPlatform.py b/toontown/coghq/MovingPlatform.py index 84c466d44..0e51be448 100644 --- a/toontown/coghq/MovingPlatform.py +++ b/toontown/coghq/MovingPlatform.py @@ -17,7 +17,7 @@ def setupCopyModel(self, parentToken, model, floorNodeName = None, parentingNode if floorNodeName is None: floorNodeName = 'floor' - if type(parentToken) == types.IntType: + if type(parentToken) == int: parentToken = ToontownGlobals.SPDynamic + parentToken self.parentToken = parentToken diff --git a/toontown/coghq/PathMasterEntity.py b/toontown/coghq/PathMasterEntity.py index 8778b5915..999d2e38d 100644 --- a/toontown/coghq/PathMasterEntity.py +++ b/toontown/coghq/PathMasterEntity.py @@ -134,7 +134,7 @@ def makePathTrack(self, node, velocity, name, turnTime = 1, lookAroundNode = Non track.append(WaitInterval(1.0)) return track path = self.path + [self.path[0]] - for pointIndex in xrange(len(path) - 1): + for pointIndex in range(len(path) - 1): startPoint = Point3(path[pointIndex]) * self.pathScale endPoint = Point3(path[pointIndex + 1]) * self.pathScale v = startPoint - endPoint @@ -154,7 +154,7 @@ def makePathTrackBak(self, node, velocity, name, turnTime = 1, lookAroundNode = track.append(WaitInterval(1.0)) return track path = self.path + [self.path[0]] - for pointIndex in xrange(len(path) - 1): + for pointIndex in range(len(path) - 1): startPoint = Point3(path[pointIndex]) * self.pathScale endPoint = Point3(path[pointIndex + 1]) * self.pathScale v = startPoint - endPoint diff --git a/toontown/coghq/SellbotHQExterior.py b/toontown/coghq/SellbotHQExterior.py index 3c8e94375..71c95a750 100644 --- a/toontown/coghq/SellbotHQExterior.py +++ b/toontown/coghq/SellbotHQExterior.py @@ -18,19 +18,19 @@ def enter(self, requestStatus): # Collect all of the vis group zone IDs: self.zoneVisDict = {} - for i in xrange(dnaStore.getNumDNAVisGroupsAI()): + for i in range(dnaStore.getNumDNAVisGroupsAI()): groupFullName = dnaStore.getDNAVisGroupName(i) visGroup = dnaStore.getDNAVisGroupAI(i) visZoneId = int(base.cr.hoodMgr.extractGroupName(groupFullName)) visZoneId = ZoneUtil.getTrueZoneId(visZoneId, self.zoneId) visibles = [] - for i in xrange(visGroup.getNumVisibles()): + for i in range(visGroup.getNumVisibles()): visibles.append(int(visGroup.visibles[i])) visibles.append(ZoneUtil.getBranchZone(visZoneId)) self.zoneVisDict[visZoneId] = visibles # Next, we want interest in all vis groups due to this being a Cog HQ: - base.cr.sendSetZoneMsg(self.zoneId, self.zoneVisDict.values()[0]) + base.cr.sendSetZoneMsg(self.zoneId, list(self.zoneVisDict.values())[0]) def exit(self): self.loader.hood.stopSky() diff --git a/toontown/coghq/StageLayout.py b/toontown/coghq/StageLayout.py index 840df6307..904d0cdea 100644 --- a/toontown/coghq/StageLayout.py +++ b/toontown/coghq/StageLayout.py @@ -6,33 +6,33 @@ import random def printAllCashbotInfo(): - print 'roomId: roomName' - for roomId, roomName in StageRoomSpecs.CashbotStageRoomId2RoomName.items(): - print '%s: %s' % (roomId, roomName) + print('roomId: roomName') + for roomId, roomName in list(StageRoomSpecs.CashbotStageRoomId2RoomName.items()): + print(('%s: %s' % (roomId, roomName))) - print '\nroomId: numBattles' - for roomId, numBattles in StageRoomSpecs.roomId2numBattles.items(): - print '%s: %s' % (roomId, numBattles) + print('\nroomId: numBattles') + for roomId, numBattles in list(StageRoomSpecs.roomId2numBattles.items()): + print(('%s: %s' % (roomId, numBattles))) - print '\nstageId floor roomIds' + print('\nstageId floor roomIds') printStageRoomIds() - print '\nstageId floor numRooms' + print('\nstageId floor numRooms') printNumRooms() - print '\nstageId floor numForcedBattles' + print('\nstageId floor numForcedBattles') printNumBattles() def iterateLawbotStages(func): from toontown.toonbase import ToontownGlobals - for layoutId in xrange(len(stageLayouts)): - for floorNum in xrange(getNumFloors(layoutId)): + for layoutId in range(len(stageLayouts)): + for floorNum in range(getNumFloors(layoutId)): func(StageLayout(0, floorNum, layoutId)) def printStageInfo(): def func(sl): - print sl + print(sl) iterateLawbotStages(func) @@ -46,26 +46,26 @@ def func(sl): usage[roomId] += 1 iterateLawbotStages(func) - roomIds = usage.keys() + roomIds = list(usage.keys()) roomIds.sort() for roomId in roomIds: - print '%s: %s' % (roomId, usage[roomId]) + print(('%s: %s' % (roomId, usage[roomId]))) def printRoomInfo(): - roomIds = StageRoomSpecs.roomId2numCogs.keys() + roomIds = list(StageRoomSpecs.roomId2numCogs.keys()) roomIds.sort() for roomId in roomIds: - print 'room %s: %s cogs, %s cogLevels, %s merit cogLevels' % (roomId, + print(('room %s: %s cogs, %s cogLevels, %s merit cogLevels' % (roomId, StageRoomSpecs.roomId2numCogs[roomId], StageRoomSpecs.roomId2numCogLevels[roomId], - StageRoomSpecs.roomId2numMeritCogLevels[roomId]) + StageRoomSpecs.roomId2numMeritCogLevels[roomId]))) def printStageRoomIds(): def func(ml): - print ml.getStageId(), ml.getFloorNum(), ml.getRoomIds() + print((ml.getStageId(), ml.getFloorNum(), ml.getRoomIds())) iterateCashbotStages(func) @@ -73,7 +73,7 @@ def func(ml): def printStageRoomNames(): def func(ml): - print ml.getStageId(), ml.getFloorNum(), ml.getRoomNames() + print((ml.getStageId(), ml.getFloorNum(), ml.getRoomNames())) iterateCashbotStages(func) @@ -81,7 +81,7 @@ def func(ml): def printNumRooms(): def func(ml): - print ml.getStageId(), ml.getFloorNum(), ml.getNumRooms() + print((ml.getStageId(), ml.getFloorNum(), ml.getNumRooms())) iterateCashbotStages(func) @@ -89,7 +89,7 @@ def func(ml): def printNumBattles(): def func(ml): - print ml.getStageId(), ml.getFloorNum(), ml.getNumBattles() + print((ml.getStageId(), ml.getFloorNum(), ml.getNumBattles())) iterateCashbotStages(func) @@ -628,7 +628,7 @@ def __init__(self, stageId, floorNum, stageLayout = 0): hallwayRng = self.getRng() connectorRoomNames = StageRoomSpecs.CashbotStageConnectorRooms - for i in xrange(self.numHallways): + for i in range(self.numHallways): self.hallways.append(hallwayRng.choice(connectorRoomNames)) def getNumRooms(self): diff --git a/toontown/coghq/StageRoomSpecs.py b/toontown/coghq/StageRoomSpecs.py index f186acf03..16c29d526 100644 --- a/toontown/coghq/StageRoomSpecs.py +++ b/toontown/coghq/StageRoomSpecs.py @@ -72,7 +72,7 @@ def getNumBattles(roomId): CashbotStageFinalRoomIDs = (2,) CashbotStageConnectorRooms = ('phase_11/models/lawbotHQ/LB_connector_7cubeL2', 'phase_11/models/lawbotHQ/LB_connector_7cubeLR') CashbotStageSpecModules = {} -for roomName, roomId in CashbotStageRoomName2RoomId.items(): +for roomName, roomId in list(CashbotStageRoomName2RoomId.items()): CashbotStageSpecModules[roomId] = locals()[roomName] CogSpecModules = {'LawbotOfficeOilRoom_Battle00': LawbotOfficeOilRoom_Battle00_Cogs, @@ -85,7 +85,7 @@ def getNumBattles(roomId): 'LawbotOfficeDiamondRoom_Battle00': LawbotOfficeDiamondRoom_Battle00_Cogs, 'LawbotOfficeGearRoom_Battle00': LawbotOfficeGearRoom_Battle00_Cogs} roomId2numBattles = {} -for roomName, roomId in CashbotStageRoomName2RoomId.items(): +for roomName, roomId in list(CashbotStageRoomName2RoomId.items()): if roomName not in CogSpecModules: roomId2numBattles[roomId] = 0 else: @@ -93,7 +93,7 @@ def getNumBattles(roomId): roomId2numBattles[roomId] = len(cogSpecModule.BattleCells) roomId2numCogs = {} -for roomName, roomId in CashbotStageRoomName2RoomId.items(): +for roomName, roomId in list(CashbotStageRoomName2RoomId.items()): if roomName not in CogSpecModules: roomId2numCogs[roomId] = 0 else: @@ -101,7 +101,7 @@ def getNumBattles(roomId): roomId2numCogs[roomId] = len(cogSpecModule.CogData) roomId2numCogLevels = {} -for roomName, roomId in CashbotStageRoomName2RoomId.items(): +for roomName, roomId in list(CashbotStageRoomName2RoomId.items()): if roomName not in CogSpecModules: roomId2numCogLevels[roomId] = 0 else: @@ -113,7 +113,7 @@ def getNumBattles(roomId): roomId2numCogLevels[roomId] = levels roomId2numMeritCogLevels = {} -for roomName, roomId in CashbotStageRoomName2RoomId.items(): +for roomName, roomId in list(CashbotStageRoomName2RoomId.items()): if roomName not in CogSpecModules or roomId in (8, 10): roomId2numMeritCogLevels[roomId] = 0 else: diff --git a/toontown/coghq/boardbothq/BoardOfficeLayout.py b/toontown/coghq/boardbothq/BoardOfficeLayout.py index 69f0caed2..e8d54cfae 100644 --- a/toontown/coghq/boardbothq/BoardOfficeLayout.py +++ b/toontown/coghq/boardbothq/BoardOfficeLayout.py @@ -6,33 +6,33 @@ import random def printAllBoardbotInfo(): - print 'roomId: roomName' - for roomId, roomName in BoardOfficeRoomSpecs.BoardOfficeRoomId2RoomName.items(): - print '%s: %s' % (roomId, roomName) + print('roomId: roomName') + for roomId, roomName in list(BoardOfficeRoomSpecs.BoardOfficeRoomId2RoomName.items()): + print(('%s: %s' % (roomId, roomName))) - print '\nroomId: numBattles' - for roomId, numBattles in BoardOfficeRoomSpecs.roomId2numBattles.items(): - print '%s: %s' % (roomId, numBattles) + print('\nroomId: numBattles') + for roomId, numBattles in list(BoardOfficeRoomSpecs.roomId2numBattles.items()): + print(('%s: %s' % (roomId, numBattles))) - print '\nboardofficeId floor roomIds' + print('\nboardofficeId floor roomIds') printBoardOfficeRoomIds() - print '\nboardofficeId floor numRooms' + print('\nboardofficeId floor numRooms') printNumRooms() - print '\nboardofficeId floor numForcedBattles' + print('\nboardofficeId floor numForcedBattles') printNumBattles() def iterateBoardOffices(func): from toontown.toonbase import ToontownGlobals for boardofficeId in [ToontownGlobals.BoardOfficeIntA, ToontownGlobals.BoardOfficeIntB, ToontownGlobals.BoardOfficeIntC]: - for floorNum in xrange(ToontownGlobals.BoardOfficeNumFloors[boardofficeId]): + for floorNum in range(ToontownGlobals.BoardOfficeNumFloors[boardofficeId]): func(BoardOfficeLayout(boardofficeId, floorNum)) def printBoardOfficeInfo(): def func(ml): - print ml + print(ml) iterateBoardOffices(func) @@ -40,7 +40,7 @@ def func(ml): def printBoardOfficeRoomIds(): def func(ml): - print ml.getBoardOfficeId(), ml.getFloorNum(), ml.getRoomIds() + print((ml.getBoardOfficeId(), ml.getFloorNum(), ml.getRoomIds())) iterateBoardOffices(func) @@ -48,7 +48,7 @@ def func(ml): def printBoardOfficeRoomNames(): def func(ml): - print ml.getBoardOfficeId(), ml.getFloorNum(), ml.getRoomNames() + print((ml.getBoardOfficeId(), ml.getFloorNum(), ml.getRoomNames())) iterateBoardOffices(func) @@ -56,7 +56,7 @@ def func(ml): def printNumRooms(): def func(ml): - print ml.getBoardOfficeId(), ml.getFloorNum(), ml.getNumRooms() + print((ml.getBoardOfficeId(), ml.getFloorNum(), ml.getNumRooms())) iterateBoardOffices(func) @@ -64,7 +64,7 @@ def func(ml): def printNumBattles(): def func(ml): - print ml.getBoardOfficeId(), ml.getFloorNum(), ml.getNumBattles() + print((ml.getBoardOfficeId(), ml.getFloorNum(), ml.getNumBattles())) iterateBoardOffices(func) @@ -723,7 +723,7 @@ def __init__(self, boardofficeId, floorNum): self.roomIds = self._genFloorLayout() hallwayRng = self.getRng() connectorRoomNames = BoardOfficeRoomSpecs.BoardOfficeConnectorRooms - for i in xrange(self.numHallways): + for i in range(self.numHallways): self.hallways.append(hallwayRng.choice(connectorRoomNames)) def _genFloorLayout(self): @@ -743,7 +743,7 @@ def _genFloorLayout(self): numBattles2middleRoomIds = invertDictLossless(BoardOfficeRoomSpecs.middleRoomId2numBattles) allBattleRooms = [] - for num, roomIds in numBattles2middleRoomIds.items(): + for num, roomIds in list(numBattles2middleRoomIds.items()): if num > 0: allBattleRooms.extend(roomIds) while 1: @@ -761,7 +761,7 @@ def _genFloorLayout(self): if middleRoomsLeft > 0: actionRoomIds = numBattles2middleRoomIds[0] - for i in xrange(middleRoomsLeft): + for i in range(middleRoomsLeft): roomId = rng.choice(actionRoomIds) actionRoomIds.remove(roomId) middleRoomIds.append(roomId) diff --git a/toontown/coghq/boardbothq/BoardOfficeManagerAI.py b/toontown/coghq/boardbothq/BoardOfficeManagerAI.py index 4363297eb..ccbd35272 100644 --- a/toontown/coghq/boardbothq/BoardOfficeManagerAI.py +++ b/toontown/coghq/boardbothq/BoardOfficeManagerAI.py @@ -1,5 +1,5 @@ from direct.directnotify import DirectNotifyGlobal -import DistributedBoardOfficeAI +from . import DistributedBoardOfficeAI from toontown.toonbase import ToontownGlobals from toontown.coghq.boardbothq import BoardOfficeLayout from direct.showbase import DirectObject @@ -34,7 +34,7 @@ def createBoardOffice(self, boardofficeId, players): for avId in players: if bboard.has('mintRoom-%s' % avId): roomId = bboard.get('mintRoom-%s' % avId) - for i in xrange(numFloors): + for i in range(numFloors): layout = BoardOfficeLayout.BoardOfficeLayout(boardofficeId, i) if roomId in layout.getRoomIds(): floor = i diff --git a/toontown/coghq/boardbothq/BoardOfficeRoomSpecs.py b/toontown/coghq/boardbothq/BoardOfficeRoomSpecs.py index 2899c339b..aa3b228c0 100644 --- a/toontown/coghq/boardbothq/BoardOfficeRoomSpecs.py +++ b/toontown/coghq/boardbothq/BoardOfficeRoomSpecs.py @@ -95,7 +95,7 @@ def getNumBattles(roomId): BoardOfficeFinalRoomIDs = (19, 20, 21, 22, 23, 24, 25, 26, 27) BoardOfficeConnectorRooms = ('phase_14/models/boardbotHQ/BD_connector_7cubeL2', 'phase_14/models/boardbotHQ/BD_connector_7cubeLR') BoardOfficeSpecModules = {} -for roomName, roomId in BoardOfficeRoomName2RoomId.items(): +for roomName, roomId in list(BoardOfficeRoomName2RoomId.items()): BoardOfficeSpecModules[roomId] = locals()[roomName] CogSpecModules = {'BoardOfficeBoilerRoom_Battle00': BoardOfficeBoilerRoom_Battle00_Cogs, @@ -115,7 +115,7 @@ def getNumBattles(roomId): 'BoardOfficePipeRoom_Battle00': BoardOfficePipeRoom_Battle00_Cogs, 'BoardOfficePipeRoom_Battle01': BoardOfficePipeRoom_Battle01_Cogs} roomId2numBattles = {} -for roomName, roomId in BoardOfficeRoomName2RoomId.items(): +for roomName, roomId in list(BoardOfficeRoomName2RoomId.items()): if roomName not in CogSpecModules: roomId2numBattles[roomId] = 0 else: diff --git a/toontown/coghq/boardbothq/DistributedBoardOffice.py b/toontown/coghq/boardbothq/DistributedBoardOffice.py index cc1e0f26a..f77101cd1 100644 --- a/toontown/coghq/boardbothq/DistributedBoardOffice.py +++ b/toontown/coghq/boardbothq/DistributedBoardOffice.py @@ -166,7 +166,7 @@ def setBossConfronted(self, avId): return def warpToRoom(self, roomId): - for i in xrange(len(self.rooms)): + for i in range(len(self.rooms)): room = self.rooms[i] if room.roomId == roomId: break diff --git a/toontown/coghq/boardbothq/DistributedBoardOfficeAI.py b/toontown/coghq/boardbothq/DistributedBoardOfficeAI.py index 0e34d7237..8e3d45d92 100644 --- a/toontown/coghq/boardbothq/DistributedBoardOfficeAI.py +++ b/toontown/coghq/boardbothq/DistributedBoardOfficeAI.py @@ -21,7 +21,7 @@ def generate(self): self.layout = BoardOfficeLayout.BoardOfficeLayout(self.boardofficeId, self.floorNum) self.rooms = [] self.battleExpAggreg = BattleExperienceAggregatorAI.BattleExperienceAggregatorAI() - for i in xrange(self.layout.getNumRooms()): + for i in range(self.layout.getNumRooms()): room = DistributedBoardOfficeRoomAI.DistributedBoardOfficeRoomAI(self.air, self.boardofficeId, self.doId, self.zoneId, self.layout.getRoomId(i), i * 2, self.avIds, self.battleExpAggreg) room.generateWithRequired(self.zoneId) self.rooms.append(room) diff --git a/toontown/coghq/boardbothq/DistributedBoardOfficeElevatorExtAI.py b/toontown/coghq/boardbothq/DistributedBoardOfficeElevatorExtAI.py index 148f951a4..6feac4248 100644 --- a/toontown/coghq/boardbothq/DistributedBoardOfficeElevatorExtAI.py +++ b/toontown/coghq/boardbothq/DistributedBoardOfficeElevatorExtAI.py @@ -34,7 +34,7 @@ def elevatorClosed(self): players.append(i) boardofficeZone = self.bldg.createBoardOffice(self.boardofficeId, players) - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] if avId: self.sendUpdateToAvatarId(avId, 'setBoardOfficeInteriorZone', [boardofficeZone]) diff --git a/toontown/coghq/boardbothq/DistributedBoardOfficeRoom.py b/toontown/coghq/boardbothq/DistributedBoardOfficeRoom.py index b48bef871..11d1632f6 100644 --- a/toontown/coghq/boardbothq/DistributedBoardOfficeRoom.py +++ b/toontown/coghq/boardbothq/DistributedBoardOfficeRoom.py @@ -151,7 +151,7 @@ def printPos(self = self): pos = base.localAvatar.getPos(thisZone) h = base.localAvatar.getH(thisZone) roomName = BoardOfficeRoomSpecs.BoardOfficeRoomId2RoomName[self.roomId] - print 'boardoffice pos: %s, h: %s, room: %s' % (repr(pos), h, roomName) + print(('boardoffice pos: %s, h: %s, room: %s' % (repr(pos), h, roomName))) if self.boardoffice is not None: floorNum = self.boardoffice.floorNum else: diff --git a/toontown/distributed/DelayDeletable.py b/toontown/distributed/DelayDeletable.py index 5b3782f68..b4aca0e32 100644 --- a/toontown/distributed/DelayDeletable.py +++ b/toontown/distributed/DelayDeletable.py @@ -13,7 +13,7 @@ def acquireDelayDelete(self, name): self.notify.error('cannot acquire DelayDelete "%s" on %s because it is in state %s' % (name, self.__class__.__name__, ESNum2Str[self.activeState])) if self.getDelayDeleteCount() == 0: self.cr._addDelayDeletedDO(self) - token = DelayDeletable.DelayDeleteSerialGen.next() + token = next(DelayDeletable.DelayDeleteSerialGen) self._token2delayDeleteName[token] = name return token @@ -25,7 +25,7 @@ def releaseDelayDelete(self, token): self.disableAnnounceAndDelete() def getDelayDeleteNames(self): - return self._token2delayDeleteName.values() + return list(self._token2delayDeleteName.values()) def forceAllowDelayDelete(self): self._delayDeleteForceAllow = True diff --git a/toontown/distributed/DistributedTimer.py b/toontown/distributed/DistributedTimer.py index bc392688a..22187e2ff 100644 --- a/toontown/distributed/DistributedTimer.py +++ b/toontown/distributed/DistributedTimer.py @@ -22,7 +22,7 @@ def delete(self): def setStartTime(self, time): self.startTime = time - print 'TIMER startTime %s' % time + print('TIMER startTime %s' % time) def getStartTime(self): return self.startTime diff --git a/toontown/distributed/HoodMgr.py b/toontown/distributed/HoodMgr.py index b17d9e7af..3c41ddd7c 100644 --- a/toontown/distributed/HoodMgr.py +++ b/toontown/distributed/HoodMgr.py @@ -257,7 +257,7 @@ def getAvailableZones(self): def getZonesInPhase(self, phase): p = [] - for i in ToontownGlobals.phaseMap.items(): + for i in list(ToontownGlobals.phaseMap.items()): if i[1] == phase: p.append(i[0]) return p @@ -296,7 +296,7 @@ def addLinkTunnelHooks(self, hoodPart, nodeList, currentZoneId): tunnelOriginList = [] for i in nodeList: linkTunnelNPC = i.findAllMatches('**/linktunnel*') - for p in xrange(linkTunnelNPC.getNumPaths()): + for p in range(linkTunnelNPC.getNumPaths()): linkTunnel = linkTunnelNPC.getPath(p) name = linkTunnel.getName() nameParts = name.split('_') diff --git a/toontown/distributed/NonRepeatableRandomSourceAI.py b/toontown/distributed/NonRepeatableRandomSourceAI.py index 562b45557..0408c6c0f 100644 --- a/toontown/distributed/NonRepeatableRandomSourceAI.py +++ b/toontown/distributed/NonRepeatableRandomSourceAI.py @@ -12,7 +12,7 @@ def __init__(self, air): def announceGenerate(self): DistributedObjectAI.announceGenerate(self) - self._contextGen = SerialMaskedGen((1L << 32) - 1) + self._contextGen = SerialMaskedGen((1 << 32) - 1) self._requests = {} self._sampleTask = self.doMethodLater(3 * 60, self._sampleRandomTask, self.uniqueName('sampleRandom')) self._sampleRandom() @@ -27,7 +27,7 @@ def _sampleRandomTask(self, task = None): return Task.again def _sampleRandom(self): - self.air.sendUpdateToDoId('NonRepeatableRandomSource', 'randomSample', OtpDoGlobals.OTP_DO_ID_TOONTOWN_NON_REPEATABLE_RANDOM_SOURCE, [self.doId, int(random.randrange(1L << 32))]) + self.air.sendUpdateToDoId('NonRepeatableRandomSource', 'randomSample', OtpDoGlobals.OTP_DO_ID_TOONTOWN_NON_REPEATABLE_RANDOM_SOURCE, [self.doId, int(random.randrange(1 << 32))]) def randomSampleAck(self): self._sampleRandom() @@ -35,7 +35,7 @@ def randomSampleAck(self): def getRandomSamples(self, callback, num = None): if num is None: num = 1 - context = self._contextGen.next() + context = next(self._contextGen) self._requests[context] = (callback,) self.air.sendUpdateToDoId('NonRepeatableRandomSource', 'getRandomSamples', OtpDoGlobals.OTP_DO_ID_TOONTOWN_NON_REPEATABLE_RANDOM_SOURCE, [self.doId, 'NonRepeatableRandomSource', diff --git a/toontown/distributed/NonRepeatableRandomSourceUD.py b/toontown/distributed/NonRepeatableRandomSourceUD.py index 1dc148d2a..2af96d777 100644 --- a/toontown/distributed/NonRepeatableRandomSourceUD.py +++ b/toontown/distributed/NonRepeatableRandomSourceUD.py @@ -44,8 +44,8 @@ def _processRequests(self): if needed > 0: numRandoms = min(needed, len(self._randoms)) if self._fakeIt: - for i in xrange(numRandoms): - request.randoms.append(random.random() * 4294967295L) + for i in range(numRandoms): + request.randoms.append(random.random() * 4294967295) else: request.randoms += self._randoms[:numRandoms] diff --git a/toontown/distributed/PlayGame.py b/toontown/distributed/PlayGame.py index fabeffaaa..85058732f 100644 --- a/toontown/distributed/PlayGame.py +++ b/toontown/distributed/PlayGame.py @@ -5,7 +5,7 @@ from direct.fsm import ClassicFSM, State from direct.fsm import State from direct.task.Task import Task -from ToontownMsgTypes import * +from .ToontownMsgTypes import * from toontown.toonbase import ToontownGlobals from toontown.hood import TTHood from toontown.hood import TTOHood @@ -527,7 +527,7 @@ def goToPartyFailed(self, reason): def getCatalogCodes(self, category): numCodes = self.dnaStore.getNumCatalogCodes(category) codes = [] - for i in xrange(numCodes): + for i in range(numCodes): codes.append(self.dnaStore.getCatalogCode(category, i)) return codes diff --git a/toontown/distributed/ToontownClientRepository.py b/toontown/distributed/ToontownClientRepository.py index 82543e2ef..2e51f5877 100644 --- a/toontown/distributed/ToontownClientRepository.py +++ b/toontown/distributed/ToontownClientRepository.py @@ -51,7 +51,7 @@ from toontown.makeatoon import TTPickANamePattern from toontown.parties import ToontownTimeManager from toontown.toon import Toon, DistributedToon -from ToontownMsgTypes import * +from .ToontownMsgTypes import * from toontown.toontowngui import ToontownLoadingBlocker from toontown.ai import DistributedSillyMeterMgr, DistributedHydrantZeroMgr, DistributedMailboxZeroMgr, DistributedTrashcanZeroMgr from toontown.hood import StreetSign @@ -75,7 +75,7 @@ def __init__(self, serverVersion, launcher = None): setInterfaceFont(TTLocalizer.InterfaceFont) setSignFont(TTLocalizer.SignFont) setFancyFont(TTLocalizer.FancyFont) - for i in xrange(len(TTLocalizer.NametagFonts)): + for i in range(len(TTLocalizer.NametagFonts)): setNametagFont(i, TTLocalizer.NametagFonts[i]) self.toons = {} @@ -140,11 +140,11 @@ def __init__(self, serverVersion, launcher = None): for torso in ToonDNA.toonTorsoTypes: for legs in ToonDNA.toonLegTypes: for gender in ('m', 'f'): - print 'species: %s, head: %s, torso: %s, legs: %s, gender: %s' % (species, + print('species: %s, head: %s, torso: %s, legs: %s, gender: %s' % (species, head, torso, legs, - gender) + gender)) dna = ToonDNA.ToonDNA() dna.newToon((head, torso, @@ -153,8 +153,8 @@ def __init__(self, serverVersion, launcher = None): toon = Toon.Toon() try: toon.setDNA(dna) - except Exception, e: - print e + except Exception as e: + print(e) self.DMENU_SCREEN = None self.hasAccepted = False @@ -260,7 +260,7 @@ def __handleAvatarChooserDone(self, avList, doneStatus): avatarChoice = av dna = ToonDNA.ToonDNA() dna.makeFromNetString(av.dna) - print '__handleAvatarChooserDone: %r, %r, %r, %r' % (av.id, av.name, dna.asTuple(), av.position) + print('__handleAvatarChooserDone: %r, %r, %r, %r' % (av.id, av.name, dna.asTuple(), av.position)) if done == 'chose': self.avChoice.exit() @@ -440,10 +440,10 @@ def n_handleGetAvatarDetailsResp(self, avId, fields): gotData = 1 - if isinstance(pad.func, types.StringType): + if isinstance(pad.func, bytes): messenger.send(pad.func, list((gotData, pad.avatar) + pad.args)) else: - apply(pad.func, (gotData, pad.avatar) + pad.args) + pad.func(*(gotData, pad.avatar) + pad.args) pad.delayDelete.destroy() @@ -466,10 +466,10 @@ def handleGetAvatarDetailsResp(self, di): dclass = self.dclassesByName[dclassName] pad.avatar.updateAllRequiredFields(dclass, di) gotData = 1 - if isinstance(pad.func, types.StringType): + if isinstance(pad.func, bytes): messenger.send(pad.func, list((gotData, pad.avatar) + pad.args)) else: - apply(pad.func, (gotData, pad.avatar) + pad.args) + pad.func(*(gotData, pad.avatar) + pad.args) pad.delayDelete.destroy() def enterPlayingGame(self, *args, **kArgs): @@ -630,12 +630,12 @@ def dumpAllSubShardObjects(self): ignoredClasses = ('MagicWordManager', 'TimeManager', 'DistributedDistrict', 'FriendManager', 'NewsManager', 'ToontownMagicWordManager', 'WelcomeValleyManager', 'DistributedTrophyMgr', 'CatalogManager', 'DistributedBankMgr', 'EstateManager', 'RaceManager', 'SafeZoneManager', 'DeleteManager', 'TutorialManager', 'ToontownDistrict', 'DistributedDeliveryManager', 'DistributedPartyManager', 'AvatarFriendsManager', 'InGameNewsMgr', 'WhitelistMgr', 'TTCodeRedemptionMgr') messenger.send('clientCleanup') - for avId, pad in self.__queryAvatarMap.items(): + for avId, pad in list(self.__queryAvatarMap.items()): pad.delayDelete.destroy() self.__queryAvatarMap = {} delayDeleted = [] - doIds = self.doId2do.keys() + doIds = list(self.doId2do.keys()) for doId in doIds: obj = self.doId2do[doId] if isNotLive: @@ -665,7 +665,7 @@ def dumpAllSubShardObjects(self): self.notify.error(s) if isNotLive: - self.notify.info('dumpAllSubShardObjects: doIds left: %s' % self.doId2do.keys()) + self.notify.info('dumpAllSubShardObjects: doIds left: %s' % list(self.doId2do.keys())) def _removeCurrentShardInterest(self, callback): if self.old_setzone_interest_handle is None: @@ -693,7 +693,7 @@ def _doIdIsOnCurrentShard(self, doId): return False def _wantShardListComplete(self): - print self.activeDistrictMap + print(self.activeDistrictMap) if self._shardsAreReady(): self.acceptOnce(ToontownDistrictStats.EventName(), self.shardDetailStatsComplete) ToontownDistrictStats.refresh() @@ -814,10 +814,10 @@ def sendGetFriendsListRequest(self): self.ttaFriendsManager.d_requestFriendsList() def cleanPetsFromFriendsMap(self): - for objId, obj in self.friendsMap.items(): + for objId, obj in list(self.friendsMap.items()): from toontown.pets import DistributedPet if isinstance(obj, DistributedPet.DistributedPet): - print 'Removing %s reference from the friendsMap' % obj.getName() + print('Removing %s reference from the friendsMap' % obj.getName()) del self.friendsMap[objId] def removePetFromFriendsMap(self): @@ -845,7 +845,7 @@ def petDetailsCallback(petAvatar): PetDetail.PetDetail(doId, petDetailsCallback) def handleGetFriendsList(self, resp): - print len(resp) + print(len(resp)) for toon in resp: doId = toon[0] name = toon[1] @@ -921,7 +921,7 @@ def handleGenerateWithRequiredOtherOwner(self, di): def getFirstBattle(self): from toontown.battle import DistributedBattleBase - for dobj in self.doId2do.values(): + for dobj in list(self.doId2do.values()): if isinstance(dobj, DistributedBattleBase.DistributedBattleBase): return dobj @@ -1080,7 +1080,7 @@ def deleteObject(self, doId, ownerView = False): self.notify.warning('Asked to delete non-existent DistObj ' + str(doId)) def _abandonShard(self): - for doId, obj in self.doId2do.items(): + for doId, obj in list(self.doId2do.items()): if obj.parentId == localAvatar.defaultShard and obj is not localAvatar: self.deleteObject(doId) diff --git a/toontown/distributed/ToontownInternalRepository.py b/toontown/distributed/ToontownInternalRepository.py index 0ecf93d00..bc0ec3802 100644 --- a/toontown/distributed/ToontownInternalRepository.py +++ b/toontown/distributed/ToontownInternalRepository.py @@ -69,6 +69,6 @@ def readerPollOnce(self): self.send(dg) self.writeServerEvent('EXCEPTION-POTENTIAL-CRASH', self.getAvatarIdFromSender(), self.getAccountIdFromSender(), repr(e), traceback.format_exc()) self.notify.warning('EXCEPTION-POTENTIAL-CRASH: %s (%s)' % (repr(e), self.getAvatarIdFromSender())) - print traceback.format_exc() + print(traceback.format_exc()) return 1 diff --git a/toontown/distributed/ToontownNetMessengerAI.py b/toontown/distributed/ToontownNetMessengerAI.py index fd0a1408d..cb36eb759 100644 --- a/toontown/distributed/ToontownNetMessengerAI.py +++ b/toontown/distributed/ToontownNetMessengerAI.py @@ -1,7 +1,7 @@ from direct.distributed.PyDatagram import PyDatagram from otp.distributed import OtpDoGlobals -import cPickle, zlib +import pickle, zlib class ToontownNetMessengerAI: @@ -29,7 +29,7 @@ def prepare(self, message, sentArgs=[], channels=None): dg.addChannel(self.msgType) dg.addUint16(self.msgType) dg.addString(message) - dg.addString(zlib.compress(cPickle.dumps(sentArgs))) + dg.addString(zlib.compress(pickle.dumps(sentArgs))) return dg def send(self, message, sentArgs=[], channels=None): @@ -40,5 +40,5 @@ def send(self, message, sentArgs=[], channels=None): def handle(self, msgType, di): message = di.getString() data = zlib.decompress(di.getString()) - sentArgs = cPickle.loads(data) + sentArgs = pickle.loads(data) messenger.send(message, sentArgs) diff --git a/toontown/dmenu/DMenuNewsManager.py b/toontown/dmenu/DMenuNewsManager.py index f7e31e553..bbaa59bf8 100644 --- a/toontown/dmenu/DMenuNewsManager.py +++ b/toontown/dmenu/DMenuNewsManager.py @@ -4,7 +4,7 @@ @author: Drew ''' from direct.showbase.DirectObject import DirectObject -import httplib +import http.client RELEASE_NOTES_URL = '/OSToontown/Project-Altis/master/resources/phase_3/etc/changelog.md' @@ -14,7 +14,7 @@ def __init__(self): DirectObject.__init__(self) def fetchReleaseNotes(self): - req = httplib.HTTPSConnection('raw.githubusercontent.com') + req = http.client.HTTPSConnection('raw.githubusercontent.com') req.request('GET', RELEASE_NOTES_URL) self.releaseNotes = req.getresponse().read() return self.releaseNotes diff --git a/toontown/dmenu/DMenuOptions.py b/toontown/dmenu/DMenuOptions.py index 99789198e..7f53b2a9a 100644 --- a/toontown/dmenu/DMenuOptions.py +++ b/toontown/dmenu/DMenuOptions.py @@ -27,7 +27,7 @@ (1280, 720), (1920, 1080)] -class DMenuOptions(DirectObject, FSM): +class DMenuOptions(FSM, DirectObject): def __init__(self): FSM.__init__(self, 'DMenuOptions') diff --git a/toontown/dna/DNALandmarkBuilding.py b/toontown/dna/DNALandmarkBuilding.py index 138f42b26..73c705b3e 100644 --- a/toontown/dna/DNALandmarkBuilding.py +++ b/toontown/dna/DNALandmarkBuilding.py @@ -37,7 +37,7 @@ def setupSuitBuildingOrigin(self, nodePathA, nodePathB): name = 's' + name[1:] node = nodePathB.find('**/*suit_building_origin') if node.isEmpty(): - print 'DNALandmarkBuilding ' + name + ' did not find **/*suit_building_origin' + print('DNALandmarkBuilding ' + name + ' did not find **/*suit_building_origin') node = nodePathA.attachNewNode(name) node.setPosHprScale(self.pos, self.hpr, self.scale) else: diff --git a/toontown/dna/DNALoader.py b/toontown/dna/DNALoader.py index 7013bfe50..615bdc5f0 100644 --- a/toontown/dna/DNALoader.py +++ b/toontown/dna/DNALoader.py @@ -71,7 +71,7 @@ def loadDNAFile(self, store, _file): self.loadDNAFileBase(store, _file) if not self.curComp: - print "DNA has no component, returning empty nodepath" + print("DNA has no component, returning empty nodepath") return NodePath() np = NodePath("dna") @@ -178,7 +178,7 @@ def handleCompData(self, dgi): new_comp = DNAVisGroup.DNAVisGroup("unnamed_comp") self.curStore.storeDNAVisGroup(new_comp) else: - if comp_code in compClassTable.keys(): + if comp_code in list(compClassTable.keys()): new_comp = compClassTable[comp_code]("unnamed_comp") else: raise DNAError.DNAError("Invalid comp code %s" % comp_code) diff --git a/toontown/dna/DNAParser.py b/toontown/dna/DNAParser.py index 24550e1fc..3f06fe5e2 100644 --- a/toontown/dna/DNAParser.py +++ b/toontown/dna/DNAParser.py @@ -27,7 +27,7 @@ def __init__(self, storage, files): def loadDNAFiles(self): for file in self.dnaFiles: - print 'Reading DNA file...', file + print('Reading DNA file...', file) loadDNABulk(self.dnaStorage, file) del self.dnaStorage @@ -39,7 +39,7 @@ def loadDNABulk(dnaStorage, file): dnaLoader.destroy() def loadDNAFile(dnaStorage, file): - print 'Reading DNA file...', file + print('Reading DNA file...', file) dnaLoader = DNALoader.DNALoader() node = dnaLoader.loadDNAFile(dnaStorage, file) dnaLoader.destroy() diff --git a/toontown/dna/DNAStorage.py b/toontown/dna/DNAStorage.py index c73d2ba22..b172d22ef 100644 --- a/toontown/dna/DNAStorage.py +++ b/toontown/dna/DNAStorage.py @@ -137,7 +137,7 @@ def findNode(self, code): try: model = loader.pdnaModel(Filename(filename)) except: - print "DNAStorage: Failed to load %s!" % (filename) + print("DNAStorage: Failed to load %s!" % (filename)) return if search: @@ -291,7 +291,7 @@ def storeSuitEdge(self, startIndex, endIndex, zoneId): endPoint = self.getSuitPointWithIndex(endIndex) if not startPoint or not endPoint: - print "DNAStorage: Attempted to add edge with unknown startPoint(%s) and/or endPoint(%s)" % (startIndex, endIndex) + print("DNAStorage: Attempted to add edge with unknown startPoint(%s) and/or endPoint(%s)" % (startIndex, endIndex)) if not startIndex in self.suitEdges: self.suitEdges[startIndex] = [] @@ -325,19 +325,19 @@ def resetSuitPoints(self): self.suitPoints = [] def resetSuitEdges(self): - for suitEdge in self.suitEdges.items(): + for suitEdge in list(self.suitEdges.items()): del suitEdge def findDNAGroup(self, node): return self.DNAGroups[node] def removeDNAGroup(self, dnagroup): - for node, group in self.DNAGroups.items(): + for node, group in list(self.DNAGroups.items()): if group == dnagroup: del self.DNAGroups[node] def resetDNAGroups(self): - for group in self.DNAGroups.items(): + for group in list(self.DNAGroups.items()): del group self.DNAGroups = {} diff --git a/toontown/dna/DNAUtil.py b/toontown/dna/DNAUtil.py index 0b1a242a8..ff21c9840 100644 --- a/toontown/dna/DNAUtil.py +++ b/toontown/dna/DNAUtil.py @@ -4,4 +4,4 @@ def dgiExtractString8(dgi): return dgi.getString() def dgiExtractColor(dgi): - return LVector4f(*(dgi.getUint8() / 255.0 for _ in xrange(4))) \ No newline at end of file + return LVector4f(*(dgi.getUint8() / 255.0 for _ in range(4))) \ No newline at end of file diff --git a/toontown/dna/DNAVisGroup.py b/toontown/dna/DNAVisGroup.py index b9bdd0c77..3d667b6b7 100644 --- a/toontown/dna/DNAVisGroup.py +++ b/toontown/dna/DNAVisGroup.py @@ -70,18 +70,18 @@ def makeFromDGI(self, dgi, dnaStorage): DNAGroup.DNAGroup.makeFromDGI(self, dgi, dnaStorage) numEdges = dgi.getUint16() - for _ in xrange(numEdges): + for _ in range(numEdges): index = dgi.getUint16() endPoint = dgi.getUint16() self.addSuitEdge(dnaStorage.getSuitEdge(index, endPoint)) numVisibles = dgi.getUint16() - for _ in xrange(numVisibles): + for _ in range(numVisibles): self.addVisible(DNAUtil.dgiExtractString8(dgi)) numCells = dgi.getUint16() - for _ in xrange(numCells): + for _ in range(numCells): w = dgi.getUint8() h = dgi.getUint8() - x, y, z = [dgi.getInt32() / 100.0 for i in xrange(3)] + x, y, z = [dgi.getInt32() / 100.0 for i in range(3)] self.addBattleCell(DNABattleCell.DNABattleCell(w, h, LVector3f(x, y, z))) \ No newline at end of file diff --git a/toontown/dna/DNAWall.py b/toontown/dna/DNAWall.py index 74114f0f4..f9435104a 100644 --- a/toontown/dna/DNAWall.py +++ b/toontown/dna/DNAWall.py @@ -2,7 +2,7 @@ from toontown.dna import DNANode # For the oddest reason the toontown.dna breaks the import? Wth -import DNAFlatBuilding +from . import DNAFlatBuilding from toontown.dna import DNAError from toontown.dna import DNAUtil diff --git a/toontown/effects/BlastEffect.py b/toontown/effects/BlastEffect.py index c1407f5e3..086c74763 100644 --- a/toontown/effects/BlastEffect.py +++ b/toontown/effects/BlastEffect.py @@ -1,6 +1,6 @@ from pandac.PandaModules import * from direct.interval.IntervalGlobal import * -from EffectController import EffectController +from .EffectController import EffectController class BlastEffect(NodePath, EffectController): diff --git a/toontown/effects/EffectController.py b/toontown/effects/EffectController.py index b6ccfcc7c..906ab9fe4 100644 --- a/toontown/effects/EffectController.py +++ b/toontown/effects/EffectController.py @@ -36,7 +36,7 @@ def play(self, lod = None): if lod != None: try: self.createTrack(lod) - except TypeError, e: + except TypeError as e: raise TypeError('Error loading %s effect.' % self.__class__.__name__) else: @@ -71,7 +71,7 @@ def startLoop(self, lod = None): if lod != None: try: self.createTrack(lod) - except TypeError, e: + except TypeError as e: raise TypeError('Error loading %s effect.' % self.__class__.__name__) else: diff --git a/toontown/effects/Firework.py b/toontown/effects/Firework.py index d8d4c3a82..3535fc3e2 100644 --- a/toontown/effects/Firework.py +++ b/toontown/effects/Firework.py @@ -118,7 +118,7 @@ def generateFireworkIval(self): elif self.typeId == FireworkType.AmericanFlag: fireworkParallel = Parallel() colors = [Vec4(1, 0, 0, 1), Vec4(1, 1, 1, 1)] - for i in xrange(4): + for i in range(4): firework = FireworkEffect(None, FireworkTrailType.LongGlowSparkle, velocity=Vec3(-30 * self.scale, 0, 150 * self.scale - 20 * i), scale=self.scale * 3.0, primaryColor=colors[i % 2], burstDelay=2.5) firework.reparentTo(self) firework.setX(-20.0 * self.scale + 10.0 * i * self.scale) diff --git a/toontown/effects/FireworkShow.py b/toontown/effects/FireworkShow.py index f884bdb37..6723558f8 100644 --- a/toontown/effects/FireworkShow.py +++ b/toontown/effects/FireworkShow.py @@ -1084,7 +1084,7 @@ def rD(): @classmethod def isValidShowType(cls, showType = -1): - if showType in cls.showData.keys(): + if showType in list(cls.showData.keys()): return True else: return False diff --git a/toontown/effects/PolyTrail.py b/toontown/effects/PolyTrail.py index e93a92e9d..63558e8e7 100644 --- a/toontown/effects/PolyTrail.py +++ b/toontown/effects/PolyTrail.py @@ -130,7 +130,7 @@ def setVertexColors(self, color_list): 0.7, 1.0] total_scales = len(scale_array) - for index in xrange(len(color_list)): + for index in range(len(color_list)): color = color_list[index] if index < total_scales: scale = scale_array[index] * 0.75 @@ -141,7 +141,7 @@ def setVertexColors(self, color_list): def setUnmodifiedVertexColors(self, color_list): if self.motion_trail: - for index in xrange(len(color_list)): + for index in range(len(color_list)): color = color_list[index] self.motion_trail.set_vertex_color(index, color, color) diff --git a/toontown/effects/ScavengerHuntEffects.py b/toontown/effects/ScavengerHuntEffects.py index 9419b6656..0fc5c777d 100644 --- a/toontown/effects/ScavengerHuntEffects.py +++ b/toontown/effects/ScavengerHuntEffects.py @@ -22,7 +22,7 @@ def __init__(self, beanAmount): def countUp(t, startVal, endVal): beanCountStr = startVal + t * (endVal - startVal) - self.countLabel['text'] = '+' + `(int(beanCountStr))` + self.countLabel['text'] = '+' + repr((int(beanCountStr))) def setCountColor(color): self.countLabel['text_fg'] = color diff --git a/toontown/effects/TrailExplosion.py b/toontown/effects/TrailExplosion.py index 2a2a12dd6..50aa9c9cc 100644 --- a/toontown/effects/TrailExplosion.py +++ b/toontown/effects/TrailExplosion.py @@ -32,7 +32,7 @@ def createTrack(self): vels = None if self.numTrails >= 3 and self.numTrails <= 5: vels = self.trailsVel[self.numTrails - 3] - for i in xrange(self.numTrails): + for i in range(self.numTrails): self.trails.append(self.attachNewNode('trail')) vel = Vec3(0, 0, 0) if vels: diff --git a/toontown/effects/Wake.py b/toontown/effects/Wake.py index 34faae294..d42cd997f 100644 --- a/toontown/effects/Wake.py +++ b/toontown/effects/Wake.py @@ -42,7 +42,7 @@ def destroyRipple(task): self.rippleCount = (self.rippleCount + 1) % 20 def stop(self): - for i in xrange(len(self.doLaters)): + for i in range(len(self.doLaters)): if self.doLaters[i]: taskMgr.remove(self.doLaters[i]) self.doLaters[i] = None diff --git a/toontown/environment/DistributedDayTimeManager.py b/toontown/environment/DistributedDayTimeManager.py index bbd486521..601b50c55 100644 --- a/toontown/environment/DistributedDayTimeManager.py +++ b/toontown/environment/DistributedDayTimeManager.py @@ -12,8 +12,8 @@ import time from direct.showbase import PythonUtil from toontown.hood import Place -import DayTimeGlobals -from DistributedWeatherMGR import DistributedWeatherMGR +from . import DayTimeGlobals +from .DistributedWeatherMGR import DistributedWeatherMGR class DistributedDayTimeManager(DistributedWeatherMGR): notify = directNotify.newCategory('DistributedDayTimeManager') diff --git a/toontown/environment/DistributedDayTimeManagerAI.py b/toontown/environment/DistributedDayTimeManagerAI.py index b9c856fc2..a0fea1c81 100644 --- a/toontown/environment/DistributedDayTimeManagerAI.py +++ b/toontown/environment/DistributedDayTimeManagerAI.py @@ -10,8 +10,8 @@ import random import time from direct.showbase import PythonUtil -import DayTimeGlobals -from DistributedWeatherMGRAI import DistributedWeatherMGRAI +from . import DayTimeGlobals +from .DistributedWeatherMGRAI import DistributedWeatherMGRAI class DistributedDayTimeManagerAI(DistributedWeatherMGRAI): notify = directNotify.newCategory('DistributedDayTimeManagerAI') diff --git a/toontown/environment/DistributedRainManager.py b/toontown/environment/DistributedRainManager.py index 0461c6511..540a4518f 100644 --- a/toontown/environment/DistributedRainManager.py +++ b/toontown/environment/DistributedRainManager.py @@ -11,8 +11,8 @@ import time from direct.showbase import PythonUtil from toontown.hood import Place -import DayTimeGlobals -from DistributedWeatherMGR import DistributedWeatherMGR +from . import DayTimeGlobals +from .DistributedWeatherMGR import DistributedWeatherMGR from toontown.battle import BattleParticles from toontown.battle.BattleProps import * diff --git a/toontown/environment/DistributedRainManagerAI.py b/toontown/environment/DistributedRainManagerAI.py index 7899f7e95..2d092bbb6 100644 --- a/toontown/environment/DistributedRainManagerAI.py +++ b/toontown/environment/DistributedRainManagerAI.py @@ -10,8 +10,8 @@ import random import time from direct.showbase import PythonUtil -import DayTimeGlobals -from DistributedWeatherMGRAI import DistributedWeatherMGRAI +from . import DayTimeGlobals +from .DistributedWeatherMGRAI import DistributedWeatherMGRAI class DistributedRainManagerAI(DistributedWeatherMGRAI): notify = directNotify.newCategory('DistributedRainManagerAI') diff --git a/toontown/environment/TemperatureManagerAI.py b/toontown/environment/TemperatureManagerAI.py index c6f313c9c..da13898c9 100644 --- a/toontown/environment/TemperatureManagerAI.py +++ b/toontown/environment/TemperatureManagerAI.py @@ -37,7 +37,7 @@ def loadHood(self, zoneId): hood.rainMgr.b_setState('Rain') def unloadHood(self, zoneId): - if zoneId not in self._temperatures.keys(): + if zoneId not in list(self._temperatures.keys()): return del self._temperatures[zoneId] diff --git a/toontown/estate/BeanRecipeGui.py b/toontown/estate/BeanRecipeGui.py index 425761fcc..6f5406e76 100644 --- a/toontown/estate/BeanRecipeGui.py +++ b/toontown/estate/BeanRecipeGui.py @@ -27,11 +27,11 @@ def __init__(self, parent, recipe, **kw): self.initialiseoptions(BeanRecipeGui) self.jellyBeanBoxList = [] xIncrement = 0.052 - for i in xrange(len(recipe)): + for i in range(len(recipe)): beanIndex = GardenGlobals.BeanColorLetters.index(recipe[i]) self.createJellyBeanBox(beanIndex, borderWidth + xIncrement * i, borderWidth) - for j in xrange(len(recipe), GardenGlobals.getNumberOfShovelBoxes()): + for j in range(len(recipe), GardenGlobals.getNumberOfShovelBoxes()): self.createEmptyBeanBox(borderWidth + xIncrement * j, borderWidth) return diff --git a/toontown/estate/DistributedCannon.py b/toontown/estate/DistributedCannon.py index bff630b05..4f51b2589 100644 --- a/toontown/estate/DistributedCannon.py +++ b/toontown/estate/DistributedCannon.py @@ -715,7 +715,7 @@ def __localCannonMoveTask(self, task): self.cannonMoving = 0 self.sndCannonMove.stop() self.__broadcastLocalCannonPosition() - print 'Cannon Rot:%s Angle:%s' % (pos[0], pos[1]) + print(('Cannon Rot:%s Angle:%s' % (pos[0], pos[1]))) return Task.cont def __broadcastLocalCannonPosition(self): @@ -796,7 +796,7 @@ def __fireCannonTask(self, task): head.reparentTo(hidden) av = self.toonModel av.reparentTo(render) - print 'start Pos%s Hpr%s' % (startPos, startHpr) + print(('start Pos%s Hpr%s' % (startPos, startHpr))) av.setPos(startPos) barrelHpr = self.barrel.getHpr(render) place = base.cr.playGame.getPlace() @@ -863,7 +863,7 @@ def removeAvFromCannon(self): if not hasattr(place, 'fsm'): return placeState = place.fsm.getCurrentState().getName() - print placeState + print(placeState) if (self.inWater or place.toonSubmerged) and placeState != 'fishing': if self.av != None: self.av.startSmooth() @@ -1496,7 +1496,7 @@ def createBlock(self, collisionName = None): (0, 1, 5, 4), (0, 4, 7, 3), (1, 2, 6, 5)] - for i in xrange(len(vertices)): + for i in range(len(vertices)): vertex = vertices[i] vertexWriter.addData3f(vertex[0], vertex[1], vertex[2]) colorWriter.addData4f(*colors[i]) diff --git a/toontown/estate/DistributedCannonAI.py b/toontown/estate/DistributedCannonAI.py index d3acf74ba..6489590fe 100644 --- a/toontown/estate/DistributedCannonAI.py +++ b/toontown/estate/DistributedCannonAI.py @@ -3,7 +3,7 @@ from direct.distributed.ClockDelta import * from toontown.minigame import CannonGameGlobals from toontown.toonbase import ToontownGlobals -import CannonGlobals +from . import CannonGlobals class DistributedCannonAI(DistributedObjectAI): notify = DirectNotifyGlobal.directNotify.newCategory("DistributedCannonAI") diff --git a/toontown/estate/DistributedChangingStatuary.py b/toontown/estate/DistributedChangingStatuary.py index e963322b6..5a57289d6 100644 --- a/toontown/estate/DistributedChangingStatuary.py +++ b/toontown/estate/DistributedChangingStatuary.py @@ -41,7 +41,7 @@ def hideParts(self): if stage == -1: stage = len(growthThresholds) self.notify.debug('growth Stage=%d' % stage) - for index in xrange(len(growthThresholds) + 1): + for index in range(len(growthThresholds) + 1): if index != stage: partName = '**/growthStage_%d' % index self.notify.debug('trying to remove %s' % partName) diff --git a/toontown/estate/DistributedCloset.py b/toontown/estate/DistributedCloset.py index b0c2960f8..684b5ce59 100644 --- a/toontown/estate/DistributedCloset.py +++ b/toontown/estate/DistributedCloset.py @@ -359,15 +359,15 @@ def setCustomerDNA(self, avId, dnaString): return def printInfo(self): - print 'avid: %s, gender: %s' % (self.av.doId, self.av.style.gender) - print 'current top = %s,%s,%s,%s and bot = %s,%s,' % (self.av.style.topTex, + print(('avid: %s, gender: %s' % (self.av.doId, self.av.style.gender))) + print(('current top = %s,%s,%s,%s and bot = %s,%s,' % (self.av.style.topTex, self.av.style.topTexColor, self.av.style.sleeveTex, self.av.style.sleeveTexColor, self.av.style.botTex, - self.av.style.botTexColor) - print 'topsList = %s' % self.av.getClothesTopsList() - print 'bottomsList = %s' % self.av.getClothesBottomsList() + self.av.style.botTexColor))) + print(('topsList = %s' % self.av.getClothesTopsList())) + print(('bottomsList = %s' % self.av.getClothesBottomsList())) def setMovie(self, mode, avId, timestamp): self.isLocalToon = avId == base.localAvatar.doId diff --git a/toontown/estate/DistributedEstate.py b/toontown/estate/DistributedEstate.py index 9b7737eb7..e42f423b6 100644 --- a/toontown/estate/DistributedEstate.py +++ b/toontown/estate/DistributedEstate.py @@ -15,7 +15,7 @@ from direct.task.Task import Task from toontown.toonbase import TTLocalizer import random -import cPickle +import pickle import time from toontown.toonbase import ToonPythonUtil as PythonUtil from toontown.hood import Place @@ -182,7 +182,7 @@ def setEstateType(self, index): def setHouseInfo(self, houseInfo): self.notify.debug('setHouseInfo') - houseType, housePos = cPickle.loads(houseInfo) + houseType, housePos = pickle.loads(houseInfo) self.loadEstate(houseType, housePos) def loadEstate(self, indexList, posList): diff --git a/toontown/estate/DistributedEstateAI.py b/toontown/estate/DistributedEstateAI.py index 30ebe417c..021ec331e 100644 --- a/toontown/estate/DistributedEstateAI.py +++ b/toontown/estate/DistributedEstateAI.py @@ -25,9 +25,9 @@ from toontown.parties import DistributedPartyJukebox40ActivityAI, DistributedPartyTrampolineActivityAI from toontown.safezone import DistributedTreasureAI -from DistributedCannonAI import * -from DistributedTargetAI import * -import CannonGlobals +from .DistributedCannonAI import * +from .DistributedTargetAI import * +from . import CannonGlobals import random NULL_PLANT = [-1, -1, 0, 0, 0] @@ -330,7 +330,7 @@ def reconsiderAvatarOrganicBonus(self): return bonus = [-1, -1, -1, -1, -1, -1, -1, -1] spentPoints = av.getSpentTrainingPoints() - for i in xrange(8): + for i in range(8): if spentPoints[i] >= 3: bonus[i] = 6 av.b_setTrackBonusLevel(bonus) @@ -353,7 +353,7 @@ def handleSingleGarden(self, avId): def destroy(self): messenger.send('garden-%d-1-gardenDestroy') - for garden in self.gardens.values(): + for garden in list(self.gardens.values()): garden.destroy() del self.gardens @@ -406,7 +406,7 @@ def generate(self): self.pond.setArea(ToontownGlobals.MyEstate) self.pond.generateWithRequired(self.zoneId) - for i in xrange(FishingTargetGlobals.getNumTargets(ToontownGlobals.MyEstate)): + for i in range(FishingTargetGlobals.getNumTargets(ToontownGlobals.MyEstate)): target = DistributedFishingTargetAI(self.air) target.setPondDoId(self.pond.getDoId()) target.generateWithRequired(self.zoneId) @@ -497,7 +497,7 @@ def announceGenerate(self): DistributedObjectAI.announceGenerate(self) self.sendUpdate('setIdList', [self.toons]) - for index, started in self.pendingGardens.items(): + for index, started in list(self.pendingGardens.items()): if started: self.gardenManager.handleSingleGarden(self.toons[index]) @@ -614,7 +614,7 @@ def destroyPet(self, owner): def __handleGetPetActivated(self, doId, activated): # if the pet wasn't activated, dont destroy it. - if not activated or doId not in self.air.doId2do.keys(): + if not activated or doId not in list(self.air.doId2do.keys()): return # alright, all's good destroy the pet instance @@ -845,7 +845,7 @@ def getSlot5Items(self): return self.items[5] def setIdList(self, idList): - for i in xrange(len(idList)): + for i in range(len(idList)): if i >= 6: return self.toons[i] = idList[i] @@ -890,7 +890,7 @@ def completeFlowerSale(self, flag): self.sendUpdate('awardedTrophy', [avId]) - av.b_setGardenTrophies(range(len(collection) // 10)) + av.b_setGardenTrophies(list(range(len(collection) // 10))) def awardedTrophy(self, todo0): pass diff --git a/toontown/estate/DistributedFireworksCannon.py b/toontown/estate/DistributedFireworksCannon.py index 51a17ed1c..82ada89fd 100644 --- a/toontown/estate/DistributedFireworksCannon.py +++ b/toontown/estate/DistributedFireworksCannon.py @@ -102,5 +102,5 @@ def localShootFirework(self, index): dummy.setPos(0, 100, 60) pos = dummy.getPos(render) dummy.removeNode() - print 'lauFirework: %s, col=%s' % (index, col1) + print(('lauFirework: %s, col=%s' % (index, col1))) self.d_requestFirework(pos[0], pos[1], pos[2], style, col1, col2) \ No newline at end of file diff --git a/toontown/estate/DistributedFlower.py b/toontown/estate/DistributedFlower.py index af8235dba..202b0e640 100644 --- a/toontown/estate/DistributedFlower.py +++ b/toontown/estate/DistributedFlower.py @@ -54,7 +54,7 @@ def showWiltOrBloom(self): desat = wilt.find('**/*desat*') bloom.hide() leaves = wilt.findAllMatches('**/*leaf*') - for leafIndex in xrange(leaves.getNumPaths()): + for leafIndex in range(leaves.getNumPaths()): leaf = leaves.getPath(leafIndex) leaf.setColorScale(1.0, 0.3, 0.1, 1.0) diff --git a/toontown/estate/DistributedFlowerAI.py b/toontown/estate/DistributedFlowerAI.py index 61de65a49..7f8970eab 100644 --- a/toontown/estate/DistributedFlowerAI.py +++ b/toontown/estate/DistributedFlowerAI.py @@ -1,10 +1,10 @@ from direct.directnotify import DirectNotifyGlobal import time -from FlowerBase import FlowerBase +from .FlowerBase import FlowerBase from otp.ai.MagicWordGlobal import * from toontown.estate.DistributedPlantBaseAI import DistributedPlantBaseAI -import GardenGlobals +from . import GardenGlobals class DistributedFlowerAI(DistributedPlantBaseAI, FlowerBase): @@ -41,7 +41,7 @@ def calculate(self, lastCheck): self.update() def update(self): - mdata = map(list, self.mgr.data['flowers']) + mdata = list(map(list, self.mgr.data['flowers'])) mdata[self.flowerIndex] = [self.getSpecies(), self.waterLevel, self.lastCheck, self.getGrowthLevel(), self.getVariety()] self.mgr.data['flowers'] = mdata self.mgr.update() @@ -82,7 +82,7 @@ def _remove(task): self.mgr.flowers.remove(self) - mdata = map(list, self.mgr.data['flowers']) + mdata = list(map(list, self.mgr.data['flowers'])) mdata[self.flowerIndex] = self.mgr.getNullPlant() self.mgr.data['flowers'] = mdata self.mgr.update() diff --git a/toontown/estate/DistributedFurnitureItem.py b/toontown/estate/DistributedFurnitureItem.py index 6e29993a5..4e23ac2eb 100644 --- a/toontown/estate/DistributedFurnitureItem.py +++ b/toontown/estate/DistributedFurnitureItem.py @@ -117,7 +117,7 @@ def __getPosHpr(self): return (pos[0], pos[1], pos[2], hpr[0], 0, 0) def __comparePosHpr(self, a, b, threshold): - for i in xrange(len(a)): + for i in range(len(a)): if abs(a[i] - b[i]) >= threshold: return 1 diff --git a/toontown/estate/DistributedFurnitureManager.py b/toontown/estate/DistributedFurnitureManager.py index f55ec75e2..7ea54cf79 100644 --- a/toontown/estate/DistributedFurnitureManager.py +++ b/toontown/estate/DistributedFurnitureManager.py @@ -33,7 +33,7 @@ def setOwnerId(self, ownerId): if self.ownerId == base.localAvatar.doId: self.cr.furnitureManager = self if self.cr.objectManager == None: - import houseDesign + from . import houseDesign self.cr.objectManager = houseDesign.ObjectManager() def setOwnerName(self, name): diff --git a/toontown/estate/DistributedFurnitureManagerAI.py b/toontown/estate/DistributedFurnitureManagerAI.py index a97e93eb3..3d532731e 100644 --- a/toontown/estate/DistributedFurnitureManagerAI.py +++ b/toontown/estate/DistributedFurnitureManagerAI.py @@ -7,11 +7,11 @@ from toontown.catalog.CatalogFlooringItem import CatalogFlooringItem from toontown.catalog.CatalogWainscotingItem import CatalogWainscotingItem from toontown.toonbase import ToontownGlobals -from DistributedFurnitureItemAI import DistributedFurnitureItemAI -from DistributedPhoneAI import DistributedPhoneAI -from DistributedBankAI import DistributedBankAI -from DistributedClosetAI import DistributedClosetAI -from DistributedTrunkAI import DistributedTrunkAI +from .DistributedFurnitureItemAI import DistributedFurnitureItemAI +from .DistributedPhoneAI import DistributedPhoneAI +from .DistributedBankAI import DistributedBankAI +from .DistributedClosetAI import DistributedClosetAI +from .DistributedTrunkAI import DistributedTrunkAI from otp.ai.MagicWordGlobal import * class FurnitureError(Exception): diff --git a/toontown/estate/DistributedGagTree.py b/toontown/estate/DistributedGagTree.py index 5240101b9..0fc668411 100644 --- a/toontown/estate/DistributedGagTree.py +++ b/toontown/estate/DistributedGagTree.py @@ -82,7 +82,7 @@ def loadModel(self): self.model.reparentTo(self.rotateNode) if self.isFruiting() and not self.isWilted(): self.fruits = [] - for i in xrange(1, self.maxFruit + 1): + for i in range(1, self.maxFruit + 1): pos = self.model.find('**/locator' + str(i)) if pos and not pos.isEmpty(): fruit = self.prop.copyTo(self.model) @@ -346,7 +346,7 @@ def stickParts(self): picker.traverse(render) if queue.getNumEntries() > 0: queue.sortEntries() - for index in xrange(queue.getNumEntries()): + for index in range(queue.getNumEntries()): entry = queue.getEntry(index) if DistributedLawnDecor.recurseParent(entry.getIntoNode(), 'terrain_DNARoot'): self.signModel.wrtReparentTo(render) diff --git a/toontown/estate/DistributedGagTreeAI.py b/toontown/estate/DistributedGagTreeAI.py index f85912f8d..cb1c22fd9 100644 --- a/toontown/estate/DistributedGagTreeAI.py +++ b/toontown/estate/DistributedGagTreeAI.py @@ -1,7 +1,8 @@ from direct.directnotify import DirectNotifyGlobal from otp.ai.MagicWordGlobal import * from toontown.estate.DistributedPlantBaseAI import DistributedPlantBaseAI -import GardenGlobals, time +from . import GardenGlobals +import time PROBLEM_WILTED = 1 PROBLEM_NOT_GROWN = 2 @@ -91,7 +92,7 @@ def delete(self): DistributedPlantBaseAI.delete(self) def update(self): - mdata = map(list, self.mgr.data['trees']) + mdata = list(map(list, self.mgr.data['trees'])) mdata[self.treeIndex] = [self.typeIndex, self.waterLevel, self.lastCheck, self.getGrowthLevel(), self.lastHarvested] self.mgr.data['trees'] = mdata self.mgr.update() @@ -159,7 +160,7 @@ def _remove(task): self.mgr.trees.remove(self) - mdata = map(list, self.mgr.data['trees']) + mdata = list(map(list, self.mgr.data['trees'])) mdata[self.treeIndex] = self.mgr.getNullPlant() self.mgr.data['trees'] = mdata self.mgr.update() diff --git a/toontown/estate/DistributedGarden.py b/toontown/estate/DistributedGarden.py index ae2786a26..ad4884253 100644 --- a/toontown/estate/DistributedGarden.py +++ b/toontown/estate/DistributedGarden.py @@ -13,7 +13,7 @@ from toontown.toonbase import TTLocalizer import random import random -import cPickle +import pickle from toontown.toonbase import ToonPythonUtil as PythonUtil from toontown.hood import Place from toontown.estate import Estate @@ -31,7 +31,7 @@ def __init__(self, cr): self.radius = 0 self.gridCells = 20 self.propTable = [None] * self.gridCells - for i in xrange(len(self.propTable)): + for i in range(len(self.propTable)): self.propTable[i] = [None] * self.gridCells self.dx = 1.0 / self.gridCells @@ -61,10 +61,10 @@ def delete(self): def sendNewProp(self, prop, x, y, z): self.notify.debug('sendNewProp') - print 'new prop (%d) = %s,%s,%s' % (prop, + print(('new prop (%d) = %s,%s,%s' % (prop, x, y, - z) + z))) if prop == HouseGlobals.PROP_ICECUBE: model = loader.loadModel('phase_8/models/props/icecube.bam') elif prop == HouseGlobals.PROP_FLOWER: diff --git a/toontown/estate/DistributedGardenPlot.py b/toontown/estate/DistributedGardenPlot.py index 754a3a76b..cd57f3941 100644 --- a/toontown/estate/DistributedGardenPlot.py +++ b/toontown/estate/DistributedGardenPlot.py @@ -1,9 +1,9 @@ -import DistributedLawnDecor +from . import DistributedLawnDecor from direct.directnotify import DirectNotifyGlobal from direct.showbase.ShowBase import * from direct.interval.IntervalGlobal import * -from DistributedGardenBox import DistributedGardenBox -import GardenGlobals +from .DistributedGardenBox import DistributedGardenBox +from . import GardenGlobals from toontown.toonbase import TTLocalizer from toontown.estate import PlantingGUI from toontown.estate import PlantTreeGUI @@ -66,7 +66,7 @@ def loadModel(self): self.model = None if self.defaultModel: self.model = loader.loadModel(self.defaultModel) - if type(self.plotScale) == types.TupleType: + if type(self.plotScale) == tuple: self.model.setScale(*self.plotScale) else: self.model.setScale(self.plotScale) diff --git a/toontown/estate/DistributedGardenPlotAI.py b/toontown/estate/DistributedGardenPlotAI.py index 2065a1c5b..fcc2635e3 100644 --- a/toontown/estate/DistributedGardenPlotAI.py +++ b/toontown/estate/DistributedGardenPlotAI.py @@ -1,8 +1,8 @@ from direct.directnotify import DirectNotifyGlobal -from DistributedLawnDecorAI import DistributedLawnDecorAI +from .DistributedLawnDecorAI import DistributedLawnDecorAI from otp.ai.MagicWordGlobal import * -import GardenGlobals +from . import GardenGlobals class DistributedGardenPlotAI(DistributedLawnDecorAI): @@ -95,7 +95,7 @@ def plantGagTree(self, track, index): if not av: return - for i in xrange(index): + for i in range(index): if not self.mgr.hasTree(track, i): self.notify.warning('%d %s' % (av.doId, 'tried to plant tree but an index is missing: %d' % index)) return self.d_setMovie(GardenGlobals.MOVIE_PLANT_REJECTED) diff --git a/toontown/estate/DistributedHouseAI.py b/toontown/estate/DistributedHouseAI.py index d21125b11..7aa0e2a4c 100644 --- a/toontown/estate/DistributedHouseAI.py +++ b/toontown/estate/DistributedHouseAI.py @@ -300,7 +300,7 @@ def addAtticItem(self, item): self.atticItems.append(item) elif item.replacesExisting() and item.hasExisting(): if item.getFlags() & FLCloset: - closets = ClosetToClothes.keys() + closets = list(ClosetToClothes.keys()) for itItem in self.interiorItems: if itItem.furnitureType in closets: posHpr = itItem.posHpr diff --git a/toontown/estate/DistributedHouseInterior.py b/toontown/estate/DistributedHouseInterior.py index 3f40eaa85..94ac0a71f 100644 --- a/toontown/estate/DistributedHouseInterior.py +++ b/toontown/estate/DistributedHouseInterior.py @@ -14,7 +14,7 @@ from toontown.catalog import CatalogMouldingItem from toontown.catalog import CatalogWainscotingItem from toontown.dna.DNAParser import DNADoor -import HouseInteriorGlobals +from . import HouseInteriorGlobals WindowPlugNames = ('**/windowcut_a*', '**/windowcut_b*', '**/windowcut_c*', '**/windowcut_d*', '**/windowcut_e*', '**/windowcut_f*') RoomNames = ('**/group2', '**/group1') @@ -105,11 +105,11 @@ def __colorWalls(self): return numSurfaceTypes = CatalogSurfaceItem.NUM_ST_TYPES numRooms = min(len(self.wallpaper) / numSurfaceTypes, len(self.roomNames)) - for room in xrange(numRooms): + for room in range(numRooms): roomName = self.roomNames[room] roomNode = self.interior.find(roomName) if not roomNode.isEmpty(): - for surface in xrange(numSurfaceTypes): + for surface in range(numSurfaceTypes): slot = room * numSurfaceTypes + surface wallpaper = self.wallpaper[slot] color = wallpaper.getColor() diff --git a/toontown/estate/DistributedHouseInteriorAI.py b/toontown/estate/DistributedHouseInteriorAI.py index c8cd3d531..3372060e6 100644 --- a/toontown/estate/DistributedHouseInteriorAI.py +++ b/toontown/estate/DistributedHouseInteriorAI.py @@ -1,5 +1,5 @@ from direct.distributed.DistributedObjectAI import DistributedObjectAI -from DistributedFurnitureManagerAI import * +from .DistributedFurnitureManagerAI import * from toontown.catalog import CatalogItem from toontown.catalog.CatalogWindowItem import CatalogWindowItem from toontown.catalog.CatalogWallpaperItem import CatalogWallpaperItem diff --git a/toontown/estate/DistributedLawnDecor.py b/toontown/estate/DistributedLawnDecor.py index 0d20504a3..f8391f454 100644 --- a/toontown/estate/DistributedLawnDecor.py +++ b/toontown/estate/DistributedLawnDecor.py @@ -181,7 +181,7 @@ def stick2Ground(self, taskfooler = 0): picker.traverse(render) if queue.getNumEntries() > 0: queue.sortEntries() - for index in xrange(queue.getNumEntries()): + for index in range(queue.getNumEntries()): entry = queue.getEntry(index) if recurseParent(entry.getIntoNode(), 'terrain_DNARoot'): self.movieNode.setZ(entry.getSurfacePoint(self)[2]) @@ -190,7 +190,7 @@ def stick2Ground(self, taskfooler = 0): picker.traverse(render) if queue.getNumEntries() > 0: queue.sortEntries() - for index in xrange(queue.getNumEntries()): + for index in range(queue.getNumEntries()): entry = queue.getEntry(index) if recurseParent(entry.getIntoNode(), 'terrain_DNARoot'): self.setZ(entry.getSurfacePoint(render)[2] + self.stickUp + 0.1) @@ -271,7 +271,7 @@ def generateToonMoveTrack(self, toon): return toonTrack def unprint(self, string): - print string + print(string) def startInteraction(self): place = base.cr.playGame.getPlace() diff --git a/toontown/estate/DistributedMailbox.py b/toontown/estate/DistributedMailbox.py index fe9d95702..f9ac8f0c4 100644 --- a/toontown/estate/DistributedMailbox.py +++ b/toontown/estate/DistributedMailbox.py @@ -220,7 +220,7 @@ def acceptInvite(self, item, acceptingIndex, callback, optional = -1): def acceptItemResponse(self, context, retcode): DistributedMailbox.notify.debug('acceptItemResponse') if retcode == ToontownGlobals.P_UserCancelled: - print 'DistributedMailbox User Canceled' + print('DistributedMailbox User Canceled') self.doCallbackContext(context, [retcode]) def discardItem(self, item, index, callback, optional = -1): diff --git a/toontown/estate/DistributedPhone.py b/toontown/estate/DistributedPhone.py index a38bdd7a0..e782589bc 100644 --- a/toontown/estate/DistributedPhone.py +++ b/toontown/estate/DistributedPhone.py @@ -372,7 +372,7 @@ def ring(self): w = 0.05 shakeOnce = Sequence(Func(phone.setR, r), Wait(w), Func(phone.setR, -r), Wait(w)) shakeSeq = Sequence() - for i in xrange(16): + for i in range(16): shakeSeq.append(shakeOnce) ringIval = Parallel(Func(base.playSfx, self.ringSfx), shakeSeq, Func(phone.setR, 0)) diff --git a/toontown/estate/DistributedPlantBase.py b/toontown/estate/DistributedPlantBase.py index 0c9e0b3a3..87c9ec54a 100644 --- a/toontown/estate/DistributedPlantBase.py +++ b/toontown/estate/DistributedPlantBase.py @@ -1,4 +1,4 @@ -import DistributedLawnDecor +from . import DistributedLawnDecor from direct.interval.IntervalGlobal import * from direct.directnotify import DirectNotifyGlobal from direct.showbase.ShowBase import * @@ -16,7 +16,7 @@ def __init__(self, cr): def delete(self): self.notify.debug('delete') - for waterTrack in self.waterTrackDict.values(): + for waterTrack in list(self.waterTrackDict.values()): if waterTrack: waterTrack.finish() diff --git a/toontown/estate/DistributedStatuaryAI.py b/toontown/estate/DistributedStatuaryAI.py index 090d5b11d..df7beb4e2 100644 --- a/toontown/estate/DistributedStatuaryAI.py +++ b/toontown/estate/DistributedStatuaryAI.py @@ -1,8 +1,8 @@ from direct.directnotify import DirectNotifyGlobal import time -from DistributedLawnDecorAI import DistributedLawnDecorAI -import GardenGlobals +from .DistributedLawnDecorAI import DistributedLawnDecorAI +from . import GardenGlobals class DistributedStatuaryAI(DistributedLawnDecorAI): diff --git a/toontown/estate/DistributedTargetAI.py b/toontown/estate/DistributedTargetAI.py index a293d04ed..47fed8d1c 100644 --- a/toontown/estate/DistributedTargetAI.py +++ b/toontown/estate/DistributedTargetAI.py @@ -1,7 +1,7 @@ from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI from panda3d.core import * -import CannonGlobals +from . import CannonGlobals class DistributedTargetAI(DistributedObjectAI): notify = DirectNotifyGlobal.directNotify.newCategory("DistributedTargetAI") diff --git a/toontown/estate/DistributedToonStatuary.py b/toontown/estate/DistributedToonStatuary.py index 26c0d8dc9..83a159472 100644 --- a/toontown/estate/DistributedToonStatuary.py +++ b/toontown/estate/DistributedToonStatuary.py @@ -112,7 +112,7 @@ def removeTextures(self): if sleeves: sleeves.setTexture(desatSleeveTex, 1) bottoms = torso.findAllMatches('**/torso-bot*') - for bottomNum in xrange(0, bottoms.getNumPaths()): + for bottomNum in range(0, bottoms.getNumPaths()): bottom = bottoms.getPath(bottomNum) if bottom: if self.toon.style.torso[1] == 's': diff --git a/toontown/estate/DistributedTrunk.py b/toontown/estate/DistributedTrunk.py index 543e4a973..1d61eb684 100644 --- a/toontown/estate/DistributedTrunk.py +++ b/toontown/estate/DistributedTrunk.py @@ -34,15 +34,15 @@ def __init__(self, cr): self.isFreePlayer = 0 def printInfo(self): - print 'avid: %s, gender: %s' % (self.av.doId, self.av.style.gender) - print 'current hat = %s, glasses = %s, backpack = %s, shoes = %s' % (self.av.getHat(), + print(('avid: %s, gender: %s' % (self.av.doId, self.av.style.gender))) + print(('current hat = %s, glasses = %s, backpack = %s, shoes = %s' % (self.av.getHat(), self.av.getGlasses(), self.av.getBackpack(), - self.av.getShoes()) - print 'hatList = %s' % self.av.getHatList() - print 'glassesList = %s' % self.av.getGlassesList() - print 'backpackList = %s' % self.av.getBackpackList() - print 'shoesList = %s' % self.av.getShoesList() + self.av.getShoes()))) + print(('hatList = %s' % self.av.getHatList())) + print(('glassesList = %s' % self.av.getGlassesList())) + print(('backpackList = %s' % self.av.getBackpackList())) + print(('shoesList = %s' % self.av.getShoesList())) def setState(self, mode, avId, ownerId, gender, hatList, glassesList, backpackList, shoesList): self.notify.debug('setState, mode=%s, avId=%s, ownerId=%d' % (mode, avId, ownerId)) diff --git a/toontown/estate/EstateLoader.py b/toontown/estate/EstateLoader.py index 7ffb5ddee..e3285554c 100644 --- a/toontown/estate/EstateLoader.py +++ b/toontown/estate/EstateLoader.py @@ -50,15 +50,15 @@ def load(self): self.underwaterSound = base.loader.loadSfx('phase_4/audio/sfx/AV_ambient_water.ogg') self.swimSound = base.loader.loadSfx('phase_4/audio/sfx/AV_swim_single_stroke.ogg') self.submergeSound = base.loader.loadSfx('phase_5.5/audio/sfx/AV_jump_in_water.ogg') - self.birdSound = map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg']) - self.cricketSound = map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg']) + self.birdSound = list(map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg'])) + self.cricketSound = list(map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg'])) if base.goonsEnabled: invModel = loader.loadModel('phase_3.5/models/gui/inventory_icons') self.invModels = [] from toontown.toonbase import ToontownBattleGlobals - for track in xrange(len(ToontownBattleGlobals.AvPropsNew)): + for track in range(len(ToontownBattleGlobals.AvPropsNew)): itemList = [] - for item in xrange(len(ToontownBattleGlobals.AvPropsNew[track])): + for item in range(len(ToontownBattleGlobals.AvPropsNew[track])): itemList.append(invModel.find('**/' + ToontownBattleGlobals.AvPropsNew[track][item])) self.invModels.append(itemList) @@ -126,10 +126,10 @@ def createSafeZone(self, dnaFile): self.loadSunMoon() def loadHouses(self): - for i in xrange(HouseGlobals.NUM_HOUSE_TYPES): + for i in range(HouseGlobals.NUM_HOUSE_TYPES): self.houseModels[i] = loader.loadModel(HouseGlobals.houseModels[i]) - for i in xrange(6): + for i in range(6): posHpr = HouseGlobals.houseDrops[i] self.houseNode[i] = self.geom.attachNewNode('esHouse_' + str(i)) self.houseNode[i].setPosHpr(*posHpr) @@ -277,15 +277,15 @@ def __cloudTrack(self): return track def debugGeom(self, decomposed): - print 'numPrimitives = %d' % decomposed.getNumPrimitives() - for primIndex in xrange(decomposed.getNumPrimitives()): + print(('numPrimitives = %d' % decomposed.getNumPrimitives())) + for primIndex in range(decomposed.getNumPrimitives()): prim = decomposed.getPrimitive(primIndex) - print 'prim = %s' % prim - print 'isIndexed = %d' % prim.isIndexed() - print 'prim.getNumPrimitives = %d' % prim.getNumPrimitives() - for basicPrim in xrange(prim.getNumPrimitives()): - print '%d start=%d' % (basicPrim, prim.getPrimitiveStart(basicPrim)) - print '%d end=%d' % (basicPrim, prim.getPrimitiveEnd(basicPrim)) + print(('prim = %s' % prim)) + print(('isIndexed = %d' % prim.isIndexed())) + print(('prim.getNumPrimitives = %d' % prim.getNumPrimitives())) + for basicPrim in range(prim.getNumPrimitives()): + print(('%d start=%d' % (basicPrim, prim.getPrimitiveStart(basicPrim)))) + print(('%d end=%d' % (basicPrim, prim.getPrimitiveEnd(basicPrim)))) def loadOnePlatform(self, version, radius, zOffset, score, multiplier): self.notify.debug('loadOnePlatform version=%d' % version) @@ -314,15 +314,15 @@ def loadCloudPlatforms(self): self.loadSkyCollision() self.numClouds = 12 pinballScore = PinballScoring[PinballCloudBumperLow] - for i in xrange(12): + for i in range(12): self.loadOnePlatform(i, 40, 0, pinballScore[0], pinballScore[1]) pinballScore = PinballScoring[PinballCloudBumperMed] - for i in xrange(12): + for i in range(12): self.loadOnePlatform(i, 60, 40, pinballScore[0], pinballScore[1]) pinballScore = PinballScoring[PinballCloudBumperHigh] - for i in xrange(12): + for i in range(12): self.loadOnePlatform(i, 20, 80, pinballScore[0], pinballScore[1]) self.cloudOrigin.stash() diff --git a/toontown/estate/EstateManagerAI.py b/toontown/estate/EstateManagerAI.py index c00f309b2..f3a1fc260 100644 --- a/toontown/estate/EstateManagerAI.py +++ b/toontown/estate/EstateManagerAI.py @@ -244,7 +244,7 @@ def exitLoadEstate(self): def enterLoadHouses(self): self.houseFSMs = [] - for houseIndex in xrange(6): + for houseIndex in range(6): fsm = LoadHouseFSM(self.mgr, self.estate, houseIndex, self.toons[houseIndex], self.__houseDone) self.houseFSMs.append(fsm) diff --git a/toontown/estate/FireworksGui.py b/toontown/estate/FireworksGui.py index 2b277f5c8..b8cd12118 100644 --- a/toontown/estate/FireworksGui.py +++ b/toontown/estate/FireworksGui.py @@ -47,7 +47,7 @@ def load(self): self.hilightColor = VBase4(1, 1, 1, 1) self.bgColor = VBase4(0.8, 0.8, 0.8, 1) self.colorButtons = [] - for i in Fireworks.colors.keys(): + for i in list(Fireworks.colors.keys()): color = Fireworks.colors[i] height = 0.07 paddedHeight = 0.1 @@ -79,7 +79,7 @@ def __initColor(self, index): def __handleColor(self, index): color = Fireworks.colors[index] - for i in xrange(len(self.colorButtons)): + for i in range(len(self.colorButtons)): self.colorButtons[i][1]['geom_color'] = self.bgColor self.colorButtons[i][1].setScale(1) diff --git a/toontown/estate/FlowerBase.py b/toontown/estate/FlowerBase.py index 75b34e1b3..e28593eb9 100644 --- a/toontown/estate/FlowerBase.py +++ b/toontown/estate/FlowerBase.py @@ -8,8 +8,8 @@ class FlowerBase: def __init__(self, species, variety): self.species = species self.variety = variety - if self.species not in GardenGlobals.PlantAttributes.keys(): - print 'remove me when everyone is updated' + if self.species not in list(GardenGlobals.PlantAttributes.keys()): + print('remove me when everyone is updated') self.species = 56 species = 56 diff --git a/toontown/estate/FlowerBasket.py b/toontown/estate/FlowerBasket.py index 0529febc1..49bb2d30c 100644 --- a/toontown/estate/FlowerBasket.py +++ b/toontown/estate/FlowerBasket.py @@ -50,7 +50,7 @@ def generateRandomBasket(self): import random numFish = random.randint(1, 20) self.flowerList = [] - for i in xrange(numFish): + for i in range(numFish): species, variety = GardenGlobals.getRandomFlower() self.addFlower(species, variety) diff --git a/toontown/estate/FlowerBrowser.py b/toontown/estate/FlowerBrowser.py index 47ca647bd..fa0531eaf 100644 --- a/toontown/estate/FlowerBrowser.py +++ b/toontown/estate/FlowerBrowser.py @@ -31,7 +31,7 @@ def __init__(self, parent = aspect2d, **kw): ('decButton_pos', (0, 0, 0.525), None), ('decButton_image3_color', Vec4(0.8, 0.8, 0.8, 0.5), None), ('numItemsVisible', 1, None), - ('items', map(str, GardenGlobals.getFlowerSpecies()), None), + ('items', list(map(str, GardenGlobals.getFlowerSpecies())), None), ('scrollSpeed', 4, None), ('itemMakeFunction', FlowerSpeciesPanel.FlowerSpeciesPanel, None), ('itemMakeExtraArgs', base.localAvatar.flowerCollection, None)) diff --git a/toontown/estate/FlowerPanel.py b/toontown/estate/FlowerPanel.py index d3546c241..55fb82415 100644 --- a/toontown/estate/FlowerPanel.py +++ b/toontown/estate/FlowerPanel.py @@ -74,8 +74,8 @@ def handleCancel(self): def show(self, code = GardenGlobals.FlowerItem): messenger.send('wakeup') - apply(self.photo.setSwimBounds, self.swimBounds) - apply(self.photo.setSwimColor, self.swimColor) + self.photo.setSwimBounds(*self.swimBounds) + self.photo.setSwimColor(*self.swimColor) if code == GardenGlobals.FlowerItem: self.extraLabel.hide() elif code == GardenGlobals.FlowerItemNewEntry: diff --git a/toontown/estate/FlowerPhoto.py b/toontown/estate/FlowerPhoto.py index d4810ac77..b88cfef22 100644 --- a/toontown/estate/FlowerPhoto.py +++ b/toontown/estate/FlowerPhoto.py @@ -42,9 +42,9 @@ def load(self): self.cCamNode.setScene(self.cRender) self.fishSwimCam = self.fishSwimCamera.attachNewNode(self.cCamNode) cm = CardMaker('displayRegionCard') - apply(cm.setFrame, self.bounds) + cm.setFrame(*self.bounds) self.card = card = self.attachNewNode(cm.generate()) - apply(card.setColor, self.color) + card.setColor(*self.color) newBounds = card.getTightBounds() ll = render2d.getRelativePoint(card, newBounds[0]) ur = render2d.getRelativePoint(card, newBounds[1]) @@ -52,7 +52,7 @@ def load(self): ur.getX(), ll.getZ(), ur.getZ()] - newBounds = map(lambda x: max(0.0, min(1.0, (x + 1.0) / 2.0)), newBounds) + newBounds = [max(0.0, min(1.0, (x + 1.0) / 2.0)) for x in newBounds] self.cDr = base.win.makeDisplayRegion(*newBounds) self.cDr.setSort(10) self.cDr.setClearColor(card.getColor()) @@ -113,8 +113,8 @@ def makeFlowerFrame(self, actor): actor.setDepthWrite(1) if not hasattr(self, 'flowerDisplayRegion'): self.flowerDisplayRegion = DirectRegion(parent=self) - apply(self.flowerDisplayRegion.setBounds, self.swimBounds) - apply(self.flowerDisplayRegion.setColor, self.swimColor) + self.flowerDisplayRegion.setBounds(*self.swimBounds) + self.flowerDisplayRegion.setColor(*self.swimColor) frame = self.flowerDisplayRegion.load() pitch = frame.attachNewNode('pitch') rotate = pitch.attachNewNode('rotate') diff --git a/toontown/estate/FlowerSpeciesPanel.py b/toontown/estate/FlowerSpeciesPanel.py index b9de7ea75..cb4f833e3 100644 --- a/toontown/estate/FlowerSpeciesPanel.py +++ b/toontown/estate/FlowerSpeciesPanel.py @@ -82,7 +82,7 @@ def setSpecies(self, species): startPos = len(varietyList) / 2 * offset if not len(varietyList) % 2: startPos -= offset / 2 - for variety in xrange(len(varietyList)): + for variety in range(len(varietyList)): label = DirectButton(parent=self, frameSize=(0, 0.445, -0.02, @@ -120,7 +120,7 @@ def update(self): if base.localAvatar.flowerCollection.hasSpecies(self.species): self.flowerPanel.show(showBackground=0) self['text'] = TTLocalizer.FlowerSpeciesNames[self.species] - for variety in xrange(len(GardenGlobals.getFlowerVarieties(self.species))): + for variety in range(len(GardenGlobals.getFlowerVarieties(self.species))): if base.localAvatar.flowerCollection.hasFlower(self.species, variety): name = GardenGlobals.getFlowerVarietyName(self.species, variety) self.speciesLabels[variety]['text'] = name diff --git a/toontown/estate/GardenDropGame.py b/toontown/estate/GardenDropGame.py index 853580a1a..8241ff125 100644 --- a/toontown/estate/GardenDropGame.py +++ b/toontown/estate/GardenDropGame.py @@ -17,7 +17,7 @@ from toontown.toonbase import TTLocalizer import random import random -import cPickle +import pickle from toontown.toonbase import ToonPythonUtil as PythonUtil from toontown.estate import GameSprite from math import pi @@ -62,15 +62,15 @@ def __init__(self): self.controlOffsetX = 0.0 self.controlOffsetZ = 0.0 self.queExtent = 3 - print 'Grid Dimensions X%s Z%s' % (gX, gZ) + print(('Grid Dimensions X%s Z%s' % (gX, gZ))) self.grid = [] self.gridDimX = gX self.gridDimZ = gZ self.gridBrick = False base.gardenGame = self - for countX in xrange(self.gridDimX): + for countX in range(self.gridDimX): newRow = [] - for countZ in xrange(self.gridDimZ): + for countZ in range(self.gridDimZ): offset = 0 if countZ % 2 == 0: offset = size / 2 @@ -81,7 +81,7 @@ def __init__(self): self.controlSprite = None self.cogSprite = self.addUnSprite(self.block, posX=0.25, posZ=0.5) self.cogSprite.setColor(self.colorShadow) - for ball in xrange(0, 3): + for ball in range(0, 3): place = random.random() * self.rangeX newSprite = self.addSprite(self.block, size=0.5, posX=self.minX + place, posZ=0.0, found=1) self.stickInGrid(newSprite, 1) @@ -99,8 +99,8 @@ def __init__(self): def findGrid(self, x, z, force = 0): currentClosest = None currentDist = 10000000 - for countX in xrange(self.gridDimX): - for countZ in xrange(self.gridDimZ): + for countX in range(self.gridDimX): + for countZ in range(self.gridDimZ): testDist = self.testPointDistanceSquare(x, z, self.grid[countX][countZ][1], self.grid[countX][countZ][2]) if self.grid[countX][countZ][0] == None and testDist < currentDist and (force or self.hasNeighbor(countX, countZ)): currentClosest = self.grid[countX][countZ] @@ -242,7 +242,7 @@ def findGrid2(self, x, z): tileDimZ = rangeZ / self.gridDimZ tileX = int(framedX / tileDimX) tileZ = int(framedZ / tileDimZ) - print 'find Grid tileX%s tileZ%s' % (tileX, tileZ) + print(('find Grid tileX%s tileZ%s' % (tileX, tileZ))) return (tileX, tileZ) def findPos(self, x, z): @@ -252,7 +252,7 @@ def findPos(self, x, z): tileDimZ = rangeZ / self.gridDimZ posX = tileDimX * x + self.minX posZ = tileDimZ * z + self.minZ - print 'find Pos X%s Z%s' % (posX, posZ) + print(('find Pos X%s Z%s' % (posX, posZ))) return (posX, posZ) def placeIntoGrid(self, sprite, x, z): @@ -262,7 +262,7 @@ def placeIntoGrid(self, sprite, x, z): newX, newZ = self.findPos(x, z) sprite.setX(newX) sprite.setZ(newZ) - print 'Setting Final Pos X%s Z%s' % (newX, newZ) + print(('Setting Final Pos X%s Z%s' % (newX, newZ))) else: self.placeIntoGrid(sprite, x + 1, z - 1) @@ -327,7 +327,7 @@ def __acceptExit(self, buttonValue = None): def addSprite(self, image, size = 0.5, posX = 0, posZ = 0, found = 0): nodeObj = DirectLabel(parent=self.frame, relief=None, image=image, pos=(posX, 0.0, posZ), scale=size, image_color=(1.0, 1.0, 1.0, 1)) - colorChoice = random.choice(range(0, 3)) + colorChoice = random.choice(list(range(0, 3))) newSprite = GameSprite.GameSprite(nodeObj, colorChoice, found) self.sprites.append(newSprite) if found: @@ -407,8 +407,8 @@ def __colTest(self): if self.tick > 5: self.tick = 0 sizeSprites = len(self.sprites) - for movingSpriteIndex in xrange(len(self.sprites)): - for testSpriteIndex in xrange(movingSpriteIndex, len(self.sprites)): + for movingSpriteIndex in range(len(self.sprites)): + for testSpriteIndex in range(movingSpriteIndex, len(self.sprites)): movingSprite = self.getSprite(movingSpriteIndex) testSprite = self.getSprite(testSpriteIndex) if testSprite and movingSprite: diff --git a/toontown/estate/GardenGlobals.py b/toontown/estate/GardenGlobals.py index b8d01da0a..15bbdadfc 100644 --- a/toontown/estate/GardenGlobals.py +++ b/toontown/estate/GardenGlobals.py @@ -54,7 +54,7 @@ def getWateringCanPower(wateringCan, wateringCanSkill): def getMaxWateringCanPower(): retval = 0 - for wateringCanAttrib in WateringCanAttributes.values(): + for wateringCanAttrib in list(WateringCanAttributes.values()): retval += wateringCanAttrib['numBoxes'] return retval * WateringMult @@ -76,9 +76,9 @@ def getMaxWateringCanPower(): FLOWER_YELLOW = 5 FLOWER_WHITE = 6 FLOWER_GREEN = 7 -ToonStatuaryTypeIndices = range(205, 209) -ChangingStatuaryTypeIndices = range(230, 232) -AnimatedStatuaryTypeIndices = range(234, 238) +ToonStatuaryTypeIndices = list(range(205, 209)) +ChangingStatuaryTypeIndices = list(range(230, 232)) +AnimatedStatuaryTypeIndices = list(range(234, 238)) PlantAttributes = {49: {'name': TTLocalizer.FlowerSpeciesNames[49], 'plantType': FLOWER_TYPE, 'growthThresholds': (1, 1, 1), @@ -306,7 +306,7 @@ def getMaxWateringCanPower(): del PlantAttributes[202] def getTreeTrackAndLevel(typeIndex): - track = typeIndex / 7 + track = typeIndex // 7 level = typeIndex % 7 return (track, level) @@ -467,7 +467,7 @@ def getTreeTypeIndex(track, level): def getRecipeKey(beans, special): testDict = {'beans': beans, 'special': special} - for key in Recipes.keys(): + for key in list(Recipes.keys()): recipe = Recipes[key] if testDict == recipe: return key @@ -476,7 +476,7 @@ def getRecipeKey(beans, special): def getRecipeKeyUsingSpecial(special): - for key in Recipes.keys(): + for key in list(Recipes.keys()): recipe = Recipes[key] if recipe['special'] == special: return key @@ -528,7 +528,7 @@ def getMaxShovelSkill(): def getNumberOfShovelBoxes(): retVal = 0 - for attrib in ShovelAttributes.values(): + for attrib in list(ShovelAttributes.values()): retVal += attrib['numBoxes'] return retVal @@ -536,7 +536,7 @@ def getNumberOfShovelBoxes(): def getNumberOfWateringCanBoxes(): retVal = 0 - for attrib in WateringCanAttributes.values(): + for attrib in list(WateringCanAttributes.values()): retVal += attrib['numBoxes'] return retVal @@ -544,7 +544,7 @@ def getNumberOfWateringCanBoxes(): def getNumberOfFlowerVarieties(): retVal = 0 - for attrib in PlantAttributes.values(): + for attrib in list(PlantAttributes.values()): if attrib['plantType'] == FLOWER_TYPE: retVal += len(attrib['varieties']) @@ -553,7 +553,7 @@ def getNumberOfFlowerVarieties(): def getNumberOfFlowerSpecies(): retVal = 0 - for attrib in PlantAttributes.values(): + for attrib in list(PlantAttributes.values()): if attrib['plantType'] == FLOWER_TYPE: retVal += 1 @@ -562,7 +562,7 @@ def getNumberOfFlowerSpecies(): def getFlowerVarieties(species): retval = () - if species in PlantAttributes.keys(): + if species in list(PlantAttributes.keys()): attrib = PlantAttributes[species] if attrib['plantType'] == FLOWER_TYPE: retval = attrib['varieties'] @@ -571,7 +571,7 @@ def getFlowerVarieties(species): def getFlowerSpecies(): retVal = [] - for key in PlantAttributes.keys(): + for key in list(PlantAttributes.keys()): attrib = PlantAttributes[key] if attrib['plantType'] == FLOWER_TYPE: retVal.append(key) @@ -587,7 +587,7 @@ def getRandomFlower(): def getFlowerVarietyName(species, variety): retVal = TTLocalizer.FlowerUnknown - if species in PlantAttributes.keys(): + if species in list(PlantAttributes.keys()): attrib = PlantAttributes[species] if variety < len(attrib['varieties']): funnySpeciesNameList = TTLocalizer.FlowerFunnyNames.get(species) @@ -602,7 +602,7 @@ def getFlowerVarietyName(species, variety): def getSpeciesVarietyGivenRecipe(recipeKey): - for species in PlantAttributes.keys(): + for species in list(PlantAttributes.keys()): attrib = PlantAttributes[species] if attrib['plantType'] == GAG_TREE_TYPE: continue @@ -635,7 +635,7 @@ def validateRecipes(notify): uniqueBeans = [] numBoxes = getNumberOfShovelBoxes() uniqueSpecials = [] - for key in Recipes.keys(): + for key in list(Recipes.keys()): recipe = Recipes[key] beans = recipe['beans'] if len(beans) > numBoxes: @@ -665,7 +665,7 @@ def validatePlantAttributes(notify): for i in range(getNumberOfShovelBoxes() + 1): flowerRecipeDistribution.append([]) - for key in PlantAttributes.keys(): + for key in list(PlantAttributes.keys()): plant = PlantAttributes[key] notify.debug('now validating %s' % plant['name']) if plant['plantType'] in (GAG_TREE_TYPE, FLOWER_TYPE): @@ -1494,7 +1494,7 @@ def getPlantItWithString(special): return retval -for specialKey in Specials.keys(): +for specialKey in list(Specials.keys()): recipeKey = getRecipeKeyUsingSpecial(specialKey) if not recipeKey == -1: Specials[specialKey]['description'] = getPlantItWithString(specialKey) diff --git a/toontown/estate/GardenProgressMeter.py b/toontown/estate/GardenProgressMeter.py index 44054af0f..9f965b416 100644 --- a/toontown/estate/GardenProgressMeter.py +++ b/toontown/estate/GardenProgressMeter.py @@ -16,7 +16,7 @@ from toontown.toonbase import TTLocalizer import random import random -import cPickle +import pickle from toontown.toonbase import ToonPythonUtil as PythonUtil from toontown.estate import GameSprite from math import pi @@ -35,7 +35,7 @@ def __init__(self, typePromotion = 'game', level = 0): elif typePromotion == 'game': self.typePromotion == GAMEWIN else: - print 'No type of %s' % typePromotion + print(('No type of %s' % typePromotion)) self.level = level self.acceptErrorDialog = None self.doneEvent = 'game Done' diff --git a/toontown/estate/PlantingGUI.py b/toontown/estate/PlantingGUI.py index 260d50814..fe2bce09c 100644 --- a/toontown/estate/PlantingGUI.py +++ b/toontown/estate/PlantingGUI.py @@ -105,7 +105,7 @@ def createJellyBeanBox(self, beanIndex, xPos, zPos): self.jellyBeanBoxList.append(newBox) def setColorText(self): - for beanIndex in xrange(len(self.jellyBeanBoxList)): + for beanIndex in range(len(self.jellyBeanBoxList)): if JELLY_BEAN_PICKER_HAS_EMPTY_BOX: if beanIndex: box = self.jellyBeanBoxList[beanIndex] @@ -122,7 +122,7 @@ def createJellyBeanBoxes(self): if JELLY_BEAN_PICKER_HAS_EMPTY_BOX: maxBoxes += 1 startingXCoord = -0.1 * float(maxBoxes) / 2.0 + 0.075 - for activeBox in xrange(maxBoxes): + for activeBox in range(maxBoxes): xPos = xIncrement * activeBox + startingXCoord self.createJellyBeanBox(activeBox, xPos, zCoord) @@ -250,14 +250,14 @@ def createBoxes(self): xIncrement = 0.1 xPos = 0 startingXCoord = -0.1 * float(self.maxBoxes) / 2.0 + 0.05 - for activeBox in xrange(self.availableBoxes): + for activeBox in range(self.availableBoxes): xPos = xIncrement * activeBox + startingXCoord if USE_SCROLLING_BEAN_BOX: self.createScrollingBeanBox(activeBox, xPos, zCoord, True) else: self.createSpiffyBeanBox(activeBox, xPos, zCoord, True) - for disabledBox in xrange(self.availableBoxes, self.maxBoxes): + for disabledBox in range(self.availableBoxes, self.maxBoxes): xPos = xIncrement * disabledBox + startingXCoord if USE_SCROLLING_BEAN_BOX: self.createScrollingBeanBox(disabledBox, xPos, zCoord, False) @@ -316,7 +316,7 @@ def createScrollingBeanBox(self, index, xPos, zPos, active): if active: tempItem = BoxItem(self.attachNewNode('emptyBean')) items.append(tempItem) - for curBean in xrange(len(GardenGlobals.BeanColors)): + for curBean in range(len(GardenGlobals.BeanColors)): tempItem = BoxItem(self.attachNewNode('bean-%d-%d' % (index, curBean))) loadJellyBean(tempItem, curBean) items.append(tempItem) @@ -360,7 +360,7 @@ def matchBoxesToAvailableMoney(self): if FORCE_LEFT_TO_RIGHT: boxIndexToEnable = len(self.getRecipeStr()) - for i in xrange(0, boxIndexToEnable): + for i in range(0, boxIndexToEnable): box = self.boxList[i] if ONLY_ONE_SPIFFY_BOX_CAN_BE_CLICKED: box['state'] = DGG.DISABLED @@ -373,7 +373,7 @@ def matchBoxesToAvailableMoney(self): box['state'] = DGG.DISABLED box.setState() box.setColorScale(0.5, 0.5, 0.5, 1) - for i in xrange(boxIndexToEnable + 1, len(self.boxList)): + for i in range(boxIndexToEnable + 1, len(self.boxList)): box = self.boxList[i] box['state'] = DGG.DISABLED box.setState() diff --git a/toontown/estate/SpecialsPhoto.py b/toontown/estate/SpecialsPhoto.py index 2146d332c..91c23fc19 100644 --- a/toontown/estate/SpecialsPhoto.py +++ b/toontown/estate/SpecialsPhoto.py @@ -2,7 +2,7 @@ from panda3d.core import * from direct.interval.IntervalGlobal import * from toontown.fishing import FishGlobals -import GardenGlobals +from . import GardenGlobals from direct.actor import Actor import random @@ -43,9 +43,9 @@ def load(self): self.cCamNode.setScene(self.cRender) self.fishSwimCam = self.fishSwimCamera.attachNewNode(self.cCamNode) cm = CardMaker('displayRegionCard') - apply(cm.setFrame, self.bounds) + cm.setFrame(*self.bounds) self.card = card = self.attachNewNode(cm.generate()) - apply(card.setColor, self.color) + card.setColor(*self.color) newBounds = card.getTightBounds() ll = render2d.getRelativePoint(card, newBounds[0]) ur = render2d.getRelativePoint(card, newBounds[1]) @@ -53,7 +53,7 @@ def load(self): ur.getX(), ll.getZ(), ur.getZ()] - newBounds = map(lambda x: max(0.0, min(1.0, (x + 1.0) / 2.0)), newBounds) + newBounds = [max(0.0, min(1.0, (x + 1.0) / 2.0)) for x in newBounds] self.cDr = base.win.makeDisplayRegion(*newBounds) self.cDr.setSort(10) self.cDr.setClearColor(card.getColor()) @@ -118,8 +118,8 @@ def makeSpecialsFrame(self, actor): actor.setDepthWrite(1) if not hasattr(self, 'specialsDisplayRegion'): self.specialsDisplayRegion = DirectRegion(parent=self) - apply(self.specialsDisplayRegion.setBounds, self.backBounds) - apply(self.specialsDisplayRegion.setColor, self.backColor) + self.specialsDisplayRegion.setBounds(*self.backBounds) + self.specialsDisplayRegion.setColor(*self.backColor) frame = self.specialsDisplayRegion.load() pitch = frame.attachNewNode('pitch') rotate = pitch.attachNewNode('rotate') diff --git a/toontown/estate/houseDesign.py b/toontown/estate/houseDesign.py index 621617cd4..51d0821cc 100644 --- a/toontown/estate/houseDesign.py +++ b/toontown/estate/houseDesign.py @@ -539,7 +539,7 @@ def moveObjectStop(self, *args): self.selectedObject.wrtReparentTo(self.targetNodePath) self.selectedObject.collisionNodePath.unstash() self.selectedObject.dfitem.stopAdjustPosHpr() - for object in self.objectDict.values(): + for object in list(self.objectDict.values()): object.unstashBuiltInCollisionNodes() self.centerMarker['image'] = [self.grabUp, self.grabDown, self.grabRollover] @@ -553,7 +553,7 @@ def moveObjectStart(self): def moveObjectContinue(self, *args): messenger.send('wakeup') if self.selectedObject: - for object in self.objectDict.values(): + for object in list(self.objectDict.values()): object.stashBuiltInCollisionNodes() self.selectedObject.collisionNodePath.stash() @@ -567,7 +567,7 @@ def moveObjectContinue(self, *args): self.movingObject = 1 def setLnpColor(self, r, g, b): - for i in xrange(5): + for i in range(5): self.lnp.lineSegs.setVertexColor(i, r, g, b) def markNewPosition(self, isValid): @@ -648,7 +648,7 @@ def collisionTest(self): entry = self.iSegment.findNextCollisionEntry(skipFlags=SKIP_CAMERA | SKIP_UNPICKABLE) if offsetDict: - keys = offsetDict.keys() + keys = list(offsetDict.keys()) ortho1 = offsetDict[keys[0]] ortho2 = Vec3(0) v1 = Vec3(ortho1) @@ -820,7 +820,7 @@ def moveObjectInit(self): self.selectedObject.wrtReparentTo(self.collisionOffsetNP) def resetFurniture(self): - for o in self.objectDict.values(): + for o in list(self.objectDict.values()): o.resetMovableObject() self.objectDict = {} @@ -937,7 +937,7 @@ def createMainControls(self, guiModels): self.bindHelpText(self.inRoomButton, 'Room') self.inTrashButton = DirectButton(parent=self.itemBackgroundFrame, relief=None, text=TTLocalizer.HDInTrashLabel, text_pos=(-0.1, -0.25), image=[tagUp, tagDown, tagRollover], pos=(2.85, 0, -1.8), scale=0.8, command=self.showInTrashPicker) self.bindHelpText(self.inTrashButton, 'Trash') - for i in xrange(4): + for i in range(4): self.inAtticButton.component('text%d' % i).setR(-90) self.inRoomButton.component('text%d' % i).setR(-90) self.inTrashButton.component('text%d' % i).setR(-90) @@ -1000,17 +1000,17 @@ def createMainControls(self, guiModels): def createAtticPicker(self): self.atticItemPanels = [] - for itemIndex in xrange(len(self.furnitureManager.atticItems)): + for itemIndex in range(len(self.furnitureManager.atticItems)): panel = FurnitureItemPanel(self.furnitureManager.atticItems[itemIndex], itemIndex, command=self.bringItemFromAttic, deleteMode=self.deleteMode, helpCategory='FurnitureItemPanelAttic') self.atticItemPanels.append(panel) self.atticWallpaperPanels = [] - for itemIndex in xrange(len(self.furnitureManager.atticWallpaper)): + for itemIndex in range(len(self.furnitureManager.atticWallpaper)): panel = FurnitureItemPanel(self.furnitureManager.atticWallpaper[itemIndex], itemIndex, command=self.bringWallpaperFromAttic, deleteMode=self.deleteMode, helpCategory='FurnitureItemPanelAttic') self.atticWallpaperPanels.append(panel) self.atticWindowPanels = [] - for itemIndex in xrange(len(self.furnitureManager.atticWindows)): + for itemIndex in range(len(self.furnitureManager.atticWindows)): panel = FurnitureItemPanel(self.furnitureManager.atticWindows[itemIndex], itemIndex, command=self.bringWindowFromAttic, deleteMode=self.deleteMode, helpCategory='FurnitureItemPanelAttic') self.atticWindowPanels.append(panel) @@ -1045,7 +1045,7 @@ def regenerateAtticPicker(self): def createInRoomPicker(self): self.inRoomPanels = [] - for objectId, object in self.objectDict.items(): + for objectId, object in list(self.objectDict.items()): panel = FurnitureItemPanel(object.dfitem.item, objectId, command=self.requestReturnToAttic, deleteMode=self.deleteMode, withinFunc=self.pickInRoom, helpCategory='FurnitureItemPanelRoom') self.inRoomPanels.append(panel) @@ -1069,7 +1069,7 @@ def regenerateInRoomPicker(self): def createInTrashPicker(self): self.inTrashPanels = [] - for itemIndex in xrange(len(self.furnitureManager.deletedItems)): + for itemIndex in range(len(self.furnitureManager.deletedItems)): panel = FurnitureItemPanel(self.furnitureManager.deletedItems[itemIndex], itemIndex, command=self.requestReturnToAtticFromTrash, helpCategory='FurnitureItemPanelTrash') self.inTrashPanels.append(panel) @@ -1173,7 +1173,7 @@ def __sendItemToAtticCallback(self, objectId, retcode, item): self.atticItemPanels.append(panel) self.regenerateAtticPicker() if self.inRoomPicker: - for i in xrange(len(self.inRoomPanels)): + for i in range(len(self.inRoomPanels)): if self.inRoomPanels[i].itemId == objectId: del self.inRoomPanels[i] self.regenerateInRoomPicker() @@ -1265,14 +1265,14 @@ def bringItemFromAttic(self, item, itemIndex): if abs(pos[0]) > 3000 or abs(pos[1]) > 3000 or abs(pos[2]) > 300: self.notify.warning('bringItemFromAttic extreme pos targetNodePath=%s avatar=%s %s' % (repr(self.targetNodePath.getPos(render)), repr(base.localAvatar.getPos(render)), repr(pos))) if item.getFlags() & CatalogFurnitureItem.FLPainting: - for object in self.objectDict.values(): + for object in list(self.objectDict.values()): object.stashBuiltInCollisionNodes() self.gridSnapNP.iPosHpr() target = self.targetNodePath self.iRay.setParentNP(base.localAvatar) entry = self.iRay.pickBitMask3D(bitMask=ToontownGlobals.WallBitmask, targetNodePath=target, origin=Point3(0, 0, 6), dir=Vec3(0, 1, 0), skipFlags=SKIP_BACKFACE | SKIP_CAMERA | SKIP_UNPICKABLE) - for object in self.objectDict.values(): + for object in list(self.objectDict.values()): object.unstashBuiltInCollisionNodes() if entry: @@ -1297,7 +1297,7 @@ def __bringItemFromAtticCallback(self, retcode, dfitem, itemIndex): objectId = mo.get_key() self.atticItemPanels[itemIndex].destroy() del self.atticItemPanels[itemIndex] - for i in xrange(itemIndex, len(self.atticItemPanels)): + for i in range(itemIndex, len(self.atticItemPanels)): self.atticItemPanels[i].itemId -= 1 self.regenerateAtticPicker() @@ -1317,7 +1317,7 @@ def __deleteItemFromAtticCallback(self, retcode, item, itemIndex): return self.atticItemPanels[itemIndex].destroy() del self.atticItemPanels[itemIndex] - for i in xrange(itemIndex, len(self.atticItemPanels)): + for i in range(itemIndex, len(self.atticItemPanels)): self.atticItemPanels[i].itemId -= 1 self.regenerateAtticPicker() @@ -1356,7 +1356,7 @@ def __deleteWallpaperFromAtticCallback(self, retcode, item, itemIndex): return self.atticWallpaperPanels[itemIndex].destroy() del self.atticWallpaperPanels[itemIndex] - for i in xrange(itemIndex, len(self.atticWallpaperPanels)): + for i in range(itemIndex, len(self.atticWallpaperPanels)): self.atticWallpaperPanels[i].itemId -= 1 self.regenerateAtticPicker() @@ -1386,7 +1386,7 @@ def __bringWindowFromAtticCallback(self, retcode, itemIndex, slot): else: self.atticWindowPanels[itemIndex].destroy() del self.atticWindowPanels[itemIndex] - for i in xrange(itemIndex, len(self.atticWindowPanels)): + for i in range(itemIndex, len(self.atticWindowPanels)): self.atticWindowPanels[i].itemId -= 1 self.regenerateAtticPicker() @@ -1402,7 +1402,7 @@ def __deleteWindowFromAtticCallback(self, retcode, item, itemIndex): return self.atticWindowPanels[itemIndex].destroy() del self.atticWindowPanels[itemIndex] - for i in xrange(itemIndex, len(self.atticWindowPanels)): + for i in range(itemIndex, len(self.atticWindowPanels)): self.atticWindowPanels[i].itemId -= 1 self.regenerateAtticPicker() @@ -1555,7 +1555,7 @@ def warnNonDeletableItem(self, item): def requestReturnToAttic(self, item, objectId): self.__cleanupVerifyDelete() itemIndex = None - for i in xrange(len(self.inRoomPanels)): + for i in range(len(self.inRoomPanels)): if self.inRoomPanels[i].itemId == objectId: itemIndex = i self.__enableItemButtons(0) @@ -1602,7 +1602,7 @@ def __recoverDeletedItemCallback(self, retcode, item, itemIndex): self.__enableItemButtons(1) self.inTrashPanels[itemIndex].destroy() del self.inTrashPanels[itemIndex] - for i in xrange(itemIndex, len(self.inTrashPanels)): + for i in range(itemIndex, len(self.inTrashPanels)): self.inTrashPanels[i].itemId -= 1 self.regenerateInTrashPicker() @@ -1645,7 +1645,7 @@ def showIt(task): self.helpText['text'] = helpText self.helpText.show() else: - print 'category: %s not found' + print('category: %s not found') taskMgr.doMethodLater(0.75, showIt, 'showHelpTextDoLater') diff --git a/toontown/events/CharityScreen.py b/toontown/events/CharityScreen.py index b1dc7a36a..e5ff99a36 100644 --- a/toontown/events/CharityScreen.py +++ b/toontown/events/CharityScreen.py @@ -1,4 +1,4 @@ -import json, httplib, threading +import threading from panda3d.core import * from direct.distributed.DistributedObject import DistributedObject from direct.interval.IntervalGlobal import * @@ -7,6 +7,7 @@ from toontown.toonbase import ToontownGlobals from direct.gui.DirectGui import DirectLabel + class CharityScreen(DistributedObject): notify = directNotify.newCategory('CharityScreen') @@ -69,7 +70,8 @@ def unload(self): self.bob = None if self.screenObject: self.screenObject.removeNode() - self.screenObject = None + self.screenObject = None + def delete(self): self.cr.chairityEvent = None self.notify.debug("Deleting Charity Screen!") diff --git a/toontown/events/CharityScreenAI.py b/toontown/events/CharityScreenAI.py index b73698f4b..65ea2cece 100644 --- a/toontown/events/CharityScreenAI.py +++ b/toontown/events/CharityScreenAI.py @@ -1,4 +1,4 @@ -import json, httplib, threading +import json, http.client, threading from panda3d.core import * from direct.distributed.DistributedObjectAI import DistributedObjectAI from direct.interval.IntervalGlobal import * diff --git a/toontown/fishing/BingoCardBase.py b/toontown/fishing/BingoCardBase.py index 5a180a1b7..7bf0a945c 100644 --- a/toontown/fishing/BingoCardBase.py +++ b/toontown/fishing/BingoCardBase.py @@ -23,7 +23,7 @@ def generateCard(self, tileSeed, zoneId): fishList = FishGlobals.getPondGeneraList(zoneId) emptyCells = self.cardSize - 1 - len(fishList) rodId = 0 - for i in xrange(emptyCells): + for i in range(emptyCells): fish = FishGlobals.getRandomFishVitals(zoneId, rodId, rng) while not fish[0]: fish = FishGlobals.getRandomFishVitals(zoneId, rodId, rng) @@ -33,7 +33,7 @@ def generateCard(self, tileSeed, zoneId): if rodId > 4: rodId = 0 - for index in xrange(self.cardSize): + for index in range(self.cardSize): if index != self.cardSize / 2: choice = rng.randrange(0, len(fishList)) self.cellList.append(fishList.pop(choice)) @@ -83,14 +83,14 @@ def checkForWin(self, id): pass def rowCheck(self, rowId): - for colId in xrange(self.colSize): + for colId in range(self.colSize): if not self.gameState & 1 << self.rowSize * rowId + colId: return 0 return 1 def colCheck(self, colId): - for rowId in xrange(self.rowSize): + for rowId in range(self.rowSize): if not self.gameState & 1 << self.rowSize * rowId + colId: return 0 @@ -99,7 +99,7 @@ def colCheck(self, colId): def fDiagCheck(self, id): checkNum = self.rowSize + 1 if not id % checkNum: - for i in xrange(self.rowSize): + for i in range(self.rowSize): if not self.gameState & 1 << i * checkNum: return 0 @@ -110,7 +110,7 @@ def fDiagCheck(self, id): def bDiagCheck(self, id): checkNum = self.rowSize - 1 if not id % checkNum and not id == self.cardSize - 1: - for i in xrange(self.rowSize): + for i in range(self.rowSize): if not self.gameState & 1 << i * checkNum + checkNum: return 0 diff --git a/toontown/fishing/BingoCardGui.py b/toontown/fishing/BingoCardGui.py index a5e6241db..cfa0b0a15 100644 --- a/toontown/fishing/BingoCardGui.py +++ b/toontown/fishing/BingoCardGui.py @@ -146,7 +146,7 @@ def destroy(self): def loadCard(self): cardSize = self.game.getCardSize() - for index in xrange(cardSize): + for index in range(cardSize): self.cellGuiList[index].generateLogo() if index == cardSize / 2: self.cellGuiList[index].generateMarkedLogo() @@ -155,13 +155,13 @@ def loadCard(self): def disableCard(self): self.stopCellBlinking() - for index in xrange(self.game.getCardSize()): + for index in range(self.game.getCardSize()): self.cellGuiList[index].disable() def enableCard(self, callback = None): self.notify.info('enable Bingo card') self.stopCellBlinking() - for index in xrange(len(self.cellGuiList)): + for index in range(len(self.cellGuiList)): if index != self.game.getCardSize() / 2: self.cellGuiList[index].enable(callback) @@ -169,7 +169,7 @@ def generateCard(self, tileSeed, zoneId): rng = RandomNumGen.RandomNumGen(tileSeed) rowSize = self.game.getRowSize() fishList = FishGlobals.getPondGeneraList(zoneId) - for i in xrange(len(fishList)): + for i in range(len(fishList)): fishTuple = fishList.pop(0) weight = FishGlobals.getRandomWeight(fishTuple[0], fishTuple[1]) fish = FishBase.FishBase(fishTuple[0], fishTuple[1], weight) @@ -177,7 +177,7 @@ def generateCard(self, tileSeed, zoneId): emptyCells = self.game.getCardSize() - 1 - len(fishList) rodId = 0 - for i in xrange(emptyCells): + for i in range(emptyCells): fishVitals = FishGlobals.getRandomFishVitals(zoneId, rodId, rng) while not fishVitals[0]: fishVitals = FishGlobals.getRandomFishVitals(zoneId, rodId, rng) @@ -188,8 +188,8 @@ def generateCard(self, tileSeed, zoneId): if rodId > 4: rodId = 0 - for i in xrange(rowSize): - for j in xrange(self.game.getColSize()): + for i in range(rowSize): + for j in range(self.game.getColSize()): color = self.getCellColor(i * rowSize + j) if i * rowSize + j == self.game.getCardSize() / 2: tmpFish = 'Free' @@ -347,7 +347,7 @@ def getLightName(self, lightIndex, bOn): def makeJackpotLights(self, parent): self.jpLights = [] - for nLight in xrange(self.NumLights): + for nLight in range(self.NumLights): lightName = self.getLightName(nLight, self.Off) light = DirectFrame(parent=parent, relief=None, image=self.model.find(lightName), image_hpr=(0, 90, 0)) self.jpLights.append(light) @@ -361,7 +361,7 @@ def destroyJackpotLights(self): def lightSwitch(self, bOn, lightIndex = -1): if lightIndex == -1: - for nLight in xrange(self.NumLights): + for nLight in range(self.NumLights): self.lightSwitch(bOn, nLight) else: @@ -387,7 +387,7 @@ def flashJackpotLights(self, flashMode, nTimeIndex = 0): nTimeIndex = not nTimeIndex delay = 0.5 elif flashMode == 0: - for nLight in xrange(self.NumLights): + for nLight in range(self.NumLights): if nLight % 2 == nTimeIndex: self.lightSwitch(self.On, nLight) else: diff --git a/toontown/fishing/BingoGlobals.py b/toontown/fishing/BingoGlobals.py index e05932eab..5f1ff49a1 100644 --- a/toontown/fishing/BingoGlobals.py +++ b/toontown/fishing/BingoGlobals.py @@ -48,17 +48,17 @@ def getJackpot(typeId): def getColor(typeId): - float_color = map(lambda x: x / 255.0, CardTypeDict[typeId][0][0]) + float_color = [x / 255.0 for x in CardTypeDict[typeId][0][0]] return float_color def getButtonColor(typeId): - float_color = map(lambda x: x / 255.0, CardTypeDict[typeId][0][1]) + float_color = [x / 255.0 for x in CardTypeDict[typeId][0][1]] return float_color def getButtonRolloverColor(typeId): - float_color = map(lambda x: x / 255.0, CardTypeDict[typeId][0][2]) + float_color = [x / 255.0 for x in CardTypeDict[typeId][0][2]] return float_color diff --git a/toontown/fishing/BlockoutBingo.py b/toontown/fishing/BlockoutBingo.py index 0d7b10971..b5d8afb21 100644 --- a/toontown/fishing/BlockoutBingo.py +++ b/toontown/fishing/BlockoutBingo.py @@ -10,7 +10,7 @@ def __init__(self, cardSize = BingoGlobals.CARD_SIZE, rowSize = BingoGlobals.CAR self.gameType = BingoGlobals.BLOCKOUT_CARD def checkForWin(self, id = 0): - for i in xrange(self.rowSize): + for i in range(self.rowSize): if not self.rowCheck(i): return BingoGlobals.NO_UPDATE diff --git a/toontown/fishing/DistributedFishingPond.py b/toontown/fishing/DistributedFishingPond.py index e488ca0ea..a1555137e 100644 --- a/toontown/fishing/DistributedFishingPond.py +++ b/toontown/fishing/DistributedFishingPond.py @@ -60,7 +60,7 @@ def stopCheckingTargets(self): def checkTargets(self, task = None): self.notify.debug('checkTargets') if self.localToonSpot != None: - for target in self.targets.values(): + for target in list(self.targets.values()): targetPos = target.getPos(render) distVec = Vec3(targetPos - self.localToonBobPos) dist = distVec.length() @@ -118,9 +118,9 @@ def getLocalToonSpot(self): return self.localToonSpot def resetSpotGui(self): - for spot in self.visitedSpots.values(): + for spot in list(self.visitedSpots.values()): spot.resetCastGui() def setSpotGui(self): - for spot in self.visitedSpots.values(): + for spot in list(self.visitedSpots.values()): spot.setCastGui() diff --git a/toontown/fishing/DistributedFishingPondAI.py b/toontown/fishing/DistributedFishingPondAI.py index a33747b66..19743904e 100644 --- a/toontown/fishing/DistributedFishingPondAI.py +++ b/toontown/fishing/DistributedFishingPondAI.py @@ -15,7 +15,7 @@ def __init__(self, air): self.bingoMgr = None def start(self): - for _ in xrange(FishingTargetGlobals.getNumTargets(self.area)): + for _ in range(FishingTargetGlobals.getNumTargets(self.area)): fishingTarget = DistributedFishingTargetAI(simbase.air) fishingTarget.setPondDoId(self.doId) fishingTarget.generateWithRequired(self.zoneId) diff --git a/toontown/fishing/FishBrowser.py b/toontown/fishing/FishBrowser.py index ef6ddf3bf..acd84e847 100644 --- a/toontown/fishing/FishBrowser.py +++ b/toontown/fishing/FishBrowser.py @@ -30,7 +30,7 @@ def __init__(self, parent = aspect2d, **kw): ('decButton_pos', (0, 0, 0.525), None), ('decButton_image3_color', Vec4(0.8, 0.8, 0.8, 0.5), None), ('numItemsVisible', 1, None), - ('items', map(str, FishGlobals.getGenera()), None), + ('items', list(map(str, FishGlobals.getGenera())), None), ('scrollSpeed', 4, None), ('itemMakeFunction', GenusPanel.GenusPanel, None), ('itemMakeExtraArgs', None, None)) diff --git a/toontown/fishing/FishGlobals.py b/toontown/fishing/FishGlobals.py index 0c2fe2aa4..42cb6edb2 100644 --- a/toontown/fishing/FishGlobals.py +++ b/toontown/fishing/FishGlobals.py @@ -26,7 +26,7 @@ 95: JellybeanItem, 100: BootItem, 2: CertItem} -SortedProbabilityCutoffs = ProbabilityDict.keys() +SortedProbabilityCutoffs = list(ProbabilityDict.keys()) SortedProbabilityCutoffs.sort() Rod2JellybeanDict = {0: 10, 1: 20, @@ -600,7 +600,7 @@ def getSpecies(genus): def getGenera(): - return __fishDict.keys() + return list(__fishDict.keys()) ROD_WEIGHT_MIN_INDEX = 0 @@ -723,17 +723,17 @@ def getValue(genus, species, weight): __anywhereDict = copy.deepcopy(__emptyRodDict) __pondInfoDict = {} -for genus, speciesList in __fishDict.items(): - for species in xrange(len(speciesList)): +for genus, speciesList in list(__fishDict.items()): + for species in range(len(speciesList)): __totalNumFish += 1 speciesDesc = speciesList[species] rarity = speciesDesc[RARITY_INDEX] zoneList = speciesDesc[ZONE_LIST_INDEX] - for zoneIndex in xrange(len(zoneList)): + for zoneIndex in range(len(zoneList)): zone = zoneList[zoneIndex] effectiveRarity = getEffectiveRarity(rarity, zoneIndex) if zone == Anywhere: - for rodIndex, rarityDict in __anywhereDict.items(): + for rodIndex, rarityDict in list(__anywhereDict.items()): if canBeCaughtByRod(genus, species, rodIndex): fishList = rarityDict.setdefault(effectiveRarity, []) fishList.append((genus, species)) @@ -749,20 +749,20 @@ def getValue(genus, species, weight): else: rodDict = copy.deepcopy(__emptyRodDict) __pondInfoDict[pondZone] = rodDict - for rodIndex, rarityDict in rodDict.items(): + for rodIndex, rarityDict in list(rodDict.items()): if canBeCaughtByRod(genus, species, rodIndex): fishList = rarityDict.setdefault(effectiveRarity, []) fishList.append((genus, species)) -for zone, rodDict in __pondInfoDict.items(): - for rodIndex, anywhereRarityDict in __anywhereDict.items(): - for rarity, anywhereFishList in anywhereRarityDict.items(): +for zone, rodDict in list(__pondInfoDict.items()): + for rodIndex, anywhereRarityDict in list(__anywhereDict.items()): + for rarity, anywhereFishList in list(anywhereRarityDict.items()): rarityDict = rodDict[rodIndex] fishList = rarityDict.setdefault(rarity, []) fishList.extend(anywhereFishList) def getPondDict(zoneId): - print __pondInfoDict[zoneId] + print(__pondInfoDict[zoneId]) def getTotalNumFish(): @@ -780,19 +780,19 @@ def testRarity(rodId = 0, numIter = 100000): 8: 0, 9: 0, 10: 0} - for i in xrange(numIter): + for i in range(numIter): v = __rollRarityDice(rodId) d[v] += 1 - for rarity, count in d.items(): + for rarity, count in list(d.items()): percentage = count / float(numIter) * 100 d[rarity] = percentage - print d + print(d) def getRandomFish(): - genus = random.choice(__fishDict.keys()) + genus = random.choice(list(__fishDict.keys())) species = random.randint(0, len(__fishDict[genus]) - 1) return (genus, species) @@ -803,10 +803,10 @@ def getPondInfo(): def getSimplePondInfo(): info = {} - for pondId, pondInfo in __pondInfoDict.items(): + for pondId, pondInfo in list(__pondInfoDict.items()): pondFishList = [] - for rodId, rodInfo in pondInfo.items(): - for rarity, fishList in rodInfo.items(): + for rodId, rodInfo in list(pondInfo.items()): + for rarity, fishList in list(rodInfo.items()): for fish in fishList: if fish not in pondFishList: pondFishList.append(fish) @@ -831,13 +831,13 @@ def getPondGeneraList(pondId): def printNumGeneraPerPond(): pondInfo = getSimplePondInfo() - for pondId, fishList in pondInfo.items(): + for pondId, fishList in list(pondInfo.items()): generaList = [] for fish in fishList: if fish[0] not in generaList: generaList.append(fish[0]) - print 'Pond %s has %s Genera' % (pondId, len(generaList)) + print('Pond %s has %s Genera' % (pondId, len(generaList))) def generateFishingReport(numCasts = 10000, hitRate = 0.8): @@ -847,10 +847,10 @@ def generateFishingReport(numCasts = 10000, hitRate = 0.8): for pond in __pondInfoDict: totalPondMoney[pond] = 0 totalPondBaitCost[pond] = 0 - for rod in xrange(MaxRodId + 1): + for rod in range(MaxRodId + 1): totalRodMoney.setdefault(rod, 0) baitCost = getCastCost(rod) - for cast in xrange(numCasts): + for cast in range(numCasts): totalPondBaitCost[pond] += baitCost if random.random() > hitRate: continue @@ -872,22 +872,22 @@ def generateFishingReport(numCasts = 10000, hitRate = 0.8): totalRodMoney[rod] += value numPonds = len(totalPondMoney) - for pond, money in totalPondMoney.items(): + for pond, money in list(totalPondMoney.items()): baitCost = 0 - for rod in xrange(MaxRodId + 1): + for rod in range(MaxRodId + 1): baitCost += getCastCost(rod) totalCastCost = baitCost * numCasts - print ('pond: %s totalMoney: %s profit: %s perCast: %s' % (pond, + print(('pond: %s totalMoney: %s profit: %s perCast: %s' % (pond, money, money - totalCastCost, - (money - totalCastCost) / float(numCasts * (MaxRodId + 1))),) + (money - totalCastCost) / float(numCasts * (MaxRodId + 1))),)) - for rod, money in totalRodMoney.items(): + for rod, money in list(totalRodMoney.items()): baitCost = getCastCost(rod) totalCastCost = baitCost * (numCasts * numPonds) - print ('rod: %s totalMoney: %s castCost: %s profit: %s perCast: %s' % (rod, + print(('rod: %s totalMoney: %s castCost: %s profit: %s perCast: %s' % (rod, money, totalCastCost, money - totalCastCost, - (money - totalCastCost) / float(numCasts * numPonds)),) + (money - totalCastCost) / float(numCasts * numPonds)),)) diff --git a/toontown/fishing/FishPanel.py b/toontown/fishing/FishPanel.py index 456f39b83..ba28ac1cf 100644 --- a/toontown/fishing/FishPanel.py +++ b/toontown/fishing/FishPanel.py @@ -85,8 +85,8 @@ def handleCancel(self): def show(self, code = FishGlobals.FishItem): messenger.send('wakeup') - apply(self.photo.setSwimBounds, self.swimBounds) - apply(self.photo.setSwimColor, self.swimColor) + self.photo.setSwimBounds(*self.swimBounds) + self.photo.setSwimColor(*self.swimColor) if code == FishGlobals.FishItem: self.extraLabel.hide() elif code == FishGlobals.FishItemNewEntry: diff --git a/toontown/fishing/FishPhoto.py b/toontown/fishing/FishPhoto.py index d9c06e899..2f47e4228 100644 --- a/toontown/fishing/FishPhoto.py +++ b/toontown/fishing/FishPhoto.py @@ -38,9 +38,9 @@ def load(self): self.cCamNode.setScene(self.cRender) self.fishSwimCam = self.fishSwimCamera.attachNewNode(self.cCamNode) cm = CardMaker('displayRegionCard') - apply(cm.setFrame, self.bounds) + cm.setFrame(*self.bounds) self.card = card = self.attachNewNode(cm.generate()) - apply(card.setColor, self.color) + card.setColor(*self.color) newBounds = card.getTightBounds() ll = render2d.getRelativePoint(card, newBounds[0]) ur = render2d.getRelativePoint(card, newBounds[1]) @@ -48,7 +48,7 @@ def load(self): ur.getX(), ll.getZ(), ur.getZ()] - newBounds = map(lambda x: max(0.0, min(1.0, (x + 1.0) / 2.0)), newBounds) + newBounds = [max(0.0, min(1.0, (x + 1.0) / 2.0)) for x in newBounds] self.cDr = base.win.makeDisplayRegion(*newBounds) self.cDr.setSort(10) self.cDr.setClearColor(card.getColor()) @@ -108,8 +108,8 @@ def makeFishFrame(self, actor): actor.setDepthWrite(1) if not hasattr(self, 'fishDisplayRegion'): self.fishDisplayRegion = DirectRegion(parent=self) - apply(self.fishDisplayRegion.setBounds, self.swimBounds) - apply(self.fishDisplayRegion.setColor, self.swimColor) + self.fishDisplayRegion.setBounds(*self.swimBounds) + self.fishDisplayRegion.setColor(*self.swimColor) frame = self.fishDisplayRegion.load() pitch = frame.attachNewNode('pitch') rotate = pitch.attachNewNode('rotate') diff --git a/toontown/fishing/FishTank.py b/toontown/fishing/FishTank.py index 2142d6ac3..2364820ed 100644 --- a/toontown/fishing/FishTank.py +++ b/toontown/fishing/FishTank.py @@ -57,7 +57,7 @@ def generateRandomTank(self): import random numFish = random.randint(1, 20) self.fishList = [] - for i in xrange(numFish): + for i in range(numFish): genus, species = FishGlobals.getRandomFish() weight = FishGlobals.getRandomWeight(genus, species) fish = FishBase.FishBase(genus, species, weight) diff --git a/toontown/fishing/GenusPanel.py b/toontown/fishing/GenusPanel.py index a8d86e0af..fdd29e380 100644 --- a/toontown/fishing/GenusPanel.py +++ b/toontown/fishing/GenusPanel.py @@ -63,7 +63,7 @@ def setGenus(self, genus): startPos = len(speciesList) / 2 * offset if not len(speciesList) % 2: startPos -= offset / 2 - for species in xrange(len(speciesList)): + for species in range(len(speciesList)): label = DirectLabel(parent=self, relief=None, state=DGG.NORMAL, pos=(0.06, 0, startPos - species * offset), text=TTLocalizer.UnknownFish, text_fg=(0.2, 0.1, 0.0, 1), text_scale=TTLocalizer.GPgenus, text_align=TextNode.ALeft, text_font=ToontownGlobals.getInterfaceFont()) self.speciesLabels.append(label) @@ -80,6 +80,6 @@ def update(self): if base.localAvatar.fishCollection.hasGenus(self.genus) and self.fishPanel is not None: self.fishPanel.show(showBackground=1) self['text'] = TTLocalizer.FishGenusNames[self.genus] - for species in xrange(len(FishGlobals.getSpecies(self.genus))): + for species in range(len(FishGlobals.getSpecies(self.genus))): if base.localAvatar.fishCollection.hasFish(self.genus, species): self.speciesLabels[species]['text'] = TTLocalizer.FishSpeciesNames[self.genus][species] diff --git a/toontown/fishing/NormalBingo.py b/toontown/fishing/NormalBingo.py index f2b7cf742..5633b37d7 100644 --- a/toontown/fishing/NormalBingo.py +++ b/toontown/fishing/NormalBingo.py @@ -27,7 +27,7 @@ def checkForBingo(self): id = self.cardSize / 2 if self.checkForWin(id): return BingoGlobals.WIN - for i in xrange(BingoGlobals.CARD_ROWS): + for i in range(BingoGlobals.CARD_ROWS): if i != BingoGlobals.CARD_ROWS / 2: rowResult = self.rowCheck(i) colResult = self.colCheck(i) diff --git a/toontown/friends/FriendInvitee.py b/toontown/friends/FriendInvitee.py index 6f9bb4e12..92e424a47 100644 --- a/toontown/friends/FriendInvitee.py +++ b/toontown/friends/FriendInvitee.py @@ -63,7 +63,7 @@ def __handleButton(self, value): if base.friendMode == 0: base.cr.friendManager.up_inviteeFriendResponse(1, self.context) elif base.friendMode == 1: - print 'sending Request Invite' + print('sending Request Invite') base.cr.avatarFriendsManager.sendRequestInvite(self.avId) elif base.friendMode == 0: base.cr.friendManager.up_inviteeFriendResponse(0, self.context) diff --git a/toontown/friends/FriendsListPanel.py b/toontown/friends/FriendsListPanel.py index 1766e0b61..a24cf0394 100644 --- a/toontown/friends/FriendsListPanel.py +++ b/toontown/friends/FriendsListPanel.py @@ -541,14 +541,14 @@ def __updateScrollList(self): 0)) if self.panelType == FLPPets: - for objId, obj in base.cr.doId2do.items(): + for objId, obj in list(base.cr.doId2do.items()): from toontown.pets import DistributedPet if isinstance(obj, DistributedPet.DistributedPet): friendPair = (objId, 0) petFriends.append(friendPair) if self.panelType == FLPLOCAL: - for objId, obj in base.cr.doId2do.items(): + for objId, obj in list(base.cr.doId2do.items()): if obj.dclass == base.cr.dclassesByName['DistributedToon']: localToons.append((objId, 0)) @@ -561,7 +561,7 @@ def __updateScrollList(self): self.notify.info("Inserting our pet friend %d" % base.localAvatar.getPetId()) # petFriends.insert(0, (base.localAvatar.getPetId(), 0)) - for friendPair in self.friends.keys(): + for friendPair in list(self.friends.keys()): friendButton = self.friends[friendPair] self.scrollList.removeItem(friendButton, refresh=0) friendButton.destroy() diff --git a/toontown/friends/TTAFriendsManager.py b/toontown/friends/TTAFriendsManager.py index d725ea737..0400d1c97 100644 --- a/toontown/friends/TTAFriendsManager.py +++ b/toontown/friends/TTAFriendsManager.py @@ -36,14 +36,14 @@ def d_getPetDetails(self, petId): def petDetails(self, avId, ownerId, petName, traitSeed, sz, traits, moods, dna, lastSeen): fields = list(zip(("setHead", "setEars", "setNose", "setTail", "setBodyTexture", "setColor", "setColorScale", "setEyeColor", "setGender"), dna)) - fields.extend(zip(("setBoredom", "setRestlessness", "setPlayfulness", "setLoneliness", + fields.extend(list(zip(("setBoredom", "setRestlessness", "setPlayfulness", "setLoneliness", "setSadness", "setAffection", "setHunger", "setConfusion", "setExcitement", - "setFatigue", "setAnger", "setSurprise"), moods)) - fields.extend(zip(("setForgetfulness", "setBoredomThreshold", "setRestlessnessThreshold", + "setFatigue", "setAnger", "setSurprise"), moods))) + fields.extend(list(zip(("setForgetfulness", "setBoredomThreshold", "setRestlessnessThreshold", "setPlayfulnessThreshold", "setLonelinessThreshold", "setSadnessThreshold", "setFatigueThreshold", "setHungerThreshold", "setConfusionThreshold", "setExcitementThreshold", "setAngerThreshold", "setSurpriseThreshold", - "setAffectionThreshold"), traits)) + "setAffectionThreshold"), traits))) fields.append(("setOwnerId", ownerId)) fields.append(("setPetName", petName)) fields.append(("setTraitSeed", traitSeed)) diff --git a/toontown/friends/TTAFriendsManagerUD.py b/toontown/friends/TTAFriendsManagerUD.py index 059d2bce7..15e60badb 100644 --- a/toontown/friends/TTAFriendsManagerUD.py +++ b/toontown/friends/TTAFriendsManagerUD.py @@ -106,12 +106,12 @@ def handleRetrieve(self, dclass, fields): def enterRetrieved(self, friendsList, trueFriendsList): newList = [] - for i in xrange(len(friendsList)): + for i in range(len(friendsList)): if friendsList[i][0] == self.target: continue newList.append(friendsList[i]) newTFList = [] - for i in xrange(len(trueFriendsList)): + for i in range(len(trueFriendsList)): if trueFriendsList[i] == self.target: continue newTFList.append(trueFriendsList[i]) @@ -363,7 +363,7 @@ def clearList(self, doId): def routeTeleportQuery(self, toId): fromId = self.air.getAvatarIdFromSender() - if fromId in self.tpRequests.values(): + if fromId in list(self.tpRequests.values()): return self.tpRequests[fromId] = toId self.sendUpdateToAvatarId(toId, 'teleportQuery', [fromId]) @@ -449,7 +449,7 @@ def requestSecret(self): avId = self.air.getAvatarIdFromSender() allowed = string.lowercase + string.digits secret = '' - for i in xrange(6): + for i in range(6): secret += random.choice(allowed) if i == 2: secret += ' ' diff --git a/toontown/golf/BuildGeometry.py b/toontown/golf/BuildGeometry.py index 010f1114a..480c334a6 100644 --- a/toontown/golf/BuildGeometry.py +++ b/toontown/golf/BuildGeometry.py @@ -18,7 +18,7 @@ def circleY(angle, radius, centerX, centerY): def getCirclePoints(segCount, centerX, centerY, radius, wideX = 1.0, wideY = 1.0): returnShape = [] - for seg in xrange(0, segCount): + for seg in range(0, segCount): coordX = wideX * circleX(pi * 2.0 * float(float(seg) / float(segCount)), radius, centerX, centerY) coordY = wideY * circleY(pi * 2.0 * float(float(seg) / float(segCount)), radius, centerX, centerY) returnShape.append((coordX, coordY, 1)) @@ -46,7 +46,7 @@ def addCircle(attachNode, vertexCount, radius, color = Vec4(1.0, 1.0, 1.0, 1.0), targetTris = GeomTrifans(Geom.UHStatic) sizeTarget = len(targetCircleShape) targetTris.addVertex(0) - for countVertex in xrange(1, sizeTarget + 1): + for countVertex in range(1, sizeTarget + 1): targetTris.addVertex(countVertex) targetTris.addVertex(1) diff --git a/toontown/golf/DistributedGolfCourse.py b/toontown/golf/DistributedGolfCourse.py index a27482f11..b6acfef24 100644 --- a/toontown/golf/DistributedGolfCourse.py +++ b/toontown/golf/DistributedGolfCourse.py @@ -87,7 +87,7 @@ def delete(self): self.golfRewardDialog.delete() self.cleanUpReward() if self.toonPanels: - for x in xrange(len(self.toonPanels)): + for x in range(len(self.toonPanels)): self.toonPanels[x].destroy() self.toonPanels = None @@ -215,7 +215,7 @@ def avExited(self, avId): def exitMessageForToon(self, avId): if self.toonPanels and self.localAvId != avId: y = 0 - for x in xrange(len(self.avIdList)): + for x in range(len(self.avIdList)): if avId == self.avIdList[x] and y < len(self.toonPanels): toonPanel = self.toonPanels[y] toonPanel.headModel.hide() @@ -261,7 +261,7 @@ def enterCleanup(self): if not self.scoreBoard == None: self.scoreBoard.delete() if self.toonPanels: - for x in xrange(len(self.toonPanels)): + for x in range(len(self.toonPanels)): self.toonPanels[x].destroy() self.toonPanels = None @@ -304,7 +304,7 @@ def setScores(self, scoreList): scoreList.reverse() for avId in self.avIdList: avScores = [] - for holeIndex in xrange(self.numHoles): + for holeIndex in range(self.numHoles): avScores.append(scoreList.pop()) self.scores[avId] = avScores diff --git a/toontown/golf/DistributedGolfCourseAI.py b/toontown/golf/DistributedGolfCourseAI.py index 5f12154c4..ee3cd6068 100644 --- a/toontown/golf/DistributedGolfCourseAI.py +++ b/toontown/golf/DistributedGolfCourseAI.py @@ -295,7 +295,7 @@ def handleTimeout(avIds, self = self): allAvatarsInCourse() self.__barrier = ToonBarrier('WaitReadyCourse', self.uniqueName('WaitReadyCourse'), self.avIdList, READY_TIMEOUT, allAvatarsInCourse, handleTimeout) - for avId in self.avStateDict.keys(): + for avId in list(self.avStateDict.keys()): if self.avStateDict[avId] == READY: self.__barrier.clear(avId) @@ -329,7 +329,7 @@ def handleTimeout(avIds, self = self): stillPlaying = self.getStillPlayingAvIds() self.__barrier = ToonBarrier('WaitReadyHole', self.uniqueName('WaitReadyHole'), stillPlaying, READY_TIMEOUT, allAvatarsInHole, handleTimeout) - for avId in self.avStateDict.keys(): + for avId in list(self.avStateDict.keys()): if self.avStateDict[avId] == ONHOLE: self.__barrier.clear(avId) @@ -389,7 +389,7 @@ def enterWaitReward(self): self.recordHoleInOne() self.recordCourseUnderPar() trophiesList = [] - for index in xrange(len(self.avIdList)): + for index in range(len(self.avIdList)): avId = self.avIdList[index] if avId in self.newTrophies: oneTrophyList = self.newTrophies[avId] @@ -401,7 +401,7 @@ def enterWaitReward(self): trophiesList.append([]) holeBestList = [] - for index in xrange(len(self.avIdList)): + for index in range(len(self.avIdList)): avId = self.avIdList[index] if avId in self.newHoleBest: oneTrophyList = self.newHoleBest[avId] @@ -413,7 +413,7 @@ def enterWaitReward(self): holeBestList.append([]) courseBestList = [] - for index in xrange(len(self.avIdList)): + for index in range(len(self.avIdList)): avId = self.avIdList[index] if avId in self.newCourseBest: oneTrophyList = self.newCourseBest[avId] @@ -425,7 +425,7 @@ def enterWaitReward(self): courseBestList.append([]) cupList = [] - for index in xrange(len(self.avIdList)): + for index in range(len(self.avIdList)): avId = self.avIdList[index] if avId in self.newCups: oneCupList = self.newCups[avId] @@ -494,7 +494,7 @@ def isCurHoleDone(self): retval = True else: retval = True - for state in self.avStateDict.values(): + for state in list(self.avStateDict.values()): if not (state == BALLIN or state == EXITED): retval = False break @@ -504,7 +504,7 @@ def isCurHoleDone(self): def areAllBallsInHole(self): self.notify.debug('areAllBallsInHole, self.avStateDict=%s' % self.avStateDict) allBallsInHole = True - for state in self.avStateDict.values(): + for state in list(self.avStateDict.values()): if state != BALLIN: allBallsInHole = False @@ -576,7 +576,7 @@ def calcHolesToUse(self): if simbase.air.config.GetBool('golf-course-randomized', 1): retval = self.calcHolesToUseRandomized(self.courseId) self.notify.debug('randomized courses!') - for x in xrange(len(retval)): + for x in range(len(retval)): self.notify.debug('Hole is: %s' % retval[x]) else: @@ -737,7 +737,7 @@ def scoreCompareWithTime(tupleA, tupleB): winnerAvId = random.choice(tiedForFirst) winnerIndex = self.avIdList.index(winnerAvId) self.winnerByTieBreak = winnerAvId - for index in xrange(len(self.rankings)): + for index in range(len(self.rankings)): if self.rankings[index] > 0 and index != winnerIndex: self.rankings[index] += 1 @@ -760,7 +760,7 @@ def awardTrophies(self): endingTrophies = GolfGlobals.calcTrophyListFromHistory(endingHistory) av.b_setGolfHistory(endingHistory) newTrophies = [] - for index in xrange(len(oldTrophies)): + for index in range(len(oldTrophies)): if not oldTrophies[index] and endingTrophies[index]: self.notify.debug('New Trophy %d' % index) self.air.writeServerEvent('golf_trophy', avId, '%s' % index) @@ -781,7 +781,7 @@ def awardCups(self): oldCups = GolfGlobals.calcCupListFromHistory(oldHistory) endingCups = GolfGlobals.calcCupListFromHistory(endingHistory) newCups = [] - for index in xrange(len(oldCups)): + for index in range(len(oldCups)): if not oldCups[index] and endingCups[index]: self.notify.debug('New Trophy %d' % index) newCups.append(True) @@ -804,7 +804,7 @@ def awardHoleBest(self): av.b_setGolfHoleBest(endingHoleBest) newHoleBest = [] longestHoleBestList = 0 - for index in xrange(len(oldHoleBest)): + for index in range(len(oldHoleBest)): if endingHoleBest[index] < oldHoleBest[index]: self.notify.debug('New HoleBest %d' % index) newHoleBest.append(True) @@ -826,7 +826,7 @@ def awardCourseBest(self): av.b_setGolfCourseBest(endingCourseBest) newCourseBest = [] longestCourseBestList = 0 - for index in xrange(len(oldCourseBest)): + for index in range(len(oldCourseBest)): if endingCourseBest[index] < oldCourseBest[index]: self.notify.debug('New CourseBest %d' % index) newCourseBest.append(True) @@ -962,7 +962,7 @@ def recordHoleInOne(self): stillPlaying = self.getStillPlayingAvIds() for avId in stillPlaying: scoreList = self.scores[avId] - for holeIndex in xrange(len(scoreList)): + for holeIndex in range(len(scoreList)): strokes = scoreList[holeIndex] if strokes == 1: holeId = self.holeIds[holeIndex] diff --git a/toontown/golf/DistributedGolfHole.py b/toontown/golf/DistributedGolfHole.py index 9aa0d08a7..953df09cb 100644 --- a/toontown/golf/DistributedGolfHole.py +++ b/toontown/golf/DistributedGolfHole.py @@ -304,7 +304,7 @@ def loadSounds(self): self.crowdBuildupSfx = [] self.crowdApplauseSfx = [] self.crowdMissSfx = [] - for i in xrange(4): + for i in range(4): self.crowdBuildupSfx.append(loader.loadSfx('phase_6/audio/sfx/Golf_Crowd_Buildup.ogg')) self.crowdApplauseSfx.append(loader.loadSfx('phase_6/audio/sfx/Golf_Crowd_Applause.ogg')) self.crowdMissSfx.append(loader.loadSfx('phase_6/audio/sfx/Golf_Crowd_Miss.ogg')) @@ -346,7 +346,7 @@ def setup(self): camera.setHpr(self.camHprBallFollow) if self.holeBottomNodePath.isEmpty(): holePositions = self.holePositions - for index in xrange(len(holePositions)): + for index in range(len(holePositions)): holePos = holePositions[index] targetNodePathGeom, t1, t2 = BuildGeometry.addCircleGeom(self.targets, 16, 1) targetNodePathGeom.setPos(holePos) @@ -1273,7 +1273,7 @@ def readyCurrentGolfer(self, avId): self.currentGolferActive = True if avId in self.ballDict: self.ballDict[avId]['golfBallOdeGeom'].setCollideBits(BitMask32(16777215)) - self.ballDict[avId]['golfBallOdeGeom'].setCategoryBits(BitMask32(4278190080L)) + self.ballDict[avId]['golfBallOdeGeom'].setCategoryBits(BitMask32(4278190080)) else: self.currentGolferActive = False @@ -1380,7 +1380,7 @@ def __endTossGolf(self): def __updateGolfPower(self, task): if not self.powerBar: - print '### no power bar!!!' + print('### no power bar!!!') return Task.done newPower = self.__getGolfPower(globalClock.getFrameTime()) self.power = newPower @@ -1504,7 +1504,7 @@ def doFlyOverMovie(self, avId): cameraAnimFullPath = path + cameraName try: self.flyOverActor = Actor.Actor(camModelFullPath, {'camera': cameraAnimFullPath}) - except StandardError: + except Exception: self.notify.debug("Couldn't find flyover %s" % camModelFullPath) return False @@ -1514,7 +1514,7 @@ def doFlyOverMovie(self, avId): flyOverJoint = self.flyOverActor.find('**/camera1') children = flyOverJoint.getChildren() numChild = children.getNumPaths() - for i in xrange(numChild): + for i in range(numChild): childNodePath = children.getPath(i) childNodePath.removeNode() diff --git a/toontown/golf/DistributedGolfHoleAI.py b/toontown/golf/DistributedGolfHoleAI.py index f5d9e6d66..75e134802 100644 --- a/toontown/golf/DistributedGolfHoleAI.py +++ b/toontown/golf/DistributedGolfHoleAI.py @@ -132,11 +132,11 @@ def clearWatched(self): 1, 1, 1] - for index in xrange(len(self.golfCourse.getGolferIds())): + for index in range(len(self.golfCourse.getGolferIds())): self.watched[index] = 0 def setWatched(self, avId): - for index in xrange(len(self.golfCourse.getGolferIds())): + for index in range(len(self.golfCourse.getGolferIds())): if self.golfCourse.getGolferIds()[index] == avId: self.watched[index] = 1 @@ -448,14 +448,14 @@ def parseLocators(self, objectCollection, optional = 0): if 'optionalMovers' in self.holeInfo: for optionalMoverId in self.holeInfo['optionalMovers']: searchStr = 'optional_mover_' + str(optionalMoverId) - for objIndex in xrange(objectCollection.getNumPaths()): + for objIndex in range(objectCollection.getNumPaths()): object = objectCollection.getPath(objIndex) if searchStr in object.getName(): self.fillLocator(objectCollection, objIndex) break else: - for index in xrange(objectCollection.getNumPaths()): + for index in range(objectCollection.getNumPaths()): self.fillLocator(objectCollection, index) def fillLocator(self, objectCollection, index): diff --git a/toontown/golf/DistributedPhysicsWorldAI.py b/toontown/golf/DistributedPhysicsWorldAI.py index f6095fe02..eb0699a7c 100644 --- a/toontown/golf/DistributedPhysicsWorldAI.py +++ b/toontown/golf/DistributedPhysicsWorldAI.py @@ -49,11 +49,11 @@ def upSetCommonObjects(self, objectData): self.doAction() def setupCommonObjects(self): - print self.commonHoldData + print(self.commonHoldData) if not self.commonHoldData: return elif self.commonHoldData[0][1] == 99: - print 'no common objects' + print('no common objects') else: self.useCommonObjectData(self.commonHoldData, 0) diff --git a/toontown/golf/GolfGlobals.py b/toontown/golf/GolfGlobals.py index 3b7dcada4..a4b6fde4e 100644 --- a/toontown/golf/GolfGlobals.py +++ b/toontown/golf/GolfGlobals.py @@ -404,7 +404,7 @@ def calcTrophyListFromHistory(history): retval = [] historyIndex = 0 - for trophyIndex in xrange(NumHistory): + for trophyIndex in range(NumHistory): requirements = TrophyRequirements[trophyIndex] for amountNeeded in requirements: if history[historyIndex] >= amountNeeded: @@ -425,7 +425,7 @@ def calcCupListFromHistory(history): if gotTrophy: numTrophiesWon += 1 - for cupIndex in xrange(len(retval)): + for cupIndex in range(len(retval)): threshold = (cupIndex + 1) * TrophiesPerCup if threshold <= numTrophiesWon: retval[cupIndex] = True diff --git a/toontown/golf/GolfHoleBase.py b/toontown/golf/GolfHoleBase.py index 9be952a11..30f2090b5 100644 --- a/toontown/golf/GolfHoleBase.py +++ b/toontown/golf/GolfHoleBase.py @@ -37,26 +37,26 @@ def loadLevel(self): terrainData = self.terrainModel.find('**/softSurface') grassData = terrainData.findAllMatches('**/grass*') self.terrainData = [] - for index in xrange(grassData.getNumPaths()): + for index in range(grassData.getNumPaths()): someTerrainData = grassData[index] terrainDataOde = OdeTriMeshData(someTerrainData) self.meshDataList.append(terrainDataOde) terrainGeomOde = OdeTriMeshGeom(self.space, terrainDataOde) self.geomDataList.append(terrainGeomOde) - terrainGeomOde.setCollideBits(BitMask32(4026531840L)) + terrainGeomOde.setCollideBits(BitMask32(4026531840)) terrainGeomOde.setCategoryBits(BitMask32(240)) self.space.setSurfaceType(terrainGeomOde, GolfGlobals.GRASS_SURFACE) self.space.setCollideId(terrainGeomOde, 2) slickData = terrainData.findAllMatches('**/slick*') self.terrainData = [] - for index in xrange(slickData.getNumPaths()): + for index in range(slickData.getNumPaths()): someTerrainData = slickData[index] terrainDataOde = OdeTriMeshData(someTerrainData) self.meshDataList.append(terrainDataOde) terrainGeomOde = OdeTriMeshGeom(self.space, terrainDataOde) self.geomDataList.append(terrainGeomOde) - terrainGeomOde.setCollideBits(BitMask32(4026531840L)) + terrainGeomOde.setCollideBits(BitMask32(4026531840)) terrainGeomOde.setCategoryBits(BitMask32(240)) self.space.setSurfaceType(terrainGeomOde, GolfGlobals.SLICK_SURFACE) self.space.setCollideId(terrainGeomOde, GolfGlobals.SLICK_COLLIDE_ID) @@ -66,7 +66,7 @@ def loadLevel(self): self.meshDataList.append(cupData) cupGeom = OdeTriMeshGeom(self.space, cupData) self.geomDataList.append(cupGeom) - cupGeom.setCollideBits(BitMask32(4026531840L)) + cupGeom.setCollideBits(BitMask32(4026531840)) cupGeom.setCategoryBits(BitMask32(240)) self.space.setSurfaceType(cupGeom, GolfGlobals.HOLE_SURFACE) self.space.setCollideId(cupGeom, GolfGlobals.HOLE_CUP_COLLIDE_ID) @@ -74,7 +74,7 @@ def loadLevel(self): self.golfBarrier = self.terrainModel.find('**/collision1') if not self.golfBarrier.isEmpty(): golfBarrierCollection = self.terrainModel.findAllMatches('**/collision?') - for i in xrange(golfBarrierCollection.getNumPaths()): + for i in range(golfBarrierCollection.getNumPaths()): oneBarrier = golfBarrierCollection.getPath(i) if oneBarrier != self.golfBarrier: oneBarrier.wrtReparentTo(self.golfBarrier) @@ -90,7 +90,7 @@ def loadLevel(self): self.meshDataList.append(hardData) hardGeom = OdeTriMeshGeom(self.space, hardData) self.geomDataList.append(hardGeom) - hardGeom.setCollideBits(BitMask32(4026531840L)) + hardGeom.setCollideBits(BitMask32(4026531840)) hardGeom.setCategoryBits(BitMask32(240)) self.space.setCollideId(hardGeom, 3) hardSurface = self.space.getSurfaceType(hardGeom) @@ -126,7 +126,7 @@ def createRays(self): self.ballRay.setOffsetRotation(Mat3(1, 0, 0, 0, -1, 0, 0, 0, -1)) self.ballRay.setOffsetPosition(0, 0, 0.0) self.ballRay.setCollideBits(BitMask32(16773375)) - self.ballRay.setCategoryBits(BitMask32(4278190080L)) + self.ballRay.setCategoryBits(BitMask32(4278190080)) self.ballRayBody = body self.space.setCollideId(self.ballRay, GolfGlobals.OOB_RAY_COLLIDE_ID) self.rayList.append(self.ballRay) @@ -207,7 +207,7 @@ def trackRecordBodyFlight(self, ball, cycleTime, power, startPos, dirX, dirY): lift = 0 startTime = GolfGlobals.BALL_CONTACT_FRAME / 24 startFrame = int(startTime * self.FPS) - for frame in xrange(int(startFrame)): + for frame in range(int(startFrame)): self.simulate() self.setTimeIntoCycle(self.swingTime + float(frameCount) * self.DTAStep) frameCount += 1 @@ -268,7 +268,7 @@ def trackRecordBodyFlight(self, ball, cycleTime, power, startPos, dirX, dirY): self.notify.debug('renable limit passed') elif self.frame > 2100 + checkFrames: self.comObjNeedPass = 0 - print 'recording limit passed comObj' + print('recording limit passed comObj') if ball.isEnabled(): lastFrameEnabled = self.frame diff --git a/toontown/golf/GolfRewardDialog.py b/toontown/golf/GolfRewardDialog.py index 2912dcf43..818afefe9 100644 --- a/toontown/golf/GolfRewardDialog.py +++ b/toontown/golf/GolfRewardDialog.py @@ -32,7 +32,7 @@ def calcTrophyTextListForOnePlayer(self, avId): if av and avId in self.avIdList: playerIndex = self.avIdList.index(avId) name = av.getName() - for trophyIndex in xrange(len(self.trophyList[playerIndex])): + for trophyIndex in range(len(self.trophyList[playerIndex])): wonTrophy = self.trophyList[playerIndex][trophyIndex] if wonTrophy: trophyName = TTLocalizer.GolfTrophyDescriptions[trophyIndex] @@ -44,26 +44,26 @@ def calcTrophyTextListForOnePlayer(self, avId): def calcCupTextListForAllPlayers(self, localAvId): retval = [] - for cupPlayerIndex in xrange(len(self.avIdList)): + for cupPlayerIndex in range(len(self.avIdList)): if self.avIdList[cupPlayerIndex] != localAvId: av = base.cr.doId2do.get(self.avIdList[cupPlayerIndex]) name = '' if av: name = av.getName() cupIndex = 0 - for cupIndex in xrange(len(self.cupList[cupPlayerIndex])): + for cupIndex in range(len(self.cupList[cupPlayerIndex])): if self.cupList[cupPlayerIndex][cupIndex]: cupName = TTLocalizer.GolfCupDescriptions[cupIndex] text = TTLocalizer.GolfAvReceivesCup % {'name': name, 'cup': cupName} retval.append(text) - for cupPlayerIndex in xrange(len(self.avIdList)): + for cupPlayerIndex in range(len(self.avIdList)): if self.avIdList[cupPlayerIndex] == localAvId: av = base.cr.doId2do.get(self.avIdList[cupPlayerIndex]) name = av.getName() cupIndex = 0 - for cupIndex in xrange(len(self.cupList[cupPlayerIndex])): + for cupIndex in range(len(self.cupList[cupPlayerIndex])): if self.cupList[cupPlayerIndex][cupIndex]: cupName = TTLocalizer.GolfCupDescriptions[cupIndex] text = TTLocalizer.GolfAvReceivesCup % {'name': name, @@ -75,8 +75,8 @@ def calcCupTextListForAllPlayers(self, localAvId): def calcRankings(self, localAvId): retval = [] self.notify.debug('aimTimesList=%s' % self.aimTimesList) - for rank in xrange(len(self.rankingsList) + 1): - for avIndex in xrange(len(self.avIdList)): + for rank in range(len(self.rankingsList) + 1): + for avIndex in range(len(self.avIdList)): if self.rankingsList[avIndex] == rank: name = ' ' av = base.cr.doId2do.get(self.avIdList[avIndex]) @@ -106,22 +106,22 @@ def calcRankings(self, localAvId): def calcHoleBestTextListForAllPlayers(self, localAvId): retval = [] if GolfGlobals.CalcOtherHoleBest: - for hbPlayerIndex in xrange(len(self.avIdList)): + for hbPlayerIndex in range(len(self.avIdList)): if self.avIdList[hbPlayerIndex] != localAvId: av = base.cr.doId2do.get(self.avIdList[hbPlayerIndex]) name = av.getName() - for hbIndex in xrange(len(self.holeBestList[hbPlayerIndex])): + for hbIndex in range(len(self.holeBestList[hbPlayerIndex])): if self.holeBestList[hbPlayerIndex][hbIndex]: hbName = TTLocalizer.GolfHoleNames[hbIndex] text = TTLocalizer.GolfAvReceivesHoleBest % {'name': name, 'hole': hbName} retval.append(text) - for hbPlayerIndex in xrange(len(self.avIdList)): + for hbPlayerIndex in range(len(self.avIdList)): if self.avIdList[hbPlayerIndex] == localAvId: av = base.cr.doId2do.get(self.avIdList[hbPlayerIndex]) name = av.getName() - for hbIndex in xrange(len(self.holeBestList[hbPlayerIndex])): + for hbIndex in range(len(self.holeBestList[hbPlayerIndex])): if self.holeBestList[hbPlayerIndex][hbIndex]: hbName = TTLocalizer.GolfHoleNames[hbIndex] text = TTLocalizer.GolfAvReceivesHoleBest % {'name': name, @@ -133,22 +133,22 @@ def calcHoleBestTextListForAllPlayers(self, localAvId): def calcCourseBestTextListForAllPlayers(self, localAvId): retval = [] if GolfGlobals.CalcOtherCourseBest: - for cbPlayerIndex in xrange(len(self.avIdList)): + for cbPlayerIndex in range(len(self.avIdList)): if self.avIdList[cbPlayerIndex] != localAvId: av = base.cr.doId2do.get(self.avIdList[cbPlayerIndex]) name = av.getName() - for cbIndex in xrange(len(self.holeBestList[cbPlayerIndex])): + for cbIndex in range(len(self.holeBestList[cbPlayerIndex])): if self.holeBestList[cbPlayerIndex][cbIndex]: cbName = TTLocalizer.GolfCourseNames[cbIndex] text = TTLocalizer.GolfAvReceivesCourseBest % {'name': name, 'course': cbName} retval.append(text) - for cbPlayerIndex in xrange(len(self.avIdList)): + for cbPlayerIndex in range(len(self.avIdList)): if self.avIdList[cbPlayerIndex] == localAvId: av = base.cr.doId2do.get(self.avIdList[cbPlayerIndex]) name = av.getName() - for cbIndex in xrange(len(self.courseBestList[cbPlayerIndex])): + for cbIndex in range(len(self.courseBestList[cbPlayerIndex])): if self.courseBestList[cbPlayerIndex][cbIndex]: cbName = TTLocalizer.GolfCourseNames[cbIndex] text = TTLocalizer.GolfAvReceivesCourseBest % {'name': name, @@ -227,7 +227,7 @@ def setRankLabelText(text): retval.append(randomWinnerIval) rankings = self.calcRankings(localAvId) rankText = TTLocalizer.GolfRanking + '\n' - for rank in xrange(len(rankings)): + for rank in range(len(rankings)): rankText = rankText + rankings[rank] + '\n' oneRankIval = Parallel(Func(setRankLabelText, rankText), LerpColorScaleInterval(self.rankLabel, 8, Vec4(1, 1, 1, 1), startColorScale=Vec4(1, 1, 1, 1), blendType='easeIn')) diff --git a/toontown/golf/GolfScoreBoard.py b/toontown/golf/GolfScoreBoard.py index 02b410d80..000a48c55 100644 --- a/toontown/golf/GolfScoreBoard.py +++ b/toontown/golf/GolfScoreBoard.py @@ -57,13 +57,13 @@ def setup(self): title = GolfGlobals.getCourseName(self.golfCourse.courseId) + ' - ' + GolfGlobals.getHoleName(self.golfCourse.holeIds[self.golfCourse.curHoleIndex]) self.titleLabel = DirectLabel(parent=self.scoreboard, relief=None, pos=(0, 0, holeTop + 0.1), text_align=TextNode.ACenter, text=title, text_scale=TTLocalizer.GSBtitleLabel, text_font=ToontownGlobals.getSignFont(), text_fg=(0, 0.5, 0.125, 1)) self.playaLabel = DirectLabel(parent=self.scoreboard, relief=None, pos=(self.lineVStart - 0.23, 0, holeTop), text_align=TextNode.ACenter, text=TTLocalizer.GolfHole, text_font=ToontownGlobals.getMinnieFont(), text_scale=0.05) - for holeLIndex in xrange(self.golfCourse.numHoles): + for holeLIndex in range(self.golfCourse.numHoles): holeLabel = DirectLabel(parent=self.scoreboard, relief=None, pos=(self.lineVStart + 0.055 + horzOffset * holeLIndex, 0, holeTop), text_align=TextNode.ACenter, text='%s' % (holeLIndex + 1), text_scale=0.05) self.holeLabels.append(holeLabel) self.totalLabel = DirectLabel(parent=self.scoreboard, relief=None, pos=(self.lineVStart + 0.1 + horzOffset * 9.5, 0, holeTop), text_align=TextNode.ACenter, text=TTLocalizer.GolfTotal, text_font=ToontownGlobals.getMinnieFont(), text_scale=0.05) self.parTitleLabel = DirectLabel(parent=self.scoreboard, relief=None, pos=(self.lineVStart - 0.23, 0, holeTop - 0.1), text_align=TextNode.ACenter, text=TTLocalizer.GolfPar, text_font=ToontownGlobals.getMinnieFont(), text_scale=0.05) - for parHoleIndex in xrange(self.golfCourse.numHoles): + for parHoleIndex in range(self.golfCourse.numHoles): parLabel = DirectLabel(parent=self.scoreboard, relief=None, pos=(self.lineVStart + 0.055 + horzOffset * parHoleIndex, 0, holeTop - 0.1), text_align=TextNode.ACenter, text='%s' % GolfGlobals.HoleInfo[self.golfCourse.holeIds[parHoleIndex]]['par'], text_scale=0.05, text_wordwrap=10) totPar = totPar + GolfGlobals.HoleInfo[self.golfCourse.holeIds[parHoleIndex]]['par'] self.parLabels.append(parLabel) @@ -72,7 +72,7 @@ def setup(self): self.parLabels.append(parLabel) vert = 0.0 self.numPlayas = len(self.golfCourse.avIdList) - for playaIndex in xrange(self.numPlayas): + for playaIndex in range(self.numPlayas): name = TTLocalizer.GolfUnknownPlayer av = base.cr.doId2do.get(self.golfCourse.avIdList[playaIndex]) if av: @@ -92,7 +92,7 @@ def setup(self): self.playaTags[playaIndex].setPos(self.lineVStart - 0.23, 0, vert) self.notify.debug('self.text height = %f' % self.playaTags[playaIndex].getHeight()) holeIndex = 0 - for holeIndex in xrange(self.golfCourse.numHoles): + for holeIndex in range(self.golfCourse.numHoles): holeLabel = DirectLabel(parent=self.scoreboard, relief=None, pos=(self.lineVStart + 0.055 + horzOffset * holeIndex, 0, self.playaTop - self.vertOffset * playaIndex - self.vCenter), text_align=TextNode.ACenter, text='-', text_scale=0.05, text_wordwrap=10) self.scoreTags.append(holeLabel) @@ -109,11 +109,11 @@ def setup(self): self.lines.drawTo(self.lineVStart - 0.45, 0, self.lineHStart - 4 * 0.13) self.lines.moveTo(self.lineVStart, 0, self.lineHStart + 0.19) self.lines.drawTo(self.lineVStart, 0, self.lineHStart - 4 * 0.13) - for x in xrange(4): + for x in range(4): self.lines.moveTo(self.lineVStart - 0.45, 0, self.lineHStart - (x + 1) * self.lineHorOffset) self.lines.drawTo(self.lineVStart + 11 * self.lineVertOffset + 0.005, 0, self.lineHStart - (x + 1) * self.lineHorOffset) - for y in xrange(10): + for y in range(10): self.lines.moveTo(self.lineVStart + y * self.lineVertOffset, 0, self.lineHStart + 0.19) self.lines.drawTo(self.lineVStart + y * self.lineVertOffset, 0, self.lineHStart - 4 * 0.13) @@ -127,7 +127,7 @@ def getScoreLabel(self, avIdorIndex, holeNum): if avIdorIndex < 100: index = avIdorIndex else: - for playaIndex in xrange(self.numPlayas): + for playaIndex in range(self.numPlayas): if self.golfCourse.avIdList[playaIndex] == avIdorIndex: index = playaIndex @@ -153,7 +153,7 @@ def showBoard(self, task = None): scoreDict = self.golfCourse.scores x = 0 currentGolfer = self.golfCourse.getCurGolfer() - for playaIndex in xrange(self.numPlayas): + for playaIndex in range(self.numPlayas): if self.golfCourse.isGameDone(): self.playaTags[playaIndex].setColor(0, 0, 0, 1) elif currentGolfer == self.golfCourse.avIdList[playaIndex]: @@ -168,18 +168,18 @@ def showBoard(self, task = None): holeIndex = 0 totScore = 0 playerExited = False - for y in xrange(len(self.golfCourse.exitedAvIdList)): + for y in range(len(self.golfCourse.exitedAvIdList)): if self.golfCourse.exitedAvIdList[y] == avId: self.playaTags[x].setColor(0.7, 0.7, 0.7, 1) holeIndex = 0 - for holeIndex in xrange(self.golfCourse.numHoles): + for holeIndex in range(self.golfCourse.numHoles): self.getScoreLabel(self.avIdList[x], holeIndex).setColor(0.7, 0.7, 0.7, 1) self.totalTags[x].setColor(0.7, 0.7, 0.7, 1) playerExited = True if playerExited == False: - for holeIndex in xrange(self.golfCourse.numHoles): + for holeIndex in range(self.golfCourse.numHoles): if holeIndex <= self.golfCourse.curHoleIndex: self.getScoreLabel(avId, holeIndex)['text'] = '%s' % scoreDict[avId][holeIndex] totScore = totScore + scoreDict[avId][holeIndex] diff --git a/toontown/golf/PhysicsWorldBase.py b/toontown/golf/PhysicsWorldBase.py index f9c609f72..8c52efe0a 100644 --- a/toontown/golf/PhysicsWorldBase.py +++ b/toontown/golf/PhysicsWorldBase.py @@ -142,7 +142,7 @@ def setupSimulation(self): self.DTA = 0.0 self.frameCounter = 0 if self.canRender: - for count in xrange(self.jointMarkerCount): + for count in range(self.jointMarkerCount): testMarker = render.attachNewNode('Joint Marker') ballmodel = loader.loadModel('phase_3/models/misc/sphere') ballmodel.reparentTo(testMarker) @@ -159,7 +159,7 @@ def getTimingCycleLength(self): def getCycleTime(self, doprint = 0): cycleTime = (globalClock.getRealTime() + self.timingCycleOffset) % self.timingCycleLength if doprint: - print 'Get Cycle Time %s' % cycleTime + print('Get Cycle Time %s' % cycleTime) return cycleTime def setTimeIntoCycle(self, time, doprint = 0): @@ -231,7 +231,7 @@ def preStep(self): def postStep(self): if self.showContacts and self.canRender: - for count in xrange(self.jointMarkerCount): + for count in range(self.jointMarkerCount): pandaNodePathGeom = self.jointMarkers[count] if count < self.colCount: pandaNodePathGeom.setPos(self.space.getContactData(count * 3 + 0), self.space.getContactData(count * 3 + 1), self.space.getContactData(count * 3 + 2)) @@ -253,7 +253,7 @@ def commonObjectControl(self): eventData = entry[6] model = entry[7] force = 0.0 - for index in xrange(len(timeData)): + for index in range(len(timeData)): if index == len(timeData) - 1 and timeData[index] < time or timeData[index] < time and timeData[index + 1] > time: force = forceData[index] event = eventData[index] @@ -324,7 +324,7 @@ def useCommonObjectData(self, objectData, enable = 1): self.setTimeIntoCycle(time[2]) if time[2] > self.timingCycleLength: pass - for dataIndex in xrange(1, len(objectData)): + for dataIndex in range(1, len(objectData)): data = objectData[dataIndex] commonObject = self.commonObjectDict[data[0]] commonObject[2].setPosition(data[2], data[3], data[4]) @@ -489,22 +489,22 @@ def createSphere(self, world, space, density, radius, ballIndex = None): if ballIndex == 1: self.notify.debug('1') geom.setCollideBits(BitMask32(16777215)) - geom.setCategoryBits(BitMask32(4278190080L)) + geom.setCategoryBits(BitMask32(4278190080)) elif ballIndex == 2: self.notify.debug('2') geom.setCollideBits(BitMask32(16777215)) - geom.setCategoryBits(BitMask32(4278190080L)) + geom.setCategoryBits(BitMask32(4278190080)) elif ballIndex == 3: self.notify.debug('3') geom.setCollideBits(BitMask32(16777215)) - geom.setCategoryBits(BitMask32(4278190080L)) + geom.setCategoryBits(BitMask32(4278190080)) elif ballIndex == 4: self.notify.debug('4') geom.setCollideBits(BitMask32(16777215)) - geom.setCategoryBits(BitMask32(4278190080L)) + geom.setCategoryBits(BitMask32(4278190080)) else: - geom.setCollideBits(BitMask32(4294967295L)) - geom.setCategoryBits(BitMask32(4294967295L)) + geom.setCollideBits(BitMask32(4294967295)) + geom.setCategoryBits(BitMask32(4294967295)) geom.setBody(body) if self.notify.getDebug(): self.notify.debug('golf ball geom id') @@ -685,7 +685,7 @@ def createPinWheel(self, world, space, density, lx, ly, lz, numBoxes, disV, disH someNodePathGeom = render.attachNewNode('pinwheel') else: someNodePathGeom = self.root.attachNewNode('pinwheel') - for num in xrange(numBoxes): + for num in range(numBoxes): spin = 360.0 * float(num) / float(numBoxes) + float(offRot) self.placerNode.setH(spin) geom = OdeBoxGeom(space, boxsize) diff --git a/toontown/hood/BoardbotHQAI.py b/toontown/hood/BoardbotHQAI.py index 351315fc5..47c787125 100644 --- a/toontown/hood/BoardbotHQAI.py +++ b/toontown/hood/BoardbotHQAI.py @@ -53,7 +53,7 @@ def createBoardOfficeElevators(self): ToontownGlobals.BoardOfficeIntC ) mins = ToontownGlobals.FactoryLaffMinimums[1] - for i in xrange(len(destZones)): + for i in range(len(destZones)): boardofficeElevator = DistributedBoardOfficeElevatorExtAI( self.air, self.air.boardofficeMgr, destZones[i], antiShuffle=0, minLaff=mins[i]) diff --git a/toontown/hood/BossbotHQAI.py b/toontown/hood/BossbotHQAI.py index c8a2e60ce..5d909fb19 100644 --- a/toontown/hood/BossbotHQAI.py +++ b/toontown/hood/BossbotHQAI.py @@ -38,7 +38,7 @@ def createCogKarts(self): ) hprList = ((110.815, 0, 0), (61.231, 0, 0), (-105.481, 0, 0)) mins = ToontownGlobals.FactoryLaffMinimums[3] - for cogCourse in xrange(len(posList)): + for cogCourse in range(len(posList)): pos = posList[cogCourse] hpr = hprList[cogCourse] cogKart = DistributedCogKartAI.DistributedCogKartAI( diff --git a/toontown/hood/CashbotHQAI.py b/toontown/hood/CashbotHQAI.py index 63399de72..4316699da 100644 --- a/toontown/hood/CashbotHQAI.py +++ b/toontown/hood/CashbotHQAI.py @@ -38,7 +38,7 @@ def createMintElevators(self): ToontownGlobals.CashbotMintIntC ) mins = ToontownGlobals.FactoryLaffMinimums[1] - for i in xrange(len(destZones)): + for i in range(len(destZones)): mintElevator = DistributedMintElevatorExtAI( self.air, self.air.mintMgr, destZones[i], antiShuffle=0, minLaff=mins[i]) diff --git a/toontown/hood/DGHoodAI.py b/toontown/hood/DGHoodAI.py index 64ba41bf9..33bc7153a 100644 --- a/toontown/hood/DGHoodAI.py +++ b/toontown/hood/DGHoodAI.py @@ -84,8 +84,8 @@ def createClassicChar(self): def createButterflies(self, playground): ButterflyGlobals.generateIndexes(self.zoneId, ButterflyGlobals.DG) - for i in xrange(0, ButterflyGlobals.NUM_BUTTERFLY_AREAS[ButterflyGlobals.DG]): - for _ in xrange(0, ButterflyGlobals.NUM_BUTTERFLIES[ButterflyGlobals.DG]): + for i in range(0, ButterflyGlobals.NUM_BUTTERFLY_AREAS[ButterflyGlobals.DG]): + for _ in range(0, ButterflyGlobals.NUM_BUTTERFLIES[ButterflyGlobals.DG]): butterfly = DistributedButterflyAI(self.air, playground, i, self.zoneId) butterfly.generateWithRequired(self.zoneId) butterfly.start() diff --git a/toontown/hood/GSHoodAI.py b/toontown/hood/GSHoodAI.py index 8d9dd2040..ac542301b 100644 --- a/toontown/hood/GSHoodAI.py +++ b/toontown/hood/GSHoodAI.py @@ -67,7 +67,7 @@ def findRacingPads(self, dnaGroup, zoneId, area, padType='racing_pad'): racingPads.append(racingPad) elif isinstance(dnaGroup, DNAVisGroup): zoneId = ZoneUtil.getTrueZoneId(int(dnaGroup.getName().split(':')[0]), zoneId) - for i in xrange(dnaGroup.getNumChildren()): + for i in range(dnaGroup.getNumChildren()): (foundRacingPads, foundRacingPadGroups) = self.findRacingPads(dnaGroup.at(i), zoneId, area, padType=padType) racingPads.extend(foundRacingPads) racingPadGroups.extend(foundRacingPadGroups) @@ -90,7 +90,7 @@ def findStartingBlocks(self, dnaGroup, racePad): startingBlock.generateWithRequired(racePad.zoneId) startingBlocks.append(startingBlock) - for i in xrange(dnaGroup.getNumChildren()): + for i in range(dnaGroup.getNumChildren()): foundStartingBlocks = self.findStartingBlocks(dnaGroup.at(i), racePad) startingBlocks.extend(foundStartingBlocks) return startingBlocks diff --git a/toontown/hood/GZHoodAI.py b/toontown/hood/GZHoodAI.py index e88dc2d3f..0af9a0b1d 100644 --- a/toontown/hood/GZHoodAI.py +++ b/toontown/hood/GZHoodAI.py @@ -26,7 +26,7 @@ def findGolfKarts(self, dnaGroup, zoneId, area, overrideDNAZone=False): if isinstance(dnaGroup, DNAGroup.DNAGroup) and ('golf_kart' in dnaGroup.getName()): nameInfo = dnaGroup.getName().split('_') golfCourse = int(nameInfo[2]) - for i in xrange(dnaGroup.getNumChildren()): + for i in range(dnaGroup.getNumChildren()): childDnaGroup = dnaGroup.at(i) if 'starting_block' in childDnaGroup.getName(): pos = childDnaGroup.getPos() @@ -38,7 +38,7 @@ def findGolfKarts(self, dnaGroup, zoneId, area, overrideDNAZone=False): golfKarts.append(golfKart) elif isinstance(dnaGroup, DNAVisGroup) and (not overrideDNAZone): zoneId = ZoneUtil.getTrueZoneId(int(dnaGroup.getName().split(':')[0]), zoneId) - for i in xrange(dnaGroup.getNumChildren()): + for i in range(dnaGroup.getNumChildren()): foundGolfKarts = self.findGolfKarts(dnaGroup.at(i), zoneId, area, overrideDNAZone=overrideDNAZone) golfKarts.extend(foundGolfKarts) return golfKarts diff --git a/toontown/hood/Hood.py b/toontown/hood/Hood.py index 675886383..a6a91ee94 100644 --- a/toontown/hood/Hood.py +++ b/toontown/hood/Hood.py @@ -175,7 +175,7 @@ def handleWaitForSetZoneResponse(self, requestStatus): elif loaderName == 'minigame': pass elif loaderName == 'cogHQLoader': - print 'should be loading HQ' + print('should be loading HQ') def handleLeftQuietZone(self): status = self.quietZoneStateData.getRequestStatus() @@ -293,7 +293,7 @@ def skyTrack(self, task): def skyTransition(self, sky): if self.id != DonaldsDreamland or self.id != DonaldsDock or self.id != TheBrrrgh: if self.sky.getTag('sky').lower() != sky: - print(self.sky.getTag('sky') + "-->" + sky) + print((self.sky.getTag('sky') + "-->" + sky)) if hasattr(self, 'sky'): self.oldSky = self.sky if sky == 'mml': diff --git a/toontown/hood/HoodAI.py b/toontown/hood/HoodAI.py index 2dc1b2889..62aa589e9 100644 --- a/toontown/hood/HoodAI.py +++ b/toontown/hood/HoodAI.py @@ -87,7 +87,7 @@ def shutdown(self): del self.air.buildingManagers[buildingManager.branchId] self.buildingManagers = [] del self.fishingPonds - for distObj in self.doId2do.values(): + for distObj in list(self.doId2do.values()): distObj.requestDelete() def findFishingPonds(self, dnaGroup, zoneId, area): @@ -104,7 +104,7 @@ def findFishingPonds(self, dnaGroup, zoneId, area): fishingPonds.append(fishingPond) elif isinstance(dnaGroup, DNAVisGroup): zoneId = ZoneUtil.getTrueZoneId(int(dnaGroup.getName().split(':')[0]), zoneId) - for i in xrange(dnaGroup.getNumChildren()): + for i in range(dnaGroup.getNumChildren()): (foundFishingPonds, foundFishingPondGroups) = self.findFishingPonds(dnaGroup.at(i), zoneId, area) fishingPonds.extend(foundFishingPonds) fishingPondGroups.extend(foundFishingPondGroups) @@ -121,7 +121,7 @@ def findFishingSpots(self, dnaGroup, fishingPond): fishingSpot.generateWithRequired(fishingPond.zoneId) fishingSpots.append(fishingSpot) - for i in xrange(dnaGroup.getNumChildren()): + for i in range(dnaGroup.getNumChildren()): foundFishingSpots = self.findFishingSpots(dnaGroup.at(i), fishingPond) fishingSpots.extend(foundFishingSpots) return fishingSpots @@ -153,7 +153,7 @@ def findPartyGates(self, dnaGroup, zoneId): partyGate.generateWithRequired(zoneId) partyGates.append(partyGates) - for i in xrange(dnaGroup.getNumChildren()): + for i in range(dnaGroup.getNumChildren()): foundPartyGates = self.findPartyGates(dnaGroup.at(i), zoneId) partyGates.extend(foundPartyGates) return partyGates diff --git a/toontown/hood/InteractiveAnimatedProp.py b/toontown/hood/InteractiveAnimatedProp.py index a4a952e3e..81fa23b21 100644 --- a/toontown/hood/InteractiveAnimatedProp.py +++ b/toontown/hood/InteractiveAnimatedProp.py @@ -334,7 +334,7 @@ def createIdleAnimSequence(self, whichIdleAnim): numberOfLoops = random.randrange(minLoop, maxLoop + 1) pauseTime = random.randrange(minPauseTime, maxPauseTime + 1) result = Sequence() - for i in xrange(numberOfLoops): + for i in range(numberOfLoops): result.append(idleAnimAndSound) if self.getSettleName(whichIdleAnim): @@ -495,7 +495,7 @@ def printAnimIfClose(self, animKey): baseAnimName = animName.split('/')[-1] if localAvatar.zoneId == self.visId: self.notify.info('playing %s' % baseAnimName) - except Exception, e: + except Exception as e: self.notify.warning('Unknown error in printAnimIfClose, giving up:\n%s' % str(e)) def clearCurIval(self): diff --git a/toontown/hood/LawbotHQAI.py b/toontown/hood/LawbotHQAI.py index fa4cdce74..45eff3594 100644 --- a/toontown/hood/LawbotHQAI.py +++ b/toontown/hood/LawbotHQAI.py @@ -51,7 +51,7 @@ def createLawOfficeElevators(self): ToontownGlobals.LawbotStageIntD ) mins = ToontownGlobals.FactoryLaffMinimums[2] - for i in xrange(len(destZones)): + for i in range(len(destZones)): lawOfficeElevator = DistributedLawOfficeElevatorExtAI( self.air, self.air.lawOfficeMgr, destZones[i], i, antiShuffle=0, minLaff=mins[i]) diff --git a/toontown/hood/Place.py b/toontown/hood/Place.py index ea1f73687..900a01681 100644 --- a/toontown/hood/Place.py +++ b/toontown/hood/Place.py @@ -418,7 +418,7 @@ def startPartyNow(self, firstStart, hostId): zoneId = 0 ToontownDistrictStats.refresh('shardInfoUpdated') curShardTuples = base.cr.listActiveShards() - lowestPop = 100000000000000000L + lowestPop = 100000000000000000 shardId = None for shardInfo in curShardTuples: pop = shardInfo[2] @@ -500,7 +500,7 @@ def enterDFACallback(self, requestStatus, doneStatus): elif doneStatus['mode'] == 'incomplete': self.fsm.request('DFAReject') else: - Place.notify.error('Unknown done status for DownloadForceAcknowledge: ' + `doneStatus`) + Place.notify.error('Unknown done status for DownloadForceAcknowledge: ' + repr(doneStatus)) def enterDFAReject(self): self.fsm.request('walk') diff --git a/toontown/hood/QuietZoneState.py b/toontown/hood/QuietZoneState.py index e36e01c0c..2fc6be21d 100644 --- a/toontown/hood/QuietZoneState.py +++ b/toontown/hood/QuietZoneState.py @@ -291,7 +291,7 @@ def hSZC(task): if base.placeBeforeObjects: self._leftQuietZoneCallbacks() self._leftQuietZoneCallbacks = None - fdcs = self._leftQuietZoneLocalCallbacks.values() + fdcs = list(self._leftQuietZoneLocalCallbacks.values()) self._leftQuietZoneLocalCallbacks = {} for fdc in fdcs: if not fdc.isFinished(): @@ -332,7 +332,7 @@ def _announceDone(self): requestStatus = self._requestStatus self._setZoneCompleteCallbacks() self._setZoneCompleteCallbacks = None - fdcs = self._setZoneCompleteLocalCallbacks.values() + fdcs = list(self._setZoneCompleteLocalCallbacks.values()) self._setZoneCompleteLocalCallbacks = {} for fdc in fdcs: if not fdc.isFinished(): diff --git a/toontown/hood/SellbotHQAI.py b/toontown/hood/SellbotHQAI.py index 092e0a7e1..5e1749169 100644 --- a/toontown/hood/SellbotHQAI.py +++ b/toontown/hood/SellbotHQAI.py @@ -27,7 +27,7 @@ def startup(self): # Sellbot HQ has not just one, but four lobby doors: self.cogHQDoors = [self.extDoor] - for i in xrange(3): # CogHQAI already created one of the doors for us. + for i in range(3): # CogHQAI already created one of the doors for us. extDoor = self.makeCogHQDoor(self.lobbyZoneId, 0, i + 1, self.lobbyFADoorCode) self.cogHQDoors.append(extDoor) self.createFactoryElevators() @@ -43,7 +43,7 @@ def startup(self): def createFactoryElevators(self): # We only have two factory elevators: the front, and side elevators. - for i in xrange(2): + for i in range(2): factoryElevator = DistributedFactoryElevatorExtAI( self.air, self.air.factoryMgr, ToontownGlobals.SellbotFactoryInt, i) factoryElevator.generateWithRequired(ToontownGlobals.SellbotFactoryExt) diff --git a/toontown/hood/TTHoodAI.py b/toontown/hood/TTHoodAI.py index 8fee73d2a..647bee982 100644 --- a/toontown/hood/TTHoodAI.py +++ b/toontown/hood/TTHoodAI.py @@ -58,8 +58,8 @@ def createClassicChar(self): def createButterflies(self): ButterflyGlobals.generateIndexes(self.zoneId, ButterflyGlobals.TTC) - for i in xrange(0, ButterflyGlobals.NUM_BUTTERFLY_AREAS[ButterflyGlobals.TTC]): - for _ in xrange(0, ButterflyGlobals.NUM_BUTTERFLIES[ButterflyGlobals.TTC]): + for i in range(0, ButterflyGlobals.NUM_BUTTERFLY_AREAS[ButterflyGlobals.TTC]): + for _ in range(0, ButterflyGlobals.NUM_BUTTERFLIES[ButterflyGlobals.TTC]): butterfly = DistributedButterflyAI(self.air, playground, i, self.zoneId) butterfly.generateWithRequired(self.zoneId) butterfly.start() diff --git a/toontown/hood/TTOHoodAI.py b/toontown/hood/TTOHoodAI.py index 4903373d4..dbd8696fc 100644 --- a/toontown/hood/TTOHoodAI.py +++ b/toontown/hood/TTOHoodAI.py @@ -62,8 +62,8 @@ def createClassicChar(self): def createButterflies(self): ButterflyGlobals.generateIndexes(self.zoneId, ButterflyGlobals.TTC) - for i in xrange(0, ButterflyGlobals.NUM_BUTTERFLY_AREAS[ButterflyGlobals.TTC]): - for _ in xrange(0, ButterflyGlobals.NUM_BUTTERFLIES[ButterflyGlobals.TTC]): + for i in range(0, ButterflyGlobals.NUM_BUTTERFLY_AREAS[ButterflyGlobals.TTC]): + for _ in range(0, ButterflyGlobals.NUM_BUTTERFLIES[ButterflyGlobals.TTC]): butterfly = DistributedButterflyAI(self.air, playground, i, self.zoneId) butterfly.generateWithRequired(self.zoneId) butterfly.start() diff --git a/toontown/hood/ZeroAnimatedProp.py b/toontown/hood/ZeroAnimatedProp.py index 8f726b211..7e599ee4a 100644 --- a/toontown/hood/ZeroAnimatedProp.py +++ b/toontown/hood/ZeroAnimatedProp.py @@ -31,8 +31,8 @@ def delete(self): def loadPhaseAnims(self): animDict = {} - for key, info in self.phaseInfo.iteritems(): - if type(info[0]) == types.TupleType: + for key, info in self.phaseInfo.items(): + if type(info[0]) == tuple: for index, anims in enumerate(info[0]): fullPath = self.path + '/' + anims animName = 'phase%d_%d' % (key, index) @@ -50,9 +50,9 @@ def createPhaseIntervals(self): self.notify.debug('not creating phase ivals again') return self.phaseIvals = [] - for key, info in self.phaseInfo.iteritems(): + for key, info in self.phaseInfo.items(): self.notify.debug('key=%s' % key) - if type(info[0]) == types.TupleType: + if type(info[0]) == tuple: ival = Sequence() for index, anims in enumerate(info[0]): animName = 'phase%d_%d' % (key, index) @@ -96,7 +96,7 @@ def chooseAnimToRun(self): result = self.curPhase if base.config.GetBool('anim-props-randomized', True): pairs = [] - for i in xrange(self.curPhase + 1): + for i in range(self.curPhase + 1): pairs.append((math.pow(2, i), i)) sum = math.pow(2, self.curPhase + 1) - 1 diff --git a/toontown/launcher/QuickLauncher.py b/toontown/launcher/QuickLauncher.py index b15a6b9bc..283f0f243 100644 --- a/toontown/launcher/QuickLauncher.py +++ b/toontown/launcher/QuickLauncher.py @@ -55,7 +55,7 @@ class QuickLauncher(LauncherBase): PatchExt = 'pch' def __init__(self): - print 'Running: ToontownQuickLauncher' + print('Running: ToontownQuickLauncher') self.toontownBlueKey = 'TOONTOWN_BLUE' self.launcherMessageKey = 'LAUNCHER_MESSAGE' self.game1DoneKey = 'GAME1_DONE' @@ -64,7 +64,7 @@ def __init__(self): LauncherBase.__init__(self) self.useTTSpecificLogin = config.GetBool('tt-specific-login', 0) self.toontownPlayTokenKey = 'TTI_PLAYCOOKIE' - print 'useTTSpecificLogin=%s' % self.useTTSpecificLogin + print('useTTSpecificLogin=%s' % self.useTTSpecificLogin) self.contentDir = '/' self.serverDbFileHash = HashVal() self.launcherFileDbHash = HashVal() @@ -141,7 +141,7 @@ def resumeMultifileDownload(self): self.downloadMultifile(serverFilename, localFilename, self.currentMfname, self.downloadMultifileDone, 0, 0, self.downloadMultifileWriteToDisk) def resumeInstall(self): - for self.currentPhaseIndex in xrange(len(self.LauncherPhases)): + for self.currentPhaseIndex in range(len(self.LauncherPhases)): self.currentPhase = self.LauncherPhases[self.currentPhaseIndex] self.currentPhaseName = self.Localizer.LauncherPhaseNames[self.currentPhase] self.currentMfname = 'phase_%s.mf' % self.currentPhase @@ -179,7 +179,7 @@ def resumeInstall(self): messenger.send('launcherAllPhasesComplete') self.cleanup() return - raise StandardError, 'Some phases not listed in LauncherPhases: %s' % self.requiredInstallFiles + raise Exception('Some phases not listed in LauncherPhases: %s' % self.requiredInstallFiles) def getDecompressMultifile(self, mfname): if not self.DecompressMultifiles: @@ -253,10 +253,10 @@ def decompressMultifileTask(self, task): def decompressMultifileDone(self): self.finalizePhase() - 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))) self.resumeInstall() def finalizePhase(self): @@ -293,7 +293,7 @@ def parseWebAcctParams(self): l = s.split('&') length = len(l) dict = {} - for index in xrange(0, len(l)): + for index in range(0, len(l)): args = l[index].split('=') if len(args) == 3: name, value = args[-2:] diff --git a/toontown/launcher/ToontownDummyLauncher.py b/toontown/launcher/ToontownDummyLauncher.py index 5aefe7f59..19fd6b940 100644 --- a/toontown/launcher/ToontownDummyLauncher.py +++ b/toontown/launcher/ToontownDummyLauncher.py @@ -44,7 +44,7 @@ def getReferrerCode(self): return None def setRegistry(self, name, value): - print 'setRegistry[%s] = %s' % (name, value) + print('setRegistry[%s] = %s' % (name, value)) self.reg[name] = value def getRegistry(self, name, defaultValue = None): @@ -52,7 +52,7 @@ def getRegistry(self, name, defaultValue = None): value = self.reg[name] else: value = defaultValue - print 'getRegistry[%s] = %s' % (name, value) + print('getRegistry[%s] = %s' % (name, value)) return value def getGame2Done(self): diff --git a/toontown/launcher/ToontownLauncher.py b/toontown/launcher/ToontownLauncher.py index 9dd105004..583fd5219 100644 --- a/toontown/launcher/ToontownLauncher.py +++ b/toontown/launcher/ToontownLauncher.py @@ -33,9 +33,9 @@ def flush(self): print('\n\nStarting Toontown...') if 1: - print 'Current time: ' + time.asctime(time.localtime(time.time())) + ' ' + time.tzname[0] - print 'sys.path = ', sys.path - print 'sys.argv = ', sys.argv + print('Current time: ' + time.asctime(time.localtime(time.time())) + ' ' + time.tzname[0]) + print('sys.path = ', sys.path) + print('sys.argv = ', sys.argv) from otp.launcher.LauncherBase import LauncherBase from otp.otpbase import OTPLauncherGlobals @@ -61,7 +61,7 @@ def __init__(self): self.accountServer = sys.argv[3] self.testServerFlag = int(sys.argv[4]) else: - print 'Error: Launcher: incorrect number of parameters' + print('Error: Launcher: incorrect number of parameters') sys.exit() self.toontownBlueKey = 'TOONTOWN_BLUE' @@ -108,7 +108,7 @@ def parseWebAcctParams(self): l = s.split('&') length = len(l) dict = {} - for index in xrange(0, len(l)): + for index in range(0, len(l)): args = l[index].split('=') if len(args) == 3: [name, value] = args[-2:] @@ -150,12 +150,12 @@ def setRegistry(self, name, value): return t = type(value) - if t == types.IntType: + if t == int: WindowsRegistry.setIntValue(self.toontownRegistryKey, name, value) - elif t == types.StringType: + elif t == bytes: WindowsRegistry.setStringValue(self.toontownRegistryKey, name, value) else: - self.notify.warning('setRegistry: Invalid type for registry value: ' + `value`) + self.notify.warning('setRegistry: Invalid type for registry value: ' + repr(value)) def getRegistry(self, name, missingValue=None): self.notify.info('getRegistry%s' % ((name, missingValue),)) diff --git a/toontown/login/AccountServerDate.py b/toontown/login/AccountServerDate.py index dc77ecf0c..03c41f45e 100644 --- a/toontown/login/AccountServerDate.py +++ b/toontown/login/AccountServerDate.py @@ -28,12 +28,12 @@ def grabDate(self, force = 0): response = getHTTPResponse(url, http) if response[0] != 'ACCOUNT SERVER DATE': self.notify.debug('invalid response header') - raise UnexpectedResponse, 'unexpected response, response=%s' % response + raise UnexpectedResponse('unexpected response, response=%s' % response) try: epoch = int(response[1]) - except ValueError, e: + except ValueError as e: self.notify.debug(str(e)) - raise UnexpectedResponse, 'unexpected response, response=%s' % response + raise UnexpectedResponse('unexpected response, response=%s' % response) timeTuple = time.gmtime(epoch) self.year = timeTuple[0] diff --git a/toontown/login/AvatarChooser.py b/toontown/login/AvatarChooser.py index 4ae7cf786..8bcc7a356 100644 --- a/toontown/login/AvatarChooser.py +++ b/toontown/login/AvatarChooser.py @@ -108,7 +108,7 @@ def load(self, isPaid): used_position_indexs.append(av.position) self.panelList.append(panel) - for panelNum in xrange(0, MAX_AVATARS): + for panelNum in range(0, MAX_AVATARS): if panelNum not in used_position_indexs: panel = AvatarChoice.AvatarChoice(position=panelNum, paid=isPaid) panel.setPos(POSITIONS[panelNum]) @@ -139,7 +139,7 @@ def getLookAtPosition(self, toonHead, toonidx): return toonHead.getRandomForwardLookAtPoint() else: other_toon_idxs = [] - for i in xrange(len(self.IsLookingAt)): + for i in range(len(self.IsLookingAt)): if self.IsLookingAt[i] == toonidx: other_toon_idxs.append(i) @@ -187,7 +187,7 @@ def initLookAtInfo(self): if len(self.used_panel_indexs) == 0: return self.IsLookingAt = [] - for i in xrange(MAX_AVATARS): + for i in range(MAX_AVATARS): self.IsLookingAt.append('f') for panel in self.panelList: diff --git a/toontown/makeatoon/BodyShop.py b/toontown/makeatoon/BodyShop.py index 87e4623ff..e3e9f4302 100644 --- a/toontown/makeatoon/BodyShop.py +++ b/toontown/makeatoon/BodyShop.py @@ -264,7 +264,7 @@ def createSpeciesButtons(self): (.3, 0, -.5), (.6, 0, -.5), (.9, 0, -.5) ) - for x in xrange(len(ToonDNA.toonSpeciesTypes)): + for x in range(len(ToonDNA.toonSpeciesTypes)): name = TTLocalizer.AllSpecies[x] btn = DirectButton(relief = None, text_style = 3, image = (shuffleUp, shuffleDown, shuffleUp, shuffleDown), image_scale = (0.6, 0.7, 0.7), image1_scale = (0.63, 0.7, 0.7), image2_scale = (0.63, 0.7, 0.7), diff --git a/toontown/makeatoon/ColorShop.py b/toontown/makeatoon/ColorShop.py index f5780a205..71e1df8cb 100644 --- a/toontown/makeatoon/ColorShop.py +++ b/toontown/makeatoon/ColorShop.py @@ -61,7 +61,7 @@ def exit(self): try: del self.toon except: - print 'ColorShop: toon not found' + print('ColorShop: toon not found') self.hideButtons() @@ -180,8 +180,8 @@ def calcRelative(self, value, baseMin, baseMax, limitMin, limitMax): return ((limitMax - limitMin) * (value - baseMin) / (baseMax - baseMin)) + limitMin def __chooseHue(self): - for x in xrange(self.pickImage.getXSize()): - for y in xrange(self.pickImage.getYSize()): + for x in range(self.pickImage.getXSize()): + for y in range(self.pickImage.getYSize()): self.pickImage.setXel(x, y, colorsys.hsv_to_rgb(self.hueSlider['value'], (x / 100.0) + 0.25, (y / 100.0) + 0.4)) texture = Texture() diff --git a/toontown/makeatoon/MakeAToon.py b/toontown/makeatoon/MakeAToon.py index 02adedb00..3582fa325 100644 --- a/toontown/makeatoon/MakeAToon.py +++ b/toontown/makeatoon/MakeAToon.py @@ -12,7 +12,7 @@ from toontown.makeatoon import ColorShop from toontown.makeatoon import GenderShop from toontown.makeatoon import StatusShop -from MakeAToonGlobals import * +from .MakeAToonGlobals import * from toontown.makeatoon import MakeClothesGUI from toontown.makeatoon import NameShop from otp.avatar import Avatar @@ -310,11 +310,11 @@ def load(self): self.musicVolume = base.config.GetFloat('makeatoon-music-volume', 1) self.sfxVolume = base.config.GetFloat('makeatoon-sfx-volume', 1) self.soundBack = base.loader.loadSfx('phase_3/audio/sfx/GUI_create_toon_back.ogg') - self.crashSounds = map(base.loader.loadSfx, ['phase_3/audio/sfx/tt_s_ara_mat_crash_boing.ogg', + self.crashSounds = list(map(base.loader.loadSfx, ['phase_3/audio/sfx/tt_s_ara_mat_crash_boing.ogg', 'phase_3/audio/sfx/tt_s_ara_mat_crash_glassBoing.ogg', 'phase_3/audio/sfx/tt_s_ara_mat_crash_wood.ogg', 'phase_3/audio/sfx/tt_s_ara_mat_crash_woodBoing.ogg', - 'phase_3/audio/sfx/tt_s_ara_mat_crash_woodGlass.ogg']) + 'phase_3/audio/sfx/tt_s_ara_mat_crash_woodGlass.ogg'])) def unload(self): self.exit() diff --git a/toontown/makeatoon/NameGenerator.py b/toontown/makeatoon/NameGenerator.py index 0ddf5265c..9bf9ff94c 100644 --- a/toontown/makeatoon/NameGenerator.py +++ b/toontown/makeatoon/NameGenerator.py @@ -8,8 +8,8 @@ import os from direct.showbase import AppRunnerGlobal from direct.directnotify import DirectNotifyGlobal -import ToonNamesEnglish -from StringIO import StringIO +from . import ToonNamesEnglish +from io import StringIO class NameGenerator: text = TextNode('text') @@ -58,7 +58,7 @@ def generateLists(self): self.capPrefixes, self.lastPrefixes, self.lastSuffixes] - for tu in self.nameDictionary.values(): + for tu in list(self.nameDictionary.values()): masterList[tu[0]].append(tu[1]) return 1 @@ -68,7 +68,7 @@ def _getNameParts(self, cat2part): {}, {}, {}] - for id, tpl in self.nameDictionary.iteritems(): + for id, tpl in self.nameDictionary.items(): cat, str = tpl if cat in cat2part: nameParts[cat2part[cat]][str] = id @@ -111,7 +111,7 @@ def returnUniqueID(self, name, listnumber): newtu[1] = (7, name) else: newtu[0] = (8, name) - for tu in self.nameDictionary.items(): + for tu in list(self.nameDictionary.items()): for g in newtu: if tu[1] == g: return tu[0] @@ -127,7 +127,7 @@ def findWidestInList(self, text, nameList): maxWidth = text.calcWidth(name) maxName = name - print maxName + ' ' + str(maxWidth) + print(maxName + ' ' + str(maxWidth)) return maxName def findWidestName(self): @@ -179,13 +179,13 @@ def printWidestName(self): name = self.findWidestName() width = self.text.calcWidth(name) widthStr = str(width) - print 'The widest name is: ' + name + ' (' + widthStr + ' units)' + print('The widest name is: ' + name + ' (' + widthStr + ' units)') def printWidestLastName(self): name = self.findWidestLastName() width = self.text.calcWidth(name) widthStr = str(width) - print 'The widest last name is: ' + name + ' (' + widthStr + ' units)' + print('The widest last name is: ' + name + ' (' + widthStr + ' units)') def randomName(self, boy = 0, girl = 0): if boy and girl: @@ -314,9 +314,9 @@ def printRandomNames(self, boy = 0, girl = 0, total = 1): width = self.text.calcWidth(name) widthStr = str(width) if boy: - print 'Boy: ' + name + ' (' + widthStr + ' units)' + print('Boy: ' + name + ' (' + widthStr + ' units)') if girl: - print 'Girl: ' + name + ' (' + widthStr + ' units)' + print('Girl: ' + name + ' (' + widthStr + ' units)') i += 1 def percentOver(self, limit = 9.0, samples = 1000): @@ -330,32 +330,32 @@ def percentOver(self, limit = 9.0, samples = 1000): i += 1 percent = float(over) / float(samples) * 100 - print 'Samples: ' + str(samples) + ' Over: ' + str(over) + ' Percent: ' + str(percent) + print('Samples: ' + str(samples) + ' Over: ' + str(over) + ' Percent: ' + str(percent)) def totalNames(self): firsts = len(self.boyFirsts) + len(self.girlFirsts) + len(self.neutralFirsts) - print 'Total firsts: ' + str(firsts) + print('Total firsts: ' + str(firsts)) lasts = len(self.lastPrefixes) * len(self.lastSuffixes) - print 'Total lasts: ' + str(lasts) + print('Total lasts: ' + str(lasts)) neutralTitleFirsts = len(self.neutralTitles) * len(self.neutralFirsts) boyTitleFirsts = len(self.boyTitles) * (len(self.neutralFirsts) + len(self.boyFirsts)) + len(self.neutralTitles) * len(self.boyFirsts) girlTitleFirsts = len(self.girlTitles) * (len(self.neutralFirsts) + len(self.girlFirsts)) + len(self.neutralTitles) * len(self.girlFirsts) totalTitleFirsts = neutralTitleFirsts + boyTitleFirsts + girlTitleFirsts - print 'Total title firsts: ' + str(totalTitleFirsts) + print('Total title firsts: ' + str(totalTitleFirsts)) neutralTitleLasts = len(self.neutralTitles) * lasts boyTitleLasts = len(self.boyTitles) * lasts girlTitleLasts = len(self.girlTitles) * lasts totalTitleLasts = neutralTitleLasts + boyTitleFirsts + girlTitleLasts - print 'Total title lasts: ' + str(totalTitleLasts) + print('Total title lasts: ' + str(totalTitleLasts)) neutralFirstLasts = len(self.neutralFirsts) * lasts boyFirstLasts = len(self.boyFirsts) * lasts girlFirstLasts = len(self.girlFirsts) * lasts totalFirstLasts = neutralFirstLasts + boyFirstLasts + girlFirstLasts - print 'Total first lasts: ' + str(totalFirstLasts) + print('Total first lasts: ' + str(totalFirstLasts)) neutralTitleFirstLasts = neutralTitleFirsts * lasts boyTitleFirstLasts = boyTitleFirsts * lasts girlTitleFirstLasts = girlTitleFirsts * lasts totalTitleFirstLasts = neutralTitleFirstLasts + boyTitleFirstLasts + girlTitleFirstLasts - print 'Total title first lasts: ' + str(totalTitleFirstLasts) + print('Total title first lasts: ' + str(totalTitleFirstLasts)) totalNames = firsts + lasts + totalTitleFirsts + totalTitleLasts + totalFirstLasts + totalTitleFirstLasts - print 'Total Names: ' + str(totalNames) + print('Total Names: ' + str(totalNames)) diff --git a/toontown/makeatoon/NameShop.py b/toontown/makeatoon/NameShop.py index 444b86ec3..7b61477f9 100644 --- a/toontown/makeatoon/NameShop.py +++ b/toontown/makeatoon/NameShop.py @@ -158,7 +158,7 @@ def enter(self, toon, usedNames, warp): k = self.allFirsts.index('Von') self.allFirsts[k] = 'von' except: - print "NameShop: Couldn't find von" + print("NameShop: Couldn't find von") if not self.addedGenderSpecific: nameShopGui = loader.loadModel('phase_3/models/gui/tt_m_gui_mat_nameShop') @@ -464,7 +464,7 @@ def load(self): self.approvalDialog.buttonList[0].setPos(0, 0, -.3) self.approvalDialog.buttonList[1].setPos(0, 0, -.43) self.approvalDialog['image_scale'] = (0.8, 1, 0.77) - for x in xrange(0, 2): + for x in range(0, 2): self.approvalDialog.buttonList[x]['text_pos'] = (0, -.01) self.approvalDialog.buttonList[x]['text_scale'] = (0.04, 0.05999) self.approvalDialog.buttonList[x].setScale(1.2, 1, 1) @@ -481,7 +481,7 @@ def ubershow(self, guiObjectsToShow): try: x.show() except: - print 'NameShop: Tried to show already removed object' + print('NameShop: Tried to show already removed object') if base.cr.productName in ['DE', 'BR']: self.typeANameButton.hide() @@ -496,7 +496,7 @@ def uberhide(self, guiObjectsToHide): try: x.hide() except: - print 'NameShop: Tried to hide already removed object' + print('NameShop: Tried to hide already removed object') def uberdestroy(self, guiObjectsToDestroy): self.notify.debug('uberdestroy %s' % str(guiObjectsToDestroy)) @@ -505,7 +505,7 @@ def uberdestroy(self, guiObjectsToDestroy): x.destroy() del x except: - print 'NameShop: Tried to destroy already removed object' + print('NameShop: Tried to destroy already removed object') def getNameIndices(self): return self.nameIndices @@ -543,7 +543,7 @@ def match(npcName, name = name): name = name.strip() return TextEncoder.upper(npcName) == TextEncoder.upper(name) - for npcId in NPCToons.NPCToonDict.keys(): + for npcId in list(NPCToons.NPCToonDict.keys()): npcName = NPCToons.NPCToonDict[npcId][1] if match(npcName): self.notify.info('name matches NPC name "%s"' % npcName) @@ -671,16 +671,16 @@ def _updateGuiWithPickAName(self, flags, names, fullName): self.nameIndices[0] = self.nameGen.returnUniqueID(uberReturn[3], 0) self.nameFlags[0] = 1 except: - print 'NameShop : Should have found title, uh oh!' - print uberReturn + print('NameShop : Should have found title, uh oh!') + print(uberReturn) try: self.firstIndex = self.allFirsts.index(uberReturn[4]) self.nameIndices[1] = self.nameGen.returnUniqueID(uberReturn[4], 1) self.nameFlags[1] = 1 except: - print 'NameShop : Should have found first name, uh oh!' - print uberReturn + print('NameShop : Should have found first name, uh oh!') + print(uberReturn) try: self.prefixIndex = self.allPrefixes.index(uberReturn[5]) @@ -692,8 +692,8 @@ def _updateGuiWithPickAName(self, flags, names, fullName): else: self.nameFlags[3] = 0 except: - print 'NameShop : Some part of last name not found, uh oh!' - print uberReturn + print('NameShop : Some part of last name not found, uh oh!') + print(uberReturn) self.updateCheckBoxes() self.updateLists() @@ -907,7 +907,7 @@ def _submitTypeANameAsPickAName(self): self.fsm.request('PickAName') flags = [pattern[0] != -1, pattern[1] != -1, pattern[2] != -1] names = [] - for i in xrange(len(pattern)): + for i in range(len(pattern)): if pattern[i] != -1: names.append(pnp.getNamePartString(self.toon.style.gender, i, pattern[i])) else: diff --git a/toontown/makeatoon/StartShop.py b/toontown/makeatoon/StartShop.py index b1ffd6d74..4ddb8b53b 100644 --- a/toontown/makeatoon/StartShop.py +++ b/toontown/makeatoon/StartShop.py @@ -2,7 +2,7 @@ from toontown.toon import ToonDNA from direct.fsm import StateData from direct.gui.DirectGui import * -from MakeAToonGlobals import * +from .MakeAToonGlobals import * from toontown.toonbase import TTLocalizer, ToontownGlobals, ToontownBattleGlobals from direct.directnotify import DirectNotifyGlobal from direct.task import Task @@ -37,7 +37,7 @@ def exit(self): try: del self.toon except: - print 'StartShop: toon not found' + print('StartShop: toon not found') self.hideButtons() @@ -65,7 +65,7 @@ def load(self): self.pgRButton = DirectButton(parent=self.pgFrame, relief=None, image=shuffleImage, image_scale=halfButtonInvertScale, image1_scale=halfButtonInvertHoverScale, image2_scale=halfButtonInvertHoverScale, pos=(0.2, 0, 0), command=self.__swapPG, extraArgs=[1]) self.pgInfo = DirectFrame(parent=self.pgFrame, relief=None, text='Starting Playground:', text_font=ToontownGlobals.getBuildingNametagFont(), text_scale=0.05, text_fg=(1,1,1,1), text_wordwrap=8.0, pos=(0, 0, 0.25)) self.gagFrame = DirectFrame(parent=self.parentFrame, image=poster, image_scale=(1,1,3), relief=None, pos=(0, 0, -0.5), scale=1.1, frameColor=(1, 1, 1, 1), text='', text_scale=0.046875, text_pos=(-0.001, -0.015), text_font=ToontownGlobals.getBuildingNametagFont(), text_fg=(1, 1, 1, 1)) - for trackId in xrange(len(ToontownBattleGlobals.Tracks)): + for trackId in range(len(ToontownBattleGlobals.Tracks)): iconGeom = invModel.find('**/' + ToontownBattleGlobals.AvPropsNew[trackId][0]) if trackId == 4 or trackId == 5: button = DirectButton(parent=self.gagFrame, image=iconGeom, relief=None, pos=(0, 0, .45-(buttonYOffset*trackId)), image_color=(0.3,0.3,0.3,1), state=DGG.DISABLED) diff --git a/toontown/makeatoon/StatusShop.py b/toontown/makeatoon/StatusShop.py index 74aafade4..b5e499fec 100644 --- a/toontown/makeatoon/StatusShop.py +++ b/toontown/makeatoon/StatusShop.py @@ -35,7 +35,7 @@ def exit(self): try: del self.toon except: - print 'StatusShop: toon not found' + print('StatusShop: toon not found') self.hideButtons() diff --git a/toontown/minigame/CatchGameGlobals.py b/toontown/minigame/CatchGameGlobals.py index 0541f7e2e..c918aac59 100644 --- a/toontown/minigame/CatchGameGlobals.py +++ b/toontown/minigame/CatchGameGlobals.py @@ -26,9 +26,9 @@ def isBaseline(self): Name2DropObjectType[type.name] = type Name2DOTypeId = {} -names = Name2DropObjectType.keys() +names = list(Name2DropObjectType.keys()) names.sort() -for i in xrange(len(names)): +for i in range(len(names)): Name2DOTypeId[names[i]] = i DOTypeId2Name = names diff --git a/toontown/minigame/CogThief.py b/toontown/minigame/CogThief.py index 315788be1..c35216301 100644 --- a/toontown/minigame/CogThief.py +++ b/toontown/minigame/CogThief.py @@ -217,7 +217,7 @@ def thinkAboutGettingBarrel(self): return if not hasattr(self.game, 'barrels'): return - if self.goalId not in xrange(len(self.game.barrels)): + if self.goalId not in range(len(self.game.barrels)): return if not self.lastThinkTime: self.lastThinkTime = globalClock.getFrameTime() @@ -396,7 +396,7 @@ def accumulate(self, accumulator, valueToAdd): def seeFriends(self): self.clearVisibleList() - for cogIndex in self.game.cogInfo.keys(): + for cogIndex in list(self.game.cogInfo.keys()): if cogIndex == self.cogIndex: continue if self.sameGoal(cogIndex): diff --git a/toontown/minigame/DistributedCannonGame.py b/toontown/minigame/DistributedCannonGame.py index d19b50d6b..563e170f8 100644 --- a/toontown/minigame/DistributedCannonGame.py +++ b/toontown/minigame/DistributedCannonGame.py @@ -191,7 +191,7 @@ def unload(self): del self.downButton del self.leftButton del self.rightButton - for avId in self.toonHeadDict.keys(): + for avId in list(self.toonHeadDict.keys()): head = self.toonHeadDict[avId] head.stopBlink() head.stopLookAroundNow() @@ -203,12 +203,12 @@ def unload(self): head.delete() del self.toonHeadDict - for model in self.toonModelDict.values(): + for model in list(self.toonModelDict.values()): model.removeNode() del self.toonModelDict del self.toonScaleDict - for interval in self.toonIntervalDict.values(): + for interval in list(self.toonIntervalDict.values()): interval.finish() del self.toonIntervalDict @@ -310,7 +310,7 @@ def __createCannons(self): self.cannonDict[avId] = [cannon, barrel] numAvs = self.numPlayers - for i in xrange(numAvs): + for i in range(numAvs): avId = self.avIdList[i] self.cannonLocationDict[avId] = Point3(i * CANNON_X_SPACING - (numAvs - 1) * CANNON_X_SPACING / 2, CANNON_Y, CANNON_Z) if self.DEBUG_TOWER_RANGE: diff --git a/toontown/minigame/DistributedCatchGame.py b/toontown/minigame/DistributedCatchGame.py index 8bd90a23f..b2a722149 100644 --- a/toontown/minigame/DistributedCatchGame.py +++ b/toontown/minigame/DistributedCatchGame.py @@ -26,6 +26,7 @@ from toontown.minigame.CatchGameGlobals import Name2DropObjectType from toontown.minigame.DropPlacer import * from toontown.minigame.DropScheduler import * +from functools import reduce class DistributedCatchGame(DistributedMinigame): DropTaskName = 'dropSomething' @@ -134,7 +135,7 @@ def unload(self): self.introMovie.finish() del self.introMovie del self.__textGen - for avId in self.toonSDs.keys(): + for avId in list(self.toonSDs.keys()): toonSD = self.toonSDs[avId] toonSD.unload() @@ -148,7 +149,7 @@ def unload(self): del self.ground self.dropShadow.removeNode() del self.dropShadow - for model in self.dropObjModels.values(): + for model in list(self.dropObjModels.values()): model.removeNode() del self.dropObjModels @@ -207,8 +208,8 @@ def scaledDimensions(widthHeight, scale): self.DropPeriod /= scaledNumPlayers typeProbs = {'fruit': 3, 'anvil': 1} - probSum = reduce(lambda x, y: x + y, typeProbs.values()) - for key in typeProbs.keys(): + probSum = reduce(lambda x, y: x + y, list(typeProbs.values())) + for key in list(typeProbs.keys()): typeProbs[key] = float(typeProbs[key]) / probSum scheduler = DropScheduler(CatchGameGlobals.GameDuration, self.FirstDropDelay, self.DropPeriod, self.MaxDropDuration, self.FasterDropDelay, self.FasterDropPeriodMult) @@ -287,7 +288,7 @@ def showPosts(self): Toon.Toon(), Toon.Toon(), Toon.Toon()] - for i in xrange(len(self.posts)): + for i in range(len(self.posts)): toon = self.posts[i] toon.setDNA(base.localAvatar.getStyle()) toon.reparentTo(render) @@ -309,12 +310,12 @@ def hidePosts(self): def showDropGrid(self): self.hideDropGrid() self.dropMarkers = [] - print 'dropRows: %s' % self.DropRows - print 'dropCols: %s' % self.DropColumns - for row in xrange(self.DropRows): + print('dropRows: %s' % self.DropRows) + print('dropCols: %s' % self.DropColumns) + for row in range(self.DropRows): self.dropMarkers.append([]) rowList = self.dropMarkers[row] - for column in xrange(self.DropColumns): + for column in range(self.DropColumns): toon = Toon.Toon() toon.setDNA(base.localAvatar.getStyle()) toon.reparentTo(render) @@ -393,7 +394,7 @@ def offstage(self): self.notify.debug('offstage') DistributedSmoothNode.activateSmoothing(1, 0) self.introMovie.finish() - for avId in self.toonSDs.keys(): + for avId in list(self.toonSDs.keys()): self.toonSDs[avId].exit() self.hidePosts() @@ -481,7 +482,7 @@ def enterPlay(self): self.scores = [0] * self.numPlayers spacing = 0.4 - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): avId = self.avIdList[i] avName = self.getAvatarName(avId) scorePanel = MinigameAvatarScorePanel.MinigameAvatarScorePanel(avId, avName) @@ -523,7 +524,7 @@ def exitPlay(self): self.ignore(self.uniqueName('enter' + suit.collSphereName)) suit.collNodePath.removeNode() - for ival in self.dropIntervals.values(): + for ival in list(self.dropIntervals.values()): ival.finish() del self.dropIntervals diff --git a/toontown/minigame/DistributedCogThiefGame.py b/toontown/minigame/DistributedCogThiefGame.py index 94b99fd1c..d6b6dff15 100644 --- a/toontown/minigame/DistributedCogThiefGame.py +++ b/toontown/minigame/DistributedCogThiefGame.py @@ -62,7 +62,7 @@ def load(self): DistributedMinigame.load(self) self.music = base.loader.loadMusic('phase_4/audio/bgm/MG_CogThief.ogg') self.initCogInfo() - for barrelIndex in xrange(CTGG.NumBarrels): + for barrelIndex in range(CTGG.NumBarrels): barrel = loader.loadModel('phase_4/models/minigames/cogthief_game_gagTank') barrel.setPos(CTGG.BarrelStartingPositions[barrelIndex]) barrel.setScale(self.BarrelScale) @@ -144,7 +144,7 @@ def unload(self): barrel.removeNode() del self.barrels - for avId in self.toonSDs.keys(): + for avId in list(self.toonSDs.keys()): toonSD = self.toonSDs[avId] toonSD.unload() @@ -170,7 +170,7 @@ def onstage(self): toonSD.enter() toonSD.fsm.request('normal') self.stopGameWalk() - for cogIndex in xrange(self.getNumCogs()): + for cogIndex in range(self.getNumCogs()): suit = self.cogInfo[cogIndex]['suit'].suit pos = self.cogInfo[cogIndex]['pos'] suit.reparentTo(self.gameBoard) @@ -182,12 +182,12 @@ def onstage(self): self.toonHitTracks[avId] = Wait(0.1) self.toonRNGs = [] - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): self.toonRNGs.append(RandomNumGen.RandomNumGen(self.randomNumGen)) self.sndTable = {'hitBySuit': [None] * self.numPlayers, 'falling': [None] * self.numPlayers} - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): self.sndTable['hitBySuit'][i] = base.loader.loadSfx('phase_4/audio/sfx/MG_Tag_C.ogg') self.sndTable['falling'][i] = base.loader.loadSfx('phase_4/audio/sfx/MG_cannon_whizz.ogg') @@ -202,7 +202,7 @@ def offstage(self): for barrel in self.barrels: barrel.hide() - for avId in self.toonSDs.keys(): + for avId in list(self.toonSDs.keys()): self.toonSDs[avId].exit() for avId in self.avIdList: @@ -350,7 +350,7 @@ def doCollisions(oldPos, newPos, self = self): base.mouseInterfaceNode.setRotateSpeed(ToontownGlobals.ToonRotateSpeed * 4) def initCogInfo(self): - for cogIndex in xrange(self.getNumCogs()): + for cogIndex in range(self.getNumCogs()): self.cogInfo[cogIndex] = {'pos': Point3(CTGG.CogStartingPositions[cogIndex]), 'goal': CTGG.NoGoal, 'goalId': CTGG.InvalidGoalId, @@ -359,7 +359,7 @@ def initCogInfo(self): def loadCogs(self): suitTypes = SuitDNA.suitHeadTypes - for suitIndex in xrange(self.getNumCogs()): + for suitIndex in range(self.getNumCogs()): st = self.randomNumGen.choice(suitTypes) suit = CogThief.CogThief(suitIndex, st, self, self.getCogSpeed()) self.cogInfo[suitIndex]['suit'] = suit @@ -399,7 +399,7 @@ def hitBySuit(self, avId, timestamp, suitNum, x, y, z): return if self.gameIsEnding: return - self.notify.debug('avatar ' + `avId` + ' hit by a suit') + self.notify.debug('avatar ' + repr(avId) + ' hit by a suit') if avId != self.localAvId: self.showToonHitBySuit(avId, timestamp) self.makeSuitRespondToToonHit(timestamp, suitNum) @@ -415,7 +415,7 @@ def showToonHitBySuit(self, avId, timestamp): oldTrack.finish() toon.setPos(curPos) toon.setZ(self.TOON_Z) - parentNode = render.attachNewNode('mazeFlyToonParent-' + `avId`) + parentNode = render.attachNewNode('mazeFlyToonParent-' + repr(avId)) parentNode.setPos(toon.getPos()) toon.reparentTo(parentNode) toon.setPos(0, 0, 0) @@ -645,7 +645,7 @@ def throwingPie(self, avId, timestamp, heading, x, y, z): if self.gameFSM.getCurrentState().getName() not in ['play']: self.notify.warning('ignoring msg: av %s hit by suit' % avId) return - self.notify.debug('avatar ' + `avId` + ' throwing pie') + self.notify.debug('avatar ' + repr(avId) + ' throwing pie') if avId != self.localAvId: pos = Point3(x, y, z) self.showToonThrowingPie(avId, timestamp, heading, pos) @@ -741,7 +741,7 @@ def pieHitSuit(self, avId, timestamp, suitNum, x, y, z): return if self.gameIsEnding: return - self.notify.debug('avatar ' + `avId` + ' hit by a suit') + self.notify.debug('avatar ' + repr(avId) + ' hit by a suit') if avId != self.localAvId: self.makeSuitRespondToPieHit(timestamp, suitNum) diff --git a/toontown/minigame/DistributedCogThiefGameAI.py b/toontown/minigame/DistributedCogThiefGameAI.py index b5a4ac326..1fe387319 100644 --- a/toontown/minigame/DistributedCogThiefGameAI.py +++ b/toontown/minigame/DistributedCogThiefGameAI.py @@ -91,14 +91,14 @@ def exitCleanup(self): pass def initCogInfo(self): - for cogIndex in xrange(self.getNumCogs()): + for cogIndex in range(self.getNumCogs()): self.cogInfo[cogIndex] = {'pos': Point3(CogThiefGameGlobals.CogStartingPositions[cogIndex]), 'goal': CTGG.NoGoal, 'goalId': CTGG.InvalidGoalId, 'barrel': CTGG.NoBarrelCarried} def initBarrelInfo(self): - for barrelIndex in xrange(CogThiefGameGlobals.NumBarrels): + for barrelIndex in range(CogThiefGameGlobals.NumBarrels): self.barrelInfo[barrelIndex] = {'pos': Point3(CogThiefGameGlobals.BarrelStartingPositions[barrelIndex]), 'carriedBy': CTGG.BarrelOnGround, 'stolen': False} @@ -165,11 +165,11 @@ def isCogCarryingThisBarrel(self, cogIndex, barrelIndex): def startSuitGoals(self): delayTimes = [] - for cogIndex in xrange(self.getNumCogs()): + for cogIndex in range(self.getNumCogs()): delayTimes.append(cogIndex * 1.0) random.shuffle(delayTimes) - for cogIndex in xrange(self.getNumCogs()): + for cogIndex in range(self.getNumCogs()): self.doMethodLater(delayTimes[cogIndex], self.chooseSuitGoal, self.uniqueName('choseSuitGoal-%d-' % cogIndex), extraArgs=[cogIndex]) def chaseToon(self, suitNum, avId): @@ -281,7 +281,7 @@ def cogHitBarrel(self, clientStamp, cogIndex, barrelIndex, x, y, z): def chooseReturnPos(self, cogIndex, cogPos): shortestDistance = 10000 shortestReturnIndex = -1 - for retIndex in xrange(len(CTGG.CogReturnPositions)): + for retIndex in range(len(CTGG.CogReturnPositions)): retPos = CTGG.CogReturnPositions[retIndex] distance = (cogPos - retPos).length() if distance < shortestDistance: @@ -362,7 +362,7 @@ def markBarrelStolen(self, clientStamp, barrelIndex): def getNumBarrelsStolen(self): numStolen = 0 - for barrel in self.barrelInfo.values(): + for barrel in list(self.barrelInfo.values()): if barrel['stolen']: numStolen += 1 diff --git a/toontown/minigame/DistributedDivingGame.py b/toontown/minigame/DistributedDivingGame.py index 0038786fc..39df23c83 100644 --- a/toontown/minigame/DistributedDivingGame.py +++ b/toontown/minigame/DistributedDivingGame.py @@ -151,7 +151,7 @@ def unload(self): self.environModel.removeNode() del self.environModel self.removeChildGameFSM(self.gameFSM) - for avId in self.toonSDs.keys(): + for avId in list(self.toonSDs.keys()): toonSD = self.toonSDs[avId] toonSD.unload() @@ -291,7 +291,7 @@ def offstage(self): self.boatTilt.finish() self.mapModel.hide() DistributedSmoothNode.activateSmoothing(1, 0) - for avId in self.toonSDs.keys(): + for avId in list(self.toonSDs.keys()): self.toonSDs[avId].exit() base.camLens.setFar(ToontownGlobals.DefaultCameraFar) @@ -324,7 +324,7 @@ def offstage(self): del crab if hasattr(self, 'treasures') and self.treasures: - for i in xrange(self.NUMTREASURES): + for i in range(self.NUMTREASURES): self.treasures[i].destroy() del self.treasures @@ -335,7 +335,7 @@ def offstage(self): self.cSphereNodePath2.removeNode() del self.cSphereNodePath2 if hasattr(self, 'remoteToonCollNPs'): - for np in self.remoteToonCollNPs.values(): + for np in list(self.remoteToonCollNPs.values()): np.removeNode() del self.remoteToonCollNPs @@ -403,10 +403,10 @@ def setGameReady(self): self.SPEEDMULT = pattern[1] self.TIME = pattern[2] loadBase = 'phase_4/models/char/' - for i in xrange(self.NUMCRABS): + for i in range(self.NUMCRABS): self.crabs.append(Actor.Actor(loadBase + 'kingCrab-zero.bam', {'anim': loadBase + 'kingCrab-swimLOOP.bam'})) - for i in xrange(len(self.crabs)): + for i in range(len(self.crabs)): crab = self.crabs[i] crab.reparentTo(render) crab.name = 'king' @@ -439,7 +439,7 @@ def setGameReady(self): loadBase = 'phase_4/models/minigames/' self.treasures = [] self.chestIcons = {} - for i in xrange(self.NUMTREASURES): + for i in range(self.NUMTREASURES): self.chestIcons[i] = loader.loadModel(loadBase + 'treasure_chest.bam') self.chestIcons[i].reparentTo(self.mapModel) self.chestIcons[i].setScale(1.5) @@ -606,7 +606,7 @@ def __killTreasureBoundsTask(self): taskMgr.remove(self.TREASURE_BOUNDS_TASK) def __treasureBoundsTask(self, task): - for i in xrange(self.NUMTREASURES): + for i in range(self.NUMTREASURES): self.chestIcons[i].setPos(self.treasures[i].chest.getPos(render) / self.MAP_DIV) self.chestIcons[i].setZ(self.chestIcons[i].getZ() + self.MAP_OFF) if self.treasures[i].treasureNode.getZ() < -36: @@ -627,7 +627,7 @@ def incrementScore(self, avId, newSpot, timestamp): if avId == self.localAvId: self.reachedFlag = 0 if toonSD.status == 'treasure' and self.treasures and self.chestIcons: - for i in xrange(self.NUMTREASURES): + for i in range(self.NUMTREASURES): if self.treasures[i].grabbedId == avId: self.treasures[i].treasureNode.wrtReparentTo(render) self.treasures[i].grabbedId = 0 @@ -667,7 +667,7 @@ def setTreasureDropped(self, avId, timestamp): if not hasattr(self, 'treasures'): return ts = globalClockDelta.localElapsedTime(timestamp) - for i in xrange(self.NUMTREASURES): + for i in range(self.NUMTREASURES): if self.treasures[i].grabbedId == avId: self.treasures[i].grabbedId = 0 toonSD = self.toonSDs[avId] @@ -827,7 +827,7 @@ def setCrabMoving(self, crabId, timestamp, rand1, rand2, crabX, dir): crab = self.crabs[crabId] ts = globalClockDelta.localElapsedTime(timestamp) x = 0 - for i in xrange(self.NUMTREASURES): + for i in range(self.NUMTREASURES): x += self.treasures[i].treasureNode.getX(render) x /= self.NUMTREASURES @@ -916,7 +916,7 @@ def __updateLocalToonTask(self, task): pos[1] = -2 pos[2] += self.zVel * dt found = 0 - for i in xrange(self.NUMTREASURES): + for i in range(self.NUMTREASURES): if self.treasures[i].grabbedId == self.localAvId: found = 1 i = self.NUMTREASURES + 1 @@ -973,7 +973,7 @@ def exitSwim(self): self.treasurePanel.cleanup() self.mapAvatars[self.localAvId].destroy() del self.mapAvatars - for i in xrange(self.NUMTREASURES): + for i in range(self.NUMTREASURES): del self.chestIcons[i] del self.timer diff --git a/toontown/minigame/DistributedDivingGameAI.py b/toontown/minigame/DistributedDivingGameAI.py index 31ec45d70..eb11b064d 100644 --- a/toontown/minigame/DistributedDivingGameAI.py +++ b/toontown/minigame/DistributedDivingGameAI.py @@ -10,7 +10,7 @@ class DistributedDivingGameAI(DistributedMinigameAI): fishProportions = [] - for i in xrange(7): + for i in range(7): fishProportions.append([]) n = 100 @@ -304,7 +304,7 @@ def delete(self): def setGameReady(self): self.notify.debug('setGameReady') self.sendUpdate('setTrolleyZone', [self.trolleyZone]) - for avId in self.scoreDict.keys(): + for avId in list(self.scoreDict.keys()): self.scoreDict[avId] = 0 self.treasureHolders = [0] * self.numPlayers @@ -313,7 +313,7 @@ def setGameReady(self): self.REWARDMOD = self.difficultyPatternsAI[self.getSafezoneId()][2] DistributedMinigameAI.setGameReady(self) self.spawnings = [] - for i in xrange(DivingGameGlobals.NUM_SPAWNERS): + for i in range(DivingGameGlobals.NUM_SPAWNERS): self.spawnings.append(Sequence(Func(self.spawnFish, i), Wait(self.SPAWNTIME + random.random()), Func(self.spawnFish, i), Wait(self.SPAWNTIME - 0.5 + random.random()))) self.spawnings[i].loop() @@ -322,7 +322,7 @@ def setGameStart(self, timestamp): DistributedMinigameAI.setGameStart(self, timestamp) self.gameFSM.request('swimming') self.scoreTracking = {} - for avId in self.scoreDict.keys(): + for avId in list(self.scoreDict.keys()): self.scoreTracking[avId] = [0, 0, 0, @@ -357,10 +357,10 @@ def treasureRecovered(self): timestamp = globalClockDelta.getFrameNetworkTime() newSpot = int(random.random() * 30) self.scoreTracking[avId][4] += 1 - for someAvId in self.scoreDict.keys(): + for someAvId in list(self.scoreDict.keys()): if someAvId == avId: self.scoreDict[avId] += 10 * (self.REWARDMOD * 0.25) - self.scoreDict[someAvId] += 10 * (self.REWARDMOD * 0.75 / float(len(self.scoreDict.keys()))) + self.scoreDict[someAvId] += 10 * (self.REWARDMOD * 0.75 / float(len(list(self.scoreDict.keys())))) self.sendUpdate('incrementScore', [avId, newSpot, timestamp]) @@ -380,7 +380,7 @@ def gameOver(self): DistributedMinigameAI.gameOver(self) trackingString = 'MiniGame Stats : Diving Game' trackingString += '\nDistrict:%s' % self.getSafezoneId() - for avId in self.scoreTracking.keys(): + for avId in list(self.scoreTracking.keys()): trackingString = trackingString + '\navId:%s fishHits:%s crabHits:%s treasureCatches:%s treasureDrops:%s treasureRecoveries:%s Score: %s' % (avId, self.scoreTracking[avId][0], self.scoreTracking[avId][1], @@ -408,7 +408,7 @@ def enterSwimming(self): def timerExpired(self, task): self.notify.debug('timer expired') - for avId in self.scoreDict.keys(): + for avId in list(self.scoreDict.keys()): if self.scoreDict[avId] < 5: self.scoreDict[avId] = 5 @@ -416,12 +416,12 @@ def timerExpired(self, task): return Task.done def exitSwimming(self): - for i in xrange(DivingGameGlobals.NUM_SPAWNERS): + for i in range(DivingGameGlobals.NUM_SPAWNERS): self.spawnings[i].pause() def enterCleanup(self): self.notify.debug('enterCleanup') - for i in xrange(DivingGameGlobals.NUM_SPAWNERS): + for i in range(DivingGameGlobals.NUM_SPAWNERS): self.spawnings[i].finish() del self.spawnings @@ -457,7 +457,7 @@ def spawnFish(self, spawnerId): timestamp = globalClockDelta.getFrameNetworkTime() props = self.proportion[spawnerId] num = random.random() - for i in xrange(len(props)): + for i in range(len(props)): prop = props[i] low = prop[0] high = prop[1] diff --git a/toontown/minigame/DistributedIceGame.py b/toontown/minigame/DistributedIceGame.py index 0f1cd4395..d7031a04e 100644 --- a/toontown/minigame/DistributedIceGame.py +++ b/toontown/minigame/DistributedIceGame.py @@ -128,7 +128,7 @@ def load(self): self.setupForceArrow(avId) index += 1 - for index in xrange(len(self.avIdList), 4): + for index in range(len(self.avIdList), 4): self.setupTire(-index, index) self.setupForceArrow(-index) @@ -173,7 +173,7 @@ def load(self): self.treasureGrabSound = loader.loadSfx('phase_4/audio/sfx/MG_sfx_vine_game_bananas.ogg') self.penaltyGrabSound = loader.loadSfx('phase_4/audio/sfx/MG_cannon_fire_alt.ogg') self.tireSounds = [] - for tireIndex in xrange(4): + for tireIndex in range(4): tireHit = loader.loadSfx('phase_4/audio/sfx/Golf_Hit_Barrier_1.ogg') wallHit = loader.loadSfx('phase_4/audio/sfx/MG_maze_pickup.ogg') obstacleHit = loader.loadSfx('phase_4/audio/sfx/Golf_Hit_Barrier_2.ogg') @@ -192,7 +192,7 @@ def unload(self): del self.music self.gameBoard.removeNode() del self.gameBoard - for forceArrow in self.forceArrowDict.values(): + for forceArrow in list(self.forceArrowDict.values()): forceArrow.removeNode() del self.forceArrowDict @@ -252,7 +252,7 @@ def setGameReady(self): self.notify.debug('setGameReady') if DistributedMinigame.DistributedMinigame.setGameReady(self): return - for index in xrange(self.numPlayers): + for index in range(self.numPlayers): avId = self.avIdList[index] toon = self.getAvatar(avId) if toon: @@ -281,7 +281,7 @@ def setGameStart(self, timestamp): self.scores = [0] * self.numPlayers spacing = 0.4 - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): avId = self.avIdList[i] avName = self.getAvatarName(avId) scorePanel = MinigameAvatarScorePanel.MinigameAvatarScorePanel(avId, avName) @@ -378,7 +378,7 @@ def enterMoveTires(self): body.setAngularVel(0, 0, 0) body.setLinearVel(0, 0, 0) - for index in xrange(len(self.allTireInputs)): + for index in range(len(self.allTireInputs)): input = self.allTireInputs[index] avId = self.avIdList[index] body = self.getTireBody(avId) @@ -439,7 +439,7 @@ def compareDistance(x, y): self.scoreCircle.show() self.notify.debug('newScores = %s' % self.newScores) circleStartTime = 0 - for index in xrange(len(sortedByDistance)): + for index in range(len(sortedByDistance)): distance = sortedByDistance[index][1] avId = sortedByDistance[index][0] scorePanelIndex = self.avIdList.index(avId) @@ -493,7 +493,7 @@ def enterFinalResults(self): (lX, bY), (rX, bY))) scorePanelLocs = scorePanelLocs[self.numPlayers - 1] - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): panel = self.scorePanels[i] pos = scorePanelLocs[i] panel.wrtReparentTo(aspect2d) @@ -562,7 +562,7 @@ def setupForceArrow(self, avId): self.forceArrowDict[avId] = arrow def hideForceArrows(self): - for forceArrow in self.forceArrowDict.values(): + for forceArrow in list(self.forceArrowDict.values()): forceArrow.hide() def showForceArrows(self, realPlayersOnly = True): @@ -791,15 +791,15 @@ def setTireInputs(self, tireInputs): self.gameFSM.request('moveTires') def enableAllTireBodies(self): - for avId in self.tireDict.keys(): + for avId in list(self.tireDict.keys()): self.tireDict[avId]['tireBody'].enable() def disableAllTireBodies(self): - for avId in self.tireDict.keys(): + for avId in list(self.tireDict.keys()): self.tireDict[avId]['tireBody'].disable() def areAllTiresDisabled(self): - for avId in self.tireDict.keys(): + for avId in list(self.tireDict.keys()): if self.tireDict[avId]['tireBody'].isEnabled(): return False @@ -814,13 +814,13 @@ def __moveTiresTask(self, task): def sendTirePositions(self): tirePositions = [] - for index in xrange(len(self.avIdList)): + for index in range(len(self.avIdList)): avId = self.avIdList[index] tire = self.getTireBody(avId) pos = Point3(tire.getPosition()) tirePositions.append([pos[0], pos[1], pos[2]]) - for index in xrange(len(self.avIdList), 4): + for index in range(len(self.avIdList), 4): avId = -index tire = self.getTireBody(avId) pos = Point3(tire.getPosition()) @@ -831,7 +831,7 @@ def sendTirePositions(self): def setFinalPositions(self, finalPos): if not self.hasLocalToon: return - for index in xrange(len(self.avIdList)): + for index in range(len(self.avIdList)): avId = self.avIdList[index] tire = self.getTireBody(avId) np = self.getTireNp(avId) @@ -839,7 +839,7 @@ def setFinalPositions(self, finalPos): tire.setPosition(pos[0], pos[1], pos[2]) np.setPos(pos[0], pos[1], pos[2]) - for index in xrange(len(self.avIdList), 4): + for index in range(len(self.avIdList), 4): avId = -index tire = self.getTireBody(avId) np = self.getTireNp(avId) @@ -874,7 +874,7 @@ def setNewState(self, state): self.gameFSM.request(state) def putAllTiresInStartingPositions(self): - for index in xrange(len(self.avIdList)): + for index in range(len(self.avIdList)): avId = self.avIdList[index] np = self.tireDict[avId]['tireNodePath'] np.setPos(IceGameGlobals.StartingPositions[index]) @@ -885,7 +885,7 @@ def putAllTiresInStartingPositions(self): body.setPosition(IceGameGlobals.StartingPositions[index]) body.setQuaternion(quat) - for index in xrange(len(self.avIdList), 4): + for index in range(len(self.avIdList), 4): avId = -index np = self.tireDict[avId]['tireNodePath'] np.setPos(IceGameGlobals.StartingPositions[index]) @@ -1039,7 +1039,7 @@ def postStep(self): DistributedIceWorld.DistributedIceWorld.postStep(self) if not self.colCount: return - for count in xrange(self.colCount): + for count in range(self.colCount): c0, c1 = self.getOrderedContacts(count) if c1 in self.tireCollideIds: tireIndex = self.tireCollideIds.index(c1) diff --git a/toontown/minigame/DistributedIceGameAI.py b/toontown/minigame/DistributedIceGameAI.py index 0bee186f6..e2c19b2c8 100644 --- a/toontown/minigame/DistributedIceGameAI.py +++ b/toontown/minigame/DistributedIceGameAI.py @@ -128,11 +128,11 @@ def enterProcessEndingPositions(self): Point3(0, 0, 0), Point3(0, 0, 0)] divisor = 0 - for avId in self.avatarEndingPositions.keys(): + for avId in list(self.avatarEndingPositions.keys()): divisor += 1 oneClientEndingPositions = self.avatarEndingPositions[avId] avIndex = self.avIdList.index(avId) - for index in xrange(len(oneClientEndingPositions)): + for index in range(len(oneClientEndingPositions)): pos = oneClientEndingPositions[index] averagePos[index] += Point3(pos[0], pos[1], pos[2]) self.notify.debug('index = %d averagePos = %s' % (index, averagePos)) @@ -179,7 +179,7 @@ def compareDistance(x, y): sortedByDistance.sort(cmp=compareDistance) self.scoresAsList = [] totalPointsAdded = 0 - for index in xrange(len(self.avIdList)): + for index in range(len(self.avIdList)): pos = Point3(*self.finalEndingPositions[index]) pos.setZ(0) length = pos.length() @@ -188,7 +188,7 @@ def compareDistance(x, y): self.notify.debug('length = %s points=%s avId=%d' % (length, points, avId)) avId = self.avIdList[index] bonusIndex = 0 - for sortIndex in xrange(len(sortedByDistance)): + for sortIndex in range(len(sortedByDistance)): if sortedByDistance[sortIndex][0] == avId: bonusIndex = sortIndex @@ -241,7 +241,7 @@ def __doneShowingScores(self, task): def waitClientsChoicesTimeout(self, task): self.notify.debug('waitClientsChoicesTimeout: did not hear from all clients') - for avId in self.avatarChoices.keys(): + for avId in list(self.avatarChoices.keys()): if self.avatarChoices[avId] == (-1, 0): self.avatarChoices[avId] = (0, 0) @@ -272,7 +272,7 @@ def checkChoice(self, avId, force, direction): return (retForce, retDir) def allAvatarsChosen(self): - for avId in self.avatarChoices.keys(): + for avId in list(self.avatarChoices.keys()): choice = self.avatarChoices[avId] if choice[0] == -1 and not self.stateDict[avId] == DistributedMinigameAI.EXITED: return False @@ -349,7 +349,7 @@ def claimPenalty(self, penaltyNum): def checkScores(self): self.scoresAsList = [] - for index in xrange(len(self.avIdList)): + for index in range(len(self.avIdList)): avId = self.avIdList[index] if self.scoreDict[avId] < 0: self.scoreDict[avId] = 1 diff --git a/toontown/minigame/DistributedMazeGame.py b/toontown/minigame/DistributedMazeGame.py index 992b0503e..5f83a98ae 100644 --- a/toontown/minigame/DistributedMazeGame.py +++ b/toontown/minigame/DistributedMazeGame.py @@ -641,11 +641,11 @@ def onstage(self): camera.setPos(self.camOffset) self.__spawnCameraTask() self.toonRNGs = [] - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): self.toonRNGs.append(RandomNumGen.RandomNumGen(self.randomNumGen)) self.treasures = [] - for i in xrange(self.maze.numTreasures): + for i in range(self.maze.numTreasures): self.treasures.append(MazeTreasure.MazeTreasure(self.treasureModel, self.maze.treasurePosList[i], i, self.doId)) self.__loadSuits() @@ -654,12 +654,12 @@ def onstage(self): self.sndTable = {'hitBySuit': [None] * self.numPlayers, 'falling': [None] * self.numPlayers} - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): self.sndTable['hitBySuit'][i] = base.loader.loadSfx('phase_4/audio/sfx/MG_Tag_C.ogg') self.sndTable['falling'][i] = base.loader.loadSfx('phase_4/audio/sfx/MG_cannon_whizz.ogg') self.grabSounds = [] - for i in xrange(5): + for i in range(5): self.grabSounds.append(base.loader.loadSfx('phase_4/audio/sfx/MG_maze_pickup.ogg')) self.grabSoundIndex = 0 @@ -682,7 +682,7 @@ def offstage(self): if self.introTrack.isPlaying(): self.introTrack.finish() del self.introTrack - for avId in self.toonHitTracks.keys(): + for avId in list(self.toonHitTracks.keys()): track = self.toonHitTracks[avId] if track.isPlaying(): track.finish() @@ -766,7 +766,7 @@ def exitOff(self): def enterPlay(self): self.notify.debug('enterPlay') - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): avId = self.avIdList[i] avName = self.getAvatarName(avId) scorePanel = MinigameAvatarScorePanel.MinigameAvatarScorePanel(avId, avName) @@ -844,7 +844,7 @@ def hitBySuit(self, avId, timestamp): if self.gameFSM.getCurrentState().getName() not in ['play', 'showScores']: self.notify.warning('ignoring msg: av %s hit by suit' % avId) return - self.notify.debug('avatar ' + `avId` + ' hit by a suit') + self.notify.debug('avatar ' + repr(avId) + ' hit by a suit') if avId != self.localAvId: self.__showToonHitBySuit(avId, timestamp) @@ -859,7 +859,7 @@ def __showToonHitBySuit(self, avId, timestamp): oldTrack.finish() toon.setPos(curPos) toon.setZ(self.TOON_Z) - parentNode = render.attachNewNode('mazeFlyToonParent-' + `avId`) + parentNode = render.attachNewNode('mazeFlyToonParent-' + repr(avId)) parentNode.setPos(toon.getPos()) toon.reparentTo(parentNode) toon.setPos(0,0,0) @@ -900,7 +900,7 @@ def camTask(task, zenith = zenith, flyNode = toon, startCamPos = startCamPos, ca camera.setPos(startCamPos + camOffset*u) camera.lookAt(toon) return Task.cont - camTaskName = 'mazeToonFlyCam-' + `avId` + camTaskName = 'mazeToonFlyCam-' + repr(avId) taskMgr.add(camTask, camTaskName, priority=20) def cleanupCamTask(self = self, toon = toon, camTaskName = camTaskName, startCamPos = startCamPos): taskMgr.remove(camTaskName) @@ -1081,9 +1081,9 @@ def __loadSuits(self): fasterTable = self.fasterSuitPeriodsCurve fasterPeriods = fasterTable[safeZone][self.numSuits] suitPeriods = slowerPeriods + fasterPeriods - self.notify.debug('suit periods: ' + `suitPeriods`) + self.notify.debug('suit periods: ' + repr(suitPeriods)) self.randomNumGen.shuffle(suitPeriods) - for i in xrange(self.numSuits): + for i in range(self.numSuits): self.suits.append(MazeSuit(i, self.maze, self.randomNumGen, suitPeriods[i], self.getDifficulty())) def __unloadSuits(self): @@ -1111,14 +1111,14 @@ def __updateSuitsTask(self, task): curT = globalClock.getFrameTime() - self.gameStartTime curTic = int(curT * float(MazeGameGlobals.SUIT_TIC_FREQ)) suitUpdates = [] - for i in xrange(len(self.suits)): + for i in range(len(self.suits)): updateTics = self.suits[i].getThinkTimestampTics(curTic) - suitUpdates.extend(zip(updateTics, [i] * len(updateTics))) + suitUpdates.extend(list(zip(updateTics, [i] * len(updateTics)))) suitUpdates.sort(lambda a, b: a[0] - b[0]) if len(suitUpdates) > 0: curTic = 0 - for i in xrange(len(suitUpdates)): + for i in range(len(suitUpdates)): update = suitUpdates[i] tic = update[0] suitIndex = update[1] @@ -1133,10 +1133,10 @@ def __updateSuitsTask(self, task): j += 1 unwalkables = [] - for si in xrange(suitIndex): + for si in range(suitIndex): unwalkables.extend(self.suits[si].occupiedTiles) - for si in xrange(suitIndex + 1, len(self.suits)): + for si in range(suitIndex + 1, len(self.suits)): unwalkables.extend(self.suits[si].occupiedTiles) suit.think(curTic, curT, unwalkables) @@ -1161,7 +1161,7 @@ def enterShowScores(self): (lX, bY), (rX, bY))) scorePanelLocs = scorePanelLocs[self.numPlayers - 1] - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): panel = self.scorePanels[i] pos = scorePanelLocs[i] panel.wrtReparentTo(aspect2d) diff --git a/toontown/minigame/DistributedMazeGameAI.py b/toontown/minigame/DistributedMazeGameAI.py index 95f0363f7..b02f941a8 100644 --- a/toontown/minigame/DistributedMazeGameAI.py +++ b/toontown/minigame/DistributedMazeGameAI.py @@ -35,7 +35,7 @@ def setGameReady(self): self.numTreasures = len(mData['treasurePosList']) self.numTreasuresTaken = 0 self.takenTable = [0] * self.numTreasures - for avId in self.scoreDict.keys(): + for avId in list(self.scoreDict.keys()): self.scoreDict[avId] = 0 def setGameStart(self, timestamp): @@ -109,11 +109,11 @@ def enterWaitShowScores(self): def __doneShowingScores(self, task): self.notify.debug('doneShowingScores') - for key in self.scoreDict.keys(): + for key in list(self.scoreDict.keys()): self.scoreDict[key] = max(1, self.scoreDict[key] / 12) if self.numTreasuresTaken >= self.numTreasures: - for key in self.scoreDict.keys(): + for key in list(self.scoreDict.keys()): self.scoreDict[key] += 8 self.gameOver() diff --git a/toontown/minigame/DistributedMinigame.py b/toontown/minigame/DistributedMinigame.py index 8b6c89928..0a1da26b1 100644 --- a/toontown/minigame/DistributedMinigame.py +++ b/toontown/minigame/DistributedMinigame.py @@ -101,7 +101,7 @@ def announceGenerate(self): return self.notify.debug('BASE: handleAnnounceGenerate: send setAvatarJoined') if base.randomMinigameNetworkPlugPull and random.random() < 1.0 / 25: - print '*** DOING RANDOM MINIGAME NETWORK-PLUG-PULL BEFORE SENDING setAvatarJoined ***' + print('*** DOING RANDOM MINIGAME NETWORK-PLUG-PULL BEFORE SENDING setAvatarJoined ***') base.cr.pullNetworkPlug() self.sendUpdate('setAvatarJoined', []) self.normalExit = 1 @@ -176,17 +176,17 @@ def calcMaxDuration(self = self): taskMgr.doMethodLater(self.randomNetPlugPullDelay, self.doRandomNetworkPlugPull, self.uniqueName('random-netplugpull')) def doRandomAbort(self, task): - print '*** DOING RANDOM MINIGAME ABORT AFTER %.2f SECONDS ***' % self.randomAbortDelay + print('*** DOING RANDOM MINIGAME ABORT AFTER %.2f SECONDS ***' % self.randomAbortDelay) self.d_requestExit() return Task.done def doRandomDisconnect(self, task): - print '*** DOING RANDOM MINIGAME DISCONNECT AFTER %.2f SECONDS ***' % self.randomDisconnectDelay + print('*** DOING RANDOM MINIGAME DISCONNECT AFTER %.2f SECONDS ***' % self.randomDisconnectDelay) self.sendUpdate('setGameReady') return Task.done def doRandomNetworkPlugPull(self, task): - print '*** DOING RANDOM MINIGAME NETWORK-PLUG-PULL AFTER %.2f SECONDS ***' % self.randomNetPlugPullDelay + print('*** DOING RANDOM MINIGAME NETWORK-PLUG-PULL AFTER %.2f SECONDS ***' % self.randomNetPlugPullDelay) base.cr.pullNetworkPlug() return Task.done @@ -440,7 +440,7 @@ def setStartingVotes(self, startingVotesArray): if not len(startingVotesArray) == len(self.avIdList): self.notify.error('length does not match, startingVotes=%s, avIdList=%s' % (startingVotesArray, self.avIdList)) return - for index in xrange(len(self.avIdList)): + for index in range(len(self.avIdList)): avId = self.avIdList[index] self.startingVotes[avId] = startingVotesArray[index] diff --git a/toontown/minigame/DistributedMinigameAI.py b/toontown/minigame/DistributedMinigameAI.py index 388155d8d..f83b226d2 100644 --- a/toontown/minigame/DistributedMinigameAI.py +++ b/toontown/minigame/DistributedMinigameAI.py @@ -6,12 +6,12 @@ from direct.fsm import State from toontown.shtiker import PurchaseManagerAI from toontown.shtiker import NewbiePurchaseManagerAI -import MinigameCreatorAI +from . import MinigameCreatorAI from direct.task import Task import random -import MinigameGlobals +from . import MinigameGlobals from toontown.toonbase import ToonPythonUtil as PythonUtil -import TravelGameGlobals +from . import TravelGameGlobals from toontown.toonbase import ToontownGlobals EXITED = 0 EXPECTED = 1 @@ -237,7 +237,7 @@ def handleTimeout(avIds, self = self): self.setGameAbort() self.__barrier = ToonBarrier('waitClientsReady', self.uniqueName('waitClientsReady'), self.avIdList, READY_TIMEOUT, allAvatarsReady, handleTimeout) - for avId in self.stateDict.keys(): + for avId in list(self.stateDict.keys()): if self.stateDict[avId] == READY: self.__barrier.clear(avId) @@ -280,7 +280,7 @@ def handleTimeout(avIds, self = self): self.frameworkFSM.request('frameworkCleanup') self.__barrier = ToonBarrier('waitClientsExit', self.uniqueName('waitClientsExit'), self.avIdList, EXIT_TIMEOUT, allAvatarsExited, handleTimeout) - for avId in self.stateDict.keys(): + for avId in list(self.stateDict.keys()): if self.stateDict[avId] == EXITED: self.__barrier.clear(avId) @@ -354,7 +354,7 @@ def handleMetagamePurchaseManager(self, scoreList): if self.metagameRound < TravelGameGlobals.FinalMetagameRoundIndex: newRound = self.metagameRound if not self.minigameId == ToontownGlobals.TravelGameId: - for index in xrange(len(scoreList)): + for index in range(len(scoreList)): votesArray[index] += scoreList[index] self.notify.debug('votesArray = %s' % votesArray) @@ -384,7 +384,7 @@ def handleMetagamePurchaseManager(self, scoreList): else: self.notify.debug('last minigame, handling newbies') if ToontownGlobals.JELLYBEAN_TROLLEY_HOLIDAY in simbase.air.holidayManager.currentHolidays or ToontownGlobals.JELLYBEAN_TROLLEY_HOLIDAY_MONTH in simbase.air.holidayManager.currentHolidays: - votesArray = map(lambda x: MinigameGlobals.JellybeanTrolleyHolidayScoreMultiplier * x, votesArray) + votesArray = [MinigameGlobals.JellybeanTrolleyHolidayScoreMultiplier * x for x in votesArray] for id in self.newbieIdList: pm = NewbiePurchaseManagerAI.NewbiePurchaseManagerAI(self.air, id, self.avIdList, scoreList, self.minigameId, self.trolleyZone) MinigameCreatorAI.acquireMinigameZone(self.zoneId) diff --git a/toontown/minigame/DistributedPairingGame.py b/toontown/minigame/DistributedPairingGame.py index bfd62dc21..d67804cc6 100644 --- a/toontown/minigame/DistributedPairingGame.py +++ b/toontown/minigame/DistributedPairingGame.py @@ -87,7 +87,7 @@ def load(self): if not testCard > -1: self.yCardInc *= 1.25 self.cards = [] - for index in xrange(len(self.deck.cards)): + for index in range(len(self.deck.cards)): cardValue = self.deck.cards[index] oneCard = PairingGameCard.PairingGameCard(cardValue) oneCard.load() @@ -101,7 +101,7 @@ def load(self): oneCard.turnDown(doInterval=False) self.cards.append(oneCard) - self.bonusTraversal = range(len(self.cards)) + self.bonusTraversal = list(range(len(self.cards))) self.bonusGlow = render.attachNewNode('bonusGlow') sign = loader.loadModel('phase_4/models/minigames/garden_sign_memory') sign.find('**/sign1').removeNode() @@ -123,7 +123,7 @@ def load(self): self.matchSfx = base.loader.loadSfx('phase_4/audio/sfx/MG_pairing_match.ogg') self.matchWithBonusSfx = base.loader.loadSfx('phase_4/audio/sfx/MG_pairing_match_bonus_both.ogg') self.signalSfx = [] - for i in xrange(4): + for i in range(4): self.signalSfx.append(base.loader.loadSfx('phase_4/audio/sfx/MG_pairing_jumping_signal.ogg')) self.bonusMovesSfx = base.loader.loadSfx('phase_4/audio/sfx/MG_pairing_bonus_moves.ogg') @@ -152,7 +152,7 @@ def unload(self): del self.music del self.matchSfx del self.matchWithBonusSfx - for i in xrange(4): + for i in range(4): del self.signalSfx[0] self.signalSfx = [] @@ -192,7 +192,7 @@ def setGameReady(self): self.notify.debug('setGameReady') if DistributedMinigame.setGameReady(self): return - for index in xrange(self.numPlayers): + for index in range(self.numPlayers): avId = self.avIdList[index] toon = self.getAvatar(avId) if toon: @@ -297,7 +297,7 @@ def __doPairingGameCollisions(self, oldPos, newPos): return newPos def getDeckOrderFromValue(self, value): - for index in xrange(len(self.cards)): + for index in range(len(self.cards)): if self.cards[index].value == value: return index @@ -523,10 +523,10 @@ def calcBonusTraversal(self): halfRow = self.cardsPerRow / 2 if self.cardsPerRow % 2: halfRow += 1 - for i in xrange(halfRow): - for j in xrange(2): + for i in range(halfRow): + for j in range(2): col = i + j * halfRow - for row in xrange(self.cardsPerCol): + for row in range(self.cardsPerCol): card = self.getDeckOrderIndex(row, col) if card > -1: self.bonusTraversal.append(card) diff --git a/toontown/minigame/DistributedPairingGameAI.py b/toontown/minigame/DistributedPairingGameAI.py index 84d3c702e..62245b916 100644 --- a/toontown/minigame/DistributedPairingGameAI.py +++ b/toontown/minigame/DistributedPairingGameAI.py @@ -53,7 +53,7 @@ def setGameReady(self): self.faceUpDict[avId] = [] self.deck = PairingGameGlobals.createDeck(self.deckSeed, self.numPlayers) - for index in xrange(len(self.deck.cards)): + for index in range(len(self.deck.cards)): cardValue = self.deck.cards[index] oneCard = PlayingCardBase(cardValue) self.cards.append(oneCard) @@ -136,7 +136,7 @@ def getDeckSeed(self): def isCardFaceUp(self, deckOrderIndex): retval = False - for key in self.faceUpDict.keys(): + for key in list(self.faceUpDict.keys()): if deckOrderIndex in self.faceUpDict[key]: retval = True break @@ -148,12 +148,12 @@ def isCardFaceDown(self, deckOrderIndex): def checkForMatch(self): faceUpList = [] - for oneToonFaceUpList in self.faceUpDict.values(): + for oneToonFaceUpList in list(self.faceUpDict.values()): faceUpList += oneToonFaceUpList - for i in xrange(len(faceUpList)): + for i in range(len(faceUpList)): cardA = faceUpList[i] - for j in xrange(i + 1, len(faceUpList)): + for j in range(i + 1, len(faceUpList)): cardB = faceUpList[j] if self.cards[cardA].rank == self.cards[cardB].rank: return (cardA, cardB) @@ -162,7 +162,7 @@ def checkForMatch(self): def handleMatch(self, cardA, cardB): self.notify.debug('we got a match %d %d' % (cardA, cardB)) - for key in self.faceUpDict.keys(): + for key in list(self.faceUpDict.keys()): if cardA in self.faceUpDict[key]: self.faceUpDict[key].remove(cardA) if cardB in self.faceUpDict[key]: @@ -173,7 +173,7 @@ def handleMatch(self, cardA, cardB): def turnDownCard(self, cardA): self.notify.debug('turning down card %d' % cardA) - for key in self.faceUpDict.keys(): + for key in list(self.faceUpDict.keys()): if cardA in self.faceUpDict[key]: self.faceUpDict[key].remove(cardA) diff --git a/toontown/minigame/DistributedPatternGame.py b/toontown/minigame/DistributedPatternGame.py index 16d92dac8..833bb4439 100644 --- a/toontown/minigame/DistributedPatternGame.py +++ b/toontown/minigame/DistributedPatternGame.py @@ -6,9 +6,9 @@ import random import string -import ArrowKeys -from DistributedMinigame import * -import PatternGameGlobals +from . import ArrowKeys +from .DistributedMinigame import * +from . import PatternGameGlobals from toontown.chat.ChatGlobals import * from toontown.nametag.NametagGlobals import * from toontown.toon import NPCToons @@ -99,22 +99,22 @@ def load(self): minnieX = matchingGameGui.find('**/minnieX') minnieCircle = matchingGameGui.find('**/minnieCircle') self.arrows = [None] * 5 - for x in xrange(0, 5): + for x in range(0, 5): self.arrows[x] = minnieArrow.copyTo(hidden) self.arrows[x].hide() self.xs = [None] * 5 - for x in xrange(0, 5): + for x in range(0, 5): self.xs[x] = minnieX.copyTo(hidden) self.xs[x].hide() self.statusBalls = [] self.totalMoves = PatternGameGlobals.INITIAL_ROUND_LENGTH + PatternGameGlobals.ROUND_LENGTH_INCREMENT * (PatternGameGlobals.NUM_ROUNDS - 1) - for x in xrange(0, 4): + for x in range(0, 4): self.statusBalls.append([None] * self.totalMoves) - for x in xrange(0, 4): - for y in xrange(0, self.totalMoves): + for x in range(0, 4): + for y in range(0, self.totalMoves): self.statusBalls[x][y] = minnieCircle.copyTo(hidden) self.statusBalls[x][y].hide() @@ -135,7 +135,7 @@ def load(self): self.animPlayRates = [] animPlayRate = 1.4 animPlayRateMult = 1.06 - for i in xrange(PatternGameGlobals.NUM_ROUNDS): + for i in range(PatternGameGlobals.NUM_ROUNDS): self.animPlayRates.append(animPlayRate) animPlayRate *= animPlayRateMult @@ -156,7 +156,7 @@ def unload(self): del self.waitingText self.roundText.destroy() del self.roundText - for x in self.arrowDict.values(): + for x in list(self.arrowDict.values()): x[0].removeNode() x[1].removeNode() if len(x) == 3: @@ -223,7 +223,7 @@ def onstage(self): lt.startLookAround() self.arrowDict['lt'] = [self.arrows.pop(), self.xs.pop(), self.statusBalls.pop()] jj = self.lt.nametag3d - for k in xrange(0, 2): + for k in range(0, 2): self.arrowDict['lt'][k].setBillboardAxis() self.arrowDict['lt'][k].setBin('fixed', 100) self.arrowDict['lt'][k].reparentTo(self.lt.nametag3d) @@ -243,7 +243,7 @@ def onstage(self): self.toon.loop('neutral') self.toon.nametag.manage(base.marginManager) self.arrowDict['m'] = [self.arrows.pop(), self.xs.pop()] - for k in xrange(0, 2): + for k in range(0, 2): self.arrowDict['m'][k].setBillboardAxis() self.arrowDict['m'][k].setBin('fixed', 100) self.arrowDict['m'][k].setColor(self.arrowColor) @@ -290,7 +290,7 @@ def setGameReady(self): if toon: self.arrowDict[avId] = [self.arrows.pop(), self.xs.pop(), self.statusBalls.pop()] jj = toon.nametag3d - for k in xrange(0, 2): + for k in range(0, 2): self.arrowDict[avId][k].setBillboardAxis() self.arrowDict[avId][k].setBin('fixed', 100) self.arrowDict[avId][k].reparentTo(jj) @@ -444,7 +444,7 @@ def returnCelebrationIntervals(self, turnOn): return Parallel(ri) def formatStatusBalls(self, sb, jj): - for x in xrange(0, self.totalMoves): + for x in range(0, self.totalMoves): sb[x].setBillboardAxis() sb[x].setBin('fixed', 100) sb[x].reparentTo(jj) @@ -454,13 +454,13 @@ def formatStatusBalls(self, sb, jj): def showStatusBalls(self, toonID): sb = self.arrowDict[toonID][2] - for x in xrange(0, len(self.__serverPattern)): + for x in range(0, len(self.__serverPattern)): sb[x].setColor(1, 1, 1, 1) sb[x].show() def hideStatusBalls(self, toonID): sb = self.arrowDict[toonID][2] - for x in xrange(0, len(sb)): + for x in range(0, len(sb)): sb[x].hide() def colorStatusBall(self, toonID, which, good): @@ -694,7 +694,7 @@ def setPlayerPatterns(self, pattern1, pattern2, pattern3, pattern4, fastestAvId) pattern2, pattern3, pattern4] - for i in xrange(len(self.avIdList)): + for i in range(len(self.avIdList)): self.playerPatterns[self.avIdList[i]] = patterns[i] self.gameFSM.request('playBackPatterns') @@ -781,7 +781,7 @@ def exitCheckGameOver(self): def enterCleanup(self): self.notify.debug('enterCleanup') - for track in self.animTracks.values(): + for track in list(self.animTracks.values()): if track and track.isPlaying(): track.pause() diff --git a/toontown/minigame/DistributedPatternGameAI.py b/toontown/minigame/DistributedPatternGameAI.py index f46d9dc19..facc8a0c6 100644 --- a/toontown/minigame/DistributedPatternGameAI.py +++ b/toontown/minigame/DistributedPatternGameAI.py @@ -98,7 +98,7 @@ def enterGeneratePattern(self): self.round += 1 targetLen = PatternGameGlobals.INITIAL_ROUND_LENGTH + PatternGameGlobals.ROUND_LENGTH_INCREMENT * (self.round - 1) count = targetLen - len(self.pattern) - for i in xrange(0, count): + for i in range(0, count): self.pattern.append(random.randint(0, 3)) self.gameFSM.request('waitForResults') @@ -161,13 +161,13 @@ def __acceptPlayerPattern(self, avId, pattern, totalTime): def __gotAllPatterns(self): patterns = [[]] * 4 - for i in xrange(0, len(self.results)): + for i in range(0, len(self.results)): patterns[i] = self.results[i] if patterns[i] is None: patterns[i] = [] self.sendUpdate('setPlayerPatterns', patterns + [self.fastestAvId]) - for i in xrange(0, self.numPlayers): + for i in range(0, self.numPlayers): avId = self.avIdList[i] if not self.results[i] == self.pattern: self.perfectResults[avId] = 0 diff --git a/toontown/minigame/DistributedPhotoGame.py b/toontown/minigame/DistributedPhotoGame.py index f2eadc00a..60e0d9217 100644 --- a/toontown/minigame/DistributedPhotoGame.py +++ b/toontown/minigame/DistributedPhotoGame.py @@ -294,9 +294,9 @@ def __setupCollisions(self): self.traverser = CollisionTraverser('traverser name') self.rayArray = [] vRange = (GOODROWS - BADROWS) / 2 - for row in xrange(-(GOODROWS / 2), GOODROWS / 2 + 1): - for column in xrange(-(GOODROWS / 2), GOODROWS / 2 + 1): - goodRange = range(-((GOODROWS - BADROWS) / 2), (GOODROWS - BADROWS) / 2 + 1) + for row in range(-(GOODROWS / 2), GOODROWS / 2 + 1): + for column in range(-(GOODROWS / 2), GOODROWS / 2 + 1): + goodRange = list(range(-((GOODROWS - BADROWS) / 2), (GOODROWS - BADROWS) / 2 + 1)) rayQuality = 'g' if row not in goodRange or column not in goodRange: rayQuality = 'l' @@ -410,7 +410,7 @@ def __testCollisions(self): distDict = {} hitDict = {} centerDict = {} - for i in xrange(self.queue.getNumEntries()): + for i in range(self.queue.getNumEntries()): entry = self.queue.getEntry(i) object = None objectIndex = None @@ -727,7 +727,7 @@ def __setupSubjects(self): self.scenery.append(self.photoRoot) random.seed(time.time()) namegen = NameGenerator.NameGenerator() - for pathIndex in xrange(len(self.data['PATHS'])): + for pathIndex in range(len(self.data['PATHS'])): path = self.data['PATHS'][pathIndex] subject = Toon.Toon() gender = random.choice(['m', 'f']) @@ -987,7 +987,7 @@ def generateAssignmentPanels(self): def printAD(self): for assignment in self.assignmentDataDict: data = self.assignmentDataDict[assignment] - print 'Key:%s\nData:%s\n' % (str(assignment), data) + print('Key:%s\nData:%s\n' % (str(assignment), data)) def updateScorePanel(self): teamScore = 0.0 @@ -1015,7 +1015,7 @@ def updateAssignmentPanels(self): starList = self.starDict[data[1]] starParent = self.starParentDict[data[1]] score = int(data[2]) - for index in xrange(NUMSTARS): + for index in range(NUMSTARS): if index < score: starList[index].show() else: @@ -1054,7 +1054,7 @@ def makeAssignmentPanel(self, assignment): starImage = loader.loadModel('phase_4/models/minigames/photogame_star') starParent = model.attachNewNode('star parent') self.starDict[model] = [] - for index in xrange(NUMSTARS): + for index in range(NUMSTARS): star = DirectLabel(parent=starParent, image=starImage, image_color=(1, 1, 1, 1), image_scale=Point3(STARSIZE, 0.0, STARSIZE), relief=None) star.setX(STARSIZE * -0.5 * float(NUMSTARS) + float(index + 0.5) * STARSIZE) star.setZ(-0.05 - STARSIZE) @@ -1597,7 +1597,7 @@ def destructDL(self): def makeDictionaries(self, dnaStore): self.nodeList = [] - for i in xrange(dnaStore.getNumDNAVisGroups()): + for i in range(dnaStore.getNumDNAVisGroups()): groupFullName = dnaStore.getDNAVisGroupName(i) groupName = base.cr.hoodMgr.extractGroupName(groupFullName) groupNode = self.scene.find('**/' + groupFullName) @@ -1622,7 +1622,7 @@ def createAnimatedProps(self, nodeList): for i in nodeList: animPropNodes = i.findAllMatches('**/animated_prop_*') numAnimPropNodes = animPropNodes.getNumPaths() - for j in xrange(numAnimPropNodes): + for j in range(numAnimPropNodes): animPropNode = animPropNodes.getPath(j) if animPropNode.getName().startswith('animated_prop_generic'): className = 'GenericAnimatedProp' @@ -1637,7 +1637,7 @@ def createAnimatedProps(self, nodeList): interactivePropNodes = i.findAllMatches('**/interactive_prop_*') numInteractivePropNodes = interactivePropNodes.getNumPaths() - for j in xrange(numInteractivePropNodes): + for j in range(numInteractivePropNodes): interactivePropNode = interactivePropNodes.getPath(j) className = 'GenericAnimatedProp' symbols = {} diff --git a/toontown/minigame/DistributedPhotoGameAI.py b/toontown/minigame/DistributedPhotoGameAI.py index b6b341a37..1849f8761 100644 --- a/toontown/minigame/DistributedPhotoGameAI.py +++ b/toontown/minigame/DistributedPhotoGameAI.py @@ -134,7 +134,7 @@ def newClientPhotoScore(self, subjectIndex, pose, score): self.notify.debug('player used more film than possible') return assignmentIndex = None - for dataIndex in xrange(len(self.assignmentData)): + for dataIndex in range(len(self.assignmentData)): assignment = self.assignmentData[dataIndex] if assignment[0] == subjectIndex and assignment[1] == pose: assignmentIndex = dataIndex diff --git a/toontown/minigame/DistributedRaceGame.py b/toontown/minigame/DistributedRaceGame.py index 8760e02e7..1c9a6c90d 100644 --- a/toontown/minigame/DistributedRaceGame.py +++ b/toontown/minigame/DistributedRaceGame.py @@ -306,7 +306,7 @@ def load(self): self.winSting = base.loader.loadSfx('phase_4/audio/sfx/MG_win.ogg') self.loseSting = base.loader.loadSfx('phase_4/audio/sfx/MG_lose.ogg') self.diceButtonList = [] - for i in xrange(1, 5): + for i in range(1, 5): button = self.dice.find('**/dice_button' + str(i)) button_down = self.dice.find('**/dice_button' + str(i) + '_down') button_ro = self.dice.find('**/dice_button' + str(i) + '_ro') @@ -389,7 +389,7 @@ def setGameReady(self): if DistributedMinigame.setGameReady(self): return self.resetPositions() - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): avId = self.avIdList[i] if self.localAvId == avId: self.localAvLane = i @@ -474,7 +474,7 @@ def localToonWon(self): return 0 def anyAvatarWon(self): - for position in self.avatarPositions.values(): + for position in list(self.avatarPositions.values()): if position >= RaceGameGlobals.NumberToWin: self.notify.debug('anyAvatarWon: Somebody won') return 1 @@ -485,7 +485,7 @@ def anyAvatarWon(self): def showNumbers(self, task): self.notify.debug('showing numbers...') self.diceInstanceList = [] - for i in xrange(len(task.choiceList)): + for i in range(len(task.choiceList)): avId = self.avIdList[i] choice = task.choiceList[i] if choice == 0: @@ -503,7 +503,7 @@ def showNumbers(self, task): def showMatches(self, task): self.notify.debug('showing matches...') - for i in xrange(len(task.choiceList)): + for i in range(len(task.choiceList)): avId = self.avIdList[i] choice = task.choiceList[i] if choice != 0: @@ -533,7 +533,7 @@ def enterMoveAvatars(self, choiceList, positionList, rewardList): self.notify.debug('in enterMoveAvatars:') tasks = [] self.avatarPositionsCopy = self.avatarPositions.copy() - for i in xrange(0, len(choiceList) / self.numPlayers): + for i in range(0, len(choiceList) / self.numPlayers): startIndex = i * self.numPlayers endIndex = startIndex + self.numPlayers self.choiceList = choiceList[startIndex:endIndex] @@ -591,7 +591,7 @@ def walkDone(self, task): def getLongestLerpTime(self, afterFirst): self.notify.debug('afterFirst: ' + str(afterFirst)) longestTime = 0.0 - for i in xrange(len(self.choiceList)): + for i in range(len(self.choiceList)): freq = self.choiceList.count(self.choiceList[i]) if afterFirst or freq == 1: oldPosition = self.avatarPositionsCopy[self.avIdList[i]] @@ -667,10 +667,10 @@ def resetChanceCard(self, task): return Task.done def moveCamera(self): - bestPosIdx = self.avatarPositions.values()[0] + bestPosIdx = list(self.avatarPositions.values())[0] best_lane = 0 cur_lane = 0 - for pos in self.avatarPositions.values(): + for pos in list(self.avatarPositions.values()): if pos > bestPosIdx: bestPosIdx = pos best_lane = cur_lane @@ -721,7 +721,7 @@ def moveAvatars(self, task): self.notify.debug(' choiceList: ' + str(task.choiceList)) self.notify.debug(' positionList: ' + str(task.positionList)) self.notify.debug(' rewardList: ' + str(task.rewardList)) - for i in xrange(len(self.choiceList)): + for i in range(len(self.choiceList)): avId = self.avIdList[i] choice = task.choiceList[i] position = task.positionList[i] @@ -859,7 +859,7 @@ def setChancePositions(self, positions): def setServerChoices(self, choices, positions, rewards): if not self.hasLocalToon: return - for i in xrange(len(positions)): + for i in range(len(positions)): if positions[i] > RaceGameGlobals.NumberToWin: positions[i] = RaceGameGlobals.NumberToWin if positions[i] < 0: diff --git a/toontown/minigame/DistributedRaceGameAI.py b/toontown/minigame/DistributedRaceGameAI.py index 102e11727..cd0908313 100644 --- a/toontown/minigame/DistributedRaceGameAI.py +++ b/toontown/minigame/DistributedRaceGameAI.py @@ -55,7 +55,7 @@ def gameOver(self): DistributedMinigameAI.gameOver(self) def anyAvatarWon(self, positionDict): - for avId, position in positionDict.items(): + for avId, position in list(positionDict.items()): if position >= RaceGameGlobals.NumberToWin: self.notify.debug('anyAvatarWon: Somebody won') return 1 @@ -64,7 +64,7 @@ def anyAvatarWon(self, positionDict): return 0 def allAvatarsChosen(self): - for choice in self.avatarChoices.values(): + for choice in list(self.avatarChoices.values()): if choice == -1: return 0 @@ -123,7 +123,7 @@ def exitWaitClientsChoices(self): def waitClientsChoicesTimeout(self, task): self.notify.debug('waitClientsChoicesTimeout: did not hear from all clients') - for avId in self.avatarChoices.keys(): + for avId in list(self.avatarChoices.keys()): if self.avatarChoices[avId] == -1: self.avatarChoices[avId] = 0 @@ -137,7 +137,7 @@ def enterProcessChoices(self): self.rewardArray = [] for avId in self.avIdList: choice = self.avatarChoices[avId] - freq = self.avatarChoices.values().count(choice) + freq = list(self.avatarChoices.values()).count(choice) self.processChoice(avId, choice, freq) masterList = [] @@ -231,7 +231,7 @@ def oldEnterProcessChoices(self, recurse = 0): choice = self.avatarChoices[avId] reward = -1 if choice != 0: - freq = self.avatarChoices.values().count(choice) + freq = list(self.avatarChoices.values()).count(choice) if recurse or freq == 1: self.avatarPositions[avId] += choice if self.avatarPositions[avId] < 0: diff --git a/toontown/minigame/DistributedRingGame.py b/toontown/minigame/DistributedRingGame.py index e25bd3e37..f54dd494a 100644 --- a/toontown/minigame/DistributedRingGame.py +++ b/toontown/minigame/DistributedRingGame.py @@ -14,6 +14,7 @@ from toontown.minigame import RingTrackGroups from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer +from functools import reduce class DistributedRingGame(DistributedMinigame): UPDATE_ENVIRON_TASK = 'RingGameUpdateEnvironTask' @@ -143,19 +144,19 @@ def onstage(self): render.setFog(self.__fog) self.environNode = render.attachNewNode('environNode') self.environBlocks = [] - for i in xrange(0, 2): + for i in range(0, 2): instance = self.environModel.instanceUnderNode(self.environNode, 'model') y = self.ENVIRON_LENGTH * i instance.setY(y) self.environBlocks.append(instance) - for j in xrange(0, 2): + for j in range(0, 2): instance = self.environModel.instanceUnderNode(self.environNode, 'blocks') x = self.ENVIRON_LENGTH * (j + 1) instance.setY(y) instance.setX(-x) self.environBlocks.append(instance) - for j in xrange(0, 2): + for j in range(0, 2): instance = self.environModel.instanceUnderNode(self.environNode, 'blocks') x = self.ENVIRON_LENGTH * (j + 1) instance.setY(y) @@ -165,7 +166,7 @@ def onstage(self): self.ringNode = render.attachNewNode('ringNode') self.sndTable = {'gotRing': [None] * self.numPlayers, 'missedRing': [None] * self.numPlayers} - for i in xrange(0, self.numPlayers): + for i in range(0, self.numPlayers): self.sndTable['gotRing'][i] = base.loader.loadSfx('phase_4/audio/sfx/ring_get.ogg') self.sndTable['missedRing'][i] = base.loader.loadSfx('phase_4/audio/sfx/ring_miss.ogg') @@ -315,13 +316,13 @@ def __initTallyDisplay(self): self.__tallyTextNode.setFont(ToontownGlobals.getSignFont()) self.__tallyTextNode.setAlign(TextNode.ACenter) self.tallyMarkers = [None] * self.__numRingGroups - for i in xrange(0, self.__numRingGroups): + for i in range(0, self.__numRingGroups): self.__createTallyMarker(i, self.RT_UNKNOWN) return def __destroyTallyDisplay(self): - for i in xrange(0, self.__numRingGroups): + for i in range(0, self.__numRingGroups): self.__deleteTallyMarker(i) del self.tallyMarkers @@ -365,7 +366,7 @@ def __generateRings(self): ToontownGlobals.MinniesMelodyland: [4, 6, 6], ToontownGlobals.TheBrrrgh: [2, 6, 8], ToontownGlobals.DonaldsDreamland: [2, 6, 8]} - for distr in difficultyDistributions.values(): + for distr in list(difficultyDistributions.values()): sum = reduce(lambda x, y: x + y, distr) difficultyPatterns = {ToontownGlobals.ToontownCentral: [[0] * 14 + [1] * 2 + [2] * 0, [0, @@ -531,25 +532,25 @@ def __generateRings(self): numGroupsPerDifficulty = difficultyDistributions[safezone] def patternsAreValid(difficultyPatterns = difficultyPatterns, difficultyDistributions = difficultyDistributions): - for sz in difficultyPatterns.keys(): + for sz in list(difficultyPatterns.keys()): for pattern in difficultyPatterns[sz]: for difficulty in [0, 1, 2]: numGroupsPerDifficulty = difficultyDistributions[sz] if numGroupsPerDifficulty[difficulty] != pattern.count(difficulty): - print 'safezone:', sz - print 'pattern:', pattern - print 'difficulty:', difficulty - print 'expected %s %ss, found %s' % (numGroupsPerDifficulty[difficulty], difficulty, pattern.count(difficulty)) + print('safezone:', sz) + print('pattern:', pattern) + print('difficulty:', difficulty) + print('expected %s %ss, found %s' % (numGroupsPerDifficulty[difficulty], difficulty, pattern.count(difficulty))) return 0 return 1 pattern = self.randomNumGen.choice(difficultyPatterns[self.getSafezoneId()]) - for i in xrange(0, self.__numRingGroups): + for i in range(0, self.__numRingGroups): numRings = self.numPlayers trackGroup = RingTrackGroups.getRandomRingTrackGroup(pattern[i], numRings, self.randomNumGen) ringGroup = RingGroup.RingGroup(trackGroup, self.ringModel, RingGameGlobals.MAX_TOONXZ, self.colorIndices) - for r in xrange(numRings): + for r in range(numRings): self.__addRingDropShadow(ringGroup.getRing(r)) self.ringGroups.append(ringGroup) @@ -635,7 +636,7 @@ def exitSwim(self): def enterCleanup(self): self.notify.debug('enterCleanup') if not self.isSinglePlayer(): - for np in self.remoteToonCollNPs.values(): + for np in list(self.remoteToonCollNPs.values()): np.removeNode() del self.remoteToonCollNPs @@ -655,7 +656,7 @@ def __addDropShadow_INTERNAL(self, object, scale_x, scale_y, scale_z, list): list.append([shadow, object]) def __removeDropShadow_INTERNAL(self, object, list): - for i in xrange(len(list)): + for i in range(len(list)): entry = list[i] if entry[1] == object: entry[0].removeNode() @@ -884,7 +885,7 @@ def __processRingGroupResults(self, results): groupIndex = self.__nextRingGroupResultIndex ringGroup = self.ringGroups[self.__nextRingGroupResultIndex] self.__nextRingGroupResultIndex += 1 - for i in xrange(0, self.numPlayers): + for i in range(0, self.numPlayers): if self.avIdList[i] != self.localAvId: ring = ringGroup.getRing(i) self.__makeRingFadeAway(ring, results[i], i) diff --git a/toontown/minigame/DistributedRingGameAI.py b/toontown/minigame/DistributedRingGameAI.py index 589738003..5edb7aa00 100644 --- a/toontown/minigame/DistributedRingGameAI.py +++ b/toontown/minigame/DistributedRingGameAI.py @@ -64,10 +64,10 @@ def selectColorIndices(self): None, None] chooseFrom = RingGameGlobals.ringColorSelection[:] - for i in xrange(0, 4): + for i in range(0, 4): c = random.choice(chooseFrom) chooseFrom.remove(c) - if isinstance(c, types.TupleType): + if isinstance(c, tuple): c = random.choice(c) self.colorIndices[i] = c diff --git a/toontown/minigame/DistributedTagGame.py b/toontown/minigame/DistributedTagGame.py index 069e0921a..38257ec77 100644 --- a/toontown/minigame/DistributedTagGame.py +++ b/toontown/minigame/DistributedTagGame.py @@ -117,7 +117,7 @@ def setGameReady(self): self.acceptTagEvent(avId) myPos = self.avIdList.index(self.localAvId) - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): avId = self.avIdList[i] avatar = self.getAvatar(avId) if avatar: @@ -144,7 +144,7 @@ def exitOff(self): def enterPlay(self): self.notify.debug('enterPlay') - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): avId = self.avIdList[i] avName = self.getAvatarName(avId) scorePanel = MinigameAvatarScorePanel.MinigameAvatarScorePanel(avId, avName) @@ -231,7 +231,7 @@ def setIt(self, avId): spinTrack = LerpHprInterval(toon.getGeomNode(), duration, Point3(0, 0, 0), startHpr=Point3(-5.0 * 360.0, 0, 0), blendType='easeOut') growTrack = Parallel() gs = 2.5 - for hi in xrange(toon.headParts.getNumPaths()): + for hi in range(toon.headParts.getNumPaths()): head = toon.headParts[hi] growTrack.append(LerpScaleInterval(head, duration, Point3(gs, gs, gs))) @@ -262,7 +262,7 @@ def bounceCleanupFunc(node = toon.getGeomNode(), z = toon.getGeomNode().getZ()): if self.IT: it = self.getAvatar(self.IT) shrinkTrack = Parallel() - for hi in xrange(it.headParts.getNumPaths()): + for hi in range(it.headParts.getNumPaths()): head = it.headParts[hi] scale = ToontownGlobals.toonHeadScales[it.style.getAnimal()] shrinkTrack.append(LerpScaleInterval(head, duration, scale)) @@ -285,5 +285,5 @@ def setTreasureScore(self, scores): if not self.hasLocalToon: return self.notify.debug('setTreasureScore: %s' % scores) - for i in xrange(len(self.scorePanels)): + for i in range(len(self.scorePanels)): self.scorePanels[i].setScore(scores[i]) diff --git a/toontown/minigame/DistributedTargetGame.py b/toontown/minigame/DistributedTargetGame.py index 4cf505409..577f7c874 100644 --- a/toontown/minigame/DistributedTargetGame.py +++ b/toontown/minigame/DistributedTargetGame.py @@ -28,7 +28,7 @@ def circleY(angle, radius, centerX, centerY): def getCirclePoints(segCount, centerX, centerY, radius, wideX = 1.0, wideY = 1.0): returnShape = [] - for seg in xrange(0, int(segCount)): + for seg in range(0, int(segCount)): coordX = wideX * circleX(pi * 2.0 * float(float(seg) / float(segCount)), radius, centerX, centerY) coordY = wideY * circleY(pi * 2.0 * float(float(seg) / float(segCount)), radius, centerX, centerY) returnShape.append((coordX, coordY, 1)) @@ -41,7 +41,7 @@ def getCirclePoints(segCount, centerX, centerY, radius, wideX = 1.0, wideY = 1.0 def getRingPoints(segCount, centerX, centerY, radius, thickness = 2.0, wideX = 1.0, wideY = 1.0): returnShape = [] - for seg in xrange(0, segCount): + for seg in range(0, segCount): coordX = wideX * circleX(pi * 2.0 * float(float(seg) / float(segCount)), radius - thickness, centerX, centerY) coordY = wideY * circleY(pi * 2.0 * float(float(seg) / float(segCount)), radius - thickness, centerX, centerY) returnShape.append((coordX, coordY, 1)) @@ -66,7 +66,7 @@ def addRing(attachNode, color, vertexCount, radius, layer = 0, thickness = 1.0): targetTris = GeomTristrips(Geom.UHStatic) sizeTarget = len(targetCircleShape) - for countVertex in xrange(0, sizeTarget): + for countVertex in range(0, sizeTarget): targetTris.addVertex(countVertex) targetTris.addVertex(0) @@ -95,7 +95,7 @@ def addCircle(attachNode, color, vertexCount, radius, layer = 0): targetTris = GeomTrifans(Geom.UHStatic) sizeTarget = len(targetCircleShape) targetTris.addVertex(0) - for countVertex in xrange(1, sizeTarget + 1): + for countVertex in range(1, sizeTarget + 1): targetTris.addVertex(countVertex) targetTris.addVertex(1) @@ -404,7 +404,7 @@ def setTargetSeed(self, targetSeed, extra = None): return random.seed(targetSeed) self.pattern = TargetGameGlobals.difficultyPatterns[self.getSafezoneId()] - print 'seed %s' % targetSeed + print('seed %s' % targetSeed) self.setupTargets() def setupTargets(self): @@ -432,8 +432,8 @@ def setupTargets(self): self.accept('enterJump', self.jumpIn) self.accept('exitJump', self.jumpOut) self.targets = render.attachNewNode('targetGameTargets') - for typeIndex in xrange(len(self.targetList)): - for targetIndex in xrange(self.targetList[typeIndex]): + for typeIndex in range(len(self.targetList)): + for targetIndex in range(self.targetList[typeIndex]): goodPlacement = 0 while not goodPlacement: placeX = random.random() * (fieldWidth * 0.6) - fieldWidth * 0.6 * 0.5 @@ -468,7 +468,7 @@ def setupTargets(self): geo)) subIndex -= 1 - for jump in xrange(self.jumpNum): + for jump in range(self.jumpNum): normJumpSize = 6.8 goodPlacement = 0 while not goodPlacement: @@ -500,7 +500,7 @@ def setupTargets(self): targetNodePathGeom.setTransparency(TransparencyAttrib.MAlpha) cactusCount = 30 - for cactus in xrange(cactusCount): + for cactus in range(cactusCount): placeX = random.random() * (fieldWidth * 0.75) - fieldWidth * 0.75 * 0.5 placeY = 5.0 + random.random() * (fieldLength - 5.0) targetGN = GeomNode('cactus') @@ -588,14 +588,14 @@ def onstage(self): self.environBlocks = [] maxI = 4 self.maxDist = (maxI - 1) * self.ENVIRON_LENGTH - for i in xrange(-1, maxI + 1): + for i in range(-1, maxI + 1): instance = self.environModel.copyTo(self.environNode) y = self.ENVIRON_LENGTH * i instance.setY(y) self.addSkys(instance) self.environBlocks.append(instance) jRange = 3 - for j in xrange(0, jRange): + for j in range(0, jRange): instance = self.environModel.copyTo(self.environNode) x = self.ENVIRON_WIDTH * (j + 1) instance.setY(y) @@ -626,7 +626,7 @@ def onstage(self): sand = instance.find(self.findGround) sand.hide() - for j in xrange(0, jRange): + for j in range(0, jRange): instance = self.environModel.copyTo(self.environNode) x = self.ENVIRON_WIDTH * (j + 1) instance.setY(y) @@ -1027,7 +1027,7 @@ def exitScore(self): def enterCleanup(self): self.notify.debug('enterCleanup') if not self.isSinglePlayer(): - for np in self.remoteToonCollNPs.values(): + for np in list(self.remoteToonCollNPs.values()): np.removeNode() del self.remoteToonCollNPs @@ -1438,7 +1438,7 @@ def __addDropShadow_INTERNAL(self, object, scale_x, scale_y, scale_z, list): list.append([shadow, object]) def __removeDropShadow_INTERNAL(self, object, list): - for i in xrange(len(list)): + for i in range(len(list)): entry = list[i] if entry[1] == object: entry[0].removeNode() @@ -1530,7 +1530,7 @@ def setRoundDone(self): def setSingleScore(self, score, avId): if not self.hasLocalToon: return - for existIndex in xrange(len(self.avIdList)): + for existIndex in range(len(self.avIdList)): if self.avIdList[existIndex] == avId: self.scoreLabels[existIndex]['text'] = '%s' % score diff --git a/toontown/minigame/DistributedTargetGameAI.py b/toontown/minigame/DistributedTargetGameAI.py index c7d01d725..56604b2df 100644 --- a/toontown/minigame/DistributedTargetGameAI.py +++ b/toontown/minigame/DistributedTargetGameAI.py @@ -76,8 +76,8 @@ def setupTargets(self): self.placeValue = highestValue * 0.5 self.targetsPlaced = [] placeList = [] - for typeIndex in xrange(len(self.targetList)): - for targetIndex in xrange(self.targetList[typeIndex]): + for typeIndex in range(len(self.targetList)): + for targetIndex in range(self.targetList[typeIndex]): goodPlacement = 0 while not goodPlacement: placeX = random.random() * (fieldWidth * 0.6) - fieldWidth * 0.6 * 0.5 @@ -94,7 +94,7 @@ def setupTargets(self): def setGameStart(self, timestamp): self.notify.debug('setGameStart') - for avId in self.scoreDict.keys(): + for avId in list(self.scoreDict.keys()): self.scoreDict[avId] = 0 DistributedMinigameAI.setGameStart(self, timestamp) @@ -173,7 +173,7 @@ def getScoreList(self): 0, 0] scoreIndex = 0 - for avId in self.scoreDict.keys(): + for avId in list(self.scoreDict.keys()): scoreList[scoreIndex] = self.scoreDict[avId] avList[scoreIndex] = avId scoreIndex += 1 @@ -207,7 +207,7 @@ def setPlayerDone(self, other = None): return avId = self.air.getAvatarIdFromSender() self.barrierScore.clear(avId) - for avId in self.stateDict.keys(): + for avId in list(self.stateDict.keys()): if self.stateDict[avId] == EXITED: self.barrierScore.clear(avId) @@ -220,7 +220,7 @@ def gameOver(self): self.scoreDict[entry] = 1 self.scoreTrack.append(self.getScoreList()) - statMessage = 'MiniGame Stats : Target Game' + '\nScores' + '%s' % self.scoreTrack + '\nAvIds' + '%s' % self.scoreDict.keys() + '\nSafeZone' + '%s' % self.getSafezoneId() + statMessage = 'MiniGame Stats : Target Game' + '\nScores' + '%s' % self.scoreTrack + '\nAvIds' + '%s' % list(self.scoreDict.keys()) + '\nSafeZone' + '%s' % self.getSafezoneId() self.air.writeServerEvent('MiniGame Stats', None, statMessage) self.sendUpdate('setGameDone', []) self.gameFSM.request('cleanup') diff --git a/toontown/minigame/DistributedTravelGame.py b/toontown/minigame/DistributedTravelGame.py index 5ee26ab4c..18cf6140e 100644 --- a/toontown/minigame/DistributedTravelGame.py +++ b/toontown/minigame/DistributedTravelGame.py @@ -75,7 +75,7 @@ def map3dToAspect2d(node, point): def invertTable(table): index = {} - for key in table.keys(): + for key in list(table.keys()): value = table[key] if value not in index: index[value] = key @@ -149,10 +149,10 @@ def load(self): self.numKeys = self.keys.getNumPaths() self.keyInit = [] self.keyRef = [] - for i in xrange(self.numKeys): + for i in range(self.numKeys): key = self.keys[i] key.setTwoSided(1) - ref = self.trolleyCar.attachNewNode('key' + `i` + 'ref') + ref = self.trolleyCar.attachNewNode('key' + repr(i) + 'ref') ref.iPosHpr(key) self.keyRef.append(ref) self.keyInit.append(key.getTransform()) @@ -161,9 +161,9 @@ def load(self): self.numFrontWheels = self.frontWheels.getNumPaths() self.frontWheelInit = [] self.frontWheelRef = [] - for i in xrange(self.numFrontWheels): + for i in range(self.numFrontWheels): wheel = self.frontWheels[i] - ref = self.trolleyCar.attachNewNode('frontWheel' + `i` + 'ref') + ref = self.trolleyCar.attachNewNode('frontWheel' + repr(i) + 'ref') ref.iPosHpr(wheel) self.frontWheelRef.append(ref) self.frontWheelInit.append(wheel.getTransform()) @@ -172,9 +172,9 @@ def load(self): self.numBackWheels = self.backWheels.getNumPaths() self.backWheelInit = [] self.backWheelRef = [] - for i in xrange(self.numBackWheels): + for i in range(self.numBackWheels): wheel = self.backWheels[i] - ref = self.trolleyCar.attachNewNode('backWheel' + `i` + 'ref') + ref = self.trolleyCar.attachNewNode('backWheel' + repr(i) + 'ref') ref.iPosHpr(wheel) self.backWheelRef.append(ref) self.backWheelInit.append(wheel.getTransform()) @@ -189,7 +189,7 @@ def load(self): maxPoint = Point3(0, 0, 0) turnTable.calcTightBounds(minPoint, maxPoint) self.fullLength = maxPoint[0] - for key in TravelGameGlobals.BoardLayouts[self.boardIndex].keys(): + for key in list(TravelGameGlobals.BoardLayouts[self.boardIndex].keys()): info = TravelGameGlobals.BoardLayouts[self.boardIndex][key] switchModel = turnTable.find('**/turntable1').copyTo(render) switchModel.setPos(*info['pos']) @@ -221,7 +221,7 @@ def load(self): trainTrack = self.loadTrainTrack(startX, rootY, rootX, rootY) self.extraTrainTracks.append(trainTrack) tunnelX = None - for key in TravelGameGlobals.BoardLayouts[self.boardIndex].keys(): + for key in list(TravelGameGlobals.BoardLayouts[self.boardIndex].keys()): if self.isLeaf(key): info = TravelGameGlobals.BoardLayouts[self.boardIndex][key] switchX, switchY, switchZ = info['pos'] @@ -327,17 +327,17 @@ def unload(self): del self.entryTunnel self.trolleyCar.removeNode() del self.trolleyCar - for key in self.trainSwitches.keys(): + for key in list(self.trainSwitches.keys()): self.trainSwitches[key].removeNode() del self.trainSwitches[key] self.trainSwitches = {} - for key in self.tunnels.keys(): + for key in list(self.tunnels.keys()): self.tunnels[key].removeNode() del self.tunnels[key] self.tunnels = {} - for key in self.trainTracks.keys(): + for key in list(self.trainTracks.keys()): self.trainTracks[key].removeNode() del self.trainTracks[key] @@ -397,10 +397,10 @@ def onstage(self): self.sky.reparentTo(render) self.moveCameraToTop() self.trolleyCar.reparentTo(render) - for key in self.trainSwitches.keys(): + for key in list(self.trainSwitches.keys()): self.trainSwitches[key].reparentTo(render) - for key in self.trainTracks.keys(): + for key in list(self.trainTracks.keys()): self.trainTracks[key].reparentTo(render) for trainTrack in self.extraTrainTracks: @@ -421,10 +421,10 @@ def offstage(self): self.trolleyCar.hide() self.gui.hide() self.hideMinigamesAndBonuses() - for key in self.trainSwitches.keys(): + for key in list(self.trainSwitches.keys()): self.trainSwitches[key].hide() - for key in self.trainTracks.keys(): + for key in list(self.trainTracks.keys()): self.trainTracks[key].hide() for trainTrack in self.extraTrainTracks: @@ -441,7 +441,7 @@ def setGameReady(self): self.notify.debug('setGameReady') if DistributedMinigame.setGameReady(self): return - for index in xrange(self.numPlayers): + for index in range(self.numPlayers): avId = self.avIdList[index] name = '' avatar = self.getAvatar(avId) @@ -510,7 +510,7 @@ def enterDisplayVotes(self, votes, directions, directionToGo, directionReason): self.directionReason = directionReason self.resultsStr = '' directionTotals = [0] * TravelGameGlobals.MaxDirections - for index in xrange(len(votes)): + for index in range(len(votes)): if index < len(self.avNames): avId = self.avIdList[index] dir = directions[index] @@ -523,7 +523,7 @@ def enterDisplayVotes(self, votes, directions, directionToGo, directionReason): self.resultsStr += curStr directionStr = TTLocalizer.TravelGameTotals - for index in xrange(len(directionTotals)): + for index in range(len(directionTotals)): directionStr += ' ' + TTLocalizer.TravelGameDirections[index] + ':' directionStr += str(directionTotals[index]) @@ -658,7 +658,7 @@ def enterWinMovie(self): localAvatarWon = False localAvatarLost = False noWinner = True - for avId in self.avIdBonuses.keys(): + for avId in list(self.avIdBonuses.keys()): name = '' avatar = self.getAvatar(avId) if avatar: @@ -721,7 +721,7 @@ def setStartingVotes(self, startingVotesArray): if not len(startingVotesArray) == len(self.avIdList): self.notify.error('length does not match, startingVotes=%s, avIdList=%s' % (startingVotesArray, self.avIdList)) return - for index in xrange(len(self.avIdList)): + for index in range(len(self.avIdList)): avId = self.avIdList[index] self.startingVotes[avId] = startingVotesArray[index] if avId not in self.currentVotes: @@ -755,7 +755,7 @@ def putChoicesInScrollList(self): self.scrollList.removeAllItems() self.indexToVotes = {} index = 0 - for vote in xrange(available)[::-1]: + for vote in range(available)[::-1]: self.scrollList.addItem(str(-(vote + 1))) self.indexToVotes[index] = vote + 1 index += 1 @@ -764,7 +764,7 @@ def putChoicesInScrollList(self): self.indexToVotes[index] = 0 self.zeroVoteIndex = index index += 1 - for vote in xrange(available): + for vote in range(available): self.scrollList.addItem(str(vote + 1)) self.indexToVotes[index] = vote + 1 index += 1 @@ -854,7 +854,7 @@ def displayVotesTimeoutTask(self, task): return Task.done def updateCurrentVotes(self): - for index in xrange(len(self.resultVotes)): + for index in range(len(self.resultVotes)): avId = self.avIdList[index] oldCurrentVotes = self.currentVotes[avId] self.currentVotes[avId] -= self.resultVotes[index] @@ -884,7 +884,7 @@ def setMinigames(self, switches, minigames): if not self.hasLocalToon: return self.switchToMinigameDict = {} - for index in xrange(len(switches)): + for index in range(len(switches)): switch = switches[index] minigame = minigames[index] self.switchToMinigameDict[switch] = minigame @@ -894,13 +894,13 @@ def setMinigames(self, switches, minigames): def loadMinigameIcons(self): self.mg_icons = loader.loadModel('phase_4/models/minigames/mg_icons') - for switch in self.switchToMinigameDict.keys(): + for switch in list(self.switchToMinigameDict.keys()): minigame = self.switchToMinigameDict[switch] switchPos = self.trainSwitches[switch].getPos() labelPos = map3dToAspect2d(render, switchPos) useText = True iconName = None - if minigame in IconDict.keys(): + if minigame in list(IconDict.keys()): iconName = IconDict[minigame] icon = None if self.mg_icons: @@ -953,7 +953,7 @@ def hideMinigamesAndBonuses(self): def loadBonuses(self): self.switchToBonusLabelDict = {} - for avId in self.avIdBonuses.keys(): + for avId in list(self.avIdBonuses.keys()): if avId == self.localAvId: switch = self.avIdBonuses[avId][0] beans = self.avIdBonuses[avId][1] @@ -975,7 +975,7 @@ def setBonuses(self, switches, beans): if not self.hasLocalToon: return self.avIdBonuses = {} - for index in xrange(len(self.avIdList)): + for index in range(len(self.avIdList)): avId = self.avIdList[index] switch = switches[index] bean = beans[index] @@ -1009,27 +1009,27 @@ def getIntroMovie(self): return retval def animateTrolley(self, t, keyAngle, wheelAngle): - for i in xrange(self.numKeys): + for i in range(self.numKeys): key = self.keys[i] ref = self.keyRef[i] key.setH(ref, t * keyAngle) - for i in xrange(self.numFrontWheels): + for i in range(self.numFrontWheels): frontWheel = self.frontWheels[i] ref = self.frontWheelRef[i] frontWheel.setH(ref, t * wheelAngle) - for i in xrange(self.numBackWheels): + for i in range(self.numBackWheels): backWheel = self.backWheels[i] ref = self.backWheelRef[i] backWheel.setH(ref, t * wheelAngle) def resetAnimation(self): - for i in xrange(self.numKeys): + for i in range(self.numKeys): self.keys[i].setTransform(self.keyInit[i]) - for i in xrange(self.numFrontWheels): + for i in range(self.numFrontWheels): self.frontWheels[i].setTransform(self.frontWheelInit[i]) - for i in xrange(self.numBackWheels): + for i in range(self.numBackWheels): self.backWheels[i].setTransform(self.backWheelInit[i]) diff --git a/toontown/minigame/DistributedTravelGameAI.py b/toontown/minigame/DistributedTravelGameAI.py index 7f019a62e..115600cba 100644 --- a/toontown/minigame/DistributedTravelGameAI.py +++ b/toontown/minigame/DistributedTravelGameAI.py @@ -26,7 +26,7 @@ def __init__(self, air, minigameId): self.destSwitch = 0 self.gotBonus = {} self.desiredNextGame = -1 - self.boardIndex = random.choice(range(len(TravelGameGlobals.BoardLayouts))) + self.boardIndex = random.choice(list(range(len(TravelGameGlobals.BoardLayouts)))) def generate(self): self.notify.debug('generate') @@ -92,7 +92,7 @@ def exitWaitClientsChoices(self): def enterProcessChoices(self): self.directionVotes = [] - for dir in xrange(TravelGameGlobals.MaxDirections): + for dir in range(TravelGameGlobals.MaxDirections): self.directionVotes.append([dir, 0]) for key in self.avatarChoices: @@ -158,7 +158,7 @@ def createDefaultStartingVotes(self): def waitClientsChoicesTimeout(self, task): self.notify.debug('waitClientsChoicesTimeout: did not hear from all clients') - for avId in self.avatarChoices.keys(): + for avId in list(self.avatarChoices.keys()): if self.avatarChoices[avId] == (-1, 0): self.avatarChoices[avId] = (0, 0) @@ -199,7 +199,7 @@ def checkChoice(self, avId, votes, direction): return (retVotes, retDir) def allAvatarsChosen(self): - for avId in self.avatarChoices.keys(): + for avId in list(self.avatarChoices.keys()): choice = self.avatarChoices[avId] if choice[0] == -1 and not self.stateDict[avId] == EXITED: return False @@ -215,7 +215,7 @@ def isLeaf(self, switchIndex): def giveBonusBeans(self, endingSwitch): noOneGotBonus = True - for avId in self.avIdBonuses.keys(): + for avId in list(self.avIdBonuses.keys()): self.scoreDict[avId] = 0 if self.avIdBonuses[avId][0] == endingSwitch and not self.stateDict[avId] == EXITED: noOneGotBonus = False @@ -223,7 +223,7 @@ def giveBonusBeans(self, endingSwitch): self.gotBonus[avId] = self.avIdBonuses[avId][1] if noOneGotBonus: - for avId in self.avIdBonuses.keys(): + for avId in list(self.avIdBonuses.keys()): self.scoreDict[avId] = 1 def checkForEndGame(self): @@ -261,7 +261,7 @@ def calcMinigames(self): from toontown.minigame import MinigameCreatorAI allowedGames = MinigameCreatorAI.removeUnreleasedMinigames(allowedGames) self.switchToMinigameDict = {} - for switch in TravelGameGlobals.BoardLayouts[self.boardIndex].keys(): + for switch in list(TravelGameGlobals.BoardLayouts[self.boardIndex].keys()): if self.isLeaf(switch): if len(allowedGames) == 0: allowedGames = list(ToontownGlobals.MinigamePlayerMatrix[numPlayers]) @@ -272,7 +272,7 @@ def calcMinigames(self): switches = [] minigames = [] - for key in self.switchToMinigameDict.keys(): + for key in list(self.switchToMinigameDict.keys()): switches.append(key) minigames.append(self.switchToMinigameDict[key]) @@ -280,7 +280,7 @@ def calcMinigames(self): def calcBonusBeans(self): possibleLeaves = [] - for switch in TravelGameGlobals.BoardLayouts[self.boardIndex].keys(): + for switch in list(TravelGameGlobals.BoardLayouts[self.boardIndex].keys()): if self.isLeaf(switch): possibleLeaves.append(switch) @@ -313,7 +313,7 @@ def handleExitedAvatar(self, avId): self.stateDict[avId] = EXITED allExited = True for avId in self.avIdList: - if avId in self.stateDict.keys() and self.stateDict[avId] != EXITED: + if avId in list(self.stateDict.keys()) and self.stateDict[avId] != EXITED: allExited = False break diff --git a/toontown/minigame/DistributedTugOfWarGame.py b/toontown/minigame/DistributedTugOfWarGame.py index 3977b2875..ee7a12a46 100644 --- a/toontown/minigame/DistributedTugOfWarGame.py +++ b/toontown/minigame/DistributedTugOfWarGame.py @@ -90,7 +90,7 @@ def __init__(self, cr): [8, 12]] self.nextRateIndex = 0 self.drinkPositions = [] - for k in xrange(4): + for k in range(4): self.drinkPositions.append(VBase3(-.2 + 0.2 * k, 16 + 2 * k, 0.0)) self.rng = RandomNumGen.RandomNumGen(1000) @@ -134,7 +134,7 @@ def load(self): self.powerMeter.setPower(8) self.powerMeter.setTarget(8) self.arrows = [None] * 2 - for x in xrange(len(self.arrows)): + for x in range(len(self.arrows)): self.arrows[x] = loader.loadModel('phase_3/models/props/arrow') self.arrows[x].reparentTo(self.powerMeter) self.arrows[x].hide() @@ -266,7 +266,7 @@ def onstage(self): self.splash.reparentTo(render) self.suitSplash.reparentTo(render) base.playMusic(self.music, looping=1, volume=1) - for x in xrange(len(self.arrows)): + for x in range(len(self.arrows)): self.arrows[x].show() for avId in self.avIdList: @@ -280,7 +280,7 @@ def offstage(self): self.introTrack.finish() del self.introTrack self.introTrack = None - for track in self.animTracks.values(): + for track in list(self.animTracks.values()): if track: track.finish() del track @@ -391,7 +391,7 @@ def setGameReady(self): return def hideControls(self): - for x in xrange(len(self.arrows)): + for x in range(len(self.arrows)): self.arrows[x].hide() for rope in self.tugRopes: @@ -624,10 +624,10 @@ def initToons(self): def calculatePositions(self): hprPositions = [VBase3(240, 0, 0), VBase3(120, 0, 0)] dockPositions = [] - for k in xrange(5): + for k in range(5): dockPositions.append(VBase3(-9.0 + 1.5 * k, 18, 0.1)) - for k in xrange(5): + for k in range(5): dockPositions.append(VBase3(3 + 1.5 * k, 18, 0.1)) self.sendUpdate('sendNewAvIdList', [self.avIdList]) @@ -710,8 +710,8 @@ def calculatePositions(self): toon.setHpr(self.hprDict[avId]) def arrangeByHeight(self, avIdList, order, iStart, iFin): - for i in xrange(iStart, iFin + 1): - for j in xrange(i + 1, iFin + 1): + for i in range(iStart, iFin + 1): + for j in range(i + 1, iFin + 1): if order == self.H_TO_L and self.rightHandDict[avIdList[i]].getZ() < self.rightHandDict[avIdList[j]].getZ() or order == self.L_TO_H and self.rightHandDict[avIdList[i]].getZ() > self.rightHandDict[avIdList[j]].getZ(): temp = avIdList[i] avIdList[i] = avIdList[j] @@ -828,10 +828,10 @@ def __releaseHandler(self, index): def __updateKeyPressRateTask(self, task): if self.gameFSM.getCurrentState().getName() != 'tug': return Task.done - for i in xrange(len(self.keyTTL)): + for i in range(len(self.keyTTL)): self.keyTTL[i] -= 0.1 - for i in xrange(len(self.keyTTL)): + for i in range(len(self.keyTTL)): if self.keyTTL[i] <= 0: a = self.keyTTL[0:i] del self.keyTTL @@ -982,7 +982,7 @@ def sendStopSignal(self, winners, losers, tieers): exitSeq.append(Wait(2.5)) exitSeq.append(Func(self.gameOver)) self.showTrack = Parallel(reactSeq, exitSeq) - for x in self.animTracks.values(): + for x in list(self.animTracks.values()): if x != None: x.finish() @@ -1011,7 +1011,7 @@ def sendCurrentPosition(self, avIdList, offsetList): return if self.gameFSM.getCurrentState().getName() != 'tug': return - for i in xrange(len(avIdList)): + for i in range(len(avIdList)): self.offsetDict[avIdList[i]] = offsetList[i] self.moveToons() @@ -1181,7 +1181,7 @@ def initRopes(self): numRopes = self.numPlayers else: numRopes = self.numPlayers - 1 - for x in xrange(0, numRopes): + for x in range(0, numRopes): rope = Rope.Rope(self.uniqueName('TugRope' + str(x))) if rope.showRope: rope.ropeNode.setRenderMode(RopeNode.RMBillboard) @@ -1201,10 +1201,10 @@ def __spawnUpdateRopeTask(self): def __updateRopeTask(self, task): if self.tugRopes != None: - for i in xrange(len(self.tugRopes)): + for i in range(len(self.tugRopes)): if self.tugRopes[i] != None: self.ropePts[i] = self.tugRopes[i].getPoints(len(self.ropeTex[i])) - for j in xrange(len(self.ropePts[i])): + for j in range(len(self.ropePts[i])): self.ropeTex[i][j].setPos(self.ropePts[i][j]) return Task.cont diff --git a/toontown/minigame/DistributedTugOfWarGameAI.py b/toontown/minigame/DistributedTugOfWarGameAI.py index a4b10d313..fecdcdd82 100644 --- a/toontown/minigame/DistributedTugOfWarGameAI.py +++ b/toontown/minigame/DistributedTugOfWarGameAI.py @@ -189,7 +189,7 @@ def enterWaitForResults(self): def calculateOffsets(self): f = [0, 0] for i in [0, 1]: - for x in self.forceDict[i].values(): + for x in list(self.forceDict[i].values()): f[i] += x if self.gameType == TugOfWarGameGlobals.TOON_VS_COG: @@ -222,7 +222,7 @@ def reportCurrentKeyRate(self, keyRate, force): if self.howManyReported == self.numPlayers: self.howManyReported = 0 self.calculateOffsets() - self.sendUpdate('sendCurrentPosition', [self.offsetDict.keys(), self.offsetDict.values()]) + self.sendUpdate('sendCurrentPosition', [list(self.offsetDict.keys()), list(self.offsetDict.values())]) if self.gameType == TugOfWarGameGlobals.TOON_VS_COG: self.sendUpdate('sendSuitPosition', [self.suitOffset]) @@ -244,7 +244,7 @@ def __processResults(self): self.losers.append(self.suitId) else: self.winners.append(self.suitId) - for i in xrange(0, self.numPlayers): + for i in range(0, self.numPlayers): avId = self.avIdList[i] if self.side[avId] != self.losingSide: self.scoreDict[avId] = self.suitJellybeanReward + TugOfWarGameGlobals.WIN_JELLYBEANS @@ -254,7 +254,7 @@ def __processResults(self): self.losers.append(avId) else: - for i in xrange(0, self.numPlayers): + for i in range(0, self.numPlayers): avId = self.avIdList[i] if self.side[avId] != self.losingSide: self.scoreDict[avId] = TugOfWarGameGlobals.WIN_JELLYBEANS @@ -264,7 +264,7 @@ def __processResults(self): self.losers.append(avId) elif self.gameType == TugOfWarGameGlobals.TOON_VS_COG: - for i in xrange(0, self.numPlayers): + for i in range(0, self.numPlayers): avId = self.avIdList[i] if -self.offsetDict[avId] > self.suitOffset: self.scoreDict[avId] = self.suitJellybeanReward / 2 + TugOfWarGameGlobals.TIE_WIN_JELLYBEANS @@ -277,7 +277,7 @@ def __processResults(self): else: maxOffset = -100 minOffset = 100 - for i in xrange(0, self.numPlayers): + for i in range(0, self.numPlayers): avId = self.avIdList[i] if self.side[avId] == 0: if -self.offsetDict[avId] > maxOffset: @@ -290,7 +290,7 @@ def __processResults(self): elif self.offsetDict[avId] < minOffset: minOffset = self.offsetDict[avId] - for i in xrange(0, self.numPlayers): + for i in range(0, self.numPlayers): avId = self.avIdList[i] if maxOffset != minOffset: if self.side[avId] == 0: diff --git a/toontown/minigame/DistributedTwoDGame.py b/toontown/minigame/DistributedTwoDGame.py index 149ae4632..540d96c72 100644 --- a/toontown/minigame/DistributedTwoDGame.py +++ b/toontown/minigame/DistributedTwoDGame.py @@ -71,7 +71,7 @@ def unload(self): self.notify.debug('unload') DistributedMinigame.unload(self) taskMgr.remove(self.UpdateLocalToonTask) - for avId in self.toonSDs.keys(): + for avId in list(self.toonSDs.keys()): toonSD = self.toonSDs[avId] toonSD.destroy() @@ -112,7 +112,7 @@ def onstage(self): def offstage(self): self.notify.debug('offstage') self.assetMgr.offstage() - for avId in self.toonSDs.keys(): + for avId in list(self.toonSDs.keys()): self.toonSDs[avId].exit() base.localAvatar.setTransparency(0) @@ -155,7 +155,7 @@ def setGameStart(self, timestamp): self.twoDWalk = TwoDWalk(self.twoDDrive, broadcast=not self.isSinglePlayer()) self.scores = [0] * self.numPlayers spacing = 0.4 - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): avId = self.avIdList[i] avName = self.getAvatarName(avId) scorePanel = MinigameAvatarScorePanel.MinigameAvatarScorePanel(avId, avName) @@ -234,7 +234,7 @@ def enterShowScores(self): (lX, bY), (rX, bY))) scorePanelLocs = scorePanelLocs[self.numPlayers - 1] - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): panel = self.scorePanels[i] pos = scorePanelLocs[i] panel.wrtReparentTo(aspect2d) @@ -299,7 +299,7 @@ def __updateLocalToonTask(self, task): base.localAvatar.setY(0) if base.localAvatar.getZ() < -2.0: self.localToonFellDown() - for avId in self.toonSDs.keys(): + for avId in list(self.toonSDs.keys()): self.toonSDs[avId].update() return task.cont diff --git a/toontown/minigame/DistributedTwoDGameAI.py b/toontown/minigame/DistributedTwoDGameAI.py index 925e1de98..62d337098 100644 --- a/toontown/minigame/DistributedTwoDGameAI.py +++ b/toontown/minigame/DistributedTwoDGameAI.py @@ -49,7 +49,7 @@ def setGameReady(self): self.numEnemies = ToonBlitzGlobals.NumEnemies self.numTreasuresTaken = 0 self.numEnemiesKilled = 0 - for avId in self.scoreDict.keys(): + for avId in list(self.scoreDict.keys()): self.scoreDict[avId] = 0 self.finishedBonusDict[avId] = 0 self.finishedTimeLeftDict[avId] = -1 @@ -62,13 +62,13 @@ def setGameReady(self): 0, 0] - for i in xrange(len(self.sectionsSelected)): + for i in range(len(self.sectionsSelected)): sectionIndex = self.sectionsSelected[i][0] attribs = ToonBlitzGlobals.SectionTypes[sectionIndex] enemiesPool = attribs[3] self.enemyHealthTable += [[]] enemyIndicesSelected = self.sectionsSelected[i][1] - for j in xrange(len(enemyIndicesSelected)): + for j in range(len(enemyIndicesSelected)): enemyIndex = enemyIndicesSelected[j] enemyType = enemiesPool[enemyIndex][0] self.enemyHealthTable[i] += [ToonBlitzGlobals.EnemyBaseHealth] @@ -78,11 +78,11 @@ def setGameReady(self): self.treasureTakenTable += [[]] treasureIndicesSelected = self.sectionsSelected[i][2] - for j in xrange(len(treasureIndicesSelected)): + for j in range(len(treasureIndicesSelected)): self.treasureTakenTable[i] += [0] enemyIndicesSelected = self.sectionsSelected[i][1] - for j in xrange(len(enemyIndicesSelected)): + for j in range(len(enemyIndicesSelected)): self.treasureTakenTable[i] += [0] def setGameStart(self, timestamp): @@ -224,7 +224,7 @@ def toonVictory(self, avId, timestamp): self.notify.warning('suspicious: ' + str(avId) + ' ' + msg) self.air.writeServerEvent('suspicious: ', avId, msg) return - if avId not in self.scoreDict.keys(): + if avId not in list(self.scoreDict.keys()): self.notify.warning('Avatar %s not in list.' % avId) self.air.writeServerEvent('suspicious: ', avId, 'TwoDGameAI.toonVictory toon not in list.') return @@ -244,7 +244,7 @@ def toonVictory(self, avId, timestamp): return def toonFellDown(self, avId, timestamp): - if avId not in self.scoreDict.keys(): + if avId not in list(self.scoreDict.keys()): self.notify.warning('Avatar %s not in list.' % avId) self.air.writeServerEvent('warning', avId, 'TwoDGameAI.toonFellDown toon not in list.') return @@ -252,7 +252,7 @@ def toonFellDown(self, avId, timestamp): self.scoreDict[avId] += ToonBlitzGlobals.ScoreLossPerFallDown[self.getSafezoneId()] def toonHitByEnemy(self, avId, timestamp): - if avId not in self.scoreDict.keys(): + if avId not in list(self.scoreDict.keys()): self.notify.warning('Avatar %s not in list.' % avId) self.air.writeServerEvent('warning', avId, 'TwoDGameAI.toonHitByEnemy toon not in list.') return @@ -260,7 +260,7 @@ def toonHitByEnemy(self, avId, timestamp): self.scoreDict[avId] += ToonBlitzGlobals.ScoreLossPerEnemyCollision[self.getSafezoneId()] def toonSquished(self, avId, timestamp): - if avId not in self.scoreDict.keys(): + if avId not in list(self.scoreDict.keys()): self.notify.warning('Avatar %s not in list.' % avId) self.air.writeServerEvent('warning', avId, 'TwoDGameAI.toonSquished toon not in list.') return @@ -292,7 +292,7 @@ def setupSections(self): difficulty, probability = weight difficultyPool += [difficulty] * probability - for i in xrange(numSections): + for i in range(numSections): difficulty = random.choice(difficultyPool) difficultyList.append(difficulty) @@ -319,11 +319,11 @@ def setupSections(self): if whileCount > 1: self.notify.debug('We need more sections than we have choices. We have to now repeat.') - for i in xrange(len(sectionsSelectedByDifficulty)): - for j in xrange(len(sectionsSelectedByDifficulty[i])): + for i in range(len(sectionsSelectedByDifficulty)): + for j in range(len(sectionsSelectedByDifficulty[i])): sectionIndicesSelected.append(sectionsSelectedByDifficulty[i][j]) - for i in xrange(len(sectionIndicesSelected)): + for i in range(len(sectionIndicesSelected)): sectionIndex = sectionIndicesSelected[i] self.sectionIndexList.append(sectionIndex) attribs = sectionTypes[sectionIndex] @@ -338,12 +338,12 @@ def setupSections(self): enemyIndicesSelected = [] if enemiesPool != None: minEnemies, maxEnemies = attribs[7] - for i in xrange(len(enemiesPool)): + for i in range(len(enemiesPool)): enemyIndicesPool += [i] numEnemies = maxEnemies * ToonBlitzGlobals.PercentMaxEnemies[szId] / 100 numEnemies = max(numEnemies, minEnemies) - for j in xrange(int(numEnemies)): + for j in range(int(numEnemies)): if len(enemyIndicesPool) == 0: break enemyIndex = random.choice(enemyIndicesPool) @@ -353,18 +353,18 @@ def setupSections(self): enemyIndicesSelected.sort() treasureIndicesPool = [] treasureValuePool = [] - for value in xrange(1, 6): + for value in range(1, 6): treasureValuePool += [value] * ToonBlitzGlobals.TreasureValueProbability[value] treasureIndicesSelected = [] if treasuresPool != None: minTreasures, maxTreasures = attribs[8] - for i in xrange(len(treasuresPool)): + for i in range(len(treasuresPool)): treasureIndicesPool += [i] numTreasures = maxTreasures * ToonBlitzGlobals.PercentMaxTreasures[szId] / 100 numTreasures = max(numTreasures, minTreasures) - for i in xrange(int(numTreasures)): + for i in range(int(numTreasures)): if len(treasureIndicesPool) == 0: break treasureIndex = random.choice(treasureIndicesPool) @@ -378,12 +378,12 @@ def setupSections(self): spawnPointIndicesSelected = [] if spawnPointsPool != None: minSpawnPoints, maxSpawnPoints = attribs[9] - for i in xrange(len(spawnPointsPool)): + for i in range(len(spawnPointsPool)): spawnPointIndicesPool += [i] numSpawnPoints = maxSpawnPoints * ToonBlitzGlobals.PercentMaxSpawnPoints[szId] / 100 numSpawnPoints = max(numSpawnPoints, minSpawnPoints) - for i in xrange(int(numSpawnPoints)): + for i in range(int(numSpawnPoints)): if len(spawnPointIndicesPool) == 0: break spawnPoint = random.choice(spawnPointIndicesPool) @@ -395,12 +395,12 @@ def setupSections(self): stomperIndicesSelected = [] if stompersPool != None: minStompers, maxStompers = attribs[10] - for i in xrange(len(stompersPool)): + for i in range(len(stompersPool)): stomperIndicesPool += [i] numStompers = maxStompers * ToonBlitzGlobals.PercentMaxStompers[szId] / 100 numStompers = max(numStompers, minStompers) - for i in xrange(int(numStompers)): + for i in range(int(numStompers)): if len(stomperIndicesPool) == 0: break stomper = random.choice(stomperIndicesPool) diff --git a/toontown/minigame/DistributedVineGame.py b/toontown/minigame/DistributedVineGame.py index 3f943439a..fdccead51 100644 --- a/toontown/minigame/DistributedVineGame.py +++ b/toontown/minigame/DistributedVineGame.py @@ -189,7 +189,7 @@ def onstage(self): self.arrowKeys.setPressHandlers(handlers) self.numTreasures = len(self.vines) - 1 self.treasures = [] - for i in xrange(self.numTreasures): + for i in range(self.numTreasures): height = self.randomNumGen.randrange(10, 25) xPos = self.randomNumGen.randrange(12, 18) pos = Point3(self.vines[i].getX() + 15, 0, height) @@ -430,11 +430,11 @@ def applyToonInfoChange(self, avId, newInfo, oldInfo): def sanityCheck(self): if not self.isInPlayState(): return - for avId in self.toonInfo.keys(): + for avId in list(self.toonInfo.keys()): myVineIndex = self.toonInfo[avId][0] foundVines = [] foundVineIndex = -1 - for curVine in xrange(len(self.vines)): + for curVine in range(len(self.vines)): curInfo = self.vines[curVine].getAttachedToonInfo(avId) if curInfo: foundVines.append(curVine) @@ -448,7 +448,7 @@ def sanityCheck(self): def getVineAndVineInfo(self, avId): retVine = -1 retInfo = None - for curVine in xrange(len(self.vines)): + for curVine in range(len(self.vines)): curInfo = self.vines[curVine].getAttachedToonInfo(avId) if curInfo: retVine = curVine @@ -467,7 +467,7 @@ def setGameReady(self): return self.toonOffsets = {} self.toonOffsetsFalling = {} - for index in xrange(self.numPlayers): + for index in range(self.numPlayers): avId = self.avIdList[index] toon = self.getAvatar(avId) if toon: @@ -512,7 +512,7 @@ def enterPlay(self): self.createRadar() self.scores = [0] * self.numPlayers spacing = 0.4 - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): avId = self.avIdList[i] avName = self.getAvatarName(avId) scorePanel = MinigameAvatarScorePanel.MinigameAvatarScorePanel(avId, avName) @@ -580,7 +580,7 @@ def enterShowScores(self): (lX, bY), (rX, bY))) scorePanelLocs = scorePanelLocs[self.numPlayers - 1] - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): panel = self.scorePanels[i] pos = scorePanelLocs[i] panel.wrtReparentTo(aspect2d) @@ -671,7 +671,7 @@ def makeCameraFollowJumpingToon(self): camera.setX(minX) def __updateOtherToonsClimbing(self): - for avId in self.toonInfo.keys(): + for avId in list(self.toonInfo.keys()): if avId == self.localAvId: continue toonInfo = self.toonInfo[avId] @@ -713,7 +713,7 @@ def __updateLocalToonTask(self, task): self.handleLocalToonFellDown() avId = self.localAvId curInfo = None - for vineIndex in xrange(len(self.vines)): + for vineIndex in range(len(self.vines)): curInfo = self.vines[vineIndex].getAttachedToonInfo(avId) if curInfo: break @@ -845,7 +845,7 @@ def createJumpingTransitionIval(self, vineIndex): swingSeq = curInfo[6] if swingSeq: curFrame = -1 - for i in xrange(len(swingSeq)): + for i in range(len(swingSeq)): self.notify.debug('testing actor interval i=%d' % i) actorIval = swingSeq[i] if not actorIval.isStopped(): @@ -1054,7 +1054,7 @@ def downArrowKeyHandler(self): def rightArrowKeyHandler(self): curInfo = None - for vineIndex in xrange(len(self.vines)): + for vineIndex in range(len(self.vines)): curInfo = self.vines[vineIndex].getAttachedToonInfo(base.localAvatar.doId) if curInfo: break @@ -1078,7 +1078,7 @@ def rightArrowKeyHandler(self): def leftArrowKeyHandler(self): curInfo = None - for vineIndex in xrange(len(self.vines)): + for vineIndex in range(len(self.vines)): curInfo = self.vines[vineIndex].getAttachedToonInfo(base.localAvatar.doId) if curInfo: break @@ -1389,7 +1389,7 @@ def loadBats(self): def createBatIvals(self): self.batIvals = [] - for batIndex in xrange(len(self.bats)): + for batIndex in range(len(self.bats)): newBatIval = self.createBatIval(batIndex) self.batIvals.append(newBatIval) @@ -1439,7 +1439,7 @@ def getIntroTrack(self): retval = Sequence() toonTakeoffs = Parallel() didCameraMove = False - for index in xrange(len(self.avIdList)): + for index in range(len(self.avIdList)): avId = self.avIdList[index] if avId != self.localAvId: continue @@ -1541,7 +1541,7 @@ def cleanupEndingTracks(self): for taskName in self.endingTrackTaskNames: taskMgr.remove(taskName) - for endingTrack in self.endingTracks.values(): + for endingTrack in list(self.endingTracks.values()): endingTrack.finish del endingTrack diff --git a/toontown/minigame/DistributedVineGameAI.py b/toontown/minigame/DistributedVineGameAI.py index a0e29d8c0..f6ed5a4bc 100644 --- a/toontown/minigame/DistributedVineGameAI.py +++ b/toontown/minigame/DistributedVineGameAI.py @@ -50,7 +50,7 @@ def setGameReady(self): self.numTreasures = VineGameGlobals.NumVines - 1 self.numTreasuresTaken = 0 self.takenTable = [0] * self.numTreasures - for avId in self.scoreDict.keys(): + for avId in list(self.scoreDict.keys()): self.scoreDict[avId] = 0 self.finishedBonus[avId] = 0 self.finishedTimeLeft[avId] = -1 @@ -286,10 +286,10 @@ def setupVineSections(self): maxSpiders = VineGameGlobals.SpiderLimits[szId] curSpiders = 0 - for i in xrange(4): + for i in range(4): spidersLeft = maxSpiders - curSpiders validChoices = [] - for numSpiders in xrange(spidersLeft + 1): + for numSpiders in range(spidersLeft + 1): validChoices += pool[numSpiders] if not validChoices: diff --git a/toontown/minigame/DivingFishSpawn.py b/toontown/minigame/DivingFishSpawn.py index 93afcc536..b66325243 100644 --- a/toontown/minigame/DivingFishSpawn.py +++ b/toontown/minigame/DivingFishSpawn.py @@ -103,7 +103,7 @@ def createFish(self, fishcode): def destroy(self): self.ignoreAll() - for fish in self.fishArray.values(): + for fish in list(self.fishArray.values()): fish.moveLerp.pause() fish.specialLerp.finish() if hasattr(fish, 'sound'): diff --git a/toontown/minigame/DropPlacer.py b/toontown/minigame/DropPlacer.py index 220e55a10..7a06b03e7 100644 --- a/toontown/minigame/DropPlacer.py +++ b/toontown/minigame/DropPlacer.py @@ -51,7 +51,7 @@ def getRandomColRow(self): return [col, row] def getNextDrop(self): - raise RuntimeError, 'DropPlacer.getNextDrop should never be called' + raise RuntimeError('DropPlacer.getNextDrop should never be called') class RandomDropPlacer(DropPlacer): @@ -885,15 +885,15 @@ def __init__(self, game, numPlayers, dropTypes, startTime = None): DropPlacer.__init__(self, game, numPlayers, dropTypes, startTime=startTime) self.DropRegionTable = self.getDropRegionTable(self.numPlayers) self.DropRegion2GridCoordList = {} - for row in xrange(len(self.DropRegionTable)): + for row in range(len(self.DropRegionTable)): rowList = self.DropRegionTable[row] - for column in xrange(len(rowList)): + for column in range(len(rowList)): region = rowList[column] if region not in self.DropRegion2GridCoordList: self.DropRegion2GridCoordList[region] = [] self.DropRegion2GridCoordList[region].append([row, column]) - self.DropRegions = self.DropRegion2GridCoordList.keys() + self.DropRegions = list(self.DropRegion2GridCoordList.keys()) self.DropRegions.sort() self.emptyDropRegions = self.DropRegions[:] self.fallingObjs = [] @@ -949,7 +949,7 @@ def __init__(self, game, numPlayers, dropTypes, startTime = None): [-1, 0], [-1, -1]] self.paths = [] - for i in xrange(self.numPlayers): + for i in range(self.numPlayers): dir = self.rng.randrange(0, len(self.moves)) col, row = self.getRandomColRow() path = {'direction': dir, diff --git a/toontown/minigame/FogOverlay.py b/toontown/minigame/FogOverlay.py index 18b76b535..a70e7b7b5 100644 --- a/toontown/minigame/FogOverlay.py +++ b/toontown/minigame/FogOverlay.py @@ -32,12 +32,12 @@ def setup(self): overlayVertexData = GeomVertexData('holds my vertices', gFormat, Geom.UHDynamic) overlayVertexWriter = GeomVertexWriter(overlayVertexData, 'vertex') overlayColorWriter = GeomVertexWriter(overlayVertexData, 'color') - for index in xrange(len(shapeVertexs)): + for index in range(len(shapeVertexs)): overlayVertexWriter.addData3f(shapeVertexs[index][0], shapeVertexs[index][1], shapeVertexs[index][2]) overlayColorWriter.addData4f(1.0, 1.0, 1.0, 1.0) overlayTris = GeomTristrips(Geom.UHStatic) - for index in xrange(len(shapeVertexs)): + for index in range(len(shapeVertexs)): overlayTris.addVertex(index) overlayTris.closePrimitive() diff --git a/toontown/minigame/MazeBase.py b/toontown/minigame/MazeBase.py index 27dfbbcf7..eb40eb39d 100644 --- a/toontown/minigame/MazeBase.py +++ b/toontown/minigame/MazeBase.py @@ -137,12 +137,12 @@ def getSpotList(length): l = [] remaining = length for quadrant in quadrants: - for u in xrange(int(length / 4)): + for u in range(int(length / 4)): l.append(getEmptySpotInQuadrant(quadrant)) remaining -= int(length / 4) - for u in xrange(remaining): + for u in range(remaining): quadrant = quadrants[randomNumGen.randint(0, len(quadrants) - 1)] l.append(getEmptySpotInQuadrant(quadrant)) diff --git a/toontown/minigame/MazeMapGui.py b/toontown/minigame/MazeMapGui.py index d355bc6a0..13e2cea39 100644 --- a/toontown/minigame/MazeMapGui.py +++ b/toontown/minigame/MazeMapGui.py @@ -27,9 +27,9 @@ def __init__(self, mazeCollTable, maskResolution = None, radiusRatio = None, bgC self._radius = self._maskResolution * radiusRatio self._revealedCells = [] - for y in xrange(self._mazeHeight): + for y in range(self._mazeHeight): self._revealedCells.append([]) - for u in xrange(self._mazeWidth): + for u in range(self._mazeWidth): self._revealedCells[y].append(False) self._revealFunctions = {MazeRevealType.SmoothCircle: self._revealSmoothCircle, @@ -49,8 +49,8 @@ def _createMapTextureCard(self): mapImage = PNMImage(MAP_RESOLUTION, MAP_RESOLUTION) mapImage.fill(*self._bgColor) fgColor = LVecBase4f(*self._fgColor) - for x in xrange(self._mazeHeight): - for y in xrange(self._mazeWidth): + for x in range(self._mazeHeight): + for y in range(self._mazeWidth): if self._mazeCollTable[y][x] == 1: ax = float(x) / self._mazeWidth * MAP_RESOLUTION invertedY = self._mazeHeight - 1 - y @@ -73,8 +73,8 @@ def _createMapTextureCard(self): def _createMaskTextureCard(self): self._maskImage = PNMImage(self._maskResolution, self._maskResolution, 4) - for x in xrange(self._maskResolution): - for y in xrange(self._maskResolution): + for x in range(self._maskResolution): + for y in range(self._maskResolution): self._maskImage.setXelA(x, y, 0, 0, 0, 1) self.maskTexture = Texture('maskTexture') @@ -233,13 +233,13 @@ def revealCell(self, x, y): self._revealedCells[y][x] = True def revealAll(self): - for x in xrange(self._maskResolution): - for y in xrange(self._maskResolution): + for x in range(self._maskResolution): + for y in range(self._maskResolution): self._maskImage.setXelA(x, y, 0, 0, 0, 0) self.revealCell(0, 0) def reset(self): - for x in xrange(self._maskResolution): - for y in xrange(self._maskResolution): + for x in range(self._maskResolution): + for y in range(self._maskResolution): self._maskImage.setXelA(x, y, 0, 0, 0, 1) diff --git a/toontown/minigame/MazeSuit.py b/toontown/minigame/MazeSuit.py index 61ef42f6d..c32199306 100644 --- a/toontown/minigame/MazeSuit.py +++ b/toontown/minigame/MazeSuit.py @@ -61,7 +61,7 @@ def destroy(self): self.suit.delete() def uniqueName(self, str): - return str + `(self.serialNum)` + return str + repr((self.serialNum)) def gameStart(self, gameStartTime): self.gameStartTime = gameStartTime @@ -190,7 +190,7 @@ def getThinkTimestampTics(self, curTic): if curTic < self.nextThinkTic: return [] else: - r = range(self.nextThinkTic, curTic + 1, self.ticPeriod) + r = list(range(self.nextThinkTic, curTic + 1, self.ticPeriod)) self.lastTicBeforeRender = r[-1] return r @@ -232,14 +232,14 @@ def thinkSuits(suitList, startTime, ticFreq = MazeGameGlobals.SUIT_TIC_FREQ): curT = globalClock.getFrameTime() - startTime curTic = int(curT * float(ticFreq)) suitUpdates = [] - for i in xrange(len(suitList)): + for i in range(len(suitList)): updateTics = suitList[i].getThinkTimestampTics(curTic) - suitUpdates.extend(zip(updateTics, [i] * len(updateTics))) + suitUpdates.extend(list(zip(updateTics, [i] * len(updateTics)))) suitUpdates.sort(lambda a, b: a[0] - b[0]) if len(suitUpdates) > 0: curTic = 0 - for i in xrange(len(suitUpdates)): + for i in range(len(suitUpdates)): update = suitUpdates[i] tic = update[0] suitIndex = update[1] @@ -254,10 +254,10 @@ def thinkSuits(suitList, startTime, ticFreq = MazeGameGlobals.SUIT_TIC_FREQ): j += 1 unwalkables = [] - for si in xrange(suitIndex): + for si in range(suitIndex): unwalkables.extend(suitList[si].occupiedTiles) - for si in xrange(suitIndex + 1, len(suitList)): + for si in range(suitIndex + 1, len(suitList)): unwalkables.extend(suitList[si].occupiedTiles) suit.think(curTic, curT, unwalkables) diff --git a/toontown/minigame/MinigameCreatorAI.py b/toontown/minigame/MinigameCreatorAI.py index 5979de3cf..413843842 100644 --- a/toontown/minigame/MinigameCreatorAI.py +++ b/toontown/minigame/MinigameCreatorAI.py @@ -29,7 +29,7 @@ def getDisabledMinigames(): if not DisabledMinigames: - for name, minigameId in ToontownGlobals.MinigameNames.items(): + for name, minigameId in list(ToontownGlobals.MinigameNames.items()): if not simbase.config.GetBool('want-%s-game' % name, True): if minigameId not in DisabledMinigames: DisabledMinigames.append(minigameId) @@ -96,13 +96,13 @@ def createMinigame(air, playerArray, trolleyZone, minigameZone=None, ToontownGlobals.TwoDGameId: DistributedTwoDGameAI.DistributedTwoDGameAI, ToontownGlobals.TravelGameId: DistributedTravelGameAI.DistributedTravelGameAI, } - from TempMinigameAI import TempMgCtors - for key, value in TempMgCtors.items(): + from .TempMinigameAI import TempMgCtors + for key, value in list(TempMgCtors.items()): mgCtors[key] = value try: mg = mgCtors[mgId](air, mgId) except KeyError: - raise Exception, 'unknown minigame ID: %s' % mgId + raise Exception('unknown minigame ID: %s' % mgId) mg.setExpectedAvatars(playerArray) mg.setNewbieIds(newbieIds) mg.setTrolleyZone(trolleyZone) @@ -111,11 +111,11 @@ def createMinigame(air, playerArray, trolleyZone, minigameZone=None, for avId in playerArray: mg.setStartingVote(avId, TravelGameGlobals.DefaultStartingVotes) else: - for index in xrange(len(startingVotes)): + for index in range(len(startingVotes)): avId = playerArray[index] votes = startingVotes[index] if votes < 0: - print 'createMinigame negative votes, avId=%s votes=%s' % (avId, votes) + print('createMinigame negative votes, avId=%s votes=%s' % (avId, votes)) votes = 0 mg.setStartingVote(avId, votes) mg.setMetagameRound(metagameRound) @@ -199,7 +199,7 @@ def minigame(command, arg0=None): RequestMinigame[invoker.doId] = request[:3] + (arg0,) + request[4:] return 'Stored your request for the minigame safezone: ' + str(arg0) if command == 'abort': - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): from toontown.minigame import DistributedMinigameAI if not isinstance(do, DistributedMinigameAI.DistributedMinigameAI): continue diff --git a/toontown/minigame/MinigamePhysicsWorldBase.py b/toontown/minigame/MinigamePhysicsWorldBase.py index 1655c9ff3..863c6e6f1 100644 --- a/toontown/minigame/MinigamePhysicsWorldBase.py +++ b/toontown/minigame/MinigamePhysicsWorldBase.py @@ -89,7 +89,7 @@ def delete(self): def setupSimulation(self): if self.canRender: - for count in xrange(self.jointMarkerCount): + for count in range(self.jointMarkerCount): testMarker = render.attachNewNode('Joint Marker') ballmodel = loader.loadModel('phase_3/models/misc/sphere') ballmodel.reparentTo(testMarker) @@ -126,7 +126,7 @@ def preStep(self): def postStep(self): if self.showContacts and self.canRender: - for count in xrange(self.jointMarkerCount): + for count in range(self.jointMarkerCount): pandaNodePathGeom = self.jointMarkers[count] if count < self.colCount: pandaNodePathGeom.setPos(self.space.getContactData(count * 3 + 0), self.space.getContactData(count * 3 + 1), self.space.getContactData(count * 3 + 2)) diff --git a/toontown/minigame/MinigameRulesPanel.py b/toontown/minigame/MinigameRulesPanel.py index c5ef8ade4..7c2f0b2ae 100644 --- a/toontown/minigame/MinigameRulesPanel.py +++ b/toontown/minigame/MinigameRulesPanel.py @@ -6,7 +6,7 @@ from panda3d.direct import * from toontown.toonbase import ToontownTimer from toontown.toonbase import TTLocalizer -import MinigameGlobals +from . import MinigameGlobals class MinigameRulesPanel(StateData.StateData): diff --git a/toontown/minigame/PairingGameCard.py b/toontown/minigame/PairingGameCard.py index 7a65701f6..76d27c162 100644 --- a/toontown/minigame/PairingGameCard.py +++ b/toontown/minigame/PairingGameCard.py @@ -32,7 +32,7 @@ def load(self): prop.setScale(7) oneCard.find('**/glow').removeNode() cs = oneCard.find('**/collision') - for solidIndex in xrange(cs.node().getNumSolids()): + for solidIndex in range(cs.node().getNumSolids()): cs.node().modifySolid(solidIndex).setTangible(False) cs.node().setName('cardCollision-%d' % self.value) diff --git a/toontown/minigame/PhotoGameBase.py b/toontown/minigame/PhotoGameBase.py index c21e88c7f..bea546571 100644 --- a/toontown/minigame/PhotoGameBase.py +++ b/toontown/minigame/PhotoGameBase.py @@ -17,7 +17,7 @@ def generateAssignmentTemplates(self, numAssignments): if numPathes == 0: return assignmentTemplates while len(assignmentTemplates) < numAssignments: - subjectIndex = random.choice(range(numPathes)) + subjectIndex = random.choice(list(range(numPathes))) pose = (None, None) while pose[0] == None: animSetIndex = self.data['PATHANIMREL'][subjectIndex] diff --git a/toontown/minigame/PlayingCardDeck.py b/toontown/minigame/PlayingCardDeck.py index c7199bef3..405b5b660 100644 --- a/toontown/minigame/PlayingCardDeck.py +++ b/toontown/minigame/PlayingCardDeck.py @@ -8,13 +8,13 @@ def __init__(self): self.shuffle() def shuffle(self): - self.cards = range(0, PlayingCardGlobals.MaxSuit * PlayingCardGlobals.MaxRank) + self.cards = list(range(0, PlayingCardGlobals.MaxSuit * PlayingCardGlobals.MaxRank)) random.shuffle(self.cards) def shuffleWithSeed(self, seed): generator = random.Random() generator.seed(seed) - self.cards = range(0, PlayingCardGlobals.MaxSuit * PlayingCardGlobals.MaxRank) + self.cards = list(range(0, PlayingCardGlobals.MaxSuit * PlayingCardGlobals.MaxRank)) generator.shuffle(self.cards) def dealCard(self): @@ -22,7 +22,7 @@ def dealCard(self): def dealCards(self, num): cardList = [] - for i in xrange(num): + for i in range(num): cardList.append(self.cards.pop(0)) return cardList diff --git a/toontown/minigame/PlayingCardGlobals.py b/toontown/minigame/PlayingCardGlobals.py index 7015abeae..acc02b28d 100644 --- a/toontown/minigame/PlayingCardGlobals.py +++ b/toontown/minigame/PlayingCardGlobals.py @@ -59,9 +59,9 @@ def initCardImages(): cardModel = loader.loadModel(modelPath) cardModel.hide() CardImages[style] = {} - for suitIndex in xrange(MaxSuit): + for suitIndex in range(MaxSuit): CardImages[style][suitIndex] = {} - for rankIndex in xrange(MaxRank): + for rankIndex in range(MaxRank): track, level = convertRankToGagTrackAndLevel(rankIndex) propName = ToontownBattleGlobals.AvPropsNew[track][level] cardNode = cardModel.find('**/%s' % propName) diff --git a/toontown/minigame/Purchase.py b/toontown/minigame/Purchase.py index aafcf51c6..cd64aa082 100644 --- a/toontown/minigame/Purchase.py +++ b/toontown/minigame/Purchase.py @@ -78,7 +78,7 @@ def load(self): numAvs = 0 count = 0 localToonIndex = 0 - for index in xrange(len(self.ids)): + for index in range(len(self.ids)): avId = self.ids[index] if avId == base.localAvatar.doId: localToonIndex = index @@ -100,7 +100,7 @@ def load(self): TOON_INDEX = 2 self.avInfoArray = [(base.localAvatar.doId, headFramePosList[0], localToonIndex)] pos = 1 - for index in xrange(len(self.ids)): + for index in range(len(self.ids)): avId = self.ids[index] if self.states[index] != PURCHASE_NO_CLIENT_STATE and self.states[index] != PURCHASE_DISCONNECTED_STATE: if avId != base.localAvatar.doId: @@ -313,7 +313,7 @@ def enterReward(self): floorNode.addSolid(floor) self.collisionFloor = render.attachNewNode(floorNode) NametagGlobals.setForceOnscreenChat(True) - for index in xrange(len(self.ids)): + for index in range(len(self.ids)): avId = self.ids[index] if self.states[index] != PURCHASE_NO_CLIENT_STATE and self.states[index] != PURCHASE_DISCONNECTED_STATE and avId in base.cr.doId2do: numToons += 1 @@ -381,7 +381,7 @@ def celebrate(task): counter.hide() winningPoints = max(task.pointsArray) - for i in xrange(len(task.ids)): + for i in range(len(task.ids)): if task.pointsArray[i] == winningPoints: avId = task.ids[i] if avId in base.cr.doId2do: @@ -516,7 +516,7 @@ def countVotesUp(self): if base.cr.newsManager.isHolidayRunning(ToontownGlobals.JELLYBEAN_TROLLEY_HOLIDAY) or base.cr.newsManager.isHolidayRunning(ToontownGlobals.JELLYBEAN_TROLLEY_HOLIDAY_MONTH): self.rewardDoubledJellybeanLabel.show() counterIndex = 0 - for index in xrange(len(self.ids)): + for index in range(len(self.ids)): avId = self.ids[index] if self.states[index] != PURCHASE_NO_CLIENT_STATE and self.states[index] != PURCHASE_DISCONNECTED_STATE and avId in base.cr.doId2do: self.counters[counterIndex].count = 0 @@ -531,7 +531,7 @@ def delayAdd(state): base.playSfx(state.countSound) return Task.done - for count in xrange(0, self.maxVotes): + for count in range(0, self.maxVotes): for counter in self.counters: index = self.counters.index(counter) if count < counter.max: @@ -560,7 +560,7 @@ def delaySubtract(state): base.playSfx(state.overMaxSound) return Task.done - for count in xrange(0, self.maxVotes): + for count in range(0, self.maxVotes): for counter in self.counters: if count < counter.max: index = self.counters.index(counter) diff --git a/toontown/minigame/RingGroup.py b/toontown/minigame/RingGroup.py index d9c7c96d6..f6f15e3a8 100644 --- a/toontown/minigame/RingGroup.py +++ b/toontown/minigame/RingGroup.py @@ -17,7 +17,7 @@ def __init__(self, trackGroup, ringModel, posScale, colorIndices): self.__numRings = len(trackGroup.tracks) self.__rings = [] self.__ringModels = [] - for i in xrange(0, self.__numRings): + for i in range(0, self.__numRings): track = trackGroup.tracks[i] tOffset = trackGroup.trackTOffsets[i] ring = Ring.Ring(track, tOffset, posScale) diff --git a/toontown/minigame/RingTrackGroups.py b/toontown/minigame/RingTrackGroups.py index f632784fd..caa1b5ca3 100644 --- a/toontown/minigame/RingTrackGroups.py +++ b/toontown/minigame/RingTrackGroups.py @@ -50,7 +50,7 @@ def getTightCircleStaticPositions(numRings): else: radius = RingGameGlobals.RING_RADIUS * 1.5 / RingGameGlobals.MAX_TOONXZ step = 2.0 * math.pi / float(numRings) - for i in xrange(0, numRings): + for i in range(0, numRings): angle = i * step + step / 2.0 positions.append(angleToXY(angle, 1.0 / 3.0)) @@ -70,7 +70,7 @@ def get_keypad(numRings, rng): tracks = [] usedPositions = [None] posScale = 0.7 + rng.random() * 0.2 - for i in xrange(0, numRings): + for i in range(0, numRings): pos = None while pos in usedPositions: pos = rng.choice(positions) @@ -92,7 +92,7 @@ def get_keypad(numRings, rng): def get_evenCircle(numRings, rng): tracks = [] tOffsets = [] - for i in xrange(0, numRings): + for i in range(0, numRings): actions, durations = RingTracks.getCircleRingActions() track = RingTrack.RingTrack(actions, durations) tracks.append(track) @@ -104,7 +104,7 @@ def get_evenCircle(numRings, rng): def get_followCircle(numRings, rng): tracks = [] tOffsets = [] - for i in xrange(0, numRings): + for i in range(0, numRings): actions, durations = RingTracks.getCircleRingActions() track = RingTrack.RingTrack(actions, durations) delay = 0.12 @@ -119,14 +119,14 @@ def get_evenCircle_withStationaryCenterRings(numRings, rng): tOffsets = [] numCenterRings = rng.randint(1, numRings - 1) positions = getTightCircleStaticPositions(numCenterRings) - for i in xrange(0, numCenterRings): + for i in range(0, numCenterRings): action = RingAction.RingActionStaticPos(positions[i]) track = RingTrack.RingTrack([action]) tracks.append(track) tOffsets.append(0) numOuterRings = numRings - numCenterRings - for i in xrange(0, numOuterRings): + for i in range(0, numOuterRings): actions, durations = RingTracks.getCircleRingActions() track = RingTrack.RingTrack(actions, durations) tracks.append(track) @@ -139,13 +139,13 @@ def __get_Slots(numRings, rng, vertical = 1): tracks = [] tOffsets = [] fpTab = [] - for i in xrange(numRings): + for i in range(numRings): fpTab.append(PythonUtil.lineupPos(i, numRings, 2.0 / 3)) offset = 1 - fpTab[-1] offset = rng.random() * (offset * 2) - offset - fpTab = map(lambda x: x + offset, fpTab) - for i in xrange(0, numRings): + fpTab = [x + offset for x in fpTab] + for i in range(0, numRings): if vertical: getActionsFunc = RingTracks.getVerticalSlotActions else: @@ -182,7 +182,7 @@ def get_plus(numRings, rng): right]]} tracks = [] actionSet = rng.choice(actionSets[numRings]) - for i in xrange(0, numRings): + for i in range(0, numRings): actions, durations = actionSet[i]() track = RingTrack.RingTrack(actions, durations) tracks.append(track) @@ -205,10 +205,10 @@ def __initInfinityTOffsets(): offsets[1] = [0.0, 3.0 / 4.0] offsets[2] = [0.0, 1.0 / 3.0, 2.0 / 3.0] inc = 14.0 / 23.0 - for numRings in xrange(4, 5): + for numRings in range(4, 5): o = [0] * numRings accum = 0.0 - for i in xrange(0, numRings): + for i in range(0, numRings): o[i] = accum % 1.0 accum += inc @@ -221,7 +221,7 @@ def __initInfinityTOffsets(): def get_vertInfinity(numRings, rng): tracks = [] - for i in xrange(0, numRings): + for i in range(0, numRings): actions, durations = RingTracks.getVerticalInfinityRingActions() track = RingTrack.RingTrack(actions, durations) tracks.append(track) @@ -231,7 +231,7 @@ def get_vertInfinity(numRings, rng): def get_horizInfinity(numRings, rng): tracks = [] - for i in xrange(0, numRings): + for i in range(0, numRings): actions, durations = RingTracks.getHorizontalInfinityRingActions() track = RingTrack.RingTrack(actions, durations) tracks.append(track) @@ -280,12 +280,12 @@ def __listComplement(list1, list2): def __initFuncTables(): global trackListGenFuncs table = [[], [], []] - for diff in xrange(0, len(table)): + for diff in range(0, len(table)): table[diff] = [[], [], [], []] - for numRings in xrange(0, len(table[diff])): + for numRings in range(0, len(table[diff])): table[diff][numRings] = __listComplement(allFuncs[diff], dontUseFuncs[numRings]) trackListGenFuncs = table diff --git a/toontown/minigame/RubberBand.py b/toontown/minigame/RubberBand.py index a54fd86ed..28f6d3ade 100644 --- a/toontown/minigame/RubberBand.py +++ b/toontown/minigame/RubberBand.py @@ -128,12 +128,12 @@ def redraw(self, task): bandVertexData = GeomVertexData('holds my vertices', gFormat, Geom.UHDynamic) bandVertexWriter = GeomVertexWriter(bandVertexData, 'vertex') bandColorWriter = GeomVertexWriter(bandVertexData, 'color') - for index in xrange(len(shapeVertexs)): + for index in range(len(shapeVertexs)): bandVertexWriter.addData3f(shapeVertexs[index][0], shapeVertexs[index][1], shapeVertexs[index][2]) bandColorWriter.addData4f(color['Red'] * colorMultList[index], color['Green'] * colorMultList[index], color['Blue'] * colorMultList[index], color['Alpha'] * colorMultList[index]) bandTris = GeomTristrips(Geom.UHStatic) - for index in xrange(len(shapeVertexs)): + for index in range(len(shapeVertexs)): bandTris.addVertex(index) bandTris.closePrimitive() diff --git a/toontown/minigame/SwingVine.py b/toontown/minigame/SwingVine.py index 06e814a71..ba255a20a 100644 --- a/toontown/minigame/SwingVine.py +++ b/toontown/minigame/SwingVine.py @@ -89,7 +89,7 @@ def unload(self): if self.hasSpider: self.spider.destroy() del self.spider - for toonInfo in self.attachedToons.values(): + for toonInfo in list(self.attachedToons.values()): attachNode = toonInfo[4] if attachNode: attachNode.removeNode() @@ -104,7 +104,7 @@ def setupCable(self): self.links = [] self.links.append((self.topLink, Point3(0, 0, 0))) anchor = self.topLink - for linkNum in xrange(self.numLinks): + for linkNum in range(self.numLinks): anchor = self.__makeLink(anchor, linkNum) self.bottomLink = self.links[-1][0] @@ -153,7 +153,7 @@ def setupTubes(self): self.tubes = [] self.tubes2 = [] radius = 0.5 - for tubeIndex in xrange(self.numTubes): + for tubeIndex in range(self.numTubes): az = self.tubeLength / 2.0 bz = -self.tubeLength / 2.0 ct = CollisionTube(0, 0, az, 0, 0, bz, radius) @@ -187,16 +187,16 @@ def __makeLink(self, anchor, linkNum): def makeSpline(self): rope = Rope.Rope() - for i in xrange(len(self.links)): + for i in range(len(self.links)): pass rope.setup(min(len(self.links), 4), self.links) - for i in xrange(len(self.links)): + for i in range(len(self.links)): pass rope.curve.normalizeKnots() self.notify.debug('after normalize Knots') - for i in xrange(len(self.links)): + for i in range(len(self.links)): pass rn = rope.ropeNode @@ -396,7 +396,7 @@ def getCenterTForTube(self, tubeIndex): def updateTubes(self): newPoint = Vec3(0, 0, 0) curve = self.rope.ropeNode.getCurve().evaluate() - for tubeIndex in xrange(self.numTubes): + for tubeIndex in range(self.numTubes): tube = self.tubes[tubeIndex] t = self.getCenterTForTube(tubeIndex) curve.evalPoint(t, newPoint) @@ -409,7 +409,7 @@ def updateTubes(self): rAngle = -90 - degrees tube.setR(rAngle) - for tubeIndex in xrange(self.numTubes): + for tubeIndex in range(self.numTubes): tube = self.tubes2[tubeIndex] t = self.getCenterTForTube(tubeIndex) curve.evalPoint(t, newPoint) @@ -448,7 +448,7 @@ def updateAttachedStuff(self): def updateAttachedToons(self): curve = self.rope.ropeNode.getCurve().evaluate() - for avId in self.attachedToons.keys(): + for avId in list(self.attachedToons.keys()): self.doubleCheckOffset(avId) t = self.attachedToons[avId][0] newPoint = Vec3(0, 0, 0) @@ -653,5 +653,5 @@ def calcSwingAnimType(self, toonT): def updateSwingAnims(self): if self.unloading: return - for avId in self.attachedToons.keys(): + for avId in list(self.attachedToons.keys()): self.setupSwingAnim(avId) diff --git a/toontown/minigame/TempMinigameAI.py b/toontown/minigame/TempMinigameAI.py index 5216a5a3c..5da99023e 100644 --- a/toontown/minigame/TempMinigameAI.py +++ b/toontown/minigame/TempMinigameAI.py @@ -4,7 +4,7 @@ TempMgCtors = {} def _printMessage(message): - print '\n\n!!!', message, '\n\n' + print('\n\n!!!', message, '\n\n') def _registerTempMinigame(name, Class, id, minPlayers = 1, maxPlayers = 4): @@ -16,7 +16,7 @@ def _registerTempMinigame(name, Class, id, minPlayers = 1, maxPlayers = 4): ToontownGlobals.MinigameIDs += (id,) ToontownGlobals.MinigameNames[name] = id TempMgCtors[id] = Class - for i in xrange(minPlayers, maxPlayers): + for i in range(minPlayers, maxPlayers): ToontownGlobals.MinigamePlayerMatrix[i] += (id,) _printMessage('registerTempMinigame: ' + name) \ No newline at end of file diff --git a/toontown/minigame/ToonBlitzAssetMgr.py b/toontown/minigame/ToonBlitzAssetMgr.py index de907689d..e27b5e6aa 100644 --- a/toontown/minigame/ToonBlitzAssetMgr.py +++ b/toontown/minigame/ToonBlitzAssetMgr.py @@ -39,7 +39,7 @@ def load(self): self.treasureModelList.append(boardIcon) self.particleGlow = loader.loadModel('phase_4/models/minigames/particleGlow') self.blockTypes = [] - for i in xrange(4): + for i in range(4): blockType = loader.loadModel('phase_4/models/minigames/toonblitz_game_block0' + str(i)) self.blockTypes.append(blockType) @@ -71,7 +71,7 @@ def load(self): self.progressLine.setScale(self.faceEndPos[0] - self.faceStartPos[0], 1, 0.01) self.progressLine.setPos(0, 0, self.faceStartPos[2]) self.cardMaker.setName('RaceProgressLineHash') - for n in xrange(ToonBlitzGlobals.NumSections[self.game.getSafezoneId()] + 1): + for n in range(ToonBlitzGlobals.NumSections[self.game.getSafezoneId()] + 1): hash = self.aspect2dRoot.attachNewNode(self.cardMaker.generate()) hash.setScale(self.progressLine.getScale()[2], 1, self.progressLine.getScale()[2] * 5) t = float(n) / ToonBlitzGlobals.NumSections[self.game.getSafezoneId()] diff --git a/toontown/minigame/TwoDEnemyMgr.py b/toontown/minigame/TwoDEnemyMgr.py index fc8f090b9..49cbff1f9 100644 --- a/toontown/minigame/TwoDEnemyMgr.py +++ b/toontown/minigame/TwoDEnemyMgr.py @@ -26,7 +26,7 @@ def load(self): self.enemiesNP = NodePath('Enemies') self.enemiesNP.reparentTo(self.section.sectionNP) self.enemies = [] - for index in xrange(len(self.enemyList)): + for index in range(len(self.enemyList)): enemyId = self.section.getSectionizedId(index) suitAttribs = self.enemyList[index] newEnemy = TwoDEnemy.TwoDEnemy(self, enemyId, suitAttribs) diff --git a/toontown/minigame/TwoDSection.py b/toontown/minigame/TwoDSection.py index 3f22d81d2..0470fac7d 100644 --- a/toontown/minigame/TwoDSection.py +++ b/toontown/minigame/TwoDSection.py @@ -74,7 +74,7 @@ def load(self, sectionInfo): self.blocksNP.reparentTo(self.sectionNP) if self.blockList[0][1][0] != (0, 0, 12): self.notify.warning('First block of section %s does not start at (0, 0, 12)' % self.sectionTypeNum) - for index in xrange(0, len(self.blockList)): + for index in range(0, len(self.blockList)): blockAttribs = self.blockList[index] fileName = ToonBlitzGlobals.BlockTypes[blockAttribs[0]][0] blockIndex = int(fileName[-1]) diff --git a/toontown/minigame/TwoDSectionMgr.py b/toontown/minigame/TwoDSectionMgr.py index 0c964b01f..6eb8d441f 100644 --- a/toontown/minigame/TwoDSectionMgr.py +++ b/toontown/minigame/TwoDSectionMgr.py @@ -56,7 +56,7 @@ def setupStartSection(self): self.startPipe.setPos(12, 0, 44) self.startArrow = self.game.assetMgr.arrow.copyTo(self.startSectionNP) self.startArrow.setPos(23, 1.5, 12.76) - for index in xrange(len(ToonBlitzGlobals.BlockListStart)): + for index in range(len(ToonBlitzGlobals.BlockListStart)): blockAttribs = ToonBlitzGlobals.BlockListStart[index] fileName = ToonBlitzGlobals.BlockTypes[blockAttribs[0]][0] blockIndex = int(fileName[-1]) @@ -99,7 +99,7 @@ def setupEndSection(self, index): def setupSections(self, sectionsSelected): self.incrementX = -24 - for index in xrange(0, len(sectionsSelected)): + for index in range(0, len(sectionsSelected)): sectionNP = NodePath('Section' + str(index)) sectionNP.reparentTo(self.game.assetMgr.world) sectionNP.setX(self.incrementX) diff --git a/toontown/minigame/TwoDStomper.py b/toontown/minigame/TwoDStomper.py index 4f6c1dba8..3b9c7d51a 100644 --- a/toontown/minigame/TwoDStomper.py +++ b/toontown/minigame/TwoDStomper.py @@ -71,7 +71,7 @@ def setupStomper(self, stomperAttribs): self.range = self.headEndZ - self.headStartZ self.collSolids = [] self.collSolids.append(originalColl) - for i in xrange(self.numCollSolids - 1): + for i in range(self.numCollSolids - 1): newColl = originalColl.copyTo(self.model) self.collSolids.append(newColl) @@ -116,7 +116,7 @@ def adjustShaftScale(self, t): def adjustCollSolidHeight(self, t): heightDiff = self.head.getZ() - self.headStartZ - for i in xrange(1, len(self.collSolids) - 1): + for i in range(1, len(self.collSolids) - 1): self.collSolids[i].setZ(heightDiff * i / (self.numCollSolids - 1)) def start(self, elapsedTime): diff --git a/toontown/minigame/TwoDStomperMgr.py b/toontown/minigame/TwoDStomperMgr.py index c3a957747..99dbdc3d4 100644 --- a/toontown/minigame/TwoDStomperMgr.py +++ b/toontown/minigame/TwoDStomperMgr.py @@ -26,7 +26,7 @@ def load(self): self.stompersNP = NodePath('Stompers') self.stompersNP.reparentTo(self.section.sectionNP) self.stompers = [] - for index in xrange(len(self.stomperList)): + for index in range(len(self.stomperList)): stomperAttribs = self.stomperList[index] self.createNewStomper(stomperAttribs) diff --git a/toontown/minigame/TwoDTreasureMgr.py b/toontown/minigame/TwoDTreasureMgr.py index eaf60d332..54732519b 100644 --- a/toontown/minigame/TwoDTreasureMgr.py +++ b/toontown/minigame/TwoDTreasureMgr.py @@ -29,7 +29,7 @@ def load(self): self.treasuresNP = NodePath('Treasures') self.treasuresNP.reparentTo(self.section.sectionNP) self.treasures = [] - for index in xrange(len(self.treasureList)): + for index in range(len(self.treasureList)): treasureAttribs = self.treasureList[index][0] treasureValue = self.treasureList[index][1] self.createNewTreasure(treasureAttribs, treasureValue) @@ -37,7 +37,7 @@ def load(self): self.enemyTreasures = [] numPlayers = self.section.sectionMgr.game.numPlayers pos = Point3(-1, -1, -1) - for index in xrange(len(self.enemyList)): + for index in range(len(self.enemyList)): self.createNewTreasure([pos], numPlayers, isEnemyGenerated=True) def createNewTreasure(self, attrib, value, isEnemyGenerated = False, model = None): diff --git a/toontown/minigame/VineHeadFrame.py b/toontown/minigame/VineHeadFrame.py index d3f57f315..fadec24c0 100644 --- a/toontown/minigame/VineHeadFrame.py +++ b/toontown/minigame/VineHeadFrame.py @@ -12,7 +12,7 @@ def __init__(self, av = None, color = Vec4(1, 1, 1, 1), *args, **kwargs): 'geom_scale': (0.5, 1, 0.5), 'pos': (0, 0, 0)} opts.update(kwargs) - apply(DirectFrame.__init__, (self,) + args, opts) + DirectFrame.__init__(*(self,) + args, **opts) self.initialiseoptions(VineHeadFrame) if av: self.setAv(av) diff --git a/toontown/minigame/VineSpider.py b/toontown/minigame/VineSpider.py index 69804512c..603899f68 100644 --- a/toontown/minigame/VineSpider.py +++ b/toontown/minigame/VineSpider.py @@ -56,8 +56,8 @@ def destroy(self): self.removeNode() def __handleEnterSphere(self, collEntry): - print 'VineSpider.__handleEnterSphere' - print collEntry + print('VineSpider.__handleEnterSphere') + print(collEntry) self.ignoreAll() self.notify.debug('treasuerGrabbed') messenger.send('VineSpiderGrabbed', [self.serialNum]) diff --git a/toontown/minigame/VoteResultsPanel.py b/toontown/minigame/VoteResultsPanel.py index 5343ff11b..8fd50e0c5 100644 --- a/toontown/minigame/VoteResultsPanel.py +++ b/toontown/minigame/VoteResultsPanel.py @@ -43,7 +43,7 @@ def __init__(self, numPlayers, avIdList, votes, directions, namesList, disconnec self.resultFrame = DirectFrame(parent=self, relief=None, pos=self.getRowPos(5)) self.resultLabel = DirectLabel(parent=self.resultFrame, text='', text_scale=0.06, pos=(0.7, 0, 0.0), text_align=TextNode.ACenter) self.setupResultLabel() - for index in xrange(self.numPlayers): + for index in range(self.numPlayers): frame = DirectFrame(parent=self, relief=None, pos=self.getRowPos(index)) self.rowFrame.append(frame) nameLabel = DirectFrame(parent=frame, relief=None, pos=(0.46, 0.0, 0.0), text=self.namesList[index], text_fg=(0.0, 0.0, 0.0, 1.0), text_scale=0.05, text_align=TextNode.ACenter, text_font=DGG.getDefaultFont()) @@ -82,7 +82,7 @@ def ticketTicker(t, label = self.entryList[index][direction + 1], startVotes = 0 track.append(Func(self.entryList[index][0].show, name='showName %d' % index)) track.append(LerpFunc(ticketTicker, duration=duration, name='countVotes %d' % index)) startVotes = 0 - for prev in xrange(index): + for prev in range(index): if self.directions[prev] == direction: startVotes += self.votes[prev] @@ -94,7 +94,7 @@ def totalTicker(t, label = self.totalVotesLabels[direction], startVotes = startV def startMovie(self): self.movie = Sequence() - for index in xrange(self.numPlayers): + for index in range(self.numPlayers): track = self.createOnePlayerSequence(index, 1.25) self.movie.append(track) self.movie.append(Wait(0.75)) diff --git a/toontown/minigame/VoteResultsTrolleyPanel.py b/toontown/minigame/VoteResultsTrolleyPanel.py index ef2042d00..18685fe02 100644 --- a/toontown/minigame/VoteResultsTrolleyPanel.py +++ b/toontown/minigame/VoteResultsTrolleyPanel.py @@ -42,7 +42,7 @@ def __init__(self, numPlayers, avIdList, votes, directions, namesList, disconnec self.resultFrame = DirectFrame(parent=self, relief=None, pos=self.getRowPos(0.5)) self.resultLabel = DirectLabel(parent=self.resultFrame, text='', text_scale=0.06, pos=(0.7, 0, 0.0), text_align=TextNode.ACenter) self.setupResultLabel() - for index in xrange(self.numPlayers): + for index in range(self.numPlayers): frame = DirectFrame(parent=self, relief=None, pos=self.getRowPos(index)) self.rowFrame.append(frame) nameLabel = DirectFrame(parent=frame, relief=None, pos=(0.46, 0.0, 0.0), text=self.namesList[index], text_fg=(0.0, 0.0, 0.0, 1.0), text_scale=0.05, text_align=TextNode.ACenter, text_font=DGG.getDefaultFont()) @@ -56,7 +56,7 @@ def __init__(self, numPlayers, avIdList, votes, directions, namesList, disconnec matchingGameGui = loader.loadModel('phase_3.5/models/gui/matching_game_gui') minnieArrow = matchingGameGui.find('**/minnieArrow') from toontown.minigame.DistributedTravelGame import map3dToAspect2d - for index in xrange(self.numPlayers): + for index in range(self.numPlayers): avId = self.avIdList[index] av = base.cr.doId2do.get(avId) if av: @@ -100,7 +100,7 @@ def __init__(self, numPlayers, avIdList, votes, directions, namesList, disconnec self.curArrowSfxIndex = 0 self.upArrowSfx = [] self.downArrowSfx = [] - for i in xrange(5): + for i in range(5): self.upArrowSfx.append(base.loader.loadSfx('phase_4/audio/sfx/MG_sfx_travel_game_blue_arrow.ogg')) self.downArrowSfx.append(base.loader.loadSfx('phase_4/audio/sfx/MG_sfx_travel_game_red_arrow.ogg')) @@ -159,7 +159,7 @@ def ticketTicker(t, label = self.entryList[index][direction + 1], startVotes = 0 track = Parallel() startVotes = 0 - for prev in xrange(index): + for prev in range(index): if self.directions[prev] == direction: startVotes += self.votes[prev] @@ -198,7 +198,7 @@ def avVotesTicker(t, label = self.avVotesLabel[index], startVotes = 0, endVotes def startMovie(self): self.movie = Sequence() - for index in xrange(self.numPlayers): + for index in range(self.numPlayers): track = self.createOnePlayerSequence(index, 1.25) self.movie.append(track) self.movie.append(Wait(0.75)) diff --git a/toontown/pandautils/BpDb.py b/toontown/pandautils/BpDb.py index a0aaeef02..babc9d8df 100644 --- a/toontown/pandautils/BpDb.py +++ b/toontown/pandautils/BpDb.py @@ -116,7 +116,7 @@ def getIgnoreCount(self, bp, decrement=False): def setIgnoreCount(self, bp, ignoreCount=0): if not isinstance(ignoreCount, int): - print 'error: first argument should be integer ignoreCount' + print('error: first argument should be integer ignoreCount') return parts = self.bpToParts(bp) @@ -215,18 +215,18 @@ def resetConfig(self, cfg): #setup bpdb prompt commands def displayHelp(self): - print 'You may use normal pdb commands plus the following:' + print('You may use normal pdb commands plus the following:') #print ' cmd [param ] [cmd] does )this( with [param] (default is def)' #print ' -----------------------------------------------------------------------' - print ' _i [n <0> [, path=]] set ignore count for bp [path] to [n]' - print ' _t [path ] toggle bp [path]' - print ' _tg [grp ] toggle grp' - print ' _tc [cfg ] toggle cfg' - print ' _z [path ] clear all settings for bp [path]' - print ' _zg [grp ] clear all settings for grp' - print ' _zc [cfg ] clear all settings for cfg (restore .prc setting)' - print ' _h displays this usage help' - print ' _ua unalias these commands from pdb' + print(' _i [n <0> [, path=]] set ignore count for bp [path] to [n]') + print(' _t [path ] toggle bp [path]') + print(' _tg [grp ] toggle grp') + print(' _tc [cfg ] toggle cfg') + print(' _z [path ] clear all settings for bp [path]') + print(' _zg [grp ] clear all settings for grp') + print(' _zc [cfg ] clear all settings for cfg (restore .prc setting)') + print(' _h displays this usage help') + print(' _ua unalias these commands from pdb') def addPdbAliases(self): self.makePdbAlias('_i', 'bpdb._i(%*)') @@ -244,28 +244,28 @@ def makePdbAlias(self, aliasName, aliasCmd): self.pdb.do_alias('%s %s'%(aliasName,aliasCmd)) def removePdbAliases(self): - for aliasName in self.pdbAliases.iterkeys(): + for aliasName in self.pdbAliases.keys(): self.pdb.do_unalias(aliasName) self.pdbAliases = {} - print '(bpdb aliases removed)' + print('(bpdb aliases removed)') #handle bpdb prompt commands by forwarding to bpMan def _e(self, *args, **kwargs): bp = self._getArg(args, [type(''),type({}),], kwargs, ['path','bp','name',], self.lastBp) enabled = self._getArg(args, [type(True),type(1),], kwargs, ['enabled','on',], True) newEnabled = self.bpMan.setEnabled(bp, enabled) - print "'%s' is now %s."%(self.bpMan.bpToPath(bp),choice(newEnabled,'enabled','disabled'),) + print("'%s' is now %s."%(self.bpMan.bpToPath(bp),choice(newEnabled,'enabled','disabled'),)) def _i(self, *args, **kwargs): bp = self._getArg(args, [type(''),type({}),], kwargs, ['path','bp','name',], self.lastBp) count = self._getArg(args, [type(1),], kwargs, ['ignoreCount','count','n',], 0) newCount = self.bpMan.setIgnoreCount(bp, count) - print "'%s' will ignored %s times."%(self.bpMan.bpToPath(bp),newCount,) + print("'%s' will ignored %s times."%(self.bpMan.bpToPath(bp),newCount,)) def _t(self, *args, **kwargs): bp = self._getArg(args, [type(''),type({}),], kwargs, ['path','bp','name',], self.lastBp) newEnabled = self.bpMan.toggleEnabled(bp) - print "'%s' is now %s."%(self.bpMan.bpToPath(bp),choice(newEnabled,'enabled','disabled'),) + print("'%s' is now %s."%(self.bpMan.bpToPath(bp),choice(newEnabled,'enabled','disabled'),)) def _tg(self, *args, **kwargs): bp = self._getArg(args, [type(''),type({}),], kwargs, ['grp',], self.lastBp) @@ -273,7 +273,7 @@ def _tg(self, *args, **kwargs): bp = {'grp':bp} bp = {'grp':bp.get('grp')} newEnabled = self.bpMan.toggleEnabled(bp) - print "'%s' is now %s."%(self.bpMan.bpToPath(bp),choice(newEnabled,'enabled','disabled'),) + print("'%s' is now %s."%(self.bpMan.bpToPath(bp),choice(newEnabled,'enabled','disabled'),)) def _tc(self, *args, **kwargs): bp = self._getArg(args, [type(''),type({}),], kwargs, ['cfg',], self.lastBp) @@ -281,12 +281,12 @@ def _tc(self, *args, **kwargs): bp = {'cfg':bp} bp = {'cfg':bp.get('cfg')} newEnabled = self.toggleConfig(bp['cfg']) - print "'%s' is now %s."%(self.bpMan.bpToPath(bp),choice(newEnabled,'enabled','disabled'),) + print("'%s' is now %s."%(self.bpMan.bpToPath(bp),choice(newEnabled,'enabled','disabled'),)) def _z(self, *args, **kwargs): bp = self._getArg(args, [type(''),type({}),], kwargs, ['path','bp','name',], self.lastBp) self.bpMan.resetBp(bp) - print "'%s' has been reset."%(self.bpMan.partsToPath(bp),) + print("'%s' has been reset."%(self.bpMan.partsToPath(bp),)) def _zg(self, *args, **kwargs): bp = self._getArg(args, [type(''),type({}),], kwargs, ['grp',], self.lastBp) @@ -294,7 +294,7 @@ def _zg(self, *args, **kwargs): bp = {'grp':bp} bp = {'grp':bp.get('grp')} self.bpMan.resetBp(bp) - print "'%s' has been reset."%(self.bpMan.partsToPath(bp),) + print("'%s' has been reset."%(self.bpMan.partsToPath(bp),)) def _zc(self, *args, **kwargs): bp = self._getArg(args, [type(''),type({}),], kwargs, ['cfg',], self.lastBp) @@ -302,7 +302,7 @@ def _zc(self, *args, **kwargs): bp = {'cfg':bp} bp = {'cfg':bp.get('cfg')} self.resetConfig(bp['cfg']) - print "'%s' has been reset."%(self.bpMan.bpToPath(bp),) + print("'%s' has been reset."%(self.bpMan.bpToPath(bp),)) def _getArg(self, args, goodTypes, kwargs, goodKeys, default = None): #look for desired arg in args and kwargs lists @@ -436,9 +436,9 @@ def wrap(*args, **kwds): dbp.maybeBreak(test=test,frameCount=frameCount+1,displayPrefix='Exited ') return f_result - wrap.func_name = f.func_name - wrap.func_dict = f.func_dict - wrap.func_doc = f.func_doc + wrap.__name__ = f.__name__ + wrap.__dict__ = f.__dict__ + wrap.__doc__ = f.__doc__ wrap.__module__ = f.__module__ return wrap @@ -474,7 +474,7 @@ def functor(*cArgs, **ckArgs): #deprecated: @staticmethod def bpGroup(*args, **kArgs): - print "BpDb.bpGroup is deprecated, use bpdb.bpPreset instead" + print("BpDb.bpGroup is deprecated, use bpdb.bpPreset instead") kwArgs = {} kwArgs.update(kArgs) kwArgs['frameCount'] = kArgs.get('frameCount', 1) + 1 @@ -514,7 +514,7 @@ def getParts(self): def displayContextHint(self, displayPrefix=''): contextString = displayPrefix + bpdb.bpMan.partsToPath({'id':self.id,'grp':self.grp,'cfg':self.cfg}) dashes = '-'*max(0, (80 - len(contextString) - 4) / 2) - print '<%s %s %s>'%(dashes,contextString,dashes) + print('<%s %s %s>'%(dashes,contextString,dashes)) def maybeBreak(self, test=None, frameCount=1, displayPrefix=''): if self.shouldBreak(test=test): diff --git a/toontown/pandautils/ElementTree.py b/toontown/pandautils/ElementTree.py index 4e52ff239..4cf652fcb 100644 --- a/toontown/pandautils/ElementTree.py +++ b/toontown/pandautils/ElementTree.py @@ -389,7 +389,7 @@ def set(self, key, value): # @defreturn list of strings def keys(self): - return self.attrib.keys() + return list(self.attrib.keys()) ## # Gets element attributes, as a sequence. The attributes are @@ -399,7 +399,7 @@ def keys(self): # @defreturn list of (string, string) tuples def items(self): - return self.attrib.items() + return list(self.attrib.items()) ## # Creates a tree iterator. The iterator loops over this element @@ -667,7 +667,7 @@ def _write(self, file, node, encoding, namespaces): elif tag is ProcessingInstruction: file.write("" % _escape_cdata(node.text, encoding)) else: - items = node.items() + items = list(node.items()) xmlns_items = [] # new namespaces in this scope try: if isinstance(tag, QName) or tag[:1] == "{": @@ -749,7 +749,7 @@ def _encode(s, encoding): except AttributeError: return s # 1.5.2: assume the string uses the right encoding -_escape = re.compile(u"[&<>\"\u0080-\uffff]+") +_escape = re.compile("[&<>\"\u0080-\uffff]+") _escape_map = { "&": "&", @@ -912,7 +912,7 @@ def handler(prefix, event=event, append=append): append((event, None)) parser.EndNamespaceDeclHandler = handler - def next(self): + def __next__(self): while 1: try: item = self._events[self._index] @@ -942,7 +942,7 @@ def __iter__(self): return self except NameError: def __getitem__(self, index): - return self.next() + return next(self) ## # Parses an XML document from a string constant. This function can @@ -1162,7 +1162,7 @@ def _start(self, tag, attrib_in): fixname = self._fixname tag = fixname(tag) attrib = {} - for key, value in attrib_in.items(): + for key, value in list(attrib_in.items()): attrib[fixname(key)] = self._fixtext(value) return self._target.start(tag, attrib) diff --git a/toontown/pandautils/yaml/__init__.py b/toontown/pandautils/yaml/__init__.py index 76e19e13f..d3e57381d 100644 --- a/toontown/pandautils/yaml/__init__.py +++ b/toontown/pandautils/yaml/__init__.py @@ -1,17 +1,17 @@ -from error import * +from .error import * -from tokens import * -from events import * -from nodes import * +from .tokens import * +from .events import * +from .nodes import * -from loader import * -from dumper import * +from .loader import * +from .dumper import * __version__ = '3.11' try: - from cyaml import * + from .cyaml import * __with_libyaml__ = True except ImportError: __with_libyaml__ = False @@ -109,7 +109,7 @@ def emit(events, stream=None, Dumper=Dumper, """ getvalue = None if stream is None: - from StringIO import StringIO + from io import StringIO stream = StringIO() getvalue = stream.getvalue dumper = Dumper(stream, canonical=canonical, indent=indent, width=width, @@ -134,9 +134,9 @@ def serialize_all(nodes, stream=None, Dumper=Dumper, getvalue = None if stream is None: if encoding is None: - from StringIO import StringIO + from io import StringIO else: - from cStringIO import StringIO + from io import StringIO stream = StringIO() getvalue = stream.getvalue dumper = Dumper(stream, canonical=canonical, indent=indent, width=width, @@ -173,9 +173,9 @@ def dump_all(documents, stream=None, Dumper=Dumper, getvalue = None if stream is None: if encoding is None: - from StringIO import StringIO + from io import StringIO else: - from cStringIO import StringIO + from io import StringIO stream = StringIO() getvalue = stream.getvalue dumper = Dumper(stream, default_style=default_style, @@ -283,13 +283,11 @@ def __init__(cls, name, bases, kwds): cls.yaml_loader.add_constructor(cls.yaml_tag, cls.from_yaml) cls.yaml_dumper.add_representer(cls, cls.to_yaml) -class YAMLObject(object): +class YAMLObject(object, metaclass=YAMLObjectMetaclass): """ An object that can dump itself to a YAML stream and load itself from a YAML stream. """ - - __metaclass__ = YAMLObjectMetaclass __slots__ = () # no direct instantiation, so allow immutable subclasses yaml_loader = Loader diff --git a/toontown/pandautils/yaml/composer.py b/toontown/pandautils/yaml/composer.py index 06e5ac782..e0b71c4d1 100644 --- a/toontown/pandautils/yaml/composer.py +++ b/toontown/pandautils/yaml/composer.py @@ -1,9 +1,9 @@ __all__ = ['Composer', 'ComposerError'] -from error import MarkedYAMLError -from events import * -from nodes import * +from .error import MarkedYAMLError +from .events import * +from .nodes import * class ComposerError(MarkedYAMLError): pass @@ -88,7 +88,7 @@ def compose_node(self, parent, index): def compose_scalar_node(self, anchor): event = self.get_event() tag = event.tag - if tag is None or tag == u'!': + if tag is None or tag == '!': tag = self.resolve(ScalarNode, event.value, event.implicit) node = ScalarNode(tag, event.value, event.start_mark, event.end_mark, style=event.style) @@ -99,7 +99,7 @@ def compose_scalar_node(self, anchor): def compose_sequence_node(self, anchor): start_event = self.get_event() tag = start_event.tag - if tag is None or tag == u'!': + if tag is None or tag == '!': tag = self.resolve(SequenceNode, None, start_event.implicit) node = SequenceNode(tag, [], start_event.start_mark, None, @@ -117,7 +117,7 @@ def compose_sequence_node(self, anchor): def compose_mapping_node(self, anchor): start_event = self.get_event() tag = start_event.tag - if tag is None or tag == u'!': + if tag is None or tag == '!': tag = self.resolve(MappingNode, None, start_event.implicit) node = MappingNode(tag, [], start_event.start_mark, None, diff --git a/toontown/pandautils/yaml/constructor.py b/toontown/pandautils/yaml/constructor.py index 635faac3e..1eb27cd3e 100644 --- a/toontown/pandautils/yaml/constructor.py +++ b/toontown/pandautils/yaml/constructor.py @@ -2,8 +2,8 @@ __all__ = ['BaseConstructor', 'SafeConstructor', 'Constructor', 'ConstructorError'] -from error import * -from nodes import * +from .error import * +from .nodes import * import datetime @@ -90,7 +90,7 @@ def construct_object(self, node, deep=False): data = constructor(self, tag_suffix, node) if isinstance(data, types.GeneratorType): generator = data - data = generator.next() + data = next(generator) if self.deep_construct: for dummy in generator: pass @@ -127,7 +127,7 @@ def construct_mapping(self, node, deep=False): key = self.construct_object(key_node, deep=deep) try: hash(key) - except TypeError, exc: + except TypeError as exc: raise ConstructorError("while constructing a mapping", node.start_mark, "found unacceptable key (%s)" % exc, key_node.start_mark) value = self.construct_object(value_node, deep=deep) @@ -163,7 +163,7 @@ class SafeConstructor(BaseConstructor): def construct_scalar(self, node): if isinstance(node, MappingNode): for key_node, value_node in node.value: - if key_node.tag == u'tag:yaml.org,2002:value': + if key_node.tag == 'tag:yaml.org,2002:value': return self.construct_scalar(value_node) return BaseConstructor.construct_scalar(self, node) @@ -172,7 +172,7 @@ def flatten_mapping(self, node): index = 0 while index < len(node.value): key_node, value_node = node.value[index] - if key_node.tag == u'tag:yaml.org,2002:merge': + if key_node.tag == 'tag:yaml.org,2002:merge': del node.value[index] if isinstance(value_node, MappingNode): self.flatten_mapping(value_node) @@ -194,8 +194,8 @@ def flatten_mapping(self, node): raise ConstructorError("while constructing a mapping", node.start_mark, "expected a mapping or list of mappings for merging, but found %s" % value_node.id, value_node.start_mark) - elif key_node.tag == u'tag:yaml.org,2002:value': - key_node.tag = u'tag:yaml.org,2002:str' + elif key_node.tag == 'tag:yaml.org,2002:value': + key_node.tag = 'tag:yaml.org,2002:str' index += 1 else: index += 1 @@ -212,12 +212,12 @@ def construct_yaml_null(self, node): return None bool_values = { - u'yes': True, - u'no': False, - u'true': True, - u'false': False, - u'on': True, - u'off': False, + 'yes': True, + 'no': False, + 'true': True, + 'false': False, + 'on': True, + 'off': False, } def construct_yaml_bool(self, node): @@ -285,12 +285,12 @@ def construct_yaml_binary(self, node): value = self.construct_scalar(node) try: return str(value).decode('base64') - except (binascii.Error, UnicodeEncodeError), exc: + except (binascii.Error, UnicodeEncodeError) as exc: raise ConstructorError(None, None, "failed to decode base64 data: %s" % exc, node.start_mark) timestamp_regexp = re.compile( - ur'''^(?P[0-9][0-9][0-9][0-9]) + r'''^(?P[0-9][0-9][0-9][0-9]) -(?P[0-9][0-9]?) -(?P[0-9][0-9]?) (?:(?:[Tt]|[ \t]+) @@ -414,51 +414,51 @@ def construct_undefined(self, node): node.start_mark) SafeConstructor.add_constructor( - u'tag:yaml.org,2002:null', + 'tag:yaml.org,2002:null', SafeConstructor.construct_yaml_null) SafeConstructor.add_constructor( - u'tag:yaml.org,2002:bool', + 'tag:yaml.org,2002:bool', SafeConstructor.construct_yaml_bool) SafeConstructor.add_constructor( - u'tag:yaml.org,2002:int', + 'tag:yaml.org,2002:int', SafeConstructor.construct_yaml_int) SafeConstructor.add_constructor( - u'tag:yaml.org,2002:float', + 'tag:yaml.org,2002:float', SafeConstructor.construct_yaml_float) SafeConstructor.add_constructor( - u'tag:yaml.org,2002:binary', + 'tag:yaml.org,2002:binary', SafeConstructor.construct_yaml_binary) SafeConstructor.add_constructor( - u'tag:yaml.org,2002:timestamp', + 'tag:yaml.org,2002:timestamp', SafeConstructor.construct_yaml_timestamp) SafeConstructor.add_constructor( - u'tag:yaml.org,2002:omap', + 'tag:yaml.org,2002:omap', SafeConstructor.construct_yaml_omap) SafeConstructor.add_constructor( - u'tag:yaml.org,2002:pairs', + 'tag:yaml.org,2002:pairs', SafeConstructor.construct_yaml_pairs) SafeConstructor.add_constructor( - u'tag:yaml.org,2002:set', + 'tag:yaml.org,2002:set', SafeConstructor.construct_yaml_set) SafeConstructor.add_constructor( - u'tag:yaml.org,2002:str', + 'tag:yaml.org,2002:str', SafeConstructor.construct_yaml_str) SafeConstructor.add_constructor( - u'tag:yaml.org,2002:seq', + 'tag:yaml.org,2002:seq', SafeConstructor.construct_yaml_seq) SafeConstructor.add_constructor( - u'tag:yaml.org,2002:map', + 'tag:yaml.org,2002:map', SafeConstructor.construct_yaml_map) SafeConstructor.add_constructor(None, @@ -473,7 +473,7 @@ def construct_python_unicode(self, node): return self.construct_scalar(node) def construct_python_long(self, node): - return long(self.construct_yaml_int(node)) + return int(self.construct_yaml_int(node)) def construct_python_complex(self, node): return complex(self.construct_scalar(node)) @@ -487,7 +487,7 @@ def find_python_module(self, name, mark): "expected non-empty name appended to the tag", mark) try: __import__(name) - except ImportError, exc: + except ImportError as exc: raise ConstructorError("while constructing a Python module", mark, "cannot find module %r (%s)" % (name.encode('utf-8'), exc), mark) return sys.modules[name] @@ -496,14 +496,14 @@ def find_python_name(self, name, mark): if not name: raise ConstructorError("while constructing a Python object", mark, "expected non-empty name appended to the tag", mark) - if u'.' in name: + if '.' in name: module_name, object_name = name.rsplit('.', 1) else: module_name = '__builtin__' object_name = name try: __import__(module_name) - except ImportError, exc: + except ImportError as exc: raise ConstructorError("while constructing a Python object", mark, "cannot find module %r (%s)" % (module_name.encode('utf-8'), exc), mark) module = sys.modules[module_name] @@ -559,7 +559,7 @@ def set_python_instance_state(self, instance, state): instance.__dict__.update(state) elif state: slotstate.update(state) - for key, value in slotstate.items(): + for key, value in list(slotstate.items()): setattr(object, key, value) def construct_python_object(self, suffix, node): @@ -610,66 +610,66 @@ def construct_python_object_new(self, suffix, node): return self.construct_python_object_apply(suffix, node, newobj=True) Constructor.add_constructor( - u'tag:yaml.org,2002:python/none', + 'tag:yaml.org,2002:python/none', Constructor.construct_yaml_null) Constructor.add_constructor( - u'tag:yaml.org,2002:python/bool', + 'tag:yaml.org,2002:python/bool', Constructor.construct_yaml_bool) Constructor.add_constructor( - u'tag:yaml.org,2002:python/str', + 'tag:yaml.org,2002:python/str', Constructor.construct_python_str) Constructor.add_constructor( - u'tag:yaml.org,2002:python/unicode', + 'tag:yaml.org,2002:python/unicode', Constructor.construct_python_unicode) Constructor.add_constructor( - u'tag:yaml.org,2002:python/int', + 'tag:yaml.org,2002:python/int', Constructor.construct_yaml_int) Constructor.add_constructor( - u'tag:yaml.org,2002:python/long', + 'tag:yaml.org,2002:python/long', Constructor.construct_python_long) Constructor.add_constructor( - u'tag:yaml.org,2002:python/float', + 'tag:yaml.org,2002:python/float', Constructor.construct_yaml_float) Constructor.add_constructor( - u'tag:yaml.org,2002:python/complex', + 'tag:yaml.org,2002:python/complex', Constructor.construct_python_complex) Constructor.add_constructor( - u'tag:yaml.org,2002:python/list', + 'tag:yaml.org,2002:python/list', Constructor.construct_yaml_seq) Constructor.add_constructor( - u'tag:yaml.org,2002:python/tuple', + 'tag:yaml.org,2002:python/tuple', Constructor.construct_python_tuple) Constructor.add_constructor( - u'tag:yaml.org,2002:python/dict', + 'tag:yaml.org,2002:python/dict', Constructor.construct_yaml_map) Constructor.add_multi_constructor( - u'tag:yaml.org,2002:python/name:', + 'tag:yaml.org,2002:python/name:', Constructor.construct_python_name) Constructor.add_multi_constructor( - u'tag:yaml.org,2002:python/module:', + 'tag:yaml.org,2002:python/module:', Constructor.construct_python_module) Constructor.add_multi_constructor( - u'tag:yaml.org,2002:python/object:', + 'tag:yaml.org,2002:python/object:', Constructor.construct_python_object) Constructor.add_multi_constructor( - u'tag:yaml.org,2002:python/object/apply:', + 'tag:yaml.org,2002:python/object/apply:', Constructor.construct_python_object_apply) Constructor.add_multi_constructor( - u'tag:yaml.org,2002:python/object/new:', + 'tag:yaml.org,2002:python/object/new:', Constructor.construct_python_object_new) diff --git a/toontown/pandautils/yaml/cyaml.py b/toontown/pandautils/yaml/cyaml.py index 68dcd7519..d5cb87e99 100644 --- a/toontown/pandautils/yaml/cyaml.py +++ b/toontown/pandautils/yaml/cyaml.py @@ -4,12 +4,12 @@ from _yaml import CParser, CEmitter -from constructor import * +from .constructor import * -from serializer import * -from representer import * +from .serializer import * +from .representer import * -from resolver import * +from .resolver import * class CBaseLoader(CParser, BaseConstructor, BaseResolver): diff --git a/toontown/pandautils/yaml/dumper.py b/toontown/pandautils/yaml/dumper.py index f811d2c91..0b6912877 100644 --- a/toontown/pandautils/yaml/dumper.py +++ b/toontown/pandautils/yaml/dumper.py @@ -1,10 +1,10 @@ __all__ = ['BaseDumper', 'SafeDumper', 'Dumper'] -from emitter import * -from serializer import * -from representer import * -from resolver import * +from .emitter import * +from .serializer import * +from .representer import * +from .resolver import * class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver): diff --git a/toontown/pandautils/yaml/emitter.py b/toontown/pandautils/yaml/emitter.py index e5bcdcccb..3b6e3e211 100644 --- a/toontown/pandautils/yaml/emitter.py +++ b/toontown/pandautils/yaml/emitter.py @@ -8,8 +8,8 @@ __all__ = ['Emitter', 'EmitterError'] -from error import YAMLError -from events import * +from .error import YAMLError +from .events import * class EmitterError(YAMLError): pass @@ -31,8 +31,8 @@ def __init__(self, scalar, empty, multiline, class Emitter(object): DEFAULT_TAG_PREFIXES = { - u'!' : u'!', - u'tag:yaml.org,2002:' : u'!!', + '!' : '!', + 'tag:yaml.org,2002:' : '!!', } def __init__(self, stream, canonical=None, indent=None, width=None, @@ -88,8 +88,8 @@ def __init__(self, stream, canonical=None, indent=None, width=None, self.best_width = 80 if width and width > self.best_indent*2: self.best_width = width - self.best_line_break = u'\n' - if line_break in [u'\r', u'\n', u'\r\n']: + self.best_line_break = '\n' + if line_break in ['\r', '\n', '\r\n']: self.best_line_break = line_break # Tag prefixes. @@ -178,14 +178,14 @@ def expect_first_document_start(self): def expect_document_start(self, first=False): if isinstance(self.event, DocumentStartEvent): if (self.event.version or self.event.tags) and self.open_ended: - self.write_indicator(u'...', True) + self.write_indicator('...', True) self.write_indent() if self.event.version: version_text = self.prepare_version(self.event.version) self.write_version_directive(version_text) self.tag_prefixes = self.DEFAULT_TAG_PREFIXES.copy() if self.event.tags: - handles = self.event.tags.keys() + handles = list(self.event.tags.keys()) handles.sort() for handle in handles: prefix = self.event.tags[handle] @@ -198,13 +198,13 @@ def expect_document_start(self, first=False): and not self.check_empty_document()) if not implicit: self.write_indent() - self.write_indicator(u'---', True) + self.write_indicator('---', True) if self.canonical: self.write_indent() self.state = self.expect_document_root elif isinstance(self.event, StreamEndEvent): if self.open_ended: - self.write_indicator(u'...', True) + self.write_indicator('...', True) self.write_indent() self.write_stream_end() self.state = self.expect_nothing @@ -216,7 +216,7 @@ def expect_document_end(self): if isinstance(self.event, DocumentEndEvent): self.write_indent() if self.event.explicit: - self.write_indicator(u'...', True) + self.write_indicator('...', True) self.write_indent() self.flush_stream() self.state = self.expect_document_start @@ -239,7 +239,7 @@ def expect_node(self, root=False, sequence=False, mapping=False, if isinstance(self.event, AliasEvent): self.expect_alias() elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)): - self.process_anchor(u'&') + self.process_anchor('&') self.process_tag() if isinstance(self.event, ScalarEvent): self.expect_scalar() @@ -261,7 +261,7 @@ def expect_node(self, root=False, sequence=False, mapping=False, def expect_alias(self): if self.event.anchor is None: raise EmitterError("anchor is not specified for alias") - self.process_anchor(u'*') + self.process_anchor('*') self.state = self.states.pop() def expect_scalar(self): @@ -273,7 +273,7 @@ def expect_scalar(self): # Flow sequence handlers. def expect_flow_sequence(self): - self.write_indicator(u'[', True, whitespace=True) + self.write_indicator('[', True, whitespace=True) self.flow_level += 1 self.increase_indent(flow=True) self.state = self.expect_first_flow_sequence_item @@ -282,7 +282,7 @@ def expect_first_flow_sequence_item(self): if isinstance(self.event, SequenceEndEvent): self.indent = self.indents.pop() self.flow_level -= 1 - self.write_indicator(u']', False) + self.write_indicator(']', False) self.state = self.states.pop() else: if self.canonical or self.column > self.best_width: @@ -295,12 +295,12 @@ def expect_flow_sequence_item(self): self.indent = self.indents.pop() self.flow_level -= 1 if self.canonical: - self.write_indicator(u',', False) + self.write_indicator(',', False) self.write_indent() - self.write_indicator(u']', False) + self.write_indicator(']', False) self.state = self.states.pop() else: - self.write_indicator(u',', False) + self.write_indicator(',', False) if self.canonical or self.column > self.best_width: self.write_indent() self.states.append(self.expect_flow_sequence_item) @@ -309,7 +309,7 @@ def expect_flow_sequence_item(self): # Flow mapping handlers. def expect_flow_mapping(self): - self.write_indicator(u'{', True, whitespace=True) + self.write_indicator('{', True, whitespace=True) self.flow_level += 1 self.increase_indent(flow=True) self.state = self.expect_first_flow_mapping_key @@ -318,7 +318,7 @@ def expect_first_flow_mapping_key(self): if isinstance(self.event, MappingEndEvent): self.indent = self.indents.pop() self.flow_level -= 1 - self.write_indicator(u'}', False) + self.write_indicator('}', False) self.state = self.states.pop() else: if self.canonical or self.column > self.best_width: @@ -327,7 +327,7 @@ def expect_first_flow_mapping_key(self): self.states.append(self.expect_flow_mapping_simple_value) self.expect_node(mapping=True, simple_key=True) else: - self.write_indicator(u'?', True) + self.write_indicator('?', True) self.states.append(self.expect_flow_mapping_value) self.expect_node(mapping=True) @@ -336,31 +336,31 @@ def expect_flow_mapping_key(self): self.indent = self.indents.pop() self.flow_level -= 1 if self.canonical: - self.write_indicator(u',', False) + self.write_indicator(',', False) self.write_indent() - self.write_indicator(u'}', False) + self.write_indicator('}', False) self.state = self.states.pop() else: - self.write_indicator(u',', False) + self.write_indicator(',', False) if self.canonical or self.column > self.best_width: self.write_indent() if not self.canonical and self.check_simple_key(): self.states.append(self.expect_flow_mapping_simple_value) self.expect_node(mapping=True, simple_key=True) else: - self.write_indicator(u'?', True) + self.write_indicator('?', True) self.states.append(self.expect_flow_mapping_value) self.expect_node(mapping=True) def expect_flow_mapping_simple_value(self): - self.write_indicator(u':', False) + self.write_indicator(':', False) self.states.append(self.expect_flow_mapping_key) self.expect_node(mapping=True) def expect_flow_mapping_value(self): if self.canonical or self.column > self.best_width: self.write_indent() - self.write_indicator(u':', True) + self.write_indicator(':', True) self.states.append(self.expect_flow_mapping_key) self.expect_node(mapping=True) @@ -380,7 +380,7 @@ def expect_block_sequence_item(self, first=False): self.state = self.states.pop() else: self.write_indent() - self.write_indicator(u'-', True, indention=True) + self.write_indicator('-', True, indention=True) self.states.append(self.expect_block_sequence_item) self.expect_node(sequence=True) @@ -403,18 +403,18 @@ def expect_block_mapping_key(self, first=False): self.states.append(self.expect_block_mapping_simple_value) self.expect_node(mapping=True, simple_key=True) else: - self.write_indicator(u'?', True, indention=True) + self.write_indicator('?', True, indention=True) self.states.append(self.expect_block_mapping_value) self.expect_node(mapping=True) def expect_block_mapping_simple_value(self): - self.write_indicator(u':', False) + self.write_indicator(':', False) self.states.append(self.expect_block_mapping_key) self.expect_node(mapping=True) def expect_block_mapping_value(self): self.write_indent() - self.write_indicator(u':', True, indention=True) + self.write_indicator(':', True, indention=True) self.states.append(self.expect_block_mapping_key) self.expect_node(mapping=True) @@ -433,7 +433,7 @@ def check_empty_document(self): return False event = self.events[0] return (isinstance(event, ScalarEvent) and event.anchor is None - and event.tag is None and event.implicit and event.value == u'') + and event.tag is None and event.implicit and event.value == '') def check_simple_key(self): length = 0 @@ -478,7 +478,7 @@ def process_tag(self): self.prepared_tag = None return if self.event.implicit[0] and tag is None: - tag = u'!' + tag = '!' self.prepared_tag = None else: if (not self.canonical or tag is None) and self.event.implicit: @@ -541,17 +541,17 @@ def prepare_version(self, version): major, minor = version if major != 1: raise EmitterError("unsupported YAML version: %d.%d" % (major, minor)) - return u'%d.%d' % (major, minor) + return '%d.%d' % (major, minor) def prepare_tag_handle(self, handle): if not handle: raise EmitterError("tag handle must not be empty") - if handle[0] != u'!' or handle[-1] != u'!': + if handle[0] != '!' or handle[-1] != '!': raise EmitterError("tag handle must start and end with '!': %r" % (handle.encode('utf-8'))) for ch in handle[1:-1]: - if not (u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \ - or ch in u'-_'): + if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_'): raise EmitterError("invalid character %r in the tag handle: %r" % (ch.encode('utf-8'), handle.encode('utf-8'))) return handle @@ -561,12 +561,12 @@ def prepare_tag_prefix(self, prefix): raise EmitterError("tag prefix must not be empty") chunks = [] start = end = 0 - if prefix[0] == u'!': + if prefix[0] == '!': end = 1 while end < len(prefix): ch = prefix[end] - if u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \ - or ch in u'-;/?!:@&=+$,_.~*\'()[]': + if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-;/?!:@&=+$,_.~*\'()[]': end += 1 else: if start < end: @@ -574,32 +574,32 @@ def prepare_tag_prefix(self, prefix): start = end = end+1 data = ch.encode('utf-8') for ch in data: - chunks.append(u'%%%02X' % ord(ch)) + chunks.append('%%%02X' % ord(ch)) if start < end: chunks.append(prefix[start:end]) - return u''.join(chunks) + return ''.join(chunks) def prepare_tag(self, tag): if not tag: raise EmitterError("tag must not be empty") - if tag == u'!': + if tag == '!': return tag handle = None suffix = tag - prefixes = self.tag_prefixes.keys() + prefixes = list(self.tag_prefixes.keys()) prefixes.sort() for prefix in prefixes: if tag.startswith(prefix) \ - and (prefix == u'!' or len(prefix) < len(tag)): + and (prefix == '!' or len(prefix) < len(tag)): handle = self.tag_prefixes[prefix] suffix = tag[len(prefix):] chunks = [] start = end = 0 while end < len(suffix): ch = suffix[end] - if u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \ - or ch in u'-;/?:@&=+$,_.~*\'()[]' \ - or (ch == u'!' and handle != u'!'): + if '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-;/?:@&=+$,_.~*\'()[]' \ + or (ch == '!' and handle != '!'): end += 1 else: if start < end: @@ -607,21 +607,21 @@ def prepare_tag(self, tag): start = end = end+1 data = ch.encode('utf-8') for ch in data: - chunks.append(u'%%%02X' % ord(ch)) + chunks.append('%%%02X' % ord(ch)) if start < end: chunks.append(suffix[start:end]) - suffix_text = u''.join(chunks) + suffix_text = ''.join(chunks) if handle: - return u'%s%s' % (handle, suffix_text) + return '%s%s' % (handle, suffix_text) else: - return u'!<%s>' % suffix_text + return '!<%s>' % suffix_text def prepare_anchor(self, anchor): if not anchor: raise EmitterError("anchor must not be empty") for ch in anchor: - if not (u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \ - or ch in u'-_'): + if not ('0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_'): raise EmitterError("invalid character %r in the anchor: %r" % (ch.encode('utf-8'), anchor.encode('utf-8'))) return anchor @@ -650,7 +650,7 @@ def analyze_scalar(self, scalar): space_break = False # Check document indicators. - if scalar.startswith(u'---') or scalar.startswith(u'...'): + if scalar.startswith('---') or scalar.startswith('...'): block_indicators = True flow_indicators = True @@ -659,7 +659,7 @@ def analyze_scalar(self, scalar): # Last character or followed by a whitespace. followed_by_whitespace = (len(scalar) == 1 or - scalar[1] in u'\0 \t\r\n\x85\u2028\u2029') + scalar[1] in '\0 \t\r\n\x85\u2028\u2029') # The previous character is a space. previous_space = False @@ -674,34 +674,34 @@ def analyze_scalar(self, scalar): # Check for indicators. if index == 0: # Leading indicators are special characters. - if ch in u'#,[]{}&*!|>\'\"%@`': + if ch in '#,[]{}&*!|>\'\"%@`': flow_indicators = True block_indicators = True - if ch in u'?:': + if ch in '?:': flow_indicators = True if followed_by_whitespace: block_indicators = True - if ch == u'-' and followed_by_whitespace: + if ch == '-' and followed_by_whitespace: flow_indicators = True block_indicators = True else: # Some indicators cannot appear within a scalar as well. - if ch in u',?[]{}': + if ch in ',?[]{}': flow_indicators = True - if ch == u':': + if ch == ':': flow_indicators = True if followed_by_whitespace: block_indicators = True - if ch == u'#' and preceeded_by_whitespace: + if ch == '#' and preceeded_by_whitespace: flow_indicators = True block_indicators = True # Check for line breaks, special, and unicode characters. - if ch in u'\n\x85\u2028\u2029': + if ch in '\n\x85\u2028\u2029': line_breaks = True - if not (ch == u'\n' or u'\x20' <= ch <= u'\x7E'): - if (ch == u'\x85' or u'\xA0' <= ch <= u'\uD7FF' - or u'\uE000' <= ch <= u'\uFFFD') and ch != u'\uFEFF': + if not (ch == '\n' or '\x20' <= ch <= '\x7E'): + if (ch == '\x85' or '\xA0' <= ch <= '\uD7FF' + or '\uE000' <= ch <= '\uFFFD') and ch != '\uFEFF': unicode_characters = True if not self.allow_unicode: special_characters = True @@ -709,7 +709,7 @@ def analyze_scalar(self, scalar): special_characters = True # Detect important whitespace combinations. - if ch == u' ': + if ch == ' ': if index == 0: leading_space = True if index == len(scalar)-1: @@ -718,7 +718,7 @@ def analyze_scalar(self, scalar): break_space = True previous_space = True previous_break = False - elif ch in u'\n\x85\u2028\u2029': + elif ch in '\n\x85\u2028\u2029': if index == 0: leading_break = True if index == len(scalar)-1: @@ -733,9 +733,9 @@ def analyze_scalar(self, scalar): # Prepare for the next character. index += 1 - preceeded_by_whitespace = (ch in u'\0 \t\r\n\x85\u2028\u2029') + preceeded_by_whitespace = (ch in '\0 \t\r\n\x85\u2028\u2029') followed_by_whitespace = (index+1 >= len(scalar) or - scalar[index+1] in u'\0 \t\r\n\x85\u2028\u2029') + scalar[index+1] in '\0 \t\r\n\x85\u2028\u2029') # Let's decide what styles are allowed. allow_flow_plain = True @@ -794,7 +794,7 @@ def flush_stream(self): def write_stream_start(self): # Write BOM if needed. if self.encoding and self.encoding.startswith('utf-16'): - self.stream.write(u'\uFEFF'.encode(self.encoding)) + self.stream.write('\uFEFF'.encode(self.encoding)) def write_stream_end(self): self.flush_stream() @@ -804,7 +804,7 @@ def write_indicator(self, indicator, need_whitespace, if self.whitespace or not need_whitespace: data = indicator else: - data = u' '+indicator + data = ' '+indicator self.whitespace = whitespace self.indention = self.indention and indention self.column += len(data) @@ -820,7 +820,7 @@ def write_indent(self): self.write_line_break() if self.column < indent: self.whitespace = True - data = u' '*(indent-self.column) + data = ' '*(indent-self.column) self.column = indent if self.encoding: data = data.encode(self.encoding) @@ -838,14 +838,14 @@ def write_line_break(self, data=None): self.stream.write(data) def write_version_directive(self, version_text): - data = u'%%YAML %s' % version_text + data = '%%YAML %s' % version_text if self.encoding: data = data.encode(self.encoding) self.stream.write(data) self.write_line_break() def write_tag_directive(self, handle_text, prefix_text): - data = u'%%TAG %s %s' % (handle_text, prefix_text) + data = '%%TAG %s %s' % (handle_text, prefix_text) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) @@ -854,7 +854,7 @@ def write_tag_directive(self, handle_text, prefix_text): # Scalar streams. def write_single_quoted(self, text, split=True): - self.write_indicator(u'\'', True) + self.write_indicator('\'', True) spaces = False breaks = False start = end = 0 @@ -863,7 +863,7 @@ def write_single_quoted(self, text, split=True): if end < len(text): ch = text[end] if spaces: - if ch is None or ch != u' ': + if ch is None or ch != ' ': if start+1 == end and self.column > self.best_width and split \ and start != 0 and end != len(text): self.write_indent() @@ -875,18 +875,18 @@ def write_single_quoted(self, text, split=True): self.stream.write(data) start = end elif breaks: - if ch is None or ch not in u'\n\x85\u2028\u2029': - if text[start] == u'\n': + if ch is None or ch not in '\n\x85\u2028\u2029': + if text[start] == '\n': self.write_line_break() for br in text[start:end]: - if br == u'\n': + if br == '\n': self.write_line_break() else: self.write_line_break(br) self.write_indent() start = end else: - if ch is None or ch in u' \n\x85\u2028\u2029' or ch == u'\'': + if ch is None or ch in ' \n\x85\u2028\u2029' or ch == '\'': if start < end: data = text[start:end] self.column += len(data) @@ -894,49 +894,49 @@ def write_single_quoted(self, text, split=True): data = data.encode(self.encoding) self.stream.write(data) start = end - if ch == u'\'': - data = u'\'\'' + if ch == '\'': + data = '\'\'' self.column += 2 if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end + 1 if ch is not None: - spaces = (ch == u' ') - breaks = (ch in u'\n\x85\u2028\u2029') + spaces = (ch == ' ') + breaks = (ch in '\n\x85\u2028\u2029') end += 1 - self.write_indicator(u'\'', False) + self.write_indicator('\'', False) ESCAPE_REPLACEMENTS = { - u'\0': u'0', - u'\x07': u'a', - u'\x08': u'b', - u'\x09': u't', - u'\x0A': u'n', - u'\x0B': u'v', - u'\x0C': u'f', - u'\x0D': u'r', - u'\x1B': u'e', - u'\"': u'\"', - u'\\': u'\\', - u'\x85': u'N', - u'\xA0': u'_', - u'\u2028': u'L', - u'\u2029': u'P', + '\0': '0', + '\x07': 'a', + '\x08': 'b', + '\x09': 't', + '\x0A': 'n', + '\x0B': 'v', + '\x0C': 'f', + '\x0D': 'r', + '\x1B': 'e', + '\"': '\"', + '\\': '\\', + '\x85': 'N', + '\xA0': '_', + '\u2028': 'L', + '\u2029': 'P', } def write_double_quoted(self, text, split=True): - self.write_indicator(u'"', True) + self.write_indicator('"', True) start = end = 0 while end <= len(text): ch = None if end < len(text): ch = text[end] - if ch is None or ch in u'"\\\x85\u2028\u2029\uFEFF' \ - or not (u'\x20' <= ch <= u'\x7E' + if ch is None or ch in '"\\\x85\u2028\u2029\uFEFF' \ + or not ('\x20' <= ch <= '\x7E' or (self.allow_unicode - and (u'\xA0' <= ch <= u'\uD7FF' - or u'\uE000' <= ch <= u'\uFFFD'))): + and ('\xA0' <= ch <= '\uD7FF' + or '\uE000' <= ch <= '\uFFFD'))): if start < end: data = text[start:end] self.column += len(data) @@ -946,21 +946,21 @@ def write_double_quoted(self, text, split=True): start = end if ch is not None: if ch in self.ESCAPE_REPLACEMENTS: - data = u'\\'+self.ESCAPE_REPLACEMENTS[ch] - elif ch <= u'\xFF': - data = u'\\x%02X' % ord(ch) - elif ch <= u'\uFFFF': - data = u'\\u%04X' % ord(ch) + data = '\\'+self.ESCAPE_REPLACEMENTS[ch] + elif ch <= '\xFF': + data = '\\x%02X' % ord(ch) + elif ch <= '\uFFFF': + data = '\\u%04X' % ord(ch) else: - data = u'\\U%08X' % ord(ch) + data = '\\U%08X' % ord(ch) self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end+1 - if 0 < end < len(text)-1 and (ch == u' ' or start >= end) \ + if 0 < end < len(text)-1 and (ch == ' ' or start >= end) \ and self.column+(end-start) > self.best_width and split: - data = text[start:end]+u'\\' + data = text[start:end]+'\\' if start < end: start = end self.column += len(data) @@ -970,30 +970,30 @@ def write_double_quoted(self, text, split=True): self.write_indent() self.whitespace = False self.indention = False - if text[start] == u' ': - data = u'\\' + if text[start] == ' ': + data = '\\' self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) end += 1 - self.write_indicator(u'"', False) + self.write_indicator('"', False) def determine_block_hints(self, text): - hints = u'' + hints = '' if text: - if text[0] in u' \n\x85\u2028\u2029': - hints += unicode(self.best_indent) - if text[-1] not in u'\n\x85\u2028\u2029': - hints += u'-' - elif len(text) == 1 or text[-2] in u'\n\x85\u2028\u2029': - hints += u'+' + if text[0] in ' \n\x85\u2028\u2029': + hints += str(self.best_indent) + if text[-1] not in '\n\x85\u2028\u2029': + hints += '-' + elif len(text) == 1 or text[-2] in '\n\x85\u2028\u2029': + hints += '+' return hints def write_folded(self, text): hints = self.determine_block_hints(text) - self.write_indicator(u'>'+hints, True) - if hints[-1:] == u'+': + self.write_indicator('>'+hints, True) + if hints[-1:] == '+': self.open_ended = True self.write_line_break() leading_space = True @@ -1005,13 +1005,13 @@ def write_folded(self, text): if end < len(text): ch = text[end] if breaks: - if ch is None or ch not in u'\n\x85\u2028\u2029': - if not leading_space and ch is not None and ch != u' ' \ - and text[start] == u'\n': + if ch is None or ch not in '\n\x85\u2028\u2029': + if not leading_space and ch is not None and ch != ' ' \ + and text[start] == '\n': self.write_line_break() - leading_space = (ch == u' ') + leading_space = (ch == ' ') for br in text[start:end]: - if br == u'\n': + if br == '\n': self.write_line_break() else: self.write_line_break(br) @@ -1019,7 +1019,7 @@ def write_folded(self, text): self.write_indent() start = end elif spaces: - if ch != u' ': + if ch != ' ': if start+1 == end and self.column > self.best_width: self.write_indent() else: @@ -1030,7 +1030,7 @@ def write_folded(self, text): self.stream.write(data) start = end else: - if ch is None or ch in u' \n\x85\u2028\u2029': + if ch is None or ch in ' \n\x85\u2028\u2029': data = text[start:end] self.column += len(data) if self.encoding: @@ -1040,14 +1040,14 @@ def write_folded(self, text): self.write_line_break() start = end if ch is not None: - breaks = (ch in u'\n\x85\u2028\u2029') - spaces = (ch == u' ') + breaks = (ch in '\n\x85\u2028\u2029') + spaces = (ch == ' ') end += 1 def write_literal(self, text): hints = self.determine_block_hints(text) - self.write_indicator(u'|'+hints, True) - if hints[-1:] == u'+': + self.write_indicator('|'+hints, True) + if hints[-1:] == '+': self.open_ended = True self.write_line_break() breaks = True @@ -1057,9 +1057,9 @@ def write_literal(self, text): if end < len(text): ch = text[end] if breaks: - if ch is None or ch not in u'\n\x85\u2028\u2029': + if ch is None or ch not in '\n\x85\u2028\u2029': for br in text[start:end]: - if br == u'\n': + if br == '\n': self.write_line_break() else: self.write_line_break(br) @@ -1067,7 +1067,7 @@ def write_literal(self, text): self.write_indent() start = end else: - if ch is None or ch in u'\n\x85\u2028\u2029': + if ch is None or ch in '\n\x85\u2028\u2029': data = text[start:end] if self.encoding: data = data.encode(self.encoding) @@ -1076,7 +1076,7 @@ def write_literal(self, text): self.write_line_break() start = end if ch is not None: - breaks = (ch in u'\n\x85\u2028\u2029') + breaks = (ch in '\n\x85\u2028\u2029') end += 1 def write_plain(self, text, split=True): @@ -1085,7 +1085,7 @@ def write_plain(self, text, split=True): if not text: return if not self.whitespace: - data = u' ' + data = ' ' self.column += len(data) if self.encoding: data = data.encode(self.encoding) @@ -1100,7 +1100,7 @@ def write_plain(self, text, split=True): if end < len(text): ch = text[end] if spaces: - if ch != u' ': + if ch != ' ': if start+1 == end and self.column > self.best_width and split: self.write_indent() self.whitespace = False @@ -1113,11 +1113,11 @@ def write_plain(self, text, split=True): self.stream.write(data) start = end elif breaks: - if ch not in u'\n\x85\u2028\u2029': - if text[start] == u'\n': + if ch not in '\n\x85\u2028\u2029': + if text[start] == '\n': self.write_line_break() for br in text[start:end]: - if br == u'\n': + if br == '\n': self.write_line_break() else: self.write_line_break(br) @@ -1126,7 +1126,7 @@ def write_plain(self, text, split=True): self.indention = False start = end else: - if ch is None or ch in u' \n\x85\u2028\u2029': + if ch is None or ch in ' \n\x85\u2028\u2029': data = text[start:end] self.column += len(data) if self.encoding: @@ -1134,7 +1134,7 @@ def write_plain(self, text, split=True): self.stream.write(data) start = end if ch is not None: - spaces = (ch == u' ') - breaks = (ch in u'\n\x85\u2028\u2029') + spaces = (ch == ' ') + breaks = (ch in '\n\x85\u2028\u2029') end += 1 diff --git a/toontown/pandautils/yaml/error.py b/toontown/pandautils/yaml/error.py index 577686db5..e68d5f452 100644 --- a/toontown/pandautils/yaml/error.py +++ b/toontown/pandautils/yaml/error.py @@ -16,7 +16,7 @@ def get_snippet(self, indent=4, max_length=75): return None head = '' start = self.pointer - while start > 0 and self.buffer[start-1] not in u'\0\r\n\x85\u2028\u2029': + while start > 0 and self.buffer[start-1] not in '\0\r\n\x85\u2028\u2029': start -= 1 if self.pointer-start > max_length/2-1: head = ' ... ' @@ -24,7 +24,7 @@ def get_snippet(self, indent=4, max_length=75): break tail = '' end = self.pointer - while end < len(self.buffer) and self.buffer[end] not in u'\0\r\n\x85\u2028\u2029': + while end < len(self.buffer) and self.buffer[end] not in '\0\r\n\x85\u2028\u2029': end += 1 if end-self.pointer > max_length/2-1: tail = ' ... ' diff --git a/toontown/pandautils/yaml/loader.py b/toontown/pandautils/yaml/loader.py index 293ff467b..08c8f01b3 100644 --- a/toontown/pandautils/yaml/loader.py +++ b/toontown/pandautils/yaml/loader.py @@ -1,12 +1,12 @@ __all__ = ['BaseLoader', 'SafeLoader', 'Loader'] -from reader import * -from scanner import * -from parser import * -from composer import * -from constructor import * -from resolver import * +from .reader import * +from .scanner import * +from .parser import * +from .composer import * +from .constructor import * +from .resolver import * class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver): diff --git a/toontown/pandautils/yaml/parser.py b/toontown/pandautils/yaml/parser.py index f9e3057f3..e8d7751e9 100644 --- a/toontown/pandautils/yaml/parser.py +++ b/toontown/pandautils/yaml/parser.py @@ -61,10 +61,10 @@ __all__ = ['Parser', 'ParserError'] -from error import MarkedYAMLError -from tokens import * -from events import * -from scanner import * +from .error import MarkedYAMLError +from .tokens import * +from .events import * +from .scanner import * class ParserError(MarkedYAMLError): pass @@ -74,8 +74,8 @@ class Parser(object): # do not give many comments here. DEFAULT_TAGS = { - u'!': u'!', - u'!!': u'tag:yaml.org,2002:', + '!': '!', + '!!': 'tag:yaml.org,2002:', } def __init__(self): @@ -219,7 +219,7 @@ def process_directives(self): self.tag_handles = {} while self.check_token(DirectiveToken): token = self.get_token() - if token.name == u'YAML': + if token.name == 'YAML': if self.yaml_version is not None: raise ParserError(None, None, "found duplicate YAML directive", token.start_mark) @@ -229,7 +229,7 @@ def process_directives(self): "found incompatible YAML document (version 1.* is required)", token.start_mark) self.yaml_version = token.value - elif token.name == u'TAG': + elif token.name == 'TAG': handle, prefix = token.value if handle in self.tag_handles: raise ParserError(None, None, @@ -315,7 +315,7 @@ def parse_node(self, block=False, indentless_sequence=False): if start_mark is None: start_mark = end_mark = self.peek_token().start_mark event = None - implicit = (tag is None or tag == u'!') + implicit = (tag is None or tag == '!') if indentless_sequence and self.check_token(BlockEntryToken): end_mark = self.peek_token().end_mark event = SequenceStartEvent(anchor, tag, implicit, @@ -325,7 +325,7 @@ def parse_node(self, block=False, indentless_sequence=False): if self.check_token(ScalarToken): token = self.get_token() end_mark = token.end_mark - if (token.plain and tag is None) or tag == u'!': + if (token.plain and tag is None) or tag == '!': implicit = (True, False) elif tag is None: implicit = (False, True) @@ -357,7 +357,7 @@ def parse_node(self, block=False, indentless_sequence=False): elif anchor is not None or tag is not None: # Empty scalars are allowed even if a tag or an anchor is # specified. - event = ScalarEvent(anchor, tag, (implicit, False), u'', + event = ScalarEvent(anchor, tag, (implicit, False), '', start_mark, end_mark) self.state = self.states.pop() else: @@ -585,5 +585,5 @@ def parse_flow_mapping_empty_value(self): return self.process_empty_scalar(self.peek_token().start_mark) def process_empty_scalar(self, mark): - return ScalarEvent(None, None, (True, False), u'', mark, mark) + return ScalarEvent(None, None, (True, False), '', mark, mark) diff --git a/toontown/pandautils/yaml/reader.py b/toontown/pandautils/yaml/reader.py index 3249e6b9f..c6d98ff1a 100644 --- a/toontown/pandautils/yaml/reader.py +++ b/toontown/pandautils/yaml/reader.py @@ -17,7 +17,7 @@ __all__ = ['Reader', 'ReaderError'] -from error import YAMLError, Mark +from .error import YAMLError, Mark import codecs, re @@ -61,7 +61,7 @@ def __init__(self, stream): self.stream = None self.stream_pointer = 0 self.eof = True - self.buffer = u'' + self.buffer = '' self.pointer = 0 self.raw_buffer = None self.raw_decode = None @@ -69,10 +69,10 @@ def __init__(self, stream): self.index = 0 self.line = 0 self.column = 0 - if isinstance(stream, unicode): + if isinstance(stream, str): self.name = "" self.check_printable(stream) - self.buffer = stream+u'\0' + self.buffer = stream+'\0' elif isinstance(stream, str): self.name = "" self.raw_buffer = stream @@ -103,11 +103,11 @@ def forward(self, length=1): ch = self.buffer[self.pointer] self.pointer += 1 self.index += 1 - if ch in u'\n\x85\u2028\u2029' \ - or (ch == u'\r' and self.buffer[self.pointer] != u'\n'): + if ch in '\n\x85\u2028\u2029' \ + or (ch == '\r' and self.buffer[self.pointer] != '\n'): self.line += 1 self.column = 0 - elif ch != u'\uFEFF': + elif ch != '\uFEFF': self.column += 1 length -= 1 @@ -122,7 +122,7 @@ def get_mark(self): def determine_encoding(self): while not self.eof and len(self.raw_buffer) < 2: self.update_raw() - if not isinstance(self.raw_buffer, unicode): + if not isinstance(self.raw_buffer, str): if self.raw_buffer.startswith(codecs.BOM_UTF16_LE): self.raw_decode = codecs.utf_16_le_decode self.encoding = 'utf-16-le' @@ -134,7 +134,7 @@ def determine_encoding(self): self.encoding = 'utf-8' self.update(1) - NON_PRINTABLE = re.compile(u'[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD]') + NON_PRINTABLE = re.compile('[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD]') def check_printable(self, data): match = self.NON_PRINTABLE.search(data) if match: @@ -155,7 +155,7 @@ def update(self, length): try: data, converted = self.raw_decode(self.raw_buffer, 'strict', self.eof) - except UnicodeDecodeError, exc: + except UnicodeDecodeError as exc: character = exc.object[exc.start] if self.stream is not None: position = self.stream_pointer-len(self.raw_buffer)+exc.start @@ -170,7 +170,7 @@ def update(self, length): self.buffer += data self.raw_buffer = self.raw_buffer[converted:] if self.eof: - self.buffer += u'\0' + self.buffer += '\0' self.raw_buffer = None break diff --git a/toontown/pandautils/yaml/representer.py b/toontown/pandautils/yaml/representer.py index 5f4fc70db..de4398c21 100644 --- a/toontown/pandautils/yaml/representer.py +++ b/toontown/pandautils/yaml/representer.py @@ -2,12 +2,12 @@ __all__ = ['BaseRepresenter', 'SafeRepresenter', 'Representer', 'RepresenterError'] -from error import * -from nodes import * +from .error import * +from .nodes import * import datetime -import sys, copy_reg, types +import sys, copyreg, types class RepresenterError(YAMLError): pass @@ -66,7 +66,7 @@ def represent_data(self, data): elif None in self.yaml_representers: node = self.yaml_representers[None](self, data) else: - node = ScalarNode(None, unicode(data)) + node = ScalarNode(None, str(data)) #if alias_key is not None: # self.represented_objects[alias_key] = node return node @@ -116,7 +116,7 @@ def represent_mapping(self, tag, mapping, flow_style=None): self.represented_objects[self.alias_key] = node best_style = True if hasattr(mapping, 'items'): - mapping = mapping.items() + mapping = list(mapping.items()) mapping.sort() for item_key, item_value in mapping: node_key = self.represent_data(item_key) @@ -141,44 +141,44 @@ class SafeRepresenter(BaseRepresenter): def ignore_aliases(self, data): if data in [None, ()]: return True - if isinstance(data, (str, unicode, bool, int, float)): + if isinstance(data, (str, bool, int, float)): return True def represent_none(self, data): - return self.represent_scalar(u'tag:yaml.org,2002:null', - u'null') + return self.represent_scalar('tag:yaml.org,2002:null', + 'null') def represent_str(self, data): tag = None style = None try: - data = unicode(data, 'ascii') - tag = u'tag:yaml.org,2002:str' + data = str(data, 'ascii') + tag = 'tag:yaml.org,2002:str' except UnicodeDecodeError: try: - data = unicode(data, 'utf-8') - tag = u'tag:yaml.org,2002:str' + data = str(data, 'utf-8') + tag = 'tag:yaml.org,2002:str' except UnicodeDecodeError: data = data.encode('base64') - tag = u'tag:yaml.org,2002:binary' + tag = 'tag:yaml.org,2002:binary' style = '|' return self.represent_scalar(tag, data, style=style) def represent_unicode(self, data): - return self.represent_scalar(u'tag:yaml.org,2002:str', data) + return self.represent_scalar('tag:yaml.org,2002:str', data) def represent_bool(self, data): if data: - value = u'true' + value = 'true' else: - value = u'false' - return self.represent_scalar(u'tag:yaml.org,2002:bool', value) + value = 'false' + return self.represent_scalar('tag:yaml.org,2002:bool', value) def represent_int(self, data): - return self.represent_scalar(u'tag:yaml.org,2002:int', unicode(data)) + return self.represent_scalar('tag:yaml.org,2002:int', str(data)) def represent_long(self, data): - return self.represent_scalar(u'tag:yaml.org,2002:int', unicode(data)) + return self.represent_scalar('tag:yaml.org,2002:int', str(data)) inf_value = 1e300 while repr(inf_value) != repr(inf_value*inf_value): @@ -186,13 +186,13 @@ def represent_long(self, data): def represent_float(self, data): if data != data or (data == 0.0 and data == 1.0): - value = u'.nan' + value = '.nan' elif data == self.inf_value: - value = u'.inf' + value = '.inf' elif data == -self.inf_value: - value = u'-.inf' + value = '-.inf' else: - value = unicode(repr(data)).lower() + value = str(repr(data)).lower() # Note that in some cases `repr(data)` represents a float number # without the decimal parts. For instance: # >>> repr(1e17) @@ -200,9 +200,9 @@ def represent_float(self, data): # Unfortunately, this is not a valid float representation according # to the definition of the `!!float` tag. We fix this by adding # '.0' before the 'e' symbol. - if u'.' not in value and u'e' in value: - value = value.replace(u'e', u'.0e', 1) - return self.represent_scalar(u'tag:yaml.org,2002:float', value) + if '.' not in value and 'e' in value: + value = value.replace('e', '.0e', 1) + return self.represent_scalar('tag:yaml.org,2002:float', value) def represent_list(self, data): #pairs = (len(data) > 0 and isinstance(data, list)) @@ -212,7 +212,7 @@ def represent_list(self, data): # pairs = False # break #if not pairs: - return self.represent_sequence(u'tag:yaml.org,2002:seq', data) + return self.represent_sequence('tag:yaml.org,2002:seq', data) #value = [] #for item_key, item_value in data: # value.append(self.represent_mapping(u'tag:yaml.org,2002:map', @@ -220,21 +220,21 @@ def represent_list(self, data): #return SequenceNode(u'tag:yaml.org,2002:pairs', value) def represent_dict(self, data): - return self.represent_mapping(u'tag:yaml.org,2002:map', data) + return self.represent_mapping('tag:yaml.org,2002:map', data) def represent_set(self, data): value = {} for key in data: value[key] = None - return self.represent_mapping(u'tag:yaml.org,2002:set', value) + return self.represent_mapping('tag:yaml.org,2002:set', value) def represent_date(self, data): - value = unicode(data.isoformat()) - return self.represent_scalar(u'tag:yaml.org,2002:timestamp', value) + value = str(data.isoformat()) + return self.represent_scalar('tag:yaml.org,2002:timestamp', value) def represent_datetime(self, data): - value = unicode(data.isoformat(' ')) - return self.represent_scalar(u'tag:yaml.org,2002:timestamp', value) + value = str(data.isoformat(' ')) + return self.represent_scalar('tag:yaml.org,2002:timestamp', value) def represent_yaml_object(self, tag, data, cls, flow_style=None): if hasattr(data, '__getstate__'): @@ -252,7 +252,7 @@ def represent_undefined(self, data): SafeRepresenter.add_representer(str, SafeRepresenter.represent_str) -SafeRepresenter.add_representer(unicode, +SafeRepresenter.add_representer(str, SafeRepresenter.represent_unicode) SafeRepresenter.add_representer(bool, @@ -261,7 +261,7 @@ def represent_undefined(self, data): SafeRepresenter.add_representer(int, SafeRepresenter.represent_int) -SafeRepresenter.add_representer(long, +SafeRepresenter.add_representer(int, SafeRepresenter.represent_long) SafeRepresenter.add_representer(float, @@ -294,15 +294,15 @@ def represent_str(self, data): tag = None style = None try: - data = unicode(data, 'ascii') - tag = u'tag:yaml.org,2002:str' + data = str(data, 'ascii') + tag = 'tag:yaml.org,2002:str' except UnicodeDecodeError: try: - data = unicode(data, 'utf-8') - tag = u'tag:yaml.org,2002:python/str' + data = str(data, 'utf-8') + tag = 'tag:yaml.org,2002:python/str' except UnicodeDecodeError: data = data.encode('base64') - tag = u'tag:yaml.org,2002:binary' + tag = 'tag:yaml.org,2002:binary' style = '|' return self.represent_scalar(tag, data, style=style) @@ -310,38 +310,38 @@ def represent_unicode(self, data): tag = None try: data.encode('ascii') - tag = u'tag:yaml.org,2002:python/unicode' + tag = 'tag:yaml.org,2002:python/unicode' except UnicodeEncodeError: - tag = u'tag:yaml.org,2002:str' + tag = 'tag:yaml.org,2002:str' return self.represent_scalar(tag, data) def represent_long(self, data): - tag = u'tag:yaml.org,2002:int' + tag = 'tag:yaml.org,2002:int' if int(data) is not data: - tag = u'tag:yaml.org,2002:python/long' - return self.represent_scalar(tag, unicode(data)) + tag = 'tag:yaml.org,2002:python/long' + return self.represent_scalar(tag, str(data)) def represent_complex(self, data): if data.imag == 0.0: - data = u'%r' % data.real + data = '%r' % data.real elif data.real == 0.0: - data = u'%rj' % data.imag + data = '%rj' % data.imag elif data.imag > 0: - data = u'%r+%rj' % (data.real, data.imag) + data = '%r+%rj' % (data.real, data.imag) else: - data = u'%r%rj' % (data.real, data.imag) - return self.represent_scalar(u'tag:yaml.org,2002:python/complex', data) + data = '%r%rj' % (data.real, data.imag) + return self.represent_scalar('tag:yaml.org,2002:python/complex', data) def represent_tuple(self, data): - return self.represent_sequence(u'tag:yaml.org,2002:python/tuple', data) + return self.represent_sequence('tag:yaml.org,2002:python/tuple', data) def represent_name(self, data): - name = u'%s.%s' % (data.__module__, data.__name__) - return self.represent_scalar(u'tag:yaml.org,2002:python/name:'+name, u'') + name = '%s.%s' % (data.__module__, data.__name__) + return self.represent_scalar('tag:yaml.org,2002:python/name:'+name, '') def represent_module(self, data): return self.represent_scalar( - u'tag:yaml.org,2002:python/module:'+data.__name__, u'') + 'tag:yaml.org,2002:python/module:'+data.__name__, '') def represent_instance(self, data): # For instances of classic classes, we use __getinitargs__ and @@ -362,7 +362,7 @@ def represent_instance(self, data): # !!python/object/new node. cls = data.__class__ - class_name = u'%s.%s' % (cls.__module__, cls.__name__) + class_name = '%s.%s' % (cls.__module__, cls.__name__) args = None state = None if hasattr(data, '__getinitargs__'): @@ -373,16 +373,16 @@ def represent_instance(self, data): state = data.__dict__ if args is None and isinstance(state, dict): return self.represent_mapping( - u'tag:yaml.org,2002:python/object:'+class_name, state) + 'tag:yaml.org,2002:python/object:'+class_name, state) if isinstance(state, dict) and not state: return self.represent_sequence( - u'tag:yaml.org,2002:python/object/new:'+class_name, args) + 'tag:yaml.org,2002:python/object/new:'+class_name, args) value = {} if args: value['args'] = args value['state'] = state return self.represent_mapping( - u'tag:yaml.org,2002:python/object/new:'+class_name, value) + 'tag:yaml.org,2002:python/object/new:'+class_name, value) def represent_object(self, data): # We use __reduce__ API to save the data. data.__reduce__ returns @@ -402,8 +402,8 @@ def represent_object(self, data): # !!python/object/apply node. cls = type(data) - if cls in copy_reg.dispatch_table: - reduce = copy_reg.dispatch_table[cls](data) + if cls in copyreg.dispatch_table: + reduce = copyreg.dispatch_table[cls](data) elif hasattr(data, '__reduce_ex__'): reduce = data.__reduce_ex__(2) elif hasattr(data, '__reduce__'): @@ -422,16 +422,16 @@ def represent_object(self, data): if function.__name__ == '__newobj__': function = args[0] args = args[1:] - tag = u'tag:yaml.org,2002:python/object/new:' + tag = 'tag:yaml.org,2002:python/object/new:' newobj = True else: - tag = u'tag:yaml.org,2002:python/object/apply:' + tag = 'tag:yaml.org,2002:python/object/apply:' newobj = False - function_name = u'%s.%s' % (function.__module__, function.__name__) + function_name = '%s.%s' % (function.__module__, function.__name__) if not args and not listitems and not dictitems \ and isinstance(state, dict) and newobj: return self.represent_mapping( - u'tag:yaml.org,2002:python/object:'+function_name, state) + 'tag:yaml.org,2002:python/object:'+function_name, state) if not listitems and not dictitems \ and isinstance(state, dict) and not state: return self.represent_sequence(tag+function_name, args) @@ -449,10 +449,10 @@ def represent_object(self, data): Representer.add_representer(str, Representer.represent_str) -Representer.add_representer(unicode, +Representer.add_representer(str, Representer.represent_unicode) -Representer.add_representer(long, +Representer.add_representer(int, Representer.represent_long) Representer.add_representer(complex, @@ -464,7 +464,7 @@ def represent_object(self, data): Representer.add_representer(type, Representer.represent_name) -Representer.add_representer(types.ClassType, +Representer.add_representer(type, Representer.represent_name) Representer.add_representer(types.FunctionType, @@ -476,8 +476,7 @@ def represent_object(self, data): Representer.add_representer(types.ModuleType, Representer.represent_module) -Representer.add_multi_representer(types.InstanceType, - Representer.represent_instance) + Representer.add_multi_representer(object, Representer.represent_object) diff --git a/toontown/pandautils/yaml/resolver.py b/toontown/pandautils/yaml/resolver.py index 6b5ab8759..cb4a0df85 100644 --- a/toontown/pandautils/yaml/resolver.py +++ b/toontown/pandautils/yaml/resolver.py @@ -1,8 +1,8 @@ __all__ = ['BaseResolver', 'Resolver'] -from error import * -from nodes import * +from .error import * +from .nodes import * import re @@ -11,9 +11,9 @@ class ResolverError(YAMLError): class BaseResolver(object): - DEFAULT_SCALAR_TAG = u'tag:yaml.org,2002:str' - DEFAULT_SEQUENCE_TAG = u'tag:yaml.org,2002:seq' - DEFAULT_MAPPING_TAG = u'tag:yaml.org,2002:map' + DEFAULT_SCALAR_TAG = 'tag:yaml.org,2002:str' + DEFAULT_SEQUENCE_TAG = 'tag:yaml.org,2002:seq' + DEFAULT_MAPPING_TAG = 'tag:yaml.org,2002:map' yaml_implicit_resolvers = {} yaml_path_resolvers = {} @@ -66,10 +66,10 @@ def add_path_resolver(cls, tag, path, kind=None): elif node_check is dict: node_check = MappingNode elif node_check not in [ScalarNode, SequenceNode, MappingNode] \ - and not isinstance(node_check, basestring) \ + and not isinstance(node_check, str) \ and node_check is not None: raise ResolverError("Invalid node checker: %s" % node_check) - if not isinstance(index_check, (basestring, int)) \ + if not isinstance(index_check, (str, int)) \ and index_check is not None: raise ResolverError("Invalid index checker: %s" % index_check) new_path.append((node_check, index_check)) @@ -117,7 +117,7 @@ def ascend_resolver(self): def check_resolver_prefix(self, depth, path, kind, current_node, current_index): node_check, index_check = path[depth-1] - if isinstance(node_check, basestring): + if isinstance(node_check, str): if current_node.tag != node_check: return elif node_check is not None: @@ -128,7 +128,7 @@ def check_resolver_prefix(self, depth, path, kind, if (index_check is False or index_check is None) \ and current_index is None: return - if isinstance(index_check, basestring): + if isinstance(index_check, str): if not (isinstance(current_index, ScalarNode) and index_check == current_index.value): return @@ -139,8 +139,8 @@ def check_resolver_prefix(self, depth, path, kind, def resolve(self, kind, value, implicit): if kind is ScalarNode and implicit[0]: - if value == u'': - resolvers = self.yaml_implicit_resolvers.get(u'', []) + if value == '': + resolvers = self.yaml_implicit_resolvers.get('', []) else: resolvers = self.yaml_implicit_resolvers.get(value[0], []) resolvers += self.yaml_implicit_resolvers.get(None, []) @@ -165,60 +165,60 @@ class Resolver(BaseResolver): pass Resolver.add_implicit_resolver( - u'tag:yaml.org,2002:bool', - re.compile(ur'''^(?:yes|Yes|YES|no|No|NO + 'tag:yaml.org,2002:bool', + re.compile(r'''^(?:yes|Yes|YES|no|No|NO |true|True|TRUE|false|False|FALSE |on|On|ON|off|Off|OFF)$''', re.X), - list(u'yYnNtTfFoO')) + list('yYnNtTfFoO')) Resolver.add_implicit_resolver( - u'tag:yaml.org,2002:float', - re.compile(ur'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)? + 'tag:yaml.org,2002:float', + re.compile(r'''^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+][0-9]+)? |\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]* |[-+]?\.(?:inf|Inf|INF) |\.(?:nan|NaN|NAN))$''', re.X), - list(u'-+0123456789.')) + list('-+0123456789.')) Resolver.add_implicit_resolver( - u'tag:yaml.org,2002:int', - re.compile(ur'''^(?:[-+]?0b[0-1_]+ + 'tag:yaml.org,2002:int', + re.compile(r'''^(?:[-+]?0b[0-1_]+ |[-+]?0[0-7_]+ |[-+]?(?:0|[1-9][0-9_]*) |[-+]?0x[0-9a-fA-F_]+ |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X), - list(u'-+0123456789')) + list('-+0123456789')) Resolver.add_implicit_resolver( - u'tag:yaml.org,2002:merge', - re.compile(ur'^(?:<<)$'), - [u'<']) + 'tag:yaml.org,2002:merge', + re.compile(r'^(?:<<)$'), + ['<']) Resolver.add_implicit_resolver( - u'tag:yaml.org,2002:null', - re.compile(ur'''^(?: ~ + 'tag:yaml.org,2002:null', + re.compile(r'''^(?: ~ |null|Null|NULL | )$''', re.X), - [u'~', u'n', u'N', u'']) + ['~', 'n', 'N', '']) Resolver.add_implicit_resolver( - u'tag:yaml.org,2002:timestamp', - re.compile(ur'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] + 'tag:yaml.org,2002:timestamp', + re.compile(r'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]? (?:[Tt]|[ \t]+)[0-9][0-9]? :[0-9][0-9] :[0-9][0-9] (?:\.[0-9]*)? (?:[ \t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X), - list(u'0123456789')) + list('0123456789')) Resolver.add_implicit_resolver( - u'tag:yaml.org,2002:value', - re.compile(ur'^(?:=)$'), - [u'=']) + 'tag:yaml.org,2002:value', + re.compile(r'^(?:=)$'), + ['=']) # The following resolver is only for documentation purposes. It cannot work # because plain scalars cannot start with '!', '&', or '*'. Resolver.add_implicit_resolver( - u'tag:yaml.org,2002:yaml', - re.compile(ur'^(?:!|&|\*)$'), - list(u'!&*')) + 'tag:yaml.org,2002:yaml', + re.compile(r'^(?:!|&|\*)$'), + list('!&*')) diff --git a/toontown/pandautils/yaml/scanner.py b/toontown/pandautils/yaml/scanner.py index 5228fad65..f59e3331a 100644 --- a/toontown/pandautils/yaml/scanner.py +++ b/toontown/pandautils/yaml/scanner.py @@ -26,8 +26,8 @@ __all__ = ['Scanner', 'ScannerError'] -from error import MarkedYAMLError -from tokens import * +from .error import MarkedYAMLError +from .tokens import * class ScannerError(MarkedYAMLError): pass @@ -166,19 +166,19 @@ def fetch_more_tokens(self): ch = self.peek() # Is it the end of stream? - if ch == u'\0': + if ch == '\0': return self.fetch_stream_end() # Is it a directive? - if ch == u'%' and self.check_directive(): + if ch == '%' and self.check_directive(): return self.fetch_directive() # Is it the document start? - if ch == u'-' and self.check_document_start(): + if ch == '-' and self.check_document_start(): return self.fetch_document_start() # Is it the document end? - if ch == u'.' and self.check_document_end(): + if ch == '.' and self.check_document_end(): return self.fetch_document_end() # TODO: support for BOM within a stream. @@ -188,63 +188,63 @@ def fetch_more_tokens(self): # Note: the order of the following checks is NOT significant. # Is it the flow sequence start indicator? - if ch == u'[': + if ch == '[': return self.fetch_flow_sequence_start() # Is it the flow mapping start indicator? - if ch == u'{': + if ch == '{': return self.fetch_flow_mapping_start() # Is it the flow sequence end indicator? - if ch == u']': + if ch == ']': return self.fetch_flow_sequence_end() # Is it the flow mapping end indicator? - if ch == u'}': + if ch == '}': return self.fetch_flow_mapping_end() # Is it the flow entry indicator? - if ch == u',': + if ch == ',': return self.fetch_flow_entry() # Is it the block entry indicator? - if ch == u'-' and self.check_block_entry(): + if ch == '-' and self.check_block_entry(): return self.fetch_block_entry() # Is it the key indicator? - if ch == u'?' and self.check_key(): + if ch == '?' and self.check_key(): return self.fetch_key() # Is it the value indicator? - if ch == u':' and self.check_value(): + if ch == ':' and self.check_value(): return self.fetch_value() # Is it an alias? - if ch == u'*': + if ch == '*': return self.fetch_alias() # Is it an anchor? - if ch == u'&': + if ch == '&': return self.fetch_anchor() # Is it a tag? - if ch == u'!': + if ch == '!': return self.fetch_tag() # Is it a literal scalar? - if ch == u'|' and not self.flow_level: + if ch == '|' and not self.flow_level: return self.fetch_literal() # Is it a folded scalar? - if ch == u'>' and not self.flow_level: + if ch == '>' and not self.flow_level: return self.fetch_folded() # Is it a single quoted scalar? - if ch == u'\'': + if ch == '\'': return self.fetch_single() # Is it a double quoted scalar? - if ch == u'\"': + if ch == '\"': return self.fetch_double() # It must be a plain scalar then. @@ -280,7 +280,7 @@ def stale_possible_simple_keys(self): # - should be no longer than 1024 characters. # Disabling this procedure will allow simple keys of any length and # height (may cause problems if indentation is broken though). - for level in self.possible_simple_keys.keys(): + for level in list(self.possible_simple_keys.keys()): key = self.possible_simple_keys[level] if key.line != self.line \ or self.index-key.index > 1024: @@ -692,22 +692,22 @@ def check_document_start(self): # DOCUMENT-START: ^ '---' (' '|'\n') if self.column == 0: - if self.prefix(3) == u'---' \ - and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029': + if self.prefix(3) == '---' \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': return True def check_document_end(self): # DOCUMENT-END: ^ '...' (' '|'\n') if self.column == 0: - if self.prefix(3) == u'...' \ - and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029': + if self.prefix(3) == '...' \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': return True def check_block_entry(self): # BLOCK-ENTRY: '-' (' '|'\n') - return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029' + return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' def check_key(self): @@ -717,7 +717,7 @@ def check_key(self): # KEY(block context): '?' (' '|'\n') else: - return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029' + return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' def check_value(self): @@ -727,7 +727,7 @@ def check_value(self): # VALUE(block context): ':' (' '|'\n') else: - return self.peek(1) in u'\0 \t\r\n\x85\u2028\u2029' + return self.peek(1) in '\0 \t\r\n\x85\u2028\u2029' def check_plain(self): @@ -744,9 +744,9 @@ def check_plain(self): # '-' character) because we want the flow context to be space # independent. ch = self.peek() - return ch not in u'\0 \t\r\n\x85\u2028\u2029-?:,[]{}#&*!|>\'\"%@`' \ - or (self.peek(1) not in u'\0 \t\r\n\x85\u2028\u2029' - and (ch == u'-' or (not self.flow_level and ch in u'?:'))) + return ch not in '\0 \t\r\n\x85\u2028\u2029-?:,[]{}#&*!|>\'\"%@`' \ + or (self.peek(1) not in '\0 \t\r\n\x85\u2028\u2029' + and (ch == '-' or (not self.flow_level and ch in '?:'))) # Scanners. @@ -770,14 +770,14 @@ def scan_to_next_token(self): # `unwind_indent` before issuing BLOCK-END. # Scanners for block, flow, and plain scalars need to be modified. - if self.index == 0 and self.peek() == u'\uFEFF': + if self.index == 0 and self.peek() == '\uFEFF': self.forward() found = False while not found: - while self.peek() == u' ': + while self.peek() == ' ': self.forward() - if self.peek() == u'#': - while self.peek() not in u'\0\r\n\x85\u2028\u2029': + if self.peek() == '#': + while self.peek() not in '\0\r\n\x85\u2028\u2029': self.forward() if self.scan_line_break(): if not self.flow_level: @@ -791,15 +791,15 @@ def scan_directive(self): self.forward() name = self.scan_directive_name(start_mark) value = None - if name == u'YAML': + if name == 'YAML': value = self.scan_yaml_directive_value(start_mark) end_mark = self.get_mark() - elif name == u'TAG': + elif name == 'TAG': value = self.scan_tag_directive_value(start_mark) end_mark = self.get_mark() else: end_mark = self.get_mark() - while self.peek() not in u'\0\r\n\x85\u2028\u2029': + while self.peek() not in '\0\r\n\x85\u2028\u2029': self.forward() self.scan_directive_ignored_line(start_mark) return DirectiveToken(name, value, start_mark, end_mark) @@ -808,8 +808,8 @@ def scan_directive_name(self, start_mark): # See the specification for details. length = 0 ch = self.peek(length) - while u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \ - or ch in u'-_': + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_': length += 1 ch = self.peek(length) if not length: @@ -819,7 +819,7 @@ def scan_directive_name(self, start_mark): value = self.prefix(length) self.forward(length) ch = self.peek() - if ch not in u'\0 \r\n\x85\u2028\u2029': + if ch not in '\0 \r\n\x85\u2028\u2029': raise ScannerError("while scanning a directive", start_mark, "expected alphabetic or numeric character, but found %r" % ch.encode('utf-8'), self.get_mark()) @@ -827,7 +827,7 @@ def scan_directive_name(self, start_mark): def scan_yaml_directive_value(self, start_mark): # See the specification for details. - while self.peek() == u' ': + while self.peek() == ' ': self.forward() major = self.scan_yaml_directive_number(start_mark) if self.peek() != '.': @@ -837,7 +837,7 @@ def scan_yaml_directive_value(self, start_mark): self.get_mark()) self.forward() minor = self.scan_yaml_directive_number(start_mark) - if self.peek() not in u'\0 \r\n\x85\u2028\u2029': + if self.peek() not in '\0 \r\n\x85\u2028\u2029': raise ScannerError("while scanning a directive", start_mark, "expected a digit or ' ', but found %r" % self.peek().encode('utf-8'), @@ -847,12 +847,12 @@ def scan_yaml_directive_value(self, start_mark): def scan_yaml_directive_number(self, start_mark): # See the specification for details. ch = self.peek() - if not (u'0' <= ch <= u'9'): + if not ('0' <= ch <= '9'): raise ScannerError("while scanning a directive", start_mark, "expected a digit, but found %r" % ch.encode('utf-8'), self.get_mark()) length = 0 - while u'0' <= self.peek(length) <= u'9': + while '0' <= self.peek(length) <= '9': length += 1 value = int(self.prefix(length)) self.forward(length) @@ -860,10 +860,10 @@ def scan_yaml_directive_number(self, start_mark): def scan_tag_directive_value(self, start_mark): # See the specification for details. - while self.peek() == u' ': + while self.peek() == ' ': self.forward() handle = self.scan_tag_directive_handle(start_mark) - while self.peek() == u' ': + while self.peek() == ' ': self.forward() prefix = self.scan_tag_directive_prefix(start_mark) return (handle, prefix) @@ -872,7 +872,7 @@ def scan_tag_directive_handle(self, start_mark): # See the specification for details. value = self.scan_tag_handle('directive', start_mark) ch = self.peek() - if ch != u' ': + if ch != ' ': raise ScannerError("while scanning a directive", start_mark, "expected ' ', but found %r" % ch.encode('utf-8'), self.get_mark()) @@ -882,7 +882,7 @@ def scan_tag_directive_prefix(self, start_mark): # See the specification for details. value = self.scan_tag_uri('directive', start_mark) ch = self.peek() - if ch not in u'\0 \r\n\x85\u2028\u2029': + if ch not in '\0 \r\n\x85\u2028\u2029': raise ScannerError("while scanning a directive", start_mark, "expected ' ', but found %r" % ch.encode('utf-8'), self.get_mark()) @@ -890,13 +890,13 @@ def scan_tag_directive_prefix(self, start_mark): def scan_directive_ignored_line(self, start_mark): # See the specification for details. - while self.peek() == u' ': + while self.peek() == ' ': self.forward() - if self.peek() == u'#': - while self.peek() not in u'\0\r\n\x85\u2028\u2029': + if self.peek() == '#': + while self.peek() not in '\0\r\n\x85\u2028\u2029': self.forward() ch = self.peek() - if ch not in u'\0\r\n\x85\u2028\u2029': + if ch not in '\0\r\n\x85\u2028\u2029': raise ScannerError("while scanning a directive", start_mark, "expected a comment or a line break, but found %r" % ch.encode('utf-8'), self.get_mark()) @@ -913,15 +913,15 @@ def scan_anchor(self, TokenClass): # Therefore we restrict aliases to numbers and ASCII letters. start_mark = self.get_mark() indicator = self.peek() - if indicator == u'*': + if indicator == '*': name = 'alias' else: name = 'anchor' self.forward() length = 0 ch = self.peek(length) - while u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \ - or ch in u'-_': + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_': length += 1 ch = self.peek(length) if not length: @@ -931,7 +931,7 @@ def scan_anchor(self, TokenClass): value = self.prefix(length) self.forward(length) ch = self.peek() - if ch not in u'\0 \t\r\n\x85\u2028\u2029?:,]}%@`': + if ch not in '\0 \t\r\n\x85\u2028\u2029?:,]}%@`': raise ScannerError("while scanning an %s" % name, start_mark, "expected alphabetic or numeric character, but found %r" % ch.encode('utf-8'), self.get_mark()) @@ -942,37 +942,37 @@ def scan_tag(self): # See the specification for details. start_mark = self.get_mark() ch = self.peek(1) - if ch == u'<': + if ch == '<': handle = None self.forward(2) suffix = self.scan_tag_uri('tag', start_mark) - if self.peek() != u'>': + if self.peek() != '>': raise ScannerError("while parsing a tag", start_mark, "expected '>', but found %r" % self.peek().encode('utf-8'), self.get_mark()) self.forward() - elif ch in u'\0 \t\r\n\x85\u2028\u2029': + elif ch in '\0 \t\r\n\x85\u2028\u2029': handle = None - suffix = u'!' + suffix = '!' self.forward() else: length = 1 use_handle = False - while ch not in u'\0 \r\n\x85\u2028\u2029': - if ch == u'!': + while ch not in '\0 \r\n\x85\u2028\u2029': + if ch == '!': use_handle = True break length += 1 ch = self.peek(length) - handle = u'!' + handle = '!' if use_handle: handle = self.scan_tag_handle('tag', start_mark) else: - handle = u'!' + handle = '!' self.forward() suffix = self.scan_tag_uri('tag', start_mark) ch = self.peek() - if ch not in u'\0 \r\n\x85\u2028\u2029': + if ch not in '\0 \r\n\x85\u2028\u2029': raise ScannerError("while scanning a tag", start_mark, "expected ' ', but found %r" % ch.encode('utf-8'), self.get_mark()) @@ -1006,29 +1006,29 @@ def scan_block_scalar(self, style): else: indent = min_indent+increment-1 breaks, end_mark = self.scan_block_scalar_breaks(indent) - line_break = u'' + line_break = '' # Scan the inner part of the block scalar. - while self.column == indent and self.peek() != u'\0': + while self.column == indent and self.peek() != '\0': chunks.extend(breaks) - leading_non_space = self.peek() not in u' \t' + leading_non_space = self.peek() not in ' \t' length = 0 - while self.peek(length) not in u'\0\r\n\x85\u2028\u2029': + while self.peek(length) not in '\0\r\n\x85\u2028\u2029': length += 1 chunks.append(self.prefix(length)) self.forward(length) line_break = self.scan_line_break() breaks, end_mark = self.scan_block_scalar_breaks(indent) - if self.column == indent and self.peek() != u'\0': + if self.column == indent and self.peek() != '\0': # Unfortunately, folding rules are ambiguous. # # This is the folding according to the specification: - if folded and line_break == u'\n' \ - and leading_non_space and self.peek() not in u' \t': + if folded and line_break == '\n' \ + and leading_non_space and self.peek() not in ' \t': if not breaks: - chunks.append(u' ') + chunks.append(' ') else: chunks.append(line_break) @@ -1053,7 +1053,7 @@ def scan_block_scalar(self, style): chunks.extend(breaks) # We are done. - return ScalarToken(u''.join(chunks), False, start_mark, end_mark, + return ScalarToken(''.join(chunks), False, start_mark, end_mark, style) def scan_block_scalar_indicators(self, start_mark): @@ -1061,21 +1061,21 @@ def scan_block_scalar_indicators(self, start_mark): chomping = None increment = None ch = self.peek() - if ch in u'+-': + if ch in '+-': if ch == '+': chomping = True else: chomping = False self.forward() ch = self.peek() - if ch in u'0123456789': + if ch in '0123456789': increment = int(ch) if increment == 0: raise ScannerError("while scanning a block scalar", start_mark, "expected indentation indicator in the range 1-9, but found 0", self.get_mark()) self.forward() - elif ch in u'0123456789': + elif ch in '0123456789': increment = int(ch) if increment == 0: raise ScannerError("while scanning a block scalar", start_mark, @@ -1083,14 +1083,14 @@ def scan_block_scalar_indicators(self, start_mark): self.get_mark()) self.forward() ch = self.peek() - if ch in u'+-': + if ch in '+-': if ch == '+': chomping = True else: chomping = False self.forward() ch = self.peek() - if ch not in u'\0 \r\n\x85\u2028\u2029': + if ch not in '\0 \r\n\x85\u2028\u2029': raise ScannerError("while scanning a block scalar", start_mark, "expected chomping or indentation indicators, but found %r" % ch.encode('utf-8'), self.get_mark()) @@ -1098,13 +1098,13 @@ def scan_block_scalar_indicators(self, start_mark): def scan_block_scalar_ignored_line(self, start_mark): # See the specification for details. - while self.peek() == u' ': + while self.peek() == ' ': self.forward() - if self.peek() == u'#': - while self.peek() not in u'\0\r\n\x85\u2028\u2029': + if self.peek() == '#': + while self.peek() not in '\0\r\n\x85\u2028\u2029': self.forward() ch = self.peek() - if ch not in u'\0\r\n\x85\u2028\u2029': + if ch not in '\0\r\n\x85\u2028\u2029': raise ScannerError("while scanning a block scalar", start_mark, "expected a comment or a line break, but found %r" % ch.encode('utf-8'), self.get_mark()) @@ -1115,8 +1115,8 @@ def scan_block_scalar_indentation(self): chunks = [] max_indent = 0 end_mark = self.get_mark() - while self.peek() in u' \r\n\x85\u2028\u2029': - if self.peek() != u' ': + while self.peek() in ' \r\n\x85\u2028\u2029': + if self.peek() != ' ': chunks.append(self.scan_line_break()) end_mark = self.get_mark() else: @@ -1129,12 +1129,12 @@ def scan_block_scalar_breaks(self, indent): # See the specification for details. chunks = [] end_mark = self.get_mark() - while self.column < indent and self.peek() == u' ': + while self.column < indent and self.peek() == ' ': self.forward() - while self.peek() in u'\r\n\x85\u2028\u2029': + while self.peek() in '\r\n\x85\u2028\u2029': chunks.append(self.scan_line_break()) end_mark = self.get_mark() - while self.column < indent and self.peek() == u' ': + while self.column < indent and self.peek() == ' ': self.forward() return chunks, end_mark @@ -1159,33 +1159,33 @@ def scan_flow_scalar(self, style): chunks.extend(self.scan_flow_scalar_non_spaces(double, start_mark)) self.forward() end_mark = self.get_mark() - return ScalarToken(u''.join(chunks), False, start_mark, end_mark, + return ScalarToken(''.join(chunks), False, start_mark, end_mark, style) ESCAPE_REPLACEMENTS = { - u'0': u'\0', - u'a': u'\x07', - u'b': u'\x08', - u't': u'\x09', - u'\t': u'\x09', - u'n': u'\x0A', - u'v': u'\x0B', - u'f': u'\x0C', - u'r': u'\x0D', - u'e': u'\x1B', - u' ': u'\x20', - u'\"': u'\"', - u'\\': u'\\', - u'N': u'\x85', - u'_': u'\xA0', - u'L': u'\u2028', - u'P': u'\u2029', + '0': '\0', + 'a': '\x07', + 'b': '\x08', + 't': '\x09', + '\t': '\x09', + 'n': '\x0A', + 'v': '\x0B', + 'f': '\x0C', + 'r': '\x0D', + 'e': '\x1B', + ' ': '\x20', + '\"': '\"', + '\\': '\\', + 'N': '\x85', + '_': '\xA0', + 'L': '\u2028', + 'P': '\u2029', } ESCAPE_CODES = { - u'x': 2, - u'u': 4, - u'U': 8, + 'x': 2, + 'u': 4, + 'U': 8, } def scan_flow_scalar_non_spaces(self, double, start_mark): @@ -1193,19 +1193,19 @@ def scan_flow_scalar_non_spaces(self, double, start_mark): chunks = [] while True: length = 0 - while self.peek(length) not in u'\'\"\\\0 \t\r\n\x85\u2028\u2029': + while self.peek(length) not in '\'\"\\\0 \t\r\n\x85\u2028\u2029': length += 1 if length: chunks.append(self.prefix(length)) self.forward(length) ch = self.peek() - if not double and ch == u'\'' and self.peek(1) == u'\'': - chunks.append(u'\'') + if not double and ch == '\'' and self.peek(1) == '\'': + chunks.append('\'') self.forward(2) - elif (double and ch == u'\'') or (not double and ch in u'\"\\'): + elif (double and ch == '\'') or (not double and ch in '\"\\'): chunks.append(ch) self.forward() - elif double and ch == u'\\': + elif double and ch == '\\': self.forward() ch = self.peek() if ch in self.ESCAPE_REPLACEMENTS: @@ -1215,14 +1215,14 @@ def scan_flow_scalar_non_spaces(self, double, start_mark): length = self.ESCAPE_CODES[ch] self.forward() for k in range(length): - if self.peek(k) not in u'0123456789ABCDEFabcdef': + if self.peek(k) not in '0123456789ABCDEFabcdef': raise ScannerError("while scanning a double-quoted scalar", start_mark, "expected escape sequence of %d hexdecimal numbers, but found %r" % (length, self.peek(k).encode('utf-8')), self.get_mark()) code = int(self.prefix(length), 16) - chunks.append(unichr(code)) + chunks.append(chr(code)) self.forward(length) - elif ch in u'\r\n\x85\u2028\u2029': + elif ch in '\r\n\x85\u2028\u2029': self.scan_line_break() chunks.extend(self.scan_flow_scalar_breaks(double, start_mark)) else: @@ -1235,21 +1235,21 @@ def scan_flow_scalar_spaces(self, double, start_mark): # See the specification for details. chunks = [] length = 0 - while self.peek(length) in u' \t': + while self.peek(length) in ' \t': length += 1 whitespaces = self.prefix(length) self.forward(length) ch = self.peek() - if ch == u'\0': + if ch == '\0': raise ScannerError("while scanning a quoted scalar", start_mark, "found unexpected end of stream", self.get_mark()) - elif ch in u'\r\n\x85\u2028\u2029': + elif ch in '\r\n\x85\u2028\u2029': line_break = self.scan_line_break() breaks = self.scan_flow_scalar_breaks(double, start_mark) - if line_break != u'\n': + if line_break != '\n': chunks.append(line_break) elif not breaks: - chunks.append(u' ') + chunks.append(' ') chunks.extend(breaks) else: chunks.append(whitespaces) @@ -1262,13 +1262,13 @@ def scan_flow_scalar_breaks(self, double, start_mark): # Instead of checking indentation, we check for document # separators. prefix = self.prefix(3) - if (prefix == u'---' or prefix == u'...') \ - and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029': + if (prefix == '---' or prefix == '...') \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': raise ScannerError("while scanning a quoted scalar", start_mark, "found unexpected document separator", self.get_mark()) - while self.peek() in u' \t': + while self.peek() in ' \t': self.forward() - if self.peek() in u'\r\n\x85\u2028\u2029': + if self.peek() in '\r\n\x85\u2028\u2029': chunks.append(self.scan_line_break()) else: return chunks @@ -1290,19 +1290,19 @@ def scan_plain(self): spaces = [] while True: length = 0 - if self.peek() == u'#': + if self.peek() == '#': break while True: ch = self.peek(length) - if ch in u'\0 \t\r\n\x85\u2028\u2029' \ - or (not self.flow_level and ch == u':' and - self.peek(length+1) in u'\0 \t\r\n\x85\u2028\u2029') \ - or (self.flow_level and ch in u',:?[]{}'): + if ch in '\0 \t\r\n\x85\u2028\u2029' \ + or (not self.flow_level and ch == ':' and + self.peek(length+1) in '\0 \t\r\n\x85\u2028\u2029') \ + or (self.flow_level and ch in ',:?[]{}'): break length += 1 # It's not clear what we should do with ':' in the flow context. - if (self.flow_level and ch == u':' - and self.peek(length+1) not in u'\0 \t\r\n\x85\u2028\u2029,[]{}'): + if (self.flow_level and ch == ':' + and self.peek(length+1) not in '\0 \t\r\n\x85\u2028\u2029,[]{}'): self.forward(length) raise ScannerError("while scanning a plain scalar", start_mark, "found unexpected ':'", self.get_mark(), @@ -1315,10 +1315,10 @@ def scan_plain(self): self.forward(length) end_mark = self.get_mark() spaces = self.scan_plain_spaces(indent, start_mark) - if not spaces or self.peek() == u'#' \ + if not spaces or self.peek() == '#' \ or (not self.flow_level and self.column < indent): break - return ScalarToken(u''.join(chunks), True, start_mark, end_mark) + return ScalarToken(''.join(chunks), True, start_mark, end_mark) def scan_plain_spaces(self, indent, start_mark): # See the specification for details. @@ -1326,32 +1326,32 @@ def scan_plain_spaces(self, indent, start_mark): # We just forbid them completely. Do not use tabs in YAML! chunks = [] length = 0 - while self.peek(length) in u' ': + while self.peek(length) in ' ': length += 1 whitespaces = self.prefix(length) self.forward(length) ch = self.peek() - if ch in u'\r\n\x85\u2028\u2029': + if ch in '\r\n\x85\u2028\u2029': line_break = self.scan_line_break() self.allow_simple_key = True prefix = self.prefix(3) - if (prefix == u'---' or prefix == u'...') \ - and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029': + if (prefix == '---' or prefix == '...') \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': return breaks = [] - while self.peek() in u' \r\n\x85\u2028\u2029': + while self.peek() in ' \r\n\x85\u2028\u2029': if self.peek() == ' ': self.forward() else: breaks.append(self.scan_line_break()) prefix = self.prefix(3) - if (prefix == u'---' or prefix == u'...') \ - and self.peek(3) in u'\0 \t\r\n\x85\u2028\u2029': + if (prefix == '---' or prefix == '...') \ + and self.peek(3) in '\0 \t\r\n\x85\u2028\u2029': return - if line_break != u'\n': + if line_break != '\n': chunks.append(line_break) elif not breaks: - chunks.append(u' ') + chunks.append(' ') chunks.extend(breaks) elif whitespaces: chunks.append(whitespaces) @@ -1362,18 +1362,18 @@ def scan_tag_handle(self, name, start_mark): # For some strange reasons, the specification does not allow '_' in # tag handles. I have allowed it anyway. ch = self.peek() - if ch != u'!': + if ch != '!': raise ScannerError("while scanning a %s" % name, start_mark, "expected '!', but found %r" % ch.encode('utf-8'), self.get_mark()) length = 1 ch = self.peek(length) - if ch != u' ': - while u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \ - or ch in u'-_': + if ch != ' ': + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-_': length += 1 ch = self.peek(length) - if ch != u'!': + if ch != '!': self.forward(length) raise ScannerError("while scanning a %s" % name, start_mark, "expected '!', but found %r" % ch.encode('utf-8'), @@ -1389,9 +1389,9 @@ def scan_tag_uri(self, name, start_mark): chunks = [] length = 0 ch = self.peek(length) - while u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \ - or ch in u'-;/?:@&=+$,_.!~*\'()[]%': - if ch == u'%': + while '0' <= ch <= '9' or 'A' <= ch <= 'Z' or 'a' <= ch <= 'z' \ + or ch in '-;/?:@&=+$,_.!~*\'()[]%': + if ch == '%': chunks.append(self.prefix(length)) self.forward(length) length = 0 @@ -1407,24 +1407,24 @@ def scan_tag_uri(self, name, start_mark): raise ScannerError("while parsing a %s" % name, start_mark, "expected URI, but found %r" % ch.encode('utf-8'), self.get_mark()) - return u''.join(chunks) + return ''.join(chunks) def scan_uri_escapes(self, name, start_mark): # See the specification for details. bytes = [] mark = self.get_mark() - while self.peek() == u'%': + while self.peek() == '%': self.forward() for k in range(2): - if self.peek(k) not in u'0123456789ABCDEFabcdef': + if self.peek(k) not in '0123456789ABCDEFabcdef': raise ScannerError("while scanning a %s" % name, start_mark, "expected URI escape sequence of 2 hexdecimal numbers, but found %r" % (self.peek(k).encode('utf-8')), self.get_mark()) bytes.append(chr(int(self.prefix(2), 16))) self.forward(2) try: - value = unicode(''.join(bytes), 'utf-8') - except UnicodeDecodeError, exc: + value = str(''.join(bytes), 'utf-8') + except UnicodeDecodeError as exc: raise ScannerError("while scanning a %s" % name, start_mark, str(exc), mark) return value @@ -1438,16 +1438,16 @@ def scan_line_break(self): # '\u2029 : '\u2029' # default : '' ch = self.peek() - if ch in u'\r\n\x85': - if self.prefix(2) == u'\r\n': + if ch in '\r\n\x85': + if self.prefix(2) == '\r\n': self.forward(2) else: self.forward() - return u'\n' - elif ch in u'\u2028\u2029': + return '\n' + elif ch in '\u2028\u2029': self.forward() return ch - return u'' + return '' #try: # import psyco diff --git a/toontown/pandautils/yaml/serializer.py b/toontown/pandautils/yaml/serializer.py index 0bf1e96dc..230bae76f 100644 --- a/toontown/pandautils/yaml/serializer.py +++ b/toontown/pandautils/yaml/serializer.py @@ -1,16 +1,16 @@ __all__ = ['Serializer', 'SerializerError'] -from error import YAMLError -from events import * -from nodes import * +from .error import YAMLError +from .events import * +from .nodes import * class SerializerError(YAMLError): pass class Serializer(object): - ANCHOR_TEMPLATE = u'id%03d' + ANCHOR_TEMPLATE = 'id%03d' def __init__(self, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None): diff --git a/toontown/parties/CalendarGuiMonth.py b/toontown/parties/CalendarGuiMonth.py index 8aec1f021..9465cc39a 100644 --- a/toontown/parties/CalendarGuiMonth.py +++ b/toontown/parties/CalendarGuiMonth.py @@ -29,7 +29,7 @@ def createDummyLocators(self): self.monthLocator = self.attachNewNode('monthLocator') self.monthLocator.setZ(0.6) self.weekDayLocators = [] - for i in xrange(7): + for i in range(7): self.weekDayLocators.append(self.attachNewNode('weekDayLocator-%d' % i)) self.weekDayLocators[i].setZ(0.5) self.weekDayLocators[i].setX(i * 0.24 + -0.75) @@ -37,9 +37,9 @@ def createDummyLocators(self): dayTopLeftX = -0.8 dayTopLeftZ = 0.4 self.dayLocators = [] - for row in xrange(6): + for row in range(6): oneWeek = [] - for col in xrange(7): + for col in range(7): newDayLoc = self.attachNewNode('dayLocator-row-%d-col-%d' % (row, col)) newDayLoc.setX(col * 0.24 + dayTopLeftX) newDayLoc.setZ(row * -0.18 + dayTopLeftZ) @@ -71,9 +71,9 @@ def load(self): self.attachMarker(weekDayLoc) self.dayLocators = [] - for row in xrange(6): + for row in range(6): oneWeek = [] - for col in xrange(7): + for col in range(7): newDayLoc = self.find('**/loc_box_%s_%s' % (row, col)) oneWeek.append(newDayLoc) @@ -97,7 +97,7 @@ def createGuiObjects(self): 246 / 255.0, 1.0)) self.weekdayLabels = [] - for posIndex in xrange(7): + for posIndex in range(7): adjustedNameIndex = (posIndex - 1) % 7 self.weekdayLabels.append(DirectLabel(parent=self.weekDayLocators[posIndex], relief=None, text=TTLocalizer.DayNamesAbbrev[adjustedNameIndex], text_font=ToontownGlobals.getInterfaceFont(), text_fg=(255 / 255.0, 146 / 255.0, diff --git a/toontown/parties/Decoration.py b/toontown/parties/Decoration.py index 39dc33056..7edddb583 100644 --- a/toontown/parties/Decoration.py +++ b/toontown/parties/Decoration.py @@ -211,7 +211,7 @@ def __init__(self, name, x, y, h): self.decorationModels = loader.loadModel('phase_4/models/parties/partyDecorations') self.decorationModels.copyTo(self) decors = self.findAllMatches('**/partyDecoration_*') - for i in xrange(decors.getNumPaths()): + for i in range(decors.getNumPaths()): decPiece = decors.getPath(i) n = decPiece.getName() if n.endswith('shadow') or n.endswith('base') or n.endswith('collision') or n.endswith(name): diff --git a/toontown/parties/DistributedParty.py b/toontown/parties/DistributedParty.py index c1868df6b..80ba3176a 100644 --- a/toontown/parties/DistributedParty.py +++ b/toontown/parties/DistributedParty.py @@ -322,8 +322,8 @@ def setPartyInfoTuple(self, partyInfoTuple): False]] def fillGrid(x, y, size): - for i in xrange(-size[1] / 2 + 1, size[1] / 2 + 1): - for j in xrange(-size[0] / 2 + 1, size[0] / 2 + 1): + for i in range(-size[1] / 2 + 1, size[1] / 2 + 1): + for j in range(-size[0] / 2 + 1, size[0] / 2 + 1): self.grid[i + y][j + x] = False for activityBase in self.partyInfo.activityList: @@ -371,7 +371,7 @@ def loadGrass(self): grass = loader.loadModel('phase_13/models/parties/grass') clearPositions = self.getClearSquarePositions() numTufts = min(len(clearPositions) * 3, PartyGlobals.TuftsOfGrass) - for i in xrange(numTufts): + for i in range(numTufts): g = grass.copyTo(self.grassRoot) pos = random.choice(clearPositions) g.setPos(pos[0] + random.randint(-8, 8), pos[1] + random.randint(-8, 8), 0.0) @@ -412,8 +412,8 @@ def announceGenerate(self): if config.GetBool('show-debug-party-grid', 0): self.testGrid = NodePath('test_grid') self.testGrid.reparentTo(base.cr.playGame.hood.loader.geom) - for i in xrange(len(self.grid)): - for j in xrange(len(self.grid[i])): + for i in range(len(self.grid)): + for j in range(len(self.grid[i])): cm = CardMaker('gridsquare') np = NodePath(cm.generate()) np.setScale(12) @@ -428,13 +428,13 @@ def announceGenerate(self): def getClearSquarePos(self): clearPositions = self.getClearSquarePositions() if len(clearPositions) == 0: - raise StandardError, 'Party %s has no empty grid squares.' % self.doId + raise Exception('Party %s has no empty grid squares.' % self.doId) return random.choice(clearPositions) def getClearSquarePositions(self): clearPositions = [] - for y in xrange(len(self.grid)): - for x in xrange(len(self.grid[0])): + for y in range(len(self.grid)): + for x in range(len(self.grid[0])): if self.grid[y][x]: pos = (PartyUtils.convertDistanceFromPartyGrid(x, 0), PartyUtils.convertDistanceFromPartyGrid(y, 1), 0.1) clearPositions.append(pos) diff --git a/toontown/parties/DistributedPartyAI.py b/toontown/parties/DistributedPartyAI.py index fadc392d9..1a5466732 100644 --- a/toontown/parties/DistributedPartyAI.py +++ b/toontown/parties/DistributedPartyAI.py @@ -149,7 +149,7 @@ def enteredParty(self): def removeAvatar(self, avId): if avId in self.avIdsAtParty: - print 'REMOVE FROM PARTTY!' + print('REMOVE FROM PARTTY!') self.air.globalPartyMgr.d_toonLeftParty(self.info.get('partyId', 0), avId) self.avIdsAtParty.remove(avId) diff --git a/toontown/parties/DistributedPartyActivity.py b/toontown/parties/DistributedPartyActivity.py index ecc9f7fe5..274a05610 100644 --- a/toontown/parties/DistributedPartyActivity.py +++ b/toontown/parties/DistributedPartyActivity.py @@ -192,7 +192,7 @@ def cleanup(self = self): def disable(self): self.notify.debug('BASE: disable') DistributedObject.DistributedObject.disable(self) - rorToonIds = self._toonId2ror.keys() + rorToonIds = list(self._toonId2ror.keys()) for toonId in rorToonIds: self.cr.relatedObjectMgr.abortRequest(self._toonId2ror[toonId]) del self._toonId2ror[toonId] diff --git a/toontown/parties/DistributedPartyCannon.py b/toontown/parties/DistributedPartyCannon.py index f96435439..2aca21d15 100644 --- a/toontown/parties/DistributedPartyCannon.py +++ b/toontown/parties/DistributedPartyCannon.py @@ -257,12 +257,12 @@ def setLanded(self, avId): def removeAvFromCannon(self, avId): place = base.cr.playGame.getPlace() av = base.cr.doId2do.get(avId) - print 'removeAvFromCannon' + print('removeAvFromCannon') if place: if not hasattr(place, 'fsm'): return placeState = place.fsm.getCurrentState().getName() - print placeState + print(placeState) if placeState != 'fishing': if av != None: av.startSmooth() diff --git a/toontown/parties/DistributedPartyCannonActivity.py b/toontown/parties/DistributedPartyCannonActivity.py index 5a659bdfc..0ba86214e 100644 --- a/toontown/parties/DistributedPartyCannonActivity.py +++ b/toontown/parties/DistributedPartyCannonActivity.py @@ -338,7 +338,7 @@ def setToonTrajectory(self, avId, launchTime, x, y, z, h, p, r, vx, vy, vz): def _remoteToonFlyTask(self, task = None): ids2del = [] frameTime = globalClock.getFrameTime() - for avId, trajInfo in self._avId2trajectoryInfo.iteritems(): + for avId, trajInfo in self._avId2trajectoryInfo.items(): trajectory = trajInfo.trajectory startTime = trajInfo.startT groundTime = trajectory.calcTimeOfImpactOnPlane(0.0) / self.TimeFactor + startTime diff --git a/toontown/parties/DistributedPartyCannonActivityAI.py b/toontown/parties/DistributedPartyCannonActivityAI.py index f24d5d81e..286de9650 100644 --- a/toontown/parties/DistributedPartyCannonActivityAI.py +++ b/toontown/parties/DistributedPartyCannonActivityAI.py @@ -44,7 +44,7 @@ def b_setCannonWillFire(self, cannonId, rot, angle, toonId): def cloudsColorRequest(self): avId = self.air.getAvatarIdFromSender() - self.sendUpdateToAvatarId(avId, 'cloudsColorResponse', [self.cloudColors.values()]) + self.sendUpdateToAvatarId(avId, 'cloudsColorResponse', [list(self.cloudColors.values())]) def requestCloudHit(self, cloudId, r, g, b): avId = self.air.getAvatarIdFromSender() diff --git a/toontown/parties/DistributedPartyCatchActivity.py b/toontown/parties/DistributedPartyCatchActivity.py index 6a82319d7..6c3003621 100644 --- a/toontown/parties/DistributedPartyCatchActivity.py +++ b/toontown/parties/DistributedPartyCatchActivity.py @@ -118,23 +118,23 @@ def load(self, loadModels = 1, arenaModel = 'partyCatchTree'): DistributedPartyCatchActivity.notify.debug('PartyCatch: load') self.activityFSM = CatchActivityFSM(self) if __dev__: - for o in xrange(3): - print {0: 'SPOTS PER PLAYER', + for o in range(3): + print({0: 'SPOTS PER PLAYER', 1: 'DROPS PER MINUTE PER SPOT DURING NORMAL DROP PERIOD', - 2: 'DROPS PER MINUTE PER PLAYER DURING NORMAL DROP PERIOD'}[o] - for i in xrange(1, self.FallRateCap_Players + 10): + 2: 'DROPS PER MINUTE PER PLAYER DURING NORMAL DROP PERIOD'}[o]) + for i in range(1, self.FallRateCap_Players + 10): self.defineConstants(forceNumPlayers=i) numDropLocations = self.DropRows * self.DropColumns numDropsPerMin = 60.0 / self.DropPeriod if o == 0: spotsPerPlayer = numDropLocations / float(i) - print '%2d PLAYERS: %s' % (i, spotsPerPlayer) + print('%2d PLAYERS: %s' % (i, spotsPerPlayer)) elif o == 1: numDropsPerMinPerSpot = numDropsPerMin / numDropLocations - print '%2d PLAYERS: %s' % (i, numDropsPerMinPerSpot) + print('%2d PLAYERS: %s' % (i, numDropsPerMinPerSpot)) elif i > 0: numDropsPerMinPerPlayer = numDropsPerMin / i - print '%2d PLAYERS: %s' % (i, numDropsPerMinPerPlayer) + print('%2d PLAYERS: %s' % (i, numDropsPerMinPerPlayer)) self.defineConstants() self.treesAndFence = loader.loadModel('phase_13/models/parties/%s' % arenaModel) @@ -214,7 +214,7 @@ def unload(self): self.stopDropTask() del self.activityFSM del self.__textGen - for avId in self.toonSDs.keys(): + for avId in list(self.toonSDs.keys()): if avId in self.toonSDs: toonSD = self.toonSDs[avId] toonSD.unload() @@ -225,7 +225,7 @@ def unload(self): self.dropShadow.removeNode() del self.dropShadow base.cr.parentMgr.unregisterParent(self._avatarNodePathParentToken) - for model in self.dropObjModels.values(): + for model in list(self.dropObjModels.values()): model.removeNode() del self.dropObjModels @@ -398,7 +398,7 @@ def showPosts(self): Toon.Toon(), Toon.Toon(), Toon.Toon()] - for i in xrange(len(self.posts)): + for i in range(len(self.posts)): tree = self.posts[i] tree.reparentTo(render) x = self.StageHalfWidth @@ -419,10 +419,10 @@ def hidePosts(self): def showDropGrid(self): self.hideDropGrid() self.dropMarkers = [] - for row in xrange(self.DropRows): + for row in range(self.DropRows): self.dropMarkers.append([]) rowList = self.dropMarkers[row] - for column in xrange(self.DropColumns): + for column in range(self.DropColumns): toon = Toon.Toon() toon.setDNA(base.localAvatar.getStyle()) toon.reparentTo(self.root) @@ -588,7 +588,7 @@ def finishDropInterval(self, generation, objNum): def finishAllDropIntervals(self): if hasattr(self, 'dropIntervals'): - for dropInterval in self.dropIntervals.values(): + for dropInterval in list(self.dropIntervals.values()): dropInterval.finish() def setGenerations(self, generations): @@ -601,7 +601,7 @@ def setGenerations(self, generations): gen2nt[id] = timestamp32 gen2np[id] = numPlayers - ids = self._id2gen.keys() + ids = list(self._id2gen.keys()) for id in ids: if id not in gen2t: self._removeGeneration(id) @@ -817,7 +817,7 @@ def finishActive(self): del self.finishIval if base.localAvatar.doId in self.toonIds: self.takeLocalAvatarOutOfActivity() - for ival in self.dropIntervals.values(): + for ival in list(self.dropIntervals.values()): ival.finish() del self.dropIntervals diff --git a/toontown/parties/DistributedPartyCatchActivityBase.py b/toontown/parties/DistributedPartyCatchActivityBase.py index 66730f03b..0ea760f2c 100644 --- a/toontown/parties/DistributedPartyCatchActivityBase.py +++ b/toontown/parties/DistributedPartyCatchActivityBase.py @@ -2,6 +2,7 @@ from direct.directnotify import DirectNotifyGlobal from toontown.minigame.DropScheduler import ThreePhaseDropScheduler from toontown.parties import PartyGlobals +from functools import reduce class DistributedPartyCatchActivityBase: notify = DirectNotifyGlobal.directNotify.newCategory('DistributedPartyCatchActivityBase') @@ -45,8 +46,8 @@ def scaledDimensions(widthHeight, scale): self.DropPeriod /= scaledNumPlayers typeProbs = {'fruit': 3, 'anvil': 1} - probSum = reduce(lambda x, y: x + y, typeProbs.values()) - for key in typeProbs.keys(): + probSum = reduce(lambda x, y: x + y, list(typeProbs.values())) + for key in list(typeProbs.keys()): typeProbs[key] = float(typeProbs[key]) / probSum scheduler = ThreePhaseDropScheduler(PartyGlobals.CatchActivityDuration, self.FirstDropDelay, self.DropPeriod, self.MaxDropDuration, self.SlowerDropPeriodMult, self.NormalDropDelay, self.FasterDropDelay, self.FasterDropPeriodMult) diff --git a/toontown/parties/DistributedPartyCogActivity.py b/toontown/parties/DistributedPartyCogActivity.py index de189aff7..e72afaf5f 100644 --- a/toontown/parties/DistributedPartyCogActivity.py +++ b/toontown/parties/DistributedPartyCogActivity.py @@ -1,9 +1,9 @@ from direct.distributed.ClockDelta import globalClockDelta from pandac.PandaModules import Point3 from toontown.toonbase import TTLocalizer -import PartyGlobals -from DistributedPartyTeamActivity import DistributedPartyTeamActivity -from PartyCogActivity import PartyCogActivity +from . import PartyGlobals +from .DistributedPartyTeamActivity import DistributedPartyTeamActivity +from .PartyCogActivity import PartyCogActivity class DistributedPartyCogActivity(DistributedPartyTeamActivity): notify = directNotify.newCategory('DistributedPartyCogActivity') diff --git a/toontown/parties/DistributedPartyCogActivityAI.py b/toontown/parties/DistributedPartyCogActivityAI.py index ef77044f2..2b1cde3bc 100644 --- a/toontown/parties/DistributedPartyCogActivityAI.py +++ b/toontown/parties/DistributedPartyCogActivityAI.py @@ -58,7 +58,7 @@ def d_setCogDistances(self): self.sendUpdate('setCogDistances', [self.cogDistances]) def calcReward(self): - for avId, s in self.scores.items(): + for avId, s in list(self.scores.items()): s = int(s / PartyGlobals.CogPinataPushBodyFactor) if s > self.highscore[1]: av = self.air.doId2do.get(avId) diff --git a/toontown/parties/DistributedPartyDance20Activity.py b/toontown/parties/DistributedPartyDance20Activity.py index 5721f6e72..72385da15 100644 --- a/toontown/parties/DistributedPartyDance20Activity.py +++ b/toontown/parties/DistributedPartyDance20Activity.py @@ -20,7 +20,7 @@ def load(self): correctBall = self.danceFloor.find('**/discoBall_20') if not correctBall.isEmpty(): numChildren = parentGroup.getNumChildren() - for i in xrange(numChildren): + for i in range(numChildren): child = parentGroup.getChild(i) if child != correctBall: child.hide() diff --git a/toontown/parties/DistributedPartyDanceActivity.py b/toontown/parties/DistributedPartyDanceActivity.py index dfb243d83..cbafaec8f 100644 --- a/toontown/parties/DistributedPartyDanceActivity.py +++ b/toontown/parties/DistributedPartyDanceActivity.py @@ -21,7 +21,7 @@ def load(self): origBall = self.danceFloor.find('**/discoBall_mesh_orig') if not correctBall.isEmpty(): numChildren = parentGroup.getNumChildren() - for i in xrange(numChildren): + for i in range(numChildren): child = parentGroup.getChild(i) if child != correctBall: child.hide() diff --git a/toontown/parties/DistributedPartyDanceActivityBase.py b/toontown/parties/DistributedPartyDanceActivityBase.py index 5305e6b4c..5d46df114 100644 --- a/toontown/parties/DistributedPartyDanceActivityBase.py +++ b/toontown/parties/DistributedPartyDanceActivityBase.py @@ -43,7 +43,7 @@ def __init__(self, cr, actId, dancePatternToAnims, model = 'phase_13/models/part def generateInit(self): self.notify.debug('generateInit') DistributedPartyActivity.generateInit(self) - self.keyCodes = KeyCodes(patterns=self.dancePatternToAnims.keys()) + self.keyCodes = KeyCodes(patterns=list(self.dancePatternToAnims.keys())) self.gui = KeyCodesGui(self.keyCodes) self.__initOrthoWalk() self.activityFSM = DanceActivityFSM(self) @@ -84,7 +84,7 @@ def unload(self): self.danceFloor.removeNode() self.danceFloor = None self.__destroyOrthoWalk() - for toonId in self.dancingToonFSMs.keys(): + for toonId in list(self.dancingToonFSMs.keys()): self.dancingToonFSMs[toonId].destroy() del self.dancingToonFSMs[toonId] diff --git a/toontown/parties/DistributedPartyFireworksActivity.py b/toontown/parties/DistributedPartyFireworksActivity.py index 9bcb8fd0d..3eafd1e31 100644 --- a/toontown/parties/DistributedPartyFireworksActivity.py +++ b/toontown/parties/DistributedPartyFireworksActivity.py @@ -16,7 +16,7 @@ from toontown.parties.PartyGlobals import FireworksPostLaunchDelay from toontown.parties.PartyGlobals import RocketSoundDelay from toontown.parties.PartyGlobals import RocketDirectionDelay -from DistributedPartyActivity import DistributedPartyActivity +from .DistributedPartyActivity import DistributedPartyActivity from toontown.parties.activityFSMs import FireworksActivityFSM from toontown.parties import PartyGlobals @@ -48,7 +48,7 @@ def load(self): self.launchPadModel.setPos(0.0, -18.0, 0.0) self.launchPadModel.reparentTo(self.root) railingsCollection = self.launchPadModel.findAllMatches('**/launchPad_mesh/*railing*') - for i in xrange(railingsCollection.getNumPaths()): + for i in range(railingsCollection.getNumPaths()): railingsCollection[i].setAttrib(AlphaTestAttrib.make(RenderAttrib.MGreater, 0.75)) leverLocator = self.launchPadModel.find('**/RocketLever_locator') diff --git a/toontown/parties/DistributedPartyJukeboxActivityBase.py b/toontown/parties/DistributedPartyJukeboxActivityBase.py index 5ddcc9979..8c1d857b9 100644 --- a/toontown/parties/DistributedPartyJukeboxActivityBase.py +++ b/toontown/parties/DistributedPartyJukeboxActivityBase.py @@ -123,7 +123,7 @@ def d_queuedSongsRequest(self): def queuedSongsResponse(self, songInfoList, index): if self.gui.isLoaded(): - for i in xrange(len(songInfoList)): + for i in range(len(songInfoList)): songInfo = songInfoList[i] self.__addSongToQueue(songInfo, isLocalQueue=index >= 0 and i == index) diff --git a/toontown/parties/DistributedPartyTeamActivityAI.py b/toontown/parties/DistributedPartyTeamActivityAI.py index a5a265eed..7f6c50fd5 100644 --- a/toontown/parties/DistributedPartyTeamActivityAI.py +++ b/toontown/parties/DistributedPartyTeamActivityAI.py @@ -100,7 +100,7 @@ def getPlayersPerTeam(self): def __areTeamsCorrect(self): minPlayers = self.getPlayersPerTeam()[0] - return all(len(self.toonIds[i]) >= minPlayers for i in xrange(2)) + return all(len(self.toonIds[i]) >= minPlayers for i in range(2)) def getDuration(self): raise NotImplementedError('getDuration() -- pure virtual') diff --git a/toontown/parties/DistributedPartyTrampolineActivity.py b/toontown/parties/DistributedPartyTrampolineActivity.py index 0e8bee73b..0245791f4 100644 --- a/toontown/parties/DistributedPartyTrampolineActivity.py +++ b/toontown/parties/DistributedPartyTrampolineActivity.py @@ -71,7 +71,7 @@ def __init__(self, cr, doJellyBeans = True, doTricks = False, texture = None): VBase4(0.4, 0.4, 1.0, 1.0), VBase4(1.0, 0.5, 1.0, 1.0)] delta = (self.jellyBeanStopHeight - self.jellyBeanStartHeight) / (self.numJellyBeans - 1) - self.jellyBeanPositions = [ self.jellyBeanStartHeight + n * delta for n in xrange(self.numJellyBeans) ] + self.jellyBeanPositions = [ self.jellyBeanStartHeight + n * delta for n in range(self.numJellyBeans) ] self.doSimulateStep = False def load(self): @@ -99,7 +99,7 @@ def loadModels(self): self.surface.setZ(self.trampHeight) self.trampActor.controlJoint(self.surface, 'modelRoot', 'trampoline_joint1') self.sign.setPos(PartyGlobals.TrampolineSignOffset) - self.beans = [ loader.loadModelCopy('phase_4/models/props/jellybean4') for i in xrange(self.numJellyBeans) ] + self.beans = [ loader.loadModelCopy('phase_4/models/props/jellybean4') for i in range(self.numJellyBeans) ] for bean in self.beans: bean.find('**/jellybean').setP(-35.0) bean.setScale(3.0) @@ -133,7 +133,7 @@ def loadGUI(self): jumpLineLocator = self.gui.find('**/jumpLine_locator') guiBean = self.gui.find('**/trampolineGUI_GreenJellyBean') self.gui.find('**/trampolineGUI_GreenJellyBean').stash() - self.guiBeans = [ guiBean.instanceUnderNode(jumpLineLocator, self.uniqueName('guiBean%d' % i)) for i in xrange(self.numJellyBeans) ] + self.guiBeans = [ guiBean.instanceUnderNode(jumpLineLocator, self.uniqueName('guiBean%d' % i)) for i in range(self.numJellyBeans) ] self.guiBeans[-1].setScale(1.5) heightTextNode = TextNode(self.uniqueName('TrampolineActivity.heightTextNode')) heightTextNode.setFont(ToontownGlobals.getSignFont()) @@ -295,7 +295,7 @@ def setupJellyBeans(self): self.beansToCollect = [] self.beanDetails = [] self.numBeansCollected = 0 - for i in xrange(self.numJellyBeans): + for i in range(self.numJellyBeans): bean = self.beans[i] guiBean = self.guiBeans[i] height = self.jellyBeanPositions[i] @@ -319,7 +319,7 @@ def setupJellyBeans(self): guiBean, beanAnim)) - self.beansToCollect = range(self.numJellyBeans) + self.beansToCollect = list(range(self.numJellyBeans)) def cleanupJellyBeans(self): for bean in self.beans: diff --git a/toontown/parties/DistributedPartyTrampolineActivityAI.py b/toontown/parties/DistributedPartyTrampolineActivityAI.py index 166a7ca64..c7c52834c 100644 --- a/toontown/parties/DistributedPartyTrampolineActivityAI.py +++ b/toontown/parties/DistributedPartyTrampolineActivityAI.py @@ -59,7 +59,7 @@ def reportHeightInformation(self, height): self.air.writeServerEvent('suspicious',avId,'Toon incorrectly reported height!') def enterActive(self): - self.jellybeans = range(PartyGlobals.TrampolineNumJellyBeans) + self.jellybeans = list(range(PartyGlobals.TrampolineNumJellyBeans)) taskMgr.doMethodLater(PartyGlobals.TrampolineDuration, self.sendUpdate, 'exitTrampoline%d' % self.doId, extraArgs=['leaveTrampoline', []]) self.sendUpdate('setState', ['Active', globalClockDelta.getRealNetworkTime()]) self.collected = 0 diff --git a/toontown/parties/DistributedPartyTugOfWarActivity.py b/toontown/parties/DistributedPartyTugOfWarActivity.py index dc10cda7c..a5c0eac10 100644 --- a/toontown/parties/DistributedPartyTugOfWarActivity.py +++ b/toontown/parties/DistributedPartyTugOfWarActivity.py @@ -12,7 +12,7 @@ from toontown.minigame.MinigamePowerMeter import MinigamePowerMeter from toontown.minigame.ArrowKeys import ArrowKeys from toontown.parties import PartyGlobals, PartyUtils -from DistributedPartyTeamActivity import DistributedPartyTeamActivity +from .DistributedPartyTeamActivity import DistributedPartyTeamActivity class DistributedPartyTugOfWarActivity(DistributedPartyTeamActivity): notify = directNotify.newCategory('DistributedPartyTugOfWarActivity') @@ -143,24 +143,24 @@ def loadModels(self): self.playArea.reparentTo(self.root) self.sign.reparentTo(self.playArea.find('**/TugOfWar_sign_locator')) self.dockPositions = [[], []] - for i in xrange(4): + for i in range(4): self.dockPositions[0].append(Point3(-PartyGlobals.TugOfWarInitialToonPositionsXOffset - PartyGlobals.TugOfWarToonPositionXSeparation * i, 0.0, PartyGlobals.TugOfWarToonPositionZ)) - for i in xrange(4): + for i in range(4): self.dockPositions[1].append(Point3(PartyGlobals.TugOfWarInitialToonPositionsXOffset + PartyGlobals.TugOfWarToonPositionXSeparation * i, 0.0, PartyGlobals.TugOfWarToonPositionZ)) self.hopOffPositions = [[], []] - for i in xrange(1, 5): + for i in range(1, 5): self.hopOffPositions[PartyGlobals.TeamActivityTeams.LeftTeam].append(self.playArea.find('**/leftTeamHopOff%d_locator' % i).getPos()) self.hopOffPositions[PartyGlobals.TeamActivityTeams.RightTeam].append(self.playArea.find('**/rightTeamHopOff%d_locator' % i).getPos()) - for i in xrange(1, 5): + for i in range(1, 5): pos = self.playArea.find('**/fallenToon%d_locator' % i).getPos() self.fallenPositions.append(pos) self.joinCollision = [] self.joinCollisionNodePaths = [] - for i in xrange(len(PartyGlobals.TeamActivityTeams)): + for i in range(len(PartyGlobals.TeamActivityTeams)): collShape = CollisionTube(PartyGlobals.TugOfWarJoinCollisionEndPoints[0], PartyGlobals.TugOfWarJoinCollisionEndPoints[1], PartyGlobals.TugOfWarJoinCollisionRadius) collShape.setTangible(True) self.joinCollision.append(CollisionNode('TugOfWarJoinCollision%d' % i)) @@ -174,7 +174,7 @@ def loadModels(self): ropeModel = loader.loadModel('phase_4/models/minigames/tug_of_war_rope') self.ropeTexture = ropeModel.findTexture('*') ropeModel.removeNode() - for i in xrange(PartyGlobals.TugOfWarMaximumPlayersPerTeam * 2 - 1): + for i in range(PartyGlobals.TugOfWarMaximumPlayersPerTeam * 2 - 1): rope = Rope(self.uniqueName('TugRope%d' % i)) if rope.showRope: rope.ropeNode.setRenderMode(RopeNode.RMBillboard) @@ -200,7 +200,7 @@ def loadGuiElements(self): self.powerMeter.setPos(0.0, 0.0, 0.6) self.powerMeter.hide() self.arrows = [None] * 2 - for x in xrange(len(self.arrows)): + for x in range(len(self.arrows)): self.arrows[x] = loader.loadModel('phase_3/models/props/arrow') self.arrows[x].reparentTo(self.powerMeter) self.arrows[x].setScale(0.2 - 0.4 * x, 0.2, 0.2) @@ -213,7 +213,7 @@ def loadSounds(self): def loadIntervals(self): self.updateIdealRateInterval = Sequence() self.updateIdealRateInterval.append(Wait(PartyGlobals.TugOfWarTargetRateList[0][0])) - for i in xrange(1, len(PartyGlobals.TugOfWarTargetRateList)): + for i in range(1, len(PartyGlobals.TugOfWarTargetRateList)): duration = PartyGlobals.TugOfWarTargetRateList[i][0] idealRate = PartyGlobals.TugOfWarTargetRateList[i][1] self.updateIdealRateInterval.append(Func(self.setIdealRate, idealRate)) @@ -311,11 +311,11 @@ def unloadIntervals(self): del self.splashInterval def __enableCollisions(self): - for i in xrange(len(PartyGlobals.TeamActivityTeams)): + for i in range(len(PartyGlobals.TeamActivityTeams)): self.accept('enterTugOfWarJoinCollision%d' % i, getattr(self, '_join%s' % PartyGlobals.TeamActivityTeams.getString(i))) def __disableCollisions(self): - for i in xrange(len(PartyGlobals.TeamActivityTeams)): + for i in range(len(PartyGlobals.TeamActivityTeams)): self.ignore('enterTugOfWarJoinCollision%d' % i) def startWaitForEnough(self): @@ -413,7 +413,7 @@ def startConclusion(self, losingTeam): if self.getAvatar(toonId): self.getAvatar(toonId).loop('victory') - for ival in self.toonIdsToAnimIntervals.values(): + for ival in list(self.toonIdsToAnimIntervals.values()): if ival is not None: ival.finish() @@ -462,7 +462,7 @@ def setUpRopes(self): for currTeam in teams: numToons = len(self.toonIds[currTeam]) if numToons > 1: - for i in xrange(numToons - 1, 0, -1): + for i in range(numToons - 1, 0, -1): toon1 = self.toonIds[currTeam][i] toon2 = self.toonIds[currTeam][i - 1] if toon1 not in self.toonIdsToRightHands: @@ -503,10 +503,10 @@ def setIdealRate(self, idealRate): self.idealForce = self.advantage * (4 + 0.4 * self.idealRate) def updateKeyPressRate(self): - for i in xrange(len(self.keyTTL)): + for i in range(len(self.keyTTL)): self.keyTTL[i] -= PartyGlobals.TugOfWarKeyPressUpdateRate - for i in xrange(len(self.keyTTL)): + for i in range(len(self.keyTTL)): if self.keyTTL[i] <= 0.0: a = self.keyTTL[0:i] del self.keyTTL diff --git a/toontown/parties/DistributedPartyValentineDance20Activity.py b/toontown/parties/DistributedPartyValentineDance20Activity.py index 47399e19e..7b5db749f 100644 --- a/toontown/parties/DistributedPartyValentineDance20Activity.py +++ b/toontown/parties/DistributedPartyValentineDance20Activity.py @@ -20,7 +20,7 @@ def load(self): correctBall = self.danceFloor.find('**/discoBall_20') if not correctBall.isEmpty(): numChildren = parentGroup.getNumChildren() - for i in xrange(numChildren): + for i in range(numChildren): child = parentGroup.getChild(i) if child != correctBall: child.hide() diff --git a/toontown/parties/DistributedPartyValentineDanceActivity.py b/toontown/parties/DistributedPartyValentineDanceActivity.py index d61d5e40f..7652d1f6d 100644 --- a/toontown/parties/DistributedPartyValentineDanceActivity.py +++ b/toontown/parties/DistributedPartyValentineDanceActivity.py @@ -21,7 +21,7 @@ def load(self): origBall = self.danceFloor.find('**/discoBall_mesh_orig') if not correctBall.isEmpty(): numChildren = parentGroup.getNumChildren() - for i in xrange(numChildren): + for i in range(numChildren): child = parentGroup.getChild(i) if child != correctBall: child.hide() diff --git a/toontown/parties/InviteVisual.py b/toontown/parties/InviteVisual.py index c000abb7d..4c5d9c34f 100644 --- a/toontown/parties/InviteVisual.py +++ b/toontown/parties/InviteVisual.py @@ -94,7 +94,7 @@ def insertCarriageReturn(self, stringLeft, stringDone = ''): desiredNumberOfCharactersInLine = 42 if len(stringLeft) < desiredNumberOfCharactersInLine: return stringDone + '\n' + stringLeft - for i in xrange(desiredNumberOfCharactersInLine - 6, len(stringLeft)): + for i in range(desiredNumberOfCharactersInLine - 6, len(stringLeft)): if stringLeft[i] == ' ': return self.insertCarriageReturn(stringLeft[i:], stringDone + '\n' + stringLeft[:i]) diff --git a/toontown/parties/JukeboxGui.py b/toontown/parties/JukeboxGui.py index 362a455d7..f3cb1836d 100644 --- a/toontown/parties/JukeboxGui.py +++ b/toontown/parties/JukeboxGui.py @@ -56,13 +56,13 @@ def enable(self, timer = 0): self.load() phase = 13 tunes = self.phaseToMusicData[13] - for filename, info in tunes.items(): + for filename, info in list(tunes.items()): self.addToSongList(info[0], phase, filename, info[1]) - for phase, tunes in self.phaseToMusicData.items(): + for phase, tunes in list(self.phaseToMusicData.items()): if phase == 13: continue - for filename, info in tunes.items(): + for filename, info in list(tunes.items()): self.addToSongList(info[0], phase, filename, info[1]) self._windowFrame.show() diff --git a/toontown/parties/KeyCodes.py b/toontown/parties/KeyCodes.py index e1a4f3e06..16c11e3cd 100644 --- a/toontown/parties/KeyCodes.py +++ b/toontown/parties/KeyCodes.py @@ -79,7 +79,7 @@ def disable(self): return def __enableControls(self): - for key in self._keyMap.keys(): + for key in list(self._keyMap.keys()): self.__acceptKeyDown(key) self.__acceptKeyUp(key) diff --git a/toontown/parties/KeyCodesGui.py b/toontown/parties/KeyCodesGui.py index d96460200..cca416965 100644 --- a/toontown/parties/KeyCodesGui.py +++ b/toontown/parties/KeyCodesGui.py @@ -31,7 +31,7 @@ def load(self): minnieArrow.setScale(0.6) minnieArrow.setZ(self._yOffset + 0.2) maxLength = self._keyCodes.getLargestPatternLength() - for i in xrange(maxLength): + for i in range(maxLength): arrow = minnieArrow.copyTo(hidden) self._arrowNodes.append(arrow) @@ -65,7 +65,7 @@ def disable(self): def hideArrows(self, startIndex = 0): length = len(self._arrowNodes) if startIndex < length: - for i in xrange(startIndex, length): + for i in range(startIndex, length): self._arrowNodes[i].reparentTo(hidden) def hideAll(self, startIndex = 0): @@ -108,7 +108,7 @@ def __handleTimeoutTask(self, task): def __centerArrows(self): length = self._keyCodes.getCurrentInputLength() - for i in xrange(length): + for i in range(length): x = -(length * self._arrowWidth * 0.5) + self._arrowWidth * (i + 0.5) self._arrowNodes[i].setX(x) diff --git a/toontown/parties/PartyCog.py b/toontown/parties/PartyCog.py index 770236a2d..e2d1d710f 100644 --- a/toontown/parties/PartyCog.py +++ b/toontown/parties/PartyCog.py @@ -30,7 +30,7 @@ def unload(self): cog.unload() def updateDistances(self, distances): - for i in xrange(len(distances)): + for i in range(len(distances)): self.cogs[i].updateDistance(distances[i]) diff --git a/toontown/parties/PartyCogActivity.py b/toontown/parties/PartyCogActivity.py index 5f95866c9..e79e80111 100644 --- a/toontown/parties/PartyCogActivity.py +++ b/toontown/parties/PartyCogActivity.py @@ -71,7 +71,7 @@ def load(self): self.arrows = [] self.distanceLabels = [] self.teamColors = list(PartyGlobals.CogActivityColors) + [PartyGlobals.TeamActivityStatusColor] - for i in xrange(3): + for i in range(3): start = self.arena.find('**/cog%d_start_locator' % (i + 1)) end = self.arena.find('**/cog%d_end_locator' % (i + 1)) cog = self.cogManager.generateCog(self.arena) @@ -106,13 +106,13 @@ def load(self): def _initArenaDoors(self): self._arenaDoors = (self.arena.find('**/doorL'), self.arena.find('**/doorR')) arenaDoorLocators = (self.arena.find('**/doorL_locator'), self.arena.find('**/doorR_locator')) - for i in xrange(len(arenaDoorLocators)): + for i in range(len(arenaDoorLocators)): arenaDoorLocators[i].wrtReparentTo(self._arenaDoors[i]) self._arenaDoorTimers = (self.createDoorTimer(PartyGlobals.TeamActivityTeams.LeftTeam), self.createDoorTimer(PartyGlobals.TeamActivityTeams.RightTeam)) self._arenaDoorIvals = [None, None] self._doorStartPos = [] - for i in xrange(len(self._arenaDoors)): + for i in range(len(self._arenaDoors)): door = self._arenaDoors[i] timer = self._arenaDoorTimers[i] timer.reparentTo(arenaDoorLocators[i]) @@ -198,7 +198,7 @@ def unload(self): self.distanceLabels = None if len(self.players): - for player in self.players.values(): + for player in list(self.players.values()): player.disable() player.destroy() @@ -215,11 +215,11 @@ def unload(self): self._destroyArenaDoors() self.arena.removeNode() self.arena = None - for ival in self.toonPieTracks.values(): + for ival in list(self.toonPieTracks.values()): if ival is not None and ival.isPlaying(): try: ival.finish() - except Exception, theException: + except Exception as theException: self.notify.warning('Ival could not finish:\n %s \nException %s ' % (str(ival), str(theException))) self.toonPieTracks = {} @@ -227,12 +227,12 @@ def unload(self): if ival is not None and ival.isPlaying(): try: ival.finish() - except Exception, theException: + except Exception as theException: self.notify.warning('Ival could not finish:\n %s \nException %s ' % (str(ival), str(theException))) self.pieIvals = [] self.toonIdsToAnimIntervals = {} - for eventName in self.toonPieEventNames.values(): + for eventName in list(self.toonPieEventNames.values()): self.ignore(eventName) self.toonPieEventNames = {} @@ -271,12 +271,12 @@ def closeArenaDoorForTeam(self, team): def openArenaDoors(self): self.enableEnterGateCollision() - for i in xrange(len(self._arenaDoors)): + for i in range(len(self._arenaDoors)): self.openArenaDoorForTeam(i) def closeArenaDoors(self): self.disableEnterGateCollision() - for i in xrange(len(self._arenaDoors)): + for i in range(len(self._arenaDoors)): self.closeArenaDoorForTeam(i) def showArenaDoorTimers(self, duration): @@ -418,7 +418,7 @@ def startActivity(self, timestamp): if self.player is not None: self.player.resetScore() self.hideTeamFlags(self.player.team) - for player in self.players.values(): + for player in list(self.players.values()): self.finishToonIval(player.toon.doId) player.enable() @@ -433,10 +433,10 @@ def startActivity(self, timestamp): return def stopActivity(self): - for player in self.players.values(): + for player in list(self.players.values()): player.disable() - for eventName in self.toonPieEventNames.values(): + for eventName in list(self.toonPieEventNames.values()): self.ignore(eventName) self.toonPieEventNames.clear() @@ -636,7 +636,7 @@ def showArrow(self, arrowNum): for point in points: point.setY(Y) - for i in xrange(len(arrows)): + for i in range(len(arrows)): arrow = arrows[i] arrow.draw(points[i].getPos(), cog.root.getPos(), animate=False) arrow.unstash() diff --git a/toontown/parties/PartyCogActivityGui.py b/toontown/parties/PartyCogActivityGui.py index 9a58cd31c..1854e799d 100644 --- a/toontown/parties/PartyCogActivityGui.py +++ b/toontown/parties/PartyCogActivityGui.py @@ -26,7 +26,7 @@ def __init__(self): i = 0 self.cogTracker.find('**/shadow').setBin('fixed', 0) self.cogTracker.find('**/plane').setBin('fixed', 1) - for i in xrange(3): + for i in range(3): layers = [self.cogTracker.find('**/cog%d_blue' % i), self.cogTracker.find('**/cog%d_orange' % i), self.cogTracker.find('**/cog%d_white' % i)] self.cogs.append(self.cogTracker.find('**/cog%d' % i)) self.cogLayers.append(layers) diff --git a/toontown/parties/PartyCogActivityPlayer.py b/toontown/parties/PartyCogActivityPlayer.py index 940cd93a7..79fecaa2d 100644 --- a/toontown/parties/PartyCogActivityPlayer.py +++ b/toontown/parties/PartyCogActivityPlayer.py @@ -12,10 +12,10 @@ from toontown.battle.BattleProps import globalPropPool from toontown.battle.BattleSounds import globalBattleSoundCache from toontown.parties import PartyGlobals -from PartyCogActivityInput import PartyCogActivityInput -from PartyCogActivityGui import PartyCogActivityGui -from PartyCogUtils import CameraManager -from PartyCogUtils import StrafingControl +from .PartyCogActivityInput import PartyCogActivityInput +from .PartyCogActivityGui import PartyCogActivityGui +from .PartyCogUtils import CameraManager +from .PartyCogUtils import StrafingControl UPDATE_TASK_NAME = 'PartyCogActivityLocalPlayer_UpdateTask' THROW_PIE_LIMIT_TIME = 0.2 diff --git a/toontown/parties/PartyEditor.py b/toontown/parties/PartyEditor.py index b736e3f96..9a695c498 100644 --- a/toontown/parties/PartyEditor.py +++ b/toontown/parties/PartyEditor.py @@ -1,5 +1,4 @@ import time -from sets import Set from pandac.PandaModules import Vec3, Vec4, Point3, TextNode, VBase4 from toontown.pgui.DirectGui import DirectFrame, DirectButton, DirectLabel, DirectScrolledList, DirectCheckButton from toontown.pgui import DirectGuiGlobals @@ -14,7 +13,7 @@ from toontown.parties.PartyEditorGrid import PartyEditorGrid from toontown.parties.PartyEditorListElement import PartyEditorListElement -class PartyEditor(DirectObject, FSM): +class PartyEditor(FSM, DirectObject): notify = directNotify.newCategory('PartyEditor') def __init__(self, partyPlanner, parent): @@ -171,13 +170,13 @@ def handleMutuallyExclusiveActivities(self): def getMutuallyExclusiveActivities(self): currentActivities = self.partyEditorGrid.getActivitiesOnGrid() - actSet = Set([]) + actSet = set([]) for act in currentActivities: actSet.add(act[0]) result = None for mutuallyExclusiveTuples in PartyGlobals.MutuallyExclusiveActivities: - mutSet = Set(mutuallyExclusiveTuples) + mutSet = set(mutuallyExclusiveTuples) inter = mutSet.intersection(actSet) if len(inter) > 1: result = inter diff --git a/toontown/parties/PartyEditorGrid.py b/toontown/parties/PartyEditorGrid.py index 0ae39c04a..0a22eca0b 100644 --- a/toontown/parties/PartyEditorGrid.py +++ b/toontown/parties/PartyEditorGrid.py @@ -290,8 +290,8 @@ def initGrid(self): None, None, None]] - for y in xrange(len(self.grid)): - for x in xrange(len(self.grid[0])): + for y in range(len(self.grid)): + for x in range(len(self.grid[0])): if self.grid[y][x]: self.grid[y][x] = PartyEditorGridSquare(self.partyEditor, x, y) @@ -299,8 +299,8 @@ def initGrid(self): def getActivitiesOnGrid(self): activities = [] - for y in xrange(len(self.grid)): - for x in xrange(len(self.grid[0])): + for y in range(len(self.grid)): + for x in range(len(self.grid[0])): if self.grid[y][x] and self.grid[y][x].gridElement: if not self.grid[y][x].gridElement.isDecoration: activityTuple = self.grid[y][x].gridElement.getActivityTuple(x, y) @@ -312,8 +312,8 @@ def getActivitiesOnGrid(self): def getActivitiesElementsOnGrid(self): activities = [] activityElems = [] - for y in xrange(len(self.grid)): - for x in xrange(len(self.grid[0])): + for y in range(len(self.grid)): + for x in range(len(self.grid[0])): if self.grid[y][x] and self.grid[y][x].gridElement: if not self.grid[y][x].gridElement.isDecoration: activityTuple = self.grid[y][x].gridElement.getActivityTuple(x, y) @@ -325,8 +325,8 @@ def getActivitiesElementsOnGrid(self): def getDecorationsOnGrid(self): decorations = [] - for y in xrange(len(self.grid)): - for x in xrange(len(self.grid[0])): + for y in range(len(self.grid)): + for x in range(len(self.grid[0])): if self.grid[y][x] and self.grid[y][x].gridElement: if self.grid[y][x].gridElement.isDecoration: decorationTuple = self.grid[y][x].gridElement.getDecorationTuple(x, y) @@ -344,8 +344,8 @@ def getGridSquare(self, x, y): def checkGridSquareForAvailability(self, gridSquare, size): xOffsetLow, xOffsetHigh, yOffset = self.getXYOffsets(size) - for y in xrange(int(gridSquare.y - size[1] / 2), int(gridSquare.y + size[1] / 2) + yOffset): - for x in xrange(int(gridSquare.x - size[0] / 2) + xOffsetLow, int(gridSquare.x + size[0] / 2) + xOffsetHigh): + for y in range(int(gridSquare.y - size[1] / 2), int(gridSquare.y + size[1] / 2) + yOffset): + for x in range(int(gridSquare.x - size[0] / 2) + xOffsetLow, int(gridSquare.x + size[0] / 2) + xOffsetHigh): testGridSquare = self.getGridSquare(x, y) if testGridSquare is None: return False @@ -361,8 +361,8 @@ def getClearGridSquare(self, size, desiredXY = None): if self.grid[y][x] is not None: if self.checkGridSquareForAvailability(self.grid[y][x], size): return self.grid[y][x] - for y in xrange(PartyGlobals.PartyEditorGridSize[1]): - for x in xrange(PartyGlobals.PartyEditorGridSize[0]): + for y in range(PartyGlobals.PartyEditorGridSize[1]): + for x in range(PartyGlobals.PartyEditorGridSize[0]): if self.grid[y][x] is not None: if self.checkGridSquareForAvailability(self.grid[y][x], size): return self.grid[y][x] @@ -384,8 +384,8 @@ def getXYOffsets(self, size): def registerNewElement(self, gridElement, centerGridSquare, size): xOffsetLow, xOffsetHigh, yOffset = self.getXYOffsets(size) - for y in xrange(int(centerGridSquare.y - size[1] / 2), int(centerGridSquare.y + size[1] / 2) + yOffset): - for x in xrange(int(centerGridSquare.x - size[0] / 2) + xOffsetLow, int(centerGridSquare.x + size[0] / 2) + xOffsetHigh): + for y in range(int(centerGridSquare.y - size[1] / 2), int(centerGridSquare.y + size[1] / 2) + yOffset): + for x in range(int(centerGridSquare.x - size[0] / 2) + xOffsetLow, int(centerGridSquare.x + size[0] / 2) + xOffsetHigh): testGridSquare = self.getGridSquare(x, y) if testGridSquare is None: return False @@ -400,8 +400,8 @@ def registerNewElement(self, gridElement, centerGridSquare, size): def removeElement(self, centerGridSquare, size): xOffsetLow, xOffsetHigh, yOffset = self.getXYOffsets(size) - for y in xrange(int(centerGridSquare.y - size[1] / 2), int(centerGridSquare.y + size[1] / 2) + yOffset): - for x in xrange(int(centerGridSquare.x - size[0] / 2) + xOffsetLow, int(centerGridSquare.x + size[0] / 2) + xOffsetHigh): + for y in range(int(centerGridSquare.y - size[1] / 2), int(centerGridSquare.y + size[1] / 2) + yOffset): + for x in range(int(centerGridSquare.x - size[0] / 2) + xOffsetLow, int(centerGridSquare.x + size[0] / 2) + xOffsetHigh): testGridSquare = self.getGridSquare(x, y) if testGridSquare is None: return False @@ -414,8 +414,8 @@ def removeElement(self, centerGridSquare, size): def destroy(self): self.partyEditor = None - for y in xrange(len(self.grid)): - for x in xrange(len(self.grid[0])): + for y in range(len(self.grid)): + for x in range(len(self.grid[0])): if self.grid[y][x]: self.grid[y][x].destroy() diff --git a/toontown/parties/PartyEditorListElement.py b/toontown/parties/PartyEditorListElement.py index d1ddc7c71..3f765ef8f 100644 --- a/toontown/parties/PartyEditorListElement.py +++ b/toontown/parties/PartyEditorListElement.py @@ -79,11 +79,11 @@ def __init__(self, partyEditor, id, isDecoration = False, **kw): self.bind(DirectGuiGlobals.B1RELEASE, self.released) self.partyEditorGridElements = [] if self.isDecoration: - for i in xrange(PartyGlobals.DecorationInformationDict[self.id]['limitPerParty']): + for i in range(PartyGlobals.DecorationInformationDict[self.id]['limitPerParty']): self.partyEditorGridElements.append(PartyEditorGridElement(self.partyEditor, self.id, self.isDecoration, self.checkSoldOutAndPaidStatusAndAffordability)) else: - for i in xrange(PartyGlobals.ActivityInformationDict[self.id]['limitPerParty']): + for i in range(PartyGlobals.ActivityInformationDict[self.id]['limitPerParty']): self.partyEditorGridElements.append(PartyEditorGridElement(self.partyEditor, self.id, self.isDecoration, self.checkSoldOutAndPaidStatusAndAffordability)) self.activeGridElementIndex = -1 @@ -140,7 +140,7 @@ def checkSoldOutAndPaidStatusAndAffordability(self): else: self.setTooExpensive(False) tooExpensive = False - for i in xrange(len(self.partyEditorGridElements)): + for i in range(len(self.partyEditorGridElements)): if not self.partyEditorGridElements[i].overValidSquare: if not tooExpensive: self.setSoldOut(False) @@ -180,14 +180,14 @@ def setSoldOut(self, value): def clicked(self, mouseEvent): PartyEditorListElement.notify.debug("Element %s's icon was clicked" % self.name) self.partyEditor.listElementClicked() - for i in xrange(len(self.partyEditorGridElements)): + for i in range(len(self.partyEditorGridElements)): if not self.partyEditorGridElements[i].overValidSquare: self.partyEditorGridElements[i].attach(mouseEvent) self.activeGridElementIndex = i return def buyButtonClicked(self, desiredXY = None): - for i in xrange(len(self.partyEditorGridElements)): + for i in range(len(self.partyEditorGridElements)): if not self.partyEditorGridElements[i].overValidSquare: if self.partyEditorGridElements[i].placeInPartyGrounds(desiredXY): self.activeGridElementIndex = i diff --git a/toontown/parties/PartyGlobals.py b/toontown/parties/PartyGlobals.py index efd4732b6..087a0c29b 100644 --- a/toontown/parties/PartyGlobals.py +++ b/toontown/parties/PartyGlobals.py @@ -651,9 +651,9 @@ def isBaseline(self): Name2DropObjectType[type.name] = type Name2DOTypeId = {} -names = Name2DropObjectType.keys() +names = list(Name2DropObjectType.keys()) names.sort() -for i in xrange(len(names)): +for i in range(len(names)): Name2DOTypeId[names[i]] = i DOTypeId2Name = names @@ -818,12 +818,12 @@ def countMusic(): for key in PhaseToMusicData: numMusic += len(PhaseToMusicData[key]) - print 'PhaseToMusicData %d' % numMusic + print('PhaseToMusicData %d' % numMusic) numMusic = 0 for key in PhaseToMusicData40: numMusic += len(PhaseToMusicData40[key]) - print 'PhaseToMusicData40 %d' % numMusic + print('PhaseToMusicData40 %d' % numMusic) def getMusicRepeatTimes(length, minLength = MUSIC_MIN_LENGTH_SECONDS): diff --git a/toontown/parties/PartyLoader.py b/toontown/parties/PartyLoader.py index 4d7d407d1..d903b1d69 100644 --- a/toontown/parties/PartyLoader.py +++ b/toontown/parties/PartyLoader.py @@ -42,8 +42,8 @@ def load(self): self.underwaterSound = base.loader.loadSfx('phase_4/audio/sfx/AV_ambient_water.ogg') self.swimSound = base.loader.loadSfx('phase_4/audio/sfx/AV_swim_single_stroke.ogg') self.submergeSound = base.loader.loadSfx('phase_5.5/audio/sfx/AV_jump_in_water.ogg') - self.birdSound = map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg']) - self.cricketSound = map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg']) + self.birdSound = list(map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg'])) + self.cricketSound = list(map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg'])) def unload(self): self.ignoreAll() @@ -205,15 +205,15 @@ def __cloudTrack(self): return track def debugGeom(self, decomposed): - print 'numPrimitives = %d' % decomposed.getNumPrimitives() - for primIndex in xrange(decomposed.getNumPrimitives()): + print('numPrimitives = %d' % decomposed.getNumPrimitives()) + for primIndex in range(decomposed.getNumPrimitives()): prim = decomposed.getPrimitive(primIndex) - print 'prim = %s' % prim - print 'isIndexed = %d' % prim.isIndexed() - print 'prim.getNumPrimitives = %d' % prim.getNumPrimitives() - for basicPrim in xrange(prim.getNumPrimitives()): - print '%d start=%d' % (basicPrim, prim.getPrimitiveStart(basicPrim)) - print '%d end=%d' % (basicPrim, prim.getPrimitiveEnd(basicPrim)) + print('prim = %s' % prim) + print('isIndexed = %d' % prim.isIndexed()) + print('prim.getNumPrimitives = %d' % prim.getNumPrimitives()) + for basicPrim in range(prim.getNumPrimitives()): + print('%d start=%d' % (basicPrim, prim.getPrimitiveStart(basicPrim))) + print('%d end=%d' % (basicPrim, prim.getPrimitiveEnd(basicPrim))) def loadCloud(self, version, radius, zOffset): self.notify.debug('loadOnePlatform version=%d' % version) @@ -242,13 +242,13 @@ def loadCloudPlatforms(self): self.cloudOrigin.setZ(30) self.loadSkyCollision() self.numClouds = 12 - for i in xrange(self.numClouds): + for i in range(self.numClouds): self.loadCloud(i, 50, 0) - for i in xrange(self.numClouds): + for i in range(self.numClouds): self.loadCloud(i, 70, 30) - for i in xrange(self.numClouds): + for i in range(self.numClouds): self.loadCloud(i, 30, 60) self.cloudOrigin.stash() diff --git a/toontown/parties/PartyPlanner.py b/toontown/parties/PartyPlanner.py index bb00ca316..9b2d1008c 100644 --- a/toontown/parties/PartyPlanner.py +++ b/toontown/parties/PartyPlanner.py @@ -585,7 +585,7 @@ def _createInvitationPage(self): return page def __handleHolidays(self): - self.inviteThemes = range(len(PartyGlobals.InviteTheme)) + self.inviteThemes = list(range(len(PartyGlobals.InviteTheme))) if hasattr(base.cr, 'newsManager') and base.cr.newsManager: holidayIds = base.cr.newsManager.getHolidayIdList() if ToontownGlobals.VALENTINES_DAY not in holidayIds: diff --git a/toontown/pets/DistributedPet.py b/toontown/pets/DistributedPet.py index f0de96a46..57ec0b07d 100644 --- a/toontown/pets/DistributedPet.py +++ b/toontown/pets/DistributedPet.py @@ -115,7 +115,7 @@ def setSafeZone(self, safeZone): self.safeZone = safeZone def __generateDistTraitFuncs(self): - for i in xrange(PetTraits.PetTraits.NumTraits): + for i in range(PetTraits.PetTraits.NumTraits): traitName = PetTraits.getTraitNames()[i] setterName = self.getSetterName(traitName) @@ -204,7 +204,7 @@ def announceGenerate(self, public = True): Pet.Pet.setName(self, self.petName) self.traits = PetTraits.PetTraits(self.traitSeed, self.safeZone) self.mood = PetMood.PetMood(self) - for mood, value in self.requiredMoodComponents.items(): + for mood, value in list(self.requiredMoodComponents.items()): self.mood.setComponent(mood, value, announce=0) self.notify.info("We are now generating DNA, Tail is " + str(self.tail)) @@ -473,15 +473,15 @@ def setMovie(self, mode, avId, timestamp): try: self.movieTrack = Sequence(Func(self._petMovieStart, av), Parallel(av.getCallPetIval(), Sequence(Wait(0.54), SoundInterval(self.callSfx))), self._getPetMovieCompleteIval(av)) self.movieTrack.start() - except StandardError, error: - print str(error) + except Exception as error: + print(str(error)) if mode == PetConstants.PET_MOVIE_SCRATCH: try: self.movieTrack = Sequence(Func(self._petMovieStart, av), Func(self.holdPetDownForMovie), Parallel(self.getInteractIval(self.Interactions.SCRATCH), av.getScratchPetIval(), SoundInterval(self.petSfx)), Func(self.releasePetFromHoldDown), self._getPetMovieCompleteIval(av)) self.movieTrack.start() - except StandardError, error: - print str(error) + except Exception as error: + print(str(error)) if mode == PetConstants.PET_MOVIE_FEED: self.bean = loader.loadModel('phase_4/models/props/jellybean4') diff --git a/toontown/pets/DistributedPetAI.py b/toontown/pets/DistributedPetAI.py index fde1ea1cf..8abf3b40f 100644 --- a/toontown/pets/DistributedPetAI.py +++ b/toontown/pets/DistributedPetAI.py @@ -120,7 +120,7 @@ def handleLogicalZoneChange(self, newZoneId, oldZoneId): def announceZoneChange(self, newZoneId, oldZoneId): DistributedPetAI.notify.debug('%s.announceZoneChange: %s->%s' % (self.doId, oldZoneId, newZoneId)) broadcastZones = list2dict([newZoneId, oldZoneId]) - PetObserve.send(broadcastZones.keys(), PetObserve.PetActionObserve(PetObserve.Actions.CHANGE_ZONE, self.doId, (oldZoneId, newZoneId))) + PetObserve.send(list(broadcastZones.keys()), PetObserve.PetActionObserve(PetObserve.Actions.CHANGE_ZONE, self.doId, (oldZoneId, newZoneId))) def getOwnerId(self): return self.ownerId @@ -193,7 +193,7 @@ def setTraits(self, traitList): self.traitList = traitList def __generateDistTraitFuncs(self): - for i in xrange(PetTraits.PetTraits.NumTraits): + for i in range(PetTraits.PetTraits.NumTraits): traitName = PetTraits.getTraitNames()[i] getterName = self.getSetterName(traitName, 'get') b_setterName = self.getSetterName(traitName, 'b_set') @@ -468,7 +468,7 @@ def announceGenerate(self, public = False): self.traits = PetTraits.PetTraits(self.traitSeed, self.safeZone) self.public = public if not hasattr(self, '_beingCreatedInDB'): - for i in xrange(len(self.traitList)): + for i in range(len(self.traitList)): value = self.traitList[i] if value == 0.0: traitName = PetTraits.getTraitNames()[i] @@ -490,7 +490,7 @@ def announceGenerate(self, public = False): self.setH(-90) # (randFloat(360)) if self.initialDNA: self.setDNA(self.initialDNA) - for mood, value in self.requiredMoodComponents.items(): + for mood, value in list(self.requiredMoodComponents.items()): self.mood.setComponent(mood, value, announce=0) self.requiredMoodComponents = {} @@ -711,11 +711,11 @@ def lerpMood(self, component, factor): self.setMoodComponent(component, lerp(curVal, 1.0, factor)) def addToMoods(self, mood2delta): - for mood, delta in mood2delta.items(): + for mood, delta in list(mood2delta.items()): self.addToMood(mood, delta) def lerpMoods(self, mood2factor): - for mood, factor in mood2factor.items(): + for mood, factor in list(mood2factor.items()): self.lerpMood(mood, factor) def handleMoodChange(self, components = [], distribute = 1): @@ -864,25 +864,25 @@ def _getNearbyToon(self): nearbyToonDict = self._getFullNearbyToonDict() if not len(nearbyToonDict): return None - return nearbyToonDict[random.choice(nearbyToonDict.keys())] + return nearbyToonDict[random.choice(list(nearbyToonDict.keys()))] def _getNearbyToonNonOwner(self): nearbyToonDict = self._getNearbyToonDict() if not len(nearbyToonDict): return None - return nearbyToonDict[random.choice(nearbyToonDict.keys())] + return nearbyToonDict[random.choice(list(nearbyToonDict.keys()))] def _getNearbyPet(self): nearbyPetDict = self._getNearbyPetDict() if not len(nearbyPetDict): return None - return nearbyPetDict[random.choice(nearbyPetDict.keys())] + return nearbyPetDict[random.choice(list(nearbyPetDict.keys()))] def _getNearbyAvatar(self): nearbyAvDict = self._getNearbyAvatarDict() if not len(nearbyAvDict): return None - return nearbyAvDict[random.choice(nearbyAvDict.keys())] + return nearbyAvDict[random.choice(list(nearbyAvDict.keys()))] def isBusy(self): return self.busy > 0 @@ -980,7 +980,7 @@ def getAverageDist(self): return sum / 3.0 def lockPetMoveTask(self, avId): - if not hasattr(self, 'air') or not self.air.doId2do.has_key(avId): + if not hasattr(self, 'air') or avId not in self.air.doId2do: self.notify.warning('avId: %s gone or self deleted!' % avId) return Task.done @@ -990,7 +990,7 @@ def lockPetMoveTask(self, avId): if len(self.distList) > 3: self.distList.pop(0) - if self.movieDistSwitch.has_key(self.movieMode): + if self.movieMode in self.movieDistSwitch: dist_Callable = self.movieDistSwitch.get(self.movieMode) movieDist = dist_Callable(av.getStyle().getLegSize()) else: diff --git a/toontown/pets/DistributedPetProxy.py b/toontown/pets/DistributedPetProxy.py index 8fefb9a81..a8d8d6cf1 100644 --- a/toontown/pets/DistributedPetProxy.py +++ b/toontown/pets/DistributedPetProxy.py @@ -43,7 +43,7 @@ def setSafeZone(self, safeZone): self.safeZone = safeZone def __generateDistTraitFuncs(self): - for i in xrange(PetTraits.PetTraits.NumTraits): + for i in range(PetTraits.PetTraits.NumTraits): traitName = PetTraits.getTraitNames()[i] setterName = self.getSetterName(traitName) @@ -133,10 +133,10 @@ def setMood(self, *componentValues): def announceGenerate(self): DistributedObject.DistributedObject.announceGenerate(self) self.traits = PetTraits.PetTraits(self.traitSeed, self.safeZone) - print self.traits.traits + print(self.traits.traits) self.mood = PetMood.PetMood(self) self.lastKnownMood = self.mood.makeCopy() - for mood, value in self.requiredMoodComponents.items(): + for mood, value in list(self.requiredMoodComponents.items()): self.mood.setComponent(mood, value, announce=0) self.requiredMoodComponents = {} diff --git a/toontown/pets/DistributedPetProxyAI.py b/toontown/pets/DistributedPetProxyAI.py index d3a2bec8a..25b445b74 100644 --- a/toontown/pets/DistributedPetProxyAI.py +++ b/toontown/pets/DistributedPetProxyAI.py @@ -108,7 +108,7 @@ def setTraits(self, traitList): self.traitList = traitList def __generateDistTraitFuncs(self): - for i in xrange(PetTraits.PetTraits.NumTraits): + for i in range(PetTraits.PetTraits.NumTraits): traitName = PetTraits.getTraitNames()[i] getterName = self.getSetterName(traitName, 'get') b_setterName = self.getSetterName(traitName, 'b_set') @@ -358,8 +358,8 @@ def setTrickAptitude(self, trickId, aptitude, send = 1): def generate(self): DistributedObjectAI.DistributedObjectAI.generate(self) self.traits = PetTraits.PetTraits(self.traitSeed, self.safeZone) - print self.traits.traits - for i in xrange(len(self.traitList)): + print(self.traits.traits) + for i in range(len(self.traitList)): value = self.traitList[i] if value == 0.0: traitName = PetTraits.getTraitNames()[i] @@ -372,7 +372,7 @@ def generate(self): self.__dict__[setterName](traitValue) self.mood = PetMood.PetMood(self) - for mood, value in self.requiredMoodComponents.items(): + for mood, value in list(self.requiredMoodComponents.items()): self.mood.setComponent(mood, value, announce=0) self.requiredMoodComponents = {} @@ -409,11 +409,11 @@ def lerpMood(self, component, factor): self.setMoodComponent(component, lerp(curVal, 1.0, factor)) def addToMoods(self, mood2delta): - for mood, delta in mood2delta.items(): + for mood, delta in list(mood2delta.items()): self.addToMood(mood, delta) def lerpMoods(self, mood2factor): - for mood, factor in mood2factor.items(): + for mood, factor in list(mood2factor.items()): self.lerpMood(mood, factor) def isContented(self): diff --git a/toontown/pets/Pet.py b/toontown/pets/Pet.py index 4706252b1..55d9262cc 100644 --- a/toontown/pets/Pet.py +++ b/toontown/pets/Pet.py @@ -8,7 +8,7 @@ from direct.actor import Actor from direct.task import Task from toontown.pets import PetDNA -from PetDNA import HeadParts, EarParts, NoseParts, TailParts, BodyTypes, BodyTextures, AllPetColors, getColors, ColorScales, PetEyeColors, EarTextures, TailTextures, getFootTexture, getEarTexture, GiraffeTail, LeopardTail, PetGenders +from .PetDNA import HeadParts, EarParts, NoseParts, TailParts, BodyTypes, BodyTextures, AllPetColors, getColors, ColorScales, PetEyeColors, EarTextures, TailTextures, getFootTexture, getEarTexture, GiraffeTail, LeopardTail, PetGenders from toontown.toonbase import TTLocalizer from toontown.toonbase import ToontownGlobals from toontown.toonbase import ToonPythonUtil as PythonUtil @@ -288,7 +288,7 @@ def generateMoods(self): self.moodIcons.setZ(3.5) moods = moodIcons.findAllMatches('**/+GeomNode') - for moodNum in xrange(0, moods.getNumPaths()): + for moodNum in range(0, moods.getNumPaths()): mood = moods.getPath(moodNum) mood.reparentTo(self.moodIcons) mood.setBillboardPointEye() @@ -421,7 +421,7 @@ def exitDance(self): def enterNeutral(self): anim = 'neutral' - self.pose(anim, random.choice(range(0, self.getNumFrames(anim)))) + self.pose(anim, random.choice(list(range(0, self.getNumFrames(anim))))) self.loop(anim, restart=0) def exitNeutral(self): @@ -429,7 +429,7 @@ def exitNeutral(self): def enterNeutralHappy(self): anim = 'neutralHappy' - self.pose(anim, random.choice(range(0, self.getNumFrames(anim)))) + self.pose(anim, random.choice(list(range(0, self.getNumFrames(anim))))) self.loop(anim, restart=0) def exitNeutralHappy(self): @@ -437,7 +437,7 @@ def exitNeutralHappy(self): def enterNeutralSad(self): anim = 'neutralSad' - self.pose(anim, random.choice(range(0, self.getNumFrames(anim)))) + self.pose(anim, random.choice(list(range(0, self.getNumFrames(anim))))) self.loop(anim, restart=0) def exitNeutralSad(self): @@ -636,7 +636,7 @@ def unlockPet(self): def getInteractIval(self, interactId): anims = self.InteractAnims[interactId] - if type(anims) == types.StringType: + if type(anims) == bytes: animIval = ActorInterval(self, anims) else: animIval = Sequence() @@ -651,19 +651,19 @@ def gridPets(): offsetX = 0 offsetY = 0 startPos = base.localAvatar.getPos() - for body in xrange(0, len(BodyTypes)): + for body in range(0, len(BodyTypes)): colors = getColors(body) for color in colors: p = Pet() - p.setDNA([random.choice(range(-1, len(HeadParts))), - random.choice(range(-1, len(EarParts))), - random.choice(range(-1, len(NoseParts))), - random.choice(range(-1, len(TailParts))), + p.setDNA([random.choice(list(range(-1, len(HeadParts)))), + random.choice(list(range(-1, len(EarParts)))), + random.choice(list(range(-1, len(NoseParts)))), + random.choice(list(range(-1, len(TailParts)))), body, color, - random.choice(range(-1, len(ColorScales))), - random.choice(range(0, len(PetEyeColors))), - random.choice(range(0, len(PetGenders)))]) + random.choice(list(range(-1, len(ColorScales)))), + random.choice(list(range(0, len(PetEyeColors)))), + random.choice(list(range(0, len(PetGenders))))]) p.setPos(startPos[0] + offsetX, startPos[1] + offsetY, startPos[2]) p.animFSM.request('neutral') p.reparentTo(render) diff --git a/toontown/pets/PetActionFSM.py b/toontown/pets/PetActionFSM.py index 74c093739..b7241d4ea 100644 --- a/toontown/pets/PetActionFSM.py +++ b/toontown/pets/PetActionFSM.py @@ -55,7 +55,7 @@ def finish(avatar = avatar, trickId = trickId, self = self): aptitude = self.pet.getTrickAptitude(trickId) healAmt = int(lerp(healRange[0], healRange[1], aptitude)) if healAmt: - for avId, av in self.pet._getFullNearbyToonDict().items(): + for avId, av in list(self.pet._getFullNearbyToonDict().items()): if isinstance(av, DistributedToonAI.DistributedToonAI): try: av.toonUp(healAmt) diff --git a/toontown/pets/PetBrain.py b/toontown/pets/PetBrain.py index 96e101441..87245a048 100644 --- a/toontown/pets/PetBrain.py +++ b/toontown/pets/PetBrain.py @@ -46,8 +46,8 @@ def destroy(self): del self.focus del self.pet if self.doId2goals: - self.notify.warning('destroy(): self.doId2goals is not empty: %s' % self.doId2goals.keys()) - for goalList in self.doId2goals.values(): + self.notify.warning('destroy(): self.doId2goals is not empty: %s' % list(self.doId2goals.keys())) + for goalList in list(self.doId2goals.values()): for goal in goalList: goal.destroy() @@ -134,7 +134,7 @@ def _think(self, task = None): self.pscAware.start() if len(self.nearbyAvs) > PetConstants.MaxAvatarAwareness: self.nextAwarenessIndex %= len(self.nearbyAvs) - self._considerBecomeAwareOf(self.nearbyAvs.keys()[self.nextAwarenessIndex]) + self._considerBecomeAwareOf(list(self.nearbyAvs.keys())[self.nextAwarenessIndex]) self.nextAwarenessIndex += 1 if __dev__: self.pscAware.stop() diff --git a/toontown/pets/PetCollider.py b/toontown/pets/PetCollider.py index 510554965..10979e0ab 100644 --- a/toontown/pets/PetCollider.py +++ b/toontown/pets/PetCollider.py @@ -61,7 +61,7 @@ def _getCollisionEvent(self): return 'petFeeler-%s' % self._getSerialNum() def handleCollision(self, collEntry): - print 'collision!' + print('collision!') cPoint = collEntry.getSurfacePoint(self.cLineNodePath) cNormal = collEntry.getSurfaceNormal(self.cLineNodePath) messenger.send(self.mover.getCollisionEventName(), [cPoint, cNormal]) diff --git a/toontown/pets/PetDNA.py b/toontown/pets/PetDNA.py index 0246b3d6c..8f11b3aed 100644 --- a/toontown/pets/PetDNA.py +++ b/toontown/pets/PetDNA.py @@ -186,15 +186,15 @@ def getRandomPetDNA(zoneId = ToontownGlobals.DonaldsDreamland): from random import choice - head = choice(range(-1, len(HeadParts))) - ears = choice(range(-1, len(EarParts))) - nose = choice(range(-1, len(NoseParts))) - tail = choice(range(-1, len(TailParts))) + head = choice(list(range(-1, len(HeadParts)))) + ears = choice(list(range(-1, len(EarParts)))) + nose = choice(list(range(-1, len(NoseParts)))) + tail = choice(list(range(-1, len(TailParts)))) body = getSpecies(zoneId) - color = choice(range(0, len(getColors(body)))) - colorScale = choice(range(0, len(ColorScales))) - eyes = choice(range(0, len(PetEyeColors))) - gender = choice(range(0, len(PetGenders))) + color = choice(list(range(0, len(getColors(body))))) + colorScale = choice(list(range(0, len(ColorScales)))) + eyes = choice(list(range(0, len(PetEyeColors)))) + gender = choice(list(range(0, len(PetGenders)))) return [head, ears, nose, @@ -245,7 +245,7 @@ def getBodyRarity(bodyIndex): for zoneId in PetRarities['body']: for body in PetRarities['body'][zoneId]: totalWeight += PetRarities['body'][zoneId][body] - if weight.has_key(body): + if body in weight: weight[body] += PetRarities['body'][zoneId][body] else: weight[body] = PetRarities['body'][zoneId][body] diff --git a/toontown/pets/PetDetailPanel.py b/toontown/pets/PetDetailPanel.py index ed2da995c..1ed517ee9 100644 --- a/toontown/pets/PetDetailPanel.py +++ b/toontown/pets/PetDetailPanel.py @@ -48,7 +48,7 @@ def cleanup(self): def update(self, pet): if not pet: return - for trickId in PetTricks.TrickId2scIds.keys(): + for trickId in list(PetTricks.TrickId2scIds.keys()): trickText = TTLocalizer.PetTrickStrings[trickId] if trickId < len(pet.trickAptitudes): aptitude = pet.trickAptitudes[trickId] diff --git a/toontown/pets/PetGoalMgr.py b/toontown/pets/PetGoalMgr.py index 8ccf10ac6..353af43bf 100644 --- a/toontown/pets/PetGoalMgr.py +++ b/toontown/pets/PetGoalMgr.py @@ -25,7 +25,7 @@ def destroy(self): del self.pscSetup del self.pscFindPrimary del self.pscSetPrimary - goals = self.goals.keys() + goals = list(self.goals.keys()) for goal in goals: self.removeGoal(goal) goal.destroy() diff --git a/toontown/pets/PetLookerAI.py b/toontown/pets/PetLookerAI.py index 08cb5bd2f..1d7506b9b 100644 --- a/toontown/pets/PetLookerAI.py +++ b/toontown/pets/PetLookerAI.py @@ -33,7 +33,7 @@ def destroy(self): if self.__active: self.exitPetLook() if len(self.others): - PetLookerAI.notify.warning('%s: self.others not empty: %s' % (self.doId, self.others.keys())) + PetLookerAI.notify.warning('%s: self.others not empty: %s' % (self.doId, list(self.others.keys()))) self.others = {} def _getPetLookerBodyNode(self): @@ -48,7 +48,7 @@ def enterPetLook(self): PetLookerAI.notify.warning('enterPetLook: %s already active!' % self.doId) return if len(self.others): - PetLookerAI.notify.warning('%s: len(self.others) != 0: %s' % (self.doId, self.others.keys())) + PetLookerAI.notify.warning('%s: len(self.others) != 0: %s' % (self.doId, list(self.others.keys()))) self.others = {} self.__active = 1 self.__collNode = self._getPetLookerBodyNode().attachNewNode('PetLookerCollNode') @@ -60,13 +60,13 @@ def exitPetLook(self): PetLookerAI.notify.warning('exitPetLook: %s not active!' % self.doId) return if len(self.others): - otherIds = self.others.keys() + otherIds = list(self.others.keys()) PetLookerAI.notify.warning('%s: still in otherIds: %s' % (self.doId, otherIds)) for otherId in otherIds: self._handleLookingAtOtherStop(otherId) if len(self.others): - PetLookerAI.notify.warning('%s: self.others still not empty: %s' % (self.doId, self.others.keys())) + PetLookerAI.notify.warning('%s: self.others still not empty: %s' % (self.doId, list(self.others.keys()))) self.others = {} self._destroyPetLookSphere() self.__collNode.removeNode() diff --git a/toontown/pets/PetManagerAI.py b/toontown/pets/PetManagerAI.py index 4af0fa8bc..c11db7615 100644 --- a/toontown/pets/PetManagerAI.py +++ b/toontown/pets/PetManagerAI.py @@ -80,7 +80,7 @@ def __init__(self, air): self.air = air def getAvailablePets(self, numPets=5): - return random.sample(xrange(256), numPets) + return random.sample(range(256), numPets) def createNewPetFromSeed(self, avId, petSeeds, nameIndex, gender, safeZoneId): creator = PetCreator(self.air, avId, petSeeds, nameIndex, gender, safeZoneId) diff --git a/toontown/pets/PetNameGenerator.py b/toontown/pets/PetNameGenerator.py index 836442343..8aa6dcb88 100644 --- a/toontown/pets/PetNameGenerator.py +++ b/toontown/pets/PetNameGenerator.py @@ -7,7 +7,7 @@ from panda3d.core import * from panda3d.direct import * from toontown.pets import PetNamesEnglish -from StringIO import StringIO +from io import StringIO class PetNameGenerator: notify = DirectNotifyGlobal.directNotify.newCategory('PetNameGenerator') @@ -33,7 +33,7 @@ def generateLists(self): currentLine = input.readline() masterList = [self.boyFirsts, self.girlFirsts, self.neutralFirsts] - for tu in self.nameDictionary.values(): + for tu in list(self.nameDictionary.values()): masterList[tu[0]].append(tu[1]) return 1 @@ -49,7 +49,7 @@ def returnUniqueID(self, name): newtu[0] = (0, name) newtu[1] = (1, name) newtu[2] = (2, name) - for tu in self.nameDictionary.items(): + for tu in list(self.nameDictionary.items()): for g in newtu: if tu[1] == g: return tu[0] diff --git a/toontown/pets/PetObserve.py b/toontown/pets/PetObserve.py index ee8c9eb05..a17a42055 100644 --- a/toontown/pets/PetObserve.py +++ b/toontown/pets/PetObserve.py @@ -10,7 +10,7 @@ def getEventName(zoneId): def send(zoneIds, petObserve): if petObserve.isValid(): - if type(zoneIds) not in (types.ListType, types.TupleType): + if type(zoneIds) not in (list, tuple): zoneIds = [zoneIds] for zoneId in zoneIds: messenger.send(getEventName(zoneId), [petObserve]) diff --git a/toontown/pets/PetTraits.py b/toontown/pets/PetTraits.py index b94be8678..1bb84002f 100644 --- a/toontown/pets/PetTraits.py +++ b/toontown/pets/PetTraits.py @@ -185,7 +185,7 @@ def __init__(self, traitSeed, safeZoneId, traitValueList = []): self.safeZoneId = safeZoneId self.rng = random.Random(self.traitSeed) self.traits = {} - for i in xrange(len(PetTraits.TraitDescs)): + for i in range(len(PetTraits.TraitDescs)): if i < len(traitValueList) and traitValueList[i] > 0.0: trait = PetTraits.Trait(i, self, traitValueList[i]) else: @@ -194,7 +194,7 @@ def __init__(self, traitSeed, safeZoneId, traitValueList = []): self.__dict__[trait.name] = trait.value extremeTraits = [] - for trait in self.traits.values(): + for trait in list(self.traits.values()): if not trait.hasWorth: continue if trait.quality == TraitDistribution.TraitQuality.AVERAGE: @@ -226,7 +226,7 @@ def getExtremeTraits(self): def getOverallValue(self): total = 0 numUsed = 0 - for trait in self.traits.values(): + for trait in list(self.traits.values()): if trait.hasWorth: if trait.higherIsBetter: value = trait.value @@ -235,7 +235,7 @@ def getOverallValue(self): total += value numUsed += 1 - value = total / len(self.traits.values()) + value = total / len(list(self.traits.values())) return value def getExtremeTraitDescriptions(self): diff --git a/toontown/pets/PetTricks.py b/toontown/pets/PetTricks.py index d522af098..5f7aa02e8 100644 --- a/toontown/pets/PetTricks.py +++ b/toontown/pets/PetTricks.py @@ -62,7 +62,7 @@ def getSoundIval(trickId): sounds = TrickSounds.get(trickId, None) if sounds: - if type(sounds) == types.StringType: + if type(sounds) == bytes: sound = loader.loadSfx(sounds) return SoundInterval(sound) else: @@ -79,7 +79,7 @@ def getTrickIval(pet, trickId): anims = TrickAnims[trickId] animRate = random.uniform(0.9, 1.1) waitTime = random.uniform(0.0, 1.0) - if type(anims) == types.StringType: + if type(anims) == bytes: if trickId == Tricks.JUMP: animIval = Parallel() animIval.append(ActorInterval(pet, anims, playRate=animRate)) diff --git a/toontown/pgui/DirectButton.py b/toontown/pgui/DirectButton.py index 110b4e5a3..a745e49b2 100644 --- a/toontown/pgui/DirectButton.py +++ b/toontown/pgui/DirectButton.py @@ -3,8 +3,8 @@ __all__ = ['DirectButton'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG -from DirectFrame import * +from . import DirectGuiGlobals as DGG +from .DirectFrame import * class DirectButton(DirectFrame): """ @@ -100,7 +100,7 @@ def setCommandButtons(self): def commandFunc(self, event): if self['command']: # Pass any extra args to command - apply(self['command'], self['extraArgs']) + self['command'](*self['extraArgs']) def setClickSound(self): clickSound = self['clickSound'] diff --git a/toontown/pgui/DirectCheckBox.py b/toontown/pgui/DirectCheckBox.py index a67fd1076..9ab0e22a7 100644 --- a/toontown/pgui/DirectCheckBox.py +++ b/toontown/pgui/DirectCheckBox.py @@ -55,5 +55,5 @@ def commandFunc(self, event): if self['command']: # Pass any extra args to command - apply(self['command'], [self['isChecked']] + self['extraArgs']) + self['command'](*[self['isChecked']] + self['extraArgs']) diff --git a/toontown/pgui/DirectCheckButton.py b/toontown/pgui/DirectCheckButton.py index 77244b185..df6853cae 100644 --- a/toontown/pgui/DirectCheckButton.py +++ b/toontown/pgui/DirectCheckButton.py @@ -3,9 +3,9 @@ __all__ = ['DirectCheckButton'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG -from DirectButton import * -from DirectLabel import * +from . import DirectGuiGlobals as DGG +from .DirectButton import * +from .DirectLabel import * class DirectCheckButton(DirectButton): """ @@ -170,7 +170,7 @@ def commandFunc(self, event): if self['command']: # Pass any extra args to command - apply(self['command'], [self['indicatorValue']] + self['extraArgs']) + self['command'](*[self['indicatorValue']] + self['extraArgs']) def setIndicatorValue(self): self.component('indicator').guiItem.setState(self['indicatorValue']) diff --git a/toontown/pgui/DirectDialog.py b/toontown/pgui/DirectDialog.py index 803cce546..4e3dd0d72 100644 --- a/toontown/pgui/DirectDialog.py +++ b/toontown/pgui/DirectDialog.py @@ -3,9 +3,9 @@ __all__ = ['findDialog', 'cleanupDialog', 'DirectDialog', 'OkDialog', 'OkCancelDialog', 'YesNoDialog', 'YesNoCancelDialog', 'RetryCancelDialog'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG -from DirectFrame import * -from DirectButton import * +from . import DirectGuiGlobals as DGG +from .DirectFrame import * +from .DirectButton import * import types def findDialog(uniqueName): @@ -182,11 +182,11 @@ def __init__(self, parent = None, **kw): def configureDialog(self): # Set up hot key bindings - bindList = zip(self.buttonList, self['buttonHotKeyList'], - self['buttonValueList']) + bindList = list(zip(self.buttonList, self['buttonHotKeyList'], + self['buttonValueList'])) for button, hotKey, value in bindList: - if ((type(hotKey) == types.ListType) or - (type(hotKey) == types.TupleType)): + if ((type(hotKey) == list) or + (type(hotKey) == tuple)): for key in hotKey: button.bind('press-' + key + '-', self.buttonCommand, extraArgs = [value]) @@ -261,12 +261,12 @@ def configureDialog(self): scale = self['button_scale'] # Can either be a Vec3 or a tuple of 3 values if (isinstance(scale, Vec3) or - (type(scale) == types.ListType) or - (type(scale) == types.TupleType)): + (type(scale) == list) or + (type(scale) == tuple)): sx = scale[0] sz = scale[2] - elif ((type(scale) == types.IntType) or - (type(scale) == types.FloatType)): + elif ((type(scale) == int) or + (type(scale) == float)): sx = sz = scale else: sx = sz = 1 diff --git a/toontown/pgui/DirectEntry.py b/toontown/pgui/DirectEntry.py index e2b306af0..d5dde69ae 100644 --- a/toontown/pgui/DirectEntry.py +++ b/toontown/pgui/DirectEntry.py @@ -3,9 +3,9 @@ __all__ = ['DirectEntry'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG -from DirectFrame import * -from OnscreenText import OnscreenText +from . import DirectGuiGlobals as DGG +from .DirectFrame import * +from .OnscreenText import OnscreenText import string,types # import this to make sure it gets pulled into the publish import encodings.utf_8 @@ -175,12 +175,12 @@ def setClickSound(self): def commandFunc(self, event): if self['command']: # Pass any extra args to command - apply(self['command'], [self.get()] + self['extraArgs']) + self['command'](*[self.get()] + self['extraArgs']) def failedCommandFunc(self, event): if self['failedCommand']: # Pass any extra args - apply(self['failedCommand'], [self.get()] + self['failedExtraArgs']) + self['failedCommand'](*[self.get()] + self['failedExtraArgs']) def autoCapitalizeFunc(self): if self['autoCapitalize']: @@ -192,7 +192,7 @@ def autoCapitalizeFunc(self): def focusInCommandFunc(self): if self['focusInCommand']: - apply(self['focusInCommand'], self['focusInExtraArgs']) + self['focusInCommand'](*self['focusInExtraArgs']) if self['autoCapitalize']: self.accept(self.guiItem.getTypeEvent(), self._handleTyping) self.accept(self.guiItem.getEraseEvent(), self._handleErasing) @@ -210,7 +210,7 @@ def _autoCapitalize(self): wordSoFar = '' # track whether the previous character was part of a word or not wasNonWordChar = True - for i in xrange(len(name)): + for i in range(len(name)): character = name[i] # test to see if we are between words # - Count characters that can't be capitalized as a break between words @@ -247,7 +247,7 @@ def _autoCapitalize(self): def focusOutCommandFunc(self): if self['focusOutCommand']: - apply(self['focusOutCommand'], self['focusOutExtraArgs']) + self['focusOutCommand'](*self['focusOutExtraArgs']) if self['autoCapitalize']: self.ignore(self.guiItem.getTypeEvent()) self.ignore(self.guiItem.getEraseEvent()) @@ -257,7 +257,7 @@ def set(self, text): does not change the current cursor position. Also see enterText(). """ - self.unicodeText = isinstance(text, types.UnicodeType) + self.unicodeText = isinstance(text, str) if self.unicodeText: self.guiItem.setWtext(text) else: diff --git a/toontown/pgui/DirectEntryScroll.py b/toontown/pgui/DirectEntryScroll.py index bf829bed6..7e258aca9 100644 --- a/toontown/pgui/DirectEntryScroll.py +++ b/toontown/pgui/DirectEntryScroll.py @@ -1,10 +1,10 @@ __all__ = ['DirectEntryScroll'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG -from DirectScrolledFrame import * -from DirectFrame import * -from DirectEntry import * +from . import DirectGuiGlobals as DGG +from .DirectScrolledFrame import * +from .DirectFrame import * +from .DirectEntry import * class DirectEntryScroll(DirectFrame): def __init__(self, entry, parent = None, **kw): diff --git a/toontown/pgui/DirectFrame.py b/toontown/pgui/DirectFrame.py index 4603f9356..876f28bdd 100644 --- a/toontown/pgui/DirectFrame.py +++ b/toontown/pgui/DirectFrame.py @@ -3,10 +3,10 @@ __all__ = ['DirectFrame'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG -from DirectGuiBase import * -from OnscreenImage import OnscreenImage -from OnscreenGeom import OnscreenGeom +from . import DirectGuiGlobals as DGG +from .DirectGuiBase import * +from .OnscreenImage import OnscreenImage +from .OnscreenGeom import OnscreenGeom import string, types class DirectFrame(DirectGuiWidget): @@ -54,7 +54,7 @@ def setText(self): # Determine if user passed in single string or a sequence if self['text'] == None: textList = (None,) * self['numStates'] - elif isinstance(self['text'], types.StringTypes): + elif isinstance(self['text'], (str,)): # If just passing in a single string, make a tuple out of it textList = (self['text'],) * self['numStates'] else: @@ -80,7 +80,7 @@ def setText(self): if text == None: return else: - from OnscreenText import OnscreenText + from .OnscreenText import OnscreenText self.createcomponent( component, (), 'text', OnscreenText, @@ -97,7 +97,7 @@ def setGeom(self): # Passed in None geomList = (None,) * self['numStates'] elif isinstance(geom, NodePath) or \ - isinstance(geom, types.StringTypes): + isinstance(geom, (str,)): # Passed in a single node path, make a tuple out of it geomList = (geom,) * self['numStates'] else: @@ -139,14 +139,14 @@ def setImage(self): imageList = (None,) * self['numStates'] elif isinstance(arg, NodePath) or \ isinstance(arg, Texture) or \ - isinstance(arg, types.StringTypes): + isinstance(arg, (str,)): # Passed in a single node path, make a tuple out of it imageList = (arg,) * self['numStates'] else: # Otherwise, hope that the user has passed in a tuple/list if ((len(arg) == 2) and - isinstance(arg[0], types.StringTypes) and - isinstance(arg[1], types.StringTypes)): + isinstance(arg[0], (str,)) and + isinstance(arg[1], (str,))): # Its a model/node pair of strings imageList = (arg,) * self['numStates'] else: diff --git a/toontown/pgui/DirectGui.py b/toontown/pgui/DirectGui.py index 1d3c0636d..75a7d82f1 100644 --- a/toontown/pgui/DirectGui.py +++ b/toontown/pgui/DirectGui.py @@ -1,9 +1,9 @@ """Undocumented Module""" -import DirectGuiGlobals as DGG -from OnscreenText import * -from OnscreenGeom import * -from OnscreenImage import * +from . import DirectGuiGlobals as DGG +from .OnscreenText import * +from .OnscreenGeom import * +from .OnscreenImage import * # MPG DirectStart should call this? # Set up default font @@ -12,17 +12,17 @@ # PGItem.getTextNode().setFont(defaultFont) # Direct Gui Classes -from DirectFrame import * -from DirectButton import * -from DirectEntry import * -from DirectEntryScroll import * -from DirectLabel import * -from DirectScrolledList import * -from DirectDialog import * -from DirectWaitBar import * -from DirectSlider import * -from DirectScrollBar import * -from DirectScrolledFrame import * -from DirectCheckButton import * -from DirectOptionMenu import * -from DirectRadioButton import * +from .DirectFrame import * +from .DirectButton import * +from .DirectEntry import * +from .DirectEntryScroll import * +from .DirectLabel import * +from .DirectScrolledList import * +from .DirectDialog import * +from .DirectWaitBar import * +from .DirectSlider import * +from .DirectScrollBar import * +from .DirectScrolledFrame import * +from .DirectCheckButton import * +from .DirectOptionMenu import * +from .DirectRadioButton import * diff --git a/toontown/pgui/DirectGuiBase.py b/toontown/pgui/DirectGuiBase.py index 5e1e969ef..4d580855e 100644 --- a/toontown/pgui/DirectGuiBase.py +++ b/toontown/pgui/DirectGuiBase.py @@ -4,10 +4,10 @@ from pandac.PandaModules import * -import DirectGuiGlobals as DGG -from OnscreenText import * -from OnscreenGeom import * -from OnscreenImage import * +from . import DirectGuiGlobals as DGG +from .OnscreenText import * +from .OnscreenGeom import * +from .OnscreenImage import * from direct.directtools.DirectUtil import ROUND_TO from direct.showbase import DirectObject from direct.task import Task @@ -173,7 +173,7 @@ def defineoptions(self, keywords, optionDefs, dynamicGroups = ()): # override those in the base class. if not hasattr(self, '_constructorKeywords'): tmp = {} - for option, value in keywords.items(): + for option, value in list(keywords.items()): tmp[option] = [value, 0] self._constructorKeywords = tmp self._optionInfo = {} @@ -236,7 +236,7 @@ def initialiseoptions(self, myClass): # Call the configuration callback function for every option. FUNCTION = DGG._OPT_FUNCTION self.fInit = 1 - for info in self._optionInfo.values(): + for info in list(self._optionInfo.values()): func = info[FUNCTION] if func is not None and func is not DGG.INITOPT: func() @@ -245,7 +245,7 @@ def initialiseoptions(self, myClass): # Now check if anything is left over unusedOptions = [] keywords = self._constructorKeywords - for name in keywords.keys(): + for name in list(keywords.keys()): used = keywords[name][1] if not used: # This keyword argument has not been used. If it @@ -260,8 +260,8 @@ def initialiseoptions(self, myClass): text = 'Unknown option "' else: text = 'Unknown options "' - raise KeyError, text + ', '.join(unusedOptions) + \ - '" for ' + myClass.__name__ + raise KeyError(text + ', '.join(unusedOptions) + \ + '" for ' + myClass.__name__) # Can now call post init func self.postInitialiseFunc() @@ -282,7 +282,7 @@ def options(self): """ options = [] if hasattr(self, '_optionInfo'): - for option, info in self._optionInfo.items(): + for option, info in list(self._optionInfo.items()): isinit = info[DGG._OPT_FUNCTION] is DGG.INITOPT default = info[DGG._OPT_DEFAULT] options.append((option, default, isinit)) @@ -315,7 +315,7 @@ def configure(self, option=None, **kw): # (optionName, default, value) if option is None: rtn = {} - for option, config in self._optionInfo.items(): + for option, config in list(self._optionInfo.items()): rtn[option] = (option, config[DGG._OPT_DEFAULT], config[DGG._OPT_VALUE]) @@ -347,13 +347,13 @@ def configure(self, option=None, **kw): indirectOptions = {} indirectOptions_has_key = indirectOptions.__contains__ - for option, value in kw.items(): + for option, value in list(kw.items()): if optionInfo_has_key(option): # This is one of the options of this gui item. # Check it is an initialisation option. if optionInfo[option][FUNCTION] is DGG.INITOPT: - print 'Cannot configure initialisation option "' \ - + option + '" for ' + self.__class__.__name__ + print('Cannot configure initialisation option "' \ + + option + '" for ' + self.__class__.__name__) break #raise KeyError, \ # 'Cannot configure initialisation option "' \ @@ -393,7 +393,7 @@ def configure(self, option=None, **kw): # components in the group. componentConfigFuncs = [] # For each component - for info in componentInfo.values(): + for info in list(componentInfo.values()): # Check if it is a member of this group if info[4] == component: # Yes, append its config func @@ -401,8 +401,8 @@ def configure(self, option=None, **kw): if len(componentConfigFuncs) == 0 and \ component not in self._dynamicGroups: - raise KeyError, 'Unknown option "' + option + \ - '" for ' + self.__class__.__name__ + raise KeyError('Unknown option "' + option + \ + '" for ' + self.__class__.__name__) # Add the configure method(s) (may be more than # one if this is configuring a component group) @@ -415,12 +415,12 @@ def configure(self, option=None, **kw): indirectOptions[componentConfigFunc][componentOption] \ = value else: - raise KeyError, 'Unknown option "' + option + \ - '" for ' + self.__class__.__name__ + raise KeyError('Unknown option "' + option + \ + '" for ' + self.__class__.__name__) # Call the configure methods for any components. # Pass in the dictionary of keyword/values created above - for func, options in indirectOptions.items(): + for func, options in list(indirectOptions.items()): func(**options) # Call the configuration callback function for each option. @@ -464,14 +464,14 @@ def cget(self, option): else: # If this is a group name, call cget for one of # the components in the group. - for info in self.__componentInfo.values(): + for info in list(self.__componentInfo.values()): if info[4] == component: componentCget = info[3] return componentCget(componentOption) # Option not found - raise KeyError, 'Unknown option "' + option + \ - '" for ' + self.__class__.__name__ + raise KeyError('Unknown option "' + option + \ + '" for ' + self.__class__.__name__) # Allow index style refererences __getitem__ = cget @@ -483,8 +483,7 @@ def createcomponent(self, componentName, componentAliases, componentGroup, """ # Check for invalid component name if '_' in componentName: - raise ValueError, \ - 'Component name "%s" must not contain "_"' % componentName + raise ValueError('Component name "%s" must not contain "_"' % componentName) # Get construction keywords if hasattr(self, '_constructorKeywords'): @@ -509,7 +508,7 @@ def createcomponent(self, componentName, componentAliases, componentGroup, # with corresponding keys beginning with *component*. alias = alias + '_' aliasLen = len(alias) - for option in keywords.keys(): + for option in list(keywords.keys()): if len(option) > aliasLen and option[:aliasLen] == alias: newkey = component + '_' + option[aliasLen:] keywords[newkey] = keywords[option] @@ -522,7 +521,7 @@ def createcomponent(self, componentName, componentAliases, componentGroup, # First, walk through the option list looking for arguments # than refer to this component's group. - for option in keywords.keys(): + for option in list(keywords.keys()): # Check if this keyword argument refers to the group # of this component. If so, add this to the options # to use when constructing the widget. Mark the @@ -541,7 +540,7 @@ def createcomponent(self, componentName, componentAliases, componentGroup, # specific than the group arguments, above; we walk through # the list afterwards so they will override. - for option in keywords.keys(): + for option in list(keywords.keys()): if len(option) > nameLen and option[:nameLen] == componentPrefix: # The keyword argument refers to this component, so add # this to the options to use when constructing the widget. @@ -553,7 +552,7 @@ def createcomponent(self, componentName, componentAliases, componentGroup, if widgetClass is None: return None # Get arguments for widget constructor - if len(widgetArgs) == 1 and type(widgetArgs[0]) == types.TupleType: + if len(widgetArgs) == 1 and type(widgetArgs[0]) == tuple: # Arguments to the constructor can be specified as either # multiple trailing arguments to createcomponent() or as a # single tuple argument. @@ -603,7 +602,7 @@ def component(self, name): def components(self): # Return a list of all components. - names = self.__componentInfo.keys() + names = list(self.__componentInfo.keys()) names.sort() return names @@ -634,8 +633,8 @@ def bind(self, event, command, extraArgs = []): gEvent = event + self.guiId if base.config.GetBool('debug-directgui-msgs', False): from toontown.toonbase.ToonPythonUtil import StackTrace - print gEvent - print StackTrace() + print(gEvent) + print(StackTrace()) self.accept(gEvent, command, extraArgs = extraArgs) def unbind(self, event): @@ -955,7 +954,7 @@ def setRelief(self, fSetStyle = 1): # Convert None, and string arguments if relief == None: relief = PGFrameStyle.TNone - elif isinstance(relief, types.StringTypes): + elif isinstance(relief, (str,)): # Convert string to frame style int relief = DGG.FrameStyleDict[relief] # Set style @@ -980,8 +979,8 @@ def setRelief(self, fSetStyle = 1): def setFrameColor(self): # this might be a single color or a list of colors colors = self['frameColor'] - if type(colors[0]) == types.IntType or \ - type(colors[0]) == types.FloatType: + if type(colors[0]) == int or \ + type(colors[0]) == float: colors = (colors,) for i in range(self['numStates']): if i >= len(colors): @@ -996,14 +995,14 @@ def setFrameTexture(self): textures = self['frameTexture'] if textures == None or \ isinstance(textures, Texture) or \ - isinstance(textures, types.StringTypes): + isinstance(textures, (str,)): textures = (textures,) * self['numStates'] for i in range(self['numStates']): if i >= len(textures): texture = textures[-1] else: texture = textures[i] - if isinstance(texture, types.StringTypes): + if isinstance(texture, (str,)): texture = loader.loadTexture(texture) if texture: self.frameStyle[i].setTexture(texture) @@ -1068,9 +1067,9 @@ def destroy(self): def printConfig(self, indent = 0): space = ' ' * indent - print space + self.guiId, '-', self.__class__.__name__ - print space + 'Pos: ' + self.getPos().pPrintValues() - print space + 'Scale: ' + self.getScale().pPrintValues() + print(space + self.guiId, '-', self.__class__.__name__) + print(space + 'Pos: ' + self.getPos().pPrintValues()) + print(space + 'Scale: ' + self.getScale().pPrintValues()) # Print out children info for child in self.getChildren(): messenger.send(DGG.PRINT + child.getName(), [indent + 2]) @@ -1079,7 +1078,7 @@ def copyOptions(self, other): """ Copy other's options into our self so we look and feel like other """ - for key, value in other._optionInfo.items(): + for key, value in list(other._optionInfo.items()): self[key] = value[1] def taskName(self, idString): diff --git a/toontown/pgui/DirectGuiTest.py b/toontown/pgui/DirectGuiTest.py index 2b076eed0..dabfd4305 100644 --- a/toontown/pgui/DirectGuiTest.py +++ b/toontown/pgui/DirectGuiTest.py @@ -5,7 +5,7 @@ if __name__ == "__main__": from direct.directbase import DirectStart - from DirectGui import * + from .DirectGui import * #from whrandom import * from random import * @@ -15,7 +15,7 @@ # Here we specify the button's command def dummyCmd(index): - print 'Button %d POW!!!!' % index + print('Button %d POW!!!!' % index) # Define some commands to bind to enter, exit and click events def shrink(db): @@ -91,7 +91,7 @@ def ouch(db): # DIRECT ENTRY EXAMPLE def printEntryText(text): - print 'Text:', text + print('Text:', text) # Here we create an entry, and specify everything up front # CALL de1.get() and de1.set('new text') to get and set entry contents @@ -107,7 +107,7 @@ def printEntryText(text): # DIRECT DIALOG EXAMPLE def printDialogValue(value): - print 'Value:', value + print('Value:', value) simpleDialog = YesNoDialog(text = 'Simple', command = printDialogValue) @@ -125,7 +125,7 @@ def printDialogValue(value): customDialog = DirectDialog(text = 'Pick a number', buttonTextList = [str(i) for i in range(10)], - buttonValueList = range(10), + buttonValueList = list(range(10)), command = printDialogValue) @@ -133,9 +133,9 @@ def printDialogValue(value): # NOTE: There are some utility functions which help you get size # of a direct gui widget. These can be used to position and scale an # image after you've created the entry. scale = (width/2, 1, height/2) - print 'BOUNDS:', de1.getBounds() - print 'WIDTH:', de1.getWidth() - print 'HEIGHT:', de1.getHeight() - print 'CENTER:', de1.getCenter() + print('BOUNDS:', de1.getBounds()) + print('WIDTH:', de1.getWidth()) + print('HEIGHT:', de1.getHeight()) + print('CENTER:', de1.getCenter()) run() diff --git a/toontown/pgui/DirectLabel.py b/toontown/pgui/DirectLabel.py index babd6d53c..1ec6b88d1 100644 --- a/toontown/pgui/DirectLabel.py +++ b/toontown/pgui/DirectLabel.py @@ -3,8 +3,8 @@ __all__ = ['DirectLabel'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG -from DirectFrame import * +from . import DirectGuiGlobals as DGG +from .DirectFrame import * class DirectLabel(DirectFrame): """ diff --git a/toontown/pgui/DirectOptionMenu.py b/toontown/pgui/DirectOptionMenu.py index b37436b5c..ed9cfca0b 100644 --- a/toontown/pgui/DirectOptionMenu.py +++ b/toontown/pgui/DirectOptionMenu.py @@ -5,10 +5,10 @@ import types from pandac.PandaModules import * -import DirectGuiGlobals as DGG -from DirectButton import * -from DirectLabel import * -from DirectFrame import * +from . import DirectGuiGlobals as DGG +from .DirectButton import * +from .DirectLabel import * +from .DirectFrame import * class DirectOptionMenu(DirectButton): """ @@ -252,7 +252,7 @@ def selectHighlightedIndex(self, event = None): def index(self, index): intIndex = None - if isinstance(index, types.IntType): + if isinstance(index, int): intIndex = index elif index in self['items']: i = 0 @@ -272,7 +272,7 @@ def set(self, index, fCommand = 1): self['text'] = item if fCommand and self['command']: # Pass any extra args to command - apply(self['command'], [item] + self['extraArgs']) + self['command'](*[item] + self['extraArgs']) def get(self): """ Get currently selected item """ diff --git a/toontown/pgui/DirectRadioButton.py b/toontown/pgui/DirectRadioButton.py index c96ba13db..0a86f8ef3 100644 --- a/toontown/pgui/DirectRadioButton.py +++ b/toontown/pgui/DirectRadioButton.py @@ -3,9 +3,9 @@ __all__ = ['DirectRadioButton'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG -from DirectButton import * -from DirectLabel import * +from . import DirectGuiGlobals as DGG +from .DirectButton import * +from .DirectLabel import * class DirectRadioButton(DirectButton): """ @@ -203,7 +203,7 @@ def check(self): if self['command']: # Pass any extra args to command - apply(self['command'], self['extraArgs']) + self['command'](*self['extraArgs']) def setOthers(self, others): self['others'] = others diff --git a/toontown/pgui/DirectScrollBar.py b/toontown/pgui/DirectScrollBar.py index f69896568..fb2fc17c0 100644 --- a/toontown/pgui/DirectScrollBar.py +++ b/toontown/pgui/DirectScrollBar.py @@ -3,9 +3,9 @@ __all__ = ['DirectScrollBar'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG -from DirectFrame import * -from DirectButton import * +from . import DirectGuiGlobals as DGG +from .DirectFrame import * +from .DirectButton import * """ import DirectScrollBar @@ -142,7 +142,7 @@ def setOrientation(self): elif self['orientation'] == DGG.VERTICAL_INVERTED: self.guiItem.setAxis(Vec3(0, 0, 1)) else: - raise ValueError, 'Invalid value for orientation: %s' % (self['orientation']) + raise ValueError('Invalid value for orientation: %s' % (self['orientation'])) def setManageButtons(self): self.guiItem.setManagePieces(self['manageButtons']) @@ -164,5 +164,5 @@ def commandFunc(self): self._optionInfo['value'][DGG._OPT_VALUE] = self.guiItem.getValue() if self['command']: - apply(self['command'], self['extraArgs']) + self['command'](*self['extraArgs']) diff --git a/toontown/pgui/DirectScrolledFrame.py b/toontown/pgui/DirectScrolledFrame.py index e3efa164c..8e4aa5c58 100644 --- a/toontown/pgui/DirectScrolledFrame.py +++ b/toontown/pgui/DirectScrolledFrame.py @@ -3,9 +3,9 @@ __all__ = ['DirectScrolledFrame'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG -from DirectFrame import * -from DirectScrollBar import * +from . import DirectGuiGlobals as DGG +from .DirectFrame import * +from .DirectScrollBar import * """ import DirectScrolledFrame @@ -87,7 +87,7 @@ def setAutoHideScrollBars(self): def commandFunc(self): if self['command']: - apply(self['command'], self['extraArgs']) + self['command'](*self['extraArgs']) def destroy(self): # Destroy children of the canvas diff --git a/toontown/pgui/DirectScrolledList.py b/toontown/pgui/DirectScrolledList.py index dcf59dcdf..7b2d9752e 100644 --- a/toontown/pgui/DirectScrolledList.py +++ b/toontown/pgui/DirectScrolledList.py @@ -3,11 +3,11 @@ __all__ = ['DirectScrolledListItem', 'DirectScrolledList'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG +from . import DirectGuiGlobals as DGG from direct.directnotify import DirectNotifyGlobal from direct.task.Task import Task -from DirectFrame import * -from DirectButton import * +from .DirectFrame import * +from .DirectButton import * import string, types @@ -39,7 +39,7 @@ def __init__(self, parent=None, **kw): def select(self): assert self.notify.debugStateCall(self) - apply(self.nextCommand, self.nextCommandExtraArgs) + self.nextCommand(*self.nextCommandExtraArgs) self._parent.selectListItem(self) @@ -251,7 +251,7 @@ def scrollTo(self, index, centered=0): if item.__class__.__name__ == 'str': if self['itemMakeFunction']: # If there is a function to create the item - item = apply(self['itemMakeFunction'], (item, i, self['itemMakeExtraArgs'])) + item = self['itemMakeFunction'](*(item, i, self['itemMakeExtraArgs'])) else: item = DirectFrame(text = item, text_align = self['itemsAlign'], @@ -269,7 +269,7 @@ def scrollTo(self, index, centered=0): if self['command']: # Pass any extra args to command - apply(self['command'], self['extraArgs']) + self['command'](*self['extraArgs']) return ret def makeAllItems(self): @@ -283,8 +283,7 @@ def makeAllItems(self): if item.__class__.__name__ == 'str': if self['itemMakeFunction']: # If there is a function to create the item - item = apply(self['itemMakeFunction'], - (item, i, self['itemMakeExtraArgs'])) + item = self['itemMakeFunction'](*(item, i, self['itemMakeExtraArgs'])) else: item = DirectFrame(text = item, text_align = self['itemsAlign'], diff --git a/toontown/pgui/DirectSlider.py b/toontown/pgui/DirectSlider.py index d2066c3b6..907e34c65 100644 --- a/toontown/pgui/DirectSlider.py +++ b/toontown/pgui/DirectSlider.py @@ -3,9 +3,9 @@ __all__ = ['DirectSlider'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG -from DirectFrame import * -from DirectButton import * +from . import DirectGuiGlobals as DGG +from .DirectFrame import * +from .DirectButton import * """ import DirectSlider @@ -111,7 +111,7 @@ def setOrientation(self): elif self['orientation'] == DGG.VERTICAL: self.guiItem.setAxis(Vec3(0, 0, 1)) else: - raise ValueError, 'Invalid value for orientation: %s' % (self['orientation']) + raise ValueError('Invalid value for orientation: %s' % (self['orientation'])) def destroy(self): if (hasattr(self, 'thumb')): @@ -124,4 +124,4 @@ def commandFunc(self): self._optionInfo['value'][DGG._OPT_VALUE] = self.guiItem.getValue() if self['command']: - apply(self['command'], self['extraArgs']) + self['command'](*self['extraArgs']) diff --git a/toontown/pgui/DirectWaitBar.py b/toontown/pgui/DirectWaitBar.py index c1e7bee0c..bbf269a9a 100644 --- a/toontown/pgui/DirectWaitBar.py +++ b/toontown/pgui/DirectWaitBar.py @@ -3,8 +3,8 @@ __all__ = ['DirectWaitBar'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG -from DirectFrame import * +from . import DirectGuiGlobals as DGG +from .DirectFrame import * import types """ @@ -93,7 +93,7 @@ def setBarTexture(self): """Updates the bar texture, which you can set using bar['barTexture'].""" # this must be a single texture (or a string). texture = self['barTexture'] - if isinstance(texture, types.StringTypes): + if isinstance(texture, (str,)): texture = loader.loadTexture(texture) if texture: self.barStyle.setTexture(texture) diff --git a/toontown/pgui/OnscreenGeom.py b/toontown/pgui/OnscreenGeom.py index d9ef571aa..a7d5544cd 100644 --- a/toontown/pgui/OnscreenGeom.py +++ b/toontown/pgui/OnscreenGeom.py @@ -3,7 +3,7 @@ __all__ = ['OnscreenGeom'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG +from . import DirectGuiGlobals as DGG from direct.showbase.DirectObject import DirectObject import string,types @@ -50,25 +50,25 @@ def __init__(self, geom = None, # Adjust pose # Set pos - if (isinstance(pos, types.TupleType) or - isinstance(pos, types.ListType)): - apply(self.setPos, pos) + if (isinstance(pos, tuple) or + isinstance(pos, list)): + self.setPos(*pos) elif isinstance(pos, VBase3): self.setPos(pos) # Hpr - if (isinstance(hpr, types.TupleType) or - isinstance(hpr, types.ListType)): - apply(self.setHpr, hpr) + if (isinstance(hpr, tuple) or + isinstance(hpr, list)): + self.setHpr(*hpr) elif isinstance(hpr, VBase3): self.setPos(hpr) # Scale - if (isinstance(scale, types.TupleType) or - isinstance(scale, types.ListType)): - apply(self.setScale, scale) + if (isinstance(scale, tuple) or + isinstance(scale, list)): + self.setScale(*scale) elif isinstance(scale, VBase3): self.setPos(scale) - elif (isinstance(scale, types.FloatType) or - isinstance(scale, types.IntType)): + elif (isinstance(scale, float) or + isinstance(scale, int)): self.setScale(scale) def setGeom(self, geom, @@ -94,7 +94,7 @@ def setGeom(self, geom, # Assign geometry if isinstance(geom, NodePath): self.assign(geom.copyTo(parent, sort)) - elif isinstance(geom, types.StringTypes): + elif isinstance(geom, (str,)): self.assign(loader.loadModel(geom)) self.reparentTo(parent, sort) @@ -110,24 +110,24 @@ def getGeom(self): return self def configure(self, option=None, **kw): - for option, value in kw.items(): + for option, value in list(kw.items()): # Use option string to access setter function try: setter = getattr(self, 'set' + option[0].upper() + option[1:]) if (((setter == self.setPos) or (setter == self.setHpr) or (setter == self.setScale)) and - (isinstance(value, types.TupleType) or - isinstance(value, types.ListType))): - apply(setter, value) + (isinstance(value, tuple) or + isinstance(value, list))): + setter(*value) else: setter(value) except AttributeError: - print 'OnscreenText.configure: invalid option:', option + print('OnscreenText.configure: invalid option:', option) # Allow index style references def __setitem__(self, key, value): - apply(self.configure, (), {key: value}) + self.configure(*(), **{key: value}) def cget(self, option): # Get current configuration setting. diff --git a/toontown/pgui/OnscreenImage.py b/toontown/pgui/OnscreenImage.py index 50923eec1..3c5308758 100644 --- a/toontown/pgui/OnscreenImage.py +++ b/toontown/pgui/OnscreenImage.py @@ -3,7 +3,7 @@ __all__ = ['OnscreenImage'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG +from . import DirectGuiGlobals as DGG from direct.showbase.DirectObject import DirectObject import string,types @@ -50,25 +50,25 @@ def __init__(self, image = None, # Adjust pose # Set pos - if (isinstance(pos, types.TupleType) or - isinstance(pos, types.ListType)): - apply(self.setPos, pos) + if (isinstance(pos, tuple) or + isinstance(pos, list)): + self.setPos(*pos) elif isinstance(pos, VBase3): self.setPos(pos) # Hpr - if (isinstance(hpr, types.TupleType) or - isinstance(hpr, types.ListType)): - apply(self.setHpr, hpr) + if (isinstance(hpr, tuple) or + isinstance(hpr, list)): + self.setHpr(*hpr) elif isinstance(hpr, VBase3): self.setHpr(hpr) # Scale - if (isinstance(scale, types.TupleType) or - isinstance(scale, types.ListType)): - apply(self.setScale, scale) + if (isinstance(scale, tuple) or + isinstance(scale, list)): + self.setScale(*scale) elif isinstance(scale, VBase3): self.setScale(scale) - elif (isinstance(scale, types.FloatType) or - isinstance(scale, types.IntType)): + elif (isinstance(scale, float) or + isinstance(scale, int)): self.setScale(scale) # Set color @@ -96,7 +96,7 @@ def setImage(self, image, # Assign geometry if isinstance(image, NodePath): self.assign(image.copyTo(parent, sort)) - elif isinstance(image, types.StringTypes) or \ + elif isinstance(image, (str,)) or \ isinstance(image, Texture): if isinstance(image, Texture): # It's a Texture @@ -116,9 +116,9 @@ def setImage(self, image, if node: self.assign(node.copyTo(parent, sort)) else: - print 'OnscreenImage: node %s not found' % image[1] + print('OnscreenImage: node %s not found' % image[1]) else: - print 'OnscreenImage: model %s not found' % image[0] + print('OnscreenImage: model %s not found' % image[0]) if transform and not self.isEmpty(): self.setTransform(transform) @@ -127,24 +127,24 @@ def getImage(self): return self def configure(self, option=None, **kw): - for option, value in kw.items(): + for option, value in list(kw.items()): # Use option string to access setter function try: setter = getattr(self, 'set' + option[0].upper() + option[1:]) if (((setter == self.setPos) or (setter == self.setHpr) or (setter == self.setScale)) and - (isinstance(value, types.TupleType) or - isinstance(value, types.ListType))): - apply(setter, value) + (isinstance(value, tuple) or + isinstance(value, list))): + setter(*value) else: setter(value) except AttributeError: - print 'OnscreenImage.configure: invalid option:', option + print('OnscreenImage.configure: invalid option:', option) # Allow index style references def __setitem__(self, key, value): - apply(self.configure, (), {key: value}) + self.configure(*(), **{key: value}) def cget(self, option): # Get current configuration setting. diff --git a/toontown/pgui/OnscreenText.py b/toontown/pgui/OnscreenText.py index ed212d264..3b70aeb1d 100644 --- a/toontown/pgui/OnscreenText.py +++ b/toontown/pgui/OnscreenText.py @@ -3,7 +3,7 @@ __all__ = ['OnscreenText', 'Plain', 'ScreenTitle', 'ScreenPrompt', 'NameConfirm', 'BlackOnWhite'] from pandac.PandaModules import * -import DirectGuiGlobals as DGG +from . import DirectGuiGlobals as DGG from direct.showbase.DirectObject import DirectObject import string,types @@ -152,7 +152,7 @@ def __init__(self, text = '', else: raise ValueError - if not isinstance(scale, types.TupleType): + if not isinstance(scale, tuple): # If the scale is already a tuple, it's a 2-d (x, y) scale. # Otherwise, it's a uniform scale--make it a tuple. scale = (scale, scale) @@ -259,14 +259,14 @@ def clearText(self): self.textNode.clearText() def setText(self, text): - self.unicodeText = isinstance(text, types.UnicodeType) + self.unicodeText = isinstance(text, str) if self.unicodeText: self.textNode.setWtext(text) else: self.textNode.setText(text) def appendText(self, text): - if isinstance(text, types.UnicodeType): + if isinstance(text, str): self.unicodeText = 1 if self.unicodeText: self.textNode.appendWtext(text) @@ -312,7 +312,7 @@ def setScale(self, sx, sy = None): """ if sy == None: - if isinstance(sx, types.TupleType): + if isinstance(sx, tuple): self.scale = sx else: self.scale = (sx, sx) @@ -376,9 +376,9 @@ def setFrame(self, frame): def configure(self, option=None, **kw): # These is for compatibility with DirectGui functions if not self.mayChange: - print 'OnscreenText.configure: mayChange == 0' + print('OnscreenText.configure: mayChange == 0') return - for option, value in kw.items(): + for option, value in list(kw.items()): # Use option string to access setter function try: setter = getattr(self, 'set' + option[0].upper() + option[1:]) @@ -387,11 +387,11 @@ def configure(self, option=None, **kw): else: setter(value) except AttributeError: - print 'OnscreenText.configure: invalid option:', option + print('OnscreenText.configure: invalid option:', option) # Allow index style references def __setitem__(self, key, value): - apply(self.configure, (), {key: value}) + self.configure(*(), **{key: value}) def cget(self, option): # Get current configuration setting. diff --git a/toontown/pickatoon/PickAToon.py b/toontown/pickatoon/PickAToon.py index fcacc1081..df2054189 100644 --- a/toontown/pickatoon/PickAToon.py +++ b/toontown/pickatoon/PickAToon.py @@ -64,7 +64,7 @@ class PickAToon(DirectObject): def __init__(self, avatarList, parentFSM, doneEvent): DirectObject.__init__(self) - self.toonList = {i: (i in [x.position for x in avatarList]) for i in xrange(6)} + self.toonList = {i: (i in [x.position for x in avatarList]) for i in range(6)} self.avatarList = avatarList self.selectedToon = 0 self.doneEvent = doneEvent @@ -203,7 +203,7 @@ def load(self): self.setupButtons(av, position = av.position) buttonIndex.append(av.position) - for pos in xrange(0, 6): + for pos in range(0, 6): if pos not in buttonIndex: button = self.setupButtons(position = pos) diff --git a/toontown/pickatoon/ShardPicker.py b/toontown/pickatoon/ShardPicker.py index f79bc3010..962926cd4 100644 --- a/toontown/pickatoon/ShardPicker.py +++ b/toontown/pickatoon/ShardPicker.py @@ -264,7 +264,7 @@ def compareShardTuples(a, b): else: removeInvasionMarker(buttonTuple[3]) - for shardId, buttonTuple in self.shardButtonMap.items(): + for shardId, buttonTuple in list(self.shardButtonMap.items()): if shardId not in currentMap: buttonTuple[0].destroy() del self.shardButtonMap[shardId] diff --git a/toontown/quest/QuestChoiceGui.py b/toontown/quest/QuestChoiceGui.py index 0925b8f7c..1fc6f820f 100644 --- a/toontown/quest/QuestChoiceGui.py +++ b/toontown/quest/QuestChoiceGui.py @@ -23,7 +23,7 @@ def __init__(self): base.setCellsActive([base.bottomCells[0], base.bottomCells[1]], 0) def setQuests(self, quests, fromNpcId, timeout): - for i in xrange(0, len(quests), 3): + for i in range(0, len(quests), 3): questId, rewardId, toNpcId = quests[i:i + 3] qp = QuestPoster.QuestPoster() qp.reparentTo(self) @@ -43,7 +43,7 @@ def setQuests(self, quests, fromNpcId, timeout): self.timer.setPos(-0.2, 0, -0.6) elif len(quests) == 3 * 3: self['geom_scale'] = (1.85, 1, 0.9) - map(lambda x: x.setScale(0.95), self.questChoicePosters) + list(map(lambda x: x.setScale(0.95), self.questChoicePosters)) self.questChoicePosters[0].setPos(0, 0, -0.4) self.questChoicePosters[1].setPos(0, 0, 0.125) self.questChoicePosters[2].setPos(0, 0, 0.65) diff --git a/toontown/quest/QuestMap.py b/toontown/quest/QuestMap.py index 68416050b..be5e21069 100644 --- a/toontown/quest/QuestMap.py +++ b/toontown/quest/QuestMap.py @@ -223,7 +223,7 @@ def updateQuestInfo(self): if (self.hoodId != hoodId) or (self.zoneId != branchId): continue - for blockIndex in xrange(base.cr.playGame.dnaStore.getNumBlockNumbers()): + for blockIndex in range(base.cr.playGame.dnaStore.getNumBlockNumbers()): blockNumber = base.cr.playGame.dnaStore.getBlockNumberAt(blockIndex) zoneId = base.cr.playGame.dnaStore.getZoneFromBlockNumber(blockNumber) interiorZoneId = (zoneId - (zoneId%100)) + 500 + blockNumber @@ -236,7 +236,7 @@ def updateQuestInfo(self): isSuitBlock=base.cr.playGame.dnaStore.isSuitBlock(blockNumber)) continue - for blockIndex in xrange(base.cr.playGame.dnaStore.getNumBlockNumbers()): + for blockIndex in range(base.cr.playGame.dnaStore.getNumBlockNumbers()): blockNumber = base.cr.playGame.dnaStore.getBlockNumberAt(blockIndex) if base.cr.playGame.dnaStore.isSuitBlock(blockNumber) and blockNumber not in self.questBlocks: self.putSuitBuildingMarker( diff --git a/toontown/quest/QuestParser.py b/toontown/quest/QuestParser.py index 89a95803f..2ba10f9d6 100644 --- a/toontown/quest/QuestParser.py +++ b/toontown/quest/QuestParser.py @@ -1,5 +1,5 @@ import copy, os, re, sys, token, tokenize -from StringIO import StringIO +from io import StringIO from panda3d.core import * from direct.directnotify import DirectNotifyGlobal from direct.interval.IntervalGlobal import * @@ -80,7 +80,7 @@ def getLineOfTokens(gen): tokens = [] nextNeg = 0 try: - token = gen.next() + token = next(gen) except StopIteration: return None if token[0] == tokenize.ENDMARKER: @@ -108,7 +108,7 @@ def getLineOfTokens(gen): notify.warning('Ignored token type: %s on line: %s' % (tokenize.tok_name[token[0]], token[2][0])) try: - token = gen.next() + token = next(gen) except StopIteration: break @@ -174,7 +174,7 @@ def cleanup(self): self.currentTrack = None self.ignoreAll() taskMgr.remove(self.uniqueId) - for toonHeadFrame in self.toonHeads.values(): + for toonHeadFrame in list(self.toonHeads.values()): toonHeadFrame.destroy() while self.chars: diff --git a/toontown/quest/QuestPoster.py b/toontown/quest/QuestPoster.py index cc6c28028..02bc81730 100644 --- a/toontown/quest/QuestPoster.py +++ b/toontown/quest/QuestPoster.py @@ -192,7 +192,7 @@ def loadElevator(self, building, numFloors, isCogdo=False): None, None] npc = elevatorModel.findAllMatches('**/floor_light_?;+s') - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): np = npc.getPath(i) floor = int(np.getName()[-1:]) - 1 floorIndicator[floor] = np @@ -350,7 +350,7 @@ def update(self, questDesc): if not wantFormat: captions = quest.getObjectiveStrings() else: - captions = map(string.capwords, quest.getObjectiveStrings()) + captions = list(map(string.capwords, quest.getObjectiveStrings())) imageColor = Vec4(*self.colors['white']) if quest.getType() == Quests.DeliverGagQuest or quest.getType() == Quests.DeliverItemQuest: frameBgColor = 'red' @@ -434,7 +434,7 @@ def update(self, questDesc): invModel = loader.loadModel('phase_3.5/models/gui/inventory_icons') posChoices = [] access = base.localAvatar.getTrackAccess() - for i in xrange(len(Tracks)): + for i in range(len(Tracks)): if access[i] == 0: posChoices.append(i) lIconGeom = invModel.find('**/' + AvPropsNew[random.choice(posChoices)][1]) @@ -500,7 +500,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsCogNewbieQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -569,7 +569,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsCogNewbieQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -602,7 +602,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsCogNewbieQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -635,7 +635,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsCogNewbieQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -668,7 +668,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsCogNewbieQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -701,7 +701,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsCogNewbieQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -734,7 +734,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsCogPartQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -767,7 +767,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsCogNewbieQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -796,7 +796,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsCogNewbieQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -825,7 +825,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsCogNewbieQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -854,7 +854,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsCogNewbieQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -883,7 +883,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsCogNewbieQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -912,7 +912,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsRescueQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -980,7 +980,7 @@ def update(self, questDesc): infoText = TTLocalizer.QuestPosterPlayground if not fComplete: captions = [TTLocalizer.QuestsMinigameNewbieQuestCaption % quest.getNewbieLevel()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsMinigameNewbieQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -1045,7 +1045,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsCogNewbieQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) @@ -1091,7 +1091,7 @@ def update(self, questDesc): if not fComplete: headlineString = TTLocalizer.QuestsNewbieQuestHeadline captions = [quest.getCaption()] - captions.append(map(string.capwords, quest.getObjectiveStrings())) + captions.append(list(map(string.capwords, quest.getObjectiveStrings()))) auxText = TTLocalizer.QuestsCogNewbieQuestAux lPos.setX(-0.18) self.laffMeter = self.createLaffMeter(quest.getNewbieLevel()) diff --git a/toontown/quest/QuestRewardCounter.py b/toontown/quest/QuestRewardCounter.py index 91fc599c4..de6e9c21b 100644 --- a/toontown/quest/QuestRewardCounter.py +++ b/toontown/quest/QuestRewardCounter.py @@ -91,7 +91,7 @@ def setFromAvatar(self, av): def setRewardIndex(self, tier, rewardIds, rewardHistory): self.reset() - for tierNum in xrange(tier): + for tierNum in range(tier): for rewardId in Quests.getRewardsInTier(tierNum): reward = Quests.getReward(rewardId) reward.countReward(self) diff --git a/toontown/quest/Quests.py b/toontown/quest/Quests.py index f00d3b17b..ef76c082c 100644 --- a/toontown/quest/Quests.py +++ b/toontown/quest/Quests.py @@ -146,9 +146,9 @@ def simulateRecoveryVar(numNeeded, baseChance, list = 0, cap = 1): else: currentFail += 1 - print 'Test results: %s tries, %s longest failure chain, %s cap hits' % (numTries, greatestFailChain, capHits) + print('Test results: %s tries, %s longest failure chain, %s cap hits' % (numTries, greatestFailChain, capHits)) if list: - print 'failures for each succes %s' % attemptList + print('failures for each succes %s' % attemptList) def simulateRecoveryFix(numNeeded, baseChance, list = 0): @@ -173,9 +173,9 @@ def simulateRecoveryFix(numNeeded, baseChance, list = 0): else: currentFail += 1 - print 'Test results: %s tries, %s longest failure chain' % (numTries, greatestFailChain) + print('Test results: %s tries, %s longest failure chain' % (numTries, greatestFailChain)) if list: - print 'failures for each succes %s' % attemptList + print('failures for each succes %s' % attemptList) class Quest: @@ -195,7 +195,7 @@ def check(self, cond, msg): pass def checkLocation(self, location): - locations = [Anywhere] + TTLocalizer.GlobalStreetNames.keys() + locations = [Anywhere] + list(TTLocalizer.GlobalStreetNames.keys()) self.check(location in locations, 'invalid location: %s' % location) def checkNumCogs(self, num): @@ -205,7 +205,7 @@ def checkNewbieLevel(self, level): self.check(1, 'invalid newbie level: %s' % level) def checkCogType(self, type): - types = [Any] + SuitBattleGlobals.SuitAttributes.keys() + types = [Any] + list(SuitBattleGlobals.SuitAttributes.keys()) self.check(type in types, 'invalid cog type: %s' % type) def checkCogTrack(self, track): @@ -290,13 +290,13 @@ def checkGagItem(self, item): self.check(item >= ToontownBattleGlobals.MIN_LEVEL_INDEX and item <= ToontownBattleGlobals.MAX_LEVEL_INDEX, 'invalid gag item: %s' % item) def checkDeliveryItem(self, item): - self.check(ItemDict.has_key(item), 'invalid delivery item: %s' % item) + self.check(item in ItemDict, 'invalid delivery item: %s' % item) def checkNumItems(self, num): self.check(1, 'invalid num items: %s' % num) def checkRecoveryItem(self, item): - self.check(ItemDict.has_key(item), 'invalid recovery item: %s' % item) + self.check(item in ItemDict, 'invalid recovery item: %s' % item) def checkPercentChance(self, chance): self.check(chance > 0 and chance <= 100, 'invalid percent chance: %s' % chance) @@ -305,7 +305,7 @@ def checkRecoveryItemHolderAndType(self, holder, holderType = 'type'): holderTypes = ['type', 'level', 'track'] self.check(holderType in holderTypes, 'invalid recovery item holderType: %s' % holderType) if holderType == 'type': - holders = [Any, AnyFish] + SuitBattleGlobals.SuitAttributes.keys() + holders = [Any, AnyFish] + list(SuitBattleGlobals.SuitAttributes.keys()) self.check(holder in holders, 'invalid recovery item holder: %s for holderType: %s' % (holder, holderType)) elif holderType == 'level': pass @@ -2131,7 +2131,7 @@ def testRecover(self, progress): def testDone(self, progress): numberDone = progress & pow(2, 16) - 1 - print 'Quest number done %s' % numberDone + print('Quest number done %s' % numberDone) if numberDone >= self.getNumItems(): return 1 else: @@ -3261,11 +3261,11 @@ def isQuestJustForFun(questId, rewardId): def getAllRewardIdsForReward(rewardId): if rewardId is AnyCashbotSuitPart: - return range(4000, 4011 + 1) + return list(range(4000, 4011 + 1)) if rewardId is AnyLawbotSuitPart: - return range(4100, 4113 + 1) + return list(range(4100, 4113 + 1)) if rewardId is AnyBossbotSuitPart: - return range(4200, 4216 + 1) + return list(range(4200, 4216 + 1)) return (rewardId,) @@ -3277,7 +3277,7 @@ def findFinalRewardId(questId): try: questDesc = QuestDict[questId] except KeyError: - print 'findFinalRewardId: Quest ID: %d not found' % questId + print('findFinalRewardId: Quest ID: %d not found' % questId) return -1 nextQuestId = questDesc[QuestDictNextQuestIndex] @@ -3298,7 +3298,7 @@ def findFinalRewardId(questId): return (finalRewardId, remainingSteps) -for questId in QuestDict.keys(): +for questId in list(QuestDict.keys()): findFinalRewardId(questId) def getStartingQuests(tier = None): @@ -3369,7 +3369,7 @@ def filterQuests(entireQuestPool, currentNpc, av): notify.debug('filterQuests: entireQuestPool: %s' % entireQuestPool) validQuestPool = dict([ (questId, 1) for questId in entireQuestPool ]) if isLoopingFinalTier(av.getRewardTier()): - history = map(lambda questDesc: questDesc[0], av.quests) + history = [questDesc[0] for questDesc in av.quests] else: history = av.getQuestHistory() if notify.getDebug(): @@ -3414,7 +3414,7 @@ def filterQuests(entireQuestPool, currentNpc, av): notify.debug('filterQuests: Removed %s because npc involved' % questId) break - finalQuestPool = filter(lambda key: validQuestPool[key], validQuestPool.keys()) + finalQuestPool = [key for key in list(validQuestPool.keys()) if validQuestPool[key]] if notify.getDebug(): notify.debug('filterQuests: finalQuestPool: %s' % finalQuestPool) return finalQuestPool @@ -3556,7 +3556,7 @@ def chooseBestQuests(currentNpc, av): for entry in currentQuests: currentIds.append(getFirstQuestIdInChain(entry[0])) bestQuests = [] - for questId in QuestDict.keys(): + for questId in list(QuestDict.keys()): if len(bestQuests) >= 3: break questEntry = QuestDict.get(questId) @@ -3604,7 +3604,7 @@ def getFirstQuestIdInChain(questId): return questId def questExists(id): - return QuestDict.has_key(id) + return id in QuestDict def getQuest(id): @@ -4227,7 +4227,7 @@ def getNextRewards(numChoices, tier, av): if av.getGameAccess() == OTPGlobals.AccessFull and tier == TT_TIER + 3: optRewards = [] if isLoopingFinalTier(tier): - rewardHistory = map(lambda questDesc: questDesc[3], av.quests) + rewardHistory = [questDesc[3] for questDesc in av.quests] if notify.getDebug(): notify.debug('getNextRewards: current rewards (history): %s' % rewardHistory) else: @@ -4958,7 +4958,7 @@ def getNumRewardsInTier(tier): def rewardTierExists(tier): - return RequiredRewardTrackDict.has_key(tier) + return tier in RequiredRewardTrackDict def getOptionalRewardsInTier(tier): @@ -5447,7 +5447,7 @@ def getRewardIdFromTrackId(trackId): 4306)} def isRewardOptional(tier, rewardId): - return OptionalRewardTrackDict.has_key(tier) and rewardId in OptionalRewardTrackDict[tier] + return tier in OptionalRewardTrackDict and rewardId in OptionalRewardTrackDict[tier] def getItemName(itemId): @@ -5518,7 +5518,7 @@ def avatarHasAllRequiredRewards(av, tier): avQuests = av.getQuests() # Iterate through the current quests. - for i in xrange(0, len(avQuests), 5): + for i in range(0, len(avQuests), 5): questDesc = avQuests[i:i + 5] questId, fromNpcId, toNpcId, rewardId, toonProgress = questDesc transformedRewardId = transformReward(rewardId, av) @@ -5567,7 +5567,7 @@ def avatarHasAllRequiredRewards(av, tier): def nextQuestList(nextQuest): if nextQuest == NA: return None - seqTypes = (types.ListType, types.TupleType) + seqTypes = (list, tuple) if type(nextQuest) in seqTypes: return nextQuest else: @@ -5580,12 +5580,12 @@ def checkReward(questId, forked = 0): reward = quest[5] nextQuests = nextQuestList(quest[6]) if nextQuests is None: - validRewards = RewardDict.keys() + [Any, + validRewards = list(RewardDict.keys()) + [Any, AnyCashbotSuitPart, AnyLawbotSuitPart, OBSOLETE] if reward is OBSOLETE: - print 'warning: quest %s is obsolete' % questId + print('warning: quest %s is obsolete' % questId) return reward else: forked = forked or len(nextQuests) > 1 @@ -5598,16 +5598,16 @@ def checkReward(questId, forked = 0): def assertAllQuestsValid(): - print 'checking quests...' - for questId in QuestDict.keys(): + print('checking quests...') + for questId in list(QuestDict.keys()): try: quest = getQuest(questId) - except AssertionError, e: + except AssertionError as e: err = 'invalid quest: %s' % questId - print err + print(err) raise - for questId in QuestDict.keys(): + for questId in list(QuestDict.keys()): quest = QuestDict[questId] tier, start, questDesc, fromNpc, toNpc, reward, nextQuest, dialog = quest if start: diff --git a/toontown/quest/TrackChoiceGui.py b/toontown/quest/TrackChoiceGui.py index 66c0abc7c..18e919508 100644 --- a/toontown/quest/TrackChoiceGui.py +++ b/toontown/quest/TrackChoiceGui.py @@ -70,7 +70,7 @@ def __init__(self, tracks, timeout): self.timer.countdown(timeout, self.timeout) self.trackChoicePosters = [] trackAccess = base.localAvatar.getTrackAccess() - for trackId in xrange(ToontownBattleGlobals.NUM_GAG_TRACKS): + for trackId in range(ToontownBattleGlobals.NUM_GAG_TRACKS): if trackAccess[trackId] == 0: self.choices.append(trackId) tp = TrackPoster(trackId, self.chooseTrack) diff --git a/toontown/racing/DistributedLeaderBoard.py b/toontown/racing/DistributedLeaderBoard.py index 57d2f8cca..aa72a4ef8 100644 --- a/toontown/racing/DistributedLeaderBoard.py +++ b/toontown/racing/DistributedLeaderBoard.py @@ -7,7 +7,7 @@ from pandac.PandaModules import * from toontown.toonbase.ToontownGlobals import * import random -import cPickle +import pickle class DistributedLeaderBoard(DistributedObject.DistributedObject): notify = DirectNotifyGlobal.directNotify.newCategory('DisributedLeaderBoard') @@ -52,7 +52,7 @@ def setPosHpr(self, x, y, z, h, p, r): def setDisplay(self, pData): self.notify.debug('setDisplay: changing leaderboard text on local side') - trackName, recordTitle, scores = cPickle.loads(pData) + trackName, recordTitle, scores = pickle.loads(pData) self.display(trackName, recordTitle, scores) def buildListParts(self): @@ -72,7 +72,7 @@ def buildListParts(self): z = zListTop self.nameTextNodes = [] self.timeTextNodes = [] - for i in xrange(10): + for i in range(10): row, nameText, timeText, placeText = self.buildLeaderRow() self.nameTextNodes.append(nameText) placeText.setText(str(len(self.nameTextNodes)) + '.') @@ -92,7 +92,7 @@ def display(self, pTrackTitle = 'Track Title', pPeriodTitle = 'Period Title', pL self.titleTextNode.setText(pPeriodTitle) self.trackNameNode.setText(pTrackTitle) self.updateCount += 1 - for i in xrange(10): + for i in range(10): if i > len(pLeaderList): self.nameTextNodes[i].setText('-') self.timeTextNodes[i].setText('-') diff --git a/toontown/racing/DistributedRace.py b/toontown/racing/DistributedRace.py index 8bdc576e0..efbf6b783 100644 --- a/toontown/racing/DistributedRace.py +++ b/toontown/racing/DistributedRace.py @@ -121,7 +121,7 @@ def announceGenerate(self): localAvatar.d_broadcastPositionNow() DistributedSmoothNode.activateSmoothing(1, 1) self.reversed = self.trackId / 2.0 > int(self.trackId / 2.0) - for i in xrange(3): + for i in range(3): base.loader.tick() self.sky = loader.loadModel('phase_3.5/models/props/TT_sky') @@ -135,7 +135,7 @@ def announceGenerate(self): self.loadFog() self.setupGeom() self.startSky() - for i in xrange(5): + for i in range(5): base.loader.tick() def disable(self): @@ -252,7 +252,7 @@ def setPlace(self, avId, totalTime, place, entryFee, qualify, winnings, bonus, t return def setCircuitPlace(self, avId, place, entryFee, winnings, bonus, trophies): - print 'setting cicruit place' + print('setting cicruit place') if self.fsm.getCurrentState().getName() == 'leaving': return if avId == localAvatar.doId: @@ -265,13 +265,13 @@ def setCircuitPlace(self, avId, place, entryFee, winnings, bonus, trophies): self.placeFixup.append([oldPlace - 1, place - 1]) avatar = base.cr.doId2do.get(avId, None) if avatar: - print 'circuit trophies %s' % trophies - print 'winnings %s' % winnings + print('circuit trophies %s' % trophies) + print('winnings %s' % winnings) self.gui.racerFinishedCircuit(avId, oldPlace, entryFee, winnings, bonus, trophies) return def endCircuitRace(self): - print self.placeFixup + print(self.placeFixup) self.gui.circuitFinished(self.placeFixup) def prepForRace(self): @@ -421,7 +421,7 @@ def enterPrep(self): self.spin = Vec3(180, 0, 0) else: self.spin = Vec3(0, 0, 0) - for i in xrange(4): + for i in range(4): base.loader.tick() self.gui.initRaceMode() @@ -772,7 +772,7 @@ def loadUrbanTrack(self): self.buildingGroups[side] = [] self.currBldgInd[side] = None self.currBldgGroups[side] = None - for i in xrange(maxNum): + for i in range(maxNum): for barricade in ('innerbarricade', 'outerbarricade'): bldgGroup = self.townGeom.find('**/Buildings_' + side + '-' + barricade + '_' + str(i)) if bldgGroup.isEmpty(): @@ -913,7 +913,7 @@ def showBuildings(self, t, forceRecompute = False): def setupGeom(self): trackFilepath = RaceGlobals.TrackDict[self.trackId][0] self.geom = loader.loadModel(trackFilepath) - for i in xrange(10): + for i in range(10): base.loader.tick() self.geom.reparentTo(render) @@ -923,12 +923,12 @@ def setupGeom(self): lapStartPos = self.geom.find('**/lap_start').getPos() self.startPos = lapStartPos lapMidPos = self.geom.find('**/lap_middle').getPos() - for i in xrange(5): + for i in range(5): base.loader.tick() self.startingPos = [] posLocators = self.geom.findAllMatches('**/start_pos*') - for i in xrange(posLocators.getNumPaths()): + for i in range(posLocators.getNumPaths()): base.loader.tick() self.startingPos.append([posLocators[i].getPos(), posLocators[i].getHpr()]) @@ -942,35 +942,35 @@ def setupGeom(self): self.curve = self.geom.find('**/curve_reverse').node() else: self.curve = self.geom.find('**/curve_forward').node() - for i in xrange(4000): + for i in range(4000): self.curvePoints.append(Point3(0, 0, 0)) self.curve.getPoint(i / 4000.0 * (self.curve.getMaxT() - 1e-11), self.curvePoints[-1]) self.curveTs.append(i / 4000.0 * (self.curve.getMaxT() - 1e-11)) if self.trackId in (RaceGlobals.RT_Urban_2, RaceGlobals.RT_Urban_2_rev): self.precomputeSideStreets() - for i in xrange(10): + for i in range(10): base.loader.tick() self.startT = self.getNearestT(lapStartPos) self.midT = self.getNearestT(lapMidPos) self.gags = [] gagList = RaceGlobals.TrackDict[self.trackId][4] - for i in xrange(len(gagList)): + for i in range(len(gagList)): self.notify.debug('generating gag: %s' % i) self.gags.append(RaceGag(self, i, Vec3(*gagList[i]) + Vec3(0, 0, 3))) - for i in xrange(5): + for i in range(5): base.loader.tick() def precomputeSideStreets(self): farDist = base.camLens.getFar() + 300 farDistSquared = farDist * farDist - for i in xrange(int(self.barricadeSegments)): + for i in range(int(self.barricadeSegments)): testPoint = Point3(0, 0, 0) self.curve.getPoint(i / self.barricadeSegments * (self.curve.getMaxT() - 1e-11), testPoint) for side in ('innersidest', 'outersidest'): - for bldgGroupIndex in xrange(len(self.buildingGroups[side])): + for bldgGroupIndex in range(len(self.buildingGroups[side])): bldgGroup = self.buildingGroups[side][bldgGroupIndex] if not bldgGroup.getNode(0).getBounds().isEmpty(): bldgPoint = bldgGroup.getNode(0).getBounds().getCenter() @@ -1019,7 +1019,7 @@ def findSegmentStart(self): minIndex = -1 currPoint = Point3(0, 0, 0) kartPoint = self.localKart.getPos() - for i in xrange(len(self.curvePoints)): + for i in range(len(self.curvePoints)): currPoint = self.curvePoints[i] currLength2 = (kartPoint - currPoint).lengthSquared() if currLength2 < minLength2: @@ -1046,7 +1046,7 @@ def getNearestT(self, pos): minLength2 = 1000000 minIndex = -1 currPoint = Point3(0, 0, 0) - for i in xrange(len(self.curvePoints)): + for i in range(len(self.curvePoints)): currPoint = self.curvePoints[i] currLength2 = (pos - currPoint).lengthSquared() if currLength2 < minLength2: @@ -1194,7 +1194,7 @@ def hitBoostArrow(self, cevent): idStr = into.getTag('boostId') arrowVec = self.boostDir.get(idStr) if arrowVec == None: - print 'Unknown boost arrow %s' % idStr + print('Unknown boost arrow %s' % idStr) return fvec = self.localKart.forward.getPos(self.geom) - self.localKart.getPos(self.geom) fvec.normalize() diff --git a/toontown/racing/DistributedRaceAI.py b/toontown/racing/DistributedRaceAI.py index 42b42ca53..90d66d93d 100644 --- a/toontown/racing/DistributedRaceAI.py +++ b/toontown/racing/DistributedRaceAI.py @@ -43,7 +43,7 @@ def delete(self): for gag in self.livingGags: gag.requestDelete() self.air.deallocateZone(self.zoneId) - for i in xrange(len(self.gags)): + for i in range(len(self.gags)): taskMgr.remove('regenGag%i-%i' % (i, self.doId)) DistributedObjectAI.delete(self) @@ -58,7 +58,7 @@ def enterPrep(self): self.beginBarrier('waitingForReady', self.avatars, 60, self.readyBarrierCallback) self.gagPoints = RaceGlobals.TrackDict[self.trackId][4] if self.raceType != RaceGlobals.Practice: - for i in xrange(len(self.gagPoints)): + for i in range(len(self.gagPoints)): gagId = random.randint(0, 5) self.b_genGag(i, 1, gagId) self.d_prepForRace() @@ -321,7 +321,7 @@ def calculateTrophies(self, avId, won, qualify, time): kartingHistory = av.getKartingHistory() avTrophies = av.getKartingTrophies() numTrophies = 0 - for i in xrange(30): + for i in range(30): if avTrophies[i] != 0: numTrophies += 1 oldLaffBoost = int(numTrophies/10) @@ -333,7 +333,7 @@ def calculateTrophies(self, avId, won, qualify, time): if kartingHistory[3] > RaceGlobals.TotalWonRaces: avTrophies[RaceGlobals.TotalWins] = 1 trophies.append(RaceGlobals.TotalWins) - for i in xrange(3): + for i in range(3): if kartingHistory[genre] >= RaceGlobals.WonRaces[i] and avTrophies[RaceGlobals.AllWinsList[genre][i]] != 1: avTrophies[RaceGlobals.AllWinsList[genre][i]] = 1 trophies.append(RaceGlobals.AllWinsList[genre][i]) @@ -343,7 +343,7 @@ def calculateTrophies(self, avId, won, qualify, time): if kartingHistory[7] >= RaceGlobals.TotalQualifiedRaces and avTrophies[RaceGlobals.TotalQuals] != 1: avTrophies[RaceGlobals.TotalQuals] = 1 trophies.append(RaceGlobals.TotalQuals) - for i in xrange(3): + for i in range(3): if kartingHistory[genre + 4] >= RaceGlobals.QualifiedRaces[i] and avTrophies[RaceGlobals.AllQualsList[genre][i]] != 1: avTrophies[RaceGlobals.AllQualsList[genre][i]] = 1 trophies.append(RaceGlobals.AllQualsList[genre][i]) @@ -352,7 +352,7 @@ def calculateTrophies(self, avId, won, qualify, time): kartingHistory[i] = 255 av.b_setKartingHistory(kartingHistory) pKartingBest = av.getKartingPersonalBestAll() - trackIndex = TTLocalizer.KartRace_TrackNames.keys().index(self.trackId) + trackIndex = list(TTLocalizer.KartRace_TrackNames.keys()).index(self.trackId) if pKartingBest[trackIndex] > time or not pKartingBest[trackIndex]: pKartingBest[trackIndex] = time av.b_setKartingPersonalBest(pKartingBest) @@ -366,7 +366,7 @@ def calculateTrophies(self, avId, won, qualify, time): trophies.append(RaceGlobals.GrandTouring) newLaffBoost = int((len(trophies) + numTrophies)/10) if newLaffBoost - oldLaffBoost != 0: - for i in xrange(newLaffBoost): + for i in range(newLaffBoost): if avTrophies[RaceGlobals.TrophyCups[i]] != 1: avTrophies[RaceGlobals.TrophyCups[i]] = 1 trophies.append(RaceGlobals.TrophyCups[i]) diff --git a/toontown/racing/DistributedRacePad.py b/toontown/racing/DistributedRacePad.py index 071c25565..27c32288a 100644 --- a/toontown/racing/DistributedRacePad.py +++ b/toontown/racing/DistributedRacePad.py @@ -206,7 +206,7 @@ def hideTunnelSignText(self): if self.tunnelSign: textNodePaths = self.tunnelSign.findAllMatches('**/+TextNode') numTextNodePaths = textNodePaths.getNumPaths() - for i in xrange(numTextNodePaths): + for i in range(numTextNodePaths): textNodePath = textNodePaths.getPath(i) textNodePath.hide() @@ -214,7 +214,7 @@ def showTunnelSignText(self): if self.tunnelSign: textNodePaths = self.tunnelSign.findAllMatches('**/+TextNode') numTextNodePaths = textNodePaths.getNumPaths() - for i in xrange(numTextNodePaths): + for i in range(numTextNodePaths): textNodePath = textNodePaths.getPath(i) textNodePath.show() @@ -265,7 +265,7 @@ def cleanupTunnelText(self): if self.tunnelSign: textNodePaths = self.tunnelSign.findAllMatches('**/+TextNode') numTextNodePaths = textNodePaths.getNumPaths() - for i in xrange(numTextNodePaths): + for i in range(numTextNodePaths): textNodePath = textNodePaths.getPath(i) textNodePath.removeNode() textNodePath = None diff --git a/toontown/racing/DistributedRacePadAI.py b/toontown/racing/DistributedRacePadAI.py index eca1573c9..cc239f29b 100644 --- a/toontown/racing/DistributedRacePadAI.py +++ b/toontown/racing/DistributedRacePadAI.py @@ -126,7 +126,7 @@ def createRace(self): race.setRaceType(self.trackType) race.setCircuitLoop([]) race.setAvatars(avatars) - race.setStartingPlaces(range(len(avatars))) + race.setStartingPlaces(list(range(len(avatars)))) race.setLapCount(3) race.generateWithRequired(self.raceZone) for avId in avatars: diff --git a/toontown/racing/DistributedVehicle.py b/toontown/racing/DistributedVehicle.py index 288909b39..7e3f55fb8 100644 --- a/toontown/racing/DistributedVehicle.py +++ b/toontown/racing/DistributedVehicle.py @@ -130,7 +130,7 @@ def __init__(self, cr): self.pieCount = 0 self.numPieChunks = 6 self.pieSlideSpeed = [] - for piece in xrange(self.numPieChunks): + for piece in range(self.numPieChunks): self.pieSlideSpeed.append(randFloat(0.0, 0.2)) self.wantSmoke = ConfigVariableBool('want-kart-smoke', 1).getValue() @@ -428,7 +428,7 @@ def stopSparkParticles(self, side = None): sides = {0: 'right', 1: 'left'} if side == None: - for x in sides.keys(): + for x in list(sides.keys()): self.sparks[x].effect.getParticlesNamed('particles-1').setBirthRate(1000) taskMgr.doMethodLater(0.75, self.sparks[x].stop, 'stopSparks-' + sides[x], extraArgs=[]) @@ -544,13 +544,13 @@ def doHeadScale(self, model, scale): if scale == None: scale = ToontownGlobals.toonHeadScales[model.style.getAnimal()] base.localAvatar.clearCheesyEffect() - for hi in xrange(model.headParts.getNumPaths()): + for hi in range(model.headParts.getNumPaths()): head = model.headParts[hi] head.setScale(scale) def __createPieWindshield(self): self.piePieces = [] - for piece in xrange(self.numPieChunks): + for piece in range(self.numPieChunks): self.piePieces.append(DirectLabel(relief=None, pos=(0.0, 0.0, 0.0), image=self.pieSplatter, image_scale=(0.5, 0.5, 0.5), text=' ', text_scale=0.18, text_fg=(1, 0, 1, 1), text_pos=(-0.0, 0.0, 0), text_font=ToontownGlobals.getSignFont(), textMayChange=1)) self.piePieces[piece].hide() @@ -562,7 +562,7 @@ def showPieces(self): piece.show() xRange += 2.5 / self.numPieChunks - for piece in xrange(self.numPieChunks): + for piece in range(self.numPieChunks): self.pieSlideSpeed[piece] = randFloat(0.0, 0.2) def splatPie(self): @@ -584,7 +584,7 @@ def __countPies(self): def __slidePies(self, optional = None): dt = globalClock.getDt() - for piece in xrange(self.numPieChunks): + for piece in range(self.numPieChunks): self.pieSlideSpeed[piece] += randFloat(0.0, 0.25 * dt) pieSpeed = self.pieSlideSpeed[piece] * dt self.piePieces[piece].setPos(self.piePieces[piece].getPos()[0], self.piePieces[piece].getPos()[1] - pieSpeed, self.piePieces[piece].getPos()[2] - pieSpeed) @@ -899,7 +899,7 @@ def __watchControls(self, task): driftMin = self.surfaceModifiers[self.groundType]['driftMin'] * 0.2 if self.skidding: driftMin = self.surfaceModifiers[self.groundType]['driftMin'] - for i in xrange(int(numFrames)): + for i in range(int(numFrames)): self.physicsMgr.doPhysics(self.physicsDt) curVelocity = self.actorNode.getPhysicsObject().getVelocity() idealVelocity = curHeading * curSpeed @@ -1017,7 +1017,7 @@ def shakeWheel(self, nWheel, floorNode): def stickCarToGround(self): posList = [] nWheels = len(self.wheelData) - for nWheel in xrange(nWheels): + for nWheel in range(nWheels): cQueue = self.cQueue[nWheel] cQueue.sortEntries() if cQueue.getNumEntries() == 0: @@ -1129,14 +1129,14 @@ def dropOnMe(self, timestamp): def lookUp(self): if self.toon and self.toon.headParts: headParts = self.toon.headParts - for hi in xrange(headParts.getNumPaths()): + for hi in range(headParts.getNumPaths()): head = headParts[hi] head.setP(90) def lookNormal(self): if self.toon and self.toon.headParts: headParts = self.toon.headParts - for hi in xrange(headParts.getNumPaths()): + for hi in range(headParts.getNumPaths()): head = headParts[hi] head.setP(0) @@ -1190,7 +1190,7 @@ def hitBanana(self): self.wipeOut.start() def hitPie(self): - print 'yar, got Me with pi!' + print('yar, got Me with pi!') self.splatPie() if self.wipeOut: self.wipeOut.pause() diff --git a/toontown/racing/Kart.py b/toontown/racing/Kart.py index bf56aaeb4..a4d551df6 100644 --- a/toontown/racing/Kart.py +++ b/toontown/racing/Kart.py @@ -68,13 +68,13 @@ def generateKart(self, forGui = 0): levelIn[0] = base.config.GetInt('lod1-in', 2500) levelIn[1] = base.config.GetInt('lod1-out', 0) self.toonSeat = NodePath('toonSeat') - for level in xrange(lodRequired): + for level in range(lodRequired): self.__createLODKart(level) self.LODnode.addSwitch(levelIn[level], levelOut[level]) self.setScale(self.baseScale) self.flattenMedium() - for level in xrange(lodRequired): + for level in range(lodRequired): self.toonSeat = self.toonSeat.instanceTo(self.toonNode[level]) self.LODpath.reparentTo(self.rotateNode) @@ -134,7 +134,7 @@ def __createLODKart(self, level): self.toonNode[level].setPos(pos) def resetGeomPos(self): - for level in self.geom.keys(): + for level in list(self.geom.keys()): self.geom[level].setPos(0, 0, 0.025) def __update(self): @@ -154,7 +154,7 @@ def __update(self): self.__applyDecals() self.__applyAccessoryColor() else: - raise StandardError, 'Kart::__update - Has this method been called before generateKart?' + raise Exception('Kart::__update - Has this method been called before generateKart?') elif field == KartDNA.bodyColor: self.__applyBodyColor() elif field == KartDNA.accColor: @@ -162,7 +162,7 @@ def __update(self): elif field == KartDNA.ebType: if self.kartAccessories[KartDNA.ebType] != None: name = self.kartAccessories[KartDNA.ebType].getName() - for key in self.geom.keys(): + for key in list(self.geom.keys()): self.geom[key].find('**/%s' % name).removeNode() self.kartAccessories[KartDNA.ebType].removeNode() @@ -171,7 +171,7 @@ def __update(self): elif field == KartDNA.spType: if self.kartAccessories[KartDNA.spType] != None: name = self.kartAccessories[KartDNA.spType].getName() - for key in self.geom.keys(): + for key in list(self.geom.keys()): self.geom[key].find('**/%s' % name).removeNode() self.kartAccessories[KartDNA.spType].removeNode() @@ -180,7 +180,7 @@ def __update(self): elif field == KartDNA.fwwType: if self.kartAccessories[KartDNA.fwwType] != (None, None): left, right = self.kartAccessories[KartDNA.fwwType] - for key in self.geom.keys(): + for key in list(self.geom.keys()): self.geom[key].find('**/%s' % left.getName()).removeNode() self.geom[key].find('**/%s' % right.getName()).removeNode() @@ -191,7 +191,7 @@ def __update(self): elif field == KartDNA.bwwType: if self.kartAccessories[KartDNA.bwwType] != (None, None): left, right = self.kartAccessories[KartDNA.bwwType] - for key in self.geom.keys(): + for key in list(self.geom.keys()): self.geom[key].find('**/%s' % left.getName()).removeNode() self.geom[key].find('**/%s' % right.getName()).removeNode() @@ -436,7 +436,7 @@ def getDNA(self): def setDNA(self, dna): if self.kartDNA != [-1] * getNumFields(): - for field in xrange(len(self.kartDNA)): + for field in range(len(self.kartDNA)): if dna[field] != self.kartDNA[field]: self.updateDNAField(field, dna[field]) @@ -527,7 +527,7 @@ def generateEngineStartTrack(self): length = self.kartStartSfx.length() def printVol(): - print self.kartLoopSfx.getVolume() + print(self.kartLoopSfx.getVolume()) track = Parallel(SoundInterval(self.kartStartSfx), Func(self.kartLoopSfx.play), LerpFunctionInterval(self.kartLoopSfx.setVolume, fromData=0, toData=0.4, duration=length)) return Sequence(track, Func(printVol)) diff --git a/toontown/racing/KartDNA.py b/toontown/racing/KartDNA.py index 28256e2c6..789589780 100644 --- a/toontown/racing/KartDNA.py +++ b/toontown/racing/KartDNA.py @@ -518,9 +518,9 @@ def getTexCardNode(accId): def checkKartDNAValidity(dna): if not checkNumFieldsValidity(len(dna)): return 0 - for field in xrange(len(dna)): + for field in range(len(dna)): if field == KartDNA.bodyType: - if dna[field] not in KartDict.keys(): + if dna[field] not in list(KartDict.keys()): return 0 elif field == KartDNA.bodyColor or field == KartDNA.accColor: accList = [InvalidEntry] + AccessoryTypeDict.get(KartDNA.bodyColor) @@ -556,19 +556,19 @@ def getAccessoryItemList(accessoryType): def getKartTypeInfo(type): - if type in KartDict.keys(): + if type in list(KartDict.keys()): return KartDict[type] return InvalidEntry def getAccessoryInfo(index): - if index in AccessoryDict.keys(): + if index in list(AccessoryDict.keys()): return AccessoryDict[index] return InvalidEntry def getAccessoryType(accessoryId): - for key in AccessoryTypeDict.keys(): + for key in list(AccessoryTypeDict.keys()): if accessoryId in AccessoryTypeDict[key]: return key @@ -591,7 +591,7 @@ def getAccessoryDictFromOwned(accessoryOwnedList, pType = -1): def getAccessDictByType(accessoryOwnedList): accessDict = {} - if type(accessoryOwnedList) == types.ListType: + if type(accessoryOwnedList) == list: for accOwnedId in accessoryOwnedList: accType = getAccessoryType(accOwnedId) if accType != InvalidEntry: @@ -600,7 +600,7 @@ def getAccessDictByType(accessoryOwnedList): accessDict[accType].append(accOwnedId) else: - print 'KartDNA: getAccessDictByType: bad accessory list: ', accessoryOwnedList + print('KartDNA: getAccessDictByType: bad accessory list: ', accessoryOwnedList) return accessDict diff --git a/toontown/racing/KartShopGui.py b/toontown/racing/KartShopGui.py index d94d76c15..25366c5ee 100644 --- a/toontown/racing/KartShopGui.py +++ b/toontown/racing/KartShopGui.py @@ -29,7 +29,7 @@ KS_TEXT_SIZE_BIG = TTLocalizer.KSGtextSizeBig KS_TEXT_SIZE_SMALL = TTLocalizer.KSGtextSizeSmall -class KartShopGuiMgr(object, DirectObject.DirectObject): +class KartShopGuiMgr(DirectObject.DirectObject): notify = DirectNotifyGlobal.directNotify.newCategory('KartShopGuiMgr') class MainMenuDlg(DirectFrame): @@ -90,7 +90,7 @@ class BuyKartDlg(DirectFrame): def __init__(self, doneEvent): self.modelScale = 1 model = loader.loadModel('phase_6/models/gui/BuyKartPanel') - self.unownedKartList = KartDict.keys() + self.unownedKartList = list(KartDict.keys()) if base.localAvatar.hasKart(): k = base.localAvatar.getKartBodyType() if k in self.unownedKartList: @@ -258,7 +258,7 @@ def __init__(self, doneEvent): pressEffect=False, command=lambda : messenger.send(doneEvent, [RK_OPTIONS.ReturnKart])) oldDNA = list(base.localAvatar.getKartDNA()) - for d in xrange(len(oldDNA)): + for d in range(len(oldDNA)): if d == KartDNA.bodyType: continue else: @@ -612,7 +612,7 @@ def showAccessory(self): self.arrowLeftButton['state'] = DGG.NORMAL curDNA = None curDNA = list(base.localAvatar.getKartDNA()) - for d in xrange(len(curDNA)): + for d in range(len(curDNA)): if d == KartDNA.bodyType or d == KartDNA.accColor or d == KartDNA.bodyColor: continue else: @@ -820,7 +820,7 @@ def destroy(self): self.ignoreAll() self.timer.destroy() del self.timer - for event in self.dialogEventDict.values(): + for event in list(self.dialogEventDict.values()): self.ignore(event) self.dialogEventDict = None diff --git a/toontown/racing/Piejectile.py b/toontown/racing/Piejectile.py index eefce5502..0603b3b2e 100644 --- a/toontown/racing/Piejectile.py +++ b/toontown/racing/Piejectile.py @@ -43,7 +43,7 @@ def __init__(self, sourceId, targetId, type, name): self.rotH = randFloat(-360, 360) self.rotP = randFloat(-90, 90) self.rotR = randFloat(-90, 90) - print 'generating Pie %s' % self.name + print('generating Pie %s' % self.name) self.ownerKart = base.cr.doId2do.get(base.race.kartMap.get(sourceId, None), None) if targetId != 0: self.targetKart = base.cr.doId2do.get(base.race.kartMap.get(targetId, None), None) @@ -66,7 +66,7 @@ def __init__(self, sourceId, targetId, type, name): self.reparentTo(render) def delete(self): - print 'removing piejectile' + print('removing piejectile') taskMgr.remove(self.taskName) self.__undoCollisions() self.physicsMgr.clearLinearForces() @@ -186,7 +186,7 @@ def __updatePhysics(self, task): self.engine.setVector(Vec3(0, 10 + 10 * self.timeRatio + targetSpeed * (0.5 + 0.5 * self.timeRatio) + self.d2t * (0.5 + 0.5 * self.timeRatio), 12)) else: self.engine.setVector(Vec3(0, 100, 3)) - for i in xrange(int(numFrames)): + for i in range(int(numFrames)): pitch = self.gagNode.getP() self.gagNode.setP(pitch + self.rotH * self.physicsDt) roll = self.gagNode.getR() diff --git a/toontown/racing/RaceEndPanels.py b/toontown/racing/RaceEndPanels.py index 9007d0e1d..3dfc00a7c 100644 --- a/toontown/racing/RaceEndPanels.py +++ b/toontown/racing/RaceEndPanels.py @@ -31,10 +31,10 @@ def __init__(self, numRacers, race, raceEndPanel, *args, **kwargs): self.pointsLabel = DirectLabel(parent=self, relief=None, pos=(0.7, 0, 0.3), text=TTLocalizer.KartRace_CircuitPoints, text_fg=(0.0, 0.0, 0.0, 1.0), text_scale=TTLocalizer.REPsmallLabel) self.pointsLabel.hide() self.rowFrame = [] - for x in xrange(self.numRacers): + for x in range(self.numRacers): frame = DirectFrame(parent=self, relief=None, pos=self.getRowPos(x)) self.rowFrame.append(frame) - pLabel = DirectLabel(parent=frame, relief=None, pos=(0.0, 0.0, -0.01), text=`(x + 1)` + ' -', text_fg=(0.5, 0.5, 0.5, 1.0), text_scale=TTLocalizer.REPlargeLabel, text_align=TextNode.ARight, text_font=DGG.getDefaultFont()) + pLabel = DirectLabel(parent=frame, relief=None, pos=(0.0, 0.0, -0.01), text=repr((x + 1)) + ' -', text_fg=(0.5, 0.5, 0.5, 1.0), text_scale=TTLocalizer.REPlargeLabel, text_align=TextNode.ARight, text_font=DGG.getDefaultFont()) fFrame = DirectFrame(parent=frame, relief=None, pos=(0.1, -0.01, 0.01)) nLabel = DirectLabel(parent=frame, relief=None, pos=(0.46, 0.0, 0.0), text='', text_fg=(0.0, 0.0, 0.0, 1.0), text_scale=TTLocalizer.REPsmallLabel, text_align=TextNode.ACenter, text_font=DGG.getDefaultFont()) tLabel = DirectLabel(parent=frame, relief=None, pos=(0.9, 0.0, 0.0), text="--'--''--", text_fg=(0.5, 0.5, 0.5, 1.0), text_scale=TTLocalizer.REPsmallLabel, text_font=DGG.getDefaultFont()) @@ -98,7 +98,7 @@ def flipText(flip, label = self.entryList[place - 1][3], timeStr = timeStr, recS bonusSeq = Sequence() if qualify and bonus: qText = TTLocalizer.KartRace_Qualified - for i in xrange(1, 7): + for i in range(1, 7): bonusSeq.append(Func(flipText, 0, recStr=qText)) bonusSeq.append(Wait(0.5)) bonusSeq.append(Func(flipText, 1)) @@ -110,12 +110,12 @@ def flipText(flip, label = self.entryList[place - 1][3], timeStr = timeStr, recS elif qualify: qText = TTLocalizer.KartRace_Qualified - for i in xrange(0, 12): + for i in range(0, 12): bonusSeq.append(Func(flipText, i % 2, recStr=qText)) bonusSeq.append(Wait(0.5)) elif bonus: - for i in xrange(0, 12): + for i in range(0, 12): bonusSeq.append(Func(flipText, i % 2)) bonusSeq.append(Wait(0.5)) @@ -284,7 +284,7 @@ def wrapStr(str = '', maxWidth = 10, font = DGG.getDefaultFont()): bonusType = None if ticBonus > 0: if not endOfCircuitRace: - bonusType = RaceGlobals.PeriodDict.values().index(ticBonus) + bonusType = list(RaceGlobals.PeriodDict.values()).index(ticBonus) else: ticBonus = 0 if endOfCircuitRace: @@ -374,7 +374,7 @@ def updateWinnings(self, place, winnings): self.results.updateWinnings(place, winnings) def updateWinningsFromCircuit(self, place, entryFee, winnings, bonus, trophies = ()): - print 'updateWinningsFromCircuit' + print('updateWinningsFromCircuit') self.seq.finish() totalTickets = winnings + entryFee + bonus self.results.updateWinnings(place, totalTickets) diff --git a/toontown/racing/RaceGUI.py b/toontown/racing/RaceGUI.py index 05b8a3ec8..fa048819f 100644 --- a/toontown/racing/RaceGUI.py +++ b/toontown/racing/RaceGUI.py @@ -118,7 +118,7 @@ def initRaceMode(self): ls = LineSegs('MapLines') ls.setColor(1, 1, 1, 1) ls.setThickness(2) - for x in xrange(101): + for x in range(101): self.race.curve.getPoint(x / 100.0 * maxT, pt) if x == 0: ls.moveTo(pt[0], pt[1], pt[2]) @@ -149,7 +149,7 @@ def initRaceMode(self): self.wrongWaySeq = Sequence(self.wrongWayLabel.colorScaleInterval(0.25, colorScale=Vec4(1, 1, 1, 1), startColorScale=Vec4(1, 1, 1, 0)), self.wrongWayLabel.colorScaleInterval(0.25, colorScale=Vec4(1, 1, 1, 0), startColorScale=Vec4(1, 1, 1, 1))) interpolateFacePos = lambda x: self.faceStartPos * (1.0 - x) + self.faceEndPos * x self.timeLabels = [] - for x in xrange(self.race.lapCount): + for x in range(self.race.lapCount): minLabel = DirectLabel(relief=None, pos=(interpolateFacePos((2.0 * x + 1) / (self.race.lapCount * 2))[0] - 0.06, 0, 0.84), text="0'", text_scale=0.06, text_fg=(0.95, 0.95, 0, 1), text_font=ToontownGlobals.getSignFont(), text_align=TextNode.ARight) minLabel.reparentTo(self.raceModeRoot) self.directObjList.append(minLabel) @@ -180,7 +180,7 @@ def initRaceMode(self): line.setScale(self.faceEndPos[0] - self.faceStartPos[0], 1, 0.01) line.setPos(0, 0, self.faceStartPos[2]) self.cardMaker.setName('RaceProgressLineHash') - for n in xrange(self.race.lapCount + 1): + for n in range(self.race.lapCount + 1): hash = self.raceModeRoot.attachNewNode(self.cardMaker.generate()) hash.setScale(line.getScale()[2], 1, line.getScale()[2] * 5) t = float(n) / self.race.lapCount @@ -222,7 +222,7 @@ def updateGag(self, gagIndex): def waitingOnGag(self, cycleTime): if self.gag: numTextures = len(self.gagTextures) - startOffset = random.choice(range(0, numTextures)) + startOffset = random.choice(list(range(0, numTextures))) self.gag.show() self.gagCycleInterval = Parallel(LerpFunc(self.showNextGag, fromData=startOffset, toData=numTextures * 2 * cycleTime + startOffset, blendType='easeOut', duration=cycleTime), LerpHprInterval(self.gag, duration=cycleTime, hpr=Point3(0, 180 * numTextures * 2 * cycleTime - 90, 0), blendType='easeOut', startHpr=Point3(0, 0, 0)), SoundInterval(self.gagCycleSound, loop=1, duration=cycleTime, startTime=0), name='gagCycleInterval') self.gagCycleInterval.start() @@ -264,7 +264,7 @@ def enableRaceMode(self): self.render2dRoot.show() self.raceModeRoot.show() self.maxLapHit = min(self.maxLapHit, self.race.lapCount - 1) - for x in xrange(self.maxLapHit + 1): + for x in range(self.maxLapHit + 1): for y in self.timeLabels[x]: y.configure(text_font=ToontownGlobals.getSignFont()) y.show() @@ -321,7 +321,7 @@ def setSpotLapLinear(self, t, spot): def update(self, time): placeSorter = [] placeCount = 0 - for key in self.racerDict.keys(): + for key in list(self.racerDict.keys()): racer = self.racerDict[key] curvetime = racer.curvetime face = racer.face @@ -368,13 +368,13 @@ def update(self, time): 3: TTLocalizer.KartRace_ThirdSuffix, 4: TTLocalizer.KartRace_FourthSuffix} placeSorter.sort() - for x, p in zip(placeSorter, xrange(len(placeSorter), 0, -1)): + for x, p in zip(placeSorter, range(len(placeSorter), 0, -1)): self.racerDict[x[1]].update(place=p + placeCount - len(placeSorter)) localRacer = self.racerDict[localAvatar.doId] nearDiff, farDiff = RaceGlobals.TrackDict[self.race.trackId][8] if not localRacer.finished and self.faceEndPos[0] - localRacer.face.getX() < nearDiff: - for racerId in self.racerDict.keys(): + for racerId in list(self.racerDict.keys()): racer = self.racerDict[racerId] if not racer.enabled or racerId == localAvatar.doId or racer.face.getX() >= self.faceEndPos[0]: continue @@ -406,7 +406,7 @@ def update(self, time): self.wrongWaySeq.finish() def updateRacerInfo(self, avId, curvetime = None, maxlaphit = None): - if avId in self.racerDict.keys(): + if avId in list(self.racerDict.keys()): self.racerDict[avId].update(curvetime=curvetime, maxlaphit=maxlaphit) def racerEntered(self, avId): @@ -433,7 +433,7 @@ def racerEntered(self, avId): mapspot.reparentTo(self.mapLines) mapspot.setHpr(self.mapScene, 0, 0, 0) self.racerDict[avId] = self.RacerInfo(headframe, mapspot) - for key, i in zip(self.racerDict.keys(), range(len(self.racerDict.keys()))): + for key, i in zip(list(self.racerDict.keys()), list(range(len(list(self.racerDict.keys()))))): face = self.racerDict[key].face mapspot = self.racerDict[key].mapspot face.setX(self.faceStartPos[0]) diff --git a/toontown/racing/RaceGlobals.py b/toontown/racing/RaceGlobals.py index d357fbb7d..ffede378d 100644 --- a/toontown/racing/RaceGlobals.py +++ b/toontown/racing/RaceGlobals.py @@ -356,7 +356,7 @@ def getNextRaceInfo(prevTrackId, genreString, padId): 1.0, 'GS_Race_CC.ogg', (0.002, 0.003))} -TrackIds = TrackDict.keys() +TrackIds = list(TrackDict.keys()) TrackIds.sort() def getEntryFee(trackId, raceType): @@ -382,7 +382,7 @@ def getDefaultRecordTime(trackId): PeriodDict = {Daily: 10, Weekly: 100, AllTime: 1000} -PeriodIds = PeriodDict.keys() +PeriodIds = list(PeriodDict.keys()) NumRecordPeriods = len(PeriodIds) NumRecordsPerPeriod = 10 Winnings = [4.0, @@ -539,7 +539,7 @@ def getCircuitLoop(startingTrack): circuitLoop = [startingTrack] for loop in CircuitLoops: if startingTrack in loop: - print loop + print(loop) numTracks = len(loop) tempLoop = loop * 2 startingIndex = tempLoop.index(startingTrack) diff --git a/toontown/racing/RaceHeadFrame.py b/toontown/racing/RaceHeadFrame.py index 060448e15..040fd6c92 100644 --- a/toontown/racing/RaceHeadFrame.py +++ b/toontown/racing/RaceHeadFrame.py @@ -13,7 +13,7 @@ def __init__(self, av = None, color = Vec4(1, 1, 1, 1), *args, **kwargs): 'geom_scale': (1, 1, 0.5), 'pos': (0, 0, 0)} opts.update(kwargs) - apply(DirectFrame.__init__, (self,) + args, opts) + DirectFrame.__init__(*(self,) + args, **opts) self.initialiseoptions(RaceHeadFrame) if av: self.setAv(av) diff --git a/toontown/rpc/ToontownRPCConnection.py b/toontown/rpc/ToontownRPCConnection.py index 4b9d89924..5ec5a98f0 100644 --- a/toontown/rpc/ToontownRPCConnection.py +++ b/toontown/rpc/ToontownRPCConnection.py @@ -1,7 +1,7 @@ from direct.directnotify.DirectNotifyGlobal import directNotify from direct.stdpy import threading from direct.stdpy import threading2 -import httplib +import http.client import json import socket import time @@ -203,7 +203,7 @@ def writeHTTPResponse(self, body, contentType=None, code=200): """ Write an HTTP response to the socket. """ - response = 'HTTP/1.1 %d %s\r\n' % (code, httplib.responses.get(code)) + response = 'HTTP/1.1 %d %s\r\n' % (code, http.client.responses.get(code)) # Add the standard headers: response += 'Date: %s\r\n' % time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime()) @@ -225,7 +225,7 @@ def writeHTTPError(self, code): Write an HTTP error response to the socket. """ self.notify.warning('Received a bad HTTP request: ' + str(code)) - body = '%d %s' % (code, httplib.responses.get(code)) + body = '%d %s' % (code, http.client.responses.get(code)) self.writeHTTPResponse(body, contentType='text/plain', code=code) def writeJSONResponse(self, response, id=None): diff --git a/toontown/rpc/ToontownRPCDispatcher.py b/toontown/rpc/ToontownRPCDispatcher.py index 383590f8c..dde92056e 100644 --- a/toontown/rpc/ToontownRPCDispatcher.py +++ b/toontown/rpc/ToontownRPCDispatcher.py @@ -12,7 +12,7 @@ def dispatch(self, request): """ Handle a JSON-RPC 2.0 request. """ - if (not isinstance(request.method, basestring)) or \ + if (not isinstance(request.method, str)) or \ (not isinstance(request.params, (tuple, list, dict))): request.error(-32600, 'Invalid Request') return @@ -32,7 +32,7 @@ def dispatch(self, request): elif len(request.params) > 0: token = request.params[0] params = request.params[1:] - if not isinstance(token, basestring): + if not isinstance(token, str): request.error(-32000, 'No token provided') return error = self.handler.authenticate(token, method) diff --git a/toontown/rpc/ToontownRPCHandler.py b/toontown/rpc/ToontownRPCHandler.py index f16e32040..f5507165b 100644 --- a/toontown/rpc/ToontownRPCHandler.py +++ b/toontown/rpc/ToontownRPCHandler.py @@ -235,7 +235,7 @@ def rpc_messageAccount(self, accountId, message): [int accountId] = The ID of the account to send the message to. [str message] = The message to send. """ - channel = accountId + (1003L<<32) + channel = accountId + (1003<<32) self.rpc_messageChannel(channel, message) @rpcmethod(accessLevel=MODERATOR) @@ -249,7 +249,7 @@ def rpc_messageAvatar(self, avId, message): [int avId] = The ID of the avatar to send the message to. [str message] = The message to send. """ - channel = avId + (1001L<<32) + channel = avId + (1001<<32) self.rpc_messageChannel(channel, message) # --- KICKS --- @@ -325,7 +325,7 @@ def rpc_kickAccount(self, accountId, code, reason): [int code] = The code for the kick. [str reason] = The reason for the kick. """ - channel = accountId + (1003L<<32) + channel = accountId + (1003<<32) self.rpc_kickChannel(channel, code, reason) @rpcmethod(accessLevel=MODERATOR) @@ -338,7 +338,7 @@ def rpc_kickAvatar(self, avId, code, reason): [int code] = The code for the kick. [str reason] = The reason for the kick. """ - channel = avId + (1001L<<32) + channel = avId + (1001<<32) self.rpc_kickChannel(channel, code, reason) # --- BANS --- diff --git a/toontown/rpc/ToontownRPCServer.py b/toontown/rpc/ToontownRPCServer.py index 8f38a49f9..fa2d5631c 100644 --- a/toontown/rpc/ToontownRPCServer.py +++ b/toontown/rpc/ToontownRPCServer.py @@ -4,7 +4,7 @@ from panda3d.core import TP_normal import select import socket -import urlparse +import urllib.parse from toontown.rpc.ToontownRPCConnection import ToontownRPCConnection @@ -16,7 +16,7 @@ def __init__(self, endpoint, handler): self.handler = handler # Parse the endpoint: - url = urlparse.urlparse(endpoint) + url = urllib.parse.urlparse(endpoint) # We only support the http scheme: if url.scheme != 'http': @@ -67,7 +67,7 @@ def stop(self): taskMgr.remove(taskName) # Close any open connections: - for k, v in self.connections.items(): + for k, v in list(self.connections.items()): v.close() del self.connections[k] @@ -95,7 +95,7 @@ def pollOnce(self): Poll for incoming data once. """ try: - rlist = select.select([self.listenerSocket] + self.connections.keys(), [], [])[0] + rlist = select.select([self.listenerSocket] + list(self.connections.keys()), [], [])[0] except: # It's likely that one or more of our sockets is no longer valid. @@ -107,7 +107,7 @@ def pollOnce(self): # Otherwise, discard the faulty sockets, and wait for the next poll # iteration: - for socket in self.connections.keys(): + for socket in list(self.connections.keys()): try: socket.fileno() socket.getpeername() @@ -144,7 +144,7 @@ def handleNewConnection(self): """ try: conn = self.listenerSocket.accept()[0] - except socket.error, e: + except socket.error as e: if e.args[0] != errno.EWOULDBLOCK: raise e self.connections[conn] = ToontownRPCConnection(conn, self.handler) diff --git a/toontown/safezone/BRSafeZoneLoader.py b/toontown/safezone/BRSafeZoneLoader.py index 1e9dfd398..f4e2c1289 100644 --- a/toontown/safezone/BRSafeZoneLoader.py +++ b/toontown/safezone/BRSafeZoneLoader.py @@ -14,9 +14,9 @@ def __init__(self, hood, parentFSM, doneEvent): def load(self): SafeZoneLoader.SafeZoneLoader.load(self) - self.windSound = map(base.loader.loadSfx, ['phase_8/audio/sfx/SZ_TB_wind_1.ogg', + self.windSound = list(map(base.loader.loadSfx, ['phase_8/audio/sfx/SZ_TB_wind_1.ogg', 'phase_8/audio/sfx/SZ_TB_wind_2.ogg', - 'phase_8/audio/sfx/SZ_TB_wind_3.ogg']) + 'phase_8/audio/sfx/SZ_TB_wind_3.ogg'])) self.snow = BattleParticles.loadParticleFile('snowdisk.ptf') self.snow.setPos(0, 0, 5) self.snowRender = self.geom.attachNewNode('snowRender') diff --git a/toontown/safezone/ButterflyGlobals.py b/toontown/safezone/ButterflyGlobals.py index c6dd941ed..680c44e2f 100644 --- a/toontown/safezone/ButterflyGlobals.py +++ b/toontown/safezone/ButterflyGlobals.py @@ -190,7 +190,7 @@ def generateIndexes(doId, playground): usedI = [] unusedI = [] for area in ButterflyPoints[playground]: - usedI.append(range(0, len(area))) + usedI.append(list(range(0, len(area)))) unusedI.append([]) allocatedIndexes[doId] = (usedI, unusedI) diff --git a/toontown/safezone/CheckersBoard.py b/toontown/safezone/CheckersBoard.py index 7d46aeee8..15b1ed86d 100644 --- a/toontown/safezone/CheckersBoard.py +++ b/toontown/safezone/CheckersBoard.py @@ -4,7 +4,7 @@ class CheckersBoard: def __init__(self): self.squareList = [] - for x in xrange(32): + for x in range(32): self.squareList.append(CheckersTile(x)) self.squareList[0].setAdjacent([None, @@ -285,14 +285,14 @@ def getAdjacent(self, squareNum): def getStates(self): retList = [] - for x in xrange(32): + for x in range(32): retList.append(self.squareList[x].getState()) return retList def setStates(self, squares): y = 0 - for x in xrange(32): + for x in range(32): self.squareList[x].setState(squares[x]) def getJumps(self, squareNum): diff --git a/toontown/safezone/ChineseCheckersBoard.py b/toontown/safezone/ChineseCheckersBoard.py index afc140870..a0a1f5d19 100644 --- a/toontown/safezone/ChineseCheckersBoard.py +++ b/toontown/safezone/ChineseCheckersBoard.py @@ -4,7 +4,7 @@ class ChineseCheckersBoard: def __init__(self): self.squareList = [] - for x in xrange(121): + for x in range(121): self.squareList.append(CheckersSquare(x)) self.squareList[0].setAdjacent([None, @@ -767,14 +767,14 @@ def getAdjacentOffset(self, squareNum): def getStates(self): retList = [] - for x in xrange(121): + for x in range(121): retList.append(self.squareList[x].getState()) return retList def setStates(self, squares): y = 0 - for x in xrange(121): + for x in range(121): self.squareList[x].setState(squares[x]) diff --git a/toontown/safezone/DGSafeZoneLoader.py b/toontown/safezone/DGSafeZoneLoader.py index e6acfee81..4de301f80 100644 --- a/toontown/safezone/DGSafeZoneLoader.py +++ b/toontown/safezone/DGSafeZoneLoader.py @@ -13,10 +13,10 @@ def __init__(self, hood, parentFSM, doneEvent): def load(self): SafeZoneLoader.SafeZoneLoader.load(self) - self.birdSound = map(base.loader.loadSfx, ['phase_8/audio/sfx/SZ_DG_bird_01.ogg', + self.birdSound = list(map(base.loader.loadSfx, ['phase_8/audio/sfx/SZ_DG_bird_01.ogg', 'phase_8/audio/sfx/SZ_DG_bird_02.ogg', 'phase_8/audio/sfx/SZ_DG_bird_03.ogg', - 'phase_8/audio/sfx/SZ_DG_bird_04.ogg']) + 'phase_8/audio/sfx/SZ_DG_bird_04.ogg'])) def unload(self): SafeZoneLoader.SafeZoneLoader.unload(self) diff --git a/toontown/safezone/DistributedCheckers.py b/toontown/safezone/DistributedCheckers.py index 6282b1491..e5b384264 100644 --- a/toontown/safezone/DistributedCheckers.py +++ b/toontown/safezone/DistributedCheckers.py @@ -95,7 +95,7 @@ def __init__(self, cr): x = self.boardNode.find('**/locator*') self.locatorList = x.getChildren() tempList = [] - for x in xrange(0, 32): + for x in range(0, 32): self.locatorList[x].setTag('GamePeiceLocator', '%d' % x) tempList.append(self.locatorList[x].attachNewNode(CollisionNode('picker%d' % x))) tempList[x].node().addSolid(CollisionSphere(0, 0, 0, 0.39)) @@ -449,7 +449,7 @@ def handleClicked(self, index): def existsLegalJumpsFrom(self, index, peice): if peice == 'king': - for x in xrange(4): + for x in range(4): if self.board.squareList[index].getAdjacent()[x] != None and \ self.board.squareList[index].getJumps()[x] != None: adj = self.board.squareList[self.board.squareList[index].getAdjacent()[x]] @@ -511,7 +511,7 @@ def checkLegalMove(self, firstSquare, secondSquare, peice): else: moveForward = [0, 3] if peice == 'king': - for x in xrange(4): + for x in range(4): if firstSquare.getAdjacent()[x] != None: if self.board.squareList[firstSquare.getAdjacent()[x]].getState() == 0 and secondSquare.getNum() in firstSquare.getAdjacent(): return True @@ -581,7 +581,7 @@ def updateGameState(self, squares): self.playerNum = 1 self.playerColorString = 'white' isObserve = True - for xx in xrange(32): + for xx in range(32): for blah in self.locatorList[xx].getChildren(): blah.hide() if self.locatorList[xx].getChildren().index(blah) != 0: @@ -669,7 +669,7 @@ def updateGameState(self, squares): return def hideChildren(self, nodeList): - for x in xrange(1, 2): + for x in range(1, 2): nodeList[x].hide() def animatePeice(self, tableState, moveList, type, playerColor): @@ -691,7 +691,7 @@ def animatePeice(self, tableState, moveList, type, playerColor): checkersPeiceTrack = Sequence() length = len(moveList) - for x in xrange(length - 1): + for x in range(length - 1): checkersPeiceTrack.append(Parallel(SoundInterval(self.moveSound), ProjectileInterval(gamePeiceForAnimation, endPos=self.locatorList[moveList[x + 1]].getPos(), duration=0.5))) checkersPeiceTrack.append(Func(gamePeiceForAnimation.removeNode)) diff --git a/toontown/safezone/DistributedChineseCheckers.py b/toontown/safezone/DistributedChineseCheckers.py index 143305f07..042fdf8f9 100644 --- a/toontown/safezone/DistributedChineseCheckers.py +++ b/toontown/safezone/DistributedChineseCheckers.py @@ -143,7 +143,7 @@ def __init__(self, cr): x = self.boardNode.find('**/locators') self.locatorList = x.getChildren() tempList = [] - for x in xrange(0, 121): + for x in range(0, 121): self.locatorList[x].setTag('GamePeiceLocator', '%d' % x) tempList.append(self.locatorList[x].attachNewNode(CollisionNode('picker%d' % x))) tempList[x].node().addSolid(CollisionSphere(0, 0, 0, 0.115)) @@ -297,7 +297,7 @@ def sendTurn(self, playersTurn): def announceSeatPositions(self, playerPos): self.playerSeats = playerPos - for x in xrange(6): + for x in range(6): pos = self.table.seats[x].getPos(render) renderedPeice = loader.loadModel('phase_6/models/golf/checker_marble.bam') renderedPeice.reparentTo(self.playerTags) @@ -638,7 +638,7 @@ def updateGameState(self, squares): self.board.setStates(squares) self.mySquares = [] messenger.send('wakeup') - for x in xrange(121): + for x in range(121): self.locatorList[x].clearColor() owner = self.board.squareList[x].getState() if owner == self.playerNum: @@ -672,7 +672,7 @@ def animatePeice(self, tableState, moveList): self.locatorList[moveList[0]].hide() checkersPeiceTrack = Sequence() length = len(moveList) - for x in xrange(length - 1): + for x in range(length - 1): checkersPeiceTrack.append(Parallel(SoundInterval(self.moveSound), ProjectileInterval(gamePeiceForAnimation, endPos=self.locatorList[moveList[x + 1]].getPos(), duration=0.5))) checkersPeiceTrack.append(Func(gamePeiceForAnimation.removeNode)) diff --git a/toontown/safezone/DistributedFindFour.py b/toontown/safezone/DistributedFindFour.py index 80f52e2f8..ff758efd2 100644 --- a/toontown/safezone/DistributedFindFour.py +++ b/toontown/safezone/DistributedFindFour.py @@ -122,7 +122,7 @@ def __init__(self, cr): self.startingPositions = self.startingPositions.getChildren() instancePiece = self.boardNode.find('**/pieces') tempList = [] - for x in xrange(7): + for x in range(7): self.startingPositions[x].setTag('StartLocator', '%d' % x) collNode = CollisionNode('startpicker%d' % x) collNode.setIntoCollideMask(BitMask32(4096)) @@ -135,7 +135,7 @@ def __init__(self, cr): val.hide() tempList = [] - for x in xrange(42): + for x in range(42): self.locatorList[x].setTag('GamePeiceLocator', '%d' % x) collNode = CollisionNode('startpicker%d' % x) collNode.setIntoCollideMask(BitMask32(4096)) @@ -464,27 +464,27 @@ def setGameState(self, tableState, moveCol, movePos, turn): messenger.send('wakeup') if self.table.fsm.getCurrentState().getName() == 'observing': isBlank = True - for x in xrange(7): + for x in range(7): if self.board[5][x] != 0: isBlank = False break gameBlank = True - for x in xrange(7): + for x in range(7): if tableState[5][x] != 0: gameBlank = False break if isBlank == True and gameBlank == False: - for x in xrange(6): - for y in xrange(7): + for x in range(6): + for y in range(7): self.board[x][y] = tableState[x][y] self.updateGameState() return if moveCol == 0 and movePos == 0 and turn == 0: - for x in xrange(6): - for y in xrange(7): + for x in range(6): + for y in range(7): self.board[x][y] = tableState[x][y] self.updateGameState() @@ -496,13 +496,13 @@ def setGameState(self, tableState, moveCol, movePos, turn): return def updateGameState(self): - for x in xrange(6): - for y in xrange(7): + for x in range(6): + for y in range(7): for z in self.locatorList[x * 7 + y].getChild(1).getChildren(): z.hide() - for x in xrange(6): - for y in xrange(7): + for x in range(6): + for y in range(7): state = self.board[x][y] if state == 1: self.locatorList[x * 7 + y].getChild(1).getChild(0).show() @@ -510,8 +510,8 @@ def updateGameState(self): self.locatorList[x * 7 + y].getChild(1).getChild(1).show() def checkForWin(self): - for x in xrange(6): - for y in xrange(7): + for x in range(6): + for y in range(7): if self.board[x][y] == self.playerNum: if self.checkHorizontal(x, y, self.playerNum) == True: return [x, y] @@ -535,7 +535,7 @@ def announceWinnerPosition(self, x, y, winDirection, playerNum): elif winDirection == 2: blinkList = self.findDiagonal(x, y, playerNum) if blinkList != []: - print blinkList + print(blinkList) val0 = x * 7 + y x = blinkList[0][0] y = blinkList[0][1] @@ -561,7 +561,7 @@ def tie(self): self.moveSequence.finish() if self.turnText: self.turnText.hide() - for x in xrange(41): + for x in range(41): self.tieSequence.append(Parallel(LerpColorInterval(self.locatorList[x], 0.15, Vec4(0.5, 0.5, 0.5, 0.5), Vec4(1, 1, 1, 1)), LerpColorInterval(self.locatorList[x], 0.15, Vec4(1, 1, 1, 1), Vec4(0.5, 0.5, 0.5, 0.5)))) whisper = WhisperPopup('This Find Four game has resulted in a Tie!', OTPGlobals.getInterfaceFont(), WTNormal) @@ -573,8 +573,8 @@ def hideChildren(self, nodeList): def animatePeice(self, tableState, moveCol, movePos, turn): messenger.send('wakeup') - for x in xrange(6): - for y in xrange(7): + for x in range(6): + for y in range(7): self.board[x][y] = tableState[x][y] pos = self.startingPositions[moveCol].getPos() @@ -621,13 +621,13 @@ def doNothing(self): def checkHorizontal(self, rVal, cVal, playerNum): if cVal == 3: - for x in xrange(1, 4): + for x in range(1, 4): if self.board[rVal][cVal - x] != playerNum: break if self.board[rVal][cVal - x] == playerNum and x == 3: return True - for x in xrange(1, 4): + for x in range(1, 4): if self.board[rVal][cVal + x] != playerNum: break if self.board[rVal][cVal + x] == playerNum and x == 3: @@ -635,7 +635,7 @@ def checkHorizontal(self, rVal, cVal, playerNum): return False elif cVal == 2: - for x in xrange(1, 4): + for x in range(1, 4): if self.board[rVal][cVal + x] != playerNum: break if self.board[rVal][cVal + x] == playerNum and x == 3: @@ -643,7 +643,7 @@ def checkHorizontal(self, rVal, cVal, playerNum): return False elif cVal == 4: - for x in xrange(1, 4): + for x in range(1, 4): if self.board[rVal][cVal - x] != playerNum: break if self.board[rVal][cVal - x] == playerNum and x == 3: @@ -655,7 +655,7 @@ def checkHorizontal(self, rVal, cVal, playerNum): def checkVertical(self, rVal, cVal, playerNum): if rVal == 2: - for x in xrange(1, 4): + for x in range(1, 4): if self.board[rVal + x][cVal] != playerNum: break if self.board[rVal + x][cVal] == playerNum and x == 3: @@ -663,7 +663,7 @@ def checkVertical(self, rVal, cVal, playerNum): return False elif rVal == 3: - for x in xrange(1, 4): + for x in range(1, 4): if self.board[rVal - x][cVal] != playerNum: break if self.board[rVal - x][cVal] == playerNum and x == 3: @@ -676,7 +676,7 @@ def checkVertical(self, rVal, cVal, playerNum): def checkDiagonal(self, rVal, cVal, playerNum): if cVal <= 2: if rVal == 2: - for x in xrange(1, 4): + for x in range(1, 4): if self.board[rVal + x][cVal + x] != playerNum: break if self.board[rVal + x][cVal + x] == playerNum and x == 3: @@ -684,7 +684,7 @@ def checkDiagonal(self, rVal, cVal, playerNum): return False elif rVal == 3: - for x in xrange(1, 4): + for x in range(1, 4): if self.board[rVal - x][cVal + x] != playerNum: break if self.board[rVal - x][cVal + x] == playerNum and x == 3: @@ -693,7 +693,7 @@ def checkDiagonal(self, rVal, cVal, playerNum): return False elif cVal >= 4: if rVal == 2: - for x in xrange(1, 4): + for x in range(1, 4): if self.board[rVal + x][cVal - x] != playerNum: break if self.board[rVal + x][cVal - x] == playerNum and x == 3: @@ -701,7 +701,7 @@ def checkDiagonal(self, rVal, cVal, playerNum): return False elif rVal == 3: - for x in xrange(1, 4): + for x in range(1, 4): if self.board[rVal - x][cVal - x] != playerNum: break if self.board[rVal - x][cVal - x] == playerNum and x == 3: @@ -709,13 +709,13 @@ def checkDiagonal(self, rVal, cVal, playerNum): return False elif rVal == 3 or rVal == 4 or rVal == 5: - for x in xrange(1, 4): + for x in range(1, 4): if self.board[rVal - x][cVal - x] != playerNum: break if self.board[rVal - x][cVal - x] == playerNum and x == 3: return True - for x in xrange(1, 4): + for x in range(1, 4): if self.board[rVal - x][cVal - x] != playerNum: break if self.board[rVal - x][cVal - x] == playerNum and x == 3: @@ -723,13 +723,13 @@ def checkDiagonal(self, rVal, cVal, playerNum): return False elif rVal == 0 or rVal == 1 or rVal == 2: - for x in xrange(1, 4): + for x in range(1, 4): if self.board[rVal + x][cVal - x] != playerNum: break if self.board[rVal + x][cVal - x] == playerNum and x == 3: return True - for x in xrange(1, 4): + for x in range(1, 4): if self.board[rVal + x][cVal + x] != playerNum: break if self.board[rVal + x][cVal + x] == playerNum and x == 3: @@ -741,7 +741,7 @@ def checkDiagonal(self, rVal, cVal, playerNum): def findHorizontal(self, rVal, cVal, playerNum): if cVal == 3: retList = [] - for x in xrange(1, 4): + for x in range(1, 4): retList.append([rVal, cVal - x]) if self.board[rVal][cVal - x] != playerNum: retList = [] @@ -749,7 +749,7 @@ def findHorizontal(self, rVal, cVal, playerNum): if self.board[rVal][cVal - x] == playerNum and x == 3: return retList - for x in xrange(1, 4): + for x in range(1, 4): retList.append([rVal, cVal + x]) if self.board[rVal][cVal + x] != playerNum: retList = [] @@ -760,7 +760,7 @@ def findHorizontal(self, rVal, cVal, playerNum): return [] elif cVal == 2: retList = [] - for x in xrange(1, 4): + for x in range(1, 4): retList.append([rVal, cVal + x]) if self.board[rVal][cVal + x] != playerNum: retList = [] @@ -771,7 +771,7 @@ def findHorizontal(self, rVal, cVal, playerNum): return [] elif cVal == 4: retList = [] - for x in xrange(1, 4): + for x in range(1, 4): retList.append([rVal, cVal - x]) if self.board[rVal][cVal - x] != playerNum: retList = [] @@ -786,7 +786,7 @@ def findHorizontal(self, rVal, cVal, playerNum): def findVertical(self, rVal, cVal, playerNum): if rVal == 2: retList = [] - for x in xrange(1, 4): + for x in range(1, 4): retList.append([rVal + x, cVal]) if self.board[rVal + x][cVal] != playerNum: retList = [] @@ -797,7 +797,7 @@ def findVertical(self, rVal, cVal, playerNum): return [] elif rVal == 3: retList = [] - for x in xrange(1, 4): + for x in range(1, 4): retList.append([rVal - x, cVal]) if self.board[rVal - x][cVal] != playerNum: retList = [] @@ -813,7 +813,7 @@ def findDiagonal(self, rVal, cVal, playerNum): retList = [] if cVal <= 2: if rVal == 2: - for x in xrange(1, 4): + for x in range(1, 4): retList.append([rVal + x, cVal + x]) if self.board[rVal + x][cVal + x] != playerNum: retList = [] @@ -823,7 +823,7 @@ def findDiagonal(self, rVal, cVal, playerNum): return [] elif rVal == 3: - for x in xrange(1, 4): + for x in range(1, 4): retList.append([rVal - x, cVal + x]) if self.board[rVal - x][cVal + x] != playerNum: retList = [] @@ -834,7 +834,7 @@ def findDiagonal(self, rVal, cVal, playerNum): return [] elif cVal >= 4: if rVal == 2: - for x in xrange(1, 4): + for x in range(1, 4): retList.append([rVal + x, cVal - x]) if self.board[rVal + x][cVal - x] != playerNum: retList = [] @@ -844,7 +844,7 @@ def findDiagonal(self, rVal, cVal, playerNum): return [] elif rVal == 3: - for x in xrange(1, 4): + for x in range(1, 4): retList.append([rVal - x, cVal - x]) if self.board[rVal - x][cVal - x] != playerNum: retList = [] @@ -854,7 +854,7 @@ def findDiagonal(self, rVal, cVal, playerNum): return [] elif rVal == 3 or rVal == 4 or rVal == 5: - for x in xrange(1, 4): + for x in range(1, 4): retList.append([rVal - x, cVal - x]) if self.board[rVal - x][cVal - x] != playerNum: retList = [] @@ -862,7 +862,7 @@ def findDiagonal(self, rVal, cVal, playerNum): if self.board[rVal - x][cVal - x] == playerNum and x == 3: return retList - for x in xrange(1, 4): + for x in range(1, 4): retList.append([rVal + x, cVal - x]) if self.board[rVal + x][cVal - x] != playerNum: retList = [] @@ -872,7 +872,7 @@ def findDiagonal(self, rVal, cVal, playerNum): return [] elif rVal == 0 or rVal == 1 or rVal == 2: - for x in xrange(1, 4): + for x in range(1, 4): retList.append([rVal + x, cVal - x]) if self.board[rVal + x][cVal - x] != playerNum: retList = [] @@ -880,7 +880,7 @@ def findDiagonal(self, rVal, cVal, playerNum): if self.board[rVal + x][cVal - x] == playerNum and x == 3: return retList - for x in xrange(1, 4): + for x in range(1, 4): retList.append([rVal + x, cVal + x]) if self.board[rVal + x][cVal + x] != playerNum: retList = [] diff --git a/toontown/safezone/DistributedGameTable.py b/toontown/safezone/DistributedGameTable.py index ed0270b73..b48222b33 100644 --- a/toontown/safezone/DistributedGameTable.py +++ b/toontown/safezone/DistributedGameTable.py @@ -69,7 +69,7 @@ def announceGenerate(self): self.seats = [] self.jumpOffsets = [] self.picnicTableSphereNodes = [] - for i in xrange(self.numSeats): + for i in range(self.numSeats): self.seats.append(self.picnicTable.find('**/*seat' + str(i+1))) self.jumpOffsets.append(self.picnicTable.find('**/*jumpOut' + str(i+1))) cn = CollisionNode('picnicTable_sphere_%d_%d' % (self.doId, i)) @@ -132,16 +132,16 @@ def delete(self): del self.fsm def enableCollisions(self): - for i in xrange(self.numSeats): + for i in range(self.numSeats): event = 'enterpicnicTable_sphere_%d_%d' % (self.doId, i) self.accept(event, self.handleEnterPicnicTableSphere, [i]) self.picnicTableSphereNodes[i].setCollideMask(ToontownGlobals.WallBitmask) self.tableClothSphereNode.setCollideMask(ToontownGlobals.WallBitmask) def disableCollisions(self): - for i in xrange(self.numSeats): + for i in range(self.numSeats): self.ignore('enterpicnicTable_sphere_%d_%d' % (self.doId, i)) - for i in xrange(self.numSeats): + for i in range(self.numSeats): self.picnicTableSphereNodes[i].setCollideMask(BitMask32(0)) self.tableClothSphereNode.setCollideMask(BitMask32(0)) diff --git a/toontown/safezone/DistributedGolfKartAI.py b/toontown/safezone/DistributedGolfKartAI.py index 658a37bab..3b57414a9 100644 --- a/toontown/safezone/DistributedGolfKartAI.py +++ b/toontown/safezone/DistributedGolfKartAI.py @@ -39,12 +39,12 @@ def delete(self): DistributedObjectAI.DistributedObjectAI.delete(self) def findAvailableSeat(self): - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): if self.seats[i] is None: return i def findAvatar(self, avId): - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): if self.seats[i] == avId: return i @@ -167,7 +167,7 @@ def start(self): def enterOff(self): self.accepting = 0 if hasattr(self, 'doId'): - for seatIndex in xrange(4): + for seatIndex in range(4): taskMgr.remove(self.uniqueName('clearEmpty-' + str(seatIndex))) def exitOff(self): @@ -264,7 +264,7 @@ def trolleyLeft(self): numPlayers = self.countFullSeats() avIdList = [] if numPlayers > 0: - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] avIdList.append(avId) self.clearFullNow(seatIndex) diff --git a/toontown/safezone/DistributedPartyGate.py b/toontown/safezone/DistributedPartyGate.py index 410d9c2a4..4752691b1 100644 --- a/toontown/safezone/DistributedPartyGate.py +++ b/toontown/safezone/DistributedPartyGate.py @@ -27,7 +27,7 @@ def __init__(self, cr): def loadClockSounds(self): self.clockSounds = [] - for i in xrange(1, 13): + for i in range(1, 13): if i < 10: si = '0%d' % i else: @@ -169,13 +169,13 @@ def hourChange(self, currentHour): currentHour = 12 self.hourSoundInterval = Parallel() seq1 = Sequence() - for i in xrange(currentHour): + for i in range(currentHour): seq1.append(SoundInterval(self.clockSounds[i])) seq1.append(Wait(0.2)) timeForEachDeformation = seq1.getDuration() / currentHour seq2 = Sequence() - for i in xrange(currentHour): + for i in range(currentHour): seq2.append(self.clockFlat.scaleInterval(timeForEachDeformation / 2.0, Vec3(0.9, 1.0, 1.2), blendType='easeInOut')) seq2.append(self.clockFlat.scaleInterval(timeForEachDeformation / 2.0, Vec3(1.2, 1.0, 0.9), blendType='easeInOut')) diff --git a/toontown/safezone/DistributedPartyGateAI.py b/toontown/safezone/DistributedPartyGateAI.py index d3c8aeda5..08cb0e143 100644 --- a/toontown/safezone/DistributedPartyGateAI.py +++ b/toontown/safezone/DistributedPartyGateAI.py @@ -21,7 +21,7 @@ def getPartyList(self, avId): try: self.sendUpdateToAvatarId(avId, 'listAllPublicParties', [partyManager.getPublicParties()]) except: - print(traceback.format_exc()) + print((traceback.format_exc())) def partyChoiceRequest(self, avId, shardId, zoneId): # Try to get a spot for them in the party diff --git a/toontown/safezone/DistributedPicnicBasket.py b/toontown/safezone/DistributedPicnicBasket.py index 9addf6873..7e3657a2c 100644 --- a/toontown/safezone/DistributedPicnicBasket.py +++ b/toontown/safezone/DistributedPicnicBasket.py @@ -42,7 +42,7 @@ def generate(self): self.fullSeat = [] self.food = [] - for i in xrange(4): + for i in range(4): self.food.append(None) self.fullSeat.append(self.seatState.Empty) @@ -55,13 +55,13 @@ def announceGenerate(self): self.seats = [] self.jumpOffsets = [] self.basket = None - for i in xrange(self.numSeats): + for i in range(self.numSeats): self.seats.append(self.picnicTable.find('**/*seat%d' % (i + 1))) self.jumpOffsets.append(self.picnicTable.find('**/*jumpOut%d' % (i + 1))) self.tablecloth = self.picnicTable.find('**/basket_locator') DistributedObject.DistributedObject.announceGenerate(self) - for i in xrange(self.numSeats): + for i in range(self.numSeats): self.picnicTableSphereNodes.append(self.seats[i].attachNewNode(CollisionNode('picnicTable_sphere_%d_%d' % (self.getDoId(), i)))) self.picnicTableSphereNodes[i].node().addSolid(CollisionSphere(0, 0, 0, 2)) @@ -85,7 +85,7 @@ def disable(self): DistributedObject.DistributedObject.disable(self) self.fsm.request('off') self.clearToonTracks() - for i in xrange(self.numSeats): + for i in range(self.numSeats): del self.picnicTableSphereNodes[0] del self.picnicTableSphereNodes @@ -242,17 +242,17 @@ def rejectBoard(self, avId): self.loader.place.trolley.handleRejectBoard() def __enableCollisions(self): - for i in xrange(self.numSeats): + for i in range(self.numSeats): self.accept('enterpicnicTable_sphere_%d_%d' % (self.getDoId(), i), self.handleEnterPicnicTableSphere, [i]) self.accept('enterPicnicTableOK_%d_%d' % (self.getDoId(), i), self.handleEnterPicnicTable, [i]) self.picnicTableSphereNodes[i].setCollideMask(ToontownGlobals.WallBitmask) def __disableCollisions(self): - for i in xrange(self.numSeats): + for i in range(self.numSeats): self.ignore('enterpicnicTable_sphere_%d_%d' % (self.getDoId(), i)) self.ignore('enterPicnicTableOK_%d_%d' % (self.getDoId(), i)) - for i in xrange(self.numSeats): + for i in range(self.numSeats): self.picnicTableSphereNodes[i].setCollideMask(BitMask32(0)) def enterOff(self): diff --git a/toontown/safezone/DistributedPicnicBasketAI.py b/toontown/safezone/DistributedPicnicBasketAI.py index 3a7e30bee..63e7fb998 100644 --- a/toontown/safezone/DistributedPicnicBasketAI.py +++ b/toontown/safezone/DistributedPicnicBasketAI.py @@ -42,12 +42,12 @@ def delete(self): DistributedObjectAI.DistributedObjectAI.delete(self) def findAvailableSeat(self): - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): if self.seats[i] is None: return i def findAvatar(self, avId): - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): if self.seats[i] == avId: return i @@ -179,7 +179,7 @@ def start(self): def enterOff(self): self.accepting = 0 if hasattr(self, 'doId'): - for seatIndex in xrange(4): + for seatIndex in range(4): taskMgr.remove(self.uniqueName('clearEmpty-' + str(seatIndex))) def exitOff(self): @@ -215,7 +215,7 @@ def enterWaitCountdown(self): def timeToGoTask(self, task): self.accepting = 0 if self.countFullSeats() > 0: - for x in xrange(len(self.seats)): + for x in range(len(self.seats)): if not self.seats[x] == None: self.sendUpdateToAvatarId(self.seats[x], 'setPicnicDone', []) self.acceptExiter(self.seats[x]) diff --git a/toontown/safezone/DistributedPicnicTable.py b/toontown/safezone/DistributedPicnicTable.py index 41b1aca17..fddf0682c 100644 --- a/toontown/safezone/DistributedPicnicTable.py +++ b/toontown/safezone/DistributedPicnicTable.py @@ -67,7 +67,7 @@ def __init__(self, cr): State.State('sitting', self.enterSitting, self.exitSitting, ['off']), State.State('observing', self.enterObserving, self.exitObserving, ['off'])], 'off', 'off') self.fsm.enterInitialState() - for i in xrange(self.numSeats): + for i in range(self.numSeats): self.seats.append(self.picnicTable.find('**/*seat%d' % (i + 1))) self.jumpOffsets.append(self.picnicTable.find('**/*jumpOut%d' % (i + 1))) @@ -81,7 +81,7 @@ def __init__(self, cr): def announceGenerate(self): DistributedNode.DistributedNode.announceGenerate(self) - for i in xrange(self.numSeats): + for i in range(self.numSeats): self.picnicTableSphereNodes.append(self.seats[i].attachNewNode(CollisionNode('picnicTable_sphere_%d_%d' % (self.getDoId(), i)))) self.picnicTableSphereNodes[i].node().addSolid(CollisionSphere(0, 0, 0, 2)) @@ -171,7 +171,7 @@ def requestTableState(self): def setTableState(self, tableStateList, isplaying): y = 0 - print 'SET TABLE STATE' + print('SET TABLE STATE') if isplaying == 0: self.isPlaying = False else: @@ -206,10 +206,10 @@ def setTableState(self, tableStateList, isplaying): if x != None: numPlayers += 1 - print ' GETTING 2', self.gameMenu, numPlayers + print(' GETTING 2', self.gameMenu, numPlayers) if self.gameMenu: if numPlayers > 2: - print ' GETTING HERE!!' + print(' GETTING HERE!!') self.gameMenu.FindFour.setColor(0.7, 0.7, 0.7, 0.7) self.gameMenu.FindFour['command'] = self.doNothing self.gameMenu.findFourText['fg'] = (0.7, 0.7, 0.7, 0.7) @@ -467,18 +467,18 @@ def moveCameraBack(self): self.cameraBoardTrack.start() def __enableCollisions(self): - for i in xrange(self.numSeats): + for i in range(self.numSeats): self.accept('enterpicnicTable_sphere_%d_%d' % (self.getDoId(), i), self.handleEnterPicnicTableSphere, [i]) self.picnicTableSphereNodes[i].setCollideMask(ToontownGlobals.WallBitmask) self.tableclothSphereNode.setCollideMask(ToontownGlobals.WallBitmask) def __disableCollisions(self): - for i in xrange(self.numSeats): + for i in range(self.numSeats): self.ignore('enterpicnicTable_sphere_%d_%d' % (self.getDoId(), i)) self.ignore('enterPicnicTableOK_%d_%d' % (self.getDoId(), i)) - for i in xrange(self.numSeats): + for i in range(self.numSeats): self.picnicTableSphereNodes[i].setCollideMask(BitMask32(0)) self.tableclothSphereNode.setCollideMask(BitMask32(0)) diff --git a/toontown/safezone/DistributedTrolley.py b/toontown/safezone/DistributedTrolley.py index e28628bf8..7da1d23d4 100644 --- a/toontown/safezone/DistributedTrolley.py +++ b/toontown/safezone/DistributedTrolley.py @@ -58,10 +58,10 @@ def generate(self): self.numKeys = self.keys.getNumPaths() self.keyInit = [] self.keyRef = [] - for i in xrange(self.numKeys): + for i in range(self.numKeys): key = self.keys[i] key.setTwoSided(1) - ref = self.trolleyCar.attachNewNode('key' + `i` + 'ref') + ref = self.trolleyCar.attachNewNode('key' + repr(i) + 'ref') ref.iPosHpr(key) self.keyRef.append(ref) self.keyInit.append(key.getTransform()) @@ -70,9 +70,9 @@ def generate(self): self.numFrontWheels = self.frontWheels.getNumPaths() self.frontWheelInit = [] self.frontWheelRef = [] - for i in xrange(self.numFrontWheels): + for i in range(self.numFrontWheels): wheel = self.frontWheels[i] - ref = self.trolleyCar.attachNewNode('frontWheel' + `i` + 'ref') + ref = self.trolleyCar.attachNewNode('frontWheel' + repr(i) + 'ref') ref.iPosHpr(wheel) self.frontWheelRef.append(ref) self.frontWheelInit.append(wheel.getTransform()) @@ -81,9 +81,9 @@ def generate(self): self.numBackWheels = self.backWheels.getNumPaths() self.backWheelInit = [] self.backWheelRef = [] - for i in xrange(self.numBackWheels): + for i in range(self.numBackWheels): wheel = self.backWheels[i] - ref = self.trolleyCar.attachNewNode('backWheel' + `i` + 'ref') + ref = self.trolleyCar.attachNewNode('backWheel' + repr(i) + 'ref') ref.iPosHpr(wheel) self.backWheelRef.append(ref) self.backWheelInit.append(wheel.getTransform()) @@ -361,29 +361,29 @@ def exitLeaving(self): self.trolleyExitTrack.finish() def animateTrolley(self, t, keyAngle, wheelAngle): - for i in xrange(self.numKeys): + for i in range(self.numKeys): key = self.keys[i] ref = self.keyRef[i] key.setH(ref, t * keyAngle) - for i in xrange(self.numFrontWheels): + for i in range(self.numFrontWheels): frontWheel = self.frontWheels[i] ref = self.frontWheelRef[i] frontWheel.setH(ref, t * wheelAngle) - for i in xrange(self.numBackWheels): + for i in range(self.numBackWheels): backWheel = self.backWheels[i] ref = self.backWheelRef[i] backWheel.setH(ref, t * wheelAngle) def resetAnimation(self): - for i in xrange(self.numKeys): + for i in range(self.numKeys): self.keys[i].setTransform(self.keyInit[i]) - for i in xrange(self.numFrontWheels): + for i in range(self.numFrontWheels): self.frontWheels[i].setTransform(self.frontWheelInit[i]) - for i in xrange(self.numBackWheels): + for i in range(self.numBackWheels): self.backWheels[i].setTransform(self.backWheelInit[i]) def getStareAtNodeAndOffset(self): diff --git a/toontown/safezone/DistributedTrolleyAI.py b/toontown/safezone/DistributedTrolleyAI.py index 284e1ed51..007e7ef9a 100644 --- a/toontown/safezone/DistributedTrolleyAI.py +++ b/toontown/safezone/DistributedTrolleyAI.py @@ -44,12 +44,12 @@ def delete(self): DistributedObjectAI.DistributedObjectAI.delete(self) def findAvailableSeat(self): - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): if self.seats[i] is None: return i def findAvatar(self, avId): - for i in xrange(len(self.seats)): + for i in range(len(self.seats)): if self.seats[i] == avId: return i @@ -168,7 +168,7 @@ def start(self): def enterOff(self): self.accepting = 0 if hasattr(self, 'doId'): - for seatIndex in xrange(4): + for seatIndex in range(4): taskMgr.remove(self.uniqueName('clearEmpty-' + str(seatIndex))) def exitOff(self): @@ -283,7 +283,7 @@ def trolleyLeft(self): startingVotes=startingVotes, metagameRound=metagameRound) minigameZone = mgDict['minigameZone'] minigameId = mgDict['minigameId'] - for seatIndex in xrange(len(self.seats)): + for seatIndex in range(len(self.seats)): avId = self.seats[seatIndex] if avId: self.sendUpdateToAvatarId(avId, 'setMinigameZone', [minigameZone, minigameId]) diff --git a/toontown/safezone/GSSafeZoneLoader.py b/toontown/safezone/GSSafeZoneLoader.py index 5fe9c280b..4a7b5d885 100644 --- a/toontown/safezone/GSSafeZoneLoader.py +++ b/toontown/safezone/GSSafeZoneLoader.py @@ -36,7 +36,7 @@ def load(self): holidayIds = base.cr.newsManager.getDecorationHolidayId() if ToontownGlobals.CRASHED_LEADERBOARD in holidayIds: self.startSmokeEffect() - self.birdSound = map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg']) + self.birdSound = list(map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg'])) def unload(self): del self.birdSound @@ -86,7 +86,7 @@ def exitRacetrack(self): del self.trackId def handleRaceOver(self): - print 'you done!!' + print('you done!!') def handleLeftRace(self): req = {'loader': 'safeZoneLoader', diff --git a/toontown/safezone/GZSafeZoneLoader.py b/toontown/safezone/GZSafeZoneLoader.py index 829ef3030..3d9adaa02 100644 --- a/toontown/safezone/GZSafeZoneLoader.py +++ b/toontown/safezone/GZSafeZoneLoader.py @@ -31,7 +31,7 @@ def __init__(self, hood, parentFSM, doneEvent): def load(self): SafeZoneLoader.load(self) - self.birdSound = map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg']) + self.birdSound = list(map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg'])) def unload(self): del self.birdSound @@ -89,7 +89,7 @@ def exitGolfCourse(self): del self.golfCourseId def handleRaceOver(self): - print 'you done!!' + print('you done!!') def handleLeftGolf(self): req = {'loader': 'safeZoneLoader', diff --git a/toontown/safezone/OZSafeZoneLoader.py b/toontown/safezone/OZSafeZoneLoader.py index 22478e3f4..cf81b5d86 100644 --- a/toontown/safezone/OZSafeZoneLoader.py +++ b/toontown/safezone/OZSafeZoneLoader.py @@ -33,7 +33,7 @@ def __init__(self, hood, parentFSM, doneEvent): def load(self): self.done = 0 SafeZoneLoader.load(self) - self.birdSound = map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg']) + self.birdSound = list(map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', 'phase_4/audio/sfx/SZ_TC_bird3.ogg'])) self.underwaterSound = base.loader.loadSfx('phase_4/audio/sfx/AV_ambient_water.ogg') self.swimSound = base.loader.loadSfx('phase_4/audio/sfx/AV_swim_single_stroke.ogg') self.submergeSound = base.loader.loadSfx('phase_5.5/audio/sfx/AV_jump_in_water.ogg') diff --git a/toontown/safezone/Playground.py b/toontown/safezone/Playground.py index e30d3ae9d..64d6a7a8d 100644 --- a/toontown/safezone/Playground.py +++ b/toontown/safezone/Playground.py @@ -331,13 +331,13 @@ def unload(self): def showTreasurePoints(self, points): self.hideDebugPointText() - for i in xrange(len(points)): + for i in range(len(points)): p = points[i] self.showDebugPointText(str(i), p) def showDropPoints(self, points): self.hideDebugPointText() - for i in xrange(len(points)): + for i in range(len(points)): p = points[i] self.showDebugPointText(str(i), p) @@ -352,7 +352,7 @@ def showPathPoints(self, paths, waypoints = None): lines = LineSegs() lines.setColor(1, 0, 0, 1) from toontown.classicchars import CCharPaths - for name, pointDef in paths.items(): + for name, pointDef in list(paths.items()): self.showDebugPointText(name, pointDef[0]) for connectTo in pointDef[1]: toDef = paths[connectTo] @@ -371,7 +371,7 @@ def showPathPoints(self, paths, waypoints = None): def hideDebugPointText(self): if hasattr(self, 'debugText'): children = self.debugText.getChildren() - for i in xrange(children.getNumPaths()): + for i in range(children.getNumPaths()): children[i].removeNode() def showDebugPointText(self, text, point): @@ -456,7 +456,7 @@ def enterDFACallback(self, requestStatus, doneStatus): elif ds == 'incomplete': self.fsm.request('DFAReject') else: - self.notify.error('Unknown done status for DownloadForceAcknowledge: ' + `doneStatus`) + self.notify.error('Unknown done status for DownloadForceAcknowledge: ' + repr(doneStatus)) def enterHFA(self, requestStatus): self.acceptOnce(self.hfaDoneEvent, self.enterHFACallback, [requestStatus]) @@ -480,7 +480,7 @@ def enterHFACallback(self, requestStatus, doneStatus): elif doneStatus['mode'] == 'incomplete': self.fsm.request('HFAReject') else: - self.notify.error('Unknown done status for HealthForceAcknowledge: ' + `doneStatus`) + self.notify.error('Unknown done status for HealthForceAcknowledge: ' + repr(doneStatus)) def enterHFAReject(self): self.fsm.request('walk') @@ -504,7 +504,7 @@ def enterNPCFACallback(self, requestStatus, doneStatus): elif doneStatus['mode'] == 'incomplete': self.fsm.request('NPCFAReject') else: - self.notify.error('Unknown done status for NPCForceAcknowledge: ' + `doneStatus`) + self.notify.error('Unknown done status for NPCForceAcknowledge: ' + repr(doneStatus)) def enterNPCFAReject(self): self.fsm.request('walk') @@ -676,7 +676,7 @@ def createPlayground(self, dnaFile): def makeDictionaries(self, dnaStore): self.nodeList = [] - for i in xrange(dnaStore.getNumDNAVisGroups()): + for i in range(dnaStore.getNumDNAVisGroups()): groupFullName = dnaStore.getDNAVisGroupName(i) groupName = base.cr.hoodMgr.extractGroupName(groupFullName) groupNode = self.geom.find('**/' + groupFullName) @@ -692,7 +692,7 @@ def makeDictionaries(self, dnaStore): def removeLandmarkBlockNodes(self): npc = self.geom.findAllMatches('**/suit_building_origin') - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): npc.getPath(i).removeNode() def enterTFA(self, requestStatus): diff --git a/toontown/safezone/RegenTreasurePlannerAI.py b/toontown/safezone/RegenTreasurePlannerAI.py index fd1ba0392..d5977c931 100644 --- a/toontown/safezone/RegenTreasurePlannerAI.py +++ b/toontown/safezone/RegenTreasurePlannerAI.py @@ -40,5 +40,5 @@ def placeRandomTreasure(self): self.placeTreasure(spawnPointIndex) def preSpawnTreasures(self): - for i in xrange(self.maxTreasures): + for i in range(self.maxTreasures): self.placeRandomTreasure() diff --git a/toontown/safezone/SafeZoneLoader.py b/toontown/safezone/SafeZoneLoader.py index b0e00ddb9..8710069b0 100644 --- a/toontown/safezone/SafeZoneLoader.py +++ b/toontown/safezone/SafeZoneLoader.py @@ -88,9 +88,9 @@ def createSafeZone(self, dnaFile): self.createAnimatedProps(self.nodeList) self.holidayPropTransforms = {} npl = self.geom.findAllMatches('**/=DNARoot=holiday_prop') - for i in xrange(npl.getNumPaths()): + for i in range(npl.getNumPaths()): np = npl.getPath(i) - np.setTag('transformIndex', `i`) + np.setTag('transformIndex', repr(i)) self.holidayPropTransforms[i] = np.getNetTransform() gsg = base.win.getGsg() if gsg: @@ -99,7 +99,7 @@ def createSafeZone(self, dnaFile): def makeDictionaries(self, dnaStore): self.nodeList = [] - for i in xrange(dnaStore.getNumDNAVisGroups()): + for i in range(dnaStore.getNumDNAVisGroups()): groupFullName = dnaStore.getDNAVisGroupName(i) groupName = base.cr.hoodMgr.extractGroupName(groupFullName) groupNode = self.geom.find('**/' + groupFullName) @@ -116,7 +116,7 @@ def makeDictionaries(self, dnaStore): def removeLandmarkBlockNodes(self): npc = self.geom.findAllMatches('**/suit_building_origin') - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): npc.getPath(i).removeNode() def enterStart(self): @@ -205,7 +205,7 @@ def createAnimatedProps(self, nodeList): for i in nodeList: animPropNodes = i.findAllMatches('**/animated_prop_*') numAnimPropNodes = animPropNodes.getNumPaths() - for j in xrange(numAnimPropNodes): + for j in range(numAnimPropNodes): animPropNode = animPropNodes.getPath(j) if animPropNode.getName().startswith('animated_prop_generic'): className = 'GenericAnimatedProp' @@ -220,7 +220,7 @@ def createAnimatedProps(self, nodeList): interactivePropNodes = i.findAllMatches('**/interactive_prop_*') numInteractivePropNodes = interactivePropNodes.getNumPaths() - for j in xrange(numInteractivePropNodes): + for j in range(numInteractivePropNodes): interactivePropNode = interactivePropNodes.getPath(j) className = 'GenericAnimatedProp' symbols = {} @@ -233,7 +233,7 @@ def createAnimatedProps(self, nodeList): animPropList.append(interactivePropObj) def deleteAnimatedProps(self): - for zoneNode, animPropList in self.animPropDict.items(): + for zoneNode, animPropList in list(self.animPropDict.items()): for animProp in animPropList: animProp.delete() diff --git a/toontown/safezone/TTOSafeZoneLoader.py b/toontown/safezone/TTOSafeZoneLoader.py index 3eee2a3e1..7d41cdcd8 100644 --- a/toontown/safezone/TTOSafeZoneLoader.py +++ b/toontown/safezone/TTOSafeZoneLoader.py @@ -15,9 +15,9 @@ def __init__(self, hood, parentFSM, doneEvent): def load(self): SafeZoneLoader.SafeZoneLoader.load(self) - self.birdSound = map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', + self.birdSound = list(map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', - 'phase_4/audio/sfx/SZ_TC_bird3.ogg']) + 'phase_4/audio/sfx/SZ_TC_bird3.ogg'])) library = self.geom.find('**/*toon_landmark_TT_library_DNARoot') if not library.isEmpty(): diff --git a/toontown/safezone/TTSafeZoneLoader.py b/toontown/safezone/TTSafeZoneLoader.py index 43948c198..3dc4a185d 100644 --- a/toontown/safezone/TTSafeZoneLoader.py +++ b/toontown/safezone/TTSafeZoneLoader.py @@ -15,9 +15,9 @@ def __init__(self, hood, parentFSM, doneEvent): def load(self): SafeZoneLoader.SafeZoneLoader.load(self) - self.birdSound = map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', + self.birdSound = list(map(base.loader.loadSfx, ['phase_4/audio/sfx/SZ_TC_bird1.ogg', 'phase_4/audio/sfx/SZ_TC_bird2.ogg', - 'phase_4/audio/sfx/SZ_TC_bird3.ogg']) + 'phase_4/audio/sfx/SZ_TC_bird3.ogg'])) library = self.geom.find('**/*toon_landmark_TT_library_DNARoot') if not library.isEmpty(): diff --git a/toontown/safezone/Train.py b/toontown/safezone/Train.py index a5605c90a..c74058374 100644 --- a/toontown/safezone/Train.py +++ b/toontown/safezone/Train.py @@ -97,7 +97,7 @@ def __cleanupCars(self): def __getCars(self): self.__cleanupCars() numCarsThisRun = random.randrange(1, 10) - for nCar in xrange(numCarsThisRun): + for nCar in range(numCarsThisRun): carType = random.randrange(0, self.numCars) car = loader.loadModel(self.CarFiles[carType]) car.flattenStrong() diff --git a/toontown/shtiker/AchievementsPage.py b/toontown/shtiker/AchievementsPage.py index b0bd91eed..f940f3c5b 100644 --- a/toontown/shtiker/AchievementsPage.py +++ b/toontown/shtiker/AchievementsPage.py @@ -146,9 +146,9 @@ def updatePage(self): start_pos = LVecBase3(.4, 1, -0.26) seperation = LVecBase3(0, 0, 0.7) - possibleAchievementTypes = Achievements.type2AchievementIds.keys() + possibleAchievementTypes = list(Achievements.type2AchievementIds.keys()) - for type in xrange(len(possibleAchievementTypes)): + for type in range(len(possibleAchievementTypes)): for achievement in Achievements.AchievementsDict: if isinstance(achievement, possibleAchievementTypes[type]): cat = Achievements.type2Category.get(achievement.__class__) @@ -159,7 +159,7 @@ def updatePage(self): else: self.setFrame.hide() - for achievement in xrange(self.offset, self.offset + 4): + for achievement in range(self.offset, self.offset + 4): try: achievementFrame = DirectFrame(parent = self.achievementsPageNode, image = DGG.getDefaultDialogGeom(), scale = (0.55, 0, 0.55), relief = None, pos = (POSITIONS[achievement % 4]), @@ -236,7 +236,7 @@ def updateStats(self): statRows2 = [self.createStat(y, 0.8) for y in (rowYs)] self.statRows += statRows2 self.stats = base.localAvatar.getStats() - for stat in xrange(self.statOffset, self.statOffset + 26): + for stat in range(self.statOffset, self.statOffset + 26): try: statText = TTLocalizer.StatsList[stat] % self.stats[stat] self.statRows[stat - 26]['text'] = statText diff --git a/toontown/shtiker/CertPage.py b/toontown/shtiker/CertPage.py index 7deb12fd6..9226abd26 100644 --- a/toontown/shtiker/CertPage.py +++ b/toontown/shtiker/CertPage.py @@ -1,7 +1,7 @@ from panda3d.core import * from panda3d.direct import * -import ShtikerPage -import ShtikerBook +from . import ShtikerPage +from . import ShtikerBook from direct.gui.DirectGui import * from direct.directnotify import DirectNotifyGlobal from panda3d.core import * diff --git a/toontown/shtiker/CodePage.py b/toontown/shtiker/CodePage.py index da13e7854..5e1955f57 100644 --- a/toontown/shtiker/CodePage.py +++ b/toontown/shtiker/CodePage.py @@ -1,4 +1,4 @@ -import ShtikerPage +from . import ShtikerPage from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer from direct.directnotify import DirectNotifyGlobal diff --git a/toontown/shtiker/DirectNewsFrame.py b/toontown/shtiker/DirectNewsFrame.py index 612c246ce..dbceb22af 100644 --- a/toontown/shtiker/DirectNewsFrame.py +++ b/toontown/shtiker/DirectNewsFrame.py @@ -354,12 +354,12 @@ def saveNewsCache(self): cacheIndexFilename = Filename(self.newsDir, self.CacheIndexFilename) try: file = open(cacheIndexFilename.toOsSpecific(), 'w') - except IOError, e: + except IOError as e: self.notify.warning('error opening news cache file %s: %s' % (cacheIndexFilename, str(e))) return - for filename, (size, date) in self.newsCache.items(): - print >> file, '%s\t%s\t%s' % (filename, size, date) + for filename, (size, date) in list(self.newsCache.items()): + print('%s\t%s\t%s' % (filename, size, date), file=file) def handleNewIssueOut(self): if hasattr(self, 'createdTime') and base.cr.inGameNewsMgr.getLatestIssue() < self.createdTime: diff --git a/toontown/shtiker/DisguisePage.py b/toontown/shtiker/DisguisePage.py index e57088868..f1a425256 100644 --- a/toontown/shtiker/DisguisePage.py +++ b/toontown/shtiker/DisguisePage.py @@ -53,11 +53,11 @@ def load(self): self.cogLevel = DirectLabel(parent=self.frame, relief=None, text='', text_font=ToontownGlobals.getSuitFont(), text_scale=0.09, text_align=TextNode.ACenter, pos=(-0.91, 0, -1.02)) self.partFrame = DirectFrame(parent=self.frame, relief=None) self.parts = [] - for partNum in xrange(0, 17): + for partNum in range(0, 17): self.parts.append(DirectFrame(parent=self.partFrame, relief=None, geom=gui.find('**/robot/' + PartNames[partNum]))) self.holes = [] - for partNum in xrange(0, 17): + for partNum in range(0, 17): self.holes.append(DirectFrame(parent=self.partFrame, relief=None, geom=gui.find('**/robot_hole/' + PartNames[partNum]))) self.cogPartRatio = DirectLabel(parent=self.frame, relief=None, text='', text_font=ToontownGlobals.getSuitFont(), text_scale=0.08, text_align=TextNode.ACenter, pos=(-0.91, 0, -0.82)) @@ -67,7 +67,7 @@ def load(self): self.meterFace = DirectLabel(parent=self.frame, relief=None, geom=meterFace, color=self.meterColor, pos=(0.455, 0.0, 0.04)) self.meterFaceHalf1 = DirectLabel(parent=self.frame, relief=None, geom=meterFaceHalf, color=self.meterActiveColor, pos=(0.455, 0.0, 0.04)) self.meterFaceHalf2 = DirectLabel(parent=self.frame, relief=None, geom=meterFaceHalf, color=self.meterColor, pos=(0.455, 0.0, 0.04)) - for dept in xrange(len(SuitDNA.suitDepts)): + for dept in range(len(SuitDNA.suitDepts)): button = DirectButton(parent=self.frame, relief=None, pos=(-1 + self.xOffset * dept, 0, 1.05), image=icons.find(SuitDNA.suitDeptModelPaths[dept]), image_scale=0.25, image2_color=(1, 1, 1, 0.75), command = self.doTab, extraArgs=[dept]) self.buttons.append(button) self.frame.hide() diff --git a/toontown/shtiker/DisplaySettingsDialog.py b/toontown/shtiker/DisplaySettingsDialog.py index a75943767..dc000f192 100644 --- a/toontown/shtiker/DisplaySettingsDialog.py +++ b/toontown/shtiker/DisplaySettingsDialog.py @@ -228,7 +228,7 @@ def updateScreenSize(self): self.screenSizeRightArrow.hide() def chooseClosestScreenSize(self, currentXSize, currentYSize): - for i in xrange(len(self.screenSizes)): + for i in range(len(self.screenSizes)): xSize, ySize = self.screenSizes[i] if currentXSize == xSize and currentYSize == ySize: return i @@ -236,7 +236,7 @@ def chooseClosestScreenSize(self, currentXSize, currentYSize): currentCount = currentXSize * currentYSize bestDiff = None bestI = None - for i in xrange(len(self.screenSizes)): + for i in range(len(self.screenSizes)): xSize, ySize = self.screenSizes[i] diff = abs(xSize * ySize - currentCount) if bestI == None or diff < bestDiff: @@ -316,7 +316,7 @@ def changeDisplayProperties(self, pipe, width, height, fullscreen = False): # ratio and fit it (besides the native resolution itself, # of course). Let's just use one of the second largest # ratio's resolutions: - ratios = sorted(base.resDict.keys(), reverse=False) + ratios = sorted(list(base.resDict.keys()), reverse=False) nativeIndex = ratios.index(base.nativeRatio) width, height = sorted(base.resDict[ratios[nativeIndex - 1]])[0] properties.setSize(width, height) diff --git a/toontown/shtiker/EventsPage.py b/toontown/shtiker/EventsPage.py index 4e7f3afa7..e85b468ac 100644 --- a/toontown/shtiker/EventsPage.py +++ b/toontown/shtiker/EventsPage.py @@ -1,4 +1,4 @@ -import urllib +import urllib.request, urllib.parse, urllib.error from pandac.PandaModules import Vec4, Vec3, TextNode, PNMImage, StringStream, Texture, HTTPClient, DocumentSpec, Ramfile, Point3 from direct.task.Task import Task from direct.gui.DirectGui import DirectFrame, DirectLabel, DirectButton, DirectScrolledList, DirectCheckButton, OnscreenText @@ -689,7 +689,7 @@ def createArticleTextList(self): def makeButton(itemName, itemNum, *extraArgs): def buttonCommand(): - print itemName, itemNum + print(itemName, itemNum) return DirectLabel(text=itemName, relief=None, text_align=TextNode.ALeft, scale=0.06) @@ -784,7 +784,7 @@ def downloadArticlesTask(self, task): self.articleImages = {} self.articleText = {} try: - urlfile = urllib.urlopen(self.getNewsUrl()) + urlfile = urllib.request.urlopen(self.getNewsUrl()) except IOError: self.notify.warning('Could not open %s' % self.getNewsUrl()) self.newsStatusLabel['text'] = TTLocalizer.EventsPageNewsUnavailable @@ -793,14 +793,14 @@ def downloadArticlesTask(self, task): urlStrings = urlfile.read() urlfile.close() urls = urlStrings.split('\r\n') - for index in xrange(len(urls) / 2): + for index in range(len(urls) / 2): imageUrl = urls[index * 2] textUrl = urls[index * 2 + 1] img = PNMImage() self.articleImages[index] = img try: self.notify.info('opening %s' % imageUrl) - imageFile = urllib.urlopen(imageUrl) + imageFile = urllib.request.urlopen(imageUrl) data = imageFile.read() img.read(StringStream(data)) imageFile.close() @@ -811,7 +811,7 @@ def downloadArticlesTask(self, task): self.articleText[index] = text try: self.notify.info('opening %s' % textUrl) - textFile = urllib.urlopen(textUrl) + textFile = urllib.request.urlopen(textUrl) data = textFile.read() data = data.replace('\\1', '\x01') data = data.replace('\\2', '\x02') @@ -1021,7 +1021,7 @@ def getFileUrl(self, fileUrl): result = True urlStrings = '' try: - urlfile = urllib.urlopen(fileUrl) + urlfile = urllib.request.urlopen(fileUrl) urlStrings = urlfile.read() urlfile.close() except IOError: diff --git a/toontown/shtiker/FishPage.py b/toontown/shtiker/FishPage.py index f1dab8483..897253c69 100644 --- a/toontown/shtiker/FishPage.py +++ b/toontown/shtiker/FishPage.py @@ -86,7 +86,7 @@ def createFishTrophyFrame(self): self.trophies = [] hOffset = -0.5 vOffset = 0.4 - for level, trophyDesc in FishGlobals.TrophyDict.items(): + for level, trophyDesc in list(FishGlobals.TrophyDict.items()): trophy = FishingTrophy(-1) trophy.nameLabel['text'] = trophyDesc[0] trophy.reparentTo(self.trophyFrame) diff --git a/toontown/shtiker/GardenPage.py b/toontown/shtiker/GardenPage.py index 5c2aae607..cbd12ab86 100644 --- a/toontown/shtiker/GardenPage.py +++ b/toontown/shtiker/GardenPage.py @@ -230,7 +230,7 @@ def createGardenTrophyFrame(self): self.trophies = [] hOffset = -0.5 vOffset = 0.4 - for level, trophyDesc in GardenGlobals.TrophyDict.items(): + for level, trophyDesc in list(GardenGlobals.TrophyDict.items()): trophy = GardenTrophy(-1) trophy.nameLabel['text'] = trophyDesc[0] trophy.reparentTo(self.trophyFrame) @@ -261,7 +261,7 @@ def createFlowerPicker(self): 0.1), borderWidth=(0.025, 0.025), scale=0.45, frameColor=(0.8, 0.8, 0.7, 1), barColor=(0.4, 0.6, 1.0, 1), range=self.barLength + self.FUDGE_FACTOR, value=self.barLength * 0.5 + self.FUDGE_FACTOR, text=' ' + TTLocalizer.Laff, text_scale=0.11, text_fg=(0.05, 0.14, 0.2, 1), text_align=TextNode.ALeft, text_pos=(-0.57, -0.035)) def unload(self): - print 'gardenPage Unloading' + print('gardenPage Unloading') if hasattr(self, 'specialsPhoto'): del self.specialsPhoto if hasattr(self, 'trophies'): @@ -302,7 +302,7 @@ def updatePage(self): self.wateringCanBar['text'] = textToUse self.wateringCanBar['value'] = float(curWateringCanSkill) / float(maxWateringCanSkill) * self.barLength + self.FUDGE_FACTOR else: - print 'no shovel bar' + print('no shovel bar') if self.mode == GardenPage_Collection: if hasattr(self, 'browser'): self.browser.update() diff --git a/toontown/shtiker/GolfPage.py b/toontown/shtiker/GolfPage.py index 1c8d491b4..fd47fcaba 100644 --- a/toontown/shtiker/GolfPage.py +++ b/toontown/shtiker/GolfPage.py @@ -6,7 +6,7 @@ from toontown.fishing.FishPhoto import DirectRegion from toontown.shtiker.ShtikerPage import ShtikerPage from toontown.toonbase import ToontownGlobals, TTLocalizer -from FishPage import FishingTrophy +from .FishPage import FishingTrophy from toontown.golf import GolfGlobals if (__debug__): import pdb @@ -84,7 +84,7 @@ def setMode(self, mode, updateAnyways = 0): self.recordsTab['state'] = DGG.NORMAL self.trophyTab['state'] = DGG.DISABLED else: - raise StandardError, 'GolfPage::setMode - Invalid Mode %s' % mode + raise Exception('GolfPage::setMode - Invalid Mode %s' % mode) self.updatePage() def updatePage(self): @@ -95,7 +95,7 @@ def updatePage(self): self.golfTrophies.show() self.golfRecords.hide() else: - raise StandardError, 'GolfPage::updatePage - Invalid Mode %s' % self.mode + raise Exception('GolfPage::updatePage - Invalid Mode %s' % self.mode) class GolfingRecordsUI(DirectFrame): @@ -162,16 +162,16 @@ def show(self): bestHoles = self.avatar.getGolfHoleBest() bestCourses = self.avatar.getGolfCourseBest() if bestHoles != self.lastHoleBest or bestCourses != self.lastCourseBest: - numCourse = len(GolfGlobals.CourseInfo.keys()) - numHoles = len(GolfGlobals.HoleInfo.keys()) - for i in xrange(numCourse): + numCourse = len(list(GolfGlobals.CourseInfo.keys())) + numHoles = len(list(GolfGlobals.HoleInfo.keys())) + for i in range(numCourse): score = bestCourses[i] if score != 0: self.bestDisplayList[i]['text'] = (str(score),) else: self.bestDisplayList[i]['text'] = TTLocalizer.KartRace_Unraced - for i in xrange(numHoles): + for i in range(numHoles): score = bestHoles[i] if score != 0: self.bestDisplayList[i + numCourse]['text'] = str(score) @@ -233,8 +233,8 @@ def load(self): yStart = 0.475 xOffset = 0.17 yOffset = 0.23 - for j in xrange(GolfGlobals.NumCups): - for i in xrange(GolfGlobals.TrophiesPerCup): + for j in range(GolfGlobals.NumCups): + for i in range(GolfGlobals.TrophiesPerCup): trophyPanel = DirectLabel(parent=self, relief=None, pos=(xStart + i * xOffset, 0.0, yStart - j * yOffset), state=DGG.NORMAL, image=DGG.getDefaultDialogGeom(), image_scale=(0.75, 1, 1), image_color=(0.8, 0.8, 0.8, 1), text=TTLocalizer.SuitPageMystery[0], text_scale=0.45, text_fg=(0, 0, 0, 1), text_pos=(0, 0, -0.25), text_font=ToontownGlobals.getInterfaceFont(), text_wordwrap=5.5) trophyPanel.scale = 0.2 trophyPanel.setScale(trophyPanel.scale) @@ -243,7 +243,7 @@ def load(self): xStart = -0.25 yStart = -0.38 xOffset = 0.25 - for i in xrange(GolfGlobals.NumCups): + for i in range(GolfGlobals.NumCups): cupPanel = DirectLabel(parent=self, relief=None, pos=(xStart + i * xOffset, 0.0, yStart), state=DGG.NORMAL, image=DGG.getDefaultDialogGeom(), image_scale=(0.75, 1, 1), image_color=(0.8, 0.8, 0.8, 1), text=TTLocalizer.SuitPageMystery[0], text_scale=0.45, text_fg=(0, 0, 0, 1), text_pos=(0, 0, -0.25), text_font=ToontownGlobals.getInterfaceFont(), text_wordwrap=5.5) cupPanel.scale = 0.3 cupPanel.setScale(cupPanel.scale) @@ -288,7 +288,7 @@ def show(self): DirectFrame.show(self) def updateTrophies(self): - for t in xrange(len(self.trophyPanels)): + for t in range(len(self.trophyPanels)): if self.trophies[t]: trophyPanel = self.trophyPanels[t] trophyPanel['text'] = '' @@ -311,7 +311,7 @@ def updateTrophies(self): trophyPanel.unbind(DGG.ENTER) trophyPanel.unbind(DGG.EXIT) - for t in xrange(len(self.cupPanels)): + for t in range(len(self.cupPanels)): if self.cups[t]: cupPanel = self.cupPanels[t] cupPanel['text'] = '' diff --git a/toontown/shtiker/HtmlView.py b/toontown/shtiker/HtmlView.py index 13b18f97c..8b3c46558 100644 --- a/toontown/shtiker/HtmlView.py +++ b/toontown/shtiker/HtmlView.py @@ -39,14 +39,14 @@ def __init__(self, parent = aspect2d): else: GlobalWebcore = AwWebCore(AwWebCore.LOGVERBOSE, True, AwWebCore.PFBGRA) GlobalWebcore.setBaseDirectory('.') - for errResponse in xrange(400, 600): + for errResponse in range(400, 600): GlobalWebcore.setCustomResponsePage(errResponse, 'error.html') self.webView = GlobalWebcore.createWebView(WEB_WIDTH, WEB_HEIGHT, self.transparency, False, 70) frameName = '' inGameNewsUrl = self.getInGameNewsUrl() self.imgBuffer = array.array('B') - for i in xrange(WEB_WIDTH * WEB_HEIGHT): + for i in range(WEB_WIDTH * WEB_HEIGHT): self.imgBuffer.append(0) self.imgBuffer.append(0) self.imgBuffer.append(0) @@ -54,14 +54,14 @@ def __init__(self, parent = aspect2d): if self.useHalfTexture: self.leftBuffer = array.array('B') - for i in xrange(WEB_HALF_WIDTH * WEB_HEIGHT): + for i in range(WEB_HALF_WIDTH * WEB_HEIGHT): self.leftBuffer.append(0) self.leftBuffer.append(0) self.leftBuffer.append(0) self.leftBuffer.append(255) self.rightBuffer = array.array('B') - for i in xrange(WEB_HALF_WIDTH * WEB_HEIGHT): + for i in range(WEB_HALF_WIDTH * WEB_HEIGHT): self.rightBuffer.append(0) self.rightBuffer.append(0) self.rightBuffer.append(0) diff --git a/toontown/shtiker/InventoryPageNEW.py b/toontown/shtiker/InventoryPageNEW.py index 36f3e9b7a..9774a4b71 100644 --- a/toontown/shtiker/InventoryPageNEW.py +++ b/toontown/shtiker/InventoryPageNEW.py @@ -1,4 +1,4 @@ -import ShtikerPage +from . import ShtikerPage from toontown.toonbase import ToontownBattleGlobals from direct.gui.DirectGui import * from panda3d.core import * diff --git a/toontown/shtiker/InventoryPageOLD.py b/toontown/shtiker/InventoryPageOLD.py index 8eab2851b..3c8351385 100644 --- a/toontown/shtiker/InventoryPageOLD.py +++ b/toontown/shtiker/InventoryPageOLD.py @@ -1,4 +1,4 @@ -import ShtikerPage +from . import ShtikerPage from toontown.toonbase import ToontownBattleGlobals from direct.gui.DirectGui import * from panda3d.core import * diff --git a/toontown/shtiker/IssueFrame.py b/toontown/shtiker/IssueFrame.py index f9ac5974a..7c191c0be 100644 --- a/toontown/shtiker/IssueFrame.py +++ b/toontown/shtiker/IssueFrame.py @@ -187,7 +187,7 @@ def loadHomePageButtons(self, section, subsection, pageFrame): image_scale = float(desiredXSize) / xSize image_scale *= float(69) / 70 self.sectionBtns = [] - for section in xrange(1, len(self.SectionIdents)): + for section in range(1, len(self.SectionIdents)): image = self.gui.find('**/%s' % buttonNames[section]) rolloverImage = self.gui.find('**/%s' % rolloverButtonNames[section]) if image.isEmpty(): @@ -311,7 +311,7 @@ def loadNavButtons(self, pageFrame): frameSize2, frameSize2) self.sectionBtns = [] - for section in xrange(0, len(self.SectionIdents)): + for section in range(0, len(self.SectionIdents)): image = self.guiNav.find('**/%s' % buttonNames[section]) rolloverImage = self.guiNav.find('**/%s' % rolloverButtonNames[section]) if image.isEmpty(): diff --git a/toontown/shtiker/KartPage.py b/toontown/shtiker/KartPage.py index 29dbb5150..0a4fbc2cb 100644 --- a/toontown/shtiker/KartPage.py +++ b/toontown/shtiker/KartPage.py @@ -9,7 +9,7 @@ from toontown.racing import RaceGlobals from toontown.shtiker.ShtikerPage import ShtikerPage from toontown.toonbase import ToontownGlobals, TTLocalizer -from FishPage import FishingTrophy +from .FishPage import FishingTrophy if (__debug__): import pdb @@ -92,7 +92,7 @@ def setMode(self, mode, updateAnyways = 0): self.recordsTab['state'] = DGG.NORMAL self.trophyTab['state'] = DGG.DISABLED else: - raise StandardError, 'KartPage::setMode - Invalid Mode %s' % mode + raise Exception('KartPage::setMode - Invalid Mode %s' % mode) self.updatePage() def updatePage(self): @@ -109,7 +109,7 @@ def updatePage(self): self.racingTrophies.show() self.racingRecords.hide() else: - raise StandardError, 'KartPage::updatePage - Invalid Mode %s' % self.mode + raise Exception('KartPage::updatePage - Invalid Mode %s' % self.mode) class KartCustomizeUI(DirectFrame): @@ -206,7 +206,7 @@ def load(self): def show(self): bestTimes = self.avatar.getKartingPersonalBestAll() if bestTimes != self.lastTimes: - for i in xrange(0, len(bestTimes)): + for i in range(0, len(bestTimes)): time = bestTimes[i] if time != 0.0: whole, part = divmod(time, 1) @@ -248,8 +248,8 @@ def load(self): yStart = 0.475 xOffset = 0.17 yOffset = 0.23 - for j in xrange(RaceGlobals.NumCups): - for i in xrange(RaceGlobals.TrophiesPerCup): + for j in range(RaceGlobals.NumCups): + for i in range(RaceGlobals.TrophiesPerCup): trophyPanel = DirectLabel(parent=self, relief=None, pos=(xStart + i * xOffset, 0.0, yStart - j * yOffset), state=DGG.NORMAL, image=DGG.getDefaultDialogGeom(), image_scale=(0.75, 1, 1), image_color=(0.8, 0.8, 0.8, 1), text=TTLocalizer.SuitPageMystery[0], text_scale=0.45, text_fg=(0, 0, 0, 1), text_pos=(0, 0, -0.25), text_font=ToontownGlobals.getInterfaceFont(), text_wordwrap=5.5) trophyPanel.scale = 0.2 trophyPanel.setScale(trophyPanel.scale) @@ -258,7 +258,7 @@ def load(self): xStart = -0.25 yStart = -0.38 xOffset = 0.25 - for i in xrange(RaceGlobals.NumCups): + for i in range(RaceGlobals.NumCups): cupPanel = DirectLabel(parent=self, relief=None, pos=(xStart + i * xOffset, 0.0, yStart), state=DGG.NORMAL, image=DGG.getDefaultDialogGeom(), image_scale=(0.75, 1, 1), image_color=(0.8, 0.8, 0.8, 1), text=TTLocalizer.SuitPageMystery[0], text_scale=0.45, text_fg=(0, 0, 0, 1), text_pos=(0, 0, -0.25), text_font=ToontownGlobals.getInterfaceFont(), text_wordwrap=5.5) cupPanel.scale = 0.3 cupPanel.setScale(cupPanel.scale) @@ -284,7 +284,7 @@ def show(self): DirectFrame.show(self) def updateTrophies(self): - for t in xrange(len(self.trophyPanels)): + for t in range(len(self.trophyPanels)): if self.trophies[t]: trophyPanel = self.trophyPanels[t] trophyPanel['text'] = '' @@ -341,7 +341,7 @@ def initUpdatedDNA(self): def setUpdatedDNA(self): currKartDNA = self.avatar.getKartDNA() - for i in xrange(len(self.updatedDNA)): + for i in range(len(self.updatedDNA)): if self.updatedDNA[i] != currKartDNA[i]: self.avatar.requestKartDNAFieldUpdate(i, self.updatedDNA[i]) @@ -618,11 +618,11 @@ def __init__(self, avatar, parent = aspect2d): DirectFrame.__init__(self, parent=parent, relief=None, pos=(0, 0, 0), scale=(1.0, 1.0, 1.0)) def destroy(self): - for key in self.buttonDict.keys(): + for key in list(self.buttonDict.keys()): self.buttonDict[key].destroy() del self.buttonDict[key] - for key in self.itemViewers.keys(): + for key in list(self.itemViewers.keys()): self.itemViewers[key].destroy() del self.itemViewers[key] @@ -692,7 +692,7 @@ def setupAccessoryIcons(self): self.__changeItemCategory(self.state) def resetAccessoryIcons(self): - for key in self.buttonDict.keys(): + for key in list(self.buttonDict.keys()): self.buttonDict[key].setProp('state', DGG.NORMAL) self.itemViewers['main'].show() @@ -737,7 +737,7 @@ def __changeItemCategory(self, buttonType): self.itemViewers['main'].setViewerText(TTLocalizer.KartShtikerSelect) self.itemViewers['main'].setupViewer(buttonType) else: - raise StandardError, 'KartPage.py::__changeItemCategory - INVALID Category Type!' + raise Exception('KartPage.py::__changeItemCategory - INVALID Category Type!') if self.state != buttonType and self.state != InvalidEntry: self.buttonDict[self.state]['state'] = DGG.NORMAL self.buttonDict[self.state].setColorScale(1, 1, 1, 1) @@ -823,8 +823,8 @@ def makeKartFrame(self): self.kart = None if not hasattr(self, 'kartDisplayRegion'): self.kartDisplayRegion = DirectRegion(parent=self) - apply(self.kartDisplayRegion.setBounds, self.bounds) - apply(self.kartDisplayRegion.setColor, self.colors) + self.kartDisplayRegion.setBounds(*self.bounds) + self.kartDisplayRegion.setColor(*self.colors) frame = self.kartDisplayRegion.load() if self.dna: self.kart = Kart() diff --git a/toontown/shtiker/PurchaseManagerAI.py b/toontown/shtiker/PurchaseManagerAI.py index 23da152e3..e79cc9886 100644 --- a/toontown/shtiker/PurchaseManagerAI.py +++ b/toontown/shtiker/PurchaseManagerAI.py @@ -27,10 +27,10 @@ def __init__(self, air, playerArray, mpArray, previousMinigameId, trolleyZone, n self.votesArray = [] self.metagameRound = metagameRound self.desiredNextGame = desiredNextGame - for i in xrange(len(self.playerIds), 4): + for i in range(len(self.playerIds), 4): self.playerIds.append(0) - for i in xrange(len(self.minigamePoints), 4): + for i in range(len(self.minigamePoints), 4): self.minigamePoints.append(0) self.playerStates = [None, @@ -45,7 +45,7 @@ def __init__(self, air, playerArray, mpArray, previousMinigameId, trolleyZone, n 0, 0, 0] - for i in xrange(len(self.playerIds)): + for i in range(len(self.playerIds)): avId = self.playerIds[i] if avId <= 3: self.playerStates[i] = PURCHASE_NO_CLIENT_STATE @@ -258,7 +258,7 @@ def timeIsUp(self): def getVotesArrayMatchingPlayAgainList(self, playAgainList): retval = [] - for playAgainIndex in xrange(len(playAgainList)): + for playAgainIndex in range(len(playAgainList)): avId = playAgainList[playAgainIndex] origIndex = self.playerIds.index(avId) if self.votesArray and origIndex < len(self.votesArray): @@ -297,7 +297,7 @@ def shutDown(self): return None def findAvIndex(self, avId): - for i in xrange(len(self.playerIds)): + for i in range(len(self.playerIds)): if avId == self.playerIds[i]: return i @@ -313,7 +313,7 @@ def getNumUndecided(self): def getPlayAgainList(self): playAgainList = [] - for i in xrange(len(self.playerStates)): + for i in range(len(self.playerStates)): if self.playerStates[i] == PURCHASE_PLAYAGAIN_STATE: playAgainList.append(self.playerIds[i]) diff --git a/toontown/shtiker/QuestPage.py b/toontown/shtiker/QuestPage.py index c870b9a8b..4893c96b6 100644 --- a/toontown/shtiker/QuestPage.py +++ b/toontown/shtiker/QuestPage.py @@ -48,7 +48,7 @@ def load(self): 0, 0)) self.questFrames = [] - for i in xrange(ToontownGlobals.MaxQuestCarryLimit): + for i in range(ToontownGlobals.MaxQuestCarryLimit): frame = QuestBookPoster.QuestBookPoster(reverse=i > 1, mapIndex=i + 1) frame.reparentTo(self) frame.setPosHpr(*questFramePlaceList[i]) @@ -84,7 +84,7 @@ def fillQuestFrame(self, questDesc, index): self.quests[index] = questDesc def getLowestUnusedIndex(self): - for i in xrange(ToontownGlobals.MaxQuestCarryLimit): + for i in range(ToontownGlobals.MaxQuestCarryLimit): if self.quests[i] == None: return i @@ -94,23 +94,23 @@ def updatePage(self): self.notify.debug('updatePage()') newQuests = base.localAvatar.quests carryLimit = base.localAvatar.getQuestCarryLimit() - for i in xrange(ToontownGlobals.MaxQuestCarryLimit): + for i in range(ToontownGlobals.MaxQuestCarryLimit): if i < carryLimit: self.questFrames[i].show() else: self.questFrames[i].hide() - for index, questDesc in self.quests.items(): + for index, questDesc in list(self.quests.items()): if questDesc is not None and list(questDesc) not in newQuests: self.clearQuestFrame(index) for questDesc in newQuests: newQuestDesc = tuple(questDesc) - if newQuestDesc not in self.quests.values(): + if newQuestDesc not in list(self.quests.values()): index = self.getLowestUnusedIndex() self.fillQuestFrame(newQuestDesc, index) - for i, questDesc in self.quests.iteritems(): + for i, questDesc in self.quests.items(): if questDesc: if self.canDeleteQuest(questDesc): self.questFrames[i].setDeleteCallback(self.__deleteQuest) @@ -143,7 +143,7 @@ def showQuestsOnscreen(self): if self.onscreen or base.localAvatar.invPage.onscreen: return self.onscreen = 1 - for i in xrange(ToontownGlobals.MaxQuestCarryLimit): + for i in range(ToontownGlobals.MaxQuestCarryLimit): if hasattr(self.questFrames[i], 'mapIndex'): self.questFrames[i].mapIndex.show() @@ -160,7 +160,7 @@ def hideQuestsOnscreen(self): if not self.onscreen: return self.onscreen = 0 - for i in xrange(ToontownGlobals.MaxQuestCarryLimit): + for i in range(ToontownGlobals.MaxQuestCarryLimit): if hasattr(self.questFrames[i], 'mapIndex'): self.questFrames[i].mapIndex.hide() diff --git a/toontown/shtiker/ShardPage.py b/toontown/shtiker/ShardPage.py index b2ff58d06..1eb0def22 100644 --- a/toontown/shtiker/ShardPage.py +++ b/toontown/shtiker/ShardPage.py @@ -246,7 +246,7 @@ def updateScrollList(self): currentMap = {} self.shardButtons = [] - for i in xrange(len(curShardTuples)): + for i in range(len(curShardTuples)): shardId, name, pop, WVPop, invasionStatus = curShardTuples[i] @@ -286,7 +286,7 @@ def updateScrollList(self): removeInvasionMarker(buttonTuple[3]) anyChanges = 1 - for shardId, buttonTuple in self.shardButtonMap.items(): + for shardId, buttonTuple in list(self.shardButtonMap.items()): if shardId not in currentMap: buttonTuple[3].removeNode() diff --git a/toontown/shtiker/ShtikerBook.py b/toontown/shtiker/ShtikerBook.py index 24fdd0086..d0cb7aef9 100644 --- a/toontown/shtiker/ShtikerBook.py +++ b/toontown/shtiker/ShtikerBook.py @@ -94,7 +94,7 @@ def exit(self): self.pages[self.currPageIndex].exit() base.render.show() setBlackBackground = 0 - for obj in base.cr.doId2do.values(): + for obj in list(base.cr.doId2do.values()): if isinstance(obj, DistributedFireworkShow.DistributedFireworkShow) or isinstance(obj, DistributedPartyFireworksActivity.DistributedPartyFireworksActivity): setBlackBackground = 1 if setBlackBackground: diff --git a/toontown/shtiker/SuitPage.py b/toontown/shtiker/SuitPage.py index 710593be8..42b470c64 100644 --- a/toontown/shtiker/SuitPage.py +++ b/toontown/shtiker/SuitPage.py @@ -8,7 +8,7 @@ from toontown.suit import SuitDNA from toontown.suit import Suit from toontown.battle import SuitBattleGlobals -from CogPageGlobals import * +from .CogPageGlobals import * SCALE_FACTOR = 1.5 RADAR_DELAY = 0.2 BUILDING_RADAR_POS = (0.4, @@ -121,7 +121,7 @@ def load(self): gui = loader.loadModel('phase_3.5/models/gui/suitpage_gui') self.panelModel = gui.find('**/card') self.shadowModels = [] - for index in xrange(1, len(SuitDNA.suitHeadTypes) + 1): + for index in range(1, len(SuitDNA.suitHeadTypes) + 1): self.shadowModels.append(gui.find('**/shadow' + str(index))) del gui self.makePanels() @@ -171,7 +171,7 @@ def exit(self): taskMgr.remove('suitListResponseTimeout-later') taskMgr.remove('showCogRadarLater') taskMgr.remove('showBuildingRadarLater') - for index in xrange(0, len(self.radarOn)): + for index in range(0, len(self.radarOn)): if self.radarOn[index]: self.toggleRadar(index) self.radarButtons[index]['state'] = DGG.NORMAL @@ -184,11 +184,11 @@ def __emblemChange(self, newEmblems): def grow(self, panel, pos): if self.bigPanel: - print 'setting next panel - ' + str(panel) + print('setting next panel - ' + str(panel)) self.nextPanel = panel self.nextPanelPos = pos return - print 'big panel - ' + str(panel) + print('big panel - ' + str(panel)) self.bigPanel = panel panel.reparentTo(self.enlargedPanelNode) panel.setScale(panel.getScale() * SCALE_FACTOR) @@ -197,11 +197,11 @@ def grow(self, panel, pos): panel.summonButton['state'] = DGG.NORMAL def shrink(self, panel, pos): - print 'trying to shrink - ' + str(panel) + print('trying to shrink - ' + str(panel)) if panel != self.bigPanel: self.nextPanel = None return - print 'shrink panel - ' + str(panel) + print('shrink panel - ' + str(panel)) self.bigPanel = None panel.setScale(panel.scale) panel.reparentTo(self.panelNode) @@ -261,10 +261,10 @@ def makePanels(self): self.rolloverFrame.setBin('gui-popup', 0) self.rolloverFrame.hide() gui.removeNode() - for dept in xrange(0, len(SuitDNA.suitDepts)): + for dept in range(0, len(SuitDNA.suitDepts)): row = [] color = PANEL_COLORS[dept] - for type in xrange(0, SuitDNA.suitsPerDept): + for type in range(0, SuitDNA.suitsPerDept): panel = DirectLabel(parent=self.panelNode, pos=(xStart + type * xOffset, 0.0, yStart - dept * yOffset), relief=None, state=DGG.NORMAL, image=self.panelModel, image_scale=(1, 1, 0.8), image_color=color, text=TTLocalizer.SuitPageMystery, text_scale=0.045, text_fg=(0, 0, 0, 1), text_pos=(0, 0.148, 0), text_font=ToontownGlobals.getSuitFont(), text_wordwrap=7) panel.scale = 0.6 panel.setScale(panel.scale) @@ -410,15 +410,15 @@ def setPanelStatus(self, panel, status): panel['image_color'] = PANEL_COLORS_COMPLETE2[index / SuitDNA.suitsPerDept] def updateAllCogs(self, status): - for index in xrange(0, len(base.localAvatar.cogs)): + for index in range(0, len(base.localAvatar.cogs)): base.localAvatar.cogs[index] = status self.updatePage() def updatePage(self): index = 0 cogs = base.localAvatar.cogs - for dept in xrange(0, len(SuitDNA.suitDepts)): - for type in xrange(0, SuitDNA.suitsPerDept): + for dept in range(0, len(SuitDNA.suitDepts)): + for type in range(0, SuitDNA.suitsPerDept): self.updateCogStatus(dept, type, cogs[index]) index += 1 self.updateCogRadarButtons(base.localAvatar.cogRadar) @@ -428,11 +428,11 @@ def updateCogStatus(self, dept, type, status): if dept == 5: pass if dept < 0 or dept > len(SuitDNA.suitDepts): - print 'ucs: bad cog dept: ', dept + print('ucs: bad cog dept: ', dept) elif type < 0 or type > SuitDNA.suitsPerDept: - print 'ucs: bad cog type: ', type + print('ucs: bad cog type: ', type) elif status < COG_UNSEEN or status > COG_COMPLETE2: - print 'ucs: bad status: ', status + print('ucs: bad status: ', status) else: self.resetPanel(dept, type) panel = self.panels[dept * SuitDNA.suitsPerDept + type] @@ -453,7 +453,7 @@ def updateCogStatus(self, dept, type, status): self.setPanelStatus(panel, COG_COMPLETE2) def updateCogRadarButtons(self, radars): - for index in xrange(0, len(radars)): + for index in range(0, len(radars)): if radars[index] == 1: self.radarButtons[index]['state'] = DGG.NORMAL @@ -488,7 +488,7 @@ def activateButton(s = self, index = deptNum): return def updateBuildingRadarButtons(self, radars): - for index in xrange(0, len(radars)): + for index in range(0, len(radars)): if radars[index] == 1: self.radarButtons[index].building = 1 diff --git a/toontown/shtiker/TrackPage.py b/toontown/shtiker/TrackPage.py index 633adab1b..44c2f6dd5 100644 --- a/toontown/shtiker/TrackPage.py +++ b/toontown/shtiker/TrackPage.py @@ -33,7 +33,7 @@ def load(self): self.flatButton = self.buttonModels.find('**/InventoryButtonFlat') self.rowModel = self.buttonModels.find('**/TrainingPointRow') self.infoText = OnscreenText(parent=self, text='', wordwrap = 30, scale=0.055, fg=(0, 0, 0, 1), shadow=(0, 0, 0, 0), pos=(0.0, -0.6), font=ToontownGlobals.getInterfaceFont(), mayChange=True) - for track in xrange(len(ToontownBattleGlobals.Tracks)): + for track in range(len(ToontownBattleGlobals.Tracks)): trackFrame = DirectFrame(parent=self, image=self.rowModel, scale=(1.05, 0.8, 1.1), pos=(0, 0.3, TrackYOffset + track * TrackYSpacing), image_color=(ToontownBattleGlobals.TrackColors[track][0], ToontownBattleGlobals.TrackColors[track][1], ToontownBattleGlobals.TrackColors[track][2], @@ -42,7 +42,7 @@ def load(self): self.trackNameLabels.append(DirectLabel(text=TextEncoder.upper(ToontownBattleGlobals.Tracks[track]), parent=self.trackRows[track], pos=(-0.72 + -0.06825, -0.1, 0.01), scale=TTLocalizer.INtrackNameLabels, relief=None, text_fg=(0.2, 0.2, 0.2, 1), text_font=ToontownGlobals.getInterfaceFont(), text_align=TextNode.ALeft, textMayChange=0)) self.trackProgressLabels.append(DirectLabel(text='', parent=self.trackRows[track], pos=(-0.72 + -0.06825, -0.1, -0.025), scale=TTLocalizer.INtrackNameLabels/2, relief=None, text_fg=(0.2, 0.2, 0.2, 1), text_font=ToontownGlobals.getInterfaceFont(), text_align=TextNode.ALeft, textMayChange=0)) self.buttons.append([]) - for item in xrange(5): + for item in range(5): button = DirectButton(parent=self.trackRows[track], image=(self.upButton, self.downButton, self.rolloverButton, @@ -65,7 +65,7 @@ def clearPage(self): pass def updatePage(self): - for track in xrange(8): + for track in range(8): points = base.localAvatar.getSpentTrainingPoints() points = points[track] if points < 2: @@ -97,7 +97,7 @@ def updateButtons(self): for buttonArray in self.buttons: for button in buttonArray: button['state'] = DGG.DISABLED - for track in xrange(len(pointArray)): + for track in range(len(pointArray)): i = 0 for button in self.buttons[track]: if i == (pointArray[track] - 1) or i >= (pointArray[track] + 1): @@ -108,7 +108,7 @@ def updateButtons(self): button['image_color'] = Vec4(0, 0.6, 1, 1) button['text'] = '0/1' i += 1 - for iteration in xrange(pointArray[track]): + for iteration in range(pointArray[track]): if pointArray[track] == 1: self.buttons[track][iteration]['state'] = DGG.NORMAL self.buttons[track][iteration]['image_color'] = Vec4(0, 0.6, 1, 1) @@ -117,18 +117,18 @@ def updateButtons(self): self.buttons[track][iteration]['image_color'] = Vec4(0.4, 0.4, 0.4, 1) self.buttons[track][iteration]['text'] = '1/1' if pointArray[track] < 2: - for i in xrange(3): + for i in range(3): self.buttons[track][i+2]['state'] = DGG.DISABLED self.buttons[track][i+2]['image_color'] = Vec4(0.4, 0.4, 0.4, 1) self.buttons[track][i+2]['text'] = '0/1' else: - for i in xrange(2): + for i in range(2): self.buttons[track][i+3]['state'] = DGG.DISABLED self.buttons[track][i+3]['image_color'] = Vec4(0.4, 0.4, 0.4, 1) self.buttons[track][i+3]['text'] = '0/1' if av.getTrainingPoints() == 0: if pointArray[track] == 1: - for i in xrange(len(self.buttons[track])): + for i in range(len(self.buttons[track])): if i == 0: pass else: diff --git a/toontown/speedchat/TTSCAprilToonsMenu.py b/toontown/speedchat/TTSCAprilToonsMenu.py index 39f67df3a..7c9c75840 100644 --- a/toontown/speedchat/TTSCAprilToonsMenu.py +++ b/toontown/speedchat/TTSCAprilToonsMenu.py @@ -47,7 +47,7 @@ def __aprilToonsMessagesChanged(self): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link April Toons phrase %s which does not seem to exist' % phrase + print('warning: tried to link April Toons phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -55,7 +55,7 @@ def __aprilToonsMessagesChanged(self): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link April Toons phrase %s which does not seem to exist' % phrase + print('warning: tried to link April Toons phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCBoardingMenu.py b/toontown/speedchat/TTSCBoardingMenu.py index 9729d96a8..d3c11a59f 100644 --- a/toontown/speedchat/TTSCBoardingMenu.py +++ b/toontown/speedchat/TTSCBoardingMenu.py @@ -46,12 +46,12 @@ def __boardingMessagesChanged(self, zoneId): except: return - for count in xrange(len(BoardingMenuGuide)): + for count in range(len(BoardingMenuGuide)): section = BoardingMenuGuide[count] if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link boarding phrase %s which does not seem to exist' % phrase + print('warning: tried to link boarding phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -60,7 +60,7 @@ def __boardingMessagesChanged(self, zoneId): phrases = ZoneIdsToMsgs[zoneId][count] for phrase in phrases: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link boarding phrase %s which does not seem to exist' % phrase + print('warning: tried to link boarding phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCGolfMenu.py b/toontown/speedchat/TTSCGolfMenu.py index bd37c5f51..730ce29eb 100644 --- a/toontown/speedchat/TTSCGolfMenu.py +++ b/toontown/speedchat/TTSCGolfMenu.py @@ -52,7 +52,7 @@ def __golfMessagesChanged(self): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link golf phrase %s which does not seem to exist' % phrase + print('warning: tried to link golf phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -60,7 +60,7 @@ def __golfMessagesChanged(self): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link golf phrase %s which does not seem to exist' % phrase + print('warning: tried to link golf phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCHalloweenMenu.py b/toontown/speedchat/TTSCHalloweenMenu.py index 53e8aeed1..30b3ba6ea 100644 --- a/toontown/speedchat/TTSCHalloweenMenu.py +++ b/toontown/speedchat/TTSCHalloweenMenu.py @@ -28,7 +28,7 @@ def __messagesChanged(self): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Halloween phrase %s which does not seem to exist' % phrase + print('warning: tried to link Halloween phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -36,7 +36,7 @@ def __messagesChanged(self): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Halloween phrase %s which does not seem to exist' % phrase + print('warning: tried to link Halloween phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCIdesOfMarchMenu.py b/toontown/speedchat/TTSCIdesOfMarchMenu.py index a2e4f897d..bb9a5cdd8 100644 --- a/toontown/speedchat/TTSCIdesOfMarchMenu.py +++ b/toontown/speedchat/TTSCIdesOfMarchMenu.py @@ -28,7 +28,7 @@ def __messagesChanged(self): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link IdesOfMarch phrase %s which does not seem to exist' % phrase + print('warning: tried to link IdesOfMarch phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -36,7 +36,7 @@ def __messagesChanged(self): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link IdesOfMarch phrase %s which does not seem to exist' % phrase + print('warning: tried to link IdesOfMarch phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCJellybeanJamMenu.py b/toontown/speedchat/TTSCJellybeanJamMenu.py index 5d275cbdf..cb8f2f50c 100644 --- a/toontown/speedchat/TTSCJellybeanJamMenu.py +++ b/toontown/speedchat/TTSCJellybeanJamMenu.py @@ -23,7 +23,7 @@ def __init__(self, phase): if phase in JellybeanJamPhases: self.__messagesChanged(phase) else: - print 'warning: tried to add Jellybean Jam phase %s which does not seem to exist' % phase + print('warning: tried to add Jellybean Jam phase %s which does not seem to exist' % phase) def destroy(self): SCMenu.destroy(self) @@ -42,7 +42,7 @@ def __messagesChanged(self, phase): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Jellybean Jam phrase %s which does not seem to exist' % phrase + print('warning: tried to link Jellybean Jam phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -50,7 +50,7 @@ def __messagesChanged(self, phase): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Jellybean Jam phrase %s which does not seem to exist' % phrase + print('warning: tried to link Jellybean Jam phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCKartRacingMenu.py b/toontown/speedchat/TTSCKartRacingMenu.py index b570d14d5..24f9b697c 100644 --- a/toontown/speedchat/TTSCKartRacingMenu.py +++ b/toontown/speedchat/TTSCKartRacingMenu.py @@ -90,7 +90,7 @@ def __kartRacingMessagesChanged(self): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link kart phrase %s which does not seem to exist' % phrase + print('warning: tried to link kart phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -98,7 +98,7 @@ def __kartRacingMessagesChanged(self): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link kart phrase %s which does not seem to exist' % phrase + print('warning: tried to link kart phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCResistanceMenu.py b/toontown/speedchat/TTSCResistanceMenu.py index 51bb7c420..a17799e0c 100644 --- a/toontown/speedchat/TTSCResistanceMenu.py +++ b/toontown/speedchat/TTSCResistanceMenu.py @@ -2,7 +2,7 @@ from otp.speedchat.SCMenu import SCMenu from otp.speedchat.SCMenuHolder import SCMenuHolder from toontown.chat import ResistanceChat -from TTSCResistanceTerminal import TTSCResistanceTerminal +from .TTSCResistanceTerminal import TTSCResistanceTerminal class TTSCResistanceMenu(SCMenu): diff --git a/toontown/speedchat/TTSCSellbotFieldOfficeMenu.py b/toontown/speedchat/TTSCSellbotFieldOfficeMenu.py index d13bb7846..b7b6fd7df 100644 --- a/toontown/speedchat/TTSCSellbotFieldOfficeMenu.py +++ b/toontown/speedchat/TTSCSellbotFieldOfficeMenu.py @@ -5,7 +5,7 @@ from toontown.speedchat.TTSCIndexedTerminal import TTSCIndexedTerminal from otp.otpbase import OTPLocalizer from toontown.cogdominium import CogdoInterior -SellbotFieldOfficeMenu = [(OTPLocalizer.SellbotFieldOfficeMenuSections[0], range(30404, 30409)), (OTPLocalizer.SellbotFieldOfficeMenuSections[1], range(30409, 30419))] +SellbotFieldOfficeMenu = [(OTPLocalizer.SellbotFieldOfficeMenuSections[0], list(range(30404, 30409))), (OTPLocalizer.SellbotFieldOfficeMenuSections[1], list(range(30409, 30419)))] class TTSCSellbotFieldOfficeMenu(SCMenu): @@ -31,7 +31,7 @@ def __messagesChanged(self, inSellbotFieldOffice): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Winter phrase %s which does not seem to exist' % phrase + print('warning: tried to link Winter phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -39,7 +39,7 @@ def __messagesChanged(self, inSellbotFieldOffice): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Halloween phrase %s which does not seem to exist' % phrase + print('warning: tried to link Halloween phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCSellbotInvasionMenu.py b/toontown/speedchat/TTSCSellbotInvasionMenu.py index 8ca1c726b..c86ac3bf3 100644 --- a/toontown/speedchat/TTSCSellbotInvasionMenu.py +++ b/toontown/speedchat/TTSCSellbotInvasionMenu.py @@ -4,7 +4,7 @@ from otp.speedchat.SCStaticTextTerminal import SCStaticTextTerminal from toontown.speedchat.TTSCIndexedTerminal import TTSCIndexedTerminal from otp.otpbase import OTPLocalizer -SellbotInvasionMenu = [(OTPLocalizer.SellbotInvasionMenuSections[0], range(30400, 30404))] +SellbotInvasionMenu = [(OTPLocalizer.SellbotInvasionMenuSections[0], list(range(30400, 30404)))] class TTSCSellbotInvasionMenu(SCMenu): @@ -29,7 +29,7 @@ def __messagesChanged(self): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Winter phrase %s which does not seem to exist' % phrase + print('warning: tried to link Winter phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -37,7 +37,7 @@ def __messagesChanged(self): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Halloween phrase %s which does not seem to exist' % phrase + print('warning: tried to link Halloween phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCSellbotNerfMenu.py b/toontown/speedchat/TTSCSellbotNerfMenu.py index 7f6081d85..f842024db 100644 --- a/toontown/speedchat/TTSCSellbotNerfMenu.py +++ b/toontown/speedchat/TTSCSellbotNerfMenu.py @@ -51,7 +51,7 @@ def __messagesChanged(self): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Sellbot Nerf phrase %s which does not seem to exist' % phrase + print('warning: tried to link Sellbot Nerf phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -59,7 +59,7 @@ def __messagesChanged(self): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Sellbot Nerf phrase %s which does not seem to exist' % phrase + print('warning: tried to link Sellbot Nerf phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCSillyPhaseFiveMenu.py b/toontown/speedchat/TTSCSillyPhaseFiveMenu.py index afc842a1e..d77fe9209 100644 --- a/toontown/speedchat/TTSCSillyPhaseFiveMenu.py +++ b/toontown/speedchat/TTSCSillyPhaseFiveMenu.py @@ -33,7 +33,7 @@ def __SillyPhaseFiveMessagesChanged(self): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Silly PhaseFive phrase %s which does not seem to exist' % phrase + print('warning: tried to link Silly PhaseFive phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -41,7 +41,7 @@ def __SillyPhaseFiveMessagesChanged(self): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Silly PhaseFive phrase %s which does not seem to exist' % phrase + print('warning: tried to link Silly PhaseFive phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCSillyPhaseFourMenu.py b/toontown/speedchat/TTSCSillyPhaseFourMenu.py index 600d60710..ae4721705 100644 --- a/toontown/speedchat/TTSCSillyPhaseFourMenu.py +++ b/toontown/speedchat/TTSCSillyPhaseFourMenu.py @@ -32,7 +32,7 @@ def __SillyPhaseFourMessagesChanged(self): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Silly PhaseFour phrase %s which does not seem to exist' % phrase + print('warning: tried to link Silly PhaseFour phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -40,7 +40,7 @@ def __SillyPhaseFourMessagesChanged(self): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Silly PhaseFour phrase %s which does not seem to exist' % phrase + print('warning: tried to link Silly PhaseFour phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCSillyPhaseOneMenu.py b/toontown/speedchat/TTSCSillyPhaseOneMenu.py index e2612fd20..ede3c14ca 100644 --- a/toontown/speedchat/TTSCSillyPhaseOneMenu.py +++ b/toontown/speedchat/TTSCSillyPhaseOneMenu.py @@ -32,7 +32,7 @@ def __SillyPhaseOneMessagesChanged(self): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Silly PhaseOne phrase %s which does not seem to exist' % phrase + print('warning: tried to link Silly PhaseOne phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -40,7 +40,7 @@ def __SillyPhaseOneMessagesChanged(self): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Silly PhaseOne phrase %s which does not seem to exist' % phrase + print('warning: tried to link Silly PhaseOne phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCSillyPhaseThreeMenu.py b/toontown/speedchat/TTSCSillyPhaseThreeMenu.py index 85cfc8d1e..8209c7645 100644 --- a/toontown/speedchat/TTSCSillyPhaseThreeMenu.py +++ b/toontown/speedchat/TTSCSillyPhaseThreeMenu.py @@ -37,7 +37,7 @@ def __SillyPhaseThreeMessagesChanged(self): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Silly PhaseThree phrase %s which does not seem to exist' % phrase + print('warning: tried to link Silly PhaseThree phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -45,7 +45,7 @@ def __SillyPhaseThreeMessagesChanged(self): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Silly PhaseThree phrase %s which does not seem to exist' % phrase + print('warning: tried to link Silly PhaseThree phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCSillyPhaseTwoMenu.py b/toontown/speedchat/TTSCSillyPhaseTwoMenu.py index c916a05e7..7a231d568 100644 --- a/toontown/speedchat/TTSCSillyPhaseTwoMenu.py +++ b/toontown/speedchat/TTSCSillyPhaseTwoMenu.py @@ -34,7 +34,7 @@ def __SillyPhaseTwoMessagesChanged(self): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Silly PhaseTwo phrase %s which does not seem to exist' % phrase + print('warning: tried to link Silly PhaseTwo phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -42,7 +42,7 @@ def __SillyPhaseTwoMessagesChanged(self): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Silly PhaseTwo phrase %s which does not seem to exist' % phrase + print('warning: tried to link Silly PhaseTwo phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCSingingMenu.py b/toontown/speedchat/TTSCSingingMenu.py index 131da01b9..e428bfab4 100644 --- a/toontown/speedchat/TTSCSingingMenu.py +++ b/toontown/speedchat/TTSCSingingMenu.py @@ -32,17 +32,17 @@ def __singingMessagesChanged(self): except: return - for count in xrange(len(SingingMenuGuide)): + for count in range(len(SingingMenuGuide)): section = SingingMenuGuide[count] if section[0] == -1: for phrase in section[1]: emote = None if type(phrase) == type({}): - item = phrase.keys()[0] + item = list(phrase.keys())[0] emote = phrase[item] phrase = item if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link a singing phrase %s which does not seem to exist' % phrase + print('warning: tried to link a singing phrase %s which does not seem to exist' % phrase) break terminal = TTSCSingingTerminal(phrase) if emote is not None: diff --git a/toontown/speedchat/TTSCToontaskMenu.py b/toontown/speedchat/TTSCToontaskMenu.py index 259e618be..8fabb3626 100644 --- a/toontown/speedchat/TTSCToontaskMenu.py +++ b/toontown/speedchat/TTSCToontaskMenu.py @@ -36,7 +36,7 @@ def addTerminal(terminal, self = self, phrases = phrases): msgs = q.getSCStrings(toNpcId, toonProgress) if type(msgs) != type([]): msgs = [msgs] - for i in xrange(len(msgs)): + for i in range(len(msgs)): addTerminal(TTSCToontaskTerminal(msgs[i], taskId, toNpcId, toonProgress, i)) needToontask = 1 diff --git a/toontown/speedchat/TTSCVictoryPartiesMenu.py b/toontown/speedchat/TTSCVictoryPartiesMenu.py index fb76b3ac3..5b88be692 100644 --- a/toontown/speedchat/TTSCVictoryPartiesMenu.py +++ b/toontown/speedchat/TTSCVictoryPartiesMenu.py @@ -41,7 +41,7 @@ def __messagesChanged(self): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Victory Parties phrase %s which does not seem to exist' % phrase + print('warning: tried to link Victory Parties phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) @@ -49,7 +49,7 @@ def __messagesChanged(self): menu = SCMenu() for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Victory Parties phrase %s which does not seem to exist' % phrase + print('warning: tried to link Victory Parties phrase %s which does not seem to exist' % phrase) break menu.append(SCStaticTextTerminal(phrase)) diff --git a/toontown/speedchat/TTSCWinterMenu.py b/toontown/speedchat/TTSCWinterMenu.py index 89d043612..33e479421 100644 --- a/toontown/speedchat/TTSCWinterMenu.py +++ b/toontown/speedchat/TTSCWinterMenu.py @@ -38,16 +38,16 @@ def __messagesChanged(self, carol): if section[0] == -1: for phrase in section[1]: if phrase not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Winter phrase %s which does not seem to exist' % phrase + print('warning: tried to link Winter phrase %s which does not seem to exist' % phrase) break self.append(SCStaticTextTerminal(phrase)) else: menu = SCMenu() - for phrase in section[1].keys(): + for phrase in list(section[1].keys()): blatherTxt = section[1][phrase] if blatherTxt not in OTPLocalizer.SpeedChatStaticText: - print 'warning: tried to link Winter phrase %s which does not seem to exist' % phrase + print('warning: tried to link Winter phrase %s which does not seem to exist' % phrase) break menu.append(TTSCIndexedTerminal(OTPLocalizer.SpeedChatStaticText.get(phrase, None), blatherTxt)) diff --git a/toontown/suit/BossCog.py b/toontown/suit/BossCog.py index a0752de29..940f1073b 100644 --- a/toontown/suit/BossCog.py +++ b/toontown/suit/BossCog.py @@ -588,7 +588,7 @@ def getAnim(self, anim): self.raised = 1 elif anim == 'Fb_fall': ival = Parallel(ActorInterval(self, 'Fb_fall'), Sequence(SoundInterval(self.reelSfx, node=self), SoundInterval(self.deathSfx))) - elif isinstance(anim, types.StringType): + elif isinstance(anim, bytes): ival = ActorInterval(self, anim) else: ival = anim diff --git a/toontown/suit/DistributedBoardbotBoss.py b/toontown/suit/DistributedBoardbotBoss.py index 979edf548..3be1eb8b0 100644 --- a/toontown/suit/DistributedBoardbotBoss.py +++ b/toontown/suit/DistributedBoardbotBoss.py @@ -82,7 +82,7 @@ def announceGenerate(self): self.piesRestockSfx = loader.loadSfx('phase_9/audio/sfx/CHQ_SOS_pies_restock.ogg') self.rampSlideSfx = loader.loadSfx('phase_9/audio/sfx/CHQ_VP_ramp_slide.ogg') self.strafeSfx = [] - for i in xrange(10): + for i in range(10): self.strafeSfx.append(loader.loadSfx('phase_3.5/audio/sfx/SA_shred.ogg')) render.setTag('pieCode', str(ToontownGlobals.PieCodeNotBossCog)) @@ -1086,7 +1086,7 @@ def __arrangeToonsAroundCage(self): radius = 15 numToons = len(self.involvedToons) center = (numToons - 1) / 2.0 - for i in xrange(numToons): + for i in range(numToons): toon = base.cr.doId2do.get(self.involvedToons[i]) if toon: angle = 270 - 15 * (i - center) @@ -1117,7 +1117,7 @@ def doorBCallback(self, isOpen): def __toonsToPromotionPosition(self, toonIds, battleNode): points = BattleBase.BattleBase.toonPoints[len(toonIds) - 1] - for i in xrange(len(toonIds)): + for i in range(len(toonIds)): toon = base.cr.doId2do.get(toonIds[i]) if toon: toon.reparentTo(render) @@ -1126,7 +1126,7 @@ def __toonsToPromotionPosition(self, toonIds, battleNode): def __doobersToPromotionPosition(self, doobers, battleNode): points = BattleBase.BattleBase.toonPoints[len(doobers) - 1] - for i in xrange(len(doobers)): + for i in range(len(doobers)): suit = doobers[i] suit.fsm.request('neutral') suit.loop('neutral') @@ -1232,7 +1232,7 @@ def doStrafe(self, side, direction): spread = -spread dist = 50 rate = time / numGears - for i in xrange(numGears): + for i in range(numGears): node = gearRoot.attachNewNode(str(i)) node.hide() node.setPos(0, 0, 0) diff --git a/toontown/suit/DistributedBoardbotBossAI.py b/toontown/suit/DistributedBoardbotBossAI.py index 5390efd8f..801c97811 100644 --- a/toontown/suit/DistributedBoardbotBossAI.py +++ b/toontown/suit/DistributedBoardbotBossAI.py @@ -25,11 +25,11 @@ def __init__(self, air): self.doobers = [] if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays: if random.random() <= 0.25: - self.cagedToonNpcId = random.choice(NPCToons.AprilToonsFriends.keys()) + self.cagedToonNpcId = random.choice(list(NPCToons.AprilToonsFriends.keys())) else: - self.cagedToonNpcId = random.choice(NPCToons.HQnpcFriends.keys()) + self.cagedToonNpcId = random.choice(list(NPCToons.HQnpcFriends.keys())) else: - self.cagedToonNpcId = random.choice(NPCToons.HQnpcFriends.keys()) + self.cagedToonNpcId = random.choice(list(NPCToons.HQnpcFriends.keys())) self.bossMaxDamage = ToontownGlobals.SellbotBossMaxDamage self.recoverRate = 0 self.recoverStartTime = 0 @@ -416,7 +416,7 @@ def __resetDoobers(self): def __makeDoobers(self): self.__resetDoobers() - for i in xrange(8): + for i in range(8): suit = DistributedSuitAI.DistributedSuitAI(self.air, None) level = random.randrange(len(SuitDNA.suitsPerLevel)) suit.dna = SuitDNA.SuitDNA() @@ -457,7 +457,7 @@ def skipChairman(): """ invoker = spellbook.getInvoker() boss = None - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): if isinstance(do, DistributedBoardbotBossAI): if invoker.doId in do.involvedToons: boss = do @@ -477,7 +477,7 @@ def killChairman(): """ invoker = spellbook.getInvoker() boss = None - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): if isinstance(do, DistributedBoardbotBossAI): if invoker.doId in do.involvedToons: boss = do diff --git a/toontown/suit/DistributedBossCog.py b/toontown/suit/DistributedBossCog.py index 0687ebbbb..90357d3fe 100644 --- a/toontown/suit/DistributedBossCog.py +++ b/toontown/suit/DistributedBossCog.py @@ -200,7 +200,7 @@ def storeInterval(self, interval, name): self.activeIntervals[name] = interval def cleanupIntervals(self): - for interval in self.activeIntervals.values(): + for interval in list(self.activeIntervals.values()): interval.finish() DelayDelete.cleanupDelayDeletes(interval) @@ -492,7 +492,7 @@ def rollBoss(self, t, fromPos, deltaPos): self.cqueue.sortEntries() numEntries = self.cqueue.getNumEntries() if numEntries != 0: - for i in xrange(self.cqueue.getNumEntries() - 1, -1, -1): + for i in range(self.cqueue.getNumEntries() - 1, -1, -1): entry = self.cqueue.getEntry(i) solid = entry.getFrom() if solid == self.ray1: @@ -650,7 +650,7 @@ def localToonDied(self): def toonsToBattlePosition(self, toonIds, battleNode): points = BattleBase.BattleBase.toonPoints[len(toonIds) - 1] self.notify.debug('toonsToBattlePosition: points = %s' % points[0][0]) - for i in xrange(len(toonIds)): + for i in range(len(toonIds)): toon = base.cr.doId2do.get(toonIds[i]) if toon: toon.reparentTo(render) @@ -854,7 +854,7 @@ def backupToonsToBattlePosition(self, toonIds, battleNode): self.notify.debug('backupToonsToBattlePosition:') ival = Parallel() points = BattleBase.BattleBase.toonPoints[len(toonIds) - 1] - for i in xrange(len(toonIds)): + for i in range(len(toonIds)): toon = base.cr.doId2do.get(toonIds[i]) if toon: pos, h = points[i] @@ -907,7 +907,7 @@ def doDirectedAttack(self, avId, attackCode): if not self.twoFaced: neutral = 'Ff_neutral' gearTrack = Parallel() - for i in xrange(4): + for i in range(4): node = gearRoot.attachNewNode(str(i)) node.hide() node.setPos(0, 5.85, 4.0) @@ -1116,7 +1116,7 @@ def exitFrolic(self): pass def setToonsToNeutral(self, toonIds): - for i in xrange(len(toonIds)): + for i in range(len(toonIds)): toon = base.cr.doId2do.get(toonIds[i]) if toon: if toon.isDisguised: diff --git a/toontown/suit/DistributedBossCogAI.py b/toontown/suit/DistributedBossCogAI.py index b897f8339..8aeda8e15 100644 --- a/toontown/suit/DistributedBossCogAI.py +++ b/toontown/suit/DistributedBossCogAI.py @@ -505,7 +505,7 @@ def invokeSuitPlanner(self, buildingCode, skelecog, skelecogRandom=0, dept=None) return suits def generateSuits(self, battleNumber): - raise StandardError, 'generateSuits unimplemented' + raise Exception('generateSuits unimplemented') def handleRoundDone(self, battle, suits, activeSuits, toonIds, totalHp, deadSuits): totalMaxHp = 0 diff --git a/toontown/suit/DistributedBossbotBoss.py b/toontown/suit/DistributedBossbotBoss.py index 9239314c7..0c3c77919 100644 --- a/toontown/suit/DistributedBossbotBoss.py +++ b/toontown/suit/DistributedBossbotBoss.py @@ -178,7 +178,7 @@ def unloadEnvironment(self): if belt: belt.cleanup() - for spot in self.golfSpots.values(): + for spot in list(self.golfSpots.values()): if spot: spot.cleanup() @@ -401,7 +401,7 @@ def __arrangeToonsAroundResistanceToon(self): radius = 9 numToons = len(self.involvedToons) center = (numToons - 1) / 2.0 - for i in xrange(numToons): + for i in range(numToons): toon = self.cr.doId2do.get(self.involvedToons[i]) if toon: angle = 90 - 25 * (i - center) @@ -545,7 +545,7 @@ def enterPrepareBattleThree(self): def calcNotDeadList(self): if not self.notDeadList: self.notDeadList = [] - for tableIndex in xrange(len(self.tables)): + for tableIndex in range(len(self.tables)): table = self.tables[tableIndex] tableInfo = table.getNotDeadInfo() self.notDeadList += tableInfo @@ -584,7 +584,7 @@ def makePrepareBattleThreeMovie(self): def enterBattleThree(self): self.cleanupIntervals() self.calcNotDeadList() - for table in self.tables.values(): + for table in list(self.tables.values()): table.setAllDinersToSitNeutral() self.battleANode.setPosHpr(*ToontownGlobals.DinerBattleAPosHpr) @@ -862,7 +862,7 @@ def __arrangeToonsAroundResistanceToonForReward(self): radius = 7 numToons = len(self.involvedToons) center = (numToons - 1) / 2.0 - for i in xrange(numToons): + for i in range(numToons): toon = self.cr.doId2do.get(self.involvedToons[i]) if toon: angle = 90 - 15 * (i - center) @@ -890,7 +890,7 @@ def doDirectedAttack(self, avId, attackCode): if not self.twoFaced: neutral = 'Ff_neutral' gearTrack = Parallel() - for i in xrange(4): + for i in range(4): nodeName = '%s-%s' % (str(i), globalClock.getFrameTime()) node = gearRoot.attachNewNode(nodeName) node.hide() @@ -1249,7 +1249,7 @@ def zapLocalToon(self, attackCode, origin = None): def getToonTableIndex(self, toonId): tableIndex = -1 - for table in self.tables.values(): + for table in list(self.tables.values()): if table.avId == toonId: tableIndex = table.index break @@ -1258,7 +1258,7 @@ def getToonTableIndex(self, toonId): def getToonGolfSpotIndex(self, toonId): golfSpotIndex = -1 - for golfSpot in self.golfSpots.values(): + for golfSpot in list(self.golfSpots.values()): if golfSpot.avId == toonId: golfSpotIndex = golfSpot.index break @@ -1312,7 +1312,7 @@ def doGolfAttack(self, avId, attackCode): if not self.twoFaced: neutral = 'Ff_neutral' gearTrack = Parallel() - for i in xrange(5): + for i in range(5): nodeName = '%s-%s' % (str(i), globalClock.getFrameTime()) node = gearRoot.attachNewNode(nodeName) node.hide() @@ -1406,7 +1406,7 @@ def doGolfAreaAttack(self): ballLaunch.reparentTo(gearRoot) ballLaunch.setPos(self.BallLaunchOffset) gearTrack = Parallel() - for i in xrange(5): + for i in range(5): nodeName = '%s-%s' % (str(i), globalClock.getFrameTime()) node = gearRoot.attachNewNode(nodeName) node.hide() @@ -1521,7 +1521,7 @@ def doOvertimeAttack(self, index): neutral = 'Ff_neutral' gearTrack = Parallel() - for i in xrange(4): + for i in range(4): node = gearRoot.attachNewNode(str(i)) node.hide() node.setPos(0, 5.85, 4.0) diff --git a/toontown/suit/DistributedBossbotBossAI.py b/toontown/suit/DistributedBossbotBossAI.py index 0f7142d34..eaaca5c82 100644 --- a/toontown/suit/DistributedBossbotBossAI.py +++ b/toontown/suit/DistributedBossbotBossAI.py @@ -218,7 +218,7 @@ def exitPrepareBattleTwo(self): def createFoodBelts(self): if self.foodBelts: return - for i in xrange(2): + for i in range(2): newBelt = DistributedFoodBeltAI.DistributedFoodBeltAI(self.air, self, i) self.foodBelts.append(newBelt) newBelt.generateWithRequired(self.zoneId) @@ -238,7 +238,7 @@ def createBanquetTables(self): self.numTables = diffInfo[0] self.numDinersPerTable = diffInfo[1] dinerLevel = diffInfo[2] - for i in xrange(self.numTables): + for i in range(self.numTables): newTable = DistributedBanquetTableAI.DistributedBanquetTableAI(self.air, self, i, self.numDinersPerTable, dinerLevel) self.tables.append(newTable) newTable.generateWithRequired(self.zoneId) @@ -277,7 +277,7 @@ def requestGetFood(self, beltIndex, foodIndex, foodNum): avId = self.air.getAvatarIdFromSender() if self.state != 'BattleTwo': grantRequest = False - elif (beltIndex, foodNum) not in self.toonFoodStatus.values(): + elif (beltIndex, foodNum) not in list(self.toonFoodStatus.values()): if avId not in self.toonFoodStatus: grantRequest = True elif self.toonFoodStatus[avId] == None: @@ -338,7 +338,7 @@ def makeBattleThreeBattles(self): def generateDinerSuits(self): diners = [] - for i in xrange(len(self.notDeadList)): + for i in range(len(self.notDeadList)): if simbase.config.GetBool('bossbot-boss-cheat', 0): suit = self.__genSuitObject(self.zoneId, 2, 'c', 2, 0) else: @@ -350,7 +350,7 @@ def generateDinerSuits(self): diners.append((suit, 100)) active = [] - for i in xrange(2): + for i in range(2): if simbase.config.GetBool('bossbot-boss-cheat', 0): suit = self.__genSuitObject(self.zoneId, 2, 'c', 2, 0) else: @@ -544,7 +544,7 @@ def d_setSpeedDamage(self, speedDamage, recoverRate, recoverStartTime): def createGolfSpots(self): if self.golfSpots: return - for i in xrange(self.numGolfSpots): + for i in range(self.numGolfSpots): newGolfSpot = DistributedGolfSpotAI.DistributedGolfSpotAI(self.air, self, i) self.golfSpots.append(newGolfSpot) newGolfSpot.generateWithRequired(self.zoneId) @@ -943,7 +943,7 @@ def skipCEO(): """ invoker = spellbook.getInvoker() boss = None - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): if isinstance(do, DistributedBossbotBossAI): if invoker.doId in do.involvedToons: boss = do @@ -962,7 +962,7 @@ def skipCEOFinal(): """ invoker = spellbook.getInvoker() boss = None - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): if isinstance(do, DistributedBossbotBossAI): if invoker.doId in do.involvedToons: boss = do @@ -982,7 +982,7 @@ def killCEO(): """ invoker = spellbook.getInvoker() boss = None - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): if isinstance(do, DistributedBossbotBossAI): if invoker.doId in do.involvedToons: boss = do diff --git a/toontown/suit/DistributedCashbotBoss.py b/toontown/suit/DistributedCashbotBoss.py index 817365010..5add21d78 100644 --- a/toontown/suit/DistributedCashbotBoss.py +++ b/toontown/suit/DistributedCashbotBoss.py @@ -131,7 +131,7 @@ def __makeResistanceToon(self): self.resistanceToon.setDisplayName(TTLocalizer.ResistanceToonName) random.setstate(state) self.fakeGoons = [] - for i in xrange(self.numFakeGoons): + for i in range(self.numFakeGoons): goon = DistributedCashbotBossGoon.DistributedCashbotBossGoon(base.cr) goon.doId = -1 - i goon.setBossCogId(self.doId) @@ -147,7 +147,7 @@ def __cleanupResistanceToon(self): self.resistanceToon.removeActive() self.resistanceToon.delete() self.resistanceToon = None - for i in xrange(self.numFakeGoons): + for i in range(self.numFakeGoons): self.fakeGoons[i].disable() self.fakeGoons[i].delete() self.fakeGoons[i] = None @@ -257,7 +257,7 @@ def replaceCollisionPolysWithPlanes(self, model): self.notify.warning('Not a collision node: %s' % repr(cnp)) break newCollideMask = newCollideMask | cn.getIntoCollideMask() - for i in xrange(cn.getNumSolids()): + for i in range(cn.getNumSolids()): solid = cn.getSolid(i) if isinstance(solid, CollisionPolygon): plane = Plane(solid.getPlane()) @@ -497,7 +497,7 @@ def __makeGoonMovieForBattleThree(self): VBase3(231, 0, 0)]] mainGoon = self.fakeGoons[0] goonLoop = Parallel() - for i in xrange(1, self.numFakeGoons): + for i in range(1, self.numFakeGoons): goon = self.fakeGoons[i] goonLoop.append(Sequence(goon.posHprInterval(8, goonPosHprs[i][0], goonPosHprs[i][1]), goon.posHprInterval(8, goonPosHprs[i][2], goonPosHprs[i][3]))) @@ -575,7 +575,7 @@ def makePrepareBattleThreeMovie(self, delayDeletes, crane, safe): def moveToonsToBattleThreePos(self, toons): track = Parallel() - for i in xrange(len(toons)): + for i in range(len(toons)): toon = base.cr.doId2do.get(toons[i]) if toon: posHpr = ToontownGlobals.CashbotToonsBattleThreeStartPosHpr[i] @@ -701,17 +701,17 @@ def destroyAllGoons(self): goon.b_destroyGoon() def deactivateCranes(self): - for crane in self.cranes.values(): + for crane in list(self.cranes.values()): crane.demand('Free') def hideBattleThreeObjects(self): for goon in self.goons: goon.demand('Off') - for safe in self.safes.values(): + for safe in list(self.safes.values()): safe.demand('Off') - for crane in self.cranes.values(): + for crane in list(self.cranes.values()): crane.demand('Off') def __doPhysics(self, task): @@ -735,7 +735,7 @@ def __arrangeToonsAroundResistanceToon(self): radius = 7 numToons = len(self.involvedToons) center = (numToons - 1) / 2.0 - for i in xrange(numToons): + for i in range(numToons): toon = self.cr.doId2do.get(self.involvedToons[i]) if toon: angle = 90 - 15 * (i - center) diff --git a/toontown/suit/DistributedCashbotBossAI.py b/toontown/suit/DistributedCashbotBossAI.py index 9a2ac7f3c..afca65757 100644 --- a/toontown/suit/DistributedCashbotBossAI.py +++ b/toontown/suit/DistributedCashbotBossAI.py @@ -88,14 +88,14 @@ def removeToon(self, avId): def __makeBattleThreeObjects(self): if self.cranes == None: self.cranes = [] - for index in xrange(len(ToontownGlobals.CashbotBossCranePosHprs)): + for index in range(len(ToontownGlobals.CashbotBossCranePosHprs)): crane = DistributedCashbotBossCraneAI.DistributedCashbotBossCraneAI(self.air, self, index) crane.generateWithRequired(self.zoneId) self.cranes.append(crane) if self.safes == None: self.safes = [] - for index in xrange(len(ToontownGlobals.CashbotBossSafePosHprs)): + for index in range(len(ToontownGlobals.CashbotBossSafePosHprs)): safe = DistributedCashbotBossSafeAI.DistributedCashbotBossSafeAI(self.air, self, index) safe.generateWithRequired(self.zoneId) self.safes.append(safe) @@ -210,11 +210,11 @@ def __recycleTreasure(self, treasure): self.recycledTreasures.append(treasure) def deleteAllTreasures(self): - for treasure in self.treasures.values(): + for treasure in list(self.treasures.values()): treasure.requestDelete() self.treasures = {} - for treasure in self.grabbingTreasures.values(): + for treasure in list(self.grabbingTreasures.values()): taskMgr.remove(treasure.uniqueName('recycleTreasure')) treasure.requestDelete() @@ -623,7 +623,7 @@ def __doneVictory(self, avIds): if toon: toon.addResistanceMessage(self.rewardId) if self.bonusUnites: - for x in xrange(self.bonusUnites): + for x in range(self.bonusUnites): toon.addResistanceMessage(ResistanceChat.getRandomId()) toon.b_promote(self.deptIndex) toon.addStat(ToontownGlobals.STATS_CFO) @@ -649,7 +649,7 @@ def restartCraneRound(): """ invoker = spellbook.getInvoker() boss = None - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): if isinstance(do, DistributedCashbotBossAI): if invoker.doId in do.involvedToons: boss = do @@ -669,7 +669,7 @@ def skipCFO(): """ invoker = spellbook.getInvoker() boss = None - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): if isinstance(do, DistributedCashbotBossAI): if invoker.doId in do.involvedToons: boss = do @@ -689,7 +689,7 @@ def cfo2(): """ invoker = spellbook.getInvoker() boss = None - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): if isinstance(do, DistributedCashbotBossAI): if invoker.doId in do.involvedToons: boss = do @@ -707,7 +707,7 @@ def killCFO(): """ invoker = spellbook.getInvoker() boss = None - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): if isinstance(do, DistributedCashbotBossAI): if invoker.doId in do.involvedToons: boss = do diff --git a/toontown/suit/DistributedCashbotBossGoonAI.py b/toontown/suit/DistributedCashbotBossGoonAI.py index b5dd99cfe..d0ff38823 100644 --- a/toontown/suit/DistributedCashbotBossGoonAI.py +++ b/toontown/suit/DistributedCashbotBossGoonAI.py @@ -105,7 +105,7 @@ def __chooseDirection(self): self.tubeNode.setIntoCollideMask(self.onMask) entries = {} self.cQueue.sortEntries() - for i in xrange(self.cQueue.getNumEntries() - 1, -1, -1): + for i in range(self.cQueue.getNumEntries() - 1, -1, -1): entry = self.cQueue.getEntry(i) dist = Vec3(entry.getSurfacePoint(self)).length() if dist < 1.2: @@ -114,7 +114,7 @@ def __chooseDirection(self): netScore = 0 scoreTable = [] - for i in xrange(len(self.directionTable)): + for i in range(len(self.directionTable)): heading, weight = self.directionTable[i] seg = self.feelers[i] dist = entries.get(seg, self.feelerLength) @@ -126,7 +126,7 @@ def __chooseDirection(self): self.notify.info('Could not find a path for %s' % self.doId) return None s = random.uniform(0, netScore) - for i in xrange(len(self.directionTable)): + for i in range(len(self.directionTable)): s -= scoreTable[i] if s <= 0: heading, weight = self.directionTable[i] diff --git a/toontown/suit/DistributedFactorySuit.py b/toontown/suit/DistributedFactorySuit.py index b4d532543..866635afd 100644 --- a/toontown/suit/DistributedFactorySuit.py +++ b/toontown/suit/DistributedFactorySuit.py @@ -429,7 +429,7 @@ def setVirtual(self, isVirtual = 1): actorNode = self.find('**/__Actor_modelRoot') actorCollection = actorNode.findAllMatches('*') parts = () - for thingIndex in xrange(0, actorCollection.getNumPaths()): + for thingIndex in range(0, actorCollection.getNumPaths()): thing = actorCollection[thingIndex] if thing.getName() not in ('joint_attachMeter', 'joint_nameTag', 'def_nameTag'): thing.setColorScale(1.0, 0.0, 0.0, 1.0) diff --git a/toontown/suit/DistributedGoonAI.py b/toontown/suit/DistributedGoonAI.py index 0c6e198d3..f92008d98 100644 --- a/toontown/suit/DistributedGoonAI.py +++ b/toontown/suit/DistributedGoonAI.py @@ -132,7 +132,7 @@ def setParameterize(self, x, y, z, pathIndex): t = 0 self.tSeg = [t] self.pathSeg = [] - for i in xrange(len(pathPts) - 1): + for i in range(len(pathPts) - 1): ptA = pathPts[i] ptB = pathPts[i + 1] t += T_TURN @@ -149,7 +149,7 @@ def setParameterize(self, x, y, z, pathIndex): self.parameterized = 1 def getPathPoint(self, t): - for i in xrange(len(self.tSeg) - 1): + for i in range(len(self.tSeg) - 1): if t >= self.tSeg[i] and t < self.tSeg[i + 1]: tSeg = t - self.tSeg[i] t = tSeg / (self.tSeg[i + 1] - self.tSeg[i]) diff --git a/toontown/suit/DistributedLawbotBoss.py b/toontown/suit/DistributedLawbotBoss.py index 1f929df61..22ae30dbb 100644 --- a/toontown/suit/DistributedLawbotBoss.py +++ b/toontown/suit/DistributedLawbotBoss.py @@ -103,7 +103,7 @@ def announceGenerate(self): self.juryMovesSfx = loader.loadSfx('phase_11/audio/sfx/LB_jury_moves.ogg') self.toonUpSfx = loader.loadSfx('phase_11/audio/sfx/LB_toonup.ogg') self.strafeSfx = [] - for i in xrange(10): + for i in range(10): self.strafeSfx.append(loader.loadSfx('phase_3.5/audio/sfx/SA_shred.ogg')) render.setTag('pieCode', str(ToontownGlobals.PieCodeNotBossCog)) @@ -219,7 +219,7 @@ def setLawyerIds(self, lawyerIds): def __gotLawyers(self, lawyers): self.lawyerRequest = None self.lawyers = lawyers - for i in xrange(len(self.lawyers)): + for i in range(len(self.lawyers)): suit = self.lawyers[i] suit.fsm.request('neutral') suit.loop('neutral') @@ -847,7 +847,7 @@ def enterBattleTwo(self): self.toonsToBattlePosition(self.toonsB, self.battleBNode) base.playMusic(self.battleTwoMusic, looping=1, volume=0.9) self.startJuryBoxMoving() - for index in xrange(len(self.cannons)): + for index in range(len(self.cannons)): cannon = self.cannons[index] cannon.cannon.show() @@ -876,7 +876,7 @@ def exitBattleTwo(self): self.juryTimer.destroy() del self.juryTimer self.juryTimer = None - for chair in self.chairs.values(): + for chair in list(self.chairs.values()): chair.stopCogsFlying() return @@ -1189,7 +1189,7 @@ def doorBCallback(self, isOpen): def __toonsToPromotionPosition(self, toonIds, battleNode): self.notify.debug('----- __toonsToPromotionPosition') points = BattleBase.BattleBase.toonPoints[len(toonIds) - 1] - for i in xrange(len(toonIds)): + for i in range(len(toonIds)): toon = base.cr.doId2do.get(toonIds[i]) if toon: toon.reparentTo(render) @@ -1314,7 +1314,7 @@ def doStrafe(self, side, direction): spread = -spread dist = 50 rate = time / numGears - for i in xrange(numGears): + for i in range(numGears): node = gearRoot.attachNewNode(str(i)) node.hide() node.setPos(0, 0, 0) @@ -1343,7 +1343,7 @@ def replaceCollisionPolysWithPlanes(self, model): self.notify.warning('Not a collision node: %s' % repr(cnp)) break newCollideMask = newCollideMask | cn.getIntoCollideMask() - for i in xrange(cn.getNumSolids()): + for i in range(cn.getNumSolids()): solid = cn.getSolid(i) if isinstance(solid, CollisionPolygon): plane = Plane(solid.getPlane()) @@ -1405,7 +1405,7 @@ def walkToonsToBattlePosition(self, toonIds, battleNode): ival = Parallel() points = BattleBase.BattleBase.toonPoints[len(toonIds) - 1] self.notify.debug('walkToonsToBattlePosition: points = %s' % points[0][0]) - for i in xrange(len(toonIds)): + for i in range(len(toonIds)): toon = base.cr.doId2do.get(toonIds[i]) if toon: pos, h = points[i] @@ -1438,7 +1438,7 @@ def toonsToBattlePosition(self, toonIds, battleNode): points = list(BattleBase.BattleBase.toonPoints[3]) points.extend(BattleBase.BattleBase.toonPoints[len(toonIds) - 5]) self.notify.debug('toonsToBattlePosition: points = %s' % points[0][0]) - for i in xrange(len(toonIds)): + for i in range(len(toonIds)): toon = base.cr.doId2do.get(toonIds[i]) if toon: toon.wrtReparentTo(render) @@ -1486,7 +1486,7 @@ def createBlock(self, x1, y1, z1, x2, y2, z2, r = 1.0, g = 1.0, b = 1.0, a = 1.0 vertexWriter.addData3f(x2, y1, z2) vertexWriter.addData3f(x1, y2, z2) vertexWriter.addData3f(x2, y2, z2) - for index in xrange(8): + for index in range(8): normalWriter.addData3f(1.0, 1.0, 1.0) colorWriter.addData4f(r, g, b, a) texWriter.addData2f(1.0, 1.0) @@ -1661,7 +1661,7 @@ def __arrangeToonsAroundWitnessToon(self): radius = 7 numToons = len(self.involvedToons) center = (numToons - 1) / 2.0 - for i in xrange(numToons): + for i in range(numToons): toon = self.cr.doId2do.get(self.involvedToons[i]) if toon: angle = 90 - 15 * (i - center) @@ -1751,7 +1751,7 @@ def __makePrepareBattleThreeMovie(self): def countToonJurors(self): self.numToonJurorsSeated = 0 - for key in self.chairs.keys(): + for key in list(self.chairs.keys()): chair = self.chairs[key] if chair.state == 'ToonJuror' or chair.state == None and chair.newState == 'ToonJuror': self.numToonJurorsSeated += 1 @@ -1799,7 +1799,7 @@ def setTaunt(self, tauntIndex, extraInfo): gotError = True if gotError: st = StackTrace() - print st + print(st) return chatString = TTLocalizer.LawbotBossTaunts[1] if tauntIndex == 0: @@ -1848,7 +1848,7 @@ def toonEnteredCannon(self, toonId, cannonIndex): def numJurorsSeatedByCannon(self, cannonIndex): retVal = 0 - for chair in self.chairs.values(): + for chair in list(self.chairs.values()): if chair.state == 'ToonJuror': if chair.toonJurorIndex == cannonIndex: retVal += 1 diff --git a/toontown/suit/DistributedLawbotBossAI.py b/toontown/suit/DistributedLawbotBossAI.py index 4006d9746..fb5858328 100644 --- a/toontown/suit/DistributedLawbotBossAI.py +++ b/toontown/suit/DistributedLawbotBossAI.py @@ -36,7 +36,7 @@ def __init__(self, air): self.cannons = None self.chairs = None self.gavels = None - self.cagedToonNpcId = random.choice(NPCToons.npcFriends.keys()) + self.cagedToonNpcId = random.choice(list(NPCToons.npcFriends.keys())) self.bossMaxDamage = ToontownGlobals.LawbotBossMaxDamage self.recoverRate = 0 self.recoverStartTime = 0 @@ -338,7 +338,7 @@ def __makeCannons(self): self.notify.debug('totalDisplacement=%s' % totalDisplacement) numToons = len(self.involvedToons) stepDisplacement = totalDisplacement / (numToons + 1) - for index in xrange(numToons): + for index in range(numToons): newPos = stepDisplacement * (index + 1) self.notify.debug('curDisplacement = %s' % newPos) newPos += startPt @@ -352,7 +352,7 @@ def __makeCannons(self): def __makeChairs(self): if self.chairs == None: self.chairs = [] - for index in xrange(12): + for index in range(12): chair = DistributedLawbotChairAI.DistributedLawbotChairAI(self.air, self, index) chair.generateWithRequired(self.zoneId) self.chairs.append(chair) @@ -564,7 +564,7 @@ def __goodJump(self, avId): def __makeBattleThreeObjects(self): if self.gavels == None: self.gavels = [] - for index in xrange(self.numGavels): + for index in range(self.numGavels): gavel = DistributedLawbotBossGavelAI.DistributedLawbotBossGavelAI(self.air, self, index) gavel.generateWithRequired(self.zoneId) self.gavels.append(gavel) @@ -673,7 +673,7 @@ def giveCogSummonReward(self, toon, prefDeptIndex, prefSummonType): summonType = 'invasion' else: foundOne = False - for curDeptIndex in xrange(len(SuitDNA.suitDepts)): + for curDeptIndex in range(len(SuitDNA.suitDepts)): if not toon.hasParticularCogSummons(curDeptIndex, cogLevel, prefSummonType): deptIndex = curDeptIndex foundOne = True @@ -694,12 +694,12 @@ def giveCogSummonReward(self, toon, prefDeptIndex, prefSummonType): foundOne = True break - possibleCogLevel = range(SuitDNA.suitsPerDept) - possibleDeptIndex = range(len(SuitDNA.suitDepts)) + possibleCogLevel = list(range(SuitDNA.suitsPerDept)) + possibleDeptIndex = list(range(len(SuitDNA.suitDepts))) possibleSummonType = ['single', 'building', 'invasion'] typeWeights = ['single'] * 3 + ['building'] * 60 + ['invasion'] * 37 if not foundOne: - for i in xrange(5): + for i in range(5): randomCogLevel = random.choice(possibleCogLevel) randomSummonType = random.choice(typeWeights) randomDeptIndex = random.choice(possibleDeptIndex) @@ -785,7 +785,7 @@ def __makeLawyers(self): 'sd', 'le', 'bw'] - for i in xrange(self.numLawyers): + for i in range(self.numLawyers): suit = DistributedLawbotBossSuitAI.DistributedLawbotBossSuitAI(self.air, None) suit.dna = SuitDNA.SuitDNA() lawCog = random.choice(lawCogChoices) @@ -895,7 +895,7 @@ def skipCJ(): """ invoker = spellbook.getInvoker() boss = None - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): if isinstance(do, DistributedLawbotBossAI): if invoker.doId in do.involvedToons: boss = do @@ -915,7 +915,7 @@ def killCJ(): """ invoker = spellbook.getInvoker() boss = None - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): if isinstance(do, DistributedLawbotBossAI): if invoker.doId in do.involvedToons: boss = do diff --git a/toontown/suit/DistributedLawbotBossSuit.py b/toontown/suit/DistributedLawbotBossSuit.py index a810389e0..3e33e0db1 100644 --- a/toontown/suit/DistributedLawbotBossSuit.py +++ b/toontown/suit/DistributedLawbotBossSuit.py @@ -271,7 +271,7 @@ def getEvidence(self, usedForAttack = False): return model def cleanupIntervals(self): - for interval in self.activeIntervals.values(): + for interval in list(self.activeIntervals.values()): interval.finish() self.activeIntervals = {} diff --git a/toontown/suit/DistributedSellbotBoss.py b/toontown/suit/DistributedSellbotBoss.py index 884c36aea..fb9a5f992 100644 --- a/toontown/suit/DistributedSellbotBoss.py +++ b/toontown/suit/DistributedSellbotBoss.py @@ -82,7 +82,7 @@ def announceGenerate(self): self.piesRestockSfx = loader.loadSfx('phase_9/audio/sfx/CHQ_SOS_pies_restock.ogg') self.rampSlideSfx = loader.loadSfx('phase_9/audio/sfx/CHQ_VP_ramp_slide.ogg') self.strafeSfx = [] - for i in xrange(10): + for i in range(10): self.strafeSfx.append(loader.loadSfx('phase_3.5/audio/sfx/SA_shred.ogg')) render.setTag('pieCode', str(ToontownGlobals.PieCodeNotBossCog)) @@ -1083,7 +1083,7 @@ def __arrangeToonsAroundCage(self): radius = 15 numToons = len(self.involvedToons) center = (numToons - 1) / 2.0 - for i in xrange(numToons): + for i in range(numToons): toon = base.cr.doId2do.get(self.involvedToons[i]) if toon: angle = 270 - 15 * (i - center) @@ -1114,7 +1114,7 @@ def doorBCallback(self, isOpen): def __toonsToPromotionPosition(self, toonIds, battleNode): points = BattleBase.BattleBase.toonPoints[len(toonIds) - 1] - for i in xrange(len(toonIds)): + for i in range(len(toonIds)): toon = base.cr.doId2do.get(toonIds[i]) if toon: toon.reparentTo(render) @@ -1123,7 +1123,7 @@ def __toonsToPromotionPosition(self, toonIds, battleNode): def __doobersToPromotionPosition(self, doobers, battleNode): points = BattleBase.BattleBase.toonPoints[len(doobers) - 1] - for i in xrange(len(doobers)): + for i in range(len(doobers)): suit = doobers[i] suit.fsm.request('neutral') suit.loop('neutral') @@ -1229,7 +1229,7 @@ def doStrafe(self, side, direction): spread = -spread dist = 50 rate = time / numGears - for i in xrange(numGears): + for i in range(numGears): node = gearRoot.attachNewNode(str(i)) node.hide() node.setPos(0, 0, 0) diff --git a/toontown/suit/DistributedSellbotBossAI.py b/toontown/suit/DistributedSellbotBossAI.py index e56546afd..1c7a63401 100644 --- a/toontown/suit/DistributedSellbotBossAI.py +++ b/toontown/suit/DistributedSellbotBossAI.py @@ -23,7 +23,7 @@ def __init__(self, air): DistributedBossCogAI.DistributedBossCogAI.__init__(self, air, 's') FSM.FSM.__init__(self, 'DistributedSellbotBossAI') self.doobers = [] - self.cagedToonNpcId = random.choice(NPCToons.HQnpcFriends.keys()) + self.cagedToonNpcId = random.choice(list(NPCToons.HQnpcFriends.keys())) self.bossMaxDamage = ToontownGlobals.SellbotBossMaxDamage self.battleOnePlanner = SuitBuildingGlobals.SUIT_PLANNER_VP self.battleTwoPlanner = SuitBuildingGlobals.SUIT_PLANNER_VP_SKELECOGS @@ -424,7 +424,7 @@ def __resetDoobers(self): def __makeDoobers(self): self.__resetDoobers() - for i in xrange(8): + for i in range(8): suit = DistributedSuitAI.DistributedSuitAI(self.air, None) level = random.randrange(len(SuitDNA.suitsPerLevel)) suit.dna = SuitDNA.SuitDNA() @@ -516,7 +516,7 @@ def skipVP(): """ invoker = spellbook.getInvoker() boss = None - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): if isinstance(do, DistributedSellbotBossAI): if invoker.doId in do.involvedToons: boss = do @@ -536,7 +536,7 @@ def killVP(): """ invoker = spellbook.getInvoker() boss = None - for do in simbase.air.doId2do.values(): + for do in list(simbase.air.doId2do.values()): if isinstance(do, DistributedSellbotBossAI): if invoker.doId in do.involvedToons: boss = do diff --git a/toontown/suit/DistributedSuit.py b/toontown/suit/DistributedSuit.py index 0fb493cc3..5b2716b0d 100644 --- a/toontown/suit/DistributedSuit.py +++ b/toontown/suit/DistributedSuit.py @@ -261,15 +261,15 @@ def debugSuitPosition(self, elapsed, currentLeg, x, y, timestamp): chug = globalClock.getRealTime() - now messageAge = now - globalClockDelta.networkToLocalTime(timestamp, now) if messageAge < -(chug + 0.5) or messageAge > chug + 1.0: - print 'Apparently out of sync with AI by %0.2f seconds. Suggest resync!' % messageAge + print('Apparently out of sync with AI by %0.2f seconds. Suggest resync!' % messageAge) return localElapsed = now - self.pathStartTime timeDiff = localElapsed - (elapsed + messageAge) if abs(timeDiff) > 0.2: - print "%s (%d) appears to be %0.2f seconds out of sync along its path. Suggest '~cogs sync'." % (self.getName(), self.getDoId(), timeDiff) + print("%s (%d) appears to be %0.2f seconds out of sync along its path. Suggest '~cogs sync'." % (self.getName(), self.getDoId(), timeDiff)) return if self.legList == None: - print "%s (%d) doesn't have a legList yet." % (self.getName(), self.getDoId()) + print("%s (%d) doesn't have a legList yet." % (self.getName(), self.getDoId())) return netPos = Point3(x, y, 0.0) leg = self.legList.getLeg(currentLeg) @@ -278,23 +278,23 @@ def debugSuitPosition(self, elapsed, currentLeg, x, y, timestamp): calcDelta = Vec3(netPos - calcPos) diff = calcDelta.length() if diff > 4.0: - print '%s (%d) is %0.2f feet from the AI computed path!' % (self.getName(), self.getDoId(), diff) - print 'Probably your DNA files are out of sync.' + print('%s (%d) is %0.2f feet from the AI computed path!' % (self.getName(), self.getDoId(), diff)) + print('Probably your DNA files are out of sync.') return localPos = Point3(self.getX(), self.getY(), 0.0) localDelta = Vec3(netPos - localPos) diff = localDelta.length() if diff > 10.0: - print '%s (%d) in state %s is %0.2f feet from its correct position!' % (self.getName(), + print('%s (%d) in state %s is %0.2f feet from its correct position!' % (self.getName(), self.getDoId(), self.fsm.getCurrentState().getName(), - diff) - print 'Should be at (%0.2f, %0.2f), but is at (%0.2f, %0.2f).' % (x, + diff)) + print('Should be at (%0.2f, %0.2f), but is at (%0.2f, %0.2f).' % (x, y, localPos[0], - localPos[1]) + localPos[1])) return - print '%s (%d) is in the correct position.' % (self.getName(), self.getDoId()) + print('%s (%d) is in the correct position.' % (self.getName(), self.getDoId())) def denyBattle(self): DistributedSuitBase.DistributedSuitBase.denyBattle(self) diff --git a/toontown/suit/DistributedSuitAI.py b/toontown/suit/DistributedSuitAI.py index 770a46b4e..704d532f6 100644 --- a/toontown/suit/DistributedSuitAI.py +++ b/toontown/suit/DistributedSuitAI.py @@ -206,7 +206,7 @@ def initializePath(self): self.makeLegList() if self.notify.getDebug(): self.notify.debug('Leg list:') - print self.legList + print(self.legList) idx1 = self.startPoint.getIndex() idx2 = self.endPoint.getIndex() self.pathStartTime = globalClock.getFrameTime() diff --git a/toontown/suit/DistributedSuitBase.py b/toontown/suit/DistributedSuitBase.py index c366f8c93..27e03e070 100644 --- a/toontown/suit/DistributedSuitBase.py +++ b/toontown/suit/DistributedSuitBase.py @@ -304,7 +304,7 @@ def denyBattle(self): def makePathTrack(self, nodePath, posPoints, velocity, name): track = Sequence(name=name) nodePath.setPos(posPoints[0]) - for pointIndex in xrange(len(posPoints) - 1): + for pointIndex in range(len(posPoints) - 1): startPoint = posPoints[pointIndex] endPoint = posPoints[pointIndex + 1] track.append(Func(nodePath.headsUp, endPoint[0], endPoint[1], endPoint[2])) diff --git a/toontown/suit/DistributedSuitPlanner.py b/toontown/suit/DistributedSuitPlanner.py index 583e975da..438c68439 100644 --- a/toontown/suit/DistributedSuitPlanner.py +++ b/toontown/suit/DistributedSuitPlanner.py @@ -55,7 +55,7 @@ def showPaths(self): self.__doShowPoints(vizNode, lines, None, points) cnode = CollisionNode('battleCells') cnode.setCollideMask(BitMask32.allOff()) - for zoneId, cellPos in self.battlePosDict.items(): + for zoneId, cellPos in list(self.battlePosDict.items()): cnode.addSolid(CollisionSphere(LPoint3f(cellPos), 9)) text = '%s' % zoneId self.__makePathVizText(text, cellPos[0], cellPos[1], cellPos[2] + 9, (1, 1, 1, 1)) @@ -97,7 +97,7 @@ def __doShowPoints(self, vizNode, lines, p, points): self.pathViz.attachNewNode(cn) adjacent = self.dnaStore.getAdjacentPoints(p) numPoints = adjacent.getNumPoints() - for i in xrange(numPoints): + for i in range(numPoints): qi = adjacent.getPointIndex(i) q = self.dnaStore.getSuitPointWithIndex(qi) pp = p.getPos() @@ -172,7 +172,7 @@ def __hideEdges(self, i, collisionEntry): @magicWord(category=CATEGORY_COMMUNITY_MANAGER) def suitPaths(): response = "Couldn't toggle suit path visualization." - for do in base.cr.doId2do.values(): + for do in list(base.cr.doId2do.values()): if not isinstance(do, DistributedSuitPlanner): continue if getattr(do, '_showPaths', False): diff --git a/toontown/suit/DistributedSuitPlannerAI.py b/toontown/suit/DistributedSuitPlannerAI.py index e1d4ee6d3..0b35df3a8 100644 --- a/toontown/suit/DistributedSuitPlannerAI.py +++ b/toontown/suit/DistributedSuitPlannerAI.py @@ -117,7 +117,7 @@ def __init__(self, air, zoneId): if simbase.air.wantCogdominiums: if not hasattr(self.__class__, 'CogdoPopAdjusted'): self.__class__.CogdoPopAdjusted = False - for index in xrange(len(self.SuitHoodInfo)): + for index in range(len(self.SuitHoodInfo)): hoodInfo = self.SuitHoodInfo[index] hoodInfo[self.SUIT_HOOD_INFO_BMIN] = int(0.5 + self.CogdoPopFactor * hoodInfo[ self.SUIT_HOOD_INFO_BMIN]) @@ -126,7 +126,7 @@ def __init__(self, air, zoneId): self.SUIT_HOOD_INFO_BMAX]) self.hoodInfoIdx = -1 - for index in xrange(len(self.SuitHoodInfo)): + for index in range(len(self.SuitHoodInfo)): currHoodInfo = self.SuitHoodInfo[index] if currHoodInfo[self.SUIT_HOOD_INFO_ZONE] == self.canonicalZoneId: self.hoodInfoIdx = index @@ -255,7 +255,7 @@ def countNumBuildingsPerHeight(self, count): def formatNumSuitsPerTrack(self, count): result = ' ' - for (track, num) in count.items(): + for (track, num) in list(count.items()): result += ' %s:%s' % (track, num) return result[2:] @@ -679,7 +679,7 @@ def createInitialSuitBuildings(self): # If we aren't at our minimum number of buildings, let's spawn some! suitBlockCount = len(self.buildingMgr.getSuitBlocks()) if suitBlockCount < self.targetNumSuitBuildings: - for _ in xrange(self.targetNumSuitBuildings - suitBlockCount): + for _ in range(self.targetNumSuitBuildings - suitBlockCount): blockNumber = random.choice(self.buildingMgr.getToonBlocks()) building = self.buildingMgr.getBuilding(blockNumber) if building is None: @@ -712,7 +712,7 @@ def assignInitialSuitBuildings(self): totalBuildings = 0 targetSuitBuildings = 0 actualSuitBuildings = 0 - for sp in self.air.suitPlanners.values(): + for sp in list(self.air.suitPlanners.values()): totalBuildings += len(sp.frontdoorPointList) targetSuitBuildings += sp.targetNumSuitBuildings if sp.buildingMgr: @@ -721,7 +721,7 @@ def assignInitialSuitBuildings(self): self.notify.debug('Want %s out of %s total suit buildings; we currently have %s assigned, %s actual.' % (wantedSuitBuildings, totalBuildings, targetSuitBuildings, actualSuitBuildings)) if actualSuitBuildings > 0: numReassigned = 0 - for sp in self.air.suitPlanners.values(): + for sp in list(self.air.suitPlanners.values()): if sp.buildingMgr: numBuildings = len(sp.buildingMgr.getSuitBlocks()) else: @@ -752,7 +752,7 @@ def assignSuitBuildings(self, numToAssign): 's': 0, 'g': 0 } - for sp in self.air.suitPlanners.values(): + for sp in list(self.air.suitPlanners.values()): sp.countNumBuildingsPerTrack(numPerTrack) numPerTrack['c'] += sp.pendingBuildingTracks.count('c') numPerTrack['l'] += sp.pendingBuildingTracks.count('l') @@ -767,7 +767,7 @@ def assignSuitBuildings(self, numToAssign): 4: 0, 5: 0 } - for sp in self.air.suitPlanners.values(): + for sp in list(self.air.suitPlanners.values()): sp.countNumBuildingsPerHeight(numPerHeight) numPerHeight[0] += sp.pendingBuildingHeights.count(0) numPerHeight[1] += sp.pendingBuildingHeights.count(1) @@ -778,7 +778,7 @@ def assignSuitBuildings(self, numToAssign): while numToAssign > 0: smallestCount = None smallestTracks = [] - for trackIndex in xrange(4): + for trackIndex in range(4): if totalWeightPerTrack[trackIndex]: track = SuitDNA.suitDepts[trackIndex] count = numPerTrack[track] @@ -794,7 +794,7 @@ def assignSuitBuildings(self, numToAssign): buildingTrackIndex = SuitDNA.suitDepts.index(buildingTrack) smallestCount = None smallestHeights = [] - for height in xrange(5): + for height in range(5): if totalWeightPerHeight[height]: count = float(numPerHeight[height]) / float(self.BUILDING_HEIGHT_DISTRIBUTION[height]) if (smallestCount is None) or (count < smallestCount): @@ -902,7 +902,7 @@ def chooseStreetWithPreference(self, hoodInfo, buildingTrackIndex, buildingHeigh totalWeight = sum(dist) c = random.random() * totalWeight t = 0 - for i in xrange(len(hoodInfo)): + for i in range(len(hoodInfo)): t += dist[i] if c < t: return hoodInfo[i] @@ -948,7 +948,7 @@ def requestBattle(self, zoneId, suit, toonId): pos = self.battlePosDict[canonicalZoneId] interactivePropTrackBonus = -1 - if simbase.config.GetBool('props-buff-battles', True) and self.cellToGagBonusDict.has_key(canonicalZoneId): + if simbase.config.GetBool('props-buff-battles', True) and canonicalZoneId in self.cellToGagBonusDict: tentativeBonusTrack = self.cellToGagBonusDict[canonicalZoneId] trackToHolidayDict = { ToontownBattleGlobals.SQUIRT_TRACK: ToontownGlobals.HYDRANTS_BUFF_BATTLES, @@ -1016,7 +1016,7 @@ def postBattleResumeCheck(self, suit): if suit.zoneId == currBattle[0]: self.notify.debug(' battle found' + str(suit.zoneId)) for currPath in currBattle[1]: - for currPathPtSuit in xrange(suit.currWpt, suit.myPath.getNumPoints()): + for currPathPtSuit in range(suit.currWpt, suit.myPath.getNumPoints()): ptIdx = suit.myPath.getPointIndex(currPathPtSuit) if self.notify.getDebug(): self.notify.debug(' comparing' + str(ptIdx) + 'with' + str(currPath)) @@ -1026,7 +1026,7 @@ def postBattleResumeCheck(self, suit): return 0 battleIndex += 1 pointList = [] - for currPathPtSuit in xrange(suit.currWpt, suit.myPath.getNumPoints()): + for currPathPtSuit in range(suit.currWpt, suit.myPath.getNumPoints()): ptIdx = suit.myPath.getPointIndex(currPathPtSuit) if self.notify.getDebug(): self.notify.debug(' appending point with index of' + str(ptIdx)) @@ -1070,12 +1070,12 @@ def pickLevelTypeAndTrack(self, level=None, type=None, track=None): self.isElite = True if type is None: if ZoneUtil.isCogHQZone(self.zoneId): - typeChoices = range(max(level - 4, 1), min(level, self.MAX_SUIT_TYPES_HQ) + 1) + typeChoices = list(range(max(level - 4, 1), min(level, self.MAX_SUIT_TYPES_HQ) + 1)) type = random.choice(typeChoices) if random.random() < self.HQ_SKELE_CHANCE: self.skeleChance = 1 else: - typeChoices = range(max(level - 4, 1), min(level, self.MAX_SUIT_TYPES) + 1) + typeChoices = list(range(max(level - 4, 1), min(level, self.MAX_SUIT_TYPES) + 1)) type = random.choice(typeChoices) if level > 12: pass diff --git a/toontown/suit/RoguesGallery.py b/toontown/suit/RoguesGallery.py index 885c59ca5..2018de93f 100644 --- a/toontown/suit/RoguesGallery.py +++ b/toontown/suit/RoguesGallery.py @@ -91,7 +91,7 @@ def __makeGallery(self): self.text.setTextColor(0.0, 0.0, 0.0, 1.0) self.rowHeight = 0.0 self.minXScale = None - print "rognamestr='", self.rognamestr, "'\n" + print("rognamestr='", self.rognamestr, "'\n") if self.rognamestr == None or len(self.rognamestr) == 0: for dept in SuitDNA.suitDepts: self.__makeDept(dept) @@ -109,7 +109,7 @@ def __makeGallery(self): def __makeDept(self, dept): self.suitRow = [] self.rowWidth = 0.0 - for type in xrange(self.numSuitTypes): + for type in range(self.numSuitTypes): self.__makeSuit(dept, type) xScale = self.xRowSpace / self.rowWidth diff --git a/toontown/suit/SellbotBossGlobals.py b/toontown/suit/SellbotBossGlobals.py index a4c321514..51eb8a1da 100644 --- a/toontown/suit/SellbotBossGlobals.py +++ b/toontown/suit/SellbotBossGlobals.py @@ -46,7 +46,7 @@ 'rewardPerGrabMax': 0}} def setBarrelAttr(barrel, entId): - for defAttr, defValue in BarrelDefs[entId].iteritems(): + for defAttr, defValue in BarrelDefs[entId].items(): setattr(barrel, defAttr, defValue) diff --git a/toontown/suit/Suit.py b/toontown/suit/Suit.py index 104eb42d5..16acf4313 100644 --- a/toontown/suit/Suit.py +++ b/toontown/suit/Suit.py @@ -227,7 +227,7 @@ def loadModels(): global Preloaded if not Preloaded: - print 'Preloading suits...' + print('Preloading suits...') def preload(task): for filepath in SuitParts: @@ -250,7 +250,7 @@ def unloadSuits(level): unloadDialog(level) def loadSuitModelsAndAnims(level, flag = 0): - for key in ModelDict.keys(): + for key in list(ModelDict.keys()): model, phase = ModelDict[key] if flag: filepath = 'phase_3.5' + model + 'mod' @@ -282,7 +282,7 @@ def loadSuitAnims(suit, flag = 1): animList = () else: - print 'Invalid suit name: ', suit + print('Invalid suit name: ', suit) return -1 for anim in animList: phase = 'phase_' + str(anim[2]) @@ -623,7 +623,7 @@ def generateHead(self, headType): filePrefix, phase = ModelDict[self.style.body] headModel = loader.loadModel('phase_' + str(phase) + filePrefix + 'heads') headReferences = headModel.findAllMatches('**/' + headType) - for i in xrange(0, headReferences.getNumPaths()): + for i in range(0, headReferences.getNumPaths()): if self.style.body == 'a': headPart = self.instance(headReferences.getPath(i), 'modelRoot', 'to_head') else: @@ -867,7 +867,7 @@ def makeSkeleton(self, elite = False): self.setBlend(frameBlend = base.wantSmoothAnims) self.setLODAnimation(base.lodMaxRange, base.lodMinRange, base.lodDelayFactor) parts = self.findAllMatches('**/pPlane*') - for partNum in xrange(0, parts.getNumPaths()): + for partNum in range(0, parts.getNumPaths()): bb = parts.getPath(partNum) bb.setTwoSided(1) diff --git a/toontown/suit/SuitBase.py b/toontown/suit/SuitBase.py index cd6be2391..32058e87f 100644 --- a/toontown/suit/SuitBase.py +++ b/toontown/suit/SuitBase.py @@ -86,10 +86,10 @@ def getPath(self): return self.path def printPath(self): - print '%d points in path' % self.pathLength - for currPathPt in xrange(self.pathLength): + print('%d points in path' % self.pathLength) + for currPathPt in range(self.pathLength): indexVal = self.path.getPointIndex(currPathPt) - print '\t', self.sp.dnaStore.getSuitPointWithIndex(indexVal) + print('\t', self.sp.dnaStore.getSuitPointWithIndex(indexVal)) def makeLegList(self): self.legList = SuitLegList(self.path, self.sp.dnaStore) \ No newline at end of file diff --git a/toontown/suit/SuitDNA.py b/toontown/suit/SuitDNA.py index 9e470a899..7c23c7b9e 100644 --- a/toontown/suit/SuitDNA.py +++ b/toontown/suit/SuitDNA.py @@ -54,7 +54,7 @@ def getSuitBodyType(name): elif name in suitCTypes: return 'c' else: - print 'Unknown body type for suit name: ', name + print('Unknown body type for suit name: ', name) return @@ -72,7 +72,7 @@ def getSuitDept(name): elif index < suitsPerDept * 5: return suitDepts[4] else: - print 'Unknown dept for suit name: ', name + print('Unknown dept for suit name: ', name) return @@ -192,7 +192,7 @@ def newBossCog(self, dept): def newSuitRandom(self, level = None, dept = None): self.type = 's' if level == None: - level = random.choice(range(1, len(suitsPerLevel))) + level = random.choice(list(range(1, len(suitsPerLevel)))) elif level < 0 or level > len(suitsPerLevel): notify.error('Invalid suit level: %d' % level) if dept == None: @@ -202,12 +202,12 @@ def newSuitRandom(self, level = None, dept = None): base = index * suitsPerDept offset = 0 if level > 1: - for i in xrange(1, level): + for i in range(1, level): offset = offset + suitsPerLevel[i - 1] bottom = base + offset top = bottom + suitsPerLevel[level - 1] - self.name = suitHeadTypes[random.choice(range(bottom, top))] + self.name = suitHeadTypes[random.choice(list(range(bottom, top)))] self.body = getSuitBodyType(self.name) def newGoon(self, name = None): diff --git a/toontown/suit/SuitInvasionManagerAI.py b/toontown/suit/SuitInvasionManagerAI.py index 5a938f357..d698af72f 100644 --- a/toontown/suit/SuitInvasionManagerAI.py +++ b/toontown/suit/SuitInvasionManagerAI.py @@ -194,7 +194,7 @@ def notifyInvasionBulletin(self, avId): [msgType, self.getSuitName(), self.remaining, self.flags]) def flySuits(self): - for suitPlanner in self.air.suitPlanners.values(): + for suitPlanner in list(self.air.suitPlanners.values()): suitPlanner.flySuits() def handleSuitDefeated(self): diff --git a/toontown/suit/SuitLegList.py b/toontown/suit/SuitLegList.py index f2f4258b7..53b956c7c 100644 --- a/toontown/suit/SuitLegList.py +++ b/toontown/suit/SuitLegList.py @@ -120,7 +120,7 @@ def __init__(self, path, dnaStore): self.add(self.path.getPoint(0), self.path.getPoint(1), self.getFirstLegType()) # Next, connect each of the points in our path through SuitLegs: - for i in xrange(self.path.getNumPoints() - 1): + for i in range(self.path.getNumPoints() - 1): pointA = self.path.getPoint(i) pointB = self.path.getPoint(i + 1) pointTypeA = pointA.getPointType() diff --git a/toontown/suit/SuitPlannerBase.py b/toontown/suit/SuitPlannerBase.py index 923b87187..47c6d4b77 100644 --- a/toontown/suit/SuitPlannerBase.py +++ b/toontown/suit/SuitPlannerBase.py @@ -62,7 +62,7 @@ class SuitPlannerBase: heights = [0, 0, 0, 0, 0, 0] for level in levels: minFloors, maxFloors = SuitBuildingGlobals.SuitBuildingInfo[level - 1][0] - for i in xrange(minFloors - 1, maxFloors): + for i in range(minFloors - 1, maxFloors): heights[i] += 1 currHoodInfo[SUIT_HOOD_INFO_HEIGHTS] = heights @@ -123,7 +123,7 @@ def initDNAInfo(self): self.notify.info('zone %s has %s disconnected suit paths.' % (self.zoneId, numGraphs)) self.battlePosDict = {} self.cellToGagBonusDict = {} - for i in xrange(self.dnaStore.getNumDNAVisGroupsAI()): + for i in range(self.dnaStore.getNumDNAVisGroupsAI()): vg = self.dnaStore.getDNAVisGroupAI(i) zoneId = int(self.extractGroupName(vg.getName())) if vg.getNumBattleCells() == 1: @@ -141,7 +141,7 @@ def initDNAInfo(self): if battleCellId == -1: self.notify.warning('interactive prop %s at %s not associated with a a battle' % (childDnaGroup, zoneId)) elif battleCellId == 0: - if self.cellToGagBonusDict.has_key(zoneId): + if zoneId in self.cellToGagBonusDict: self.notify.error('FIXME battle cell at zone %s has two props %s %s linked to it' % (zoneId, self.cellToGagBonusDict[zoneId], childDnaGroup)) else: name = childDnaGroup.getName() @@ -158,7 +158,7 @@ def initDNAInfo(self): self.sidedoorPointList = [] self.cogHQDoorPointList = [] numPoints = self.dnaStore.getNumSuitPoints() - for i in xrange(numPoints): + for i in range(numPoints): point = self.dnaStore.getSuitPointAtIndex(i) if point.getPointType() == DNASuitPoint.FRONT_DOOR_POINT: self.frontdoorPointList.append(point) @@ -180,10 +180,10 @@ def performPathTest(self): endPoint = startAndEnd[1] path = self.dnaStore.getSuitPath(startPoint, endPoint) numPathPoints = path.getNumPoints() - for i in xrange(numPathPoints - 1): + for i in range(numPathPoints - 1): zone = self.dnaStore.getSuitEdgeZone(path.getPointIndex(i), path.getPointIndex(i + 1)) travelTime = self.dnaStore.getSuitEdgeTravelTime(path.getPointIndex(i), path.getPointIndex(i + 1), self.suitWalkSpeed) - self.notify.debug('edge from point ' + `i` + ' to point ' + `(i + 1)` + ' is in zone: ' + `zone` + ' and will take ' + `travelTime` + ' seconds to walk.') + self.notify.debug('edge from point ' + repr(i) + ' to point ' + repr((i + 1)) + ' is in zone: ' + repr(zone) + ' and will take ' + repr(travelTime) + ' seconds to walk.') def genPath(self, startPoint, endPoint, minPathLen, maxPathLen): return self.dnaStore.getSuitPath(startPoint, endPoint, minPathLen, maxPathLen) diff --git a/toontown/toon/DeathForceAcknowledge.py b/toontown/toon/DeathForceAcknowledge.py index b30134f13..9dfe25ec2 100644 --- a/toontown/toon/DeathForceAcknowledge.py +++ b/toontown/toon/DeathForceAcknowledge.py @@ -18,7 +18,7 @@ def __init__(self, doneEvent): self.fade.reparentTo(aspect2d, FADE_SORT_INDEX) fadeModel.removeNode() else: - print 'Problem loading fadeModel.' + print('Problem loading fadeModel.') self.fade = None self.dialog = TTDialog.TTGlobalDialog( message=TTLocalizer.PlaygroundDeathAckMessage, diff --git a/toontown/toon/DistributedNPCBlocker.py b/toontown/toon/DistributedNPCBlocker.py index 0a7e4e4de..3f28a4cfa 100644 --- a/toontown/toon/DistributedNPCBlocker.py +++ b/toontown/toon/DistributedNPCBlocker.py @@ -1,5 +1,5 @@ from pandac.PandaModules import * -from DistributedNPCToonBase import * +from .DistributedNPCToonBase import * from direct.gui.DirectGui import * from pandac.PandaModules import * from toontown.toon import NPCToons diff --git a/toontown/toon/DistributedNPCBlockerAI.py b/toontown/toon/DistributedNPCBlockerAI.py index ddecc9c2b..0c21507fe 100644 --- a/toontown/toon/DistributedNPCBlockerAI.py +++ b/toontown/toon/DistributedNPCBlockerAI.py @@ -1,6 +1,6 @@ from otp.ai.AIBaseGlobal import * from pandac.PandaModules import * -from DistributedNPCToonBaseAI import * +from .DistributedNPCToonBaseAI import * from toontown.toon import NPCToons from direct.task.Task import Task diff --git a/toontown/toon/DistributedNPCPetclerk.py b/toontown/toon/DistributedNPCPetclerk.py index 10f5c3ec7..c2649f664 100644 --- a/toontown/toon/DistributedNPCPetclerk.py +++ b/toontown/toon/DistributedNPCPetclerk.py @@ -90,7 +90,7 @@ def resetPetshopClerk(self): return Task.done def ignoreEventDict(self): - for event in self.eventDict.values(): + for event in list(self.eventDict.values()): self.ignore(event) def setPetSeeds(self, petSeeds): diff --git a/toontown/toon/DistributedNPCPetclerkAI.py b/toontown/toon/DistributedNPCPetclerkAI.py index b241e9c65..80be3f0a0 100644 --- a/toontown/toon/DistributedNPCPetclerkAI.py +++ b/toontown/toon/DistributedNPCPetclerkAI.py @@ -91,7 +91,7 @@ def petAdopted(self, petNum, nameIndex): if av: from toontown.hood import ZoneUtil zoneId = ZoneUtil.getCanonicalSafeZoneId(self.zoneId) - if petNum not in xrange(0, len(self.petSeeds)): + if petNum not in range(0, len(self.petSeeds)): self.air.writeServerEvent('suspicious', avId, 'DistributedNPCPetshopAI.petAdopted and no such pet!') self.notify.warning('somebody called petAdopted on a non-existent pet! avId: %s' % avId) return @@ -103,7 +103,7 @@ def petAdopted(self, petNum, nameIndex): if av.petId != 0: simbase.air.petMgr.deleteToonsPet(avId) gender = petNum % len(PetDNA.PetGenders) - if nameIndex not in xrange(0, TTLocalizer.PetNameIndexMAX): + if nameIndex not in range(0, TTLocalizer.PetNameIndexMAX): self.air.writeServerEvent('avoid_crash', avId, "DistributedNPCPetclerkAI.petAdopted and didn't have valid nameIndex!") self.notify.warning("somebody called petAdopted and didn't have valid nameIndex to adopt! avId: %s" % avId) return diff --git a/toontown/toon/DistributedNPCSpecialQuestGiver.py b/toontown/toon/DistributedNPCSpecialQuestGiver.py index 6ac4bb682..9349de81a 100644 --- a/toontown/toon/DistributedNPCSpecialQuestGiver.py +++ b/toontown/toon/DistributedNPCSpecialQuestGiver.py @@ -24,7 +24,7 @@ def __init__(self, cr): def announceGenerate(self): self.setAnimState('neutral', 0.9, None, None) - npcOrigin = self.cr.playGame.hood.loader.geom.find('**/npc_origin_' + `(self.posIndex)`) + npcOrigin = self.cr.playGame.hood.loader.geom.find('**/npc_origin_' + repr((self.posIndex))) if not npcOrigin.isEmpty(): self.reparentTo(npcOrigin) self.clearMat() diff --git a/toontown/toon/DistributedNPCSpecialQuestGiverAI.py b/toontown/toon/DistributedNPCSpecialQuestGiverAI.py index 94d990352..0e9e1df81 100644 --- a/toontown/toon/DistributedNPCSpecialQuestGiverAI.py +++ b/toontown/toon/DistributedNPCSpecialQuestGiverAI.py @@ -1,7 +1,7 @@ from otp.ai.AIBaseGlobal import * from direct.task.Task import Task from pandac.PandaModules import * -from DistributedNPCToonBaseAI import * +from .DistributedNPCToonBaseAI import * from toontown.quest import Quests from toontown.nametag.NametagGlobals import * diff --git a/toontown/toon/DistributedNPCTailor.py b/toontown/toon/DistributedNPCTailor.py index 652ed5cb2..143fecd03 100644 --- a/toontown/toon/DistributedNPCTailor.py +++ b/toontown/toon/DistributedNPCTailor.py @@ -137,31 +137,31 @@ def setMovie(self, mode, npcId, avId, timestamp): self.setChatAbsolute(TTLocalizer.STOREOWNER_BROWSING, CFSpeech | CFTimeout) if self.isLocalToon: taskMgr.doMethodLater(3.0, self.popupPurchaseGUI, self.uniqueName('popupPurchaseGUI')) - print '-----------Starting tailor interaction-----------' - print 'avid: %s, gender: %s' % (self.av.doId, self.av.style.gender) - print 'current top = %s,%s,%s,%s and bot = %s,%s,' % (self.av.style.topTex, + print('-----------Starting tailor interaction-----------') + print('avid: %s, gender: %s' % (self.av.doId, self.av.style.gender)) + print('current top = %s,%s,%s,%s and bot = %s,%s,' % (self.av.style.topTex, self.av.style.topTexColor, self.av.style.sleeveTex, self.av.style.sleeveTexColor, self.av.style.botTex, - self.av.style.botTexColor) - print 'topsList = %s' % self.av.getClothesTopsList() - print 'bottomsList = %s' % self.av.getClothesBottomsList() - print '-------------------------------------------------' + self.av.style.botTexColor)) + print('topsList = %s' % self.av.getClothesTopsList()) + print('bottomsList = %s' % self.av.getClothesBottomsList()) + print('-------------------------------------------------') elif mode == NPCToons.PURCHASE_MOVIE_COMPLETE: self.setChatAbsolute(TTLocalizer.STOREOWNER_GOODBYE, CFSpeech | CFTimeout) if self.av and self.isLocalToon: - print '-----------ending tailor interaction-----------' - print 'avid: %s, gender: %s' % (self.av.doId, self.av.style.gender) - print 'current top = %s,%s,%s,%s and bot = %s,%s,' % (self.av.style.topTex, + print('-----------ending tailor interaction-----------') + print('avid: %s, gender: %s' % (self.av.doId, self.av.style.gender)) + print('current top = %s,%s,%s,%s and bot = %s,%s,' % (self.av.style.topTex, self.av.style.topTexColor, self.av.style.sleeveTex, self.av.style.sleeveTexColor, self.av.style.botTex, - self.av.style.botTexColor) - print 'topsList = %s' % self.av.getClothesTopsList() - print 'bottomsList = %s' % self.av.getClothesBottomsList() - print '-------------------------------------------------' + self.av.style.botTexColor)) + print('topsList = %s' % self.av.getClothesTopsList()) + print('bottomsList = %s' % self.av.getClothesBottomsList()) + print('-------------------------------------------------') self.resetTailor() elif mode == NPCToons.PURCHASE_MOVIE_NO_MONEY: self.notify.warning('PURCHASE_MOVIE_NO_MONEY should not be called') @@ -209,7 +209,7 @@ def __handlePurchaseDone(self, timeout = 0): which = which | ClosetGlobals.SHIRT if self.clothesGUI.bottomChoice != -1: which = which | ClosetGlobals.SHORTS - print 'setDNA: which = %d, top = %d, bot = %d' % (which, self.clothesGUI.topChoice, self.clothesGUI.bottomChoice) + print('setDNA: which = %d, top = %d, bot = %d' % (which, self.clothesGUI.topChoice, self.clothesGUI.bottomChoice)) if self.roomAvailable == 0: if self.isLocalToon: if self.av.isClosetFull() or which & ClosetGlobals.SHIRT and which & ClosetGlobals.SHORTS: diff --git a/toontown/toon/DistributedNPCToon.py b/toontown/toon/DistributedNPCToon.py index 225344976..a3122e013 100644 --- a/toontown/toon/DistributedNPCToon.py +++ b/toontown/toon/DistributedNPCToon.py @@ -282,7 +282,7 @@ def hasQuests(self): potentialQuests = [] nyaQuests = [] av = base.localAvatar - for quest in Quests.QuestDict.keys(): + for quest in list(Quests.QuestDict.keys()): questEntry = Quests.QuestDict.get(quest) if NPCToons.getNPCName(questEntry[Quests.QuestDictFromNpcIndex]) == self.getName(): if questEntry[1] == Quests.Start: diff --git a/toontown/toon/DistributedToon.py b/toontown/toon/DistributedToon.py index 89f4a0849..45584f22c 100644 --- a/toontown/toon/DistributedToon.py +++ b/toontown/toon/DistributedToon.py @@ -401,7 +401,7 @@ def d_reqSCResistance(self, msgIndex): def getNearbyPlayers(self, radius, includeSelf = True): nearbyToons = [] toonIds = self.cr.getObjectsOfExactClass(DistributedToon) - for toonId, toon in toonIds.items(): + for toonId, toon in list(toonIds.items()): if toon is not self: dist = toon.getDistance(self) if dist < radius: @@ -481,7 +481,7 @@ def d_updateGMNameTag(self): def updateGMNameTag(self, tagString, color, state): try: - unicode(tagString, 'utf-8') + str(tagString, 'utf-8') except UnicodeDecodeError: self.sendUpdate('logSuspiciousEvent', ['invalid GM name tag: %s from %s' % (tagString, self.doId)]) return @@ -557,7 +557,7 @@ def setTalkWhisper(self, fromAV, fromAC, avatarName, chat, mods, flags): newText, scrubbed = self.scrubTalk(chat, mods, fromAV) self.displayTalkWhisper(fromAV, avatarName, chat, mods) timestamp = time.strftime('%m-%d-%Y %H:%M:%S', time.localtime()) - print ':%s: receiveWhisperTalk: %r, %r, %r, %r, %r, %r, %r' % (timestamp, fromAV, avatarName, fromAC, None, self.doId, self.getName(), newText) + print(':%s: receiveWhisperTalk: %r, %r, %r, %r, %r, %r, %r' % (timestamp, fromAV, avatarName, fromAC, None, self.doId, self.getName(), newText)) base.talkAssistant.receiveWhisperTalk(fromAV, avatarName, fromAC, None, self.doId, self.getName(), newText) def setSleepAutoReply(self, fromId): @@ -1117,7 +1117,7 @@ def getFishingTrophies(self): def setQuests(self, flattenedQuests): questList = [] questLen = 5 - for i in xrange(0, len(flattenedQuests), questLen): + for i in range(0, len(flattenedQuests), questLen): questList.append(flattenedQuests[i:i + questLen]) self.quests = questList @@ -1244,7 +1244,7 @@ def setResistanceMessages(self, resistanceMessages): def getResistanceMessageCharges(self, textId): msgs = self.resistanceMessages - for i in xrange(len(msgs)): + for i in range(len(msgs)): if msgs[i][0] == textId: return msgs[i][1] @@ -1369,8 +1369,8 @@ def getTrackProgress(self): return [self.trackProgressId, self.trackProgress] def getTrackProgressAsArray(self, maxLength = 15): - shifts = map(operator.rshift, maxLength * [self.trackProgress], xrange(maxLength - 1, -1, -1)) - digits = map(operator.mod, shifts, maxLength * [2]) + shifts = list(map(operator.rshift, maxLength * [self.trackProgress], range(maxLength - 1, -1, -1))) + digits = list(map(operator.mod, shifts, maxLength * [2])) digits.reverse() return digits @@ -1658,11 +1658,11 @@ def pieSplat(self, x, y, z, sequence, pieCode, timestamp32): splat.start(startTime)''' def cleanupPies(self): - for track in self.pieTracks.values(): + for track in list(self.pieTracks.values()): track.finish() self.pieTracks = {} - for track in self.splatTracks.values(): + for track in list(self.splatTracks.values()): track.finish() self.splatTracks = {} @@ -2125,7 +2125,7 @@ def getGardenSpecials(self): def getMyTrees(self): treeDict = self.cr.getObjectsOfClass(DistributedGagTree.DistributedGagTree) trees = [] - for tree in treeDict.values(): + for tree in list(treeDict.values()): if tree.getOwnerId() == self.doId: trees.append(tree) @@ -2146,7 +2146,7 @@ def doIHaveRequiredTrees(self, track, level): trackAndLevelList.append((tree.gagTrack, tree.gagLevel)) haveRequired = True - for curLevel in xrange(level): + for curLevel in range(level): testTuple = (track, curLevel) if testTuple not in trackAndLevelList: haveRequired = False @@ -2531,7 +2531,7 @@ def getNumInvitesToShowInMailbox(self): def setHostedParties(self, hostedParties): DistributedToon.partyNotify.debug('setHostedParties called passing in %d parties.' % len(hostedParties)) self.hostedParties = [] - for i in xrange(len(hostedParties)): + for i in range(len(hostedParties)): hostedInfo = hostedParties[i] newParty = PartyInfo(*hostedInfo) self.hostedParties.append(newParty) @@ -2539,7 +2539,7 @@ def setHostedParties(self, hostedParties): def setPartiesInvitedTo(self, partiesInvitedTo): DistributedToon.partyNotify.debug('setPartiesInvitedTo called passing in %d parties.' % len(partiesInvitedTo)) self.partiesInvitedTo = [] - for i in xrange(len(partiesInvitedTo)): + for i in range(len(partiesInvitedTo)): partyInfo = partiesInvitedTo[i] newParty = PartyInfo(*partyInfo) self.partiesInvitedTo.append(newParty) @@ -2548,7 +2548,7 @@ def setPartiesInvitedTo(self, partiesInvitedTo): def getOnePartyInvitedTo(self, partyId): result = None - for i in xrange(len(self.partiesInvitedTo)): + for i in range(len(self.partiesInvitedTo)): partyInfo = self.partiesInvitedTo[i] if partyInfo.partyId == partyId: result = partyInfo @@ -2568,7 +2568,7 @@ def getInviteForPartyId(self, partyId): def setPartyReplies(self, replies): DistributedToon.partyNotify.debug('setPartyReplies called passing in %d parties.' % len(replies)) self.partyReplyInfoBases = [] - for i in xrange(len(replies)): + for i in range(len(replies)): partyReply = replies[i] repliesForOneParty = PartyReplyInfoBase(*partyReply) self.partyReplyInfoBases.append(repliesForOneParty) @@ -2896,7 +2896,7 @@ def _getZombieCheckTaskName(self): return self.uniqueName('zombieCheck') def _doZombieCheck(self, task = None): - self._lastZombieContext = self._zombieCheckSerialGen.next() + self._lastZombieContext = next(self._zombieCheckSerialGen) #self.cr.timeManager.checkAvOnDistrict(self, self._lastZombieContext) taskMgr.doMethodLater(60.0, self._doZombieCheck, self._getZombieCheckTaskName()) @@ -2927,7 +2927,7 @@ def getStat(self, stat): def fixStats(self, stats): badStatLen = len(stats) - for i in xrange(ToontownGlobals.TOTAL_STATS - badStatLen): + for i in range(ToontownGlobals.TOTAL_STATS - badStatLen): stats.append(0) return stats diff --git a/toontown/toon/DistributedToonAI.py b/toontown/toon/DistributedToonAI.py index f788b3eac..f9406a8e5 100644 --- a/toontown/toon/DistributedToonAI.py +++ b/toontown/toon/DistributedToonAI.py @@ -3082,7 +3082,7 @@ def getKartAccessoriesOwned(self): return owned def addOwnedAccessory(self, accessoryId): - print 'in add owned accessory' + print('in add owned accessory') if accessoryId in AccessoryDict: if self.accessories.count(accessoryId) > 0: self.air.writeServerEvent('suspicious', self.doId, 'attempt to add accessory %s which is already owned!' % accessoryId) @@ -3792,7 +3792,7 @@ def checkGagBonus(self, track, level): return trackBonus >= level def giveMeSpecials(self, id = None): - print 'Specials Go!!' + print('Specials Go!!') self.b_setGardenSpecials([(0, 3), (1, 2), (2, 3), @@ -4060,7 +4060,7 @@ def requestFishingRod(self, rodId): def logMessage(self, message): avId = self.air.getAvatarIdFromSender() if __dev__: - print 'CLIENT LOG MESSAGE %s %s' % (avId, message) + print('CLIENT LOG MESSAGE %s %s' % (avId, message)) try: self.air.writeServerEvent('clientLog', avId, message) except: @@ -4606,17 +4606,17 @@ def getAnimalSound(self): return self.animalSound def setAchievements(self, achievements): - for i in xrange(len(achievements)): - if not achievements[i] in xrange(len(Achievements.AchievementsDict)): - print 'Unknown AchievementId %s'%(achievements[i]) + for i in range(len(achievements)): + if not achievements[i] in range(len(Achievements.AchievementsDict)): + print ('Unknown AchievementId %s'%(achievements[i])) del achievements[i] self.achievements = achievements def d_setAchievements(self, achievements): - for i in xrange(len(achievements)): - if not achievements[i] in xrange(len(Achievements.AchievementsDict)): - print 'Unknown AchievementId %s'%(achievements[i]) + for i in range(len(achievements)): + if not achievements[i] in range(len(Achievements.AchievementsDict)): + print('Unknown AchievementId %s'%(achievements[i])) del achievements[i] self.sendUpdate('setAchievements', args=[achievements]) diff --git a/toontown/toon/LocalToon.py b/toontown/toon/LocalToon.py index 83742054f..41f51ec3f 100644 --- a/toontown/toon/LocalToon.py +++ b/toontown/toon/LocalToon.py @@ -59,7 +59,7 @@ from toontown.shtiker import CertPage from toontown.toon import ElevatorNotifier from toontown.toon import ToonDNA -import StreamerMode, ChatLog +from . import StreamerMode, ChatLog from toontown.toon.DistributedNPCToonBase import DistributedNPCToonBase from toontown.toonbase import TTLocalizer from toontown.toonbase import ToontownGlobals @@ -300,7 +300,7 @@ def glitchKiller(self, taskFooler = 0): if self.ticker >= 10: self.ticker = 0 if self.glitchCount >= 7: - print 'GLITCH MAXED!!! resetting pos' + print('GLITCH MAXED!!! resetting pos') self.setX(self.glitchX - 1 * (self.getX() - self.glitchX)) self.setY(self.glitchY - 1 * (self.getY() - self.glitchY)) self.glitchCount = 0 @@ -796,7 +796,7 @@ def __endTossPie(self, time): self.localTossPie(power) def localPresentPie(self, time): - import TTEmote + from . import TTEmote from otp.avatar import Emote self.__stopPresentPie() if self.tossTrack: @@ -829,7 +829,7 @@ def localPresentPie(self, time): def __stopPresentPie(self): if self.__presentingPie: - import TTEmote + from . import TTEmote from otp.avatar import Emote Emote.globalEmote.releaseBody(self) messenger.send('end-pie') @@ -882,11 +882,11 @@ def localTossPie(self, power): tossTrack = self.tossTrack self.tossTrack = None tossTrack.finish() - if self.pieTracks.has_key(sequence): + if sequence in self.pieTracks: pieTrack = self.pieTracks[sequence] del self.pieTracks[sequence] pieTrack.finish() - if self.splatTracks.has_key(sequence): + if sequence in self.splatTracks: splatTrack = self.splatTracks[sequence] del self.splatTracks[sequence] splatTrack.finish() @@ -925,7 +925,7 @@ def pieFinishedFlying(self, sequence): self.__piePowerMeter.hide() def __finishPieTrack(self, sequence): - if self.pieTracks.has_key(sequence): + if sequence in self.pieTracks: pieTrack = self.pieTracks[sequence] del self.pieTracks[sequence] pieTrack.finish() @@ -937,7 +937,7 @@ def __pieHit(self, entry): return sequence = int(entry.getFromNodePath().getNetTag('pieSequence')) self.__finishPieTrack(sequence) - if self.splatTracks.has_key(sequence): + if sequence in self.splatTracks: splatTrack = self.splatTracks[sequence] del self.splatTracks[sequence] splatTrack.finish() @@ -1241,7 +1241,7 @@ def thinkPos(self): else: zoneId = '?' strPos = 'ToonID: %s\n' % uid + '(%.3f' % pos[0] + '\n %.3f' % pos[1] + '\n %.3f)' % pos[2] + '\nH: %.3f' % hpr[0] + '\nZone: %s' % str(zoneId) + '\nVer: %s' % serverVersion + '\nDistrict: %s' % districtName - print 'Current position = ', strPos.replace('\n', ', ') + print('Current position = ', strPos.replace('\n', ', ')) self.setChatAbsolute(strPos, CFThought | CFTimeout) def __placeMarker(self): @@ -1563,7 +1563,7 @@ def __expressState(self, task = None): if place: state = place.fsm.getCurrentState() if state.getName() != self.lastPlaceState: - print 'Place State Change From %s to %s' % (self.lastPlaceState, state.getName()) + print('Place State Change From %s to %s' % (self.lastPlaceState, state.getName())) self.lastPlaceState = state.getName() return Task.cont @@ -1870,7 +1870,7 @@ def setGardenStarted(self, bStarted): def b_setAnimState(self, animName, animMultiplier = 1.0, callback = None, extraArgs = []): if self.wantStatePrint: - print 'Local Toon Anim State %s' % animName + print('Local Toon Anim State %s' % animName) DistributedToon.DistributedToon.b_setAnimState(self, animName, animMultiplier, callback, extraArgs) def swimTimeoutAction(self): @@ -1885,13 +1885,13 @@ def __handleSwimExitTeleport(self, requestStatus): base.cr.gameFSM.request('closeShard', ['afkTimeout']) def sbFriendAdd(self, id, info): - print 'sbFriendAdd' + print('sbFriendAdd') def sbFriendUpdate(self, id, info): - print 'sbFriendUpdate' + print('sbFriendUpdate') def sbFriendRemove(self, id): - print 'sbFriendRemove' + print('sbFriendRemove') def addGolfPage(self): if self.hasPlayedGolf(): @@ -1987,7 +1987,7 @@ def cheatCogdoMazeGame(self, kindOfCheat = 0): maze = base.cr.doFind('DistCogdoMazeGame') if maze: if kindOfCheat == 0: - for suitNum in maze.game.suitsById.keys(): + for suitNum in list(maze.game.suitsById.keys()): suit = maze.game.suitsById[suitNum] maze.sendUpdate('requestSuitHitByGag', [suit.type, suitNum]) diff --git a/toontown/toon/NPCToons.py b/toontown/toon/NPCToons.py index 1a2dfefc5..748e30562 100644 --- a/toontown/toon/NPCToons.py +++ b/toontown/toon/NPCToons.py @@ -128,11 +128,11 @@ def createNPC(air, npcId, desc, zoneId, posIndex = 0, questCallback = None): elif type == NPC_LOOPY: npc = DistributedNPCLoopyGAI.DistributedNPCLoopyGAI(air, npcId) elif type == NPC_INVISIBLE: - npc = DistributedNPCInvisibleAI.DistributedNPCInvisibleAI(air, npcId) + npc = DistributedNPCInvisibleAI.DistributedNPCInvisibleAI(air, npcId) elif type == NPC_RODCLERK: npc = DistributedNPCRodClerkAI.DistributedNPCRodClerkAI(air, npcId) else: - print 'createNPC() error!!!' + print('createNPC() error!!!') npc.setName(name) dna = ToonDNA.ToonDNA() if dnaType == 'r': @@ -1712,24 +1712,24 @@ def isZoneProtected(zoneId): 0, NPC_FISHERMAN), 2226: (2747, - lnames[2226], - ('rll', - 'ls', - 'l', - 'm', - (.302, 1, .09, 1), - 0, - (.302, 1, .09, 1), - (.302, 1, .09, 1), - 0, - 18, - 0, - 18, - 1, - 18), - 'm', - 1, - NPC_REGULAR), + lnames[2226], + ('rll', + 'ls', + 'l', + 'm', + (.302, 1, .09, 1), + 0, + (.302, 1, .09, 1), + (.302, 1, .09, 1), + 0, + 18, + 0, + 18, + 1, + 18), + 'm', + 1, + NPC_REGULAR), 2301: (2804, lnames[2301], ('cll', @@ -2053,347 +2053,347 @@ def isZoneProtected(zoneId): 0, NPC_FISHERMAN), 2322: (2748, - lnames[2322], - ('rll', - 'ss', - 'm', - 'm', - 10, - 0, - 10, - 10, - 0, - 27, - 0, - 27, - 0, - 27), - 'm', - 0, - NPC_REGULAR), + lnames[2322], + ('rll', + 'ss', + 'm', + 'm', + 10, + 0, + 10, + 10, + 0, + 27, + 0, + 27, + 0, + 27), + 'm', + 0, + NPC_REGULAR), 2323: (2741, - lnames[2323], - ('cls', - 'ms', - 'l', - 'm', - 17, - 0, - 0, - 17, - 97, - 13, - 86, - 13, - 1, - 13), - 'm', - 0, - NPC_LOOPY), + lnames[2323], + ('cls', + 'ms', + 'l', + 'm', + 17, + 0, + 0, + 17, + 97, + 13, + 86, + 13, + 1, + 13), + 'm', + 0, + NPC_LOOPY), 2401: (2921, - lnames[2401], - ('xls', - 'ms', - 'l', - 'm', - (0.570312, 0.449219, 0.164062, 1), - 0, - 0, - (0.570312, 0.449219, 0.164062, 1), - 10, - 14, - 3, - 14, - 7, - 18), - 'm', - 0, - NPC_REGULAR), + lnames[2401], + ('xls', + 'ms', + 'l', + 'm', + (0.570312, 0.449219, 0.164062, 1), + 0, + 0, + (0.570312, 0.449219, 0.164062, 1), + 10, + 14, + 3, + 14, + 7, + 18), + 'm', + 0, + NPC_REGULAR), 2402: (2903, - lnames[2402], - ('css', - 'ss', - 's', - 's', - (0.570312, 0.449219, 0.164062, 1), - 0, - 0, - (0.570312, 0.449219, 0.164062, 1), - 12, - 27, - 5, - 37, - 7, - 18), - 'f', - 0, - NPC_REGULAR), + lnames[2402], + ('css', + 'ss', + 's', + 's', + (0.570312, 0.449219, 0.164062, 1), + 0, + 0, + (0.570312, 0.449219, 0.164062, 1), + 12, + 27, + 5, + 37, + 7, + 18), + 'f', + 0, + NPC_REGULAR), 2403: (2902, - lnames[2403], - ('rss', - 'ls', - 'm', - 'm', - (0.996094, 0.898438, 0.320312, 1), - 0, - 0, - (0.996094, 0.898438, 0.320312, 1), - 35, - 27, - 40, - 27, - 30, - 18), - 'm', - 0, - NPC_REGULAR), + lnames[2403], + ('rss', + 'ls', + 'm', + 'm', + (0.996094, 0.898438, 0.320312, 1), + 0, + 0, + (0.996094, 0.898438, 0.320312, 1), + 35, + 27, + 40, + 27, + 30, + 18), + 'm', + 0, + NPC_REGULAR), 2404: (2922, - lnames[2404], - ('dll', - 'ms', - 'l', - 'm', - (0.570312, 0.449219, 0.164062, 1), - 0, - 0, - (0.570312, 0.449219, 0.164062, 1), - 11, - 30, - 10, - 30, - 2, - 30), - 'm', - 0, - NPC_REGULAR), + lnames[2404], + ('dll', + 'ms', + 'l', + 'm', + (0.570312, 0.449219, 0.164062, 1), + 0, + 0, + (0.570312, 0.449219, 0.164062, 1), + 11, + 30, + 10, + 30, + 2, + 30), + 'm', + 0, + NPC_REGULAR), 2405: (2923, - lnames[2405], - ('mss', - 'ms', - 'm', - 'f', - (0.304688, 0.96875, 0.402344, 1), - 0, - 0, - (0.304688, 0.96875, 0.402344, 1), - 119, - 19, - 106, - 19, - 19, - 54), - 'f', - 0, - NPC_REGULAR), + lnames[2405], + ('mss', + 'ms', + 'm', + 'f', + (0.304688, 0.96875, 0.402344, 1), + 0, + 0, + (0.304688, 0.96875, 0.402344, 1), + 119, + 19, + 106, + 19, + 19, + 54), + 'f', + 0, + NPC_REGULAR), 2406: (2905, - lnames[2406], - ('rls', - 'ls', - 'l', - 'm', - 11, - 0, - 11, - 11, - 8, - 22, - 8, - 22, - 7, - 2), - 'm', - 0, - NPC_REGULAR), + lnames[2406], + ('rls', + 'ls', + 'l', + 'm', + 11, + 0, + 11, + 11, + 8, + 22, + 8, + 22, + 7, + 2), + 'm', + 0, + NPC_REGULAR), 2407: (2907, - lnames[2407], - ('fsl', - 'md', - 'm', - 'f', - 21, - 0, - 21, - 21, - 6, - 19, - 6, - 19, - 19, - 27), - 'f', - 0, - NPC_REGULAR), + lnames[2407], + ('fsl', + 'md', + 'm', + 'f', + 21, + 0, + 21, + 21, + 6, + 19, + 6, + 19, + 19, + 27), + 'f', + 0, + NPC_REGULAR), 2408: (2904, - lnames[2408], - ('cls', - 'ld', - 'm', - 'f', - 19, - 0, - 19, - 19, - 5, - 23, - 5, - 23, - 0, - 12), - 'f', - 0, - NPC_REGULAR), + lnames[2408], + ('cls', + 'ld', + 'm', + 'f', + 19, + 0, + 19, + 19, + 5, + 23, + 5, + 23, + 0, + 12), + 'f', + 0, + NPC_REGULAR), 2409: (2908, - lnames[2409], - ('dll', - 'ss', - 's', - 'm', - 18, - 0, - 18, - 18, - 3, - 32, - 3, - 32, - 7, - 2), - 'm', - 0, - NPC_REGULAR), + lnames[2409], + ('dll', + 'ss', + 's', + 'm', + 18, + 0, + 18, + 18, + 3, + 32, + 3, + 32, + 7, + 2), + 'm', + 0, + NPC_REGULAR), 2410: (2909, - lnames[2410], - ('pss', - 'ms', - 'm', - 'm', - 10, - 0, - 10, - 10, - 97, - 27, - 86, - 27, - 37, - 27), - 'm', - 0, - NPC_REGULAR), + lnames[2410], + ('pss', + 'ms', + 'm', + 'm', + 10, + 0, + 10, + 10, + 97, + 27, + 86, + 27, + 37, + 27), + 'm', + 0, + NPC_REGULAR), 2411: (2911, - lnames[2411], - ('bss', - 'ms', - 'm', - 'm', - 26, - 0, - 26, - 26, - 4, - 2, - 4, - 2, - 5, - 9), - 'm', - 0, - NPC_REGULAR), + lnames[2411], + ('bss', + 'ms', + 'm', + 'm', + 26, + 0, + 26, + 26, + 4, + 2, + 4, + 2, + 5, + 9), + 'm', + 0, + NPC_REGULAR), 2412: (2914, - lnames[2412], - ('rsl', - 'ls', - 'm', - 'm', - 13, - 0, - 13, - 13, - 19, - 9, - 9, - 9, - 1, - 16), - 'm', - 0, - NPC_REGULAR), + lnames[2412], + ('rsl', + 'ls', + 'm', + 'm', + 13, + 0, + 13, + 13, + 19, + 9, + 9, + 9, + 1, + 16), + 'm', + 0, + NPC_REGULAR), 2413: (2920, - lnames[2413], - ('mls', - 'md', - 'm', - 'f', - 24, - 0, - 24, - 24, - 5, - 9, - 5, - 9, - 4, - 10), - 'f', - 0, - NPC_REGULAR), + lnames[2413], + ('mls', + 'md', + 'm', + 'f', + 24, + 0, + 24, + 24, + 5, + 9, + 5, + 9, + 4, + 10), + 'f', + 0, + NPC_REGULAR), 2414: (2919, - lnames[2414], - ('mss', - 'ms', - 'm', - 'm', - 10, - 0, - 10, - 10, - 0, - 29, - 0, - 29, - 1, - 5), - 'm', - 0, - NPC_REGULAR), + lnames[2414], + ('mss', + 'ms', + 'm', + 'm', + 10, + 0, + 10, + 10, + 0, + 29, + 0, + 29, + 1, + 5), + 'm', + 0, + NPC_REGULAR), 2415: (2916, - lnames[2415], - ('pss', - 'ls', - 's', - 'm', - 9, - 0, - 9, - 9, - 17, - 11, - 0, - 11, - 4, - 11), - 'm', - 0, - NPC_REGULAR), + lnames[2415], + ('pss', + 'ls', + 's', + 'm', + 9, + 0, + 9, + 9, + 17, + 11, + 0, + 11, + 4, + 11), + 'm', + 0, + NPC_REGULAR), 2416: (2915, - lnames[2416], - ('pss', - 'ld', - 's', - 'f', - 21, - 0, - 21, - 21, - 17, - 17, - 0, - 17, - 4, - 17), - 'f', - 0, - NPC_REGULAR), + lnames[2416], + ('pss', + 'ld', + 's', + 'f', + 21, + 0, + 21, + 21, + 17, + 17, + 0, + 17, + 4, + 17), + 'f', + 0, + NPC_REGULAR), 1001: (1506, lnames[1001], ('rss', @@ -6426,309 +6426,309 @@ def isZoneProtected(zoneId): 0, NPC_REGULAR), 3401: (3901, - lnames[3401], - ('fss', - 'ms', - 'm', - 'm', - (.298, .294, .349, 1), - 0, - (.298, .294, .349, 1), - (.298, .294, .349, 1), - 14, - 8, - 1, - 8, - 1, - 3), - 'm', - 0, - NPC_REGULAR), + lnames[3401], + ('fss', + 'ms', + 'm', + 'm', + (.298, .294, .349, 1), + 0, + (.298, .294, .349, 1), + (.298, .294, .349, 1), + 14, + 8, + 1, + 8, + 1, + 3), + 'm', + 0, + NPC_REGULAR), 3402: (3902, - lnames[3402], - ('xll', - 'ms', - 'm', - 'm', - (.09, .373, .286, 1), - 0, - (.09, .373, .286, 1), - (.09, .373, .286, 1), - 2, - 0, - 2, - 0, - 1, - 0), - 'm', - 0, - NPC_REGULAR), + lnames[3402], + ('xll', + 'ms', + 'm', + 'm', + (.09, .373, .286, 1), + 0, + (.09, .373, .286, 1), + (.09, .373, .286, 1), + 2, + 0, + 2, + 0, + 1, + 0), + 'm', + 0, + NPC_REGULAR), 3403: (3903, - lnames[3403], - ('tss', - 'sd', - 'l', - 'f', - (.09, .176, .384, 1), - 0, - (.09, .176, .384, 1), - (.09, .176, .384, 1), - 6, - 24, - 6, - 24, - 0, - 24), - 'f', - 0, - NPC_REGULAR), + lnames[3403], + ('tss', + 'sd', + 'l', + 'f', + (.09, .176, .384, 1), + 0, + (.09, .176, .384, 1), + (.09, .176, .384, 1), + 6, + 24, + 6, + 24, + 0, + 24), + 'f', + 0, + NPC_REGULAR), 3404: (3904, - lnames[3404], - ('cls', - 'ls', - 'm', - 'm', - (1, 1, 1, 1), - 0, - (1, 1, 1, 1), - (1, 1, 1, 1), - 3, - 6, - 3, - 6, - 5, - 6), - 'm', - 0, - NPC_REGULAR), + lnames[3404], + ('cls', + 'ls', + 'm', + 'm', + (1, 1, 1, 1), + 0, + (1, 1, 1, 1), + (1, 1, 1, 1), + 3, + 6, + 3, + 6, + 5, + 6), + 'm', + 0, + NPC_REGULAR), 3405: (3905, - lnames[3405], - ('css', - 'ms', - 'm', - 'm', - (.929, .459, .141, 1), - 0, - (.929, .459, .141, 1), - (.929, .459, .141, 1), - 14, - 0, - 2, - 0, - 0, - 0), - 'm', - 0, - NPC_REGULAR), + lnames[3405], + ('css', + 'ms', + 'm', + 'm', + (.929, .459, .141, 1), + 0, + (.929, .459, .141, 1), + (.929, .459, .141, 1), + 14, + 0, + 2, + 0, + 0, + 0), + 'm', + 0, + NPC_REGULAR), 3406: (3906, - lnames[3406], - ('ass', - 'ms', - 'm', - 'm', - (.914, .016, .016, 1), - 0, - (.914, .016, .016, 1), - (.914, .016, .016, 1), - 3, - 23, - 3, - 23, - 7, - 22), - 'm', - 0, - NPC_REGULAR), + lnames[3406], + ('ass', + 'ms', + 'm', + 'm', + (.914, .016, .016, 1), + 0, + (.914, .016, .016, 1), + (.914, .016, .016, 1), + 3, + 23, + 3, + 23, + 7, + 22), + 'm', + 0, + NPC_REGULAR), 3407: (3907, - lnames[3407], - ('dss', - 'sd', - 'm', - 'f', - (.502, .969, .827, 1), - 0, - (.502, .969, .827, 1), - (.502, .969, .827, 1), - 2, - 9, - 2, - 9, - 8, - 27), - 'f', - 0, - NPC_REGULAR), + lnames[3407], + ('dss', + 'sd', + 'm', + 'f', + (.502, .969, .827, 1), + 0, + (.502, .969, .827, 1), + (.502, .969, .827, 1), + 2, + 9, + 2, + 9, + 8, + 27), + 'f', + 0, + NPC_REGULAR), 3408: (3908, - lnames[3408], - ('bss', - 'md', - 'l', - 'f', - (.341, .047, 1, 1), - 0, - (.341, .047, 1, 1), - (.341, .047, 1, 1), - 5, - 27, - 5, - 27, - 7, - 22), - 'f', - 0, - NPC_REGULAR), + lnames[3408], + ('bss', + 'md', + 'l', + 'f', + (.341, .047, 1, 1), + 0, + (.341, .047, 1, 1), + (.341, .047, 1, 1), + 5, + 27, + 5, + 27, + 7, + 22), + 'f', + 0, + NPC_REGULAR), 3409: (3909, - lnames[3409], - ('vsl', - 'ms', - 's', - 'm', - (.337, .051, .769, 1), - 0, - (.337, .051, .769, 1), - (.337, .051, .769, 1), - 19, - 16, - 9, - 16, - 7, - 14), - 'm', - 0, - NPC_REGULAR), + lnames[3409], + ('vsl', + 'ms', + 's', + 'm', + (.337, .051, .769, 1), + 0, + (.337, .051, .769, 1), + (.337, .051, .769, 1), + 19, + 16, + 9, + 16, + 7, + 14), + 'm', + 0, + NPC_REGULAR), 3410: (3910, - lnames[3410], - ('sss', - 'ls', - 's', - 'm', - (.871, .949, .294, 1), - 0, - (.871, .949, .294, 1), - (.871, .949, .294, 1), - 34, - 27, - 0, - 27, - 0, - 27), - 'm', - 0, - NPC_REGULAR), + lnames[3410], + ('sss', + 'ls', + 's', + 'm', + (.871, .949, .294, 1), + 0, + (.871, .949, .294, 1), + (.871, .949, .294, 1), + 34, + 27, + 0, + 27, + 0, + 27), + 'm', + 0, + NPC_REGULAR), 3411: (3911, - lnames[3411], - ('css', - 'ms', - 'l', - 'm', - (.988, .863, .145, 1), - 0, - (.988, .863, .145, 1), - (.988, .863, .145, 1), - 9, - 24, - 9, - 24, - 7, - 14), - 'm', - 0, - NPC_REGULAR), + lnames[3411], + ('css', + 'ms', + 'l', + 'm', + (.988, .863, .145, 1), + 0, + (.988, .863, .145, 1), + (.988, .863, .145, 1), + 9, + 24, + 9, + 24, + 7, + 14), + 'm', + 0, + NPC_REGULAR), 3412: (3912, - lnames[3412], - ('zss', - 'ms', - 'm', - 'm', - (.404, .008, .859, 1), - 0, - (.404, .008, .859, 1), - (.404, .008, .859, 1), - 99, - 27, - 86, - 27, - 39, - 27), - 'm', - 0, - NPC_REGULAR), + lnames[3412], + ('zss', + 'ms', + 'm', + 'm', + (.404, .008, .859, 1), + 0, + (.404, .008, .859, 1), + (.404, .008, .859, 1), + 99, + 27, + 86, + 27, + 39, + 27), + 'm', + 0, + NPC_REGULAR), 3413: (3913, - lnames[3413], - ('hss', - 'ms', - 'm', - 'm', - (.592, .898, .882, 1), - 0, - (.592, .898, .882, 1), - (.592, .898, .882, 1), - 10, - 18, - 10, - 18, - 1, - 18), - 'm', - 0, - NPC_REGULAR), + lnames[3413], + ('hss', + 'ms', + 'm', + 'm', + (.592, .898, .882, 1), + 0, + (.592, .898, .882, 1), + (.592, .898, .882, 1), + 10, + 18, + 10, + 18, + 1, + 18), + 'm', + 0, + NPC_REGULAR), 3414: (3914, - lnames[3414], - ('nss', - 'ms', - 'm', - 'm', - (.424, .075, .627, 1), - 0, - (.424, .075, .627, 1), - (.424, .075, .627, 1), - 98, - 27, - 86, - 27, - 37, - 27), - 'm', - 0, - NPC_REGULAR), + lnames[3414], + ('nss', + 'ms', + 'm', + 'm', + (.424, .075, .627, 1), + 0, + (.424, .075, .627, 1), + (.424, .075, .627, 1), + 98, + 27, + 86, + 27, + 37, + 27), + 'm', + 0, + NPC_REGULAR), 3415: (3915, - lnames[3415], - ('all', - 'ms', - 'l', - 'm', - (.09, .776, .776, 1), - 0, - (.09, .776, .776, 1), - (.09, .776, .776, 1), - 54, - 27, - 43, - 27, - 7, - 2), - 'm', - 0, - NPC_REGULAR), + lnames[3415], + ('all', + 'ms', + 'l', + 'm', + (.09, .776, .776, 1), + 0, + (.09, .776, .776, 1), + (.09, .776, .776, 1), + 54, + 27, + 43, + 27, + 7, + 2), + 'm', + 0, + NPC_REGULAR), 3416: (3916, - lnames[3416], - ('bss', - 'ss', - 's', - 'm', - (1, 1, 1, 1), - 0, - (1, 1, 1, 1), - (1, 1, 1, 1), - 31, - 27, - 22, - 27, - 1, - 20), - 'm', - 0, - NPC_REGULAR), + lnames[3416], + ('bss', + 'ss', + 's', + 'm', + (1, 1, 1, 1), + 0, + (1, 1, 1, 1), + (1, 1, 1, 1), + 31, + 27, + 22, + 27, + 1, + 20), + 'm', + 0, + NPC_REGULAR), 4001: (4502, lnames[4001], 'r', @@ -8891,195 +8891,195 @@ def isZoneProtected(zoneId): 0, NPC_FISHERMAN), 4400: (4903, - lnames[4400], - ('rsl', - 'ms', - 'l', - 'm', - 17, - 0, - 17, - 17, - 67, - 27, - 56, - 27, - 17, - 27), - 'm', - 0, - NPC_REGULAR), + lnames[4400], + ('rsl', + 'ms', + 'l', + 'm', + 17, + 0, + 17, + 17, + 67, + 27, + 56, + 27, + 17, + 27), + 'm', + 0, + NPC_REGULAR), 4401: (4905, - lnames[4401], - ('csl', - 'ms', - 's', - 'f', - 5, - 0, - 5, - 5, - 97, - 27, - 86, - 27, - 43, - 27), - 'f', - 0, - NPC_REGULAR), + lnames[4401], + ('csl', + 'ms', + 's', + 'f', + 5, + 0, + 5, + 5, + 97, + 27, + 86, + 27, + 43, + 27), + 'f', + 0, + NPC_REGULAR), 4402: (4907, - lnames[4402], - ('cls', - 'ss', - 'm', - 'm', - 18, - 0, - 18, - 18, - 49, - 27, - 38, - 27, - 25, - 27), - 'm', - 0, - NPC_REGULAR), + lnames[4402], + ('cls', + 'ss', + 'm', + 'm', + 18, + 0, + 18, + 18, + 49, + 27, + 38, + 27, + 25, + 27), + 'm', + 0, + NPC_REGULAR), 4403: (4909, - lnames[4403], - ('xll', - 'ls', - 'l', - 'm', - 26, - 0, - 26, - 26, - 0, - 29, - 0, - 29, - 0, - 29), - 'm', - 0, - NPC_REGULAR), + lnames[4403], + ('xll', + 'ls', + 'l', + 'm', + 26, + 0, + 26, + 26, + 0, + 29, + 0, + 29, + 0, + 29), + 'm', + 0, + NPC_REGULAR), 4404: (4906, - lnames[4404], - ('css', - 'ls', - 'l', - 'm', - 2, - 0, - 2, - 2, - 14, - 10, - 10, - 10, - 51, - 12), - 'm', - 0, - NPC_REGULAR), + lnames[4404], + ('css', + 'ls', + 'l', + 'm', + 2, + 0, + 2, + 2, + 14, + 10, + 10, + 10, + 51, + 12), + 'm', + 0, + NPC_REGULAR), 4405: (4908, - lnames[4405], - ('fls', - 'ls', - 'm', - 'f', - 24, - 0, - 24, - 24, - 6, - 3, - 6, - 3, - 0, - 3), - 'f', - 0, - NPC_REGULAR), + lnames[4405], + ('fls', + 'ls', + 'm', + 'f', + 24, + 0, + 24, + 24, + 6, + 3, + 6, + 3, + 0, + 3), + 'f', + 0, + NPC_REGULAR), 4406: (4911, - lnames[4406], - ('dss', - 'ms', - 's', - 'm', - 18, - 0, - 18, - 18, - 54, - 27, - 43, - 27, - 2, - 16), - 'm', - 0, - NPC_REGULAR), + lnames[4406], + ('dss', + 'ms', + 's', + 'm', + 18, + 0, + 18, + 18, + 54, + 27, + 43, + 27, + 2, + 16), + 'm', + 0, + NPC_REGULAR), 4407: (4913, - lnames[4407], - ('hss', - 'sd', - 'm', - 'f', - 7, - 0, - 7, - 7, - 24, - 27, - 0, - 1, - 0, - 12), - 'f', - 0, - NPC_REGULAR), + lnames[4407], + ('hss', + 'sd', + 'm', + 'f', + 7, + 0, + 7, + 7, + 24, + 27, + 0, + 1, + 0, + 12), + 'f', + 0, + NPC_REGULAR), 4408: (4912, - lnames[4408], - ('css', - 'ms', - 'm', - 'm', - 10, - 0, - 10, - 10, - 119, - 27, - 106, - 27, - 46, - 27), - 'm', - 0, - NPC_REGULAR), + lnames[4408], + ('css', + 'ms', + 'm', + 'm', + 10, + 0, + 10, + 10, + 119, + 27, + 106, + 27, + 46, + 27), + 'm', + 0, + NPC_REGULAR), 4409: (4910, - lnames[4409], - ('bsl', - 'ms', - 'm', - 'm', - 5, - 0, - 5, - 5, - 19, - 28, - 0, - 28, - 0, - 28), - 'm', - 0, - NPC_REGULAR), + lnames[4409], + ('bsl', + 'ms', + 'm', + 'm', + 5, + 0, + 5, + 5, + 19, + 28, + 0, + 28, + 0, + 28), + 'm', + 0, + NPC_REGULAR), 5001: (5502, lnames[5001], ('fls', diff --git a/toontown/toon/TTEmote.py b/toontown/toon/TTEmote.py index bb42693ee..527d6d497 100644 --- a/toontown/toon/TTEmote.py +++ b/toontown/toon/TTEmote.py @@ -521,7 +521,7 @@ def lockStateChangeMsg(self): def unlockStateChangeMsg(self): if self.stateChangeMsgLocks <= 0: - print PythonUtil.lineTag() + ': someone unlocked too many times' + print(PythonUtil.lineTag() + ': someone unlocked too many times') return self.stateChangeMsgLocks -= 1 if self.stateChangeMsgLocks == 0 and self.stateHasChanged: @@ -537,12 +537,12 @@ def emoteEnableStateChanged(self): def disableAll(self, toon, msg = None): if toon != base.localAvatar: return - self.disableGroup(xrange(len(self.emoteFunc)), toon) + self.disableGroup(range(len(self.emoteFunc)), toon) def releaseAll(self, toon, msg = None): if toon != base.localAvatar: return - self.enableGroup(xrange(len(self.emoteFunc)), toon) + self.enableGroup(range(len(self.emoteFunc)), toon) def disableBody(self, toon, msg = None): if toon != base.localAvatar: @@ -582,7 +582,7 @@ def enableGroup(self, indices, toon): self.unlockStateChangeMsg() def disable(self, index, toon): - if isinstance(index, types.StringType): + if isinstance(index, bytes): index = OTPLocalizer.EmoteFuncDict[index] self.emoteFunc[index][1] = self.emoteFunc[index][1] + 1 if toon is base.localAvatar: @@ -590,7 +590,7 @@ def disable(self, index, toon): self.emoteEnableStateChanged() def enable(self, index, toon): - if isinstance(index, types.StringType): + if isinstance(index, bytes): index = OTPLocalizer.EmoteFuncDict[index] self.emoteFunc[index][1] = self.emoteFunc[index][1] - 1 if toon is base.localAvatar: @@ -601,7 +601,7 @@ def doEmote(self, toon, emoteIndex, ts = 0, volume = 1): try: func = self.emoteFunc[emoteIndex][0] except: - print 'Error in finding emote func %s' % emoteIndex + print('Error in finding emote func %s' % emoteIndex) return (None, None) def clearEmoteTrack(): diff --git a/toontown/toon/Toon.py b/toontown/toon/Toon.py index d388dd582..c4dfa6f30 100644 --- a/toontown/toon/Toon.py +++ b/toontown/toon/Toon.py @@ -27,6 +27,7 @@ from toontown.suit import Suit from toontown.toonbase import TTLocalizer from toontown.toonbase import ToontownGlobals +import importlib def teleportDebug(requestStatus, msg, onlyIfToAv = True): if teleportNotify.getDebug(): @@ -184,17 +185,17 @@ def teleportDebug(requestStatus, msg, onlyIfToAv = True): def loadModels(): global Preloaded if not Preloaded: - print 'Preloading avatars...' + print('Preloading avatars...') def preload(task): - for key in LegDict.keys(): + for key in list(LegDict.keys()): fileRoot = LegDict[key] Preloaded[fileRoot+'-1000'] = loader.loadModel('phase_3' + fileRoot + '1000') Preloaded[fileRoot+'-500'] = loader.loadModel('phase_3' + fileRoot + '500') Preloaded[fileRoot+'-250'] = loader.loadModel('phase_3' + fileRoot + '250') - for key in TorsoDict.keys(): + for key in list(TorsoDict.keys()): fileRoot = TorsoDict[key] Preloaded[fileRoot+'-1000'] = loader.loadModel('phase_3' + fileRoot + '1000') @@ -270,7 +271,7 @@ def loadPhaseAnims(phaseStr = 'phase_3', loadFlag = 1): animList = Phase12AnimList else: self.notify.error('Unknown phase string %s' % phaseStr) - for key in LegDict.keys(): + for key in list(LegDict.keys()): for anim in animList: if loadFlag: pass @@ -278,7 +279,7 @@ def loadPhaseAnims(phaseStr = 'phase_3', loadFlag = 1): if base.localAvatar.style.legs == key: base.localAvatar.unloadAnims([anim[0]], 'legs', None) - for key in TorsoDict.keys(): + for key in list(TorsoDict.keys()): for anim in animList: if loadFlag: pass @@ -286,7 +287,7 @@ def loadPhaseAnims(phaseStr = 'phase_3', loadFlag = 1): if base.localAvatar.style.torso == key: base.localAvatar.unloadAnims([anim[0]], 'torso', None) - for key in HeadDict.keys(): + for key in list(HeadDict.keys()): if key.find('d') >= 0: for anim in animList: if loadFlag: @@ -316,19 +317,19 @@ def compileGlobalAnimList(): 'phase_12'] for animList in phaseList: phaseStr = phaseStrList[phaseList.index(animList)] - for key in LegDict.keys(): + for key in list(LegDict.keys()): LegsAnimDict.setdefault(key, {}) for anim in animList: file = phaseStr + LegDict[key] + anim[1] LegsAnimDict[key][anim[0]] = file - for key in TorsoDict.keys(): + for key in list(TorsoDict.keys()): TorsoAnimDict.setdefault(key, {}) for anim in animList: file = phaseStr + TorsoDict[key] + anim[1] TorsoAnimDict[key][anim[0]] = file - for key in HeadDict.keys(): + for key in list(HeadDict.keys()): if key.find('d') >= 0: HeadAnimDict.setdefault(key, {}) for anim in animList: @@ -1035,7 +1036,7 @@ def generateToonClothes(self, fromNet = 0): sleeves.setTexture(sleeveTex, 1) sleeves.setColor(sleeveColor) bottoms = thisPart.findAllMatches('**/torso-bot') - for bottomNum in xrange(0, bottoms.getNumPaths()): + for bottomNum in range(0, bottoms.getNumPaths()): bottom = bottoms.getPath(bottomNum) bottom.setTexture(bottomTex, 1) bottom.setColor(bottomColor) @@ -1071,7 +1072,7 @@ def generateHat(self, fromRTM = False): tex.setMagfilter(Texture.FTLinear) hatGeom.setTexture(tex, 1) if fromRTM: - reload(AccessoryGlobals) + importlib.reload(AccessoryGlobals) transOffset = None if AccessoryGlobals.ExtendedHatTransTable.get(hat[0]): transOffset = AccessoryGlobals.ExtendedHatTransTable[hat[0]].get(self.style.head[:2]) @@ -1114,7 +1115,7 @@ def generateGlasses(self, fromRTM = False): tex.setMagfilter(Texture.FTLinear) glassesGeom.setTexture(tex, 1) if fromRTM: - reload(AccessoryGlobals) + importlib.reload(AccessoryGlobals) transOffset = None if AccessoryGlobals.ExtendedGlassesTransTable.get(glasses[0]): transOffset = AccessoryGlobals.ExtendedGlassesTransTable[glasses[0]].get(self.style.head[:2]) @@ -1154,7 +1155,7 @@ def generateBackpack(self, fromRTM = False): tex.setMagfilter(Texture.FTLinear) geom.setTexture(tex, 1) if fromRTM: - reload(AccessoryGlobals) + importlib.reload(AccessoryGlobals) transOffset = None if AccessoryGlobals.ExtendedBackpackTransTable.get(backpack[0]): transOffset = AccessoryGlobals.ExtendedBackpackTransTable[backpack[0]].get(self.style.torso[:1]) @@ -1323,7 +1324,7 @@ def findSomethingToLookAt(self): self.lerpLookAt(Point3(x, 1.5, y), blink=1) return nodePathList = [] - for id, obj in self.cr.doId2do.items(): + for id, obj in list(self.cr.doId2do.items()): if hasattr(obj, 'getStareAtNodeAndOffset') and obj != self: node, offset = obj.getStareAtNodeAndOffset() if node.getY(self) > 0.0: @@ -2257,11 +2258,11 @@ def getPieces(self, *pieces): for partName, pieceNames in pieces: part = self.getPart(partName, lodName) if part: - if type(pieceNames) == types.StringType: + if type(pieceNames) == bytes: pieceNames = (pieceNames,) for pieceName in pieceNames: npc = part.findAllMatches('**/%s;+s' % pieceName) - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): results.append(npc[i]) return results @@ -2313,7 +2314,7 @@ def __doHeadScale(self, scale, lerpTime): if not self.headParts: return track - for hi in xrange(self.headParts.getNumPaths()): + for hi in range(self.headParts.getNumPaths()): head = self.headParts[hi] track.append(LerpScaleInterval(head, lerpTime, scale, blendType='easeInOut')) @@ -2331,7 +2332,7 @@ def __doLegsScale(self, scale, lerpTime): return track if not self.legsParts: return track - for li in xrange(self.legsParts.getNumPaths()): + for li in range(self.legsParts.getNumPaths()): legs = self.legsParts[li] torso = self.torsoParts[li] track.append(LerpScaleInterval(legs, lerpTime, scale, blendType='easeInOut')) @@ -2469,10 +2470,10 @@ def getDustCloudIval(): def hideParts(): self.notify.debug('HidePaths') - for hi in xrange(self.headParts.getNumPaths()): + for hi in range(self.headParts.getNumPaths()): head = self.headParts[hi] parts = head.getChildren() - for pi in xrange(parts.getNumPaths()): + for pi in range(parts.getNumPaths()): p = parts[pi] if not p.isHidden(): p.hide() @@ -2489,10 +2490,10 @@ def hideParts(): def showHiddenParts(): self.notify.debug('ShowHiddenPaths') - for hi in xrange(self.headParts.getNumPaths()): + for hi in range(self.headParts.getNumPaths()): head = self.headParts[hi] parts = head.getChildren() - for pi in xrange(parts.getNumPaths()): + for pi in range(parts.getNumPaths()): p = parts[pi] if not self.snowMen.hasPath(p) and p.getTag('snowman') == 'enabled': p.show() @@ -4984,9 +4985,9 @@ def putOnSuit(self, suitType, setDisplayName = True, rental = False): self.stopTrackAnimToSpeed() self.startTrackAnimToSpeed() self.controlManager.disableAvatarJump() - indices = range(OTPLocalizer.SCMenuCommonCogIndices[0], OTPLocalizer.SCMenuCommonCogIndices[1] + 1) + indices = list(range(OTPLocalizer.SCMenuCommonCogIndices[0], OTPLocalizer.SCMenuCommonCogIndices[1] + 1)) customIndices = OTPLocalizer.SCMenuCustomCogIndices[suitType] - indices += range(customIndices[0], customIndices[1] + 1) + indices += list(range(customIndices[0], customIndices[1] + 1)) self.chatMgr.chatInputSpeedChat.addCogMenu(indices) self.suit.loop('neutral') self.isDisguised = 1 @@ -4998,7 +4999,7 @@ def putOnSuit(self, suitType, setDisplayName = True, rental = False): name = self.getName() suitDept = SuitDNA.suitDepts.index(SuitDNA.getSuitDept(suitType)) suitName = SuitBattleGlobals.SuitAttributes[suitType]['name'] - print self.cogLevels + print(self.cogLevels) if self.cogReviveLevels[suitDept] == -1: self.nametag.setText(TTLocalizer.SuitBaseNameWithLevel % {'name': name, 'dept': suitName, diff --git a/toontown/toon/ToonExperience.py b/toontown/toon/ToonExperience.py index e282e4850..d7460c68e 100644 --- a/toontown/toon/ToonExperience.py +++ b/toontown/toon/ToonExperience.py @@ -5,7 +5,7 @@ from direct.distributed.PyDatagramIterator import PyDatagramIterator from otp.otpbase import OTPGlobals levels = [0] -for level in xrange(1,100): +for level in range(1,100): level += 1 exp = int(15 * level * (level+5)) levels.append(exp) @@ -33,7 +33,7 @@ def setExp(self, exp): def getExpLevel(self, experience): exp = self.ExpPerLevel - for i in xrange(len(self.ExpPerLevel)): + for i in range(len(self.ExpPerLevel)): if experience < exp[i] and experience >= exp[i-1]: return i diff --git a/toontown/toon/ToonHead.py b/toontown/toon/ToonHead.py index 79c67a4b3..0324045d1 100644 --- a/toontown/toon/ToonHead.py +++ b/toontown/toon/ToonHead.py @@ -71,10 +71,10 @@ def preloadToonHeads(): global PreloadHeads if not PreloadHeads: - print 'Preloading Toon heads...' + print('Preloading Toon heads...') def preload(task): - for key in HeadDict.keys(): + for key in list(HeadDict.keys()): fileRoot = HeadDict[key] PreloadHeads['phase_3' + fileRoot + '1000'] = loader.loadModel('phase_3' + fileRoot + '1000') @@ -783,7 +783,7 @@ def __fixEyes(self, style, forGui = 0): lp = self.__eyes.find('**/joint_pupilL*') rp = self.__eyes.find('**/joint_pupilR*') if lp.isEmpty() or rp.isEmpty(): - print 'Unable to locate pupils.' + print('Unable to locate pupils.') else: leye = self.__eyes.attachNewNode('leye') reye = self.__eyes.attachNewNode('reye') @@ -918,7 +918,7 @@ def __fixHeadLongLong(self, style, lodName = None, copy = 1): else: searchRoot = self.find('**/' + str(lodName)) otherParts = searchRoot.findAllMatches('**/*short*') - for partNum in xrange(0, otherParts.getNumPaths()): + for partNum in range(0, otherParts.getNumPaths()): if copy: otherParts.getPath(partNum).removeNode() else: @@ -961,7 +961,7 @@ def __fixHeadLongShort(self, style, lodName = None, copy = 1): self.find('**/head-front-short').hide() if animalType != 'rabbit': muzzleParts = searchRoot.findAllMatches('**/muzzle-long*') - for partNum in xrange(0, muzzleParts.getNumPaths()): + for partNum in range(0, muzzleParts.getNumPaths()): if copy: muzzleParts.getPath(partNum).removeNode() else: @@ -969,7 +969,7 @@ def __fixHeadLongShort(self, style, lodName = None, copy = 1): else: muzzleParts = searchRoot.findAllMatches('**/muzzle-short*') - for partNum in xrange(0, muzzleParts.getNumPaths()): + for partNum in range(0, muzzleParts.getNumPaths()): if copy: muzzleParts.getPath(partNum).removeNode() else: @@ -1012,7 +1012,7 @@ def __fixHeadShortLong(self, style, lodName = None, copy = 1): searchRoot.find('**/head-front-long').hide() if animalType != 'rabbit': muzzleParts = searchRoot.findAllMatches('**/muzzle-short*') - for partNum in xrange(0, muzzleParts.getNumPaths()): + for partNum in range(0, muzzleParts.getNumPaths()): if copy: muzzleParts.getPath(partNum).removeNode() else: @@ -1020,7 +1020,7 @@ def __fixHeadShortLong(self, style, lodName = None, copy = 1): else: muzzleParts = searchRoot.findAllMatches('**/muzzle-long*') - for partNum in xrange(0, muzzleParts.getNumPaths()): + for partNum in range(0, muzzleParts.getNumPaths()): if copy: muzzleParts.getPath(partNum).removeNode() else: @@ -1032,7 +1032,7 @@ def __fixHeadShortShort(self, style, lodName = None, copy = 1): else: searchRoot = self.find('**/' + str(lodName)) otherParts = searchRoot.findAllMatches('**/*long*') - for partNum in xrange(0, otherParts.getNumPaths()): + for partNum in range(0, otherParts.getNumPaths()): if copy: otherParts.getPath(partNum).removeNode() else: @@ -1373,82 +1373,82 @@ def getLaughMuzzles(self): def showNormalMuzzle(self): if self.isIgnoreCheesyEffect(): return - for muzzleNum in xrange(len(self.__muzzles)): + for muzzleNum in range(len(self.__muzzles)): self.__muzzles[muzzleNum].show() def hideNormalMuzzle(self): if self.isIgnoreCheesyEffect(): return - for muzzleNum in xrange(len(self.__muzzles)): + for muzzleNum in range(len(self.__muzzles)): self.__muzzles[muzzleNum].hide() def showAngryMuzzle(self): if self.isIgnoreCheesyEffect(): return - for muzzleNum in xrange(len(self.__angryMuzzles)): + for muzzleNum in range(len(self.__angryMuzzles)): self.__angryMuzzles[muzzleNum].show() self.__muzzles[muzzleNum].hide() def hideAngryMuzzle(self): if self.isIgnoreCheesyEffect(): return - for muzzleNum in xrange(len(self.__angryMuzzles)): + for muzzleNum in range(len(self.__angryMuzzles)): self.__angryMuzzles[muzzleNum].hide() self.__muzzles[muzzleNum].show() def showSadMuzzle(self): if self.isIgnoreCheesyEffect(): return - for muzzleNum in xrange(len(self.__sadMuzzles)): + for muzzleNum in range(len(self.__sadMuzzles)): self.__sadMuzzles[muzzleNum].show() self.__muzzles[muzzleNum].hide() def hideSadMuzzle(self): if self.isIgnoreCheesyEffect(): return - for muzzleNum in xrange(len(self.__sadMuzzles)): + for muzzleNum in range(len(self.__sadMuzzles)): self.__sadMuzzles[muzzleNum].hide() self.__muzzles[muzzleNum].show() def showSmileMuzzle(self): if self.isIgnoreCheesyEffect(): return - for muzzleNum in xrange(len(self.__smileMuzzles)): + for muzzleNum in range(len(self.__smileMuzzles)): self.__smileMuzzles[muzzleNum].show() self.__muzzles[muzzleNum].hide() def hideSmileMuzzle(self): if self.isIgnoreCheesyEffect(): return - for muzzleNum in xrange(len(self.__smileMuzzles)): + for muzzleNum in range(len(self.__smileMuzzles)): self.__smileMuzzles[muzzleNum].hide() self.__muzzles[muzzleNum].show() def showLaughMuzzle(self): if self.isIgnoreCheesyEffect(): return - for muzzleNum in xrange(len(self.__laughMuzzles)): + for muzzleNum in range(len(self.__laughMuzzles)): self.__laughMuzzles[muzzleNum].show() self.__muzzles[muzzleNum].hide() def hideLaughMuzzle(self): if self.isIgnoreCheesyEffect(): return - for muzzleNum in xrange(len(self.__laughMuzzles)): + for muzzleNum in range(len(self.__laughMuzzles)): self.__laughMuzzles[muzzleNum].hide() self.__muzzles[muzzleNum].show() def showSurpriseMuzzle(self): if self.isIgnoreCheesyEffect(): return - for muzzleNum in xrange(len(self.__surpriseMuzzles)): + for muzzleNum in range(len(self.__surpriseMuzzles)): self.__surpriseMuzzles[muzzleNum].show() self.__muzzles[muzzleNum].hide() def hideSurpriseMuzzle(self): if self.isIgnoreCheesyEffect(): return - for muzzleNum in xrange(len(self.__surpriseMuzzles)): + for muzzleNum in range(len(self.__surpriseMuzzles)): self.__surpriseMuzzles[muzzleNum].hide() self.__muzzles[muzzleNum].show() diff --git a/toontown/toon/ToonTeleportPanel.py b/toontown/toon/ToonTeleportPanel.py index 9dbcc4ba3..4c6b401b7 100644 --- a/toontown/toon/ToonTeleportPanel.py +++ b/toontown/toon/ToonTeleportPanel.py @@ -236,7 +236,7 @@ def enterTeleport(self, shardId, hoodId, zoneId): shardName = base.cr.getShardName(shardId) if shardName is None: shardName = 'unknown' - print 'enterTeleport: %r, %r, %r, %r, %r' % (shardId, shardName, hoodId, zoneId, self.avId) + print('enterTeleport: %r, %r, %r, %r, %r' % (shardId, shardName, hoodId, zoneId, self.avId)) hoodsVisited = base.localAvatar.hoodsVisited canonicalHoodId = ZoneUtil.getCanonicalZoneId(hoodId) if hoodId == ToontownGlobals.MyEstate: @@ -250,7 +250,7 @@ def enterTeleport(self, shardId, hoodId, zoneId): teleportNotify.debug('enterTeleport: unknownHood') self.fsm.request('unknownHood', [hoodId]) elif canonicalHoodId not in base.cr.hoodMgr.getAvailableZones(): - print 'hoodId %d not ready' % hoodId + print('hoodId %d not ready' % hoodId) self.fsm.request('unavailableHood', [hoodId]) else: if shardId == base.localAvatar.defaultShard: diff --git a/toontown/toonbase/ClientStart.py b/toontown/toonbase/ClientStart.py index d512c44be..01a7b62a9 100644 --- a/toontown/toonbase/ClientStart.py +++ b/toontown/toonbase/ClientStart.py @@ -1,11 +1,11 @@ #!/usr/bin/env python2 -import __builtin__ +import builtins import os -__builtin__.process = 'client' +builtins.process = 'client' # Temporary hack patch: -__builtin__.__dict__.update(__import__('pandac.PandaModules', fromlist = ['*']).__dict__) +builtins.__dict__.update(__import__('pandac.PandaModules', fromlist = ['*']).__dict__) from direct.extensions_native import HTTPChannel_extensions from direct.extensions_native import Mat3_extensions from direct.extensions_native import VBase3_extensions @@ -17,7 +17,7 @@ loadPrcFile('dependencies/config/release/dev.prc') import sys -import StringIO +import io vfs = VirtualFileSystem.getGlobalPtr() import glob @@ -30,9 +30,9 @@ preferencesFilename = ConfigVariableString( 'preferences-filename', 'user/preferences.json').getValue() notify.info('Reading %s...' % preferencesFilename) -__builtin__.settings = Settings(preferencesFilename) +builtins.settings = Settings(preferencesFilename) from toontown.settings import ToontownSettings -__builtin__.ttsettings = ToontownSettings +builtins.ttsettings = ToontownSettings for setting in ttsettings.DefaultSettings: if setting not in settings: @@ -63,7 +63,7 @@ notify.info('Successfully Mounted:' + file) notify.info("Default Pack Loaded!") from toontown.toonbase.ContentPackManager import ContentPackManager -__builtin__.ContentPackMgr = ContentPackManager() +builtins.ContentPackMgr = ContentPackManager() ContentPackMgr.loadAll() loadDisplay = settings.get('loadDisplay', 'pandagl') @@ -73,12 +73,12 @@ import time import sys import random -import __builtin__ +import builtins try: from toontown.launcher.TTALauncher import TTALauncher launcher = TTALauncher() - __builtin__.launcher = launcher + builtins.launcher = launcher except Exception as e: raise (e) @@ -177,7 +177,7 @@ version.cleanup() del version base.loader = base.loader -__builtin__.loader = base.loader +builtins.loader = base.loader autoRun = ConfigVariableBool('toontown-auto-run', 1) if autoRun: @@ -187,5 +187,5 @@ raise except: from toontown.toonbase import ToonPythonUtil as PythonUtil - print PythonUtil.describeException() + print(PythonUtil.describeException()) raise diff --git a/toontown/toonbase/ClientStartDist.py b/toontown/toonbase/ClientStartDist.py index 61a137080..896acfd9c 100644 --- a/toontown/toonbase/ClientStartDist.py +++ b/toontown/toonbase/ClientStartDist.py @@ -1,7 +1,7 @@ # This is a temp patch. # It should really be done by the runtime (e.g. Project Altis.exe): import sys -import __builtin__ +import builtins # Replace some modules that do exec: import collections @@ -10,12 +10,12 @@ # Disable both dev,debug before anything else. # This is to make sure the distrubution client doesn't # get any special perms or anything of the sort. -__builtin__.__dev__ = False +builtins.__dev__ = False def __runfunc(*args, **kw): print("Something Spoopys Happened!") -__builtin__.__dict__.update(__import__('pandac.PandaModules', fromlist = ['*']).__dict__) +builtins.__dict__.update(__import__('pandac.PandaModules', fromlist = ['*']).__dict__) # __builtin__.eval = __runfunc # __builtin__.compile = __runfunc # __builtin__.execfile = __runfunc diff --git a/toontown/toonbase/ContentPackManager.py b/toontown/toonbase/ContentPackManager.py index 2221657b8..727fc217a 100644 --- a/toontown/toonbase/ContentPackManager.py +++ b/toontown/toonbase/ContentPackManager.py @@ -70,8 +70,8 @@ def applyFile(self, filename): for subfilename in mf.getSubfileNames(): if os.path.splitext(subfilename)[1] not in SupportedExtensions: mf.removeSubfile(subfilename) - print("Removing a file that is not allowed: %s" % str(subfilename)) + print(("Removing a file that is not allowed: %s" % str(subfilename))) self.vfSys.mount(mf, self.mountPoint, 0) - print('Successfully Mounted: ' + str(filename)) + print(('Successfully Mounted: ' + str(filename))) diff --git a/toontown/toonbase/StartCompiledGame.py b/toontown/toonbase/StartCompiledGame.py index e2c903cf3..5fd1616a5 100644 --- a/toontown/toonbase/StartCompiledGame.py +++ b/toontown/toonbase/StartCompiledGame.py @@ -37,7 +37,7 @@ def readDCFile(self, dcFileNames = None): self.dclassesByNumber = {} self.hashVal = 0 - if isinstance(dcFileNames, types.StringTypes): + if isinstance(dcFileNames, (str,)): # If we were given a single string, make it a list. dcFileNames = [dcFileNames] @@ -105,7 +105,7 @@ def readDCFile(self, dcFileNames = None): continue classDef = getattr(classDef, className) - if type(classDef) != types.ClassType and type(classDef) != types.TypeType: + if type(classDef) != type and type(classDef) != type: self.notify.error("Symbol %s is not a class name." % (className)) else: dclass.setClassDef(classDef) diff --git a/toontown/toonbase/TTLocalizer.py b/toontown/toonbase/TTLocalizer.py index b8523bab7..fe18a2fad 100644 --- a/toontown/toonbase/TTLocalizer.py +++ b/toontown/toonbase/TTLocalizer.py @@ -13,34 +13,34 @@ def getLanguage(): return language -print 'TTLocalizer: Running in language: %s' % language +print('TTLocalizer: Running in language: %s' % language) if language == 'english': _languageModule = 'toontown.toonbase.TTLocalizer' + language.capitalize() else: checkLanguage = 1 _languageModule = 'toontown.toonbase.TTLocalizer_' + language -print 'from ' + _languageModule + ' import *' +print('from ' + _languageModule + ' import *') from toontown.toonbase.TTLocalizerEnglish import * if checkLanguage: l = {} g = {} englishModule = __import__('toontown.toonbase.TTLocalizerEnglish', g, l) foreignModule = __import__(_languageModule, g, l) - for key, val in englishModule.__dict__.items(): + for key, val in list(englishModule.__dict__.items()): if key not in foreignModule.__dict__: - print 'WARNING: Foreign module: %s missing key: %s' % (_languageModule, key) + print('WARNING: Foreign module: %s missing key: %s' % (_languageModule, key)) locals()[key] = val - elif isinstance(val, types.DictType): + elif isinstance(val, dict): fval = foreignModule.__dict__.get(key) - for dkey, dval in val.items(): + for dkey, dval in list(val.items()): if dkey not in fval: - print 'WARNING: Foreign module: %s missing key: %s.%s' % (_languageModule, key, dkey) + print('WARNING: Foreign module: %s missing key: %s.%s' % (_languageModule, key, dkey)) fval[dkey] = dval - for dkey in fval.keys(): + for dkey in list(fval.keys()): if dkey not in val: - print 'WARNING: Foreign module: %s extra key: %s.%s' % (_languageModule, key, dkey) + print('WARNING: Foreign module: %s extra key: %s.%s' % (_languageModule, key, dkey)) - for key in foreignModule.__dict__.keys(): + for key in list(foreignModule.__dict__.keys()): if key not in englishModule.__dict__: - print 'WARNING: Foreign module: %s extra key: %s' % (_languageModule, key) + print('WARNING: Foreign module: %s extra key: %s' % (_languageModule, key)) diff --git a/toontown/toonbase/TTLocalizerEnglish.py b/toontown/toonbase/TTLocalizerEnglish.py index 0783e21a7..614d31c01 100644 --- a/toontown/toonbase/TTLocalizerEnglish.py +++ b/toontown/toonbase/TTLocalizerEnglish.py @@ -2,7 +2,7 @@ from toontown.catalog import CatalogAccessoryItemGlobals from otp.otpbase import OTPLocalizer as OL OL.SpeedChatStaticText = OL.SpeedChatStaticTextToontown.copy() -for key in OL.SpeedChatStaticTextCommon.iterkeys(): +for key in OL.SpeedChatStaticTextCommon.keys(): OL.SpeedChatStaticText[key] = OL.SpeedChatStaticTextCommon[key] commitmantst = 'kptmptest - removable' @@ -6731,7 +6731,7 @@ def getPetGuiAlign(): 11: 'shoes girl '} AwardManagerAccessoryNames = {} AccessoryTypeNames = {} -for accessoryId in CatalogAccessoryItemGlobals.AccessoryTypes.keys(): +for accessoryId in list(CatalogAccessoryItemGlobals.AccessoryTypes.keys()): accessoryInfo = CatalogAccessoryItemGlobals.AccessoryTypes[accessoryId] if accessoryInfo[0] % 4 == 0: accessoryStyleDescription = HatStylesDescriptions @@ -10285,7 +10285,7 @@ def getRecipeBeanText(beanTuple): if not beanTuple: return retval allTheSame = True - for index in xrange(len(beanTuple)): + for index in range(len(beanTuple)): if index + 1 < len(beanTuple): if not beanTuple[index] == beanTuple[index + 1]: allTheSame = False @@ -10299,7 +10299,7 @@ def getRecipeBeanText(beanTuple): else: retval += 'a' maxBeans = len(beanTuple) - for index in xrange(maxBeans): + for index in range(maxBeans): if index == maxBeans - 1: retval += ' and %s Jellybean' % BeanColorWords[beanTuple[index]] elif index == 0: diff --git a/toontown/toonbase/ToonBase.py b/toontown/toonbase/ToonBase.py index bbeb9af2d..c99cfcd07 100644 --- a/toontown/toonbase/ToonBase.py +++ b/toontown/toonbase/ToonBase.py @@ -7,7 +7,7 @@ import sys import tempfile import time -import ToontownAsyncLoader +from . import ToontownAsyncLoader from direct.directnotify import DirectNotifyGlobal from direct.filter.CommonFilters import CommonFilters from direct.gui import DirectGuiGlobals @@ -42,7 +42,7 @@ def __init__(self): # First, build a list of all possible resolutions: self.resList = [] displayInfo = self.pipe.getDisplayInformation() - for i in xrange(displayInfo.getTotalDisplayModes()): + for i in range(displayInfo.getTotalDisplayModes()): width = displayInfo.getDisplayModeWidth(i) height = displayInfo.getDisplayModeHeight(i) if (width, height) not in self.resList: @@ -67,7 +67,7 @@ def __init__(self): # If we're fullscreen, we want to fit the entire screen: res = (self.nativeWidth, self.nativeHeight) elif self.nativeRatio not in self.resDict: - print "base.resDict does not contain the native resolution: %r" % self.resDict + print("base.resDict does not contain the native resolution: %r" % self.resDict) res = (800, 600) elif len(self.resDict[self.nativeRatio]) > 1: # We have resolutions that match our native ratio and fit it! @@ -77,7 +77,7 @@ def __init__(self): # Okay, we don't have any resolutions that match our native # ratio and fit it. Let's just use one of the second largest # ratio's resolutions: - ratios = sorted(self.resDict.keys(), reverse=False) + ratios = sorted(list(self.resDict.keys()), reverse=False) nativeIndex = ratios.index(self.nativeRatio) res = sorted(self.resDict[ratios[nativeIndex - 1]])[0] diff --git a/toontown/toonbase/ToonPythonUtil.py b/toontown/toonbase/ToonPythonUtil.py index b0f19d586..552d59e52 100644 --- a/toontown/toonbase/ToonPythonUtil.py +++ b/toontown/toonbase/ToonPythonUtil.py @@ -48,8 +48,8 @@ import gc #if __debug__: import traceback -import __builtin__ -from StringIO import StringIO +import builtins +from io import StringIO import marshal from toontown.pandautils import ElementTree as ET from toontown.pandautils import BpDb @@ -61,8 +61,9 @@ from direct.directutil import Verify from panda3d.core import * from panda3d.direct import * +from direct.showbase.PythonUtil import Enum -ScalarTypes = (types.FloatType, types.IntType, types.LongType) +ScalarTypes = (float, int, int) """ # with one integer positional arg, this uses about 4/5 of the memory of the Functor class below @@ -105,9 +106,9 @@ def _do__call__(self, *args, **kargs): def _exceptionLoggedCreationStack__call__(self, *args, **kargs): try: return self._do__call__(*args, **kargs) - except Exception, e: - print '-->Functor creation stack (%s): %s' % ( - self.__name__, self.getCreationStackTraceCompactStr()) + except Exception as e: + print('-->Functor creation stack (%s): %s' % ( + self.__name__, self.getCreationStackTraceCompactStr())) raise __call__ = _do__call__ @@ -120,7 +121,7 @@ def __repr__(self): except: argStr = 'bad repr: %s' % arg.__class__ s += ', %s' % argStr - for karg, value in self._kargs.items(): + for karg, value in list(self._kargs.items()): s += ', %s=%s' % (karg, repr(value)) s += ')' return s @@ -202,7 +203,7 @@ def indent(stream, numIndents, str): 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)) @@ -219,7 +220,7 @@ def writeFsmTree(instance, indent = 0): name = '' if hasattr(instance.fsm, 'state'): name = instance.fsm.state.name - print "%s: %s"%(instance.fsm.name, name) + print("%s: %s"%(instance.fsm.name, name)) @@ -276,13 +277,13 @@ def __str__(self): return r def printStack(): - print StackTrace(start=1).compact() + print(StackTrace(start=1).compact()) return True def printReverseStack(): - print StackTrace(start=1).reverseCompact() + print(StackTrace(start=1).reverseCompact()) return True def printVerboseStack(): - print StackTrace(start=1) + print(StackTrace(start=1)) return True #----------------------------------------------------------------------------- @@ -329,7 +330,7 @@ def traceParentCall(): return traceFunctionCall(sys._getframe(2)) def printThisCall(): - print traceFunctionCall(sys._getframe(1)) + print(traceFunctionCall(sys._getframe(1))) return 1 # to allow "assert printThisCall()" @@ -343,15 +344,15 @@ def lineage(obj, verbose=0, indent=0): (Based on getClassLineage()) """ r="" - if type(obj) == types.ListType: + if type(obj) == list: r+=(" "*indent)+"python list\n" - elif type(obj) == types.DictionaryType: + elif type(obj) == dict: r+=(" "*indent)+"python dictionary\n" elif type(obj) == types.ModuleType: r+=(" "*indent)+str(obj)+"\n" elif type(obj) == types.InstanceType: r+=lineage(obj.__class__, verbose, indent) - elif type(obj) == types.ClassType: + elif type(obj) == type: r+=(" "*indent) if verbose: r+=obj.__module__+"." @@ -366,11 +367,11 @@ def trace(frame, event, arg): if event == 'line': pass elif event == 'call': - print traceFunctionCall(sys._getframe(1)) + print(traceFunctionCall(sys._getframe(1))) elif event == 'return': - print "returning" + print("returning") elif event == 'exception': - print "exception" + print("exception") return trace def troff(): sys.settrace(None) @@ -381,14 +382,14 @@ def getClassLineage(obj): """ print object inheritance list """ - if type(obj) == types.DictionaryType: + if type(obj) == dict: # Just a dictionary, return dictionary return [obj] elif (type(obj) == types.InstanceType): # Instance, make a list with the instance and its class interitance return [obj] + getClassLineage(obj.__class__) - elif ((type(obj) == types.ClassType) or - (type(obj) == types.TypeType)): + elif ((type(obj) == type) or + (type(obj) == type)): # Class or type, see what it derives from lineage = [obj] for c in obj.__bases__: @@ -408,7 +409,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) @@ -416,7 +417,7 @@ def pdir(obj, str = None, width = None, uniqueLineage.reverse() for obj in uniqueLineage: _pdir(obj, str, width, fTruncate, lineWidth, wantPrivate) - print + print() def _pdir(obj, str = None, width = None, fTruncate = 1, lineWidth = 75, wantPrivate = 0): @@ -430,8 +431,8 @@ def printHeader(name): padBefore = int((70 - length)/2.0) padAfter = max(0, 70 - length - padBefore) header = '*' * padBefore + name + '*' * padAfter - print header - print + print(header) + print() def printInstanceHeader(i, printHeader = printHeader): printHeader(i.__class__.__name__ + ' INSTANCE INFO') def printClassHeader(c, printHeader = printHeader): @@ -441,12 +442,12 @@ def printDictionaryHeader(d, printHeader = printHeader): # Print Header if type(obj) == types.InstanceType: printInstanceHeader(obj) - elif type(obj) == types.ClassType: + elif type(obj) == type: printClassHeader(obj) - elif type (obj) == types.DictionaryType: + elif type (obj) == dict: printDictionaryHeader(obj) # Get dict - if type(obj) == types.DictionaryType: + if type(obj) == dict: dict = obj # FFI objects are builtin types, they have no __dict__ elif not hasattr(obj, '__dict__'): @@ -462,7 +463,7 @@ def printDictionaryHeader(d, printHeader = printHeader): aproposKeys = [] privateKeys = [] remainingKeys = [] - for key in dict.keys(): + for key in list(dict.keys()): if not width: keyWidth = len(key) if str: @@ -501,7 +502,7 @@ def printDictionaryHeader(d, printHeader = printHeader): if fTruncate: # Cut off line (keeping at least 1 char) strvalue = strvalue[:max(1, lineWidth - maxWidth)] - print (format % key)[:maxWidth] + '\t' + strvalue + print((format % key)[:maxWidth] + '\t' + strvalue) # Magic numbers: These are the bit masks in func_code.co_flags that # reveal whether or not the function has a *arg or **kw argument. @@ -509,13 +510,13 @@ def printDictionaryHeader(d, printHeader = printHeader): _KEY_DICT = 8 def _is_variadic(function): - return function.func_code.co_flags & _POS_LIST + return function.__code__.co_flags & _POS_LIST def _has_keywordargs(function): - return function.func_code.co_flags & _KEY_DICT + return function.__code__.co_flags & _KEY_DICT def _varnames(function): - return function.func_code.co_varnames + return function.__code__.co_varnames def _getcode(f): """ @@ -524,31 +525,31 @@ def _getcode(f): object. """ def method_get(f): - return f.__name__, f.im_func + return f.__name__, f.__func__ def function_get(f): return f.__name__, f def instance_get(f): if hasattr(f, '__call__'): method = f.__call__ if (type(method) == types.MethodType): - func = method.im_func + func = method.__func__ else: func = method return ("%s%s" % (f.__class__.__name__, '__call__'), func) else: s = ("Instance %s of class %s does not have a __call__ method" % (f, f.__class__.__name__)) - raise TypeError, s + raise TypeError(s) def class_get(f): if hasattr(f, '__init__'): - return f.__name__, f.__init__.im_func + return f.__name__, f.__init__.__func__ else: return f.__name__, lambda: None codedict = { types.UnboundMethodType: method_get, types.MethodType: method_get, types.FunctionType: function_get, types.InstanceType: instance_get, - types.ClassType: class_get, + type: class_get, } try: return codedict[type(f)](f) @@ -557,7 +558,7 @@ def class_get(f): # raise ValueError, "type %s not supported yet." % type(f) return f.__name__, None else: - raise TypeError, ("object %s of type %s is not callable." % + raise TypeError("object %s of type %s is not callable." % (f, type(f))) class Signature: @@ -565,10 +566,10 @@ def __init__(self, func): self.type = type(func) self.name, self.func = _getcode(func) def ordinary_args(self): - n = self.func.func_code.co_argcount + n = self.func.__code__.co_argcount return _varnames(self.func)[0:n] def special_args(self): - n = self.func.func_code.co_argcount + n = self.func.__code__.co_argcount x = {} # if _is_variadic(self.func): @@ -589,7 +590,7 @@ def full_arglist(self): base.append(x['keyword']) return base def defaults(self): - defargs = self.func.func_defaults + defargs = self.func.__defaults__ args = self.ordinary_args() mapping = {} if defargs is not None: @@ -620,7 +621,7 @@ def __repr__(self): def doc(obj): if (isinstance(obj, types.MethodType)) or \ (isinstance(obj, types.FunctionType)): - print obj.__doc__ + print(obj.__doc__) def adjust(command = None, dim = 1, parent = None, **kw): """ @@ -646,15 +647,15 @@ def adjust(command = None, dim = 1, parent = None, **kw): from direct.tkwidgets import Valuator # Set command if specified if command: - kw['command'] = lambda x: apply(command, x) + kw['command'] = lambda x: command(*x) if parent is None: kw['title'] = command.__name__ kw['dim'] = dim # Create toplevel if needed if not parent: - vg = apply(Valuator.ValuatorGroupPanel, (parent,), kw) + vg = Valuator.ValuatorGroupPanel(*(parent,), **kw) else: - vg = apply(Valuator.ValuatorGroup, (parent,), kw) + vg = Valuator.ValuatorGroup(*(parent,), **kw) vg.pack(expand = 1, fill = 'x') return vg @@ -712,18 +713,18 @@ def sameElements(a, b): def makeList(x): """returns x, converted to a list""" - if type(x) is types.ListType: + if type(x) is list: return x - elif type(x) is types.TupleType: + elif type(x) is tuple: return list(x) else: return [x,] def makeTuple(x): """returns x, converted to a tuple""" - if type(x) is types.ListType: + if type(x) is list: return tuple(x) - elif type(x) is types.TupleType: + elif type(x) is tuple: return x else: return (x,) @@ -761,7 +762,7 @@ def invertDict(D, lossy=False): {1: 'key1', 2: 'key2'} """ n = {} - for key, value in D.items(): + for key, value in list(D.items()): if not lossy and value in n: raise 'duplicate key in invertDict: %s' % value n[value] = key @@ -776,7 +777,7 @@ def invertDictLossless(D): {1: ['key1'], 2: ['key2', 'keyA']} """ n = {} - for key, value in D.items(): + for key, value in list(D.items()): n.setdefault(value, []) n[value].append(key) return n @@ -822,7 +823,7 @@ def replace(list, old, new, all=0): return 1 else: numReplaced = 0 - for i in xrange(len(list)): + for i in range(len(list)): if list[i] == old: numReplaced += 1 list[i] = new @@ -899,10 +900,10 @@ def binaryRepr(number, max_length = 32): # This will only work reliably for relatively small numbers. # Increase the value of max_length if you think you're going # to use long integers - assert number < 2L << max_length - shifts = map (operator.rshift, max_length * [number], \ - range (max_length - 1, -1, -1)) - digits = map (operator.mod, shifts, max_length * [2]) + assert number < 2 << max_length + shifts = list(map (operator.rshift, max_length * [number], \ + list(range(max_length - 1, -1, -1)))) + digits = list(map (operator.mod, shifts, max_length * [2])) if not digits.count (1): return 0 digits = digits [digits.index (1):] return ''.join([repr(digit) for digit in digits]) @@ -948,29 +949,29 @@ def getProfileResultString(): def profileFunc(callback, name, terse, log=True): global _ProfileResultStr - if 'globalProfileFunc' in __builtin__.__dict__: + if 'globalProfileFunc' in builtins.__dict__: # rats. Python profiler is not re-entrant... base.notify.warning( 'PythonUtil.profileStart(%s): aborted, already profiling %s' #'\nStack Trace:\n%s' - % (name, __builtin__.globalProfileFunc, + % (name, builtins.globalProfileFunc, #StackTrace() )) return - __builtin__.globalProfileFunc = callback - __builtin__.globalProfileResult = [None] + builtins.globalProfileFunc = callback + builtins.globalProfileResult = [None] prefix = '***** START PROFILE: %s *****' % name if log: - print prefix + print(prefix) startProfile(cmd='globalProfileResult[0]=globalProfileFunc()', callInfo=(not terse), silent=not log) suffix = '***** END PROFILE: %s *****' % name if log: - print suffix + print(suffix) else: _ProfileResultStr = '%s\n%s\n%s' % (prefix, _ProfileResultStr, suffix) result = globalProfileResult[0] - del __builtin__.__dict__['globalProfileFunc'] - del __builtin__.__dict__['globalProfileResult'] + del builtins.__dict__['globalProfileFunc'] + del builtins.__dict__['globalProfileResult'] return result def profiled(category=None, terse=False): @@ -985,7 +986,7 @@ def loadParticles(): want-profile-particles 1 """ - assert type(category) in (types.StringType, types.NoneType), "must provide a category name for @profiled" + assert type(category) in (bytes, type(None)), "must provide a category name for @profiled" # allow profiling in published versions """ @@ -1004,7 +1005,7 @@ def nullDecorator(f): def profileDecorator(f): def _profiled(*args, **kArgs): - name = '(%s) %s from %s' % (category, f.func_name, f.__module__) + name = '(%s) %s from %s' % (category, f.__name__, f.__module__) # showbase might not be loaded yet, so don't use # base.config. Instead, query the ConfigVariableBool. @@ -1064,8 +1065,8 @@ def _installProfileCustomFuncs(filename): assert filename not in profileFilenames profileFilenames.add(filename) profileFilenameList.push(filename) - movedOpenFuncs.append(__builtin__.open) - __builtin__.open = _profileOpen + movedOpenFuncs.append(builtins.open) + builtins.open = _profileOpen movedDumpFuncs.append(marshal.dump) marshal.dump = _profileMarshalDump movedLoadFuncs.append(marshal.load) @@ -1090,7 +1091,7 @@ def _removeProfileCustomFuncs(filename): assert profileFilenameList.top() == filename marshal.load = movedLoadFuncs.pop() marshal.dump = movedDumpFuncs.pop() - __builtin__.open = movedOpenFuncs.pop() + builtins.open = movedOpenFuncs.pop() profileFilenames.remove(filename) profileFilenameList.pop() profileFilename2file.pop(filename, None) @@ -1387,7 +1388,7 @@ def __init__(self, *args, **kwArgs): else: assert len(args) == 0 if __debug__: - for arg in kwArgs.keys(): + for arg in list(kwArgs.keys()): assert arg in self.getParams() self.paramVals = dict(kwArgs) def getValue(self, param): @@ -1410,7 +1411,7 @@ def extractFrom(self, obj): def getParams(cls): # returns safely-mutable list of param names cls._compileDefaultParams() - return cls._Params.keys() + return list(cls._Params.keys()) @classmethod def getDefaultValue(cls, param): cls._compileDefaultParams() @@ -1703,7 +1704,7 @@ def __init__(self, **kwArgs): if __debug__: # make sure all of the keyword arguments passed in # are present in our data set - for arg in kwArgs.keys(): + for arg in list(kwArgs.keys()): assert arg in self.getDataNames(), ( "unknown argument for %s: '%s'" % ( self.__class__, arg)) @@ -1751,7 +1752,7 @@ def getValue(self, name): def getDataNames(cls): # returns safely-mutable list of datum names cls._compileDefaultDataSet() - return cls._DataSet.keys() + return list(cls._DataSet.keys()) @classmethod def getDefaultValue(cls, name): cls._compileDefaultDataSet() @@ -2216,8 +2217,8 @@ def weightedRand(valDict, rng=random.random): -Weights need not add up to any particular value. -The actual selection will be returned. """ - selections = valDict.keys() - weights = valDict.values() + selections = list(valDict.keys()) + weights = list(valDict.values()) totalWeight = 0 for weight in weights: @@ -2252,7 +2253,7 @@ def randInt32(rng=random.random): def randUint32(rng=random.random): """returns a random integer in [0..2^32). rng must return float in [0..1]""" - return long(rng() * 0xFFFFFFFFL) + return int(rng() * 0xFFFFFFFF) class SerialNumGen: """generates serial numbers""" @@ -2260,7 +2261,7 @@ def __init__(self, start=None): if start is None: start = 0 self.__counter = start-1 - def next(self): + def __next__(self): self.__counter += 1 return self.__counter @@ -2268,123 +2269,31 @@ class SerialMaskedGen(SerialNumGen): def __init__(self, mask, start=None): self._mask = mask SerialNumGen.__init__(self, start) - def next(self): + def __next__(self): v = SerialNumGen.next(self) return v & self._mask _serialGen = SerialNumGen() def serialNum(): global _serialGen - return _serialGen.next() + return next(_serialGen) def uniqueName(name): global _serialGen - return '%s-%s' % (name, _serialGen.next()) + return '%s-%s' % (name, next(_serialGen)) class EnumIter: def __init__(self, enum): - self._values = enum._stringTable.keys() + self._values = list(enum._stringTable.keys()) self._index = 0 def __iter__(self): return self - def next(self): + def __next__(self): if self._index >= len(self._values): raise StopIteration self._index += 1 return self._values[self._index-1] -class Enum: - """Pass in list of strings or string of comma-separated strings. - Items are accessible as instance.item, and are assigned unique, - increasing integer values. Pass in integer for 'start' to override - starting value. - - Example: - - >>> colors = Enum('red, green, blue') - >>> colors.red - 0 - >>> colors.green - 1 - >>> colors.blue - 2 - >>> colors.getString(colors.red) - 'red' - """ - - if __debug__: - # chars that cannot appear within an item string. - InvalidChars = string.whitespace - def _checkValidIdentifier(item): - invalidChars = string.whitespace+string.punctuation - invalidChars = invalidChars.replace('_','') - invalidFirstChars = invalidChars+string.digits - if item[0] in invalidFirstChars: - raise SyntaxError, ("Enum '%s' contains invalid first char" % - item) - if not disjoint(item, invalidChars): - for char in item: - if char in invalidChars: - raise SyntaxError, ( - "Enum\n'%s'\ncontains illegal char '%s'" % - (item, char)) - return 1 - _checkValidIdentifier = staticmethod(_checkValidIdentifier) - - def __init__(self, items, start=0): - if type(items) == types.StringType: - items = items.split(',') - - self._stringTable = {} - - # make sure we don't overwrite an existing element of the class - assert self._checkExistingMembers(items) - assert uniqueElements(items) - - i = start - for item in items: - # remove leading/trailing whitespace - item = string.strip(item) - # is there anything left? - if len(item) == 0: - continue - # make sure there are no invalid characters - assert Enum._checkValidIdentifier(item) - self.__dict__[item] = i - self._stringTable[i] = item - i += 1 - - def __iter__(self): - return EnumIter(self) - - def hasString(self, string): - return string in set(self._stringTable.values()) - - def fromString(self, string): - if self.hasString(string): - return self.__dict__[string] - # throw an error - {}[string] - - def getString(self, value): - return self._stringTable[value] - - def __contains__(self, value): - return value in self._stringTable - - def __len__(self): - return len(self._stringTable) - - def copyTo(self, obj): - # copies all members onto obj - for name, value in self._stringTable: - setattr(obj, name, value) - if __debug__: - def _checkExistingMembers(self, items): - for item in items: - if hasattr(self, item): - return 0 - return 1 ############################################################ # class: Singleton @@ -2443,7 +2352,7 @@ def printListEnumGen(l): n //= 10 format = '%0' + '%s' % digits + 'i:%s' for i in range(len(l)): - print format % (i, l[i]) + print(format % (i, l[i])) yield None def printListEnum(l): @@ -2517,10 +2426,10 @@ def fastRepr(obj, maxLen=200, strFactor=10, _visitedIds=None): _visitedIds = set() if id(obj) in _visitedIds: return '' % itype(obj) - if type(obj) in (types.TupleType, types.ListType): + if type(obj) in (tuple, list): s = '' - s += {types.TupleType: '(', - types.ListType: '[',}[type(obj)] + s += {tuple: '(', + list: '[',}[type(obj)] if maxLen is not None and len(obj) > maxLen: o = obj[:maxLen] ellips = '...' @@ -2533,16 +2442,16 @@ def fastRepr(obj, maxLen=200, strFactor=10, _visitedIds=None): s += ', ' _visitedIds.remove(id(obj)) s += ellips - s += {types.TupleType: ')', - types.ListType: ']',}[type(obj)] + s += {tuple: ')', + list: ']',}[type(obj)] return s - elif type(obj) is types.DictType: + elif type(obj) is dict: s = '{' if maxLen is not None and len(obj) > maxLen: - o = obj.keys()[:maxLen] + o = list(obj.keys())[:maxLen] ellips = '...' else: - o = obj.keys() + o = list(obj.keys()) ellips = '' _visitedIds.add(id(obj)) for key in o: @@ -2553,7 +2462,7 @@ def fastRepr(obj, maxLen=200, strFactor=10, _visitedIds=None): s += ellips s += '}' return s - elif type(obj) is types.StringType: + elif type(obj) is bytes: if maxLen is not None: maxLen *= strFactor if maxLen is not None and len(obj) > maxLen: @@ -2590,7 +2499,7 @@ def diffSinceBaseLine(): since.setdefault(str(itype(i)), 0) for i in obj: since[str(itype(i))] -= 1 - for i in since.keys(): + for i in list(since.keys()): if not since[i]: del since[i] else: @@ -2600,7 +2509,7 @@ def diffSinceBaseLine(): final.sort() final.reverse() for i in final: - print i + print(i) final = [] since = [] @@ -2660,14 +2569,14 @@ def getTree(obj): def convertTree(objTree, idList): newTree = {} - for key in objTree.keys(): + for key in list(objTree.keys()): obj = (idList[key],) newTree[obj] = {} r_convertTree(objTree[key], newTree[obj], idList) return newTree def r_convertTree(oldTree, newTree, idList): - for key in oldTree.keys(): + for key in list(oldTree.keys()): obj = idList.get(key) if(not obj): @@ -2679,16 +2588,16 @@ def r_convertTree(oldTree, newTree, idList): def pretty_print(tree): - for name in tree.keys(): - print name + for name in list(tree.keys()): + print(name) r_pretty_print(tree[name], 0) def r_pretty_print(tree, num): num+=1 - for name in tree.keys(): - print " "*num,name + for name in list(tree.keys()): + print(" "*num,name) r_pretty_print(tree[name],num) def r_add_chain(objId, objList, objTree, idList, num): @@ -2785,13 +2694,13 @@ def setTrace(): class ScratchPad: """empty class to stick values onto""" def __init__(self, **kArgs): - for key, value in kArgs.iteritems(): + for key, value in kArgs.items(): setattr(self, key, value) self._keys = set(kArgs.keys()) def add(self, **kArgs): - for key, value in kArgs.iteritems(): + for key, value in kArgs.items(): setattr(self, key, value) - self._keys.update(kArgs.keys()) + self._keys.update(list(kArgs.keys())) def destroy(self): for key in self._keys: delattr(self, key) @@ -2808,11 +2717,11 @@ def __contains__(self, itemName): class DestructiveScratchPad(ScratchPad): # automatically calls destroy() on elements passed to __init__ def add(self, **kArgs): - for key, value in kArgs.iteritems(): + for key, value in kArgs.items(): if hasattr(self, key): getattr(self, key).destroy() setattr(self, key, value) - self._keys.update(kArgs.keys()) + self._keys.update(list(kArgs.keys())) def destroy(self): for key in self._keys: getattr(self, key).destroy() @@ -2823,7 +2732,7 @@ class Sync: def __init__(self, name, other=None): self._name = name if other is None: - self._series = self._SeriesGen.next() + self._series = next(self._SeriesGen) self._value = 0 else: self._series = other._series @@ -2892,10 +2801,10 @@ def deeptype(obj, maxLen=100, _visitedIds=None): if id(obj) in _visitedIds: return '' % itype(obj) t = type(obj) - if t in (types.TupleType, types.ListType): + if t in (tuple, list): s = '' - s += {types.TupleType: '(', - types.ListType: '[',}[type(obj)] + s += {tuple: '(', + list: '[',}[type(obj)] if maxLen is not None and len(obj) > maxLen: o = obj[:maxLen] ellips = '...' @@ -2908,16 +2817,16 @@ def deeptype(obj, maxLen=100, _visitedIds=None): s += ', ' _visitedIds.remove(id(obj)) s += ellips - s += {types.TupleType: ')', - types.ListType: ']',}[type(obj)] + s += {tuple: ')', + list: ']',}[type(obj)] return s - elif type(obj) is types.DictType: + elif type(obj) is dict: s = '{' if maxLen is not None and len(obj) > maxLen: - o = obj.keys()[:maxLen] + o = list(obj.keys())[:maxLen] ellips = '...' else: - o = obj.keys() + o = list(obj.keys()) ellips = '' _visitedIds.add(id(obj)) for key in o: @@ -2944,7 +2853,7 @@ def getNumberedTypedString(items, maxLen=5000, numPrefix=''): first = True s = '' snip = '' - for i in xrange(len(items)): + for i in range(len(items)): if not first: s += '\n' first = False @@ -2975,7 +2884,7 @@ def getNumberedTypedSortedString(items, maxLen=5000, numPrefix=''): first = True s = '' strs.sort() - for i in xrange(len(strs)): + for i in range(len(strs)): if not first: s += '\n' first = False @@ -2999,7 +2908,7 @@ def getNumberedTypedSortedStringWithReferrersGen(items, maxLen=10000, numPrefix= for item in items: strs.append(fastRepr(item)) strs.sort() - for i in xrange(len(strs)): + for i in range(len(strs)): item = items[i] objStr = strs[i] objStr += ', \tREFERRERS=[' @@ -3030,12 +2939,12 @@ def printNumberedTyped(items, maxLen=5000): n //= 10 digits = digits format = '%0' + '%s' % digits + 'i:%s \t%s' - for i in xrange(len(items)): + for i in range(len(items)): objStr = fastRepr(items[i]) if len(objStr) > maxLen: snip = '' objStr = '%s%s' % (objStr[:(maxLen-len(snip))], snip) - print format % (i, itype(items[i]), objStr) + print(format % (i, itype(items[i]), objStr)) def printNumberedTypesGen(items, maxLen=5000): digits = 0 @@ -3045,8 +2954,8 @@ def printNumberedTypesGen(items, maxLen=5000): n //= 10 digits = digits format = '%0' + '%s' % digits + 'i:%s' - for i in xrange(len(items)): - print format % (i, itype(items[i])) + for i in range(len(items)): + print(format % (i, itype(items[i]))) yield None def printNumberedTypes(items, maxLen=5000): @@ -3178,14 +3087,14 @@ def __call__(self, *args, **kwArgs): class ClassTree: def __init__(self, instanceOrClass): - if type(instanceOrClass) in (types.ClassType, types.TypeType): + if type(instanceOrClass) in (type, type): cls = instanceOrClass else: cls = instanceOrClass.__class__ self._cls = cls self._bases = [] for base in self._cls.__bases__: - if base not in (types.ObjectType, types.TypeType): + if base not in (object, type): self._bases.append(ClassTree(base)) def getAllClasses(self): # returns set of this class and all base classes @@ -3412,7 +3321,7 @@ def decorator(f): pass pass - except NameError,e: + except NameError as e: return decorator from direct.distributed.ClockDelta import globalClockDelta @@ -3426,7 +3335,7 @@ def wrap(*args,**kwargs): if 'args' in types: rArgs += [repr(x)+', ' for x in args[1:]] + \ - [ x + ' = ' + '%s, ' % repr(y) for x,y in kwargs.items()] + [ x + ' = ' + '%s, ' % repr(y) for x,y in list(kwargs.items())] if not rArgs: rArgs = '()' @@ -3434,7 +3343,7 @@ def wrap(*args,**kwargs): rArgs = '(' + reduce(str.__add__,rArgs)[:-2] + ')' - outStr = '%s%s' % (f.func_name, rArgs) + outStr = '%s%s' % (f.__name__, rArgs) # Insert prefix place holder, if needed if prefixes: @@ -3465,18 +3374,18 @@ def wrap(*args,**kwargs): if notifyFunc: notifyFunc(outStr % (prefix,)) else: - print indent(outStr % (prefix,)) + print(indent(outStr % (prefix,))) else: if notifyFunc: notifyFunc(outStr) else: - print indent(outStr) + print(indent(outStr)) if 'interests' in types: base.cr.printInterestSets() if 'stackTrace' in types: - print StackTrace() + print(StackTrace()) global __report_indent rVal = None @@ -3486,14 +3395,14 @@ def wrap(*args,**kwargs): finally: __report_indent -= 1 if rVal is not None: - print indent(' -> '+repr(rVal)) + print(indent(' -> '+repr(rVal))) pass pass return rVal - wrap.func_name = f.func_name - wrap.func_dict = f.func_dict - wrap.func_doc = f.func_doc + wrap.__name__ = f.__name__ + wrap.__dict__ = f.__dict__ + wrap.__doc__ = f.__doc__ wrap.__module__ = f.__module__ return wrap return decorator @@ -3541,12 +3450,12 @@ def _decoratorFunc(f, append=append): def _exceptionLogged(*args, **kArgs): try: return f(*args, **kArgs) - except Exception, e: + except Exception as e: try: - s = '%s(' % f.func_name + s = '%s(' % f.__name__ for arg in args: s += '%s, ' % arg - for key, value in kArgs.items(): + for key, value in list(kArgs.items()): s += '%s=%s, ' % (key, value) if len(args) or len(kArgs): s = s[:-2] @@ -3557,7 +3466,7 @@ def _exceptionLogged(*args, **kArgs): exceptionLoggedNotify.info(s) except: exceptionLoggedNotify.info( - '%s: ERROR IN PRINTING' % f.func_name) + '%s: ERROR IN PRINTING' % f.__name__) raise _exceptionLogged.__doc__ = f.__doc__ return _exceptionLogged @@ -3578,7 +3487,7 @@ def getCreationStackTrace(self): 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 @@ -3598,7 +3507,7 @@ def __recordCreationStackStr_init__(self, *args, **kArgs): def getCreationStackTraceCompactStr(self): return ','.join(self._creationStackTraceStrLst) def printCreationStackTrace(self): - print ','.join(self._creationStackTraceStrLst) + print(','.join(self._creationStackTraceStrLst)) cls.__init__ = __recordCreationStackStr_init__ cls.getCreationStackTraceCompactStr = getCreationStackTraceCompactStr cls.printCreationStackTrace = printCreationStackTrace @@ -3621,7 +3530,7 @@ def __logMethodCall__(obj, *args, **kArgs): except: argStr = 'bad repr: %s' % arg.__class__ s += '%s, ' % argStr - for karg, value in kArgs.items(): + for karg, value in list(kArgs.items()): s += '%s=%s, ' % (karg, repr(value)) if len(args) or len(kArgs): s = s[:-2] @@ -3708,7 +3617,7 @@ def makeFlywheelGen(objects, countList=None, countFunc=None, scale=None): def flywheel(index2objectAndCount): # generator to produce a sequence whose elements appear a specific number of times while len(index2objectAndCount): - keyList = index2objectAndCount.keys() + keyList = list(index2objectAndCount.keys()) for key in keyList: if index2objectAndCount[key][1] > 0: yield index2objectAndCount[key][0] @@ -3723,14 +3632,14 @@ def flywheel(index2objectAndCount): countList.append(countFunc(object)) if scale is not None: # scale the counts if we've got a scale factor - for i in xrange(len(countList)): + for i in range(len(countList)): yield None if countList[i] > 0: countList[i] = max(1, int(countList[i] * scale)) # create a dict for the flywheel to use during its iteration to efficiently select # the objects for the sequence index2objectAndCount = {} - for i in xrange(len(countList)): + for i in range(len(countList)): yield None index2objectAndCount[i] = [objects[i], countList[i]] # create the flywheel generator @@ -3794,7 +3703,7 @@ def _profiled(*args, **kArgs): st=globalClock.getRealTime() f(*args,**kArgs) s=globalClock.getRealTime()-st - print "Function %s.%s took %s seconds"%(f.__module__, f.__name__,s) + print("Function %s.%s took %s seconds"%(f.__module__, f.__name__,s)) else: import profile as prof, pstats #detailed profile, stored in base.stats under ( @@ -3818,7 +3727,7 @@ def _profiled(*args, **kArgs): def getTotalAnnounceTime(): td=0 - for objs in base.stats.values(): + for objs in list(base.stats.values()): for stat in objs: td+=getAnnounceGenerateTime(stat) return td @@ -3826,7 +3735,7 @@ def getTotalAnnounceTime(): def getAnnounceGenerateTime(stat): val=0 stats=stat.stats - for i in stats.keys(): + for i in list(stats.keys()): if(i[2]=="announceGenerate"): newVal=stats[i][3] if(newVal>val): @@ -3853,7 +3762,7 @@ def __str__(self): def enterFunction(self, funcName, *args, **kw): rArgs = [repr(x)+', ' for x in args] + \ - [ x + ' = ' + '%s, ' % repr(y) for x,y in kw.items()] + [ x + ' = ' + '%s, ' % repr(y) for x,y in list(kw.items())] if not rArgs: rArgs = '()' @@ -3896,9 +3805,9 @@ def __del__(self): del self.log def logBlock(id, msg): - print '<< LOGBLOCK(%03d)' % id - print str(msg) - print '/LOGBLOCK(%03d) >>' % id + print('<< LOGBLOCK(%03d)' % id) + print(str(msg)) + print('/LOGBLOCK(%03d) >>' % id) class HierarchyException(Exception): JOSWILSO = 0 @@ -3995,7 +3904,7 @@ class AlphabetCounter: # object that produces 'A', 'B', 'C', ... 'AA', 'AB', etc. def __init__(self): self._curCounter = ['A'] - def next(self): + def __next__(self): result = ''.join([c for c in self._curCounter]) index = -1 while True: @@ -4022,8 +3931,8 @@ def next(self): def testAlphabetCounter(): tempList = [] ac = AlphabetCounter() - for i in xrange(26*3): - tempList.append(ac.next()) + for i in range(26*3): + tempList.append(next(ac)) assert tempList == [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ', 'BA','BB','BC','BD','BE','BF','BG','BH','BI','BJ','BK','BL','BM','BN','BO','BP','BQ','BR','BS','BT','BU','BV','BW','BX','BY','BZ',] @@ -4033,8 +3942,8 @@ def testAlphabetCounter(): num += 26 # AAZ num += 1 # ABA num += 2 # ABC - for i in xrange(num): - x = ac.next() + for i in range(num): + x = next(ac) assert x == 'ABC' testAlphabetCounter() del testAlphabetCounter @@ -4088,7 +3997,7 @@ def pandaBreak(dotpath, linenum, temporary = 0, cond = None): filename = root + "\\src" for d in dirs[1:]: filename="%s\\%s"%(filename,d) - print filename + print(filename) globalPdb.set_break(filename+".py", linenum, temporary, cond) class Default: @@ -4133,7 +4042,7 @@ def endSuperLog(): superLogFile = None def isInteger(n): - return type(n) in (types.IntType, types.LongType) + return type(n) in (int, int) def configIsToday(configName): # TODO: replace usage of strptime with something else @@ -4201,11 +4110,11 @@ def unescapeHtmlString(s): assert unescapeHtmlString('asdf%32') == 'asdf2' def repeatableRepr(obj): - if type(obj) is types.DictType: - keys = obj.keys() + if type(obj) is dict: + keys = list(obj.keys()) keys.sort() s = '{' - for i in xrange(len(keys)): + for i in range(len(keys)): key = keys[i] s += repeatableRepr(key) s += ': ' @@ -4240,17 +4149,17 @@ def bpdbGetEnabled(): def u2ascii(s): # Unicode -> ASCII - if type(s) is types.UnicodeType: + if type(s) is str: return unicodedata.normalize('NFKD', s).encode('ascii', 'backslashreplace') else: return str(s) def unicodeUtf8(s): # * -> Unicode UTF-8 - if type(s) is types.UnicodeType: + if type(s) is str: return s else: - return unicode(str(s), 'utf-8') + return str(str(s), 'utf-8') def encodedUtf8(s): # * -> 8-bit-encoded UTF-8 @@ -4326,67 +4235,67 @@ def c(l=l): del pc del bItem -import __builtin__ -__builtin__.Functor = Functor -__builtin__.Stack = Stack -__builtin__.Queue = Queue -__builtin__.Enum = Enum -__builtin__.SerialNumGen = SerialNumGen -__builtin__.SerialMaskedGen = SerialMaskedGen -__builtin__.ScratchPad = ScratchPad -__builtin__.DestructiveScratchPad = DestructiveScratchPad -__builtin__.uniqueName = uniqueName -__builtin__.serialNum = serialNum -__builtin__.profiled = profiled -__builtin__.set_trace = set_trace -__builtin__.setTrace = setTrace -__builtin__.pm = pm -__builtin__.itype = itype -__builtin__.exceptionLogged = exceptionLogged -__builtin__.appendStr = appendStr -__builtin__.bound = bound -__builtin__.clamp = clamp -__builtin__.lerp = lerp -__builtin__.notNone = notNone -__builtin__.clampScalar = clampScalar -__builtin__.makeList = makeList -__builtin__.makeTuple = makeTuple -__builtin__.printStack = printStack -__builtin__.printReverseStack = printReverseStack -__builtin__.printVerboseStack = printVerboseStack -__builtin__.DelayedCall = DelayedCall -__builtin__.DelayedFunctor = DelayedFunctor -__builtin__.FrameDelayedCall = FrameDelayedCall -__builtin__.SubframeCall = SubframeCall -__builtin__.ArgumentEater = ArgumentEater -__builtin__.ClassTree = ClassTree -__builtin__.invertDict = invertDict -__builtin__.invertDictLossless = invertDictLossless -__builtin__.getBase = getBase -__builtin__.getRepository = getRepository -__builtin__.safeRepr = safeRepr -__builtin__.fastRepr = fastRepr -__builtin__.nullGen = nullGen -__builtin__.flywheel = flywheel -__builtin__.loopGen = loopGen -__builtin__.StackTrace = StackTrace -__builtin__.choice = choice -__builtin__.report = report -__builtin__.pstatcollect = pstatcollect -__builtin__.MiniLog = MiniLog -__builtin__.MiniLogSentry = MiniLogSentry -__builtin__.logBlock = logBlock -__builtin__.HierarchyException = HierarchyException -__builtin__.pdir = pdir -__builtin__.deeptype = deeptype -__builtin__.Default = Default -__builtin__.isInteger = isInteger -__builtin__.configIsToday = configIsToday -__builtin__.typeName = typeName -__builtin__.safeTypeName = safeTypeName -__builtin__.histogramDict = histogramDict -__builtin__.repeatableRepr = repeatableRepr -__builtin__.bpdb = bpdb -__builtin__.u2ascii = u2ascii -__builtin__.unicodeUtf8 = unicodeUtf8 -__builtin__.encodedUtf8 = encodedUtf8 +import builtins +builtins.Functor = Functor +builtins.Stack = Stack +builtins.Queue = Queue +builtins.Enum = Enum +builtins.SerialNumGen = SerialNumGen +builtins.SerialMaskedGen = SerialMaskedGen +builtins.ScratchPad = ScratchPad +builtins.DestructiveScratchPad = DestructiveScratchPad +builtins.uniqueName = uniqueName +builtins.serialNum = serialNum +builtins.profiled = profiled +builtins.set_trace = set_trace +builtins.setTrace = setTrace +builtins.pm = pm +builtins.itype = itype +builtins.exceptionLogged = exceptionLogged +builtins.appendStr = appendStr +builtins.bound = bound +builtins.clamp = clamp +builtins.lerp = lerp +builtins.notNone = notNone +builtins.clampScalar = clampScalar +builtins.makeList = makeList +builtins.makeTuple = makeTuple +builtins.printStack = printStack +builtins.printReverseStack = printReverseStack +builtins.printVerboseStack = printVerboseStack +builtins.DelayedCall = DelayedCall +builtins.DelayedFunctor = DelayedFunctor +builtins.FrameDelayedCall = FrameDelayedCall +builtins.SubframeCall = SubframeCall +builtins.ArgumentEater = ArgumentEater +builtins.ClassTree = ClassTree +builtins.invertDict = invertDict +builtins.invertDictLossless = invertDictLossless +builtins.getBase = getBase +builtins.getRepository = getRepository +builtins.safeRepr = safeRepr +builtins.fastRepr = fastRepr +builtins.nullGen = nullGen +builtins.flywheel = flywheel +builtins.loopGen = loopGen +builtins.StackTrace = StackTrace +builtins.choice = choice +builtins.report = report +builtins.pstatcollect = pstatcollect +builtins.MiniLog = MiniLog +builtins.MiniLogSentry = MiniLogSentry +builtins.logBlock = logBlock +builtins.HierarchyException = HierarchyException +builtins.pdir = pdir +builtins.deeptype = deeptype +builtins.Default = Default +builtins.isInteger = isInteger +builtins.configIsToday = configIsToday +builtins.typeName = typeName +builtins.safeTypeName = safeTypeName +builtins.histogramDict = histogramDict +builtins.repeatableRepr = repeatableRepr +builtins.bpdb = bpdb +builtins.u2ascii = u2ascii +builtins.unicodeUtf8 = unicodeUtf8 +builtins.encodedUtf8 = encodedUtf8 diff --git a/toontown/toonbase/ToontownBattleGlobals.py b/toontown/toonbase/ToontownBattleGlobals.py index 3cd845b93..5bef337c1 100644 --- a/toontown/toonbase/ToontownBattleGlobals.py +++ b/toontown/toonbase/ToontownBattleGlobals.py @@ -1,6 +1,6 @@ -from ToontownGlobals import * +from .ToontownGlobals import * import math -import TTLocalizer +from . import TTLocalizer BattleCamFaceOffFov = 30.0 BattleCamFaceOffPos = Point3(0, -10, 4) BattleCamDefaultPos1 = Point3(0, -16, 3) @@ -535,7 +535,7 @@ def getMoreXpHolidayMultiplier(): def encodeUber(trackList): bitField = 0 - for trackIndex in xrange(len(trackList)): + for trackIndex in range(len(trackList)): if trackList[trackIndex] > 0: bitField += pow(2, trackIndex) diff --git a/toontown/toonbase/ToontownGlobals.py b/toontown/toonbase/ToontownGlobals.py index 045f29110..bb0daca06 100644 --- a/toontown/toonbase/ToontownGlobals.py +++ b/toontown/toonbase/ToontownGlobals.py @@ -1,4 +1,4 @@ -import TTLocalizer +from . import TTLocalizer from otp.otpbase.OTPGlobals import * from toontown.toonbase.ToonPythonUtil import Enum, invertDict from pandac.PandaModules import BitMask32, Vec4 @@ -408,7 +408,7 @@ def dept2cogHQ(dept): SellbotFactoryInt: FT_FullSuit, LawbotOfficeInt: FT_FullSuit} StreetNames = TTLocalizer.GlobalStreetNames -StreetBranchZones = StreetNames.keys() +StreetBranchZones = list(StreetNames.keys()) Hoods = (DonaldsDock, ToontownCentral, TheBrrrgh, diff --git a/toontown/toonbase/UserFunnel.py b/toontown/toonbase/UserFunnel.py index 35af0792c..2b76e218c 100644 --- a/toontown/toonbase/UserFunnel.py +++ b/toontown/toonbase/UserFunnel.py @@ -236,7 +236,7 @@ def readInPandaCookie(self): self.setTheHTTPCookie(self.pandaHTTPClientVarWSS) except IndexError: - print 'UserFunnel(Warning): Cookie Data file bad' + print('UserFunnel(Warning): Cookie Data file bad') del thedata @@ -351,7 +351,7 @@ def findIECookieFiles(self): try: sdir = os.listdir(self.ieCookieDir) except WindowsError: - print 'Dir does not exist, do nothing' + print('Dir does not exist, do nothing') return while sdir: @@ -400,7 +400,7 @@ def writeIEHitBoxCookies(self): while x < len(iecData): if iecData[x].find(self.hitboxAcct) != -1: iecData.pop(x) - print 'Removed it from the list' + print('Removed it from the list') break x += 1 @@ -500,7 +500,7 @@ def loadIEHitBoxCookies(self): def convertHitBoxIEtoPython(): if sys.platform != 'win32': - print 'Cookie Converter: Warning: System is not MS-Windows. I have not been setup to work with other systems yet. Sorry ' + sys.platform + ' user. The game client will create a cookie.' + print('Cookie Converter: Warning: System is not MS-Windows. I have not been setup to work with other systems yet. Sorry ' + sys.platform + ' user. The game client will create a cookie.') return if __dev__: return @@ -512,7 +512,7 @@ def convertHitBoxIEtoPython(): def convertHitBoxPythontoIE(): if sys.platform != 'win32': - print 'System is not MS-Windows. I have not been setup to work with other systems yet. Sorry ' + sys.platform + ' user.' + print('System is not MS-Windows. I have not been setup to work with other systems yet. Sorry ' + sys.platform + ' user.') return if os.path.isfile('cf.txt') == True: return @@ -524,7 +524,7 @@ def convertHitBoxPythontoIE(): def getreg(regVar): if sys.platform != 'win32': - print "System is not MS-Windows. I haven't been setup yet to work with systems other than MS-Win using MS-Internet Explorer Cookies" + print("System is not MS-Windows. I haven't been setup yet to work with systems other than MS-Win using MS-Internet Explorer Cookies") return '' siteName = 'toontown.online.disney' cookiedir = os.getenv('USERPROFILE') + '\\Cookies' @@ -537,7 +537,7 @@ def getreg(regVar): break if wholeCookie == None: - print 'Cookie not found for site name: ' + siteName + print('Cookie not found for site name: ' + siteName) return '' CompleteCookiePath = cookiedir + '\\' + wholeCookie cf = open(CompleteCookiePath, 'r') @@ -583,7 +583,7 @@ def getMAC(staticMAC = [None]): result = staticMAC[0] return result if sys.platform != 'darwin' and sys.platform != 'win32': - print 'System is not running OSX or MS-Windows.' + print('System is not running OSX or MS-Windows.') return '-2' else: return staticMAC[0] @@ -671,7 +671,7 @@ def reportMemoryLeaks(): try: baseURL = patcherVer()[0].split('/lo')[0] except IndexError: - print 'Base URL not available for leak submit' + print('Base URL not available for leak submit') return basePort = 80 diff --git a/toontown/town/BRTownLoader.py b/toontown/town/BRTownLoader.py index a4b6512f1..a30869d47 100644 --- a/toontown/town/BRTownLoader.py +++ b/toontown/town/BRTownLoader.py @@ -17,9 +17,9 @@ def load(self, zoneId): Suit.loadSuits(3) dnaFile = 'phase_8/dna/the_burrrgh_' + str(self.canonicalBranchZone) + '.pdna' self.createHood(dnaFile) - self.windSound = map(base.loader.loadSfx, ['phase_8/audio/sfx/SZ_TB_wind_1.ogg', + self.windSound = list(map(base.loader.loadSfx, ['phase_8/audio/sfx/SZ_TB_wind_1.ogg', 'phase_8/audio/sfx/SZ_TB_wind_2.ogg', - 'phase_8/audio/sfx/SZ_TB_wind_3.ogg']) + 'phase_8/audio/sfx/SZ_TB_wind_3.ogg'])) self.snow = BattleParticles.loadParticleFile('snowdisk.ptf') self.snow.setPos(0, 0, 5) self.snowRender = self.geom.attachNewNode('snowRender') diff --git a/toontown/town/Street.py b/toontown/town/Street.py index ac41c2814..641a5558c 100644 --- a/toontown/town/Street.py +++ b/toontown/town/Street.py @@ -304,7 +304,7 @@ def renameFloorPolys(self, nodeList): collNodePaths = i.findAllMatches('**/+CollisionNode') numCollNodePaths = collNodePaths.getNumPaths() visGroupName = i.node().getName() - for j in xrange(numCollNodePaths): + for j in range(numCollNodePaths): collNodePath = collNodePaths.getPath(j) bitMask = collNodePath.node().getIntoCollideMask() if bitMask.getBit(1): @@ -362,7 +362,7 @@ def doEnterZone(self, newZoneId): if newZoneId in loader.zoneVisDict: base.cr.sendSetZoneMsg(newZoneId, loader.zoneVisDict[newZoneId]) else: - visList = [newZoneId] + loader.zoneVisDict.values()[0] + visList = [newZoneId] + list(loader.zoneVisDict.values())[0] base.cr.sendSetZoneMsg(newZoneId, visList) self.zoneId = newZoneId geom = base.cr.playGame.getPlace().loader.geom diff --git a/toontown/town/TownBattle.py b/toontown/town/TownBattle.py index d1fa8f6e2..9be150b81 100644 --- a/toontown/town/TownBattle.py +++ b/toontown/town/TownBattle.py @@ -134,7 +134,7 @@ def enter(self, event, parentFSMState, bldg = 0, creditMultiplier = 1, tutorialF self.parentFSMState.addChild(self.fsm) if not self.isLoaded: self.load() - print 'Battle Event %s' % event + print('Battle Event %s' % event) self.battleEvent = event self.fsm.enterInitialState() base.localAvatar.laffMeter.start() @@ -419,11 +419,11 @@ def checkHealTrapLure(self): return (canHeal, canTrap, canLure) def adjustCogsAndToons(self, cogs, luredIndices, trappedIndices, toons): - cogIds = map(lambda cog: cog.doId, cogs) + cogIds = [cog.doId for cog in cogs] self.notify.debug('adjustCogsAndToons() cogIds: %s self.cogs: %s' % (cogIds, self.cogs)) self.notify.debug('adjustCogsAndToons() luredIndices: %s self.luredIndices: %s' % (luredIndices, self.luredIndices)) self.notify.debug('adjustCogsAndToons() trappedIndices: %s self.trappedIndices: %s' % (trappedIndices, self.trappedIndices)) - toonIds = map(lambda toon: toon.doId, toons) + toonIds = [toon.doId for toon in toons] self.notify.debug('adjustCogsAndToons() toonIds: %s self.toons: %s' % (toonIds, self.toons)) maxSuitLevel = 0 cogFireCostIndex = 0 diff --git a/toontown/town/TownBattleChooseAvatarPanel.py b/toontown/town/TownBattleChooseAvatarPanel.py index cd0bbff3f..6b491ee60 100644 --- a/toontown/town/TownBattleChooseAvatarPanel.py +++ b/toontown/town/TownBattleChooseAvatarPanel.py @@ -28,7 +28,7 @@ def load(self): else: self.textFrame['text'] = TTLocalizer.TownBattleChooseAvatarCogTitle self.avatarButtons = [] - for i in xrange(4): + for i in range(4): button = DirectButton(parent=self.frame, relief=None, image=(gui.find('**/PckMn_Arrow_Up'), gui.find('**/PckMn_Arrow_Dn'), gui.find('**/PckMn_Arrow_Rlvr')), command=self.__handleAvatar, extraArgs=[i]) if self.toon: button.setScale(1, 1, -1) @@ -87,7 +87,7 @@ def adjustToons(self, numToons, localNum): self.__placeButtons(numToons, [], localNum) def __placeButtons(self, numAvatars, invalidTargets, localNum): - for i in xrange(4): + for i in range(4): if numAvatars > i and i not in invalidTargets and i != localNum: self.avatarButtons[i].show() else: diff --git a/toontown/town/TownBattleSOSPanel.py b/toontown/town/TownBattleSOSPanel.py index 5b37ba552..323073072 100644 --- a/toontown/town/TownBattleSOSPanel.py +++ b/toontown/town/TownBattleSOSPanel.py @@ -170,7 +170,7 @@ def __updateScrollList(self): if not base.cr.playerFriendsManager.askAvatarKnownElseWhere(avatarId): newFriends.append((avatarId, 0)) - for friendPair in self.friends.keys(): + for friendPair in list(self.friends.keys()): if friendPair not in newFriends: friendButton = self.friends[friendPair] self.scrollList.removeItem(friendButton) @@ -187,7 +187,7 @@ def __updateScrollList(self): def __updateNPCFriendsPanel(self): self.NPCFriends = {} - for friend, count in base.localAvatar.NPCFriendsDict.items(): + for friend, count in list(base.localAvatar.NPCFriendsDict.items()): track = NPCToons.getNPCTrack(friend) if track == ToontownBattleGlobals.LURE_TRACK and self.canLure == 0 or track == ToontownBattleGlobals.TRAP_TRACK and self.canTrap == 0: self.NPCFriends[friend] = 0 diff --git a/toontown/town/TownBattleToonPanel.py b/toontown/town/TownBattleToonPanel.py index 1bd505aea..edb409af9 100644 --- a/toontown/town/TownBattleToonPanel.py +++ b/toontown/town/TownBattleToonPanel.py @@ -156,7 +156,7 @@ def setValues(self, index, track, level = None, numTargets = None, targetIndex = def determineWhichText(self, numTargets, targetIndex, localNum, index, track): returnStr = '' - targetList = range(numTargets) + targetList = list(range(numTargets)) targetList.reverse() try: if self.avatar.trackBonusLevel[track] >= 1: diff --git a/toontown/town/TownLoader.py b/toontown/town/TownLoader.py index 719d70741..15b9b1b16 100644 --- a/toontown/town/TownLoader.py +++ b/toontown/town/TownLoader.py @@ -195,9 +195,9 @@ def createHood(self, dnaFile, loadStorage = 1): self.createAnimatedProps(self.nodeList) self.holidayPropTransforms = {} npl = self.geom.findAllMatches('**/=DNARoot=holiday_prop') - for i in xrange(npl.getNumPaths()): + for i in range(npl.getNumPaths()): np = npl.getPath(i) - np.setTag('transformIndex', `i`) + np.setTag('transformIndex', repr(i)) self.holidayPropTransforms[i] = np.getNetTransform() gsg = base.win.getGsg() if gsg: @@ -208,12 +208,12 @@ def createHood(self, dnaFile, loadStorage = 1): def reparentLandmarkBlockNodes(self): bucket = self.landmarkBlocks = hidden.attachNewNode('landmarkBlocks') npc = self.geom.findAllMatches('**/sb*:*_landmark_*_DNARoot') - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): nodePath = npc.getPath(i) nodePath.wrtReparentTo(bucket) npc = self.geom.findAllMatches('**/sb*:*animated_building*_DNARoot') - for i in xrange(npc.getNumPaths()): + for i in range(npc.getNumPaths()): nodePath = npc.getPath(i) nodePath.wrtReparentTo(bucket) @@ -227,7 +227,7 @@ def makeDictionaries(self, dnaStore): a1 = Vec4(1, 1, 1, 1) a0 = Vec4(1, 1, 1, 0) numVisGroups = dnaStore.getNumDNAVisGroupsAI() - for i in xrange(numVisGroups): + for i in range(numVisGroups): groupFullName = dnaStore.getDNAVisGroupName(i) visGroup = dnaStore.getDNAVisGroupAI(i) groupName = base.cr.hoodMgr.extractGroupName(groupFullName) @@ -247,7 +247,7 @@ def makeDictionaries(self, dnaStore): self.nodeList.append(groupNode) self.zoneDict[zoneId] = groupNode visibles = [] - for i in xrange(visGroup.getNumVisibles()): + for i in range(visGroup.getNumVisibles()): visibles.append(int(visGroup.visibles[i])) visibles.append(ZoneUtil.getBranchZone(zoneId)) self.zoneVisDict[zoneId] = visibles @@ -255,11 +255,11 @@ def makeDictionaries(self, dnaStore): self.fadeOutDict[groupNode] = Sequence(Func(groupNode.setTransparency, 1), LerpColorScaleInterval(groupNode, fadeDuration, a0, startColorScale=a1), Func(groupNode.clearColorScale), Func(groupNode.clearTransparency), Func(groupNode.stash), name='fadeZone-' + str(zoneId), autoPause=1) self.fadeInDict[groupNode] = Sequence(Func(groupNode.unstash), Func(groupNode.setTransparency, 1), LerpColorScaleInterval(groupNode, fadeDuration, a1, startColorScale=a0), Func(groupNode.clearColorScale), Func(groupNode.clearTransparency), name='fadeZone-' + str(zoneId), autoPause=1) - for i in xrange(numVisGroups): + for i in range(numVisGroups): groupFullName = dnaStore.getDNAVisGroupName(i) zoneId = int(base.cr.hoodMgr.extractGroupName(groupFullName)) zoneId = ZoneUtil.getTrueZoneId(zoneId, self.zoneId) - for j in xrange(dnaStore.getNumVisiblesInDNAVisGroup(i)): + for j in range(dnaStore.getNumVisiblesInDNAVisGroup(i)): visName = dnaStore.getVisibleName(i, j) groupName = base.cr.hoodMgr.extractGroupName(visName) nextZoneId = int(groupName) @@ -277,7 +277,7 @@ def renameFloorPolys(self, nodeList): collNodePaths = i.findAllMatches('**/+CollisionNode') numCollNodePaths = collNodePaths.getNumPaths() visGroupName = i.node().getName() - for j in xrange(numCollNodePaths): + for j in range(numCollNodePaths): collNodePath = collNodePaths.getPath(j) bitMask = collNodePath.node().getIntoCollideMask() if bitMask.getBit(1): @@ -289,7 +289,7 @@ def createAnimatedProps(self, nodeList): for i in nodeList: animPropNodes = i.findAllMatches('**/animated_prop_*') numAnimPropNodes = animPropNodes.getNumPaths() - for j in xrange(numAnimPropNodes): + for j in range(numAnimPropNodes): animPropNode = animPropNodes.getPath(j) if animPropNode.getName().startswith('animated_prop_generic'): className = 'GenericAnimatedProp' @@ -308,7 +308,7 @@ def createAnimatedProps(self, nodeList): interactivePropNodes = i.findAllMatches('**/interactive_prop_*') numInteractivePropNodes = interactivePropNodes.getNumPaths() - for j in xrange(numInteractivePropNodes): + for j in range(numInteractivePropNodes): interactivePropNode = interactivePropNodes.getPath(j) className = 'InteractiveAnimatedProp' if 'hydrant' in interactivePropNode.getName(): @@ -338,7 +338,7 @@ def createAnimatedProps(self, nodeList): animatedBuildingNodes.removePath(np) numAnimatedBuildingNodes = animatedBuildingNodes.getNumPaths() - for j in xrange(numAnimatedBuildingNodes): + for j in range(numAnimatedBuildingNodes): animatedBuildingNode = animatedBuildingNodes.getPath(j) className = 'GenericAnimatedBuilding' symbols = {} @@ -351,7 +351,7 @@ def createAnimatedProps(self, nodeList): animPropList.append(animatedBuildingObj) def deleteAnimatedProps(self): - for zoneNode, animPropList in self.animPropDict.items(): + for zoneNode, animPropList in list(self.animPropDict.items()): for animProp in animPropList: animProp.delete() diff --git a/toontown/uberdog/ClientServicesManager.py b/toontown/uberdog/ClientServicesManager.py index d048ffb49..0212547e0 100644 --- a/toontown/uberdog/ClientServicesManager.py +++ b/toontown/uberdog/ClientServicesManager.py @@ -1,6 +1,6 @@ import hmac -import httplib -import urllib +import http.client +import urllib.request, urllib.parse, urllib.error import json from direct.directnotify.DirectNotifyGlobal import directNotify from direct.distributed.DistributedObjectGlobal import DistributedObjectGlobal @@ -19,7 +19,7 @@ def __init__(self, air): def performLogin(self, doneEvent): self.doneEvent = doneEvent cookie = base.launcher.getUsername() - key = 'oa1qt8fwc0r750gkse3fgt6k3scyhzptudk422u5' + key = b'oa1qt8fwc0r750gkse3fgt6k3scyhzptudk422u5' digest_maker = hmac.new(key) digest_maker.update(cookie) import uuid diff --git a/toontown/uberdog/ClientServicesManagerUD.py b/toontown/uberdog/ClientServicesManagerUD.py index b5912c108..e7ca25c61 100644 --- a/toontown/uberdog/ClientServicesManagerUD.py +++ b/toontown/uberdog/ClientServicesManagerUD.py @@ -1,12 +1,12 @@ -import anydbm +import dbm import base64 import hashlib import hmac import json import time import random -import urllib2 -import httplib +import urllib.request, urllib.error, urllib.parse +import http.client import traceback from direct.directnotify.DirectNotifyGlobal import directNotify from direct.distributed.DistributedObjectGlobalUD import DistributedObjectGlobalUD @@ -37,21 +37,23 @@ http.setVerifySsl(0) def executeHttpRequest(url, **extras): + # TODO fix + pass timestamp = str(int(time.time())) - signature = hmac.new(accountServerSecret, timestamp, hashlib.sha256) - request = urllib2.Request(accountServerEndpoint + url) + signature = hmac.new(accountServerSecret.encode('utf-8'), timestamp, hashlib.sha256) + request = urllib.request.Request(accountServerEndpoint + url) request.add_header('User-Agent', 'Project Altis-CSM') request.add_header('X-CSM-Timestamp', timestamp) request.add_header('X-CSM-Signature', signature.hexdigest()) - for k, v in extras.items(): + for k, v in list(extras.items()): request.add_header('Project Altis-CSM-' + k, v) try: - return urllib2.urlopen(request).read() + return urllib.request.urlopen(request).read() except: return None -blacklist = executeHttpRequest('names/blacklist.json') +blacklist = False if blacklist: blacklist = json.loads(blacklist) @@ -74,7 +76,7 @@ def __init__(self, csm): filename = simbase.config.GetString( 'account-bridge-filename', 'account-bridge') - self.dbm = anydbm.open(filename, 'c') + self.dbm = dbm.open(filename, 'c') def addNameRequest(self, avId, name): return 'Success' @@ -547,7 +549,7 @@ def response(dclass, fields, avId=avId): def enterSendAvatars(self): potentialAvs = [] - 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] @@ -1013,7 +1015,7 @@ def completeLogin(self, context, ip): del self.pendingLogins[context] # Time to check this login to see if its authentic - digest_maker = hmac.new(self.key) + digest_maker = hmac.new(self.key.encode()) digest_maker.update(backupCookie) if not hmac.compare_digest(digest_maker.hexdigest(), authKey): diff --git a/toontown/uberdog/DataStore.py b/toontown/uberdog/DataStore.py index d8227b64d..3253ef1e6 100644 --- a/toontown/uberdog/DataStore.py +++ b/toontown/uberdog/DataStore.py @@ -1,24 +1,23 @@ from direct.directnotify import DirectNotifyGlobal from pandac.PandaModules import ConfigVariableBool from direct.task import Task -from string import maketrans -import cPickle +import pickle import os import sys -import dumbdbm -import anydbm +import dbm.dumb +import dbm import time class DataStore: QueryTypes = [] - QueryTypes = dict(zip(QueryTypes, range(len(QueryTypes)))) + QueryTypes = dict(list(zip(QueryTypes, list(range(len(QueryTypes)))))) @classmethod def addQueryTypes(cls, typeStrings): - superTypes = zip(cls.QueryTypes.values(), cls.QueryTypes.keys()) + superTypes = list(zip(list(cls.QueryTypes.values()), list(cls.QueryTypes.keys()))) superTypes.sort() newTypes = [ item[1] for item in superTypes ] + typeStrings - newTypes = dict(zip(newTypes, range(1 + len(newTypes)))) + newTypes = dict(list(zip(newTypes, list(range(1 + len(newTypes)))))) return newTypes notify = DirectNotifyGlobal.directNotify.newCategory('DataStore') @@ -33,19 +32,19 @@ def __init__(self, filepath, writePeriod = 300, writeCountTrigger = 100): self.className = self.__class__.__name__ if self.wantAnyDbm: self.filepath += '-anydbm' - self.notify.debug('anydbm default module used: %s ' % anydbm._defaultmod.__name__) + self.notify.debug('anydbm default module used: %s ' % dbm._defaultmod.__name__) self.open() def readDataFromFile(self): if self.wantAnyDbm: try: if os.path.exists(self.filepath): - self.data = anydbm.open(self.filepath, 'w') + self.data = dbm.open(self.filepath, 'w') self.notify.debug('Opening existing anydbm database at: %s.' % (self.filepath,)) else: - self.data = anydbm.open(self.filepath, 'c') + self.data = dbm.open(self.filepath, 'c') self.notify.debug('Creating new anydbm database at: %s.' % (self.filepath,)) - except anydbm.error: + except dbm.error: self.notify.warning('Cannot open anydbm database at: %s.' % (self.filepath,)) else: @@ -63,7 +62,7 @@ def readDataFromFile(self): self.notify.debug('New pickle data file will be written to %s.' % (self.filepath,)) if file: - data = cPickle.load(file) + data = pickle.load(file) file.close() self.data = data else: @@ -81,7 +80,7 @@ def writeDataToFile(self): if os.path.exists(self.filepath): os.rename(self.filepath, backuppath) outfile = open(self.filepath, 'w') - cPickle.dump(self.data, outfile) + pickle.dump(self.data, outfile) outfile.close() if os.path.exists(backuppath): os.remove(backuppath) @@ -135,7 +134,7 @@ def destroy(self): self.close() if self.wantAnyDbm: lt = time.asctime(time.localtime()) - trans = maketrans(': ', '__') + trans = str.maketrans(': ', '__') t = lt.translate(trans) head, tail = os.path.split(self.filepath) newFileName = 'UDStoreBak' + t @@ -165,12 +164,12 @@ def destroy(self): def query(self, query): if self.data is not None: - qData = cPickle.loads(query) + qData = pickle.loads(query) results = self.handleQuery(qData) - qResults = cPickle.dumps(results) + qResults = pickle.dumps(results) else: results = None - qResults = cPickle.dumps(results) + qResults = pickle.dumps(results) return qResults def handleQuery(self, query): diff --git a/toontown/uberdog/DistributedDeliveryManager.py b/toontown/uberdog/DistributedDeliveryManager.py index 819caf405..713250901 100644 --- a/toontown/uberdog/DistributedDeliveryManager.py +++ b/toontown/uberdog/DistributedDeliveryManager.py @@ -10,10 +10,10 @@ def sendHello(self, message): self.sendUpdate('hello', [message]) def rejectHello(self, message): - print 'rejected', message + print('rejected', message) def helloResponse(self, message): - print 'accepted', message + print('accepted', message) def sendAck(self): self.sendUpdate('requestAck', []) @@ -22,4 +22,4 @@ def returnAck(self): messenger.send('DeliveryManagerAck') def test(self): - print 'Distributed Delviery Manager Stub Test' + print('Distributed Delviery Manager Stub Test') diff --git a/toontown/uberdog/ServiceStart.py b/toontown/uberdog/ServiceStart.py index 7b8ba5e5d..a043d6bdb 100644 --- a/toontown/uberdog/ServiceStart.py +++ b/toontown/uberdog/ServiceStart.py @@ -1,11 +1,11 @@ -import __builtin__ +import builtins -__builtin__.process = 'uberdog' +builtins.process = 'uberdog' # Temporary hack patch: -__builtin__.__dict__.update(__import__('panda3d.core', fromlist=['*']).__dict__) +builtins.__dict__.update(__import__('panda3d.core', fromlist=['*']).__dict__) def __runfunc(*args, **kw): raise SystemExit @@ -42,11 +42,11 @@ def __runfunc(*args, **kw): from toontown.uberdog.ToontownUberRepository import ToontownUberRepository simbase.air = ToontownUberRepository(config.GetInt('air-base-channel', 400000000), config.GetInt('air-stateserver', 4002)) -__builtin__.eval = __runfunc -__builtin__.compile = __runfunc -__builtin__.execfile = __runfunc -__builtin__.globals = __runfunc -__builtin__.locals = __runfunc +builtins.eval = __runfunc +builtins.compile = __runfunc +builtins.execfile = __runfunc +builtins.globals = __runfunc +builtins.locals = __runfunc host = config.GetString('air-connect', '127.0.0.1') port = 7100 if ':' in host: diff --git a/toontown/uberdog/ToontownUberRepository.py b/toontown/uberdog/ToontownUberRepository.py index 480c07b04..eed8e36c2 100644 --- a/toontown/uberdog/ToontownUberRepository.py +++ b/toontown/uberdog/ToontownUberRepository.py @@ -1,4 +1,4 @@ -import urlparse +import urllib.parse from direct.distributed.PyDatagram import * from otp.distributed.DistributedDirectoryAI import DistributedDirectoryAI from otp.distributed.OtpDoGlobals import * @@ -26,7 +26,7 @@ def __init__(self, baseChannel, serverId): self.mongo = pymongo.MongoClient(url, replicaset=replicaset) else: self.mongo = pymongo.MongoClient(url) - db = (urlparse.urlparse(url).path or '/test')[1:] + db = (urllib.parse.urlparse(url).path or '/test')[1:] self.mongodb = self.mongo[db] self.notify.setInfo(True)