def onLoad(argsList):
	'Called when a file is loaded'
	import pickle	
	import CvEventInterface
	loadDataStr=argsList[0]	
	if len(loadDataStr):
		CvEventInterface.onEvent( ('OnLoad',pickle.loads(loadDataStr),0,0,0,0,0 ) )	
def onLoad(argsList):
	'Called when a file is loaded'
	import pickle	
	import CvEventInterface
	loadDataStr=argsList[0]	
	if len(loadDataStr):
		CvEventInterface.onEvent( ('OnLoad',pickle.loads(loadDataStr),0,0,0,0,0 ) )	
def onLoad(argsList):
    import CvEventInterface
    loadDataStr = argsList[0]
    if loadDataStr:
        import cPickle
        CvEventInterface.onEvent(
            ('OnLoad', cPickle.loads(loadDataStr), 0, 0, 0, 0, 0))
def onLoad(argsList):
	import CvScreensInterface
	CvScreensInterface.mainInterface.bSetStartZoom = True
	import CvEventInterface
	loadDataStr = argsList[0]
	if loadDataStr:
		import cPickle
		CvEventInterface.onEvent(('OnLoad', cPickle.loads(loadDataStr), 0, 0, 0, 0, 0))
Exemple #5
0
def doHotSeatCheck(args):
	"""
	Called during EndPlayerTurn, fires SwitchHotSeatPlayer event during a hot seat
	game when the active player's turn ends.
	"""
	iGameTurn, ePlayer = args
	game = gc.getGame()
	if game.isHotSeat() and ePlayer == game.getActivePlayer():
		CvEventInterface.getEventManager().fireEvent("SwitchHotSeatPlayer", ePlayer)
Exemple #6
0
def doHotSeatCheck(args):
	"""
	Called during EndPlayerTurn, fires SwitchHotSeatPlayer event during a hot seat
	game when the active player's turn ends.
	"""
	iGameTurn, ePlayer = args
	game = gc.getGame()
	if game.isHotSeat() and ePlayer == game.getActivePlayer():
		CvEventInterface.getEventManager().fireEvent("SwitchHotSeatPlayer", ePlayer)
Exemple #7
0
def handleResolutionDropdownInput(argsList):
    "Handles Resolution Dropdown Box input"
    iValue, szName = argsList

    UserProfile.setResolution(iValue)

    # BUG - BugEventManager - start
    CvEventInterface.getEventManager().fireEvent("ResolutionChanged", iValue)
    # BUG - BugEventManager - end

    return 1
Exemple #8
0
def doHotSeatCheck(args):
    """
	Called during EndPlayerTurn, fires SwitchHotSeatPlayer event during a hot seat
	game when the active player's turn ends.
	"""
    iGameTurn, ePlayer = args
    game = gc.getGame()
    if game.isHotSeat() and ePlayer == game.getActivePlayer():
        import CvEventInterface  # advc.009b: Avoid mutual import (not sure if that was a problem here)
        CvEventInterface.getEventManager().fireEvent("SwitchHotSeatPlayer",
                                                     ePlayer)
Exemple #9
0
 def handle(self, element, keys, module, function, dll):
     dll = BugDll.decode(dll)
     if self.isDllOkay(element, dll):
         CvEventInterface.getEventManager().addShortcutHandler(
             keys,
             BugUtil.getFunction(module, function, *element.args,
                                 **element.kwargs))
     else:
         BugUtil.info(
             "InputUtil - ignoring <%s> %s, requires dll version %s",
             element.tag, keys, self.resolveDll(element, dll))
Exemple #10
0
 def handle(self, element, type, module, function, dll):
     dll = BugDll.decode(dll)
     if self.isDllOkay(element, dll):
         CvEventInterface.getEventManager().addEventHandler(
             type,
             BugUtil.getFunction(module, function, True, *element.args,
                                 **element.kwargs))
     else:
         BugUtil.info(
             "BugConfig - ignoring <%s> %s, requires dll version %s",
             element.tag, type, self.resolveDll(element, dll))
 def handle(self, element, type, module, function, dll):
     dll = BugDll.decode(dll)
     if self.isDllOkay(element, dll):
         CvEventInterface.getEventManager().addEventHandler(
             type, BugUtil.getFunction(module, function, True, *element.args, **element.kwargs)
         )
     else:
         BugUtil.info(
             "BugConfig - ignoring <%s> %s, requires dll version %s",
             element.tag,
             type,
             self.resolveDll(element, dll),
         )
def handleLanguagesDropdownBoxInput(argsList):
	# Handles Languages Dropdown Box input
	iValue = argsList[0]

	CyGame().setCurrentLanguage(iValue)

	popup = CyPopup(-1, EventContextTypes.NO_EVENTCONTEXT, True)
	popup.setBodyString(CyTranslator().getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()), 1<<0)
	popup.launch(True, PopupStates.POPUPSTATE_IMMEDIATE)

	import CvEventInterface
	CvEventInterface.getEventManager().fireEvent("LanguageChanged", iValue)
	return 1
def refresh():
	getOptionsScreen().refreshScreen()
	global g_iResChange
	if g_iResChange:
		import ScreenResolution as SR
		szRes = UsrPrfl.getResolutionString(UsrPrfl.getResolution())
		szRes = szRes.split(" x ")
		SR.x = int(szRes[0])
		SR.y = int(szRes[1])
		SR.calibrate()

		import CvEventInterface
		CvEventInterface.getEventManager().fireEvent("ResolutionChanged", g_iResChange - 100)
		g_iResChange = 0
Exemple #14
0
def preGameStart():
    # BUG - core
    import CvEventInterface
    CvEventInterface.getEventManager().fireEvent("PreGameStart")
    # continue
    import CvScreensInterface
    if not CyGame().isPitbossHost():
        # Preload the tech chooser..., only do this release builds, in debug build we may not be raising the tech chooser
        if not CyGlobalContext().isDebugBuild():
            NiTextOut("Preloading tech chooser")
            CvScreensInterface.showTechChooser()
            CvScreensInterface.techChooser.hideScreen()

    NiTextOut("Loading main interface...")
    CvScreensInterface.showMainInterface()
	def calculateScore(self,argsList):
		ePlayer = argsList[0]
		bFinal = argsList[1]
		bVictory = argsList[2]
		
		FinalFrontier = CvEventInterface.getEventManager().FinalFrontier
		iMaxPopulation = FinalFrontier.iMaxPopulation
		
		iPopulationScore = CvUtil.getScoreComponent(gc.getPlayer(ePlayer).getPopScore(), gc.getGame().getInitPopulation(), iMaxPopulation, gc.getDefineINT("SCORE_POPULATION_FACTOR"), True, bFinal, bVictory)
		printd("Pop Score Stuff")
		printd(gc.getPlayer(ePlayer).getPopScore())
		printd(gc.getGame().getInitPopulation())
		printd(iMaxPopulation)
		printd(iPopulationScore)
		iPlayerLandScore = gc.getPlayer(ePlayer).getTotalLand()
		iLandScore = CvUtil.getScoreComponent(iPlayerLandScore , gc.getGame().getInitLand(), gc.getGame().getMaxLand(), gc.getDefineINT("SCORE_LAND_FACTOR"), True, bFinal, bVictory)
		printd("Land Score Stuff")
		printd(iPlayerLandScore)
		printd(gc.getGame().getInitLand())
		printd(gc.getGame().getMaxLand())
		printd(iLandScore)
		iTechScore = CvUtil.getScoreComponent(gc.getPlayer(ePlayer).getTechScore(), gc.getGame().getInitTech(), gc.getGame().getMaxTech(), gc.getDefineINT("SCORE_TECH_FACTOR"), True, bFinal, bVictory)
		iWondersScore = CvUtil.getScoreComponent(gc.getPlayer(ePlayer).getWondersScore(), gc.getGame().getInitWonders(), gc.getGame().getMaxWonders(), gc.getDefineINT("SCORE_WONDER_FACTOR"), False, bFinal, bVictory)
		
		iTotalScore = int(iLandScore + iWondersScore + iTechScore + iPopulationScore)
		
		printd("Player %d Score: %d    Pop: %d    Land: %d    Tech: %d    Wonders:    %d" %(ePlayer, iTotalScore, iPopulationScore, iLandScore, iTechScore, iWondersScore))
		
		return iTotalScore
Exemple #16
0
def handleLanguagesDropdownBoxInput(argsList):
    "Handles Languages Dropdown Box input"
    iValue, szName = argsList

    CyGame().setCurrentLanguage(iValue)

    popup = PyPopup.PyPopup()
    popup.setHeaderString("")
    popup.setBodyString(localText.getText("TXT_KEY_FEAT_ACCOMPLISHED_OK", ()))
    popup.launch()

    # BUG - BugEventManager - start
    CvEventInterface.getEventManager().fireEvent("LanguageChanged", iValue)
    # BUG - BugEventManager - end

    return 1
Exemple #17
0
	def doHolyCity(self):
		if RevDCMOpt.isOC_LIMITED_RELIGIONS():
			#This algorithm has to deal with a PLETHORA of possibilities like multiple religions 
			#being founded by multiple players on the same turn.
			iPlayerQueue = []
			iSlotQueue = []
			# Sort through all religions and players and distinguish unique religions that want founding
			for iSlot in range(gc.getNumReligionInfos()):
				for iPlayer in range(gc.getMAX_PLAYERS()):
					PyPlayer = gc.getPlayer(iPlayer)
					if PyPlayer.isAlive():
						if not CvUtil.OwnsHolyCity(iPlayer):
							if gc.getTeam(PyPlayer.getTeam()).isHasTech(gc.getReligionInfo(iSlot).getTechPrereq()):
								if not CyGame().isReligionSlotTaken(iSlot):
									if not iSlot in iSlotQueue:
										iPlayerQueue.append(iPlayer)
										iSlotQueue.append(iSlot)
			if CyGame().isOption(GameOptionTypes.GAMEOPTION_PICK_RELIGION) or RevDCMOpt.isCHOOSE_RELIGION():
				#Throw the list to the popup manager that has to delegate multiple popups for each new religion
				pickReligion = PickReligionPopup(CvEventInterface.getEventManager())
				pickReligion.foundPickableReligions(iPlayerQueue, iSlotQueue)
			else:
				#Let the sdk handle the list as it normally would anyway
				for i in range(len(iPlayerQueue)):
					gc.getPlayer(iPlayerQueue[i]).foundReligion(iSlotQueue[i], iSlotQueue[i], True)
			return True
		if RevDCMOpt.isCHOOSE_RELIGION():
			#Stop the sdk founding a religion because all possible cases in vanilla BTS
			#have already been handled in doHolyCityTech.
			return true
		#false means allow the SDK to found a religion if needed
		return false
	def doHolyCity(self):
		if RevDCMOpt.isOC_LIMITED_RELIGIONS():
			#This algorithm has to deal with a PLETHORA of possibilities like multiple religions
			#being founded by multiple players on the same turn.
			MAX_PC_PLAYERS = gc.getMAX_PC_PLAYERS()
			iPlayerQueue = []
			iSlotQueue = []
			# Sort through all religions and players and distinguish unique religions that want founding
			for iReligion in range(gc.getNumReligionInfos()):
				if CyGame().isReligionSlotTaken(iReligion) or iReligion in iSlotQueue:
					continue
				for iPlayer in range(MAX_PC_PLAYERS):
					CyPlayer = gc.getPlayer(iPlayer)
					if CyPlayer.isAlive() and not CyPlayer.hasHolyCity(iReligion):
						if gc.getTeam(CyPlayer.getTeam()).isHasTech(gc.getReligionInfo(iReligion).getTechPrereq()):
							iPlayerQueue.append(iPlayer)
							iSlotQueue.append(iReligion)
			if CyGame().isOption(GameOptionTypes.GAMEOPTION_PICK_RELIGION) or RevDCMOpt.isCHOOSE_RELIGION():
				#Throw the list to the popup manager that has to delegate multiple popups for each new religion
				pickReligion = PickReligionPopup(CvEventInterface.getEventManager())
				pickReligion.foundPickableReligions(iPlayerQueue, iSlotQueue)
			else:
				#Let the sdk handle the list as it normally would anyway
				for i in range(len(iPlayerQueue)):
					gc.getPlayer(iPlayerQueue[i]).foundReligion(iSlotQueue[i], iSlotQueue[i], True)
			return True
		if RevDCMOpt.isCHOOSE_RELIGION():
			#Stop the sdk founding a religion because all possible cases in vanilla BTS
			#have already been handled in doHolyCityTech.
			return True
		#False means allow the SDK to found a religion if needed
		return False
	def AI_chooseProduction(self,argsList):
		pCity = argsList[0]
		
		FinalFrontier = CvEventInterface.getEventManager().FinalFrontier
		
		bOverride = FinalFrontier.getAI().doCityAIProduction(pCity)
		
		return bOverride
def onSave():
	'Here is your chance to save data.  This function should return a string'
	import CvWBDesc
	import pickle	
	import CvEventInterface
	# if the tutorial is active, it will save out the Shown Messages list
	saveDataStr = pickle.dumps( CvEventInterface.onEvent( ('OnSave',0,0,0,0,0 ) ) )
	return saveDataStr
	def getUnitCostMod(self, argsList):
		iPlayer, iUnit = argsList
		iCostMod = -1 # Any value > 0 will be used
		
		FinalFrontier = CvEventInterface.getEventManager().FinalFrontier
		iCostMod = FinalFrontier.getUnitCostMod(iPlayer, iUnit)
		
		return iCostMod
    def AI_chooseProduction(self, argsList):
        pCity = argsList[0]

        FinalFrontier = CvEventInterface.getEventManager().FinalFrontier

        bOverride = FinalFrontier.getAI().doCityAIProduction(pCity)

        return bOverride
def onSave():
	'Here is your chance to save data.  This function should return a string'
	import CvWBDesc
	import pickle	
	import CvEventInterface
	# if the tutorial is active, it will save out the Shown Messages list
	saveDataStr = pickle.dumps( CvEventInterface.onEvent( ('OnSave',0,0,0,0,0 ) ) )
	return saveDataStr
	def getBuildingCostMod(self, argsList):
		iPlayer, iCityID, iBuilding = argsList
		iCostMod = -1 # Any value > 0 will be used
		
		FinalFrontier = CvEventInterface.getEventManager().FinalFrontier
		iCostMod = FinalFrontier.getBuildingCostMod(iPlayer, iCityID, iBuilding)
		
		return iCostMod
 def __init__(self, WB):
     self.WB = WB
     self.iTable_Y = 110
     self.lAttitude = [
         "COLOR_RED", "COLOR_MAGENTA", "", "COLOR_CYAN", "COLOR_GREEN"
     ]
     import CvEventInterface
     self.eventManager = CvEventInterface.getEventManager()
Exemple #26
0
def onSave():
    import CvWBDesc
    import cPickle
    import CvEventInterface
    # if the tutorial is active, it will save out the Shown Messages list
    saveDataStr = cPickle.dumps(
        CvEventInterface.onEvent(('OnSave', 0, 0, 0, 0, 0)))
    return saveDataStr
    def getUnitCostMod(self, argsList):
        iPlayer, iUnit = argsList
        iCostMod = -1  # Any value > 0 will be used

        FinalFrontier = CvEventInterface.getEventManager().FinalFrontier
        iCostMod = FinalFrontier.getUnitCostMod(iPlayer, iUnit)

        return iCostMod
    def getBuildingCostMod(self, argsList):
        iPlayer, iCityID, iBuilding = argsList
        iCostMod = -1  # Any value > 0 will be used

        FinalFrontier = CvEventInterface.getEventManager().FinalFrontier
        iCostMod = FinalFrontier.getBuildingCostMod(iPlayer, iCityID,
                                                    iBuilding)

        return iCostMod
Exemple #29
0
 def handle(self, element, module, clazz, dll):
     dll = BugDll.decode(dll)
     if self.isDllOkay(element, dll):
         BugUtil.callFunction(module, clazz,
                              CvEventInterface.getEventManager(),
                              *element.args, **element.kwargs)
     else:
         BugUtil.info(
             "BugConfig - ignoring <%s> from %s.%s, requires dll version %s",
             element.tag, module, clazz, self.resolveDll(element, dll))
 def handle(self, element, module, clazz, dll):
     dll = BugDll.decode(dll)
     if self.isDllOkay(element, dll):
         BugUtil.callFunction(module, clazz, CvEventInterface.getEventManager(), *element.args, **element.kwargs)
     else:
         BugUtil.info(
             "BugConfig - ignoring <%s> from %s.%s, requires dll version %s",
             element.tag,
             module,
             clazz,
             self.resolveDll(element, dll),
         )
def preGameStart():
	import CvScreensInterface
	
# BUG - core - start
	import CvEventInterface
	CvEventInterface.getEventManager().fireEvent("PreGameStart")
# BUG - core - end
	
	if not CyGame().isPitbossHost():
		NiTextOut("Initializing font icons")
		# Load dynamic font icons into the icon map
		CvUtil.initDynamicFontIcons()

#	if not CyGame().isPitbossHost():
#		# Preload the tech chooser..., only do this release builds, in debug build we may not be raising the tech chooser
#		if (not gc.isDebugBuild()):
#			NiTextOut("Preloading tech chooser")
#			CvScreensInterface.showTechChooser(argsList)
#			CvScreensInterface.techChooser.hideScreen()
		
	NiTextOut("Loading main interface...")
	CvScreensInterface.showMainInterface()	
def onKbdEvent(argsList):
	"""
	Event handler for keyboard events, checks keys against the hotkey list and opens the screen or closes it on match
	"""
	eventType, key, mouseX, mouseY, plotX, plotY = argsList
	eventManager = CvEventInterface.getEventManager()
	if ( eventType == eventManager.EventKeyDown ):
		stroke = InputUtil.Keystroke(key, eventManager.bAlt, eventManager.bCtrl, eventManager.bShift)
		if stroke in keys:
			if overlayScreen.isOpen():
				hideOverlayScreen()
			else:
				showOverlayScreen()
			return 1
	return 0
	def AI_unitUpdate(self,argsList):
		pUnit = argsList[0]
		
		FinalFrontier = CvEventInterface.getEventManager().FinalFrontier
		
		bOverride = false
		
		# Only do it for actual AI units, not automated human ones
		pPlayer = gc.getPlayer(pUnit.getOwner())
		if (not pPlayer.isHuman()) and (not pPlayer.isBarbarian()) and pPlayer.isAlive() and (not pUnit.isNone()) and (not pUnit.isDead()):
			iConstructShip = gc.getInfoTypeForString(gc.getDefineSTRING("CONSTRUCT_SHIP"))
			if (pUnit.getUnitClassType() == iConstructShip):
				bOverride = FinalFrontier.getAI().doConstructionShipAI(pUnit)
		
		return bOverride
Exemple #34
0
	def __init__(self, game=None, attrs=None):
		if game is None:
			game = BugCore.game
		self.game = game
		self.eventManager = CvEventInterface.getEventManager()
		self.options = BugOptions.getOptions()
		self.optionsScreen = CvScreensInterface.getBugOptionsScreen()
		
		self.attrs = attrs
		self.mod = None
		self.iniFile = None
		self.section = None
		self.option = None
		self.screen = None
		self.symbol = None
    def calculateScore(self, argsList):
        ePlayer = argsList[0]
        bFinal = argsList[1]
        bVictory = argsList[2]

        FinalFrontier = CvEventInterface.getEventManager().FinalFrontier
        iMaxPopulation = FinalFrontier.iMaxPopulation

        iPopulationScore = CvUtil.getScoreComponent(
            gc.getPlayer(ePlayer).getPopScore(),
            gc.getGame().getInitPopulation(), iMaxPopulation,
            gc.getDefineINT("SCORE_POPULATION_FACTOR"), True, bFinal, bVictory)
        printd("Pop Score Stuff")
        printd(gc.getPlayer(ePlayer).getPopScore())
        printd(gc.getGame().getInitPopulation())
        printd(iMaxPopulation)
        printd(iPopulationScore)
        iPlayerLandScore = gc.getPlayer(ePlayer).getTotalLand()
        iLandScore = CvUtil.getScoreComponent(
            iPlayerLandScore,
            gc.getGame().getInitLand(),
            gc.getGame().getMaxLand(), gc.getDefineINT("SCORE_LAND_FACTOR"),
            True, bFinal, bVictory)
        printd("Land Score Stuff")
        printd(iPlayerLandScore)
        printd(gc.getGame().getInitLand())
        printd(gc.getGame().getMaxLand())
        printd(iLandScore)
        iTechScore = CvUtil.getScoreComponent(
            gc.getPlayer(ePlayer).getTechScore(),
            gc.getGame().getInitTech(),
            gc.getGame().getMaxTech(), gc.getDefineINT("SCORE_TECH_FACTOR"),
            True, bFinal, bVictory)
        iWondersScore = CvUtil.getScoreComponent(
            gc.getPlayer(ePlayer).getWondersScore(),
            gc.getGame().getInitWonders(),
            gc.getGame().getMaxWonders(),
            gc.getDefineINT("SCORE_WONDER_FACTOR"), False, bFinal, bVictory)

        iTotalScore = int(iLandScore + iWondersScore + iTechScore +
                          iPopulationScore)

        printd(
            "Player %d Score: %d    Pop: %d    Land: %d    Tech: %d    Wonders:    %d"
            % (ePlayer, iTotalScore, iPopulationScore, iLandScore, iTechScore,
               iWondersScore))

        return iTotalScore
Exemple #36
0
    def request(self, webserver):
        gamedata = createGameData()
        newState = not webserver.compareGamedata(gamedata)

        # Check if CvGame::doTurn is currently running.
        # Try ness for mods without the DLL changes for bGameTurnProcessing
        inconsistentState = False
        try:
            inconsistentState = CvEventInterface.getEventManager(
            ).bGameTurnProcessing
        except AttributeError:
            for iPlayer in range(gc.getMAX_CIV_PLAYERS()):
                if gc.getPlayer(iPlayer).isTurnActive():
                    inconsistentState = True
                    break
        except:
            pass

        # PB.consoleOut("Webupload request %i" % (self.requestCounter,))
        self.requestCounter += 1

        if (not inconsistentState
                and (newState or not self.reduceTraffic or
                     self.requestCounter % self.reduceFactor == 0)
           ):
            params = urllib.urlencode(
                {'action': 'update', 'id': self.gameId,
                 'pwHash': self.pwHash, 'info':
                 simplejson.dumps(
                     {'return': 'ok', 'info': gamedata})})
        else:
            # Minimal alive message.
            gamedataMinimal = {"turnTimer": gamedata.get("turnTimer")}
            if gamedata["turnTimer"] == 1:
                gamedataMinimal["turnTimerValue"] = gamedata.get(
                    "turnTimerValue")
            params = urllib.urlencode(
                {'action': 'update', 'id': self.gameId, 'pwHash': self.pwHash, 'info':
                 simplejson.dumps(
                     {'return': 'ok', 'info': gamedataMinimal})})

        try:
            # f = urllib.urlopen("%s?%s" % (url,params) ) # GET method
            urllib.urlopen(self.url, params)  # POST method

        except:
            # PB.consoleOut("Webupload failed")
            pass
    def AI_unitUpdate(self, argsList):
        pUnit = argsList[0]

        FinalFrontier = CvEventInterface.getEventManager().FinalFrontier

        bOverride = false

        # Only do it for actual AI units, not automated human ones
        pPlayer = gc.getPlayer(pUnit.getOwner())
        if (not pPlayer.isHuman()) and (
                not pPlayer.isBarbarian()) and pPlayer.isAlive() and (
                    not pUnit.isNone()) and (not pUnit.isDead()):
            iConstructShip = gc.getInfoTypeForString(
                gc.getDefineSTRING("CONSTRUCT_SHIP"))
            if (pUnit.getUnitClassType() == iConstructShip):
                bOverride = FinalFrontier.getAI().doConstructionShipAI(pUnit)

        return bOverride
Exemple #38
0
	def canPickPlot(self, argsList):
		pPlot = argsList[0]
		pGodsOfOld=CvEventInterface.getEventManager()
		if GodsOfOld.iPushButton == 2:
			if pPlot.isCoastalLand():
				return true
			else:
				return false
		if GodsOfOld.iPushButton == 3:
			if pPlot.isCity():
				iCoords = ( pPlot.getX(), pPlot.getY() )
				if pGodsOfOld.lPlagueCities.count( iCoords ) == 0:
					return true
				else:
					return false
			else:
				return false				
		return true
Exemple #39
0
 def canPickPlot(self, argsList):
     pPlot = argsList[0]
     pGodsOfOld = CvEventInterface.getEventManager()
     if GodsOfOld.iPushButton == 2:
         if pPlot.isCoastalLand():
             return true
         else:
             return false
     if GodsOfOld.iPushButton == 3:
         if pPlot.isCity():
             iCoords = (pPlot.getX(), pPlot.getY())
             if pGodsOfOld.lPlagueCities.count(iCoords) == 0:
                 return true
             else:
                 return false
         else:
             return false
     return true
Exemple #40
0
	def doHolyCityTech(self,argsList):
		eTeam = argsList[0]
		ePlayer = argsList[1]
		eTech = argsList[2]
		bFirst = argsList[3]
		if RevDCMOpt.isOC_LIMITED_RELIGIONS():
			#In limited religion, the assignment of religion cannot be done here
			#because there still could be more unknowable calls to this function
			#that affect the allocation of religions.
			return true
		if RevDCMOpt.isCHOOSE_RELIGION():
			pickReligion = PickReligionPopup(CvEventInterface.getEventManager())
			for iSlot in range(gc.getNumReligionInfos()):	
				prereq = gc.getReligionInfo(iSlot).getTechPrereq()
				if eTech == prereq and bFirst:
					pickReligion.initiatePopup(ePlayer, iSlot)
					break
			return true
		#false means allow the SDK to found a religion if needed
		return false
	def doHolyCityTech(self,argsList):
		eTeam = argsList[0]
		ePlayer = argsList[1]
		eTech = argsList[2]
		bFirst = argsList[3]
		if RevDCMOpt.isOC_LIMITED_RELIGIONS():
			#In limited religion, the assignment of religion cannot be done here
			#because there still could be more unknowable calls to this function
			#that affect the allocation of religions.
			return True
		if RevDCMOpt.isCHOOSE_RELIGION():
			pickReligion = PickReligionPopup(CvEventInterface.getEventManager())
			for iSlot in range(gc.getNumReligionInfos()):
				prereq = gc.getReligionInfo(iSlot).getTechPrereq()
				if eTech == prereq and bFirst:
					pickReligion.initiatePopup(ePlayer, iSlot)
					break
			return True
		#False means allow the SDK to found a religion if needed
		return False
	def handle(self, element, keys, module, function, dll):
		dll = BugDll.decode(dll)
		if self.isDllOkay(element, dll):
			CvEventInterface.getEventManager().addShortcutHandler(keys, BugUtil.getFunction(module, function, *element.args, **element.kwargs))
		else:
			BugUtil.info("InputUtil - ignoring <%s> %s, requires dll version %s", element.tag, keys, self.resolveDll(element, dll))
Exemple #43
0
def WorldBuilderAllPlotsCB():
    CvEventInterface.beginEvent(CvUtil.EventWBAllPlotsPopup)
Exemple #44
0
def bShift():
	return CvEventInterface.getEventManager().bShift
def WorldBuilderAllPlotsCB():
	CvEventInterface.beginEvent(CvUtil.EventWBAllPlotsPopup)
Exemple #46
0
    def request(self, webserver):
        gamedata = createGameData()
        newState = not webserver.compareGamedata(gamedata)

        # Check if CvGame::doTurn is currently running.
        # Try is necessary for mods without 'CvEventManager.bGameTurnProcessing'
        inconsistentState = False
        try:
            inconsistentState = CvEventInterface.getEventManager(
            ).bGameTurnProcessing
        except AttributeError:
            for iPlayer in range(gc.getMAX_CIV_PLAYERS()):
                if gc.getPlayer(iPlayer).isTurnActive():
                    break

                # no Player active => game turn processing
                inconsistentState = True
        except:
            pass

        # PB.consoleOut("Webupload request %i" % (self.requestCounter,))
        self.requestCounter += 1

        try:
            if (not inconsistentState
                    and (newState or not self.reduceTraffic
                         or self.requestCounter % self.reduceFactor == 0)):
                params = urllib.urlencode({
                    'action':
                    'update',
                    'id':
                    self.gameId,
                    'pwHash':
                    self.pwHash,
                    'info':
                    simplejson.dumps({
                        'return': 'ok',
                        'info': gamedata
                    })
                })
            else:
                # Minimal alive message.
                gamedataMinimal = {"turnTimer": gamedata.get("turnTimer")}
                if gamedata["turnTimer"] == 1:
                    gamedataMinimal["turnTimerValue"] = gamedata.get(
                        "turnTimerValue")
                params = urllib.urlencode({
                    'action':
                    'update',
                    'id':
                    self.gameId,
                    'pwHash':
                    self.pwHash,
                    'info':
                    simplejson.dumps({
                        'return': 'ok',
                        'info': gamedataMinimal
                    })
                })

        except Exception, e:
            PB.consoleOut("Webupload failed (1). Error: '%s'" % (e, ))
            print("Webupload failed")
            # print(gamedata)
            return
Exemple #47
0
def handleLanguagesDropdownBoxInput(argsList):
	value, name = argsList
	CvEventInterface.getEventManager().fireEvent("LanguageChanged", value)
	return 1
Exemple #48
0
def bAlt():
	return CvEventInterface.getEventManager().bAlt
Exemple #49
0
 def handle(self, element, type, module, function, dll):
     CvEventInterface.getEventManager().addEventHandler(
         type,
         BugUtil.getFunction(module, function, True, *element.args,
                             **element.kwargs))
Exemple #50
0
 def handle(self, element, module, clazz, dll):
     BugUtil.callFunction(module, clazz, CvEventInterface.getEventManager(),
                          *element.args, **element.kwargs)
Exemple #51
0
def handleResolutionDropdownInput(argsList):
	value, name = argsList
	CvEventInterface.getEventManager().fireEvent("ResolutionChanged", value)
	return 1
	def getCityFoundValue(self, argsList):
		iPlayer, iPlotX, iPlotY = argsList
		iFoundValue = -1 # Any value besides -1 will be used
		
		pPlot = CyMap().plot(iPlotX, iPlotY)
		iFeatureIDSolarSystem = gc.getInfoTypeForString('FEATURE_SOLAR_SYSTEM')
		
		if (pPlot.getFeatureType() == iFeatureIDSolarSystem and not pPlot.isCity()):
			
			printd("Determing Found Value for Plot at %d, %d" %(iPlotX, iPlotY))
			
			# CP - Adjust base value based on path distance from capital (not straight line distance)
			pCapCity = gc.getPlayer(iPlayer).getCapitalCity()
			if pCapCity and not pCapCity.isNone() :
				iDistance = CyMap().calculatePathDistance(pCapCity.plot(), pPlot)
				if iDistance == -1 : # can't get there from here
					return 0
			else : # no capital city, - would normally mean first city not founded yet, I suppose.
				iDistance = 1
				
			iFoundValue = 10000 / (iDistance + 1) # CP - this provides only a small distance penalty
			
			# Determine System value by planetary composition
			if (CyGame().getElapsedGameTurns() > 0):
				
				#iFoundValue = 0
				
				FinalFrontier = CvEventInterface.getEventManager().FinalFrontier
				pSystem = CvSolarSystem.getSystemAt(iPlotX, iPlotY) #FFPBUG
				
				for iPlanetLoop in range(pSystem.getNumPlanets()):
					pPlanet = pSystem.getPlanetByIndex(iPlanetLoop)
					
					iPlanetValue = 0
					
					# Green Planet
					if (pPlanet.getPlanetType() == CvSolarSystem.iPlanetTypeGreen):
						iPlanetValue = 400
					# Not Green Planet
					else:
						iPlanetValue = 200
						
					# CP - Give some value to planetary resources (God-Emperor, for version 1.6)
					if (pPlanet.isBonus()):
						iPlanetValue += 100 # This may need adjusting
						
						# Two Civ-specific increase to this.
						# The Forge gets -1 food in each system, so extra food is good for them meaning +50 for the resources that give extra food
						# Trade routes are very good for the Red Syndicate, so +50 for each trade route
						iTraitForge = gc.getInfoTypeForString('TRAIT_THE_FORGE')
						iTraitSyndicate = gc.getInfoTypeForString('TRAIT_SYNDICATE')
						pPlayer = gc.getPlayer(iPlayer)
						pBonus = gc.getBonusInfo(pPlanet.getBonusType())
						if (pPlayer.hasTrait(iTraitForge) and pBonus.getHealth() > 0): # all heath providing bonuses increase the planet's food
							iPlanetValue += 50
						elif (pPlayer.hasTrait(iTraitSyndicate) and pBonus.getHappiness() > 0): # all happy providing bonuses' related buildings give at least 1 extra trade route
							pBonusBuilding = gc.getBuildingInfo(FinalFrontier.dBonusBuildings[pPlanet.getBonusType()])
							iPlanetValue += 50 * pBonusBuilding.getTradeRoutes()
					
					# Planet Size
					iPlanetValue *= (pPlanet.getPlanetSize() + 1) + 2 # The +2 is to simply weight things a bit so that large planets aren't THAT much more valuable than small ones
					
					# Can it be used right away?
					if (pPlanet.getOrbitRing() < CvSolarSystem.g_iPlanetRange3):
						iPlanetValue *= 2
					
					printd("Orbit Ring %d iPlanetValue: %d" %(pPlanet.getOrbitRing(), iPlanetValue))
					
					iFoundValue += iPlanetValue
			
		else:
			iFoundValue = 0
		
		return iFoundValue
	def doMeltdown(self,argsList):
		pCity = argsList[0]
		pSystem = CvSolarSystem.getSystemAt(pCity.getX(), pCity.getY())
		iMeltPlanet = -1
		
		# check to see if there is a meltdown
		for iBuilding in range(gc.getNumBuildingInfos()):
			if pCity.getNumBuilding(iBuilding) > 0 :
				iBuildingNukeExRand = gc.getBuildingInfo(iBuilding).getNukeExplosionRand()
				if iBuildingNukeExRand != 0 :
					if CyGame().getSorenRandNum(iBuildingNukeExRand, "FFP: meltdown check in doMeltdown callback") == 0 :
						# a building has had a meltdown, check planets for buildings of this type and pick one
						lPlanets = []
						for iPlanet in range(pSystem.getNumPlanets()):
							pPlanet = pSystem.getPlanetByIndex(iPlanet)
							if pPlanet.isHasBuilding(iBuilding) :
								lPlanets.append(pPlanet)
						
						iMeltPlanet = CyGame().getSorenRandNum(len(lPlanets), "FPP: meltdown planet")
						pMeltPlanet = lPlanets[iMeltPlanet]
						
						# for the sake of simplicity, have it so that no star system will get more than one meltdown in a turn
						break # break out of building loop
		
		if iMeltPlanet == -1 :
			# no meltdown so exit now (always return True to avoid DLL's meltdown processing)
			return True
		
		pPlayer = gc.getPlayer(pCity.getOwner()) # defined now since we don't need it above
		pCityPlot = pCity.plot()
		
		# Meltdown effects (same as nuke effects, but applied to meltdown planet instead of best planet) 
		# 1) set the planet to be disabled
		# 2) remove all buildings from the now dead planet, dealing with capitol if on this planet
		# 3) if thre was a bonus on the planet, remove it from planet and plot
		# 4) chance of specified feature being distributed around system
		# 5) unit damage (possibly killed)
		# 6) population reduction
		
		# 1) disable
		pMeltPlanet.setDisabled(true)
		pMeltPlanet.setPopulation(0)
		
		# 2) remove buildings
		for iBuilding in range(gc.getNumBuildingInfos()):
			if pMeltPlanet.isHasBuilding(iBuilding) and not gc.getBuildingInfo(iBuilding).isNukeImmune():
				bRemove = True
				if (gc.getBuildingInfo(iBuilding).isCapital()):
					if (pPlayer.getNumCities () > 1):
						# The following call moves the capitol building, removing it from this city's data
						# in the DLL (which is why there is no manual setNumRealBuilding in here)
						# and adding it to the new capital city's data in the DLL plus adding it to that system's
						# current build planet to get it into the Python planet data.
						printd("Meltdown: finding new capial system")
						pPlayer.findNewCapital()
					else:
						# This is this civ's only system so we can't move the capitol building to a different one.
						# Try to move it to a different planet instead.
						printd("Meltdown: moving capitol to different planet in same system")
						# Select the planet that is the largest population limit planet
						#  (using production as tie breaker) that is not the planet being wiped out
						bRemove = False
						aiPlanetList = pSystem.getSizeYieldPlanetIndexList(1) # 1 is production, arbitrarily selected
						for iLoopPlanet in range( len(aiPlanetList)):
							pLoopPlanet = pSystem.getPlanetByIndex(aiPlanetList[iLoopPlanet][2])
							if (pLoopPlanet.getOrbitRing() != pMeltPlanet.getOrbitRing()):
								pLoopPlanet.setHasBuilding(iBuilding, true)
								printd("Meltdown: moved Capitol to planet at ring %d" % pLoopPlanet.getOrbitRing())
								bRemove = True
								break

				else:
					pCity.setNumRealBuilding(iBuilding, pCity.getNumRealBuilding(iBuilding)-1)

				if bRemove :
					# The only time this is not the case is when it is the capitol and there is no other
					# planet it can be moved to. You always need a Capitol, so it stays on the dead planet
					pMeltPlanet.setHasBuilding(iBuilding, false)

		# 2.5) unlisted above, but here anyway
		if (pSystem.getBuildingPlanetRing() == pMeltPlanet.getOrbitRing()):
			# This system's current build planet is the planet being wiped out,
			# change it to some other planet, like the new "best" planet.
			# There is an issue if every planet in the current infuence range is dead -
			# in such a case there is no planet that should be having things built on it.
			# With any luck, this will never come up.
			pSystem.setBuildingPlanetRing(pSystem.getPlanetByIndex(CvSolarSystem.getBestPlanetInSystem(pSystem)).getOrbitRing())
					
		# 3) remove bonus
		if (pMeltPlanet.isBonus()): # planet being melted has a bonus, remove it from the planet and the plot
			pMeltPlanet.setBonusType(-1)
			pCityPlot.setBonusType(-1)			
		
		# 4) feature spread
		for iDX in range(-1, 2) :
			for iDY in range (-1, 2) :
				if (iDX != 0) and (iDY != 0) :
					pPlot = plotXY( pCity.getX(), pCity.getY(), iDX, iDY)
					if pPlot and not pPlot.isNone():
						if not pPlot.isImpassable() and (FeatureTypes.NO_FEATURE == pPlot.getFeatureType()) :
							if (CyGame().getSorenRandNum(100, "Meltdown Fallout") < gc.getDefineINT("NUKE_FALLOUT_PROB")) :
								pPlot.setImprovementType(ImprovementTypes.NO_IMPROVEMENT)
								pPlot.setFeatureType(gc.getDefineINT("NUKE_FEATURE"), 0)
							
		# 5) unit damage - only check units on this plot!
		lUnit = []
		for i in range(pCityPlot.getNumUnits()):
			pLoopUnit = pCityPlot.getUnit(i)
			if ( not pLoopUnit.isDead()): #is the unit alive?
				lUnit.append(pLoopUnit) #add unit instance to list

		for pUnit in lUnit :
			if not pUnit.isDead() and not pUnit.isNukeImmune() :
				iNukeDamage = gc.getDefineINT("NUKE_UNIT_DAMAGE_BASE") + CyGame().getSorenRandNum(gc.getDefineINT("NUKE_UNIT_DAMAGE_RAND_1"), "Nuke Damage 1") + CyGame().getSorenRandNum(gc.getDefineINT("NUKE_UNIT_DAMAGE_RAND_2"), "Nuke Damage 2")
				iNukeDamage *= max(0, (pCity.getNukeModifier() + 100))
				iNukeDamage /= 100
				if pUnit.canFight() or (pUnit.airBaseCombatStr() > 0) :
					printd("Meltdown: unit %s damaged for %d" % (pUnit.getName().encode('unicode_escape'), iNukeDamage))
					pUnit.changeDamage(iNukeDamage, PlayerTypes.NO_PLAYER)
				elif iNukeDamage >= gc.getDefineINT("NUKE_NON_COMBAT_DEATH_THRESHOLD") :
					printd("Meltdown: non-combat unit %s killed from damage over threshold" % (pUnit.getName().encode('unicode_escape'),))
					pUnit.kill(false, PlayerTypes.NO_PLAYER)
					
		# 6) population reduction
		iNukedPopulation = (pCity.getPopulation() * (gc.getDefineINT("NUKE_POPULATION_DEATH_BASE") + CyGame().getSorenRandNum(gc.getDefineINT("NUKE_POPULATION_DEATH_RAND_1"), "Population Nuked 1") + CyGame().getSorenRandNum(gc.getDefineINT("NUKE_POPULATION_DEATH_RAND_2"), "Population Nuked 2"))) / 100

		iNukedPopulation *= max(0, (pCity.getNukeModifier() + 100))
		iNukedPopulation /= 100

		pCity.changePopulation(-(min((pCity.getPopulation() - 1), iNukedPopulation)))
				
		# Now update the city and display
		FinalFrontier = CvEventInterface.getEventManager().FinalFrontier
		FinalFrontier.getAI().doCityAIUpdate(pCity)
			
		pSystem.updateDisplay()
		
		# give message that this has happened
		szBuffer = localText.getText("TXT_KEY_MISC_MELTDOWN_CITY", (pCity.getName(),))
		CyInterface().addMessage( pCity.getOwner(), False, gc.getDefineINT("EVENT_MESSAGE_TIME"), szBuffer, 
				"AS2D_MELTDOWN", InterfaceMessageTypes.MESSAGE_TYPE_MINOR_EVENT,
				CyArtFileMgr().getInterfaceArtInfo("INTERFACE_UNHEALTHY_PERSON").getPath(), gc.getInfoTypeForString("COLOR_RED"),
				pCity.getX(), pCity.getY(), True, True)

		return True
Exemple #54
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)
Exemple #55
0
def bCtrl():
	return CvEventInterface.getEventManager().bCtrl
 def __init__(self, WB):
     self.WB = WB
     self.iTable_Y = 110
     import CvEventInterface
     self.eventManager = CvEventInterface.getEventManager()
 def __init__(self, WB):
     self.WB = WB
     self.iTable_Y = 80
     self.lCities = []
     import CvEventInterface
     self.eventManager = CvEventInterface.getEventManager()