Some more debuging mostly. Got it to where you can play several battles in a row...
[asgard.git] / consolecontroller.py
blob84540ea98ccdf1b0f4e2e40ce6f7003a46bec91c
1 ########################################################
2 #Copyright (c) 2006 Russ Adams, Sean Eubanks, Asgard Contributors
3 #This file is part of Asgard.
5 #Asgard is free software; you can redistribute it and/or modify
6 #it under the terms of the GNU General Public License as published by
7 #the Free Software Foundation; either version 2 of the License, or
8 #(at your option) any later version.
10 #Asgard is distributed in the hope that it will be useful,
11 #but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 #GNU General Public License for more details.
15 #You should have received a copy of the GNU General Public License
16 #along with Asgard; if not, write to the Free Software
17 #Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18 ########################################################
19 from statistic import *
20 from os import listdir
21 from battle import *
22 from equiption import *
23 from fighter import *
24 from eventtype import *
25 import struct
26 import copy
27 import sys
28 import utilities
30 class ConsoleController:
31 def __init__(self,debug,battle,view):
32 self.__debug = debug
33 self.__battle = battle
34 self.__view = view
36 battle.setController(self)
37 battle.setView(view)
38 view.setController(self)
39 view.setBattle(battle)
41 self.__gameLoop()
43 def getBattleCommand(self,vp,hp,f):
45 command = []
47 print "\033[1;34m[SELCT]\033[1;0m Turn:" + f.getName() + "; HP:" + str(f.getStat("hp").getCurrent()) + "/" + str(f.getStat("hp").getMax())
49 self.__view.printEventTypeMenu(f)
50 n = raw_input("% ")
51 t = self.__battle.getEventType(f.getEventTypes()[int(n)-1])
53 if t.getName() == "quit":
54 sys.exit()
56 self.__view.printTargetSelectMenu(vp,hp)
57 n = raw_input("% ")
58 # Select Villain
59 if vp.sizeOfParty() - int(n) >= 0:
60 d = vp.getFighter(int(n)-1)
61 # Select Hero
62 else:
63 d = hp.getFighter(int(n)-vp.sizeOfParty()-1)
64 return [d,t]
66 def getMenuCommand(self):
68 self.__view.printStartupMenu()
70 n = raw_input("% ")
72 return int(n)
74 def getDebug(self):
75 return self.__debug
77 def setDebug(self,d):
78 self.__debug = d
80 def __gameLoop(self):
81 """Retrieves events from Parties and Executes all Events in queue per iteration"""
83 print "Asgard Free Software RPG - Testing Module"
85 self.loadStaticData(False)
87 while True:
88 choice = 0
89 while choice != 4:
90 choice = self.getMenuCommand()
92 if choice == 1:
93 self.unloadStaticData()
94 self.loadStaticData(True)
95 print "loaded..."
96 else:
97 if choice == 2:
98 print "Path to Save File: ",
99 path = sys.stdin.readline()
100 self.load("" + path.strip() + "")
101 print "loaded..."
102 print "============================================================="
104 elif choice == 3:
105 print "Path to Save File: ",
106 path = sys.stdin.readline()
107 self.save("" + path.strip() + "")
108 print "saved..."
109 print "============================================================="
111 elif choice == 4:
113 if self.__battle.getParty1().sizeOfParty() == 0:
114 print "No game loaded."
115 choice = 0
116 else:
117 self.createRandomBattle()
118 print "============================================================="
119 else:
120 sys.exit()
122 print "Battle Starts."
123 self.__view.printState()
125 # initialize the event checker boolean
126 wereEvents = False
128 while not self.__battle.isOver():
129 # next iteration
130 wereEvents = self.__battle.nextTurn()
132 # only print out state if something actually happened
133 if wereEvents:
134 self.__view.printState()
136 if self.__battle.getParty1().isAlive():
137 # sum exp from enemy party
138 exp = 0
139 for f in self.__battle.getParty2().getFighters():
140 exp += f.getStat("exp").getMax()
142 # hero party gets exp
143 self.__battle.getParty1().giveExp(exp)
145 print "Final Results"
146 print "============================================================="
147 self.__view.printParty(self.__battle.getParty1())
148 print "============================================================="
149 print "Victory Fanfare. Hand's party wins "+str(exp)+" exp!"
151 else:
152 print "Game Over. Asgard mourns."
154 # clear out the hero party - they're dead!
155 self.__battle.setParty1(None)
158 def load(self,savefile):
159 #clear party1 and it's fighters
160 self.__battle.setParty1(Party("Heroes"))
162 #open savefile
163 fptr = open(savefile,"rb")
165 fptr.seek(0,2)
166 size = fptr.tell()
168 fptr.seek(0,0)
170 # number of bytes read in so far
171 readin = 0
173 while readin != size:
174 #read in struct descriptor
175 type = ord(fptr.read(1))
176 readin += 1
178 if type == 0:
179 fstring = fptr.read(struct.calcsize("20s20s20s20s20s20sB7I6B"))
180 readin += struct.calcsize("20s20s20s20s20s20sB7I6B")
183 fighter = Fighter(binary=fstring)
185 self.__battle.getParty1().addFighter(fighter)
187 #close savefile
188 fptr.close()
190 def save(self,savefile):
191 """ Writes all playable fighters to savefile. """
192 # Retrieving playable fighters
193 fighters = self.__battle.getParty1().getFighters()
195 # Writing each fighter to savefile
196 fptr = open(savefile,"wb")
197 for f in fighters:
198 # Convert fighter f to binary string
199 binStr = f.toBinaryString()
201 # Write binary string to savefile
202 fptr.write(binStr)
204 fptr.close()
206 def createRandomBattle(self):
207 self.__battle.setParty2(Party("Villains"))
208 partySize = int(random.gauss(2,1))
209 for x in range(0, partySize):
210 monstI = random.randint(0,len(self.__battle.getMonsters())-1)
212 monster = copy.deepcopy(self.__battle.getMonsters()[monstI])
213 self.__battle.getParty2().addFighter(monster)
215 for f in self.__battle.getParty1().getFighters():
216 spd = f.getStat("spd").getCurrent()
217 tom = round((1/float(spd)*100))
218 f.getStat("tom").setCurrent(tom)
219 f.getStat("tom").setMax(tom)
221 self.__battle.setCurrentTime(0)
225 def loadStaticData(self,newGame):
226 """Load static game data: eventtypes, fighters (with stats and jobs)"""
229 dir = listdir('./data/eventtypes/')
231 self.__battle.setEventTypeList([])
233 for et in dir:
235 if et[0] == ".":
236 continue
238 etTree = libxml2.parseFile('./data/eventtypes/'+et)
240 #uncomment these
241 eventType = EventType(etTree)
242 self.__battle.getEventTypeList().append(eventType)
244 ### Loading parties ###
245 self.__battle.setParty1(Party("Heroes"))
247 ### Loading fighters ###
248 dir = listdir('./data/fighter/')
249 for f in dir:
251 # f cannot be a "." file
252 if f[0] == '.':
253 continue
255 # Create Fighter XML Tree
256 fTree = libxml2.parseFile('./data/fighter/'+f)
258 # Create Fighter Object
259 fighter = Fighter(fTree=fTree)
261 # Add fighter to respective party (1 or 2)
262 if fighter.getPlayable() and newGame:
263 self.__battle.getParty1().addFighter(fighter)
264 else:
265 self.__battle.getMonsters().append(fighter)
267 def unloadStaticData(self):
268 """ Clears out all monsters and EventTypes. """
270 # Clearing out monsters
271 self.__battle.setMonsters([])
273 # Clearing out EventTypes
274 self.__battle.setEventTypeList([])
276 def getBattle(self):
277 return self.__battle
279 def getView(self):
280 return self.__view