HELP with merging my mod and BUG!!!

I don't see anything in green there. I also don't really understand how I know which event handler (whatever that is) to use. What am I looking for?

So if I get this:

Code:
    def onGameStart(self, argsList):
        'Called at the start of the game'

Yes, that is one of the functions from the big list. Which is why you add an "event handler".

Now scroll down to the next blue line. If you look "OnBeginGameTurn" is one too, so you'll need to add a third one. Just keep going, there aren't as many as you think...
 
I don't see anything in green there. I also don't really understand how I know which event handler (whatever that is) to use. What am I looking for?

So if I get this:

Code:
    def onGameStart(self, argsList):
        'Called at the start of the game'
I should "replace it" with this?

Code:
    def onGameStart(self, eventmanager):
        [COLOR=Red]eventManager.addEventHandler("GameStart", self.onGameStart)[/COLOR]
        'Called at the start of the game'
EDIT: put the wrong thing the first time.

Close. Don't put the red line there, leave that code alone. Put the red line underneath the big "def __init__(self, eventmanager):" heading.

Then you got it completely right.
 
Close. Don't put the red line there, leave that code alone. Put the red line underneath the big "def __init__(self, eventmanager):" heading.

Then you got it completely right.

What big "def__init__(self, eventmanager):" heading? :crazyeye:

I hate this :):):):), everytime I think I got it I'm totally way off and even more confused!
 
I began working on an example mod for BUG a while ago but haven't completed it. Hopefully this can help shed some light on what's necessary. The mod is very simple and doesn't maintain any game state. It's based entirely on altering some game actions and effects.

When adding events handlers and game utils callbacks--keep in mind they're both functions--you can put them into a class or in the module directly. I chose the latter route because I didn't have a need for a class. You can always do it either way.

BTW, your class names do not have to match your module names, but they can of course. I also highly recommend reading How to Think Like a Computer Scientist to learn some basic Python.

Without further ado, here is the half-baked example code:

LuckyCharms.xml

Code:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!--
	Lucky Charms
	by EmperorFool

	Example mod that provides various free goodies at random.
-->
<mod id="LuckyCharms"
	 module="LuckyCharms"
	 name="Lucky Charms"
	 author="EmperorFool"
	 version="1.0"
	 date="01/01/2010">

	<options id="LuckyCharms" file="Lucky Charms.ini">
		<section id="General">
			<option id="Enabled" key="Enabled" 
					type="boolean" default="True">
				<change function="onEnabledOptionChanged"/>
			</option>
			<option id="LeprechaunName" key="Leprechaun Name" 
					type="string" default="Freddie">
				<change function="onLeprechaunNameChanged"/>
			</option>
		</section>
		
		<section id="Gold">
			<list   id="FreeGoldChance" key="Free Gold Chance" 
					type="int" default="10"/>
			<option id="FreeGoldAmount" key="Free Gold Amount" 
					type="int" default="100"/>
		</section>
			
		<section id="Cities">
			<option id="ExtraPopChance" key="Extra Pop Chance" 
					type="int" default="50"/>
			<option id="ExtraPopMin" key="Extra Pop Min" 
					type="int" default="1"/>
			<option id="ExtraPopMax" key="Extra Pop Max" 
					type="int" default="3"/>
			
			<option id="FreeWorkerChance" key="Free Worker Chance" 
					type="int" default="1" listType="string"
					values="Low|Medium|High"/>
		</section>
	</options>
	
	<init>
		<arg name="freeGoldTechs" type="tuple">
			"TECH_HUNTING",
			"TECH_ANIMAL_HUSBANDRY",
			"TECH_PRIESTHOOD",
			"TECH_CURRENCY",
			"TECH_BANKING"
		</arg>
	</init>
	
	<event type="OnLoad" function="onLoad"/>
	<event type="GameStart" function="onGameStart"/>
	
	<event type="BeginPlayerTurn" function="onBeginPlayerTurn"/>
	<event type="cityBuilt" function="onCityBuilt"/>
	<event type="techAcquired" function="onTechAcquired"/>
	
	<shortcut key="Ctrl Shift L" function="doFreeGold"/>
</mod>

LuckyCharms.py

Code:
## LuckyCharms
##
## Example mod that provides various free goodies at random.
##
## Copyright (c) 2009 The BUG Mod.
##
## Author: EmperorFool

from CvPythonExtensions import *
import BugCore
import BugUtil


## GLOBAL VARIABLES

gc = CyGlobalContext()
options = BugCore.game.LuckyCharms


## INITIALIZATION

FREE_GOLD_TECHS = None
def init(freeGoldTechs):
	"""
	Looks up the technology keys from the XML config file and stores their TechTypes in a set.
	"""
	global FREE_GOLD_TECHS
	FREE_GOLD_TECHS = set()
	for key in freeGoldTechs:
		eTech = gc.getInfoTypeForString(key)
		if eTech >= 0:
			FREE_GOLD_TECHS.add(eTech)


## GENERAL

def onEnabledOptionChanged(option):
	introduceLeprechaun()

def onLeprechaunNameChanged(option):
	introduceLeprechaun()

def onGameStart(argsList):
	introduceLeprechaun()
	giveGold(gc.getGame().getActivePlayer())

def onLoad(argsList):
	introduceLeprechaun()

def introduceLeprechaun():
	if options.isEnabled():
		BugUtil.alert("Your lucky leprechaun for today is %s" % options.getLeprechaunName())

def isLucky(iChance, message):
	return iChance > 0 and gc.getGame().getSorenRandNum(100, message) < constrain(iChance)

def constrain(value, minValue=0, maxValue=100):
	return max(minValue, min(value, maxValue))


## FREE GOLD

def doFreeGold(argsList):
	"""
	Gives a random amount of gold to the active player in response to the shortcut being pressed.
	All shortcut functions must take a single parameter; it holds the same parameters passed to
	the onKbdEvent event handler: type (KeyDown), key, mouse x/y, plot x/y.
	"""
	giveGold(gc.getGame().getActivePlayer())

def onBeginPlayerTurn(argsList):
	"""
	Possibly gives a random amount of gold to the given player at the start of their turn.
	"""
	iGameTurn, ePlayer = argsList
	if options.isEnabled():
		if isLucky(options.getFreeGoldChance(), "free gold chance"):
			giveGold(ePlayer)

def onTechAcquired(argsList):
	eTech, eTeam, ePlayer, bAnnounce = argsList
	if options.isEnabled():
		if eTech in FREE_GOLD_TECHS:
			giveGold(ePlayer)

def giveGold(ePlayer):
	"""
	Gives a random amount of gold to the given player.
	"""
	if options.isEnabled():
		iAmount = constrain(options.getFreeGoldAmount(), 0, 1000000)
		if iAmount > 0:
			iGold = gc.getGame().getSorenRandNum(iAmount, "free gold")
			gc.getPlayer(ePlayer).changeGold(iGold)
			BugUtil.alert("Player %d just got %d gold", ePlayer, iGold)


## FREE POPULATION and WORKERS

FREE_WORKER_CHANCES = [10, 25, 50]

def onCityBuilt(argsList):
	"""
	Gives random extra population and maybe a free worker.
	"""
	city = argsList[0]
	ePlayer = city.getOwner()
	if isLucky(options.getExtraPopChance(), "extra pop chance"):
		iPop = constrain(options.getExtraPopMin(), 0, 3) + gc.getGame().getSorenRandNum(constrain(options.getExtraPopMax(), 3, 6), "extra pop")
		if iPop > 0:
			city.changePopulation(iPop)
			BugUtil.alert("Player %d just got %d extra population", ePlayer, iPop)
	if isLucky(FREE_WORKER_CHANCES[constrain(options.getFreeWorkerChance(), 0, 2)], "free worker chance"):
		eUnitClass = gc.getInfoTypeForString("UNITCLASS_WORKER")
		player = gc.getPlayer(ePlayer)
		eUnit = gc.getCivilizationInfo(player.getCivilizationType()).getCivilizationUnits(eUnitClass)
		if eUnit != -1:
			unit = player.initUnit(eUnit, city.getX(), city.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_SOUTH)
			BugUtil.alert("Player %d just got a free %s", ePlayer, unit.getName())
 
What big "def__init__(self, eventmanager):" heading? :crazyeye:

The one that goes under your "class <someclassname>:" line, where you have "def __init__(self):". Insert ", eventManager" where indicated.
 
I began working on an example mod for BUG a while ago but haven't completed it. Hopefully this can help shed some light on what's necessary. The mod is very simple and doesn't maintain any game state. It's based entirely on altering some game actions and effects.

When adding events handlers and game utils callbacks--keep in mind they're both functions--you can put them into a class or in the module directly. I chose the latter route because I didn't have a need for a class. You can always do it either way.

BTW, your class names do not have to match your module names, but they can of course. I also highly recommend reading How to Think Like a Computer Scientist to learn some basic Python.

Without further ado, here is the half-baked example code:

LuckyCharms.xml

Code:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!--
	Lucky Charms
	by EmperorFool

	Example mod that provides various free goodies at random.
-->
<mod id="LuckyCharms"
	 module="LuckyCharms"
	 name="Lucky Charms"
	 author="EmperorFool"
	 version="1.0"
	 date="01/01/2010">

	<options id="LuckyCharms" file="Lucky Charms.ini">
		<section id="General">
			<option id="Enabled" key="Enabled" 
					type="boolean" default="True">
				<change function="onEnabledOptionChanged"/>
			</option>
			<option id="LeprechaunName" key="Leprechaun Name" 
					type="string" default="Freddie">
				<change function="onLeprechaunNameChanged"/>
			</option>
		</section>
		
		<section id="Gold">
			<list   id="FreeGoldChance" key="Free Gold Chance" 
					type="int" default="10"/>
			<option id="FreeGoldAmount" key="Free Gold Amount" 
					type="int" default="100"/>
		</section>
			
		<section id="Cities">
			<option id="ExtraPopChance" key="Extra Pop Chance" 
					type="int" default="50"/>
			<option id="ExtraPopMin" key="Extra Pop Min" 
					type="int" default="1"/>
			<option id="ExtraPopMax" key="Extra Pop Max" 
					type="int" default="3"/>
			
			<option id="FreeWorkerChance" key="Free Worker Chance" 
					type="int" default="1" listType="string"
					values="Low|Medium|High"/>
		</section>
	</options>
	
	<init>
		<arg name="freeGoldTechs" type="tuple">
			"TECH_HUNTING",
			"TECH_ANIMAL_HUSBANDRY",
			"TECH_PRIESTHOOD",
			"TECH_CURRENCY",
			"TECH_BANKING"
		</arg>
	</init>
	
	<event type="OnLoad" function="onLoad"/>
	<event type="GameStart" function="onGameStart"/>
	
	<event type="BeginPlayerTurn" function="onBeginPlayerTurn"/>
	<event type="cityBuilt" function="onCityBuilt"/>
	<event type="techAcquired" function="onTechAcquired"/>
	
	<shortcut key="Ctrl Shift L" function="doFreeGold"/>
</mod>

LuckyCharms.py

Code:
## LuckyCharms
##
## Example mod that provides various free goodies at random.
##
## Copyright (c) 2009 The BUG Mod.
##
## Author: EmperorFool

from CvPythonExtensions import *
import BugCore
import BugUtil


## GLOBAL VARIABLES

gc = CyGlobalContext()
options = BugCore.game.LuckyCharms


## INITIALIZATION

FREE_GOLD_TECHS = None
def init(freeGoldTechs):
	"""
	Looks up the technology keys from the XML config file and stores their TechTypes in a set.
	"""
	global FREE_GOLD_TECHS
	FREE_GOLD_TECHS = set()
	for key in freeGoldTechs:
		eTech = gc.getInfoTypeForString(key)
		if eTech >= 0:
			FREE_GOLD_TECHS.add(eTech)


## GENERAL

def onEnabledOptionChanged(option):
	introduceLeprechaun()

def onLeprechaunNameChanged(option):
	introduceLeprechaun()

def onGameStart(argsList):
	introduceLeprechaun()
	giveGold(gc.getGame().getActivePlayer())

def onLoad(argsList):
	introduceLeprechaun()

def introduceLeprechaun():
	if options.isEnabled():
		BugUtil.alert("Your lucky leprechaun for today is %s" % options.getLeprechaunName())

def isLucky(iChance, message):
	return iChance > 0 and gc.getGame().getSorenRandNum(100, message) < constrain(iChance)

def constrain(value, minValue=0, maxValue=100):
	return max(minValue, min(value, maxValue))


## FREE GOLD

def doFreeGold(argsList):
	"""
	Gives a random amount of gold to the active player in response to the shortcut being pressed.
	All shortcut functions must take a single parameter; it holds the same parameters passed to
	the onKbdEvent event handler: type (KeyDown), key, mouse x/y, plot x/y.
	"""
	giveGold(gc.getGame().getActivePlayer())

def onBeginPlayerTurn(argsList):
	"""
	Possibly gives a random amount of gold to the given player at the start of their turn.
	"""
	iGameTurn, ePlayer = argsList
	if options.isEnabled():
		if isLucky(options.getFreeGoldChance(), "free gold chance"):
			giveGold(ePlayer)

def onTechAcquired(argsList):
	eTech, eTeam, ePlayer, bAnnounce = argsList
	if options.isEnabled():
		if eTech in FREE_GOLD_TECHS:
			giveGold(ePlayer)

def giveGold(ePlayer):
	"""
	Gives a random amount of gold to the given player.
	"""
	if options.isEnabled():
		iAmount = constrain(options.getFreeGoldAmount(), 0, 1000000)
		if iAmount > 0:
			iGold = gc.getGame().getSorenRandNum(iAmount, "free gold")
			gc.getPlayer(ePlayer).changeGold(iGold)
			BugUtil.alert("Player %d just got %d gold", ePlayer, iGold)


## FREE POPULATION and WORKERS

FREE_WORKER_CHANCES = [10, 25, 50]

def onCityBuilt(argsList):
	"""
	Gives random extra population and maybe a free worker.
	"""
	city = argsList[0]
	ePlayer = city.getOwner()
	if isLucky(options.getExtraPopChance(), "extra pop chance"):
		iPop = constrain(options.getExtraPopMin(), 0, 3) + gc.getGame().getSorenRandNum(constrain(options.getExtraPopMax(), 3, 6), "extra pop")
		if iPop > 0:
			city.changePopulation(iPop)
			BugUtil.alert("Player %d just got %d extra population", ePlayer, iPop)
	if isLucky(FREE_WORKER_CHANCES[constrain(options.getFreeWorkerChance(), 0, 2)], "free worker chance"):
		eUnitClass = gc.getInfoTypeForString("UNITCLASS_WORKER")
		player = gc.getPlayer(ePlayer)
		eUnit = gc.getCivilizationInfo(player.getCivilizationType()).getCivilizationUnits(eUnitClass)
		if eUnit != -1:
			unit = player.initUnit(eUnit, city.getX(), city.getY(), UnitAITypes.NO_UNITAI, DirectionTypes.DIRECTION_SOUTH)
			BugUtil.alert("Player %d just got a free %s", ePlayer, unit.getName())

:dubious:

Now I'm REALLY confused.

These two seem completely different.
 
Alright, wait a minute, so it should look like this then? (Changes in red)

Code:
## Sid Meier's Civilization 4
## Copyright Firaxis Games 2006
## 
## CvEventManager
## This class is passed an argsList from CvAppInterface.onEvent
## The argsList can contain anything from mouse location to key info
## The EVENTLIST that are being notified can be found 


from CvPythonExtensions import *
import CvUtil
import CvScreensInterface
import CvDebugTools
import CvWBPopups
import PyHelpers
import Popup as PyPopup
import CvCameraControls
import CvTopCivs
import sys
import CvWorldBuilderScreen
import CvAdvisorUtils
import CvTechChooser

import pickle

# BUG - Next War Merge - start
import SdToolkit
SD_MOD_ID = "NextWar"
SD_NUKES_ID = "NumNukes"
# BUG - Next War Merge - end

gc = CyGlobalContext()
localText = CyTranslator()
PyPlayer = PyHelpers.PyPlayer
PyInfo = PyHelpers.PyInfo


# globals
###################################################


g_iNumNukesWarningMessage = 7
g_iNumNukesGameOver = 20



[COLOR="Red"]class DiplomacyEventManager:
	def __init__(self, eventmanager):[/COLOR]
		#################### ON EVENT MAP ######################
		#print "EVENTMANAGER INIT"
				
		self.bCtrl = False
		self.bShift = False
		self.bAlt = False
		self.bAllowCheats = False
		
		# OnEvent Enums
		self.EventLButtonDown=1
		self.EventLcButtonDblClick=2
		self.EventRButtonDown=3
		self.EventBack=4
		self.EventForward=5
		self.EventKeyDown=6
		self.EventKeyUp=7
	
		self.__LOG_MOVEMENT = 0
		self.__LOG_BUILDING = 0
		self.__LOG_COMBAT = 0
		self.__LOG_CONTACT = 0
		self.__LOG_IMPROVEMENT =0
		self.__LOG_CITYLOST = 0
		self.__LOG_CITYBUILDING = 0
		self.__LOG_TECH = 0
		self.__LOG_UNITBUILD = 0
		self.__LOG_UNITKILLED = 1
		self.__LOG_UNITLOST = 0
		self.__LOG_UNITPROMOTED = 0
		self.__LOG_UNITSELECTED = 0
		self.__LOG_UNITPILLAGE = 0
		self.__LOG_GOODYRECEIVED = 0
		self.__LOG_GREATPERSON = 0
		self.__LOG_RELIGION = 0
		self.__LOG_RELIGIONSPREAD = 0
		self.__LOG_GOLDENAGE = 0
		self.__LOG_ENDGOLDENAGE = 0
		self.__LOG_WARPEACE = 0
		self.__LOG_PUSH_MISSION = 0
		###circus hagenbeck start part 1
                self.oldcity = [-1,-1]
                ###circus hagenbeck end part 1        
		
		# Next War tracks cities that have been razed
		self.iArcologyCityID = -1
		
		## EVENTLIST
		self.EventHandlerMap = {
			'mouseEvent'			: self.onMouseEvent,
			'kbdEvent' 				: self.onKbdEvent,
			'ModNetMessage'					: self.onModNetMessage,
			'Init'					: self.onInit,
			'Update'				: self.onUpdate,
			'UnInit'				: self.onUnInit,
			'OnSave'				: self.onSaveGame,
			'OnPreSave'				: self.onPreSave,
			'OnLoad'				: self.onLoadGame,
			'GameStart'				: self.onGameStart,
			'GameEnd'				: self.onGameEnd,
			'plotRevealed' 			: self.onPlotRevealed,
			'plotFeatureRemoved' 	: self.onPlotFeatureRemoved,
			'plotPicked'			: self.onPlotPicked,
			'nukeExplosion'			: self.onNukeExplosion,
			'gotoPlotSet'			: self.onGotoPlotSet,
			'BeginGameTurn'			: self.onBeginGameTurn,
			'EndGameTurn'			: self.onEndGameTurn,
			'BeginPlayerTurn'		: self.onBeginPlayerTurn,
			'EndPlayerTurn'			: self.onEndPlayerTurn,
			'endTurnReady'			: self.onEndTurnReady,
			'combatResult' 			: self.onCombatResult,
		  'combatLogCalc'	 		: self.onCombatLogCalc,
		  'combatLogHit'				: self.onCombatLogHit,
			'improvementBuilt' 		: self.onImprovementBuilt,
			'improvementDestroyed' 		: self.onImprovementDestroyed,
			'routeBuilt' 		: self.onRouteBuilt,
			'firstContact' 			: self.onFirstContact,
			'cityBuilt' 			: self.onCityBuilt,
			'cityRazed'				: self.onCityRazed,
			'cityAcquired' 			: self.onCityAcquired,
			'cityAcquiredAndKept' 	: self.onCityAcquiredAndKept,
			'cityLost'				: self.onCityLost,
			'cultureExpansion' 		: self.onCultureExpansion,
			'cityGrowth' 			: self.onCityGrowth,
			'cityDoTurn' 			: self.onCityDoTurn,
			'cityBuildingUnit'	: self.onCityBuildingUnit,
			'cityBuildingBuilding'	: self.onCityBuildingBuilding,
			'cityRename'				: self.onCityRename,
			'cityHurry'				: self.onCityHurry,
			'selectionGroupPushMission'		: self.onSelectionGroupPushMission,
			'unitMove' 				: self.onUnitMove,
			'unitSetXY' 			: self.onUnitSetXY,
			'unitCreated' 			: self.onUnitCreated,
			'unitBuilt' 			: self.onUnitBuilt,
			'unitKilled'			: self.onUnitKilled,
			'unitLost'				: self.onUnitLost,
			'unitPromoted'			: self.onUnitPromoted,
			'unitSelected'			: self.onUnitSelected, 
			'UnitRename'				: self.onUnitRename,
			'unitPillage'				: self.onUnitPillage,
			'unitSpreadReligionAttempt'	: self.onUnitSpreadReligionAttempt,
			'unitGifted'				: self.onUnitGifted,
			'unitBuildImprovement'				: self.onUnitBuildImprovement,
			'goodyReceived'        	: self.onGoodyReceived,
			'greatPersonBorn'      	: self.onGreatPersonBorn,
			'buildingBuilt' 		: self.onBuildingBuilt,
			'projectBuilt' 			: self.onProjectBuilt,
			'techAcquired'			: self.onTechAcquired,
			'techSelected'			: self.onTechSelected,
			'religionFounded'		: self.onReligionFounded,
			'religionSpread'		: self.onReligionSpread, 
			'religionRemove'		: self.onReligionRemove, 
			'corporationFounded'	: self.onCorporationFounded,
			'corporationSpread'		: self.onCorporationSpread, 
			'corporationRemove'		: self.onCorporationRemove, 
			'goldenAge'				: self.onGoldenAge,
			'endGoldenAge'			: self.onEndGoldenAge,
			'chat' 					: self.onChat,
			'victory'				: self.onVictory,
			'vassalState'			: self.onVassalState,
			'changeWar'				: self.onChangeWar,
			'setPlayerAlive'		: self.onSetPlayerAlive,
			'playerChangeStateReligion'		: self.onPlayerChangeStateReligion,
			'playerGoldTrade'		: self.onPlayerGoldTrade,
			'windowActivation'		: self.onWindowActivation,
			'gameUpdate'			: self.onGameUpdate,		# sample generic event
		}

		################## Events List ###############################
		#
		# Dictionary of Events, indexed by EventID (also used at popup context id)
		#   entries have name, beginFunction, applyFunction [, randomization weight...]
		#
		# Normal events first, random events after
		#	
		################## Events List ###############################
		self.Events={
			CvUtil.EventEditCityName : ('EditCityName', self.__eventEditCityNameApply, self.__eventEditCityNameBegin),
			CvUtil.EventEditCity : ('EditCity', self.__eventEditCityApply, self.__eventEditCityBegin),
			CvUtil.EventPlaceObject : ('PlaceObject', self.__eventPlaceObjectApply, self.__eventPlaceObjectBegin),
			CvUtil.EventAwardTechsAndGold: ('AwardTechsAndGold', self.__eventAwardTechsAndGoldApply, self.__eventAwardTechsAndGoldBegin),
			CvUtil.EventEditUnitName : ('EditUnitName', self.__eventEditUnitNameApply, self.__eventEditUnitNameBegin),
			CvUtil.EventWBAllPlotsPopup : ('WBAllPlotsPopup', self.__eventWBAllPlotsPopupApply, self.__eventWBAllPlotsPopupBegin),
			CvUtil.EventWBLandmarkPopup : ('WBLandmarkPopup', self.__eventWBLandmarkPopupApply, self.__eventWBLandmarkPopupBegin),
			CvUtil.EventWBScriptPopup : ('WBScriptPopup', self.__eventWBScriptPopupApply, self.__eventWBScriptPopupBegin),
			CvUtil.EventWBStartYearPopup : ('WBStartYearPopup', self.__eventWBStartYearPopupApply, self.__eventWBStartYearPopupBegin),
			CvUtil.EventShowWonder: ('ShowWonder', self.__eventShowWonderApply, self.__eventShowWonderBegin),
		}	

[COLOR="Red"]	def onLoadGame(self.onLoadGame, eventmanager):[/COLOR]
		CvAdvisorUtils.resetNoLiberateCities()
# BUG - Next War Merge - start
		# convert old script data list to SdToolkit for old saves
		data = gc.getGame().getScriptData()
		if isinstance(data, list):
			CvUtil.pyPrint('converting script data: %s' % data)
			iNukes = list[0]
			gc.getGame().setScriptData("")
			SdToolkit.sdSetGlobal(SD_MOD_ID, SD_NUKES_ID, iNukes)
# BUG - Next War Merge - end
		return 0

Is that right?
 
Yes. You have several more event handlers to add though.

Alright, now that that seems right. I don't know what an event handler is or how I know when to add it. I thought I added one last time, then you told me that wasn't right, remember this?

Code:
    def onGameStart(self, eventmanager):
        [COLOR="Red"]eventManager.addEventHandler("GameStart", self.onGameStart)[/COLOR]
        'Called at the start of the game'

Close. Don't put the red line there, leave that code alone. Put the red line underneath the big "def __init__(self, eventmanager):" heading.

Then you got it completely right.

So I'm asking you, how do I know when and when not to add it again?

BTW: With your Avatar, and how complicated this is, I feel like a wizard is training me or something!

EDIT: So the Event Handler is the thing that says, "Hey, do what I'm saying to do" right? And that goes under the times when it says def__init__(self, eventmanager) or wherever those are. Right?
 
Alright, now that that seems right. I don't know what an event handler is or how I know when to add it. I thought I added one last time, then you told me that wasn't right, remember this?

Yes. All the event handler code goes underneath the giant umbrella that is the "init function". To show you exactly what is inside the init function, let me highlight it for you:

Code:
class DiplomacyEventManager:
    def __init__(self, eventmanager):
[COLOR=Blue]        #################### ON EVENT MAP ######################
        #print "EVENTMANAGER INIT"
                
        self.bCtrl = False
        self.bShift = False
        self.bAlt = False
        self.bAllowCheats = False
        
        # OnEvent Enums
        self.EventLButtonDown=1
        self.EventLcButtonDblClick=2
        self.EventRButtonDown=3
        self.EventBack=4
        self.EventForward=5
        self.EventKeyDown=6
        self.EventKeyUp=7
    
        self.__LOG_MOVEMENT = 0
        self.__LOG_BUILDING = 0
        self.__LOG_COMBAT = 0
        self.__LOG_CONTACT = 0
        self.__LOG_IMPROVEMENT =0
        self.__LOG_CITYLOST = 0
        self.__LOG_CITYBUILDING = 0
        self.__LOG_TECH = 0
        self.__LOG_UNITBUILD = 0
        self.__LOG_UNITKILLED = 1
        self.__LOG_UNITLOST = 0
        self.__LOG_UNITPROMOTED = 0
        self.__LOG_UNITSELECTED = 0
        self.__LOG_UNITPILLAGE = 0
        self.__LOG_GOODYRECEIVED = 0
        self.__LOG_GREATPERSON = 0
        self.__LOG_RELIGION = 0
        self.__LOG_RELIGIONSPREAD = 0
        self.__LOG_GOLDENAGE = 0
        self.__LOG_ENDGOLDENAGE = 0
        self.__LOG_WARPEACE = 0
        self.__LOG_PUSH_MISSION = 0
        ###circus hagenbeck start part 1
                self.oldcity = [-1,-1]
                ###circus hagenbeck end part 1        
        
        # Next War tracks cities that have been razed
        self.iArcologyCityID = -1
        
        ## EVENTLIST
        self.EventHandlerMap = {
            'mouseEvent'            : self.onMouseEvent,
            'kbdEvent'                 : self.onKbdEvent,
            'ModNetMessage'                    : self.onModNetMessage,
            'Init'                    : self.onInit,
            'Update'                : self.onUpdate,
            'UnInit'                : self.onUnInit,
            'OnSave'                : self.onSaveGame,
            'OnPreSave'                : self.onPreSave,
            'OnLoad'                : self.onLoadGame,
            'GameStart'                : self.onGameStart,
            'GameEnd'                : self.onGameEnd,
            'plotRevealed'             : self.onPlotRevealed,
            'plotFeatureRemoved'     : self.onPlotFeatureRemoved,
            'plotPicked'            : self.onPlotPicked,
            'nukeExplosion'            : self.onNukeExplosion,
            'gotoPlotSet'            : self.onGotoPlotSet,
            'BeginGameTurn'            : self.onBeginGameTurn,
            'EndGameTurn'            : self.onEndGameTurn,
            'BeginPlayerTurn'        : self.onBeginPlayerTurn,
            'EndPlayerTurn'            : self.onEndPlayerTurn,
            'endTurnReady'            : self.onEndTurnReady,
            'combatResult'             : self.onCombatResult,
          'combatLogCalc'             : self.onCombatLogCalc,
          'combatLogHit'                : self.onCombatLogHit,
            'improvementBuilt'         : self.onImprovementBuilt,
            'improvementDestroyed'         : self.onImprovementDestroyed,
            'routeBuilt'         : self.onRouteBuilt,
            'firstContact'             : self.onFirstContact,
            'cityBuilt'             : self.onCityBuilt,
            'cityRazed'                : self.onCityRazed,
            'cityAcquired'             : self.onCityAcquired,
            'cityAcquiredAndKept'     : self.onCityAcquiredAndKept,
            'cityLost'                : self.onCityLost,
            'cultureExpansion'         : self.onCultureExpansion,
            'cityGrowth'             : self.onCityGrowth,
            'cityDoTurn'             : self.onCityDoTurn,
            'cityBuildingUnit'    : self.onCityBuildingUnit,
            'cityBuildingBuilding'    : self.onCityBuildingBuilding,
            'cityRename'                : self.onCityRename,
            'cityHurry'                : self.onCityHurry,
            'selectionGroupPushMission'        : self.onSelectionGroupPushMission,
            'unitMove'                 : self.onUnitMove,
            'unitSetXY'             : self.onUnitSetXY,
            'unitCreated'             : self.onUnitCreated,
            'unitBuilt'             : self.onUnitBuilt,
            'unitKilled'            : self.onUnitKilled,
            'unitLost'                : self.onUnitLost,
            'unitPromoted'            : self.onUnitPromoted,
            'unitSelected'            : self.onUnitSelected, 
            'UnitRename'                : self.onUnitRename,
            'unitPillage'                : self.onUnitPillage,
            'unitSpreadReligionAttempt'    : self.onUnitSpreadReligionAttempt,
            'unitGifted'                : self.onUnitGifted,
            'unitBuildImprovement'                : self.onUnitBuildImprovement,
            'goodyReceived'            : self.onGoodyReceived,
            'greatPersonBorn'          : self.onGreatPersonBorn,
            'buildingBuilt'         : self.onBuildingBuilt,
            'projectBuilt'             : self.onProjectBuilt,
            'techAcquired'            : self.onTechAcquired,
            'techSelected'            : self.onTechSelected,
            'religionFounded'        : self.onReligionFounded,
            'religionSpread'        : self.onReligionSpread, 
            'religionRemove'        : self.onReligionRemove, 
            'corporationFounded'    : self.onCorporationFounded,
            'corporationSpread'        : self.onCorporationSpread, 
            'corporationRemove'        : self.onCorporationRemove, 
            'goldenAge'                : self.onGoldenAge,
            'endGoldenAge'            : self.onEndGoldenAge,
            'chat'                     : self.onChat,
            'victory'                : self.onVictory,
            'vassalState'            : self.onVassalState,
            'changeWar'                : self.onChangeWar,
            'setPlayerAlive'        : self.onSetPlayerAlive,
            'playerChangeStateReligion'        : self.onPlayerChangeStateReligion,
            'playerGoldTrade'        : self.onPlayerGoldTrade,
            'windowActivation'        : self.onWindowActivation,
            'gameUpdate'            : self.onGameUpdate,        # sample generic event
        }

        ################## Events List ###############################
        #
        # Dictionary of Events, indexed by EventID (also used at popup context id)
        #   entries have name, beginFunction, applyFunction [, randomization weight...]
        #
        # Normal events first, random events after
        #    
        ################## Events List ###############################
        self.Events={
            CvUtil.EventEditCityName : ('EditCityName', self.__eventEditCityNameApply, self.__eventEditCityNameBegin),
            CvUtil.EventEditCity : ('EditCity', self.__eventEditCityApply, self.__eventEditCityBegin),
            CvUtil.EventPlaceObject : ('PlaceObject', self.__eventPlaceObjectApply, self.__eventPlaceObjectBegin),
            CvUtil.EventAwardTechsAndGold: ('AwardTechsAndGold', self.__eventAwardTechsAndGoldApply, self.__eventAwardTechsAndGoldBegin),
            CvUtil.EventEditUnitName : ('EditUnitName', self.__eventEditUnitNameApply, self.__eventEditUnitNameBegin),
            CvUtil.EventWBAllPlotsPopup : ('WBAllPlotsPopup', self.__eventWBAllPlotsPopupApply, self.__eventWBAllPlotsPopupBegin),
            CvUtil.EventWBLandmarkPopup : ('WBLandmarkPopup', self.__eventWBLandmarkPopupApply, self.__eventWBLandmarkPopupBegin),
            CvUtil.EventWBScriptPopup : ('WBScriptPopup', self.__eventWBScriptPopupApply, self.__eventWBScriptPopupBegin),
            CvUtil.EventWBStartYearPopup : ('WBStartYearPopup', self.__eventWBStartYearPopupApply, self.__eventWBStartYearPopupBegin),
            CvUtil.EventShowWonder: ('ShowWonder', self.__eventShowWonderApply, self.__eventShowWonderBegin),
        }    [/COLOR]
All that blue code is inside the "init" function, and loaded (this is a tough one) when the game initializes or loads for the first time.

Now wait just a moment here, you said this is what you changed:
Code:
[COLOR=Red]def onLoadGame(self.onLoadGame, eventmanager):[/COLOR]
        CvAdvisorUtils.resetNoLiberateCities()
# BUG - Next War Merge - start
That's wrong. Leave all the code that isn't inside the "init" function alone, keep it like it was.

Undo your change.

What you should have so far is this:

Code:
class DiplomacyEventManager:
    def __init__(self, eventmanager):
        [COLOR=Red]eventManager.addEventHandler("GameStart", self.onGameStart)[/COLOR]
        [COLOR=Navy]eventManager.addEventHandler("OnLoad", self.onLoadGame)[/COLOR]

        #################### ON EVENT MAP ######################
        #print "EVENTMANAGER INIT"
                
        self.bCtrl = False
        self.bShift = False
        self.bAlt = False
        self.bAllowCheats = False

... Rest if code
EDIT: So the Event Handler is the thing that says, "Hey, do what I'm saying to do" right? And that goes under the times when it says def__init__(self, eventmanager) or wherever those are. Right?

That's a pretty good lay-man's definition. You have a couple more to do after those two... I'll be back, I need to grab something to eat.
 
Just to throw in one additional programming detail, python is sensitive to indentation. Replacing tabs with spaces is not cool. I hate this particular feature of the language; I'd much rather have semicolons. But I digress. In two places, you have pasted this code where the indentation is wrong:
Code:
class DiplomacyEventManager:
	def __init__(self):
        eventManager.addEventHandler("OnLoad", self.onLoadGame)
When editing python, please use a text editor which does not arbitrarily convert spaces to tabs and the reverse, and make sure that each line inside the function is indented by one tab level compared to the function definition. If you see any spaces at the start of lines, you are going to be in trouble.

I'm not sure of the most politically correct way to phrase this, but this is a challenging project for a non-programmer. Do you have access to a programmer who you could send the files, they could make some changes to get it working, and send it back?
 
An event is where the game tells the Python code that something happened: a city was founded, a unit was trained, an improvement was built. An event handler is a function that you define to do something when that event triggers. In this line of code

Code:
eventManager.addEventHandler("[COLOR="Red"]GameStart[/COLOR]", self.[COLOR="Blue"]onGameStart[/COLOR])

GameStart is the event type. It is passed by the C++ code to the event manager when triggering an event. onGameStart is the event handler (function) you have created. The line as a whole tells the event manager to add your handler to that event. When that event is triggered, the event manager will call all of the handlers attached to it.
 
Okay, I'm prettry drunk right now, as I tend to get. Listen though, I think I have this :):):):) down. So let me get sober and explain it whjen I get up or whatever! Son!
 
@ davidallen: if I could send this to someone I would.

Anyway here is what I came up with, the section in blue are the eventhandlers I added. The part in red are defs that I couldn't find on your list (Afforess) so I didn't make an event handler for them. Do I still need to do that?

Code:
## Sid Meier's Civilization 4
## Copyright Firaxis Games 2006
## 
## CvEventManager
## This class is passed an argsList from CvAppInterface.onEvent
## The argsList can contain anything from mouse location to key info
## The EVENTLIST that are being notified can be found 


from CvPythonExtensions import *
import CvUtil
import CvScreensInterface
import CvDebugTools
import CvWBPopups
import PyHelpers
import Popup as PyPopup
import CvCameraControls
import CvTopCivs
import sys
import CvWorldBuilderScreen
import CvAdvisorUtils
import CvTechChooser

import pickle

# BUG - Next War Merge - start
import SdToolkit
SD_MOD_ID = "NextWar"
SD_NUKES_ID = "NumNukes"
# BUG - Next War Merge - end

gc = CyGlobalContext()
localText = CyTranslator()
PyPlayer = PyHelpers.PyPlayer
PyInfo = PyHelpers.PyInfo


# globals
###################################################


g_iNumNukesWarningMessage = 7
g_iNumNukesGameOver = 20



class DiplomacyEventManager:
	def __init__(self, eventmanager):
[COLOR="DeepSkyBlue"]        eventManager.addEventHandler("GameStart", self.onGameStart)
        eventManager.addEventHandler("OnLoad", self.onLoadGame)
        eventManager.addEventHandler("GameStart", self.onGameStart)
        eventManager.addEventHandler("BeginGameTurn", self.onBeginGameTurn)
        eventManager.addEventHandler("cityRazed", self.onCityRazed)
        eventManager.addEventHandler("cityDoTurn", self.onCityDoTurn)[/COLOR]
        
        
		#################### ON EVENT MAP ######################
		#print "EVENTMANAGER INIT"
				
		self.bCtrl = False
		self.bShift = False
		self.bAlt = False
		self.bAllowCheats = False
		
		# OnEvent Enums
		self.EventLButtonDown=1
		self.EventLcButtonDblClick=2
		self.EventRButtonDown=3
		self.EventBack=4
		self.EventForward=5
		self.EventKeyDown=6
		self.EventKeyUp=7
	
		self.__LOG_MOVEMENT = 0
		self.__LOG_BUILDING = 0
		self.__LOG_COMBAT = 0
		self.__LOG_CONTACT = 0
		self.__LOG_IMPROVEMENT =0
		self.__LOG_CITYLOST = 0
		self.__LOG_CITYBUILDING = 0
		self.__LOG_TECH = 0
		self.__LOG_UNITBUILD = 0
		self.__LOG_UNITKILLED = 1
		self.__LOG_UNITLOST = 0
		self.__LOG_UNITPROMOTED = 0
		self.__LOG_UNITSELECTED = 0
		self.__LOG_UNITPILLAGE = 0
		self.__LOG_GOODYRECEIVED = 0
		self.__LOG_GREATPERSON = 0
		self.__LOG_RELIGION = 0
		self.__LOG_RELIGIONSPREAD = 0
		self.__LOG_GOLDENAGE = 0
		self.__LOG_ENDGOLDENAGE = 0
		self.__LOG_WARPEACE = 0
		self.__LOG_PUSH_MISSION = 0
		###circus hagenbeck start part 1
                self.oldcity = [-1,-1]
                ###circus hagenbeck end part 1        
		
		# Next War tracks cities that have been razed
		self.iArcologyCityID = -1
		
		## EVENTLIST
		self.EventHandlerMap = {
			'mouseEvent'			: self.onMouseEvent,
			'kbdEvent' 				: self.onKbdEvent,
			'ModNetMessage'					: self.onModNetMessage,
			'Init'					: self.onInit,
			'Update'				: self.onUpdate,
			'UnInit'				: self.onUnInit,
			'OnSave'				: self.onSaveGame,
			'OnPreSave'				: self.onPreSave,
			'OnLoad'				: self.onLoadGame,
			'GameStart'				: self.onGameStart,
			'GameEnd'				: self.onGameEnd,
			'plotRevealed' 			: self.onPlotRevealed,
			'plotFeatureRemoved' 	: self.onPlotFeatureRemoved,
			'plotPicked'			: self.onPlotPicked,
			'nukeExplosion'			: self.onNukeExplosion,
			'gotoPlotSet'			: self.onGotoPlotSet,
			'BeginGameTurn'			: self.onBeginGameTurn,
			'EndGameTurn'			: self.onEndGameTurn,
			'BeginPlayerTurn'		: self.onBeginPlayerTurn,
			'EndPlayerTurn'			: self.onEndPlayerTurn,
			'endTurnReady'			: self.onEndTurnReady,
			'combatResult' 			: self.onCombatResult,
		  'combatLogCalc'	 		: self.onCombatLogCalc,
		  'combatLogHit'				: self.onCombatLogHit,
			'improvementBuilt' 		: self.onImprovementBuilt,
			'improvementDestroyed' 		: self.onImprovementDestroyed,
			'routeBuilt' 		: self.onRouteBuilt,
			'firstContact' 			: self.onFirstContact,
			'cityBuilt' 			: self.onCityBuilt,
			'cityRazed'				: self.onCityRazed,
			'cityAcquired' 			: self.onCityAcquired,
			'cityAcquiredAndKept' 	: self.onCityAcquiredAndKept,
			'cityLost'				: self.onCityLost,
			'cultureExpansion' 		: self.onCultureExpansion,
			'cityGrowth' 			: self.onCityGrowth,
			'cityDoTurn' 			: self.onCityDoTurn,
			'cityBuildingUnit'	: self.onCityBuildingUnit,
			'cityBuildingBuilding'	: self.onCityBuildingBuilding,
			'cityRename'				: self.onCityRename,
			'cityHurry'				: self.onCityHurry,
			'selectionGroupPushMission'		: self.onSelectionGroupPushMission,
			'unitMove' 				: self.onUnitMove,
			'unitSetXY' 			: self.onUnitSetXY,
			'unitCreated' 			: self.onUnitCreated,
			'unitBuilt' 			: self.onUnitBuilt,
			'unitKilled'			: self.onUnitKilled,
			'unitLost'				: self.onUnitLost,
			'unitPromoted'			: self.onUnitPromoted,
			'unitSelected'			: self.onUnitSelected, 
			'UnitRename'				: self.onUnitRename,
			'unitPillage'				: self.onUnitPillage,
			'unitSpreadReligionAttempt'	: self.onUnitSpreadReligionAttempt,
			'unitGifted'				: self.onUnitGifted,
			'unitBuildImprovement'				: self.onUnitBuildImprovement,
			'goodyReceived'        	: self.onGoodyReceived,
			'greatPersonBorn'      	: self.onGreatPersonBorn,
			'buildingBuilt' 		: self.onBuildingBuilt,
			'projectBuilt' 			: self.onProjectBuilt,
			'techAcquired'			: self.onTechAcquired,
			'techSelected'			: self.onTechSelected,
			'religionFounded'		: self.onReligionFounded,
			'religionSpread'		: self.onReligionSpread, 
			'religionRemove'		: self.onReligionRemove, 
			'corporationFounded'	: self.onCorporationFounded,
			'corporationSpread'		: self.onCorporationSpread, 
			'corporationRemove'		: self.onCorporationRemove, 
			'goldenAge'				: self.onGoldenAge,
			'endGoldenAge'			: self.onEndGoldenAge,
			'chat' 					: self.onChat,
			'victory'				: self.onVictory,
			'vassalState'			: self.onVassalState,
			'changeWar'				: self.onChangeWar,
			'setPlayerAlive'		: self.onSetPlayerAlive,
			'playerChangeStateReligion'		: self.onPlayerChangeStateReligion,
			'playerGoldTrade'		: self.onPlayerGoldTrade,
			'windowActivation'		: self.onWindowActivation,
			'gameUpdate'			: self.onGameUpdate,		# sample generic event
		}

		################## Events List ###############################
		#
		# Dictionary of Events, indexed by EventID (also used at popup context id)
		#   entries have name, beginFunction, applyFunction [, randomization weight...]
		#
		# Normal events first, random events after
		#	
		################## Events List ###############################
		self.Events={
			CvUtil.EventEditCityName : ('EditCityName', self.__eventEditCityNameApply, self.__eventEditCityNameBegin),
			CvUtil.EventEditCity : ('EditCity', self.__eventEditCityApply, self.__eventEditCityBegin),
			CvUtil.EventPlaceObject : ('PlaceObject', self.__eventPlaceObjectApply, self.__eventPlaceObjectBegin),
			CvUtil.EventAwardTechsAndGold: ('AwardTechsAndGold', self.__eventAwardTechsAndGoldApply, self.__eventAwardTechsAndGoldBegin),
			CvUtil.EventEditUnitName : ('EditUnitName', self.__eventEditUnitNameApply, self.__eventEditUnitNameBegin),
			CvUtil.EventWBAllPlotsPopup : ('WBAllPlotsPopup', self.__eventWBAllPlotsPopupApply, self.__eventWBAllPlotsPopupBegin),
			CvUtil.EventWBLandmarkPopup : ('WBLandmarkPopup', self.__eventWBLandmarkPopupApply, self.__eventWBLandmarkPopupBegin),
			CvUtil.EventWBScriptPopup : ('WBScriptPopup', self.__eventWBScriptPopupApply, self.__eventWBScriptPopupBegin),
			CvUtil.EventWBStartYearPopup : ('WBStartYearPopup', self.__eventWBStartYearPopupApply, self.__eventWBStartYearPopupBegin),
			CvUtil.EventShowWonder: ('ShowWonder', self.__eventShowWonderApply, self.__eventShowWonderBegin),
		}	

	def onLoadGame(self, argsList):
		CvAdvisorUtils.resetNoLiberateCities()
# BUG - Next War Merge - start
		# convert old script data list to SdToolkit for old saves
		data = gc.getGame().getScriptData()
		if isinstance(data, list):
			CvUtil.pyPrint('converting script data: %s' % data)
			iNukes = list[0]
			gc.getGame().setScriptData("")
			SdToolkit.sdSetGlobal(SD_MOD_ID, SD_NUKES_ID, iNukes)
# BUG - Next War Merge - end
		return 0

	def onGameStart(self, argsList):
		'Called at the start of the game'

		self.initScriptData()
		
		### circus hagenbeck start part 2
	        if (gc.getGame().getGameTurnYear() <> gc.getDefineINT("START_YEAR")):
                        for iPlayer in range (gc.getMAX_PLAYERS()):
                                player = gc.getPlayer(iPlayer)
				if player.isAlive():
                                        numbuildings = player.countNumBuildings(gc.getInfoTypeForString("BUILDING_CIRCUS_HAGENBECK"))
                                        if numbuildings>0:
                                                for iCity in range(player.getNumCities()):
                                                        pCity = player.getCity(iCity)
                                                        if pCity.getNumBuilding(gc.getInfoTypeForString("BUILDING_CIRCUS_HAGENBECK"))>0:
                                                                self.oldcity = [iPlayer,iCity]
                                                                return
                ###circus hagenbeck end part 2          
		# Are we using the scenario file? If so, then show the backstory popup
		if (CyMap().plot(0,0).getScriptData() == "Scenario"):
			for iPlayer in range(gc.getMAX_PLAYERS()):
				player = gc.getPlayer(iPlayer)
				if (player.isAlive() and player.isHuman()):
					popupInfo = CyPopupInfo()
					popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_TEXT)
					szTitle = u"<font=4b>" + localText.getText("TXT_KEY_NEXT_WAR_BACKSTORY_TITLE", ()) + u"</font>"
					szBody = u"<font=3>" + localText.getText("TXT_KEY_NEXT_WAR_BACKSTORY_TEXT", ()) + u"</font>"
					popupInfo.setText(szTitle + u"\n\n" + szBody)
					popupInfo.addPopup(iPlayer)
		if (gc.getGame().getGameTurnYear() == gc.getDefineINT("START_YEAR") and not gc.getGame().isOption(GameOptionTypes.GAMEOPTION_ADVANCED_START)):
			for iPlayer in range(gc.getMAX_PLAYERS()):
				player = gc.getPlayer(iPlayer)
				if (player.isAlive() and player.isHuman()):
					popupInfo = CyPopupInfo()
					popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_PYTHON_SCREEN)
					popupInfo.setText(u"showDawnOfMan")
					popupInfo.addPopup(iPlayer)
		else:
			CyInterface().setSoundSelectionReady(true)

		if gc.getGame().isPbem():
			for iPlayer in range(gc.getMAX_PLAYERS()):
				player = gc.getPlayer(iPlayer)
				if (player.isAlive() and player.isHuman()):
					popupInfo = CyPopupInfo()
					popupInfo.setButtonPopupType(ButtonPopupTypes.BUTTONPOPUP_DETAILS)
					popupInfo.setOption1(true)
					popupInfo.addPopup(iPlayer)
																	
		CvAdvisorUtils.resetNoLiberateCities()

	def onBeginGameTurn(self, argsList):
		'Called at the beginning of the end of each turn'
		iGameTurn = argsList[0]
###circus hagenbeck start part 3		
		if (CyGame().getTurnYear(iGameTurn)>=1890) and ( iGameTurn % 3 ==0 ):
                        counter = 0
                        while True:
                                counter = counter+1
                                if counter>=100:break
                                dice = gc.getGame().getMapRand()
                                iPlayer = dice.get(gc.getMAX_PLAYERS (), "Players")
                                pPlayer = gc.getPlayer(iPlayer)
                                if pPlayer.isNone():continue
                                if pPlayer.isAlive():
                                        iCity = dice.get(pPlayer.getNumCities () , "Cities" )
                                        pCity = pPlayer.getCity(iCity)
                                        if pCity.isNone():continue
                                        pCity.setNumRealBuilding(gc.getInfoTypeForString("BUILDING_CIRCUSHAGENBECK"),1)
                                        CyInterface().addMessage(iPlayer,false,20,CyTranslator().getText("TXT_KEY_CIRCUS_MOVED",(pCity.getName (),pCity.getName ())),'',0,'Art/Interface/Buttons/General/happy_person.dds',ColorTypes(gc.getInfoTypeForString("COLOR_GREEN")), pCity.getX(), pCity.getY(), True,True) 
                                        if self.oldcity <>[-1,-1]:
                                                otherplayer = gc.getPlayer(self.oldcity[0])
                                                othercity = otherplayer.getCity(self.oldcity[1])
                                                if not othercity.isNone():
                                                        othercity.setNumRealBuilding(gc.getInfoTypeForString("BUILDING_CIRCUSHAGENBECK"),0)
                                                        CyInterface().addMessage(self.oldcity[0],false,20,CyTranslator().getText("TXT_KEY_CIRCUS_LOST",(othercity.getName (),othercity.getName ())),'',0,'Art/Interface/Buttons/General/warning_popup.dds',ColorTypes(gc.getInfoTypeForString("COLOR_RED")), othercity.getX(), othercity.getY(), True,True)
                                        self.oldcity = [iPlayer,iCity]                                 
                                        
                                        break
###circus hagenbeck end part 3         
		CvTopCivs.CvTopCivs().turnChecker(iGameTurn)
		if (CyMap().plot(0,0).getScriptData() == "Scenario"):
			if iGameTurn!=0:
				if iGameTurn%2 == 0:
					self.doCheckDepletion()
		
	def onCityRazed(self, argsList):
		'City Razed'
		city, iPlayer = argsList
		iOwner = city.findHighestCulture()

		# Partisans!
		if city.getPopulation > 1 and iOwner != -1 and iPlayer != -1:
			owner = gc.getPlayer(iOwner)
			if not owner.isBarbarian() and owner.getNumCities() > 0:
				if gc.getTeam(owner.getTeam()).isAtWar(gc.getPlayer(iPlayer).getTeam()):
					if gc.getNumEventTriggerInfos() > 0: # prevents mods that don't have events from getting an error
						iEvent = CvUtil.findInfoTypeNum(gc.getEventTriggerInfo, gc.getNumEventTriggerInfos(),'EVENTTRIGGER_PARTISANS')
						if iEvent != -1 and gc.getGame().isEventActive(iEvent) and owner.getEventTriggerWeight(iEvent) < 0:
							triggerData = owner.initTriggeredData(iEvent, true, -1, city.getX(), city.getY(), iPlayer, city.getID(), -1, -1, -1, -1)
			
		#Raze the Arcology
		owner = PyPlayer(city.getOwner())
		razor = PyPlayer(iPlayer)
		
		self.iArcologyCityID = -1
		
		if city.getNumRealBuilding(gc.getInfoTypeForString("BUILDING_ARCOLOGY")) or city.getNumRealBuilding(gc.getInfoTypeForString("BUILDING_ARCOLOGY_SHIELDING")) or city.getNumRealBuilding(gc.getInfoTypeForString("BUILDING_DEFLECTOR_SHIELDING")):
			self.iArcologyCityID = city.getID()
		
		CvUtil.pyPrint('Player %d Civilization %s City %s was razed by Player %d' 
			%(owner.getID(), owner.getCivilizationName(), city.getName(), razor.getID()))	
		CvUtil.pyPrint("City Razed Event: %s" %(city.getName(),))
	
	def onCityDoTurn(self, argsList):
		'City Production'
		pCity = argsList[0]
		iPlayer = argsList[1]
        
# no anger defying UN resolutions start #
		iGovernmentCivicOption = CvUtil.findInfoTypeNum(gc.getCivicOptionInfo,gc.getNumCivicOptionInfos(),'CIVICOPTION_GOVERNMENT')
		iPoliceState = CvUtil.findInfoTypeNum(gc.getCivicInfo,gc.getNumCivicInfos(),'CIVIC_POLICE_STATE')
		pPlayer = gc.getPlayer(iPlayer)
		iGovernmentCivic = pPlayer.getCivics(iGovernmentCivicOption)

		if (iGovernmentCivic == iPoliceState):
			pCity.changeDefyResolutionAngerTimer(pCity.getDefyResolutionAngerTimer())
# no anger defying UN resolutions end #        

		CvAdvisorUtils.cityAdvise(pCity, iPlayer)
	
####### Next War Functions ######
## Added Fort to doCheckDepletion -- otherwise bonuses worked via forts would never be subject to resource depletion.   JKP


[COLOR="Red"]	def doCheckDepletion(self):
		self.doCheckWorkedResource("BONUS_ALUMINUM", "IMPROVEMENT_MINE", 880)
		self.doCheckWorkedResource("BONUS_ALUMINUM", "IMPROVEMENT_FORT", 880)
		self.doCheckWorkedResource("BONUS_BANANA", "IMPROVEMENT_PLANTATION", 1120)
		self.doCheckWorkedResource("BONUS_BANANA", "IMPROVEMENT_FORT", 1120)
		self.doCheckWorkedResource("BONUS_CLAM", "IMPROVEMENT_FISHING_BOATS", 880)
		self.doCheckWorkedResource("BONUS_COAL", "IMPROVEMENT_MINE", 880)
		self.doCheckWorkedResource("BONUS_COAL", "IMPROVEMENT_FORT", 880)
		self.doCheckWorkedResource("BONUS_COPPER", "IMPROVEMENT_MINE", 880)
		self.doCheckWorkedResource("BONUS_COPPER", "IMPROVEMENT_FORT", 880)
		self.doCheckWorkedResource("BONUS_CORN", "IMPROVEMENT_FARM", 1120)
		self.doCheckWorkedResource("BONUS_CORN", "IMPROVEMENT_FORT", 1120)
		self.doCheckWorkedResource("BONUS_COW", "IMPROVEMENT_PASTURE", 1120)
		self.doCheckWorkedResource("BONUS_COW", "IMPROVEMENT_FORT", 1120)
		self.doCheckWorkedResource("BONUS_CRAB", "IMPROVEMENT_FISHING_BOATS", 1120)
		self.doCheckWorkedResource("BONUS_DEER", "IMPROVEMENT_CAMP", 780)
		self.doCheckWorkedResource("BONUS_DEER", "IMPROVEMENT_FORT", 780)
		self.doCheckWorkedResource("BONUS_DYE", "IMPROVEMENT_PLANTATION", 1120)
		self.doCheckWorkedResource("BONUS_DYE", "IMPROVEMENT_FORT", 1120)
		self.doCheckWorkedResource("BONUS_FISH", "IMPROVEMENT_FISHING_BOATS", 880)
		self.doCheckWorkedResource("BONUS_FUR", "IMPROVEMENT_CAMP", 560)
		self.doCheckWorkedResource("BONUS_FUR", "IMPROVEMENT_FORT", 560)
		self.doCheckWorkedResource("BONUS_GEMS", "IMPROVEMENT_MINE", 1120)
		self.doCheckWorkedResource("BONUS_GEMS", "IMPROVEMENT_FORT", 1120)
		self.doCheckWorkedResource("BONUS_GOLD", "IMPROVEMENT_MINE", 880)
		self.doCheckWorkedResource("BONUS_GOLD", "IMPROVEMENT_FORT", 880)
		self.doCheckWorkedResource("BONUS_HORSE", "IMPROVEMENT_PASTURE", 1120)
		self.doCheckWorkedResource("BONUS_HORSE", "IMPROVEMENT_FORT", 1120)
		self.doCheckWorkedResource("BONUS_IRON", "IMPROVEMENT_MINE", 880)
		self.doCheckWorkedResource("BONUS_IRON", "IMPROVEMENT_FORT", 880)
		self.doCheckWorkedResource("BONUS_IVORY", "IMPROVEMENT_CAMP", 560)
		self.doCheckWorkedResource("BONUS_IVORY", "IMPROVEMENT_FORT", 560)
		self.doCheckWorkedResource("BONUS_MARBLE", "IMPROVEMENT_QUARRY", 750)
		self.doCheckWorkedResource("BONUS_MARBLE", "IMPROVEMENT_FORT", 750)
		self.doCheckWorkedResource("BONUS_OIL", "IMPROVEMENT_WELL", 880)
		self.doCheckWorkedResource("BONUS_OIL", "IMPROVEMENT_FORT", 880)
		self.doCheckWorkedResource("BONUS_OIL", "IMPROVEMENT_OFFSHORE_PLATFORM", 880)
		self.doCheckWorkedResource("BONUS_PIG", "IMPROVEMENT_PASTURE", 1120)
		self.doCheckWorkedResource("BONUS_PIG", "IMPROVEMENT_FORT", 1120)
		self.doCheckWorkedResource("BONUS_RICE", "IMPROVEMENT_FARM", 1120)
		self.doCheckWorkedResource("BONUS_RICE", "IMPROVEMENT_FORT", 1120)
		self.doCheckWorkedResource("BONUS_SILK", "IMPROVEMENT_PLANTATION", 1120)
		self.doCheckWorkedResource("BONUS_SILK", "IMPROVEMENT_FORT", 1120)
		self.doCheckWorkedResource("BONUS_SILVER", "IMPROVEMENT_MINE", 880)
		self.doCheckWorkedResource("BONUS_SILVER", "IMPROVEMENT_FORT", 880)
		self.doCheckWorkedResource("BONUS_SPICES", "IMPROVEMENT_PLANTATION", 1120)
		self.doCheckWorkedResource("BONUS_SPICES", "IMPROVEMENT_FORT", 1120)
		self.doCheckWorkedResource("BONUS_STONE", "IMPROVEMENT_QUARRY", 750)
		self.doCheckWorkedResource("BONUS_STONE", "IMPROVEMENT_FORT", 750)
		self.doCheckWorkedResource("BONUS_SUGAR", "IMPROVEMENT_PLANTATION", 1120)
		self.doCheckWorkedResource("BONUS_SUGAR", "IMPROVEMENT_FORT", 1120)
		self.doCheckWorkedResource("BONUS_URANIUM", "IMPROVEMENT_MINE", 880)
		self.doCheckWorkedResource("BONUS_URANIUM", "IMPROVEMENT_FORT", 880)
		self.doCheckWorkedResource("BONUS_WHALE", "IMPROVEMENT_WHALING_BOATS", 560)
		self.doCheckWorkedResource("BONUS_WHEAT", "IMPROVEMENT_FARM", 1120)
		self.doCheckWorkedResource("BONUS_WHEAT", "IMPROVEMENT_FORT", 1120)
		self.doCheckWorkedResource("BONUS_WINE", "IMPROVEMENT_WINERY", 1120)
		self.doCheckWorkedResource("BONUS_WINE", "IMPROVEMENT_FORT", 1120)

	def doCheckWorkedResource(self, bonus, improvement, randomInt):
            
		iBonus = CvUtil.findInfoTypeNum(gc.getBonusInfo, gc.getNumBonusInfos(), bonus)
        
		if (iBonus == -1):
			return
        
		lValidPlots = self.getPlotListbyBonus(iBonus)
        
		if len(lValidPlots) == 0:
			return
                
##If you have the requisite improvement (incl. fort) or if the plot is being worked by a City, continue.
                        
			for plot in lValidPlots:
				P = False
                
				if plot.getImprovementType() == CvUtil.findInfoTypeNum(gc.getImprovementInfo, gc.getNumImprovementInfos(), improvement):
					P = True
				elif plot.isCity():
					P = True

				if P == True:
					if self.getRandomNumber(randomInt) == 0:
                    
						pBonusInfo = gc.getBonusInfo(iBonus)
                    
						plot.setBonusType(-1)
                    
						szTitle = localText.getText("TEXT_KEY_NEXT_WAR_RESOURCE_DEPLETED_TITLE", ())# (pBonusInfo.getDescription(), plotgetX(), plot.getY()))
                        #szText = localText.getText("TEXT_KEY_NEXT_WAR_RESOURCE_DEPLETED", (pBonusInfo.getDescription(), plot.getX(), plot.getY()))
                        #Not sure what the above commented out code for (debugging?) -- it was commented out in PM's original NextWar code.  JKP1187
                        
						CyInterface().addMessage(plot.getOwner(), False, gc.getEVENT_MESSAGE_TIME(), szTitle, "AS2D_DISCOVERBONUS", InterfaceMessageTypes.MESSAGE_TYPE_MINOR_EVENT, pBonusInfo.getButton(), gc.getInfoTypeForString("COLOR_GREEN"), plot.getX(), plot.getY(), True, True)		
				else:
					return
				

### Below are additional functions necessary to the activity of the resource depl'n code:

	def getPlotListbyBonus(self, iBonus):
		lPlots = []
		totalPlots = gc.getMap().numPlots()
		
		for i in range(totalPlots):
			plot = gc.getMap().plotByIndex(i)
			iOwner = plot.getOwner()
			if (iOwner != -1):
				if plot.getBonusType(gc.getPlayer(iOwner).getTeam()) == iBonus:
					lPlots.append(plot)
		return lPlots

	def getRandomNumber(self, int):
		return gc.getGame().getSorenRandNum(int, "Next War")


# BUG - Next War Merge - start
	def initScriptData(self):
		
		# Set default script data manually since we need defaults for all values in the array before any functions can be called on them
		iDefaultNumNukesFired = 0
		SdToolkit.sdSetGlobal(SD_MOD_ID, SD_NUKES_ID, iDefaultNumNukesFired)
		
	def getGameNumNukes(self):
		return SdToolkit.sdGetGlobal(SD_MOD_ID, SD_NUKES_ID)

	def setGameNumNukes(self, iValue):
		SdToolkit.sdSetGlobal(SD_MOD_ID, SD_NUKES_ID, iValue)
		self.checkNukeStuff(iValue)
		
	def changeGameNumNukes(self, iChange):
		self.setGameNumNukes(self.getGameNumNukes() + iChange)
# BUG - Next War Merge - end[/COLOR]

So I guess I'm asking if that is correct? And do I have to do something similar to my DiplomacyGameUtils.py?
 
Looks perfect. Just run some test games to see if there are any more python exceptions or bugs.

And no, you only need event handler's for the Event Manager.
 
Delete all the duplicate code copied from CvEventManager. Delete from this line (inclusive):

Code:
#################### ON EVENT MAP ######################

up to but not including this line:

Code:
def onLoadGame(self, argsList):

To be clear, keep that onLoadGame(...) line in your code.

Otherwise, that looks good so far. How's it working? Post your DiplomacyGameUtils.py so we can tell what needs to be done. ;)
 
Delete all the duplicate code copied from CvEventManager. Delete from this line (inclusive):

Code:
#################### ON EVENT MAP ######################

up to but not including this line:

Code:
def onLoadGame(self, argsList):

To be clear, keep that onLoadGame(...) line in your code.

Otherwise, that looks good so far. How's it working? Post your DiplomacyGameUtils.py so we can tell what needs to be done. ;)

Alright, so you are just saying delete everything froma nd including that ON EVENT MAP LINE up to the def onLoadGame line? I have some code added in there though (for next one are for the Olympic Games, which is just a modified version of The_J's Circus Hagenbeck).

Here's the DiplomacyGameUtils.py info though:

Code:
## Sid Meier's Civilization 4
## Copyright Firaxis Games 2005
##
## Implementaion of miscellaneous game functions

import CvUtil
from CvPythonExtensions import *
import CvEventInterface

# globals
gc = CyGlobalContext()

class DiplomacyGameUtils:
	def cannotConstruct(self,argsList):
		pCity = argsList[0]
		eBuilding = argsList[1]
		bContinue = argsList[2]
		bTestVisible = argsList[3]
		bIgnoreCost = argsList[4]
		
		# player can't build an arcology if they have shielding or advanced shielding
		if eBuilding == gc.getInfoTypeForString("BUILDING_ARCOLOGY"):
			if pCity.getNumRealBuilding(gc.getInfoTypeForString("BUILDING_ARCOLOGY_SHIELDING")) or pCity.getNumRealBuilding(gc.getInfoTypeForString("BUILDING_DEFLECTOR_SHIELDING")):
				return True
		
		# player can't build shielding if they have advanced
		if eBuilding == gc.getInfoTypeForString("BUILDING_ARCOLOGY_SHIELDING"):
			if pCity.getNumRealBuilding(gc.getInfoTypeForString("BUILDING_DEFLECTOR_SHIELDING")):
				return True

		return False

		
	def getUpgradePriceOverride(self, argsList):
		iPlayer, iUnitID, iUnitTypeUpgrade = argsList
		
## Leonardo's Workshop Start ##

		pPlayer = gc.getPlayer(iPlayer)
		pUnit = pPlayer.getUnit(iUnitID)

		iPrice = gc.getDefineINT("BASE_UNIT_UPGRADE_COST")
		iPrice += (max(0, (pPlayer.getUnitProductionNeeded(iUnitTypeUpgrade) - pPlayer.getUnitProductionNeeded(pUnit.getUnitType()))) * gc.getDefineINT("UNIT_UPGRADE_COST_PER_PRODUCTION"))

		if ((not pPlayer.isHuman()) and (not pPlayer.isBarbarian())):
			pHandicapInfo = gc.getHandicapInfo(gc.getGame().getHandicapType())
			iPrice = iPrice * pHandicapInfo.getAIUnitUpgradePercent() / 100
			iPrice = iPrice * max(0, ((pHandicapInfo.getAIPerEraModifier() * pPlayer.getCurrentEra()) + 100)) / 100

		iPrice = iPrice - ((iPrice * pUnit.getUpgradeDiscount()) / 100)

		b_Leonardo = gc.getInfoTypeForString("BUILDING_LEONARDO")
		obsoleteTech = gc.getBuildingInfo(b_Leonardo).getObsoleteTech()
		if ( gc.getTeam(pPlayer.getTeam()).isHasTech(obsoleteTech) == false or obsoleteTech == -1 ):
			for iCity in range(pPlayer.getNumCities()):
				ppCity = pPlayer.getCity(iCity)
				if ppCity.getNumActiveBuilding(b_Leonardo) == true:
					iPrice = ((gc.getDefineINT("BASE_UNIT_UPGRADE_COST"))/2)
					iPrice += (((max(0, (pPlayer.getUnitProductionNeeded(iUnitTypeUpgrade) - pPlayer.getUnitProductionNeeded(pUnit.getUnitType()))) * gc.getDefineINT("UNIT_UPGRADE_COST_PER_PRODUCTION")))/2)

					if ((not pPlayer.isHuman()) and (not pPlayer.isBarbarian())):
						pHandicapInfo = gc.getHandicapInfo(gc.getGame().getHandicapType())
						iPrice = ((iPrice * pHandicapInfo.getAIUnitUpgradePercent() / 100)/2)
						iPrice = ((iPrice * max(0, ((pHandicapInfo.getAIPerEraModifier() * pPlayer.getCurrentEra()) + 100)) / 100)/2)

						iPrice = ((iPrice - ((iPrice * pUnit.getUpgradeDiscount()) / 100))/2)

		if pUnit.isHasPromotion(gc.getInfoTypeForString('PROMOTION_LEADER')):

			iPrice = 0
		
		return iPrice

## Leonardo's Workshop End ##	

## Leonardo's Workshop Start ##	
#
## NOTE: You need to comment out (add a # before) the original return -1 (done below) ##
#
#		return -1	# Any value 0 or above will be used
#
## Leonardo's Workshop End ##

There you go.
 
Uh, I got a CTD when I started the game.

I loaded the mod, started a new game (custom game, random civ, small map) and the game started up, initialized and all that, then when it finished setting up CTD. :sad:

I'll try it again in case the civ or something like that caused the crash.
 
Back
Top Bottom