示例#1
0
def init():
    """Performs the one-time initialization of the BUG core and all mods."""
    global g_initDone
    if g_initDone:
        BugUtil.debug("BugInit - init() already complete")
        return
    if not CyGame().isFinalInitialized():
        BugUtil.debug("BugInit - game not fully initialized")
        return
    global g_initRunning
    if g_initRunning:
        BugUtil.warn("BugInit - init() already running")
        return
    g_initRunning = True

    BugUtil.debug("BugInit - initializing...")
    timer = BugUtil.Timer("BUG init")

    BugPath.init()
    timer.log("init paths").start()

    loadMod("init")
    BugCore.initDone()
    timer.log("read configs").start()

    callInits()
    timer.log("call inits/events")

    timer.logTotal()

    g_initDone = True
    g_initRunning = False
    return True
示例#2
0
文件: BugInit.py 项目: AP-ML/DTM
def init():
	"""Performs the one-time initialization of the BUG core and all mods."""
	global g_initDone
	if g_initDone:
		BugUtil.debug("BugInit - init() already complete")
		return
	if not CyGame().isFinalInitialized():
		BugUtil.debug("BugInit - game not fully initialized")
		return
	global g_initRunning
	if g_initRunning:
		BugUtil.warn("BugInit - init() already running")
		return
	g_initRunning = True
	
	BugUtil.debug("BugInit - initializing...")
	timer = BugUtil.Timer("BUG init")
	
	BugPath.init()
	timer.log("init paths").start()
	
	loadMod("init")
	BugCore.initDone()
	timer.log("read configs").start()
	
	callInits()
	timer.log("call inits/events")
	
	timer.logTotal()
	
	g_initDone = True
	g_initRunning = False
	return True
def launch(argsList=None):
	"""
	Opens the mod's help file or web page externally if it can be found or displays an error alert.
	
	On Windows this opens the compiled HTML help file (CHM).
	On Mac this opens a browser window to the online help file.
	"""
	if BugPath.isMac():
		sLang = ["ENG", "ENG", "DEU", "ITA", "ENG"]
		url = "http://civ4bug.sourceforge.net/BUGModHelp/%s/index.htm" % sLang[CyGame().getCurrentLanguage()]
		try:
			import webbrowser
			showLaunchMessage()
			webbrowser.open(url, new=1, autoraise=1)
			return True
		except:
			showErrorAlert(BugUtil.getPlainText("TXT_KEY_BUG_HELP_CANNOT_OPEN_BROWSER_TITLE"), 
					BugUtil.getText("TXT_KEY_BUG_HELP_CANNOT_OPEN_BROWSER_BODY", (url,)))		
	else:
		sLang = ["ENG", "FRA", "DEU", "ITA", "ESP"]
		name = "BUG Mod Help-%s.chm" % (sLang[CyGame().getCurrentLanguage()])
		file = BugPath.findInfoFile(name)
		if file:
			import os
			message = BugUtil.getPlainText("TXT_KEY_BUG_HELP_OPENING")
			CyInterface().addImmediateMessage(message, "")
			os.startfile(file)
			return True
		else:
			showErrorAlert(BugUtil.getPlainText("TXT_KEY_BUG_HELP_MISSING_TITLE"), 
					BugUtil.getText("TXT_KEY_BUG_HELP_MISSING_BODY", (name,)))
	return False
示例#4
0
def launch(argsList=None):
    """
    Opens the mod's help file or web page externally if it can be found or displays an error alert.
    
    On Windows this opens the compiled HTML help file (CHM).
    On Mac this opens a browser window to the online help file.
    """
    if BugPath.isMac():
        sLang = ["ENG", "ENG", "DEU", "ITA", "ENG"]
        url = "http://civ4bug.sourceforge.net/BUGModHelp/%s/index.htm" % sLang[CyGame().getCurrentLanguage()]
        try:
            import webbrowser
            showLaunchMessage()
            webbrowser.open(url, new=1, autoraise=1)
            return True
        except:
            showErrorAlert(BugUtil.getPlainText("TXT_KEY_BUG_HELP_CANNOT_OPEN_BROWSER_TITLE"), 
                    BugUtil.getText("TXT_KEY_BUG_HELP_CANNOT_OPEN_BROWSER_BODY", (url,)))       
    else:
        sLang = ["ENG", "FRA", "DEU", "ITA", "ESP"]
        name = "BUG Mod Help-%s.chm" % (sLang[CyGame().getCurrentLanguage()])
        file = BugPath.findInfoFile(name)
        if file:
            import os
            message = BugUtil.getPlainText("TXT_KEY_BUG_HELP_OPENING")
            CyInterface().addImmediateMessage(message, "")
            os.startfile(file)
            return True
        else:
            showErrorAlert(BugUtil.getPlainText("TXT_KEY_BUG_HELP_MISSING_TITLE"), 
                    BugUtil.getText("TXT_KEY_BUG_HELP_MISSING_BODY", (name,)))
    return False
	def create(self, screen):
		tab = self.createTab(screen)
		panel = self.createMainPanel(screen)
		column = self.addOneColumnLayout(screen, panel)
		
		self.addLabel(screen, column, "FileNotFound", "File Not Found:")
		self.addLabel(screen, column, "IniFilename", "\"" + BugPath.getModName() + ".ini\"")
		
		self.addLabel(screen, column, "DataDirectory", "Data Directory:")
		self.addLabel(screen, column, "DataPath", BugPath.getDataDir())
    def create(self, screen):
        _ = self.createTab(screen)
        panel = self.createMainPanel(screen)
        column = self.addOneColumnLayout(screen, panel)

        self.addLabel(screen, column, "FileNotFound", "File Not Found:")
        self.addLabel(screen, column, "IniFilename",
                      "\"" + BugPath.getModName() + ".ini\"")

        self.addLabel(screen, column, "DataDirectory", "Data Directory:")
        self.addLabel(screen, column, "DataPath", BugPath.getDataDir())
示例#7
0
 def __init__(self, filename=None, *args, **kwargs):
     # Initializes the parser by reading options from the named file.
     import os.path
     import BugPath
     super(CvConfigParser, self).__init__(*args, **kwargs)
     BugPath.init()
     if filename != None:
         filenames = [
             os.path.join(os.path.dirname(BugPath._assetFileSearchPaths),
                          filename)
         ]
         self.read(filenames)
示例#8
0
    def __init__(self, filename = None, *args, **kwargs):
        """Initializes the parser by reading options from the named file."""
        super(CvConfigParser, self).__init__(*args, **kwargs)
# Rise of Mankind 2.8 - init paths before searching config files		
        BugPath.init()
#        BugPath.initSearchPaths()
        if (filename != None):
            filenames = [os.path.join(os.path.dirname(dir), filename) 
                for dir in BugPath._assetFileSearchPaths]
#			filenames += [os.path.join(os.path.dirname(dir), filename) 
#				for dir in BugPath.iniFileSearchPaths]
# Rise of Mankind 2.6 end		
			
			# print "filenames\n", filenames
            self.read(filenames)
示例#9
0
def init():
    """
	Checks for the presence of the BUFFY DLL and sets the global flags.
	"""
    if isEnabled():
        if BugPath.isMac():
            BugUtil.debug("BUFFY is not active on Mac (no DLL)")
        else:
            try:
                if gc.isBuffy():
                    global IS_DLL_PRESENT, IS_DLL_IN_CORRECT_PATH, IS_ACTIVE
                    IS_DLL_PRESENT = True
                    IS_ACTIVE = True
                    BugUtil.info("BUFFY is active (API version %d)",
                                 gc.getBuffyApiVersion())
                    try:
                        dllPath = gc.getGame().getDLLPath()
                        exePath = gc.getGame().getExePath()
                        dllPathThenUp3 = os.path.dirname(
                            os.path.dirname(os.path.dirname(dllPath)))
                        if dllPathThenUp3 == exePath:
                            IS_DLL_IN_CORRECT_PATH = True
                    except:
                        pass  # DLL path is borked
            except:
                BugUtil.info("BUFFY is not active (no DLL)")
示例#10
0
def processSetupFile():
    """
	Reads and processes the GameSetUpCheck.txt file.
	"""
    filename = BugPath.findDataFile("GameSetUpCheck.txt", "GameSetUpCheck")
    if not filename:
        BugUtil.error("Cannot find GameSetUpCheck.txt")
    else:
        try:
            BugUtil.debug("GameSetUpCheck - processing GameSetUpCheck.txt")
            fp = open(filename, 'r')
            for line in fp:
                BugUtil.debug("GameSetUpCheck - %s", line)
                (type, key, value) = line.split(",")
                if (type == 'minHOFOpponents'):
                    minHOFOpponents.append(int(value.strip()))
                elif (type == 'maxHOFOpponents'):
                    maxHOFOpponents.append(int(value.strip()))
                elif (type == 'reqHOFGameOptions'):
                    hofGameOptionRequirements.append(int(value.strip()))
                elif (type == 'hofAllowedMapScripts'):
                    hofAllowedMapScripts[key.strip()] = int(value.strip())
                elif (type == 'hofAllowedCylindrical'):
                    hofAllowedCylindrical[key.strip()] = int(value.strip())
                elif (type == 'hofAllowedToroidal'):
                    hofAllowedToroidal[key.strip()] = int(value.strip())
                elif (type == 'balancedOptionIndex'):
                    balancedOptionIndex[key.strip()] = int(value.strip())
                elif (type == 'worldWrapOptionIndex'):
                    worldWrapOptionIndex[key.strip()] = int(value.strip())
                elif (type == 'allowedWorldWrapValue'):
                    allowedWorldWrapValue[key.strip()] = int(value.strip())
                elif (type == 'modCRC'):
                    global modCRC
                    modCRC = key
                elif (type == 'dllCRC'):
                    global dllCRC
                    dllCRC = key
                elif (type == 'shaderCRC'):
                    global shaderCRC
                    shaderCRC = key
                elif (type == 'pythonCRC'):
                    global pythonCRC
                    pythonCRC = key
                elif (type == 'xmlCRC'):
                    global xmlCRC
                    xmlCRC = key
                else:
                    BugUtil.warn("Unknown type '%s' in GameSetUpCheck.txt",
                                 type)
            fp.close()
            return True
        except:
            BugUtil.trace("Error processing GameSetUpCheck.txt")
            try:
                fp.close()
            except:
                pass
    return False
示例#11
0
 def setLogFilePath(self, LogFilePath, bSaveToOptions=False):
     if (bSaveToOptions):
         AutologOpt.setFilePath(LogFilePath)
         BugOptions.write()
     if (not LogFilePath or LogFilePath == "Default"):
         LogFilePath = BugPath.findOrMakeDir("Autolog")
     self.LogFilePath = LogFilePath
     self.updateLogFile()
示例#12
0
	def setLogFilePath(self, LogFilePath, bSaveToOptions=False):
		if (bSaveToOptions):
			AutologOpt.setFilePath(LogFilePath)
			BugOptions.write()
		if (not LogFilePath or LogFilePath == "Default"):
			LogFilePath = BugPath.findOrMakeDir("Autolog")
		self.LogFilePath = LogFilePath
		self.updateLogFile()
def processSetupFile():
	"""
	Reads and processes the GameSetUpCheck.txt file.
	"""
	filename = BugPath.findDataFile("GameSetUpCheck.txt", "GameSetUpCheck")
	if not filename:
		BugUtil.error("Cannot find GameSetUpCheck.txt")
	else:
		try:
			BugUtil.debug("GameSetUpCheck - processing GameSetUpCheck.txt")
			fp = open(filename, 'r')
			for line in fp:
				BugUtil.debug("GameSetUpCheck - %s", line)
				(type, key, value) = line.split(",")
				if (type == 'minHOFOpponents'):
					minHOFOpponents.append(int(value.strip()))
				elif (type == 'maxHOFOpponents'):
					maxHOFOpponents.append(int(value.strip()))
				elif (type == 'reqHOFGameOptions'):
					hofGameOptionRequirements.append(int(value.strip()))
				elif (type == 'hofAllowedMapScripts'):
					hofAllowedMapScripts[key.strip()] = int(value.strip())
				elif (type == 'hofAllowedCylindrical'):
					hofAllowedCylindrical[key.strip()] = int(value.strip())
				elif (type == 'hofAllowedToroidal'):
					hofAllowedToroidal[key.strip()] = int(value.strip())
				elif (type == 'balancedOptionIndex'):
					balancedOptionIndex[key.strip()] = int(value.strip())
				elif (type == 'worldWrapOptionIndex'):
					worldWrapOptionIndex[key.strip()] = int(value.strip())
				elif (type == 'allowedWorldWrapValue'):
					allowedWorldWrapValue[key.strip()] = int(value.strip())
				elif (type == 'modCRC'):
					global modCRC
					modCRC = key
				elif (type == 'dllCRC'):
					global dllCRC
					dllCRC = key
				elif (type == 'shaderCRC'):
					global shaderCRC
					shaderCRC = key
				elif (type == 'pythonCRC'):
					global pythonCRC
					pythonCRC = key
				elif (type == 'xmlCRC'):
					global xmlCRC
					xmlCRC = key
				else:
					BugUtil.warn("Unknown type '%s' in GameSetUpCheck.txt", type)
			fp.close()
			return True
		except:
			BugUtil.trace("Error processing GameSetUpCheck.txt")
			try:
				fp.close()
			except:
				pass
	return False
示例#14
0
def combatMessageBuilder(cdAttacker, cdDefender, iCombatOdds):
    combatMessage = ""
    if (cdAttacker.eOwner == cdAttacker.eVisualOwner):
        combatMessage += "%s's" % (gc.getPlayer(cdAttacker.eOwner).getName(), )
    combatMessage += " %s (%.2f)" % (
        cdAttacker.sUnitName,
        cdAttacker.iCurrCombatStr / 100.0,
    )
    combatMessage += " " + localText.getText("TXT_KEY_COMBAT_MESSAGE_VS",
                                             ()) + " "
    if (cdDefender.eOwner == cdDefender.eVisualOwner):
        combatMessage += "%s's" % (gc.getPlayer(cdDefender.eOwner).getName(), )
    combatMessage += "%s (%.2f)" % (
        cdDefender.sUnitName,
        cdDefender.iCurrCombatStr / 100.0,
    )
    CyInterface().addCombatMessage(cdAttacker.eOwner, combatMessage)
    CyInterface().addCombatMessage(cdDefender.eOwner, combatMessage)
    # CtHCombat.log start
    combatMessageVs = combatMessage
    # CtHCombat.log end
    combatMessage = "%s %.1f%%" % (
        localText.getText("TXT_KEY_COMBAT_MESSAGE_ODDS", ()),
        iCombatOdds / 10.0,
    )
    CyInterface().addCombatMessage(cdAttacker.eOwner, combatMessage)
    CyInterface().addCombatMessage(cdDefender.eOwner, combatMessage)
    combatDetailMessageBuilder(cdAttacker, cdAttacker.eOwner, -1)
    combatDetailMessageBuilder(cdDefender, cdAttacker.eOwner, 1)
    combatDetailMessageBuilder(cdAttacker, cdDefender.eOwner, -1)
    combatDetailMessageBuilder(cdDefender, cdDefender.eOwner, 1)
    # CtHCombat.log
    combatMessageOdds = combatMessage
    combatLogName = None
    if not CyGame().isPitbossHost():
        isActivePlayer = gc.getGame().getActivePlayer() in [
            cdDefender.eOwner, cdAttacker.eOwner
        ]

        if isActivePlayer:
            combatLogName = BugPath.join(BugPath.getRootDir(), "Combat.log")
            f = codecs.open(combatLogName, "a", 'utf-8')
            f.write(combatMessageVs + " \n")
            f.write(combatMessageOdds + " \n")
            f.close()
示例#15
0
 def openSDFile(self):
     szPath = BugAutolog.getFilePath()
     if (not szPath or szPath == "Default"):
         szPath = BugPath.findOrMakeDir("Autolog")
     if (not os.path.isdir(szPath)):
         os.makedirs(szPath)
     szFile = os.path.join(szPath, self.FileName)
     self.SDFile = codecs.open(szFile, 'a', 'utf-8')
     BugConfigTracker.add("SDFile_Log", szFile)
示例#16
0
文件: StatusDump.py 项目: AP-ML/DTM
	def openSDFile(self):
		szPath = BugAutolog.getFilePath()
		if (not szPath or szPath == "Default"):
			szPath = BugPath.findOrMakeDir("Autolog")
		if (not os.path.isdir(szPath)):
			os.makedirs(szPath)
		szFile = os.path.join(szPath, self.FileName)
		self.SDFile = codecs.open(szFile, 'a', 'utf-8')
		BugConfigTracker.add("SDFile_Log", szFile)
示例#17
0
	def eraseDot(self, city, alpha):
		"""
		Erases the dot for a single city.
		"""
		if self.DRAW_DOTS:
			x, y = city.point
			if BugPath.isMac():
				CyEngine().addColoredPlot(x, y, self.INVISIBLE_COLOR, self.DOT_LAYER)
			else:
				CyEngine().addColoredPlotAlt(x, y, self.NO_DOT_STYLE, self.DOT_LAYER, "COLOR_BLACK", alpha)
	def eraseDot(self, city, alpha):
		"""
		Erases the dot for a single city.
		"""
		if self.DRAW_DOTS:
			x, y = city.point
			if BugPath.isMac():
				CyEngine().addColoredPlot(x, y, self.INVISIBLE_COLOR, self.DOT_LAYER)
			else:
				CyEngine().addColoredPlotAlt(x, y, self.NO_DOT_STYLE, self.DOT_LAYER, "COLOR_BLACK", alpha)
示例#19
0
文件: BugOptions.py 项目: AP-ML/DTM
	def read(self):
		try:
			self.path = BugPath.findSettingsFile(self.name)
			if not self.path:
				self.create()
			else:
				self.config = ConfigObj(self.path, encoding='utf_8')
		except IOError:
			self.path = None
			self.config = None
			BugUtil.trace("BugOptions - error reading file '%s'", self.name)
示例#20
0
	def drawDot(self, city, alpha):
		"""
		Draws the dot for a single city.
		"""
		if self.DRAW_DOTS:
			x, y = city.point
			colorInfo = gc.getColorInfo(city.color)
			if BugPath.isMac():
				color = colorInfo.getColor()
				CyEngine().addColoredPlot(x, y, NiColorA(color.r, color.g, color.b, alpha), self.DOT_LAYER)
			else:
				CyEngine().addColoredPlotAlt(x, y, self.DOT_STYLE, self.DOT_LAYER, colorInfo.getType(), alpha)
	def drawDot(self, city, alpha):
		"""
		Draws the dot for a single city.
		"""
		if self.DRAW_DOTS:
			x, y = city.point
			colorInfo = gc.getColorInfo(city.color)
			if BugPath.isMac():
				color = colorInfo.getColor()
				CyEngine().addColoredPlot(x, y, NiColorA(color.r, color.g, color.b, alpha), self.DOT_LAYER)
			else:
				CyEngine().addColoredPlotAlt(x, y, self.DOT_STYLE, self.DOT_LAYER, colorInfo.getType(), alpha)
示例#22
0
	def read(self):
		try:
			self.path = BugPath.findIniFile(self.name)
			if not self.path:
				self.create()
			else:
				self.config = ConfigObj(self.path, encoding='utf_8')
#			BugConfigTracker.add("BUG_Mod_Config", self.path)
		except IOError:
			self.path = None
			self.config = None
			BugUtil.error("BugOptions - error reading file '%s'", name)
示例#23
0
def init():
    """Performs the one-time initialization of the BUG core and all mods."""
    global g_initDone
    print "BugInit.init"
    if g_initDone:
        print "BugInit.init - already complete"
        return True

    import BugPath
    BugPath.init()

    loadMod("init")
    import BugCore
    BugCore.initDone()

    callInits()

    g_initDone = True
    CyGlobalContext().setIsBug(True)

    return True
示例#24
0
文件: BugFile.py 项目: AP-ML/DTM
	def openFile(self, bForce=False, sWrite='a'):
		if (self.HoldOpen and not bForce):
			return

		szPath = BugFile.getFilePath()
		if (not szPath or szPath == "Default"):
			szPath = BugPath.findOrMakeDir("Autolog")
		if (not os.path.isdir(szPath)):
			os.makedirs(szPath)

		szFile = os.path.join(szPath, self.FileName)
		self.File = codecs.open(szFile, sWrite, 'utf-8')
		BugConfigTracker.add("Autolog_Log", szFile)
示例#25
0
def loadMod(name):
	"""Load the given mod from its XML file using a custom parser."""
	path = BugPath.findAssetFile(name + ".xml", "Config")
	if path:
		BugUtil.debug("BugInit - loading mod %s...", name)
		parser = BugConfig.XmlParser()
		timer = BugUtil.Timer("load mod")
		try:
			parser.parse(path)
		finally:
			timer.log(name)
	else:
		BugUtil.error("BugInit - cannot find XML file for mod %s", name)
示例#26
0
def loadMod(name):
    """Load the given mod from its XML file using a custom parser."""
    path = BugPath.findAssetFile(name + ".xml", "Config")
    if path:
        BugUtil.debug("BugInit - loading mod %s...", name)
        parser = BugConfig.ConfigParser()
        timer = BugUtil.Timer("load mod")
        try:
            parser.parse(path)
        finally:
            timer.log(name)
    else:
        BugUtil.error("BugInit - cannot find XML file for mod %s", name)
示例#27
0
	def openFile(self, bForce=False, sWrite='a'):
		if (self.HoldOpen and not bForce):
			return

		szPath = BugFile.getFilePath()
		if (not szPath or szPath == "Default"):
			szPath = BugPath.findOrMakeDir("Autolog")
		if (not os.path.isdir(szPath)):
			os.makedirs(szPath)

		szFile = os.path.join(szPath, self.FileName)
		self.File = codecs.open(szFile, sWrite, 'utf-8')
		BugConfigTracker.add("Autolog_Log", szFile)
示例#28
0
def init():
	"""Performs the one-time initialization of the BUG core and all mods."""
	global g_initDone
	if g_initDone:
		BugUtil.debug("BugInit - init() already complete")
		return
	if not CyGame().isFinalInitialized():
		BugUtil.debug("BugInit - game not fully initialized")
		return
	# K-Mod. Don't use any BUG features if this is a PitBoss server.
	if CyGame().isPitbossHost():
		BugUtil.debug("BugInit - BUG disabled for PitBoss host")
		return
	# K-Mod end
	global g_initRunning
	if g_initRunning:
		BugUtil.warn("BugInit - init() already running")
		return
	g_initRunning = True
	
	BugUtil.debug("BugInit - initializing...")
	timer = BugUtil.Timer("BUG init")
	
	BugPath.init()
	timer.log("init paths").start()
	
	loadMod("init")
	BugCore.initDone()
	timer.log("read configs").start()
	
	callInits()
	timer.log("call inits/events")
	
	timer.logTotal()
	
	g_initDone = True
	g_initRunning = False
	return True
示例#29
0
def init():
    """Performs the one-time initialization of the BUG core and all mods."""
    global g_initDone
    if g_initDone:
        BugUtil.debug("BugInit - init() already complete")
        return
    if not CyGame().isFinalInitialized():
        BugUtil.debug("BugInit - game not fully initialized")
        return
    # K-Mod. Don't use any BUG features if this is a PitBoss server.
    if CyGame().isPitbossHost():
        BugUtil.debug("BugInit - BUG disabled for PitBoss host")
        return
    # K-Mod end
    global g_initRunning
    if g_initRunning:
        BugUtil.warn("BugInit - init() already running")
        return
    g_initRunning = True

    BugUtil.debug("BugInit - initializing...")
    timer = BugUtil.Timer("BUG init")

    BugPath.init()
    timer.log("init paths").start()

    loadMod("init")
    BugCore.initDone()
    timer.log("read configs").start()

    callInits()
    timer.log("call inits/events")

    timer.logTotal()

    g_initDone = True
    g_initRunning = False
    return True
示例#30
0
def loadMod(name):
    """Load the given mod from its XML file using a custom parser."""
    path = BugPath.findAssetFile(name + ".xml", "Config")
    if path:
        BugUtil.debug("BugInit - loading module %s...", name)
        parser = BugConfig.ConfigParser()
        timer = BugUtil.Timer("load mod")
        try:
            parser.parse(path)
        # <advc.009b> Say which module failed
        except Exception, e:
            BugUtil.error("BugInit - failed to parse module %s", name)
            timer.log(name)
            raise e  # </advc.009b>
        timer.log(name)
示例#31
0
def initAfterReload():
	"""
	Initialize BUG and fires PythonReloaded event after reloading Python modules while game is still running.
	
	The first time this module is loaded after the game launches, the global context is not yet ready,
	and thus BUG cannot be initialized. When the Python modules are reloaded after being changed, however,
	this will reinitialize BUG and the main interface.
	"""
	import BugInit
	import BugPath
	if not BugPath.isMac() and BugInit.init():
		try:
			import CvScreensInterface
			CvScreensInterface.reinitMainInterface()
		except:
			import BugUtil
			BugUtil.error("BugInit - failure rebuilding main interface after reloading Python modules")
		getEventManager().fireEvent("PythonReloaded")
示例#32
0
def initAfterReload():
	"""
	Initialize BUG and fires PythonReloaded event after reloading Python modules while game is still running.
	
	The first time this module is loaded after the game launches, the global context is not yet ready,
	and thus BUG cannot be initialized. When the Python modules are reloaded after being changed, however,
	this will reinitialize BUG and the main interface.
	"""
	import BugInit
	import BugPath
	if not BugPath.isMac() and BugInit.init():
		try:
			import CvScreensInterface
			CvScreensInterface.reinitMainInterface()
		except:
			import BugUtil
			BugUtil.error("BugInit - failure rebuilding main interface after reloading Python modules")
		getEventManager().fireEvent("PythonReloaded")
示例#33
0
def getSaveFileName(pathName):
    if pathName:
        activePlayer = PlayerUtil.getActivePlayer()
        if not MapFinder.isActive() and options.isUsePlayerName():
            fileName = activePlayer.getName()
            turnYear = CyGameTextMgr().getTimeStr(gc.getGame().getGameTurn(),
                                                  False)
            fileName += '_' + turnYear.replace(" ", "-")
        else:
            objLeaderHead = gc.getLeaderHeadInfo(
                activePlayer.getLeaderType()).getText()

            game = gc.getGame()
            map = gc.getMap()

            difficulty = gc.getHandicapInfo(
                activePlayer.getHandicapType()).getText()
            mapType = os.path.basename(map.getMapScriptName())
            mapSize = gc.getWorldInfo(map.getWorldSize()).getText()
            mapClimate = gc.getClimateInfo(map.getClimate()).getText()
            mapLevel = gc.getSeaLevelInfo(map.getSeaLevel()).getText()
            era = gc.getEraInfo(game.getStartEra()).getText()
            speed = gc.getGameSpeedInfo(game.getGameSpeedType()).getText()
            turnYear = CyGameTextMgr().getTimeStr(game.getGameTurn(), False)
            turnYear = turnYear.replace(" ", "-")
            turnYear = turnYear.replace(",", "-")

            fileName = objLeaderHead[0:3]
            fileName += '_' + difficulty[0:3]
            fileName += '_' + mapSize[0:3]
            fileName += '_' + mapType[0:3]
            fileName += '_' + speed[0:3]
            fileName += '_' + era[0:3]
            fileName += '_' + turnYear
            fileName += '_' + mapClimate[0:3]
            fileName += '_' + mapLevel[0:3]

        fileName = BugPath.join(pathName, fileName)
        baseFileName = CvUtil.convertToStr(fileName)
        fileName = CvUtil.convertToStr(fileName + '_' +
                                       time.strftime("%b-%d-%Y_%H-%M-%S"))

        return (fileName, baseFileName)
示例#34
0
	def write(self):
		if self.fileExists():
			if self.isDirty():
				BugUtil.debug("BugOptions - writing INI file '%s'", self.name)
				try:
					self.config.write()
					self.dirty = False
				except IOError:
					BugUtil.error("BugOptions - failed writing INI file '%s'", self.path)
		elif self.isLoaded():
			self.path = BugPath.createIniFile(self.name)
			BugUtil.debug("BugOptions - writing new INI file '%s'", self.name)
			try:
				file = open(self.path, "w")
				self.config.write(file)
				file.close()
				self.dirty = False
			except IOError:
				BugUtil.error("BugOptions - failed creating INI file '%s'", self.path)
		else:
			BugUtil.warn("BugOptions - INI file '%s' was never read", self.name)
示例#35
0
文件: AutoSave.py 项目: AP-ML/DTM
def getSaveFileName(pathName):
	if pathName:
		activePlayer = PlayerUtil.getActivePlayer()
		if not MapFinder.isActive() and options.isUsePlayerName():
			fileName = activePlayer.getName()
			turnYear = CyGameTextMgr().getTimeStr(gc.getGame().getGameTurn(), False)
			fileName += '_' + turnYear.replace(" ", "-")
		else:
			objLeaderHead = gc.getLeaderHeadInfo (activePlayer.getLeaderType()).getText()
			
			game = gc.getGame()
			map = gc.getMap()
			
			difficulty = gc.getHandicapInfo(activePlayer.getHandicapType()).getText()
			mapType = os.path.basename(map.getMapScriptName())
			mapSize = gc.getWorldInfo(map.getWorldSize()).getText()
			mapClimate = gc.getClimateInfo(map.getClimate()).getText()
			mapLevel = gc.getSeaLevelInfo(map.getSeaLevel()).getText()
			era = gc.getEraInfo(game.getStartEra()).getText()
			speed = gc.getGameSpeedInfo(game.getGameSpeedType()).getText()
			turnYear = CyGameTextMgr().getTimeStr(game.getGameTurn(), False)
			turnYear = turnYear.replace(" ", "-")
			turnYear = turnYear.replace(",", "-")

			fileName = objLeaderHead[0:3]
			fileName += '_' + difficulty[0:3]
			fileName += '_' + mapSize[0:3]
			fileName += '_' + mapType[0:3]
			fileName += '_' + speed[0:3]
			fileName += '_' + era[0:3]
			fileName += '_' + turnYear
			fileName += '_' + mapClimate[0:3]
			fileName += '_' + mapLevel[0:3]

		fileName = BugPath.join(pathName, fileName)
		baseFileName = CvUtil.convertToStr(fileName)
		fileName = CvUtil.convertToStr(fileName + '_' + time.strftime("%b-%d-%Y_%H-%M-%S"))

		return (fileName, baseFileName)
示例#36
0
文件: Buffy.py 项目: AP-ML/DTM
def init():
    """
	Checks for the presence of the BUFFY DLL and sets the global flags.
	"""
    if isEnabled():
        if BugPath.isMac():
            BugUtil.debug("BUFFY is not active on Mac (no DLL)")
        else:
            try:
                if gc.isBuffy():
                    global IS_DLL_PRESENT, IS_DLL_IN_CORRECT_PATH, IS_ACTIVE
                    IS_DLL_PRESENT = True
                    IS_ACTIVE = True
                    BugUtil.info("BUFFY is active (API version %d)", gc.getBuffyApiVersion())
                    try:
                        dllPath = gc.getGame().getDLLPath()
                        exePath = gc.getGame().getExePath()
                        dllPathThenUp3 = os.path.dirname(os.path.dirname(os.path.dirname(dllPath)))
                        if dllPathThenUp3 == exePath:
                            IS_DLL_IN_CORRECT_PATH = True
                    except:
                        pass  # DLL path is borked
            except:
                BugUtil.info("BUFFY is not active (no DLL)")
示例#37
0
def getSaveDir(type=SINGLE, variant=None):
    if variant:
        return BugPath.join(_saveDir, type, variant)
    else:
        return BugPath.join(_saveDir, type)
示例#38
0
def init():
    global _saveDir
    _saveDir = BugPath.join(BugPath.getRootDir(), "Saves")
    if not _saveDir:
        BugUtil.error("Could not find Saves directory")
示例#39
0
def writeLog():
	
	if gc.getGame().getActivePlayer() == -1:
		playername = "Pitboss"
	else:
		playername = CvUtil.convertToStr(gc.getPlayer(gc.getGame().getActivePlayer()).getNameKey())
	szNewFilename = BugPath.getRootDir() + "\\Logs\\" + "%s - Player %s - " % (playername, gc.getGame().getActivePlayer()) + "OOSLog - Turn " + "%s" % (gc.getGame().getGameTurn()) + ".txt"
	pFile = open(szNewFilename, "w")
	
	#
	# Global data
	#
	pFile.write(SEPERATOR)
	pFile.write(SEPERATOR)

	pFile.write("  GLOBALS  \n")

	pFile.write(SEPERATOR)
	pFile.write(SEPERATOR)
	pFile.write("\n\n")

	#pFile.write("Next Map Rand Value: %d\n" % CyGame().getMapRand().get(10000, "OOS Log"))
	#pFile.write("Next Soren Rand Value: %d\n" % CyGame().getSorenRand().get(10000, "OOS Log"))

	pFile.write("Total num cities: %d\n" % CyGame().getNumCities() )
	pFile.write("Total population: %d\n" % CyGame().getTotalPopulation() )
	pFile.write("Total Deals: %d\n" % CyGame().getNumDeals() )

	pFile.write("Total owned plots: %d\n" % CyMap().getOwnedPlots() )
	pFile.write("Total num areas: %d\n" % CyMap().getNumAreas() )

	pFile.write("\n\n")

	#
	# Player data
	#
	iPlayer = 0
	for iPlayer in range(gc.getMAX_PLAYERS()):
		pPlayer = gc.getPlayer(iPlayer)
		if (pPlayer.isEverAlive()):
			pFile.write(SEPERATOR)
			pFile.write(SEPERATOR)

			pFile.write("  PLAYER %d: %s  \n" % (iPlayer, CvUtil.convertToStr(pPlayer.getName())))
			pFile.write("  Civilizations: %s  \n" % (CvUtil.convertToStr(pPlayer.getCivilizationDescriptionKey())))

			pFile.write(SEPERATOR)
			pFile.write(SEPERATOR)
			pFile.write("\n\n")

			pFile.write("Basic data:\n")
			pFile.write("-----------\n")
			pFile.write("Player %d Score: %d\n" % (iPlayer, gc.getGame().getPlayerScore(iPlayer) ))

			pFile.write("Player %d Population: %d\n" % (iPlayer, pPlayer.getTotalPopulation() ) )
			pFile.write("Player %d Total Land: %d\n" % (iPlayer, pPlayer.getTotalLand() ) )
			pFile.write("Player %d Gold: %d\n" % (iPlayer, pPlayer.getGold() ) )
			pFile.write("Player %d Assets: %d\n" % (iPlayer, pPlayer.getAssets() ) )
			pFile.write("Player %d Power: %d\n" % (iPlayer, pPlayer.getPower() ) )
			pFile.write("Player %d Num Cities: %d\n" % (iPlayer, pPlayer.getNumCities() ) )
			pFile.write("Player %d Num Units: %d\n" % (iPlayer, pPlayer.getNumUnits() ) )
			pFile.write("Player %d Num Selection Groups: %d\n" % (iPlayer, pPlayer.getNumSelectionGroups() ) )
			pFile.write("Player %d Difficulty: %d\n" % (iPlayer, pPlayer.getHandicapType() ))

			pFile.write("\n\n")

			pFile.write("Yields:\n")
			pFile.write("-------\n")
			for iYield in range( int(YieldTypes.NUM_YIELD_TYPES) ):
				pFile.write("Player %d %s Total Yield: %d\n" % (iPlayer, gc.getYieldInfo(iYield).getDescription(), pPlayer.calculateTotalYield(iYield) ))

			pFile.write("\n\n")

			pFile.write("Commerce:\n")
			pFile.write("---------\n")
			for iCommerce in range( int(CommerceTypes.NUM_COMMERCE_TYPES) ):
				pFile.write("Player %d %s Total Commerce: %d\n" % (iPlayer, gc.getCommerceInfo(iCommerce).getDescription(), pPlayer.getCommerceRate(CommerceTypes(iCommerce)) ))

			pFile.write("\n\n")

			pFile.write("Bonus Info:\n")
			pFile.write("-----------\n")
			for iBonus in range(gc.getNumBonusInfos()):
				pFile.write("Player %d, %s, Number Available: %d\n" % (iPlayer, gc.getBonusInfo(iBonus).getDescription(), pPlayer.getNumAvailableBonuses(iBonus) ))
				pFile.write("Player %d, %s, Import: %d\n" % (iPlayer, gc.getBonusInfo(iBonus).getDescription(), pPlayer.getBonusImport(iBonus) ))
				pFile.write("Player %d, %s, Export: %d\n" % (iPlayer, gc.getBonusInfo(iBonus).getDescription(), pPlayer.getBonusExport(iBonus) ))
				pFile.write("\n")

			pFile.write("\n\n")

			pFile.write("Improvement Info:\n")
			pFile.write("-----------------\n")
			for iImprovement in range(gc.getNumImprovementInfos()):
				pFile.write("Player %d, %s, Improvement count: %d\n" % (iPlayer, CvUtil.convertToStr(gc.getImprovementInfo(iImprovement).getDescription()), pPlayer.getImprovementCount(iImprovement) ))

			pFile.write("\n\n")

			pFile.write("Building Class Info:\n")
			pFile.write("--------------------\n")
			for iBuildingClass in range(gc.getNumBuildingClassInfos()):
				pFile.write("Player %d, %s, Building class count plus building: %d\n" % (iPlayer, CvUtil.convertToStr(gc.getBuildingClassInfo(iBuildingClass).getDescription()), pPlayer.getBuildingClassCountPlusMaking(iBuildingClass) ))

			pFile.write("\n\n")

			pFile.write("Unit Class Info:\n")
			pFile.write("--------------------\n")
			for iUnitClass in range(gc.getNumUnitClassInfos()):
				pFile.write("Player %d, %s, Unit class count plus training: %d\n" % (iPlayer, CvUtil.convertToStr(gc.getUnitClassInfo(iUnitClass).getDescription()), pPlayer.getUnitClassCountPlusMaking(iUnitClass) ))

			pFile.write("\n\n")

			pFile.write("UnitAI Types Info:\n")
			pFile.write("------------------\n")
			for iUnitAIType in range(int(UnitAITypes.NUM_UNITAI_TYPES)):
				pFile.write("Player %d, %s, Unit AI Type count: %d\n" % (iPlayer, gc.getUnitAIInfo(iUnitAIType).getDescription(), pPlayer.AI_totalUnitAIs(UnitAITypes(iUnitAIType)) ))
			

			pFile.write("\n\n")

			pFile.write("City Info:\n")
			pFile.write("----------\n")
			iNumCities = pPlayer.getNumCities()

			if (iNumCities == 0):
				pFile.write("No Cities")
			else:
				pLoopCityTuple = pPlayer.firstCity(False)
				while (pLoopCityTuple[0] != None):
					pCity = pLoopCityTuple[0]
					#pFile.write("Player %d, City ID: %d, %s, Plot Radius: %d\n" % (iPlayer, pCity.getID(), CvUtil.convertToStr(pCity.getName()), pCity.getPlotRadius() ))

					pFile.write("X: %d, Y: %d\n" % (pCity.getX(), pCity.getY()) )
					pFile.write("Founded: %d\n" % pCity.getGameTurnFounded() )
					pFile.write("Population: %d\n" % pCity.getPopulation() )
					pFile.write("Buildings: %d\n" % pCity.getNumBuildings() )
					pFile.write("Improved Plots: %d\n" % pCity.countNumImprovedPlots() )
					pFile.write("Producing: %s\n" % pCity.getProductionName() )
					pFile.write("%d Tiles Worked, %d Specialists, %d Great People\n" % (pCity.getWorkingPopulation(), pCity.getSpecialistPopulation(), pCity.getNumGreatPeople()) )

					pLoopCityTuple = pPlayer.nextCity(pLoopCityTuple[1], False)
					pFile.write("\n")


			pFile.write("\n\n")

			pFile.write("Unit Info:\n")
			pFile.write("----------\n")
			iNumUnits = pPlayer.getNumUnits()

			if (iNumUnits == 0):
				pFile.write("No Units")
			else:
				pLoopUnitTuple = pPlayer.firstUnit(False)
				while (pLoopUnitTuple[0] != None):
					pUnit = pLoopUnitTuple[0]
					pFile.write("Player %d, Unit ID: %d, %s\n" % (iPlayer, pUnit.getID(), CvUtil.convertToStr(pUnit.getName()) ))
					pFile.write("X: %d, Y: %d\n" % (pUnit.getX(), pUnit.getY()) )
					pFile.write("Damage: %d\n" % pUnit.getDamage() )
					pFile.write("ExperienceTimes100: %d\n" % pUnit.getExperience100() )
					pFile.write("RealExperience: %d\n" % pUnit.getRealExperience() )
					pFile.write("Experience: %d\n" % pUnit.getExperience() )
					pFile.write("Level: %d\n" % pUnit.getLevel() )
					pFile.write("Promotions:\n")
					for j in range(gc.getNumPromotionInfos()):
						if (pUnit.isHasPromotion(j)):
							pFile.write("%s\n" % (CvUtil.convertToStr(gc.getPromotionInfo(j).getDescription()) ))

					pLoopUnitTuple = pPlayer.nextUnit(pLoopUnitTuple[1], False)
					pFile.write("\n")
				

			# Space at end of player's info
			pFile.write("\n\n")
		
	# Close file

	pFile.close()
示例#40
0
def log_path():
    # filepath='D:\\DoC_Log\\'
    filepath = BugPath.join(BugPath.getRootDir(), 'Saves', 'logs', '')
    return filepath
示例#41
0
文件: AutoSave.py 项目: AP-ML/DTM
def getSaveDir(type=SINGLE, variant=None):
	if variant:
		return BugPath.join(_saveDir, type, variant)
	else:
		return BugPath.join(_saveDir, type)
示例#42
0
def writeLog():

    if CyGame().isPitbossHost():
        playername = "PitBoss"
    else:
        # advc: Prepend id b/c player names can be the same (that happens easily when testing on a single machine)
        activePlayer = gc.getPlayer(gc.getGame().getActivePlayer())
        playername = str(activePlayer.getID()) + CvUtil.convertToStr(
            activePlayer.getName())
    szNewFilename = BugPath.getRootDir() + "\\Logs\\" + "OOSLog - %s - " % (
        playername) + "Turn %s" % (gc.getGame().getGameTurn()) + ".log"
    # <advc> Replacement for the bWroteLog mechanism above
    if os.path.isfile(szNewFilename):
        return  # </advc>
    pFile = open(szNewFilename, "w")

    # Backup current language
    iLanguage = CyGame().getCurrentLanguage()
    # Force english language for logs
    CyGame().setCurrentLanguage(0)

    #
    # Global data
    #
    pFile.write(SEPERATOR)
    pFile.write(SEPERATOR)

    #pFile.write(CvUtil.convertToStr(CyTranslator().getText("TXT_KEY_VERSION", ())))
    #pFile.write("\n\n")

    # The log follows the order in CvGame::calculateSyncChecksum()

    pFile.write("  GLOBALS  \n")

    pFile.write(SEPERATOR)
    pFile.write(SEPERATOR)
    pFile.write("\n\n")
    # advc: Call getSeed instead of get -- don't want to change the state of the RNGs here.
    pFile.write("Last Map Rand Value: %d\n" % CyGame().getMapRand().getSeed())
    pFile.write("Last Soren Rand Value: %d\n" %
                CyGame().getSorenRand().getSeed())

    pFile.write("Total cities: %d\n" % CyGame().getNumCities())
    pFile.write("Total population: %d\n" % CyGame().getTotalPopulation())
    pFile.write("Total deals: %d\n" % CyGame().getNumDeals())

    pFile.write("Total owned plots: %d\n" % CyMap().getOwnedPlots())
    pFile.write("Total number of areas: %d\n" % CyMap().getNumAreas())

    #pFile.write("Global counter: %d\n" % CyGame().getGlobalCounter() )
    #pFile.write("Total civilization cities: %d\n" % CyGame().getNumCivCities() )

    pFile.write("Turn slice: %d\n" % (CyGame().getTurnSlice() % 8))

    pFile.write("\n\n")

    #
    # Player data
    #
    iPlayer = 0
    for iPlayer in range(gc.getMAX_PLAYERS()):
        pPlayer = gc.getPlayer(iPlayer)
        if (pPlayer.isEverAlive()):
            pFile.write(SEPERATOR)
            pFile.write(SEPERATOR)

            pFile.write("  PLAYER %d: %s  \n" %
                        (iPlayer, CvUtil.convertToStr(pPlayer.getName())))
            #pFile.write("  Civilization: %s  \n" % (CvUtil.convertToStr(pPlayer.getCivilizationDescriptionKey())))

            pFile.write(SEPERATOR)
            pFile.write(SEPERATOR)
            pFile.write("\n\n")

            pFile.write("Basic data:\n")
            pFile.write("-----------\n")
            pFile.write("Player %d Score: %d\n" %
                        (iPlayer, gc.getGame().getPlayerScore(iPlayer)))

            pFile.write("Player %d Population: %d\n" %
                        (iPlayer, pPlayer.getTotalPopulation()))
            pFile.write("Player %d Total Land: %d\n" %
                        (iPlayer, pPlayer.getTotalLand()))
            pFile.write("Player %d Gold: %d\n" % (iPlayer, pPlayer.getGold()))
            pFile.write("Player %d Assets: %d\n" %
                        (iPlayer, pPlayer.getAssets()))
            pFile.write("Player %d Power: %d\n" %
                        (iPlayer, pPlayer.getPower()))
            pFile.write("Player %d Num Cities: %d\n" %
                        (iPlayer, pPlayer.getNumCities()))
            pFile.write("Player %d Num Units: %d\n" %
                        (iPlayer, pPlayer.getNumUnits()))
            pFile.write("Player %d Num Selection Groups: %d\n" %
                        (iPlayer, pPlayer.getNumSelectionGroups()))
            #pFile.write("Player %d Difficulty: %d\n" % (iPlayer, pPlayer.getHandicapType() ))
            #pFile.write("Player %d Religion: %s\n" % (iPlayer, CvUtil.convertToStr(pPlayer.getStateReligionKey()) ))
            #.pFile.write("Player %d Total culture: %d\n" % (iPlayer, pPlayer.countTotalCulture() ))

            pFile.write("\n\n")

            pFile.write("Yields:\n")
            pFile.write("-------\n")
            for iYield in range(int(YieldTypes.NUM_YIELD_TYPES)):
                pFile.write("Player %d %s Total Yield: %d\n" %
                            (iPlayer, gc.getYieldInfo(iYield).getDescription(),
                             pPlayer.calculateTotalYield(iYield)))

            pFile.write("\n\n")

            pFile.write("Commerce:\n")
            pFile.write("---------\n")
            for iCommerce in range(int(CommerceTypes.NUM_COMMERCE_TYPES)):
                pFile.write(
                    "Player %d %s Total Commerce: %d\n" %
                    (iPlayer, gc.getCommerceInfo(iCommerce).getDescription(),
                     pPlayer.getCommerceRate(CommerceTypes(iCommerce))))

            pFile.write("\n\n")

            pFile.write("Bonus Info:\n")
            pFile.write("-----------\n")
            for iBonus in range(gc.getNumBonusInfos()):
                pFile.write("Player %d, %s, Number Available: %d\n" %
                            (iPlayer, gc.getBonusInfo(iBonus).getDescription(),
                             pPlayer.getNumAvailableBonuses(iBonus)))
                pFile.write("Player %d, %s, Import: %d\n" %
                            (iPlayer, gc.getBonusInfo(iBonus).getDescription(),
                             pPlayer.getBonusImport(iBonus)))
                pFile.write("Player %d, %s, Export: %d\n" %
                            (iPlayer, gc.getBonusInfo(iBonus).getDescription(),
                             pPlayer.getBonusExport(iBonus)))
                pFile.write("\n")

            pFile.write("\n\n")

            pFile.write("Improvement Info:\n")
            pFile.write("-----------------\n")
            for iImprovement in range(gc.getNumImprovementInfos()):
                pFile.write(
                    "Player %d, %s, Improvement count: %d\n" %
                    (iPlayer,
                     CvUtil.convertToStr(
                         gc.getImprovementInfo(iImprovement).getDescription()),
                     pPlayer.getImprovementCount(iImprovement)))

            pFile.write("\n\n")

            pFile.write("Building Class Info:\n")
            pFile.write("--------------------\n")
            for iBuildingClass in range(gc.getNumBuildingClassInfos()):
                pFile.write(
                    "Player %d, %s, Building class count plus making: %d\n" %
                    (iPlayer,
                     CvUtil.convertToStr(
                         gc.getBuildingClassInfo(
                             iBuildingClass).getDescription()),
                     pPlayer.getBuildingClassCountPlusMaking(iBuildingClass)))

            pFile.write("\n\n")

            pFile.write("Unit Class Info:\n")
            pFile.write("--------------------\n")
            for iUnitClass in range(gc.getNumUnitClassInfos()):
                pFile.write(
                    "Player %d, %s, Unit class count plus training: %d\n" %
                    (iPlayer,
                     CvUtil.convertToStr(
                         gc.getUnitClassInfo(iUnitClass).getDescription()),
                     pPlayer.getUnitClassCountPlusMaking(iUnitClass)))

            pFile.write("\n\n")

            pFile.write("UnitAI Types Info:\n")
            pFile.write("------------------\n")
            for iUnitAIType in range(int(UnitAITypes.NUM_UNITAI_TYPES)):
                pFile.write(
                    "Player %d, %s, Unit AI Type count: %d\n" %
                    (iPlayer, gc.getUnitAIInfo(iUnitAIType).getDescription(),
                     pPlayer.AI_totalUnitAIs(UnitAITypes(iUnitAIType))))

            pFile.write("\n\n")

            pFile.write("Unit Info:\n")
            pFile.write("----------\n")
            iNumUnits = pPlayer.getNumUnits()

            if (iNumUnits == 0):
                pFile.write("No Units")
            else:
                pLoopUnitTuple = pPlayer.firstUnit(False)
                while (pLoopUnitTuple[0] != None):
                    pUnit = pLoopUnitTuple[0]
                    pFile.write("Player %d, Unit ID: %d, %s\n" %
                                (iPlayer, pUnit.getID(),
                                 CvUtil.convertToStr(pUnit.getName())))

                    pFile.write("X: %d, Y: %d\n" %
                                (pUnit.getX(), pUnit.getY()))
                    pFile.write("Damage: %d\n" % pUnit.getDamage())
                    #pFile.write("Experience: %d\n" % pUnit.getExperienceTimes100() )
                    pFile.write("Experience: %d\n" % pUnit.getExperience())
                    pFile.write("Level: %d\n" % pUnit.getLevel())
                    #pFile.write("Promotions:\n")
                    #for j in range(gc.getNumPromotionInfos()):
                    #	if (pUnit.isHasPromotion(j)):
                    #		pFile.write("%s\n" % (CvUtil.convertToStr(gc.getPromotionInfo(j).getDescription()) ))

                    pLoopUnitTuple = pPlayer.nextUnit(pLoopUnitTuple[1], False)
                    pFile.write("\n")

            if not pPlayer.isBarbarian():  # advc.003n
                pFile.write("\n\n")
                pFile.write("Attitude Info:\n")
                pFile.write("----------\n")

                iLoopPlayer = 0
                # <advc.003n> was MAX_PLAYERS
                for iLoopPlayer in range(gc.getMAX_CIV_PLAYERS()):
                    if iPlayer == iLoopPlayer:
                        continue  # </advc.003n>
                    pLoopPlayer = gc.getPlayer(iLoopPlayer)
                    pFile.write(
                        "Players %d - %d, Attitude: %d (Note, actual attitudeval number is used for the OOS checksum.)\n"
                        % (iPlayer, iLoopPlayer,
                           pPlayer.AI_getAttitude(iLoopPlayer)))

            pFile.write("\n\n")

            pFile.write("City Info:\n")
            pFile.write("----------\n")
            iNumCities = pPlayer.getNumCities()

            if (iNumCities == 0):
                pFile.write("No Cities")
            else:  # advc: Don't print this for each city
                pFile.write(
                    "(Events that have occurred are also used for the checksum.)\n"
                )
                pLoopCityTuple = pPlayer.firstCity(False)
                while (pLoopCityTuple[0] != None):
                    pCity = pLoopCityTuple[0]
                    pFile.write("Player %d, City ID: %d, %s, X: %d, Y: %d\n" %
                                (iPlayer, pCity.getID(),
                                 CvUtil.convertToStr(pCity.getName()),
                                 pCity.getX(), pCity.getY()))

                    pFile.write(
                        "Religions and corporations present are also used for the checksum.\n"
                    )
                    #pFile.write("Founded: %d\n" % pCity.getGameTurnFounded() )
                    #pFile.write("Population: %d\n" % pCity.getPopulation() )
                    #pFile.write("Buildings: %d\n" % pCity.getNumBuildings() )
                    #pFile.write("Improved Plots: %d\n" % pCity.countNumImprovedPlots() )
                    #pFile.write("Producing: %s\n" % pCity.getProductionName() )
                    #pFile.write("Turns remaining for production: %d\n" % pCity.getProductionTurnsLeft() )
                    pFile.write(
                        "%d happiness, %d unhappiness, %d health, %d unhealth, %d food\n"
                        % (pCity.happyLevel(), pCity.unhappyLevel(0),
                           pCity.goodHealth(), pCity.badHealth(False),
                           pCity.getFood()))
                    # advc.007:
                    pFile.write("Needed floating defenders: %d\n" %
                                pCity.AI_neededFloatingDefenders())
                    #pFile.write("%d Tiles Worked, %d Specialists, %d Great People\n" % (pCity.getWorkingPopulation(), pCity.getSpecialistPopulation(), pCity.getNumGreatPeople()) )
                    #pFile.write("City radius: %d\n" % pCity.getPlotRadius() )

                    pLoopCityTuple = pPlayer.nextCity(pLoopCityTuple[1], False)
                    pFile.write("\n")

            # Space at end of player's info
            pFile.write("\n\n")

    # Restore current language
    CyGame().setCurrentLanguage(iLanguage)

    # Close file

    pFile.close()
示例#43
0
def savemap(argsList=None):
    # <advc.savem>
    if gc.getGame().isNetworkMultiPlayer(
    ) and not CvEventInterface.getEventManager().isCheatsEnabled():
        return
    if not BugCore.game.MainInterface.isSavemapEnabled():
        return
    # </advc.savem>
    # First choice: Mod folder
    pathnames.append(str(BugPath.getModDir()) + "\\PrivateMaps\\")
    # Under MyGames. Can't load it from there into AdvCiv w/o toggling NoCustomAssets.
    myGamesPathFromBUG = str(BugPath.getRootDir()) + "\\PublicMaps\\"
    pathnames.append(myGamesPathFromBUG)
    # Try tywiggins's code as a fallback
    pathFromOSEnv = str(
        os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH") +
        "\\Documents\\My Games\\Beyond The Sword\\PublicMaps\\")
    if pathFromOSEnv != myGamesPathFromBUG:
        pathnames.append(pathFromOSEnv)
    # As for the file name: Will generate that based on the map settings
    # </advc.savem>

    map = CyMap()  # advc.savem
    game = CyGame()  # advc.savem
    width = map.getGridWidth()  # returns num plots, not gridsize
    height = map.getGridHeight()
    # add extra plots if plots-x or plots-y are no multiples of 4 to obtain valid gridsizes (= numplots/4)
    extraWidth = int(width % 4)
    extraHeight = int(height % 4)
    if (extraWidth != 0):
        extraWidth = 4 - extraWidth
    if (extraHeight != 0):
        extraHeight = 4 - extraHeight
    numPlots = (width + extraWidth) * (height + extraHeight)
    # <advc.savem> Make sure not to create a huge file if the map somehow returns crazy dimensions
    if numPlots < 0 or numPlots > 50000:
        BugUtil.error("savemap: Invalid number of plots: '%d'", numPlots)
        msg = "Savemap failed. Invalid number of tiles: " + str(numPlots)
        _showOnScreenMessage(msg)
        return
    # </advc.savem>
    wrapX = map.isWrapX()
    wrapY = map.isWrapY()
    topLat = map.getTopLatitude()
    bottomLat = map.getBottomLatitude()
    numPlayers = game.countCivPlayersEverAlive()

    # determine starting locations
    civs = []
    civsDesc = []
    startingPlots = []
    startingPlotsXY = []

    for i in range(numPlayers):
        player = gc.getPlayer(i)
        pIndex = 0
        civInfo = gc.getCivilizationInfo(
            player.getCivilizationType())  # advc.savem
        # determine starting location from first settler found, since player.getStartingPlot() is somewhat unreliable; only do this at gamestart
        if (game.getElapsedGameTurns() == 0
                and game.getStartEra() == 0):  # advc.savem: was getGameTurn==0
            if (player.getNumUnits() > 0):
                for j in range(player.getNumUnits()):
                    unit = player.getUnit(j)
                    if (unit.getUnitClassType() == gc.getInfoTypeForString(
                            "UNITCLASS_SETTLER")):
                        pPlot = unit.plot()
                        if (pPlot.isWater() == 0):
                            pIndex = map.plotNum(
                                pPlot.getX(),
                                pPlot.getY()) + (extraWidth * pPlot.getY())
                            # advc.savem: was print
                            BugUtil.debug(
                                "savemap: Found settler of civ '%d' ('%s') at plot '%d' ('%d', '%d')",
                                int(player.getCivilizationType()),
                                civInfo.getShortDescription(0), pIndex,
                                map.plotX(pIndex), map.plotY(pIndex))
                            startingPlots.append(pIndex)
                            civs.append(int(player.getCivilizationType()))
                            civsDesc.append(civInfo.getType())
                            break

        # fallback; determine starting location from (a) stored location, (b) capital, or (c) first city
        if (pIndex == 0):
            pPlot = player.getStartingPlot()
            if (map.isPlot(pPlot.getX(), pPlot.getY())):
                pIndex = map.plotNum(
                    pPlot.getX(), pPlot.getY()) + (extraWidth * pPlot.getY())
                startingPlots.append(pIndex)
                civs.append(int(player.getCivilizationType()))
                civsDesc.append(civInfo.getType())
            elif (player.getCapitalCity().plot() != None):
                pPlot = player.getCapitalCity().plot()
                pIndex = map.plotNum(
                    pPlot.getX(), pPlot.getY()) + (extraWidth * pPlot.getY())
                startingPlots.append(pIndex)
                civs.append(int(player.getCivilizationType()))
                civsDesc.append(civInfo.getType())
            elif ((player.getCapitalCity().plot() == None)
                  and (player.getNumCities() > 0)):
                pPlot = player.getCity(0).plot()
                pIndex = map.plotNum(
                    pPlot.getX(), pPlot.getY()) + (extraWidth * pPlot.getY())
                startingPlots.append(pIndex)
                civs.append(int(player.getCivilizationType()))
                civsDesc.append(civInfo.getType())
            # advc.savem: was print
            BugUtil.debug(
                "savemap: No settler found (or not saving on the initial turn) for civ '%d' ('%s'); setting starting location at plot '%d' ('%d', '%d')",
                int(player.getCivilizationType()),
                civInfo.getShortDescription(0), pIndex, map.plotX(pIndex),
                map.plotY(pIndex))

    # also store starting coords, not actually required, but makes debugging easier
    for i in range(len(startingPlots)):
        pIndex = startingPlots[i]
        pPlotXY = [map.plotX(pIndex), map.plotY(pIndex)]
        startingPlotsXY.append(pPlotXY)

    # determine terrain etc
    plotTypes = {}  # default 3 (PLOT_OCEAN in BTS)
    terrainTypes = {}  # default 6 (TERRAIN_OCEAN in BTS)
    bonuses = {}  # default -1
    features = {}  # default -1
    featureVarieties = {}  # default 0
    improvements = {}  # default -1
    riverwe = {}  # default -1
    riverns = {}  # default -1

    for i in range(0, height):
        for j in range(0, width):
            pPlot = map.plot(j, i)
            pIndex = map.plotNum(pPlot.getX(),
                                 pPlot.getY()) + (extraWidth * pPlot.getY())

            if (int(pPlot.getPlotType()) != 3):
                plotTypes[pIndex] = int(pPlot.getPlotType())
            if (pPlot.getTerrainType() != 6):
                terrainTypes[pIndex] = pPlot.getTerrainType()
            if (pPlot.getBonusType(-1) != -1):
                bonuses[pIndex] = pPlot.getBonusType(-1)
            if (pPlot.getFeatureType() != -1):
                features[pIndex] = pPlot.getFeatureType()
                featureVarieties[pIndex] = pPlot.getFeatureVariety()
            if (pPlot.getImprovementType() != -1):
                improvements[pIndex] = pPlot.getImprovementType()
            if (pPlot.isNOfRiver()):
                riverwe[pIndex] = int(pPlot.getRiverWEDirection())
            if (pPlot.isWOfRiver()):
                riverns[pIndex] = int(pPlot.getRiverNSDirection())

    # write mapscript
    # <advc.savem>
    mapScriptName = str(map.getMapScriptName())
    dimensionsInName = True
    wbEnding = ".CivBeyondSwordWBSave"
    if wbEnding in mapScriptName:
        mapScriptName = mapScriptName.replace(wbEnding, "")
        # Scenario dimensions aren't so interesting
        dimensionsInName = False
    # If the script is used recursively (who would do that?) the map script name can get long
    if len(mapScriptName) > 100:
        mapScriptName = mapScriptName[:100]
    filename = mapScriptName + "_"
    if dimensionsInName:
        filename += str(width) + "x" + str(height) + "_"
    filename += str(numPlayers) + "civs"
    # A bit complicated b/c I want to make sure not to overwrite anything
    goodPath = None
    goodName = None
    customAssets = False
    for pathname in pathnames:
        idSuffix = ""
        attempts = 10
        for id in range(attempts):
            if id > 0:
                idSuffix = "_" + str(id)
            goodName = filename + idSuffix
            pathStr = pathname + goodName + ".py"
            try:
                f = open(pathStr)
            except:
                # File doesn't exist yet: good (or pathname is inaccessible; we'll see about that)
                break
            BugUtil.debug("savemap: File '%s' already exists", pathStr)
            if id == attempts - 1:
                BugUtil.error(
                    "savemap: Files '%s' already exist",
                    pathname + filename + "[0.." + str(attempts - 1) + "].py")
                msg = "Failed to save map to " + pathname + " -- file " + goodName + ".py already exists."
                _showOnScreenMessage(msg)
                return
            f.close()
        try:
            f = open(pathStr, 'w')
        except:
            BugUtil.debug("savemap: Cannot open path '%s' for writing",
                          pathStr)
            customAssets = True
            continue
        goodPath = pathname
        msg = "Saving map to " + pathStr + "\nNote:"
        if customAssets:
            msg += "\n"
        else:
            msg += " "
        # I see no way to make CvDLLPythonIFaceBase aware of the new map script
        # (CvDLLPythonIFaceBase::moduleExists doesn't do the trick either)
        msg += "Playing the saved map will require a restart of Civ 4"
        if customAssets:
            msg += ", and mods that disable CustomAssets cannot load maps from that location"
        msg += "."
        _showOnScreenMessage(msg, customAssets)
        break
    if goodPath is None:
        path1 = pathnames[0]
        path2 = pathnames[1]
        BugUtil.error("savemap: Failed to write to '%s' and '%s'", path1,
                      path2)
        msg = "Unable to save map to either:\n" + path1 + " or \n" + path2
        _showOnScreenMessage(msg)
        return
    # </advc.savem>

    f.write('from CvPythonExtensions import *\n')
    f.write('import CvMapGeneratorUtil\n')
    f.write('from random import random, seed, shuffle\n')
    f.write('\n')
    # advc.savem: Moved up for quick inspection
    f.write('def getDescription():\n')
    #string = '\treturn "Saved Map, based on ' + str(map.getMapScriptName()) + ' ('+str(width)+' x '+str(height)+') with '+str(numPlayers)+' civs"\n'
    # <advc.savem> Use the above for the file name instead
    string = '\treturn '
    string += "\"Originally created with the following settings by:\\n"
    # This isn't portable; based on advc.106h.
    settingsStr = map.getSettingsString()
    settingsStr = settingsStr.replace('\n', '\\n')
    string += settingsStr + "\\n"
    string += "Original players:\\n"
    for playerID in range(numPlayers):
        player = gc.getPlayer(playerID)
        civInfo = gc.getCivilizationInfo(player.getCivilizationType())
        leaderInfo = gc.getLeaderHeadInfo(player.getLeaderType())
        string += str(playerID) + " - " + leaderInfo.getDescription(
        ) + " of " + civInfo.getShortDescription(0)
        if player.isHuman():
            string += " (human)"
        string += "\\n"
    string += "Saved on turn " + str(game.getGameTurn()) + "\""
    string += '\n'
    # </advc.savem>
    f.write(string)
    f.write('\n')
    f.write('gc = CyGlobalContext()\n')
    f.write('\n')
    f.write(
        '# seed random generator with MapRand (synchronized source for multiplayer)\n'
    )
    f.write(
        'seedValue = gc.getGame().getMapRand().get(65535, "Seeding mapRand - savemap.py")\n'
    )
    f.write('seed(seedValue)\n')
    f.write('\n')
    string = 'plotTypes = ' + str(plotTypes) + '\n'
    f.write(string)
    string = 'terrainTypes = ' + str(terrainTypes) + '\n'
    f.write(string)
    string = 'bonuses = ' + str(bonuses) + '\n'
    f.write(string)
    string = 'features = ' + str(features) + '\n'
    f.write(string)
    string = 'featureVarieties = ' + str(featureVarieties) + '\n'
    f.write(string)
    string = 'riverwe = ' + str(riverwe) + '\n'
    f.write(string)
    string = 'riverns = ' + str(riverns) + '\n'
    f.write(string)
    string = 'improvements = ' + str(improvements) + '\n'
    f.write(string)
    string = 'numPlots = ' + str(numPlots) + '\n'
    f.write(string)
    f.write('\n')
    f.write('def isAdvancedMap():\n')
    f.write('\treturn 0\n')
    f.write('\n')
    f.write('def isClimateMap():\n')
    f.write('\treturn 0\n')
    f.write('\n')
    f.write('def isSeaLevelMap():\n')
    f.write('\treturn 0\n')
    f.write('\n')
    f.write('def getNumCustomMapOptions():\n')
    f.write('\treturn 3\n')
    f.write('\n')
    f.write('def getCustomMapOptionName(argsList):\n')
    f.write('\t[iOption] = argsList\n')
    f.write('\toption_names = {\n')
    # (advc.savem: Tbd.: Options "Players", "Difficulty")
    f.write(
        '\t\t0:\t"Starting Sites",\n')  # advc.savem: was "Starting Locations"
    f.write('\t\t1:\t"Bonus Resources",\n')  # advc.savem: was "Bonuses"
    f.write('\t\t2:\t"Goody Huts"\n')
    f.write('\t\t}\n')
    f.write(
        '\ttranslated_text = unicode(CyTranslator().getText(option_names[iOption], ()))\n'
    )
    f.write('\treturn translated_text\n')
    f.write('\n')
    f.write('def getNumCustomMapOptionValues(argsList):\n')
    f.write('\t[iOption] = argsList\n')
    f.write('\toption_values = {\n')
    f.write('\t\t0:\t3,\n')
    f.write('\t\t1:\t2,\n')
    f.write('\t\t2:\t2\n')
    f.write('\t\t}\n')
    f.write('\treturn option_values[iOption]\n')
    f.write('\n')
    f.write('def getCustomMapOptionDescAt(argsList):\n')
    f.write('\t[iOption, iSelection] = argsList\n')
    f.write('\tselection_names = {\n')
    f.write('\t\t0:\t{\n')
    # (advc.savem: Tbd.: "Players" selections: "Original Players" / "Custom [Override?] Players".
    # Also: "Difficulty": "Custom Difficulty" / "Original Difficulty"
    # Could shorten the selection names further; the longer names are better for the in-game Settings tab.)
    f.write('\t\t\t0: "Original Starts",\n'
            )  # advc.savem: was "Use Fixed Starting Locations"
    # advc.savem: was "Use Fixed Starting Locations, but assign Civs at Random".
    f.write('\t\t\t1: "Shuffled Starts",\n')
    # advc.savem: Was "Ignore Fixed Locations". Warn that the normalization step will be skipped?
    f.write('\t\t\t2: "New Starts"\n')
    f.write('\t\t\t},\n')
    f.write('\t\t1:\t{\n')
    f.write('\t\t\t0: "Original Bonuses",\n'
            )  # advc.savem: was "Use Fixed Bonuses"
    f.write('\t\t\t1: "New Bonuses"\n')  # advc.savem: was "Randomize Bonuses"
    f.write('\t\t\t},\n')
    f.write('\t\t2:\t{\n')
    f.write('\t\t\t0: "Original Huts",\n'
            )  # advc.savem: was "Use fixed Goody Huts"
    f.write('\t\t\t1: "New Huts"\n')  # advc.savem: was "Randomize Goody Huts"
    f.write('\t\t\t}\n')
    f.write('\t\t}\n')
    f.write(
        '\ttranslated_text = unicode(CyTranslator().getText(selection_names[iOption][iSelection], ()))\n'
    )
    f.write('\treturn translated_text\n')
    f.write('\n')
    f.write('def getCustomMapOptionDefault(argsList):\n')
    f.write('\t[iOption] = argsList\n')
    f.write('\toption_defaults = {\n')
    f.write('\t\t0:\t0,\n')
    f.write('\t\t1:\t0,\n')
    f.write('\t\t2:\t0\n')
    f.write('\t\t}\n')
    f.write('\treturn option_defaults[iOption]\n')
    f.write('\n')
    # advc.savem: Rather confusing together with selections like "Random Bonuses"
    #f.write('def isRandomCustomMapOption(argsList):\n')
    #f.write('\t[iOption] = argsList\n')
    #f.write('\toption_random = {\n')
    #f.write('\t\t0:\tTrue,\n')
    #f.write('\t\t1:\tTrue,\n')
    #f.write('\t\t2:\tTrue\n')
    #f.write('\t\t}\n')
    #f.write('\treturn option_random[iOption]\n')
    #f.write('\n')
    f.write('def getWrapX():\n')
    string = '\treturn ' + str(wrapX) + '\n'
    f.write(string)
    f.write('\n')
    f.write('def getWrapY():\n')
    string = '\treturn ' + str(wrapY) + '\n'
    f.write(string)
    f.write('\n')
    f.write('def getTopLatitude():\n')
    string = '\treturn ' + str(topLat) + '\n'
    f.write(string)
    f.write('\n')
    f.write('def getBottomLatitude():\n')
    string = '\treturn ' + str(bottomLat) + '\n'
    f.write(string)
    f.write('\n')
    f.write('def getGridSize(argsList):\n')
    string = '\treturn (' + str((width + extraWidth) / 4) + ', ' + str(
        (height + extraHeight) / 4) + ')\n'
    f.write(string)
    f.write('\n')
    f.write('def generatePlotTypes():\n')
    f.write('\tplots = []\n')
    f.write('\tfor i in range(numPlots):\n')
    f.write('\t\tif(i in plotTypes):\n')
    f.write('\t\t\tplots.append(plotTypes[i])\n')
    f.write('\t\telse:\n')
    f.write('\t\t\tplots.append(3)\n')
    f.write('\treturn plots\n')
    f.write('\n')
    f.write('def generateTerrainTypes():\n')
    f.write('\tterrain = []\n')
    f.write('\tfor i in range(numPlots):\n')
    f.write('\t\tif(i in terrainTypes):\n')
    f.write('\t\t\tterrain.append(terrainTypes[i]) \n')
    f.write('\t\telse:\n')
    f.write('\t\t\tterrain.append(6)\n')
    f.write('\treturn terrain\n')
    f.write('\n')
    f.write('def beforeInit():\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def beforeGeneration():\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def addRivers():\n')
    f.write(
        '\t# yes, use riverwe for setNOfRiver and riverns for setWOfRiver\n')
    f.write('\tfor plotIdx in riverwe:\n')
    f.write('\t\tpPlot = CyMap().plotByIndex(plotIdx)\n')
    f.write(
        '\t\tpPlot.setNOfRiver(1, CardinalDirectionTypes(riverwe[plotIdx]))\n')
    f.write('\tfor plotIdx in riverns:\n')
    f.write('\t\tpPlot = CyMap().plotByIndex(plotIdx)\n')
    f.write(
        '\t\tpPlot.setWOfRiver(1, CardinalDirectionTypes(riverns[plotIdx]))\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def addLakes():\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def addFeatures():\n')
    f.write('\tfor plotIdx in features:\n')
    f.write('\t\tpPlot = CyMap().plotByIndex(plotIdx)\n')
    f.write(
        '\t\tpPlot.setFeatureType(features[plotIdx], featureVarieties[plotIdx])\n'
    )
    f.write('\treturn 0\n')
    f.write('\n')
    f.write('def addBonuses():\n')
    f.write('\tif CyMap().getCustomMapOption(1) == 0:\n')
    f.write('\t\tfor plotIdx in bonuses:\n')
    f.write('\t\t\tpPlot = CyMap().plotByIndex(plotIdx)\n')
    f.write('\t\t\tpPlot.setBonusType(bonuses[plotIdx])\n')
    f.write('\telse:\n')
    f.write('\t\tCyPythonMgr().allowDefaultImpl()\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def addGoodies():\n')
    f.write('\tif CyMap().getCustomMapOption(2) == 0:\n')
    f.write('\t\tfor plotIdx in improvements:\n')
    f.write(
        '\t\t\tif(improvements[plotIdx] == gc.getInfoTypeForString("IMPROVEMENT_GOODY_HUT")):\n'
    )
    f.write('\t\t\t\tpPlot = CyMap().plotByIndex(plotIdx)\n')
    f.write(
        '\t\t\t\tpPlot.setImprovementType(gc.getInfoTypeForString("IMPROVEMENT_GOODY_HUT"))\n'
    )
    f.write('\telse:\n')
    f.write('\t\tCyPythonMgr().allowDefaultImpl()\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def assignStartingPlots():\n')
    # <advc.027> Allow StartingPositionIteration to assign the plots
    f.write('\tif CyMap().getCustomMapOption(0) == 2:\n')
    f.write('\t\tCyPythonMgr().allowDefaultImpl()\n')
    f.write('\t\treturn None\n')
    # </advc.027>
    string = '\t# civs are ' + str(civsDesc) + '\n'
    f.write(string)
    string = '\tcivs = ' + str(civs) + '\n'
    f.write(string)
    string = '\tstartingPlots = ' + str(startingPlots) + '\n'
    f.write(string)
    string = '\tstartingPlotsXY = ' + str(startingPlotsXY) + '\n'
    f.write(string)
    f.write('\tif CyMap().getCustomMapOption(0) == 1:\n')
    f.write('\t\tshuffle(startingPlots)\n')
    f.write('\tusedstartingPlots = []\n')
    f.write('\tnumPlayers = CyGame().countCivPlayersEverAlive()\n')
    f.write('\tnotinlist = []\n')
    f.write('\tfor i in range(0, numPlayers):\n')
    f.write('\t\tplayer = gc.getPlayer(i)\n')
    f.write('\t\t# partly random assignment to fixed locations\n')
    f.write('\t\tif CyMap().getCustomMapOption(0) == 1:\n')
    f.write('\t\t\tif(i < len(startingPlots)):\n')
    f.write('\t\t\t\tplotindex = startingPlots[i]\n')
    f.write('\t\t\telse:\n')
    f.write('\t\t\t\tplotindex = findStartingPlot(i)\n')
    f.write(
        '\t\t\tplayer.setStartingPlot(CyMap().plotByIndex(plotindex), 1)\n')
    f.write('\t\t# fixed locations\n')
    #f.write('\t\telif CyMap().getCustomMapOption(0) == 0:\n')
    f.write('\t\telse:\n')  # advc.027: Replacing the above
    f.write('\t\t\tciv = int(player.getCivilizationType())\n')
    f.write('\t\t\tif(civs.count(civ) == 1):\n')
    f.write('\t\t\t\tpindex = civs.index(civ)\n')
    f.write('\t\t\t\tplotindex = startingPlots[pindex]\n')
    f.write('\t\t\t\tusedstartingPlots.append(plotindex)\n')
    f.write(
        '\t\t\t\tplayer.setStartingPlot(CyMap().plotByIndex(plotindex), 1)\n')
    f.write('\t\t\telse:\n')
    f.write('\t\t\t\tnotinlist.append(i)\n')
    # advc.027: Commented out (now handled upfront)
    #f.write('\t\t# fully random (ignore fixed locations)\n')
    #f.write('\t\telse:\n')
    #f.write('\t\t\tplotindex = findStartingPlot(i)\n')
    #f.write('\t\t\tplayer.setStartingPlot(CyMap().plotByIndex(plotindex), 1)\n')
    f.write('\t\n')
    f.write('\t# handle unassigned civs\n')
    f.write(
        '\topenstartingPlots = list(set(startingPlots) - set(usedstartingPlots))\n'
    )
    f.write(
        '\tshuffle(openstartingPlots) # so that unassigned civs get different position when regenerating a map\n'
    )
    f.write('\tfor i in range(len(notinlist)):\n')
    f.write('\t\tplayer = gc.getPlayer(notinlist[i])\n')
    f.write('\t\t# try to reuse unassigned starting plots\n')
    f.write('\t\tif len(openstartingPlots) > 0:\n')
    f.write('\t\t\tplotindex = openstartingPlots[0]\n')
    f.write('\t\t\topenstartingPlots.remove(plotindex)\n')
    f.write('\t\telse:\n')
    f.write('\t\t\tplotindex = findStartingPlot(notinlist[i])\n')
    f.write('\t\tplayer.setStartingPlot(CyMap().plotByIndex(plotindex), 1)\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def findStartingPlot(argsList):\n')
    f.write('\tplayerID = argsList\n')
    # <advc.027>
    f.write('\tif CyMap().getCustomMapOption(0) == 2:\n')
    f.write('\t\tCyPythonMgr().allowDefaultImpl()\n')
    f.write('\t\treturn None\n')
    # </advc.027>
    f.write('\treturn CvMapGeneratorUtil.findStartingPlot(playerID)\n')
    f.write('\n')
    f.write('def normalizeStartingPlotLocations():\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def normalizeAddRiver():\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def normalizeRemovePeaks():\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def normalizeAddLakes():\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def normalizeRemoveBadFeatures():\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def normalizeRemoveBadTerrain():\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def normalizeAddFoodBonuses():\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def normalizeAddGoodTerrain():\n')
    f.write('\treturn None\n')
    f.write('\n')
    f.write('def normalizeAddExtras():\n')
    f.write('\treturn None\n')
    f.write('\n')
    # advc.savem: AdvCiv doesn't place free AI units in the same tile; doing it only for humans won't really help.
    #f.write('def startHumansOnSameTile():\n')
    #f.write('\treturn True\n')
    f.close()
    # <advc.savem>
    BugUtil.debug("savemap: Done saving map to '%s'", string)
示例#44
0
文件: AutoSave.py 项目: AP-ML/DTM
def init():
	global _saveDir
	_saveDir = BugPath.join(BugPath.getRootDir(), "Saves")
	if not _saveDir:
		BugUtil.error("Could not find Saves directory")
示例#45
0
def writeLog():
    playername = CvUtil.convertToStr(
        gc.getPlayer(gc.getGame().getActivePlayer()).getName())
    szNewFilename = BugPath.getRootDir() + "\\Logs\\" + "OOSLog - %s - " % (
        playername) + "Turn %s" % (gc.getGame().getGameTurn()) + ".txt"
    pFile = open(szNewFilename, "w")

    # Backup current language
    iLanguage = CyGame().getCurrentLanguage()
    # Force english language for logs
    CyGame().setCurrentLanguage(0)

    #
    # Global data
    #
    pFile.write(SEPERATOR)
    pFile.write(SEPERATOR)

    pFile.write("  GLOBALS  \n")

    pFile.write(SEPERATOR)
    pFile.write(SEPERATOR)
    pFile.write("\n\n")

    pFile.write("Next Map Rand Value: %d\n" %
                CyGame().getMapRand().get(10000, "OOS Log"))
    pFile.write("Next Soren Rand Value: %d\n" %
                CyGame().getSorenRand().get(10000, "OOS Log"))

    pFile.write("Total num cities: %d\n" % CyGame().getNumCities())
    pFile.write("Total population: %d\n" % CyGame().getTotalPopulation())
    pFile.write("Total Deals: %d\n" % CyGame().getNumDeals())

    pFile.write("Total owned plots: %d\n" % CyMap().getOwnedPlots())
    pFile.write("Total num areas: %d\n" % CyMap().getNumAreas())

    pFile.write("\n\n")

    #
    # Player data
    #
    iPlayer = 0
    for iPlayer in range(gc.getMAX_PLAYERS()):
        pPlayer = gc.getPlayer(iPlayer)
        if (pPlayer.isEverAlive()):
            pFile.write(SEPERATOR)
            pFile.write(SEPERATOR)

            pFile.write("  PLAYER %d: %s  \n" %
                        (iPlayer, CvUtil.convertToStr(pPlayer.getName())))
            pFile.write(
                "  Civilizations: %s  \n" %
                (CvUtil.convertToStr(pPlayer.getCivilizationDescriptionKey())))

            pFile.write(SEPERATOR)
            pFile.write(SEPERATOR)
            pFile.write("\n\n")

            pFile.write("Basic data:\n")
            pFile.write("-----------\n")
            pFile.write("Player %d Score: %d\n" %
                        (iPlayer, gc.getGame().getPlayerScore(iPlayer)))

            pFile.write("Player %d Population: %d\n" %
                        (iPlayer, pPlayer.getTotalPopulation()))
            pFile.write("Player %d Total Land: %d\n" %
                        (iPlayer, pPlayer.getTotalLand()))
            pFile.write("Player %d Gold: %d\n" % (iPlayer, pPlayer.getGold()))
            pFile.write("Player %d Assets: %d\n" %
                        (iPlayer, pPlayer.getAssets()))
            pFile.write("Player %d Power: %d\n" %
                        (iPlayer, pPlayer.getPower()))
            pFile.write("Player %d Num Cities: %d\n" %
                        (iPlayer, pPlayer.getNumCities()))
            pFile.write("Player %d Num Units: %d\n" %
                        (iPlayer, pPlayer.getNumUnits()))
            pFile.write("Player %d Num Selection Groups: %d\n" %
                        (iPlayer, pPlayer.getNumSelectionGroups()))
            pFile.write("Player %d Difficulty: %d\n" %
                        (iPlayer, pPlayer.getHandicapType()))

            pFile.write("\n\n")

            pFile.write("Yields:\n")
            pFile.write("-------\n")
            for iYield in range(int(YieldTypes.NUM_YIELD_TYPES)):
                pFile.write("Player %d %s Total Yield: %d\n" %
                            (iPlayer, gc.getYieldInfo(iYield).getDescription(),
                             pPlayer.calculateTotalYield(iYield)))

            pFile.write("\n\n")

            pFile.write("Commerce:\n")
            pFile.write("---------\n")
            for iCommerce in range(int(CommerceTypes.NUM_COMMERCE_TYPES)):
                pFile.write(
                    "Player %d %s Total Commerce: %d\n" %
                    (iPlayer, gc.getCommerceInfo(iCommerce).getDescription(),
                     pPlayer.getCommerceRate(CommerceTypes(iCommerce))))

            pFile.write("\n\n")

            pFile.write("Bonus Info:\n")
            pFile.write("-----------\n")
            for iBonus in range(gc.getNumBonusInfos()):
                pFile.write("Player %d, %s, Number Available: %d\n" %
                            (iPlayer, gc.getBonusInfo(iBonus).getDescription(),
                             pPlayer.getNumAvailableBonuses(iBonus)))
                pFile.write("Player %d, %s, Import: %d\n" %
                            (iPlayer, gc.getBonusInfo(iBonus).getDescription(),
                             pPlayer.getBonusImport(iBonus)))
                pFile.write("Player %d, %s, Export: %d\n" %
                            (iPlayer, gc.getBonusInfo(iBonus).getDescription(),
                             pPlayer.getBonusExport(iBonus)))
                pFile.write("\n")

            pFile.write("\n\n")

            pFile.write("Improvement Info:\n")
            pFile.write("-----------------\n")
            for iImprovement in range(gc.getNumImprovementInfos()):
                pFile.write(
                    "Player %d, %s, Improvement count: %d\n" %
                    (iPlayer,
                     CvUtil.convertToStr(
                         gc.getImprovementInfo(iImprovement).getDescription()),
                     pPlayer.getImprovementCount(iImprovement)))

            pFile.write("\n\n")

            pFile.write("Building Class Info:\n")
            pFile.write("--------------------\n")
            for iBuildingClass in range(gc.getNumBuildingClassInfos()):
                pFile.write(
                    "Player %d, %s, Building class count plus building: %d\n" %
                    (iPlayer,
                     CvUtil.convertToStr(
                         gc.getBuildingClassInfo(
                             iBuildingClass).getDescription()),
                     pPlayer.getBuildingClassCountPlusMaking(iBuildingClass)))

            pFile.write("\n\n")

            pFile.write("Unit Class Info:\n")
            pFile.write("--------------------\n")
            for iUnitClass in range(gc.getNumUnitClassInfos()):
                pFile.write(
                    "Player %d, %s, Unit class count plus training: %d\n" %
                    (iPlayer,
                     CvUtil.convertToStr(
                         gc.getUnitClassInfo(iUnitClass).getDescription()),
                     pPlayer.getUnitClassCountPlusMaking(iUnitClass)))

            pFile.write("\n\n")

            pFile.write("UnitAI Types Info:\n")
            pFile.write("------------------\n")
            for iUnitAIType in range(int(UnitAITypes.NUM_UNITAI_TYPES)):
                pFile.write(
                    "Player %d, %s, Unit AI Type count: %d\n" %
                    (iPlayer, gc.getUnitAIInfo(iUnitAIType).getDescription(),
                     pPlayer.AI_totalUnitAIs(UnitAITypes(iUnitAIType))))

            pFile.write("\n\n")

            pFile.write("City Info:\n")
            pFile.write("----------\n")
            iNumCities = pPlayer.getNumCities()

            if (iNumCities == 0):
                pFile.write("No Cities")
            else:
                pLoopCityTuple = pPlayer.firstCity(False)
                while (pLoopCityTuple[0] != None):
                    pCity = pLoopCityTuple[0]
                    #pFile.write("Player %d, City ID: %d, %s, Plot Radius: %d\n" % (iPlayer, pCity.getID(), CvUtil.convertToStr(pCity.getName()), pCity.getPlotRadius() ))

                    pFile.write("X: %d, Y: %d\n" %
                                (pCity.getX(), pCity.getY()))
                    pFile.write("Founded: %d\n" % pCity.getGameTurnFounded())
                    pFile.write("Population: %d\n" % pCity.getPopulation())
                    pFile.write("Buildings: %d\n" % pCity.getNumBuildings())
                    pFile.write("Improved Plots: %d\n" %
                                pCity.countNumImprovedPlots())
                    pFile.write("Producing: %s\n" % pCity.getProductionName())
                    pFile.write(
                        "%d Tiles Worked, %d Specialists, %d Great People\n" %
                        (pCity.getWorkingPopulation(),
                         pCity.getSpecialistPopulation(),
                         pCity.getNumGreatPeople()))

                    pLoopCityTuple = pPlayer.nextCity(pLoopCityTuple[1], False)
                    pFile.write("\n")

            pFile.write("\n\n")

            pFile.write("Unit Info:\n")
            pFile.write("----------\n")
            iNumUnits = pPlayer.getNumUnits()

            if (iNumUnits == 0):
                pFile.write("No Units")
            else:
                pLoopUnitTuple = pPlayer.firstUnit(False)
                while (pLoopUnitTuple[0] != None):
                    pUnit = pLoopUnitTuple[0]
                    pFile.write("Player %d, Unit ID: %d, %s\n" %
                                (iPlayer, pUnit.getID(),
                                 CvUtil.convertToStr(pUnit.getName())))
                    pFile.write("X: %d, Y: %d\n" %
                                (pUnit.getX(), pUnit.getY()))
                    pFile.write("Damage: %d\n" % pUnit.getDamage())
                    #pFile.write("Experience: %d\n" % pUnit.getExperienceTimes100() )
                    pFile.write("Experience: %d\n" % pUnit.getExperience())
                    pFile.write("Level: %d\n" % pUnit.getLevel())
                    pFile.write("Promotions:\n")
                    for j in range(gc.getNumPromotionInfos()):
                        if (pUnit.isHasPromotion(j)):
                            pFile.write("%s\n" % (CvUtil.convertToStr(
                                gc.getPromotionInfo(j).getDescription())))

                    pLoopUnitTuple = pPlayer.nextUnit(pLoopUnitTuple[1], False)
                    pFile.write("\n")

            # Space at end of player's info
            pFile.write("\n\n")

    # Restore current language
    CyGame().setCurrentLanguage(iLanguage)

    # Close file

    pFile.close()
示例#46
0
def getUserDirStr():
    r = BugPath.getUserDir()
    if r == None:
        return ""
    return str(r)