from __future__ import print_function	# this should make the game version-independent
from tools.choose import choose		# primary input method
import rules.dr_default as rules	# the dance rules
import json	# for interface with dance system
import random 	# for use in treeAI
import copy # used in intro

# The War of the Willows
# Part One: [Untitled]



# SECTION I: THE INTRO

def intro():
	print("""

		----------------------
		THE WAR OF THE WILLOWS
		----------------------

	""")
	# first establish a container for the world data
	# is this terrible code?
	character = {
			"sanctity" : 0,
			"anger" : 0,
			"sorrow" : 0,
			"peace" : 0,
			"determination" : 0
			}

	player = copy.deepcopy( character )
	grove = copy.deepcopy( character )
	citadel = copy.deepcopy( character )

	player["sanctity"] = 5.0
	player["anger"] = 0.0
	player["sorrow"] = 5.0
	player["peace"] = 0.0
	player["determination"] = 10.0

	citadel["sanctity"] = 0.0
	citadel["anger"] = 10.0
	citadel["sorrow"] = 10.0
	citadel["peace"] = 5.0
	citadel["determination"] = 50.0

	grove["sanctity"] = 100.0
	grove["anger"] = 50.0
	grove["sorrow"] = 20.0
	grove["peace"] = 30.0
	grove["determination"] = 50.0

	game = { 
			"player" : player,
			"citadel" : citadel, 
			"grove" : grove, 
		}
	# Introduce the scene
	print("""
1	Whenever a person dies,
	you will build a pyre for them.
	Say prayers to their soul.

2	If the sacerdos determines
	that their body is unclean,
	it will be placed on the pyre immediately.

3	If the sacerdos determines, however,
	that their body is not unclean,
	it will be bathed in rose-water,
	veiled in undyed linen
	and placed on the pyre.

4	Gather all sorts of good things:
	food, drink, and instruments of pleasure.
	After lighting the fire, you will enjoy them.
	Everything that you do not consume,
	you will burn.""")

	raw_input()
	print("""
5	Once the festival has begun,
	no art should be performed
	which has ever been performed in the past
	or will ever be performed in the future.
	All songs and dances must be ecstatic.
	Any poem or image written for the festival
	must be burned in the fire.
	So no funeral-art will be made of metal or stone 
	or anything that does not burn.

6	The festival will end
	when the fire has died of its own accord.
	Do not smother it with dirt or water.
	While the fire is burning,
	no-one will join or leave the festival.

7	When the fire has died,
	the bones of the deceased
	will be gathered together
	and ground to a fine powder.
	They will be mixed with the ashes of the fire,
	the feces of the revelers,
	and good loamy soil,
	in equal parts.

8	You will put this mixture into a hole
	and set willow-root to it.
	This tree will be the grave of the deceased.
	It will not be marked by name.
	""")
	raw_input()
	print("""
		- Edicts, 6:5
	""")
	raw_input()

	print("""
	SO WE ARE FATED DEATH BY WILLOWS:

	We broke with ancient covenant,
	grew unthoughtful and wicked,
	fell away from worship of our ancestors,
	incurred their sudden and mighty wrath.
	Their bodies came alive again,
	monstrous, hungering for blood,
	and we are entirely without hope.
	""")
	raw_input()

	# make a narrative queue

	# Question One
	print("""
	And as for me... what do I want?
	""")
	choice = choose( "survival", "forgiveness", "love", "power" )
	if choice == "survival":
		print("""
		Ancestor or no ancestor,
		if they trap me
		I won't hold back.
		""")
		game["player"]["sanctity"] += 0
		game["player"]["sorrow"] += 10
		game["player"]["peace"] += 30
		game["player"]["determination"] += 5
		game["player"]["anger"] += 20
	elif choice == "forgiveness":
		print("""
		This couldn't be worse.
		They won't even listen to us!
		""")
		game["player"]["sanctity"] += 10
		game["player"]["anger"] += 5
		game["player"]["sorrow"] += 15
		game["player"]["peace"] += 15
	elif choice == "love":
		print("""
		It's all so beautiful, isn't it,
		in the end?
		""")
		game["player"]["sanctity"] += 5
		game["player"]["anger"] += 0
		game["player"]["sorrow"] += 20
		game["player"]["peace"] += 20
	elif choice == "power":
		print("""
	You feel that you're not as strong
	as you once were.

	But then again,
	maybe you're stronger than ever.

		""")
		game["player"]["sanctity"] -= 5
		game["player"]["anger"] += 30
		game["player"]["peace"] += 20
	else:
		print( "wut" )
	raw_input()

	# Question Two
	print("""
	Before leaving, I make sacrifices to...
	
	Nyeru, tree-cat of freedom?
	Hobark, Witch-Queen of the Afterlife?
	Athena, goddess of knowledge and victory?
	The geneus of my ancestors?
	Vordak, King of Fire?
	""")
	choice = choose("Nyeru", "Hobark", "Athena", "geneus", "Vordak")
	if choice == "Nyeru":
		print("""
		Nyeru whispers, "Sacrifice to someone else."
		""")
	elif choice == "Hobark":
		print("""
		Six corpses hung up to rot in the catacombs.
		I among them, dagger upraised
		to the mute human screaming,
		thrashing gainst its bonds --
		""")
		game["player"]["sanctity"] += 5
		game["player"]["sorrow"] += 20
		game["player"]["anger"] += 25
	elif choice == "Athena":
		print("""
		Peace be upon you,
		grant your peace to me,
		Athena high goddess,
		thy wisdom be eternal.

		Inspire me to victory,
		let me not sallow,
		but rise fighting to burn high
		and do what is necessary.
		""")
		game["player"]["anger"] += 10
		game["player"]["peace"] += 30
		game["player"]["sorrow"] += 20
	elif choice == "geneus":
		print("""
		The women veil themselves in black
		and repeat the names of all the ancestors they remember.
		The men forget themselves in misery,
		tearing their clothes and pouring dirt in their hair.

		The priests cut the throats
		of ten white cows and ten white bulls,
		ten female lambs and ten male lambs,
		thirty sheep and two children,
		throw salt in the sea,
		divide the parts
		and offer them on the fire.

		I go down to join them,
		I give myself up.
		The scrolls of my ancestors' names...

		The guardian of my family...
		is turned against us?
		
		Three shooting stars that night,
		reflections on the waves...
		sails of a single boat...
		""")
		game["player"]["sanctity"] += 10
		game["grove"]["anger"] -= 20
		game["player"]["sorrow"] += 20
		game["player"]["peace"] += 10
	elif choice == "Vordak":
		print("""
		A black bull and a red bull,
		three calves and a white goat,
		burnt live upon Lebanon cedar.
		White-green flash of copper powder --
		the King of Fire accepts his offering.
		""")
		game["player"]["anger"] += 40
		game["player"]["peace"] += 10
		game["player"]["sorrow"] += 10
		game["player"]["determination"] += 5
	raw_input()

	# Question Three
	print("""
	I should take a luck charm.
	""")
	choice = choose( "rose", "coin", "star", "locket" )
	
	if choice == "rose":
		print("""
		A late lover's gift --
		The twilight of our age ---
		How I wish I could have laid in bed with you
		one morning more...
		""")
	elif choice == "coin":
		print("""
		Ain't no telling what matters.
		""")
	elif choice == "star":
		print("""
		Some things are still holy.
		They must be.
		""")
	elif choice == "locket":
		print("""
		Their images inside:
		this is who you must protect.
		""")
	raw_input()

	print("""
	From here, we can oversee
	the whole Westlands,
	the great Plains of Avignor,
	now fogged with marsh.
	
	And the song they bled,
	great trees out of the ancient lands.
	
	They ripped a child in half.

	Man threw burning oil on one 'em
	and it stood before his home
	while it burned to pillar of black ash.
	He didn't last the night,
	nor his little kids.

	Came they upon the library
	ripped each book to shreds,
	slept that night in the confetti.
	""")
	raw_input()

	# Some information about your choices.
	if game["citadel"]["anger"] < game["player"]["anger"]:
		citadel["peace"] -= 1 # because of your influence
		print("""
		Love is a word for the weak:
		let them hear it stamped out!

		We will not be annihilated because of love!
		""")
	elif game["player"]["anger"] < game["citadel"]["anger"]:
		game["player"]["sorrow"] += 1
		print("""
		"Love is a word for the weak:
		let them hear it stamped out!

		"We will not be annihilated because of love!"
		""")
	else:
		print("""
		The world seems strange to you.

		Are you asleep?
		""")

	if game["player"]["peace"] > game["grove"]["peace"]:
		game["player"]["peace"] += 2
		game["grove"]["peace"] += 2
		game["citadel"]["peace"] += 2
		print("""
		Have no fear for this.

		It is a matter of mistakes.

		Let us be grateful.
		""")
	elif game["player"]["peace"] == game["grove"]["peace"]:
		game["player"]["peace"] += 1
		game["grove"]["peace"] += 1
		game["citadel"]["peace"] += 1
		print("""
		A good sign appears in the eastern sky.

		Your little boy tells you about it the next day.
		""")
	else:
		print("""
		The grasses so tremble...
		all the willows, their pink flashes...
		upon the hillside, upon the fields...
		they besiege us so gently,
		they sway in repose...
		""")

	raw_input()

	print( """
		This was autumn,
		and the leaves of the maples were yellow.
		The kingdom was white and amber that year;
		the sky was clear blue.
		And their white barks upon us,
		their twisting roots and their
		white whips of flower,
		they tore the stones from our walls
		and flung them down on the city,
		brought the castle to earth,
		dissolved our entire architecture
		and besieged us here in the citadel.
		We defend it with fire-arrows and axe-heads,
		but they are numerous beyond counting
		and our wounded number more than our strong.

		Your children are inside.
		Your brothers and sisters,
		your whole monstrous society:
		you have broken the covenant.

		They put an axe in your hand.
		Can you wield it?
		Can you wield it against the tree whose flesh
		is the flesh of your ancestors?
		""")
	raw_input()




	return game



# SECTION II: THE DANCE

# Functions for getting choices

def getInPlayer( dance_open ):
	# give short names to relevant dance variables
	lastMove = dance_open["0"]["choice"]
	dist = dance_open["game"]["d"]
	breath = dance_open["0"]["calm"] / dance_open["0"]["air"]
	options = []
	opts = {}
	phraseList = []

	# touch/strike
	if dist <= 2 and dance_open["0"]["touch"]:
		phraseList.append("Do you swing your broad-bladed axe?")
		options.append("strike")

	# advance/move closer
	if dance_open["0"]["advance"]:
		phraseList.append("Do you move closer to the tree?")
		options.append("advance")

	# retreat/flee
	if dist <= 4 and dance_open["0"]["retreat"]:
		phraseList.append("Do you distance yourself from the tree?")
		options.append("distance")

	# evade
	if dist <= 2 and dance_open["0"]["evade"]:
		phraseList.append("Do you put yourself on guard against an attack?")
		options.append("evade")

	# breathe
	if dance_open["0"]["breathe"]:
		phraseList.append("Do you take a moment to catch your breath?")
		options.append("breathe")

	# tease
	if dance_open["0"]["jest"]:
		phraseList.append("Do you shout out an urgent prayer?")
		options.append("pray")

	# print the options
	for item in phraseList:
		print("		{0}".format( item ))

	# get the choice
	choice = choose( *options )

	# resolve aliases
	if choice == "distance":
		choice = "retreat"
	elif choice == "strike":
		choice = "touch"
	elif choice == "pray":
		choice = "jest"
	return choice

def treeAI( dance_open ):
	"""
	Sanctity should be between 0 and 1,
	representing the player's sacredness.
	Will return either "chill" or "attack".
	"""
	# Calibration
	chillBase = 0 # (x-intercept) The chance of getting a chill if playerSanctity == 0
	minChance = 0.1 # The minimum chance of receiving a random chill.
	sanctityGradient = 1 # The rate of return on sanctity.

	# Shortnames
	lastMove = dance_open["1"]["choice"] # identifies own last move
	distance = dance_open["game"]["d"] # identifies distance
	playerSanctity = dance_open["0"]["sanctity"]

	# If the tree needs to breathe, it will do it no matter what.
	breath = dance_open["1"]["calm"] / dance_open["1"]["air"]
	if breath <= 0.25:
		if dance_open["1"]["choice"] != "breathe":
			return "breathe"

	# Similarly, if the tree is off-balance and forward-balanced, it retreats.
	if dance_open["1"]["balance"] > 0 and abs(dance_open["1"]["balance"]) > abs(dance_open["0"]["balance"]):
		if dance_open["1"]["choice"] != "breathe":
			return "breathe"
	
	# The equation for calculating the chance of a chill.
	chance = chillBase + playerSanctity * sanctityGradient
	if chance == 0: 
		chance = minChance

	# The big roll
	roll = random.random()
	choice = None
	if roll > chance:
		choice = "attack"
	else:
		choice = "chill"

	# A simple mechanism of alternating choices
	if choice == "attack":
		if lastMove != "advance":
			return "advance"
		else:
			return "touch"
	elif choice == "chill":
		if lastMove != "breathe":
			return "breathe"
		else:
			return "jest"

def justice( dance_open ):
	"""
	Modifies a dance game
	according to the laws governing sanctity:
	pray frequently and never attack ancestral incarnations.
	"""
	# Calibration
	sanctityInterest = 0.03 # determines how quickly praying increases sanctity

	# Equations
	if dance_open["0"]["choice"] == "jest":
		dance_open["0"]["sanctity"] += dance_open["0"]["sanctity"] * sanctityInterest
	elif dance_open["0"]["choice"] == "strike":
		dance_open["0"]["sanctity"] = 0

	return dance_open


# Functions for displaying information

def distanceCheck( dance_open ):
	dist = dance_open["game"]["d"]
	if dist == 0:
		print("""
		Branches enwrap you like muscular snakes,
		threatening to bind you entirely
		as willow-whips lash your face.
		You wriggle between them,
		fighting for freedom.
		""")
	elif abs(dist) == 1:
		print("""
		You dance within the sphere of tree-limb,
		dodging the occasional swung branch.
		From here you could mount an attack of your own,
		but it's only a matter of time
		until you make a mistake.
		""")
	elif abs(dist) == 2:
		print("""
		You stand just beyond the tree's reach,
		in the swirl of its pollen and petals
		but beyond the swing of its limbs --
		nor are you able to touch it from here.
		""")
	elif abs(dist) == 3:
		print("""
		You stand several paces from the tree,
		its grim countenance at play in the square
		where it has been ripping up the carefully-laid flagstones
		and heaving them into the storefronts.
		""")
	else:
		print("""
		You look upon the willow from a safe distance
		and it seems almost peaceful:
		the malevolence of a child's tantrum
		turning innocently against any object.
		""")

def willCheck( dance_open ):
	playerWill = dance_open["0"]["will"]
	playerEarth = dance_open["0"]["earth"]
	treeWill = dance_open["1"]["will"]
	treeEarth = dance_open["1"]["earth"]

	if playerWill <= playerEarth * 0.1:
		print("""
		You're about to black out.
		""")
	elif playerWill <= playerEarth * 0.25:
		print("""
		Your body won't move right.
		""")
	elif playerWill <= playerEarth * 1 / 3:
		print("""
		This is probably going to be permanant.
		""")
	elif playerWill <= playerEarth * 0.5:
		print("""
		Something doesn't feel right in your chest.
		""")
	elif playerWill <= playerEarth * 2 / 3:
		print("""
		Your vision swims in and out.
		""")
	elif playerWill <= playerEarth * 0.75:
		print("""
		Your ears are ringing.
		""")
	elif playerWill <= playerEarth * 0.9: 
		print("""
		Your entire body hurts.
		""")

	if playerWill == 0:
		print("""
		...
		""")

	if treeWill <= treeEarth * 0.25:
		print("""
		You've cut a deep gouge
		into the last trunk.
		""")
	elif treeWill <= treeEarth * 0.5:
		print("""
		The first trunk is a stump.
		The second is vulnerable.
		""")
	elif treeWill <= treeEarth * 0.75:
		print("""
		You've made a start
		on one of the main trunks.
		""")
	elif treeWill <= treeEarth * 0.9:
		print("""
		Whips have been torn away
		and branches hacked off.
		""")

def calmCheck( dance_open ):
	playerCalm = dance_open["0"]["calm"]
	playerAir = dance_open["0"]["air"]
	percent = playerCalm / playerAir

	if percent <= 0:
		print("""
		You feel paralyzed by exhaustion.
		""")
	elif percent <= 0.1:
		print("""
		You're gasping for breath.
		""")
	elif percent <= 0.25:
		print("""
		Gosh!
		Could use a breather.
		""")
	elif percent <= 1/3.0:
		print("""
		Don't think about mistakes.
		You're supposed to
		already know what to do.
		""")
	elif percent <= 0.5:
		print("""
		You feel winded.
		""")
	elif percent <= 1/6.0:
		print("""
		This is a nice workout.
		""")
	elif percent <= 0.75:
		print("""
		It's a nice day.
		""")
	elif percent <= 0.90:
		print("""
		You feel energetic.
		""")
	else:
		print("""
		Everything is at peace.
		Can't you see?
		""")
		

def heatCheck( dance_open ):
	playerHeat = dance_open["0"]["heat"]
	playerFire = dance_open["0"]["fire"]
	treeHeat = dance_open["1"]["heat"]
	treeFire = dance_open["1"]["fire"]
	if playerHeat + treeHeat != 0:
		difference = playerHeat / ( playerHeat + treeHeat )
	else:
		difference = 0

	if playerHeat < treeHeat and treeHeat >= treeFire / 2:
		print("""
		No pitiful mortal
		can comprehend an ancient's rage.
		""")
	if playerHeat > treeHeat and playerHeat >= playerFire / 2:
		print("""
		This beast will know your wrath!
		""")

	if playerFire == playerHeat:
		print("""
		Your head is buzzing.
		You can't see straight.
		""")
	if treeFire == treeHeat:
		print("""
		You can see a place where the bark is stripped off.
		You might be able to hit it there.
		""")

def balanceCheck( dance_open ):
	"""
	Notes on 3D representation of Balance/Water Dynamic:
	Imagine you have a ball of water in your stomach,
	right at your center of gravity.
	Every time you move, this ball follows you.
	How fast it catches up is determined by the size of your Water,
	which is represented by a bubble around you.
	Your ball cannot leave this bubble,
	and the closer it gets to the edge
	the more vulnerable you become.
	""" # Vulner Vulneir 
	playerBalance = dance_open["0"]["balance"]
	playerWater = dance_open["0"]["water"]
	treeBalance = dance_open["1"]["balance"]
	treeWater = dance_open["1"]["water"]
	# Remember that the goal of balance is to have the smallest abs-balance-as-a-percent-of-water (abaapow)
	playerRatio = abs( playerBalance ) / float( playerWater )
	treeRatio = abs( treeBalance ) / float( treeWater )
	difference = playerRatio - treeRatio
	# if playerRatio is lower (ie superior), difference will be negative
	# if treeRatio is lower, difference will be positive
		
	# aint no fuckin gentry

	# first assess the player's chances
	if difference < 0:
		print("""
		Your footing is good.
		Now you have the advantage.
		""")
	elif difference == 0:
		print("""
		Your mind is a void,
		ready to collapse in an instant
		into either victory or failure.
		""")
	else:
		print("""
		Your rhythm is off --
		""")
		if difference >= 1/3.0 :
			print("""
			Something's gone wrong in your head...
			terror washing over you.
			Whence this imbalance?
			""")
		if difference >= 2/3.0 :
			print("""
			You look like an fool!
			""")

	# assess the direction of the player's balance
	if playerBalance == 0:
		print("""
		The crowd holds its breath.
		""")
	elif playerBalance < 0:
		print("""
		Cries from the wall mock your cowardice,
		shouting, "Attack! Attack!"
		""")
	elif playerBalance > 0:
		print("""
		The worried onlookers urge you to retreat,
		calling, "Get back! Run away!"
		Your instincts tell you to flee.
		""")

	if playerRatio == 1:
		print("""
		You can bear it no longer:
		each step backward
		feels like murder.
		""")
	elif playerRatio == .9:
		print("""
		There must be some other way...
		If only you could see clearly...
		Violence cannot be really necessary.
		""")
	elif playerRatio == .75:
		print("""
		Don't you have a responsibility
		to protect the people of the city?
		""")
	elif playerRatio == .66:
		print("""
		These accusations of cowardice
		are really taking a toll on you.
		""")

def narrateActions( dance_open ):
	# Give short names to some key variables
	playerAct = dance_open["0"]["choice"]
	treeAct = dance_open["1"]["choice"]
	distance = dance_open["game"]["d"]
	advantage = dance_open["0"]["balance"]/dance_open["0"]["water"] - dance_open["1"]["balance"]/dance_open["1"]["water"] 
	futureD = abs(rules._get_future_d( dance_open )) # Technically illegal.
	
	# Determine whether a position switch has happened.
	if treeAct == "advance" and playerAct == "advance" and abs(distance) == 1:
		print("""
		You determine to dance through the tree's defenses,
		skillfully avoiding entanglement
		and perhaps landing a few strikes,
		emerging unharmed on the other side.
		""")

	# Establish whether the tree is presently hostile.
	treeIsAggressive = True
	if treeAct == "advance" or treeAct == "touch":
		treeIsAggressive = False
	
	# Establish whether the tree will successfully strike the player.
	treeLandsAttack = False
	if treeAct == "touch" and playerAct != "evade":
		if abs( futureD ) <= 1:
			treeLandsAttack = True
	if treeAct == "advance" and playerAct != "evade":
		if futureD == 0:
			treeLandsAttack = True
	if treeLandsAttack == True:
		print("""
		Fuck.
		""")

	# Narrate the player's actions
	if playerAct == "advance":
		if futureD == 0 and distance == 0:
			print("""
		You press your attack with a fury,
		swinging wildly at the limbs all around you.
			""")
		else:
			print("""
		You charge forward, axe upheld,
		""")
		if futureD > 2:
			print("""
		towards the tree.
			""")
		elif futureD >= 1:
			print("""
		into the tree's embrace.
			""")

	if playerAct == "touch":
		print("""
		You bring your axe down""")
		if futureD > 1:
			print("""
		and it swings through empty air.

		The tree is too far away.
			""")
		else:
			if advantage > 0:
				print("""
		and it slices clean through the limb.
				""")
			elif advantage == 0:
				print("""
		and it bites deep into the wood-flesh.
				""")
			else:
				print("""
		and it glances off in a flash of bark.
				""")
	
	elif playerAct == "breathe":
		print("""
	You close your eyes and remain motionless.
	All thoughts leave your mind.
	""")
		if treeLandsAttack:
			print("""
	Before you're even aware of it,
	you give yourself up to pain.
			""")
	elif playerAct == "retreat":
		print("""
	You backpedal quickly,
	trying to stay out of its reach.
	""")
	elif playerAct == "evade":
		if abs( futureD ) <= 1 and treeAct == "touch":
			print("""
		You manage to dodge a series of swiftly-swung branches.

		Gosh! That was close!
		""")
		elif futureD == 0 and treeAct == "advance":
			print("""
		You manage to avoid the bulk of the tree's harassment.
		""")
		else:
			print("""
		You ready yourself for an attack,
		but none comes your way.
			""")
	elif playerAct == "jest":
		print("""
	Hao yumm ho hai!
	We bask the day away.
	Good tree, don't cry
	cause we forgot your
	ancient mystery,
	for TREE, we do love you
	& we sorrow for you.

	Please don't do us evil.
	Don't destroy our home.
	""")

	raw_input()

	# Narrate the tree's action.
	if treeAct == "advance":
		if dance_open["game"]["d"] == 0 and futureD == 0:
			print("""
		The tree redoubles its brutal attack,
		crushing and beating you from every direction.
		""")
		else:
			print("""
		The tree trundles closer to you,
		roots tearing up flagstones.
		""")

	if treeLandsAttack == True:
		if advantage > 0:
			print("""
			Whips harass you from every direction,
			branches tear at your skin.
			""")
		elif advantage == 0:
			print("""
			A branch strikes you in the head,
			and other blows land on your arms and legs,
			attacked from every direction.
			""")
		elif advantage < 0:
			print("""
			A massive branch strikes you right in the body.
			""")
	if treeLandsAttack == False and treeAct == "touch":
		print("""
		The tree thrashes in rage,
		throwing stones about.
		""")

	if treeAct == "breathe":
		print("""
		The tree sparkles in the sunlight.
		It seems so peaceful...
		""")
	elif treeAct == "jest":
		print("""
		A subtle harmony emanates from the tree,
		a clear, high halo of melody.
		""")
	elif treeAct == "retreat":
		print("""
		The tree trundles away from you,
		leaving a trail of destruction behind.
		""")
	raw_input()

# Misc. functions for managing the dance/game relationship
def danceContinues( dance ):
	"""
	Checks to see whether the dance is over.
	"""
	gameover = False

	if dance["0"]["will"] <= 0:
		print("""
		I can't --
		""")
		gameover = True
		raw_input()

	if dance["1"]["will"] <= 0:
		print("""
		The tree has been utterly destroyed,
		cut down to the trunk,
		shattered in your rage!

		Your muscles burn and shine!
		""")
		raw_input()
		print("""
		Your head --
		""")
		gameover = True
		raw_input()

	if dance["game"]["gameover"] == 1:
		print("""
		-- nothing but a white haze --
		""")
		if gameover != True:
			gameover = True
			print("""
			Something has gone wrong.
			""")
		raw_input()
	
	if dance["0"]["sanctity"] >= 1:
		print("""
		- - -  holy  - - -
		""")
		gameover = True
		raw_input()


	if gameover == True:
		return False
	else:
		return True


def setupDance( game ):
	"""
	Rules for converting game to dance.
	"""

	# Setup Sanctity
	totalSanctity = 0
	for key in game:
		totalSanctity += game[key]["sanctity"]
	playerSanctity = ( game["player"]["sanctity"] / totalSanctity )

	playerEarth = 10
	playerAir = 10
	playerFire = 10
	playerWater = 10
	treeEarth = 20
	treeAir = 10
	treeFire = 10
	treeWater = 10

	# This tool returns player-as-a-percent-of-total in the specified quality
	def wump( key ):
		total = game["player"][key] + game["grove"][key]
		if total == 0:
			ratio = 0
		else:
			ratio = game["player"][key] / total
		return ratio

	angerRatio = wump("anger")
	peaceRatio = wump("peace")
	determRatio = wump("determination")
	sorrowRatio = wump("sorrow")
	
	# Set up the Dance stats and inform the player of the situation.
	# Earth
	playerEarth += playerEarth * determRatio
	treeEarth += treeEarth * ( 1 - determRatio )
	if playerEarth > treeEarth:
		print("""
		You, a beast of bone and flesh
		in the prime of your life!
		How should wood and spirit
		presume to oppose you?
		""")
	elif playerEarth < treeEarth:
		print("""
		A tower of natural sinew,
		irresitable to your command or your muscle:
		only by blade and blast of flame
		could you hope to oppose it.
		""")
	else:
		print("""
		Intricate signs, graven on stone.
		Symbols and spirals, wiggling persons.
		Our empires have all crumbled before,
		been reborn and decayed anew...
		""")
	raw_input()

	# Air
	playerAir += playerAir * peaceRatio
	treeAir += treeAir * ( 1 - peaceRatio )
	if playerAir > treeAir:
		print("""
		Your head is high in the sky!
		You have read books!
		An ancestor ghost, an avatar of rage,
		surely is no better than you.
		""")
	elif playerAir < treeEarth:
		print("""
		To gently sway in the wind...
		this seems like a fantasy you've had all your life.
		To be so at peace!
		To drink water from deep roots!
		""")
	else:
		print("""
		The soft scent of pollen,
		whisp of leaf on the wind...
		""")
	raw_input()

	# Fire
	playerFire += playerFire * angerRatio
	treeFire += treeFire * ( 1 - angerRatio )
	if playerFire > treeFire:
		print("""
		Now let the rage flow through you.
		Your ancestor demands your subservience
		but doesn't hesitate to murder your cousins!
		Heads crushed like gourd-fruit!
		""")
	elif playerFire < treeFire:
		print("""
		The wrath of a god,
		flaming before your very eyes,
		the fury of an absent father!

		Your soul shrinks from your muscles.
		""")
	else:
		print("""
		I saw a whisp of flame, once,
		suspended in a brazen bowl.
		Held there by oil, diffusing some scent
		into the dark of a priestly tent...
		""")
	raw_input()

	# Water
	playerWater += playerWater * sorrowRatio
	treeWater += treeWater * ( 1 - sorrowRatio )
	if playerWater > treeWater:
		print("""
		Now, you know the truth:
		that all things are ultimately equal
		and the branching labyrinth of the future
		can be navigated with solumn dignity.
		""")
	elif playerWater < treeWater:
		print("""
		How does your soul tremble so?
		What wickedness has taken root in you?

		No, there's nothing wrong --
		""")
	else:
		print("""
		A ripple in a lake,
		mist veiled the bamboo,
		rain fell on the distant mountain flank...
		you saw the black bodies of the pyre
		floating up through the mist-veil
		and the cloud of the rushing storm...
		as a child...
		at the temple...
		the grain of the altar's step...

		Was it pine?
		""")
	raw_input()

	# Actually create the dance object
	dance = rules.set_stage( playerEarth, playerAir, playerFire, playerWater,
			treeEarth, treeAir, treeFire, treeWater,
			2, 0 )

	# Insert a special variable. See TreeAI
	dance = json.loads( dance )
	dance["0"]["sanctity"] = playerSanctity
	dance = json.dumps( dance )

	
	return dance

def modifyGame( game, dance ):
	"""
	Rules for modifying game
	in accordance with the results of the dance.
	Initial game will have values between 0 and 100
	for sanctity, sorrow, anger, peace, and determination.
	Dance will have primary stat ranges from 10-20.
	"""
	# Damage from combat
	willPercent = dance["0"]["will"] / dance["0"]["earth"]
	game["player"]["determination"] = game["player"]["determination"] * willPercent

	# Describes whether the tree's rampage continues.
	if dance["0"]["sanctity"] >= 1:
	# If the player got the good ending
		game["grove"]["determination"] -= 10 # You have earned respite
		game["grove"]["anger"] -= 10
		game["grove"]["peace"] += 15 # Because its generosity has been rewarded.
		game["player"]["peace"] += 15
		game["citadel"]["peace"] += 10
		game["citadel"]["sorrow"] += 10 # Because they realize what fools they've been.
		game["player"]["sanctity"] += 100
		print("""
		The trees have taken root,
		held off their assault.
		They wave gently in the breeze,
		in the rubble of our homes,
		in our well-plowed fields.

		Now we all know
		that we've been given a chance.
		""")
	elif dance["1"]["will"] <= 0:
	# If the player destroyed the tree
		game["grove"]["anger"] += 10
		print("""
		Burned its bones to boil water,
		looked from the parapet window
		as the great ranks of them
		tore stones from the walls,
		disassembled the gate
		of our last redoubt,
		with a cool, solid fury,
		fields pink to the sunset
		with the arcs of their flowers.
		""")
	else:
	# Otherwise, you failed
		game["citadel"]["determination"] -= 20
		game["citadel"]["sorrow"] += 10
		game["grove"]["sorrow"] += 10
		game["player"]["sorrow"] += 10
		print("""
		Awoke in the infirmary,
		slipping in and out...
		Saw a fragment of your wife, your daughter,
		her hand on your shoulder,
		her soft palm on your arm;
		you couldn't help but drift away.

		Heard someone screaming,
		Heard a gargantuan rumbling,
		fissure cross the floor,
		alone in the cell, unable to move,
		and stones began to fall from the ceiling.
		""")
	raw_input()
	return game

# One round of the encounter
def oneRound( dance_open ):
	"""
	Accepts a dance object,
	describes its state, gets input, modifies it,
	and returns the new function.
	"""
	# tell about the game state
	distanceCheck( dance_open )
	heatCheck( dance_open )
	willCheck( dance_open )
	calmCheck( dance_open )
	balanceCheck( dance_open )
	raw_input()

	# get the choices, then insert them into the game data
	playerChoice = getInPlayer( dance_open )
	dance_open = justice( dance_open )
	treeChoice = treeAI( dance_open )
	dance_open["0"]["choice"] = playerChoice
	dance_open["1"]["choice"] = treeChoice

	# tell about the actions and their success or failure
	narrateActions( dance_open )

	# Apply the effects of the ancestor's ethics.
	dance_open = justice( dance_open )

	# execute the choices
	dance_closed = json.dumps( dance_open )
	dance_closed = rules.turn( dance_closed )
	dance_open = json.loads( dance_closed )
	
	return dance_open

# Core game loop.
def terrace( game ):
	"""
	The core encounter game loop.
	"""
	
	# Use the game object to create a dance object
	dance = setupDance( game )
	dance_open = json.loads( dance )

	# Perform the dance until its conclusion
	while danceContinues( dance_open ):
		dance_open = oneRound( dance_open ) # the dance JSON will be modified and interpreted
	
	# Use the dance object to modify the game object
	game = modifyGame( game, dance_open )
	
	return game



# SECTION III: THE CODA
def coda( game ):
	"""
	This section is a zooming-out.
	Does not mention the player directly,
	but references their impact on the world.
	"""
	# First establish some short names
	sanctityTotal = game["player"]["sanctity"] + game["citadel"]["sanctity"] + game["grove"]["sanctity"]
	sanctityRatio = ( game["player"]["sanctity"] + game["citadel"]["sanctity"] ) / float(sanctityTotal)

	determTotal = game["player"]["determination"] + game["citadel"]["determination"] + game["grove"]["determination"]
	determRatio = ( game["player"]["determination"] + game["citadel"]["determination"] ) / float(sanctityTotal)
	
	angerTotal = game["player"]["anger"] + game["citadel"]["anger"] + game["grove"]["anger"]
	angerRatio = ( game["player"]["anger"] + game["citadel"]["anger"] ) / float(sanctityTotal)
	
	peaceTotal = game["player"]["peace"] + game["citadel"]["peace"] + game["grove"]["peace"]
	peaceRatio = ( game["player"]["peace"] + game["citadel"]["peace"] ) / float(sanctityTotal)
	
	sorrowTotal = game["player"]["sorrow"] + game["citadel"]["sorrow"] + game["grove"]["sorrow"]
	sorrowRatio = ( game["player"]["sorrow"] + game["citadel"]["sorrow"] ) / float(sanctityTotal)

	# Calculate peace prospects.
	if peaceTotal > angerTotal:
		print("""
		The land shining in the clear sky,
		the children breathing deep
		and looking to the distant mountains.

		'We can navigate this,' say the elders,
		'if we just remain calm.'
		""")
	elif peaceTotal < angerTotal:
		print("""
		The bristling of shield and armor,
		fire and axe-haft in the night,
		the irrevocable clustering
		where the gates begin to crumble.

		The walls buckle inward...
		""")
		raw_input()

		if determRatio < 0.5:
			print("""
		No, there is no surviving this lot.
		Your ancestors brought you into this world,
		and they will bring you out of it.

		There is no surviving,
		not for anybody.
		Three comets in the southern sky,
		they all died waiting
		for the repentance that never came.
		No willow ever said, "Enough,"
		for the covenant is absolute.
			""")
		elif determRatio > 0.5:
			print("""
		We will surely survive.
		Everything is malleable.
		
		Every situation can be navigated.
		Wisdom and grace and bravery
		can triumph over absurdity.
		""")
		else:
			print("""
		So often, survival is a coin toss.
		We speak of the victors of history
		and the forces that led them there,
		but we don't make myths of the wind and rain.
		A gust left or right:
		a general falls.

		A kingdom dies.
		""")
	else:
		print("""
		Three comets in the southern sky,
		their arms around our throats,
		children crying to the dawn.

		We don't know what could happen.
		Isolated incidents, sparring matches...
		things might tumble one way 
		or another.
		""")
	raw_input()

	# Narrate sorrow

	if sorrowTotal > angerTotal:
		print("""
		The blade fell from your hand.
		Blunt the steel edge!
		Let the walls crumble,
		let the roof collapse,
		why should I care?

		None of it matters!
		We're all senseless machines
		making senseless motions
		at a senselss creator!
		""")

	if sorrowTotal > sanctityTotal:
		print("""
		Took deep draughts of the wine-bowl,
		pored it out over your head,
		kicked dust on the altar of sacrifice,
		spat on all the idols...

		Let them come!
		Your child is dead!
		Let them come for you!
		Let them come!
		""")

	if sorrowTotal > peaceTotal:
		print("""
		Tearing their hair in the dust,
		robes flayed and dyed black,
		the noble women bear their breasts to the masses,
		the poor slobber over bright pamphlets,
		your knees on the shattered stone,
		your sideways fall...
		flopping in the ecstasy of humiliation...
		""")
	raw_input()

	# Narrate sanctity.
	if sanctityRatio > 0.5:
		print("""
		The others cannot comprehend your smile...
		the holy smile of a savior and prophet...
		your art remains a mystery.

		Smoke will rise from the hillside.
		""")
	elif sanctityRatio > 0.33:
		print("""
		Everyone's dying...
		So, why is it...
		so beautiful?

		Let them die.
		Let the smoke rise up...
		but...
		do... something...
		""")
	elif sanctityRatio > 0.25:
		print("""
		The groaning chant of the priest...
		The darkness pressing in all around...
		This is the crumbling of our age...
		And... should we accept it?
		Should we burn?
		""")
	elif sanctityRatio > 0.20:
		print("""
		There's a strip of red paper
		pinned to the chalk-board.
		A torn-up textbook on the floor.
		Blood-smear of child dragged down wall...
		you built a little altar there,
		a little pillar of flame...
		""")
	elif sanctityRatio > 0.15:
		print("""
		The flickering of a flame...
		seems to suggest something...
		The world is not over.
		Your soul is not dead.
		A whisper of mystery,
		too soft for hearing.
		""")
	elif sanctityRatio > 0.1:
		print("""
		The flickering of a flame...
		seems to suggest something...
		What whispers?
		What fingers of intuition..?
		The spirit speaks words to you,
		too soft for hearing.
		""")
	else:
		print("""
			Something you don't understand...
		""")
	raw_input()

# SECTION IV: MAIN

def start():
	# I
	game = intro()
	
	# II
	game = terrace( game )

	# III
	coda( game )


# Intimate Machines
