A little bit of nothing.
[krufty_fps.git] / more_test.py~
blobaa1c52eada93fefb0b3e84e53fcd1f6058a2fc4c
1 #!/usr/bin/python
3 # PyOpenGL + Pygame
5 CONFIG = 'game_config.xml'
7 WINDOW_SIZE = (640, 480)
8 WINDOW_CAPTION = "Testing stuff"
10 BROADCAST = 50030
11 BROADCAST_BIND = 50031
12 MESSAGE = 40030
14 BUFSIZE = 120
16 TIMEOUT = .1
18 # this will change
20 SERVERREQUEST = "i_want_server"
21 SERVEROFFER = "Want_server?"
22 SERVERKILL = "DIE_server!!"
23 YOUTHERE = "you_there?"
24 IMHERE = "yeah,i'm_here"
25 WANTIN = "i_want_in"
26 YOUREIN = "urine"
27 IMOUT = "i_leave"
28 GETLIST = "get_list"
29 LIST = "peoples_on_server"
30 SOMEONEJOINED = "dude,someone_joined"
31 SOMEONELEFT = "someone_left"
32 YOUROUT = "get_lost_punk"
33 LETTER = "listen_to_me"
35 the_functions = {}
36 in_script = 0
38 import os, sys
39 from os import *
40 from os.path import *
42 import threading
43 from socket import *
44 from xml.dom.minidom import parse, parseString
45 from threading import Lock
46 from signal import *
47 from zipfile import *
49 import pygame
50 from pygame import *
52 import pgu
53 from pgu import gui as pgui
55 import lamina
57 import OpenGL
58 import OpenGL.GL
59 from OpenGL.GL import *
60 import OpenGL.GLU
61 from OpenGL.GLU import *
63 import StringIO
65 the_event_receiver = 0
67 global the_engine
68 global the_client
70 class Client:
72 def __init__(self, params):
74 self.params = params
76 self.outgoing = []
77 self.incoming = []
79 self.outgoing_lock = Lock()
80 self.incoming_lock = Lock()
82 self.broadcast = socket(AF_INET, SOCK_DGRAM)
83 self.broadcast.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
85 self.message = socket(AF_INET, SOCK_DGRAM)
87 self.message_lock = Lock()
89 self.members = []
90 self.servers = {}
92 self.current_server = []
93 self.requested_server = ()
95 self.messages_in = []
97 self.commands = CommandLine()
99 self.messages_in_lock = Lock()
101 if (params.has_key('broadcast_bind')):
102 self.broadcast.bind(((''), params['broadcast_bind']))
103 else:
104 print "Client.__init__(): No broadcast port number chosen, using", BROADCAST_BIND
105 self.broadcast.bind(((''), BROADCAST_BIND))
107 if (params.has_key('message_port')):
108 self.message.bind(((''), params['message_port']))
109 else:
110 print "Client.__init__(): No broadcast port number chosen, using", MESSAGE
111 self.message.bind(((''), MESSAGE))
113 def run(self):
115 print "Client.run(): Making threads..."
117 self.send_thread = threading.Thread(target=self.send)
118 self.receive_thread = threading.Thread(target=self.receive)
119 self.process_in_thread = threading.Thread(target=self.process_in)
120 self.process_out_thread = threading.Thread(target=self.process_out)
122 self.send_thread.start()
123 self.receive_thread.start()
124 self.process_in_thread.start()
125 self.process_out_thread.start()
127 self.send_thread.join()
128 self.receive_thread.join()
129 self.process_in_thread.join()
130 self.process_out_thread.join()
132 print "Client.run(): Closed threads"
134 return
136 def send(self):
138 print "Client.send() beginning..."
140 while (the_engine.running):
142 if (len(self.outgoing)):
144 self.outgoing_lock.acquire()
145 print "Client.send(): Acquired outgoing_lock"
147 data_out = self.outgoing.pop(0)
149 self.outgoing_lock.release()
150 print "Client.send(): Released outgoing_lock"
152 if type(data_out[1]) != type(()):
153 data_out[1] = (data_out[1][0], data_out[1][1])
155 if data_out[1][0] != '<broadcast>':
156 self.message_lock.acquire()
157 self.message.sendto(data_out[0], data_out[1])
158 self.message_lock.release()
159 else:
160 self.broadcast.sendto(data_out[0], data_out[1])
161 print "Client.send(): Sent data", data_out
162 return
164 def receive(self):
166 print "Client.receive() beginning..."
168 self.message.settimeout(TIMEOUT)
170 while (the_engine.running):
172 print "debug, no?"
174 try:
175 self.message_lock.acquire()
176 data_in = self.message.recvfrom(BUFSIZE)
177 self.message_lock.release()
178 except:
179 data_in = ()
181 if (data_in != ()):
182 self.incoming_lock.acquire()
183 self.incoming.append(data_in)
184 self.incoming_lock.release()
186 def process_in(self):
188 print "Client.process_in() beginning..."
190 global the_engine
192 while (the_engine.running):
194 if (len(self.incoming)):
195 # data in = ()
197 self.incoming_lock.acquire()
198 print "Client.process_in(): Acquired incoming_lock"
200 data_in = self.incoming.pop(0)
202 self.incoming_lock.release()
203 print "Client.process_in(): Released incoming_lock"
205 if (data_in[0][:len(YOUTHERE)] == YOUTHERE):
206 print "Client.process_in(): Received YOUTHERE, responding with IMHERE"
208 response = [IMHERE, data_in[1]]
210 self.outgoing_lock.acquire()
211 print "Client.process_in(): Acquired outgoing_lock"
213 self.outgoing.append(response)
215 self.outgoing_lock.release()
216 print "Client.process_in(): Released outgoing_lock"
218 if (data_in[0][:len(SERVEROFFER)] == SERVEROFFER):
219 print "Client.process_in(): Received SERVEROFFER"
221 split_strings = data_in[0].split()
222 self.servers[split_strings[2]] = [data_in[0][0], int(split_strings[1])]
224 event = [SERVEROFFER, {'server_name': split_strings[2]}]
226 the_engine.events.addEvent(event)
228 if (data_in[0][:len(YOUREIN)] == YOUREIN):
229 if (data_in[1] == self.requested_server):
230 self.current_server = data_in[1]
231 self.requested_server = ()
233 event = [YOUREIN]
234 data = {'server': data_in[1]}
235 event.append(data)
237 the_engine.events.addEvent(event)
239 print "Client.process_in(): Received YOUREIN, joined server"
241 if (data_in[0][:len(LIST)] == LIST):
242 print "Client.process_in(): Received LIST"
244 if (data_in[1] == self.current_server):
245 split_strings = data_in[0].split()
247 self.members = []
249 for string in split_strings:
250 if string != LIST:
251 self.members.append(string)
253 event = [LIST]
254 data = {'names': self.members}
255 event.append(data)
257 the_engine.events.addEvent(event)
259 if (data_in[0][:len(SOMEONEJOINED)] == SOMEONEJOINED):
260 print "Client.process_in(): Received SOMEONEJOINED"
262 if (data_in[1] == self.current_server):
263 left_member = ''
265 for member in self.members:
266 if member == data_in[0][len(SOMEONEJOINED) + 1:]:
267 left_member = member
269 if left_member != '':
270 self.members.remove(left_member)
272 if (data_in[0][:len(YOUROUT)] == YOUROUT):
273 print "Client.process_in(): Received YOUROUT"
275 if (data_in[1] == self.current_server):
276 self.current_server = []
278 event = [YOUROUT]
279 data = {}
280 event.append(data)
282 the_engine.events.addEvent(event)
284 if (data_in[0][:len(LETTER)] == LETTER):
285 print "Client.process_in(): Received LETTER"
287 if (data_in[1] == self.current_server):
288 split_strings = data_in[0].split(':')
290 the_message_data = data_in[0][this_string.find(":", len(LETTER) + 1) + 1:]
291 the_message_origin = split_strings[1]
293 self.messages_in_lock.acquire()
294 the_message = (the_message_data, the_message_origin)
295 self.messages_in.append(the_message)
296 self.messages_in_lock.release()
298 event = [LETTER]
299 data = {'message': the_message_data}
300 event.append(data)
302 the_engine.events.addEvent(event)
304 def process_out(self):
306 print "Client.process_out(): beginning..."
308 while (the_engine.running):
310 if (self.commands.size()):
312 # {'type': ..., 'data': ...}
314 command = self.commands.getCommand()
316 if command['type'] == SERVERKILL:
318 if self.current_server != ():
319 out_message = [''.join([SERVERKILL, ' ']), self.current_server]
321 if command.has_key('password'):
322 out_message[0] += command['password']
324 self.outgoing_lock.acquire()
325 self.outgoing.append(out_message)
326 self.outgoing_lock.release()
328 if command['type'] == SERVERREQUEST:
330 out_message = []
332 out_message.append(''.join([SERVERREQUEST, " ", str(self.params['message_port'])]))
333 out_message.append(['<broadcast>', self.params['broadcast_port']])
335 self.outgoing_lock.acquire()
336 self.outgoing.append(out_message)
337 self.outgoing_lock.release()
339 if command['type'] == GETLIST:
341 if self.current_server != ():
343 out_message = [GETLIST, self.current_server]
345 self.outgoing_lock.acquire()
346 self.outgoing.append(out_message)
347 self.outgoing_lock.release()
349 if command['type'] == IMOUT:
351 if self.current_sever != ():
353 out_message = [IMOUT, self.current_server]
355 self.outgoing_lock.acquire()
356 self.outgoing.append(out_message)
357 self.outgoing_lock.release()
359 if command['type'] == LETTER:
361 if self.current_server != ():
363 out_message = [LETTER + ':', self.current_server]
365 for dest in command['destinations']:
366 if dest in self.members:
367 out_message[0] += " " + dest
369 out_message[0] += ":" + command['message']
371 self.outgoing_lock.acquire()
372 self.outgoing.append(out_message)
373 self.outgoing_lock.release()
375 return
377 class QueueLock:
378 def __init__(self):
380 self.items = []
381 self.items_lock = Lock()
383 def size(self):
385 return len(self.items)
387 def getItem(self):
389 self.items_lock.acquire()
390 the_item = self.items.pop(0)
391 self.items_lock.release()
393 return the_item
395 def addItem(self, new_item):
397 self.items_lock.acquire()
398 self.items.append(new_item)
399 self.items_lock.release()
401 return
403 class EventReceiver(QueueLock):
405 def getEvent(self):
406 return self.getItem()
407 def addEvent(self, event):
408 self.addItem(event)
409 return
411 class CommandLine(QueueLock):
413 def getCommand(self):
414 return self.getItem()
415 def addCommand(self, command):
416 self.addItem(command)
417 return
419 class Engine:
421 def __init__(self, config):
423 self.config = config
424 self.running = 1
426 global the_engine
427 the_engine = self
429 video_flags = OPENGL|DOUBLEBUF
431 pygame.init()
432 self.display = pygame.display.set_mode(config['window_size'], video_flags)
434 self.font = pygame.font.SysFont("default", 18)
435 self.fontBig = pygame.font.SysFont("default", 24)
436 self.fontSub = pygame.font.SysFont("default", 20)
437 self.theme = pgui.Theme(['test_theme', 'gray', 'default'])
438 # self.theme = pgui.Theme('gray')
439 # self.theme = pgui.Theme('default')
441 self.resize((config['window_size']))
443 glShadeModel(GL_SMOOTH)
444 glClearColor(self.config['background_color'][0],
445 self.config['background_color'][1],
446 self.config['background_color'][2],
447 self.config['background_color'][3])
448 glClearDepth(1.0)
449 glEnable(GL_DEPTH_TEST)
450 glDepthFunc(GL_LEQUAL)
451 glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
453 pygame.display.set_caption(config['window_title'])
455 self.gui_screen = lamina.LaminaScreenSurface()
457 self.app = pgui.App(theme=self.theme)
458 self.app._screen = self.gui_screen.surf
459 self.main_container = pgui.Container(width=config['window_size'][0])
461 self.files = {}
463 self.events = EventReceiver()
465 # self.files is a map of filename to file
467 # The file has this:
468 # {parent, [children], {object_defs},
469 # {menu_defs}, {object_instances}, {menu_instances}}
471 self.zipfiles = []
473 for file in listdir(self.config['pack_dir']):
474 if (is_zipfile(os.path.join(self.config['pack_dir'], file))):
475 self.zipfiles.append(ZipFile(os.path.join(self.config['pack_dir'], file)))
477 self.running = self.addFile(self.config['init'], '')
478 self.app.init(self.main_container)
480 self.ticks = pygame.time.get_ticks()
481 self.frames = 0
483 if self.running == 0:
484 print "Engine.__init__(): Failed adding initial file"
486 def run(self):
488 while self.running:
490 self.process_events()
492 self.draw()
494 #self.updateFPS()
496 pygame.display.flip()
498 return
500 def updateFPS(self):
502 self.oldticks = self.ticks
503 self.ticks = pygame.time.get_ticks()
505 self.frames += 1
507 self.fps = (self.frames * 1000) / (self.ticks - self.oldticks)
509 pygame.display.set_caption(''.join([self.config['window_title'], ' ', str(self.fps)]))
511 return
513 def process_events(self):
515 change = 0
517 for e in pygame.event.get():
518 if e.type == QUIT:
519 self.running = 0
520 print "Should be quitting..."
522 self.app.event((e))
523 change = self.app.update(self.gui_screen.surf)
525 if (change != 0):
526 self.gui_screen.refresh(change)
528 new_event = self.convertEvent(e)
529 self.events.addEvent(new_event)
531 iterating = 1
532 while iterating:
534 if self.events.size():
535 new_event = self.events.getEvent()
536 else:
537 iterating = 0
539 if not iterating:
540 return
542 if iterating:
543 for file in self.files.keys():
545 for name in self.files[file]['object_instances'].keys():
547 self.files[file]['object_instances'][name].event(new_event[0], new_event[1])
549 return
551 def convertEvent(self, e):
553 data = {}
555 if e.type == QUIT:
556 data['none'] = ''
558 if e.type == ACTIVEEVENT:
559 data['gain'] = e.gain
560 data['state'] = e.state
562 if e.type == KEYDOWN:
563 data['unicode'] = e.unicode
564 data['key'] = e.key
565 data['mod'] = e.mod
567 if e.type == KEYUP:
568 data['key'] = e.key
569 data['mod'] = e.mod
571 if e.type == MOUSEMOTION:
572 data['pos'] = e.pos
573 data['rel'] = e.rel
574 data['buttons'] = e.buttons
576 if e.type == MOUSEBUTTONUP:
577 data['pos'] = e.pos
578 data['button'] = e.button
580 if e.type == MOUSEBUTTONDOWN:
581 data['pos'] = e.pos
582 data['button'] = e.button
584 if e.type == JOYAXISMOTION:
585 data['joy'] = e.joy
586 data['axis'] = e.axis
587 data['value'] = e.value
589 if e.type == JOYBALLMOTION:
590 data['joy'] = e.joy
591 data['ball'] = e.ball
592 data['rel'] = e.rel
594 if e.type == JOYHATMOTION:
595 data['joy'] = e.joy
596 data['hat'] = e.hat
597 data['value'] = e.value
599 if e.type == JOYBUTTONUP:
600 data['joy'] = e.joy
601 data['button'] = e.button
603 if e.type == JOYBUTTONDOWN:
604 data['joy'] = e.joy
605 data['button'] = e.button
607 if e.type == VIDEORESIZE:
608 data['size'] = e.size
609 data['w'] = e.w
610 data['h'] = e.h
612 if e.type == VIDEOEXPOSE:
613 data['none'] = ''
615 if e.type == USEREVENT:
616 data['code'] = e.code
618 type = ''
620 if e.type == QUIT: type = "QUIT"
621 if e.type == ACTIVEEVENT: type = "ACTIVEEVENT"
622 if e.type == KEYDOWN: type = "KEYDOWN"
623 if e.type == KEYUP: type = "KEYUP"
624 if e.type == MOUSEMOTION : type = "MOUSEMOTION"
625 if e.type == MOUSEBUTTONUP: type = "MOUSEBUTTONUP"
626 if e.type == MOUSEBUTTONDOWN: type = "MOUSEBUTTONDOWN"
627 if e.type == JOYAXISMOTION: type = "JOYAXISMOTION"
628 if e.type == JOYBALLMOTION: type = "JOYBALLMOTION"
629 if e.type == JOYHATMOTION: type = "JOYHATMOTION"
630 if e.type == JOYBUTTONUP: type = "JOYBUTTONUP"
631 if e.type == JOYBUTTONDOWN: type = "JOYBUTTONDOWN"
632 if e.type == VIDEORESIZE: type = "VIDEORESIZE"
633 if e.type == VIDEOEXPOSE: type = "VIDEOEXPOSE"
634 if e.type == USEREVENT: type = "USEREVENT"
636 return [type, data]
638 def draw(self):
640 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
641 glLoadIdentity()
643 # draw stuff
645 glLoadIdentity()
646 self.gui_screen.display()
648 def resize(self, (width, height)):
649 if height==0:
650 height=1
651 glViewport(0, 0, width, height)
652 glMatrixMode(GL_PROJECTION)
653 glLoadIdentity()
654 gluPerspective(45, 1.0*width/height, 0.1, 100.0)
655 glMatrixMode(GL_MODELVIEW)
656 glLoadIdentity()
658 return
660 def addFile(self, filename, parent):
662 # Because I have alot of nesting in this function,
663 # I am using 2 space formatting
665 for zipfile in self.zipfiles:
667 for file in zipfile.namelist():
669 if (file == filename):
670 dom = parseString(zipfile.read(file))
672 object_instances_d = []
673 menu_instances = []
675 if dom.childNodes[0].nodeName == 'game':
676 self.files[filename] = {
677 'object_defs': {},
678 'children': [],
679 'parent': '',
680 'object_instances': {},
681 'menu_instances': {},
682 'menu_defs': {}}
684 for node in dom.childNodes[0].childNodes:
686 if (node.nodeName == 'def'):
688 for sub_node in node.childNodes:
690 if (sub_node.nodeName == 'object'):
692 temp_object_def = {}
694 for suber_node in sub_node.childNodes:
696 if (suber_node.nodeName == 'name'):
697 if len(suber_node.childNodes):
698 temp_object_def['name'] = suber_node.childNodes[0].nodeValue
700 if (suber_node.nodeName == 'script'):
701 if len(suber_node.childNodes):
702 temp_object_def['script'] = suber_node.childNodes[0].nodeValue
704 if (suber_node.nodeName == 'tangible'):
705 if len(suber_node.childNodes):
706 temp_object_def['tangible'] = suber_node.childNodes[0].nodeValue
708 if (suber_node.nodeName == 'type'):
709 if len(suber_node.childNodes):
710 temp_object_def['type'] = suber_node.childNodes[0].nodeValue
712 self.files[filename]['object_defs'][temp_object_def['name']] = temp_object_def
713 temp_object_def = {}
715 if (sub_node.nodeName == 'menu'):
717 temp_menu_def = {}
718 temp_menu_def['elements'] = {}
720 temp_element_set = {}
722 for suber_node in sub_node.childNodes:
724 if (suber_node.nodeName == 'name'):
725 temp_menu_def['name'] = suber_node.childNodes[0].nodeValue
727 if (suber_node.nodeName == 'elements'):
729 for suberer_node in suber_node.childNodes:
731 if (suberer_node.nodeType != 3 and suberer_node.nodeType != 8):
732 if (suberer_node.hasAttribute('name')):
733 temp_element_set['name'] = suberer_node.getAttribute('name')
735 if (suberer_node.hasAttribute('x')):
736 temp_element_set['x'] = int(suberer_node.getAttribute('x'))
738 if (suberer_node.hasAttribute('y')):
739 temp_element_set['y'] = int(suberer_node.getAttribute('y'))
741 if (suberer_node.hasAttribute('width')):
742 temp_element_set['width'] = int(suberer_node.getAttribute('width'))
744 if (suberer_node.hasAttribute('height')):
745 temp_element_set['height'] = int(suberer_node.getAttribute('height'))
747 if (suberer_node.hasAttribute('parent')):
748 temp_element_set['parent'] = suberer_node.getAttribute('parent')
750 if (suberer_node.hasAttribute('target')):
751 temp_element_set['target'] = suberer_node.getAttribute('target')
753 if (suberer_node.hasAttribute('text')):
754 temp_element_set['text'] = suberer_node.getAttribute('text')
756 temp_element_set['type'] = suberer_node.nodeName
757 temp_menu_def['elements'][temp_element_set['name']] = temp_element_set
758 temp_element_set = {}
760 self.files[filename]['menu_defs'][temp_menu_def['name']] = temp_menu_def
762 temp_menu_def = {}
763 temp_element_set = {}
765 if (node.nodeName == 'instance'):
767 for sub_node in node.childNodes:
769 if (sub_node.nodeName == 'object'):
770 object_instances_d.append(sub_node.childNodes[0].nodeValue)
772 if (sub_node.nodeName == 'menu'):
773 menu_instances.append(sub_node.childNodes[0].nodeValue)
775 if (parent != ''):
776 self.files[parent]['children'].append(filename)
777 self.files[filename]['parent'] = parent
779 # create instances
781 for menuname, menu_data in self.files[filename]['menu_defs'].iteritems():
782 self.files[filename]['menu_instances'][menuname] = Menu(menu_def=menu_data)
784 for menuname in menu_instances:
785 if (self.files[filename]['menu_instances'].has_key(menuname)):
786 self.files[filename]['menu_instances'][menuname].show()
788 for file in self.files.keys():
789 if self.files[file]['menu_instances'].has_key(menuname):
790 self.files[file]['menu_instances'][menuname].show()
792 for objectname in object_instances_d:
793 self.addObject(objectname)
795 return 1
796 return 0
797 # ending 2-space formatting
799 def removeFile(self, filename):
801 if (self.files.has_key(filename)):
803 for child in self.files[filename]['children']:
804 self.removeFile(child)
806 del self.files[filename]['children']
808 parent = self.files[filename]['parent']
809 self.files[parent].pop(self.files[parent]['children'].index(filename))
811 del self.files[filename]
813 return
815 def hideAllMenus(self):
817 for file, contents in self.files.iteritems():
818 for name, menu in contents['menu_instances'].iteritems():
819 menu.hide()
821 return
823 def showMenu(self, menu_name):
825 for file, contents in self.files.iteritems():
826 for name, menu in contents['menu_instances'].iteritems():
827 if contents['menu_instances'].has_key(menu_name):
828 contents['menu_instances'][menu_name].show()
830 return
832 def hideMenu(self, menu_name):
834 for file, contents in self.files:
835 for name, menu in contents['menu_instances'].iteritems():
836 if contents['menu_instances'].has_key(menu_name):
837 contents['menu_instances'][menu_name].hide()
839 return
841 def setMenu(self, menu_name):
843 self.hideAllMenus()
844 self.showMenu(menu_name)
846 return
848 def addObject(self, objectname):
850 for file in self.files.keys():
851 if self.files[file]['object_defs'].has_key(objectname):
852 self.files[file]['object_instances'][objectname] = GameObject(
853 self.files[file]['object_defs'][objectname])
855 return
857 def removeObject(self, objectname):
859 for file in self.files.keys():
860 if self.files[file]['object_defs'].has_key(objectname):
861 del self.files[file]['object_instances'][objectname]
863 return
865 def getImage(self, filename):
867 the_buf = pygame.image.load(self.getStringIOFile(filename))
869 return the_buf
871 def getStringIOFile(self, filename):
873 for zip_file in self.zipfiles:
874 for file in zip_file.namelist():
876 if (filename == file):
878 the_string_io = StringIO.StringIO()
879 print >>the_string_io, zip_file.read(file)
880 the_string_io.seek(0)
882 return the_string_io
883 return ''
885 def getStringData(self, filename):
886 for zip_file in self.zipfiles:
887 for file in zip_file.namelist():
889 if (filename == file):
890 return zip_file.read(file)
891 return ''
893 class Menu:
895 def __init__(self, menu_def):
897 self.menu_def = menu_def
898 self.widgets = {}
900 for name, element in menu_def['elements'].iteritems():
902 multiplier_x = float(the_engine.config['window_size'][0]) / 100.00
903 multiplier_y = float(the_engine.config['window_size'][1]) / 100.00
905 dx = float(element['x']) * multiplier_x
906 dy = float(element['y']) * multiplier_y
908 dwidth = float(element['width']) * multiplier_x
909 dheight = float(element['height']) * multiplier_y
911 if (element['type'] == 'button'):
912 self.widgets[name] = pgui.Button(element['text'].encode(), width=dwidth, height=dheight)
913 self.widgets[name].connect(pgui.CLICK, self.clicked, name)
915 if (element['type'] == 'image'):
916 self.widgets[name] = pgui.Image(the_engine.getImage(element['text']))
918 if (element['type'] == 'label'):
919 self.widgets[name] = pgui.Label(element['text'])
921 if (element['type'] == 'listbox'):
922 self.widgets[name] = pgui.List(width=dwidth, height=dheight)
924 if (self.widgets.has_key(name)):
925 self.widgets[name].resize(width=dwidth, height=dheight)
926 else:
927 print "Menu.__init__(): Widget type", element['type'], " not implemented yet, skipping."
929 self.hidden = 1
931 def show(self):
933 global the_engine
935 multiplier_x = float(the_engine.config['window_size'][0]) / 100.00
936 multiplier_y = float(the_engine.config['window_size'][1]) / 100.00
938 if (self.hidden == 1):
939 for name, element in self.menu_def['elements'].iteritems():
940 dx = float(element['x']) * multiplier_x
941 dy = float(element['y']) * multiplier_y
943 if self.widgets.has_key(name):
944 the_engine.main_container.add(self.widgets[name], dx, dy)
946 self.hidden = 0
948 return
950 def hide(self):
952 global the_engine
954 if (self.hidden != 1):
955 for name, element in self.menu_def['elements'].iteritems():
957 if (self.widgets.has_key(name)):
958 the_engine.main_container.remove(self.widgets[name])
960 self.hidden = 1
962 return
964 def clicked(self, button_name):
966 if self.menu_def['elements'].has_key(button_name):
968 if self.menu_def['elements'][button_name]['target'] != '':
969 exec(self.menu_def['elements'][button_name]['target'])
971 the_engine.events.addEvent(['BUTTON_CLICKED',
972 {'name': button_name, 'menu_name': self.menu_def['name']}])
974 return
976 class GameObject:
978 def __init__(self, dmold):
980 self.mold = dmold
981 global the_functions
982 global in_script
984 if self.mold['script'] != '':
986 in_script = 1
988 the_file = the_engine.getStringData(self.mold['script'])
989 if the_file != '':
990 exec(the_file)
992 in_script = 0
993 self.my_functions = the_functions
995 the_functions = {}
997 def event(self, event, data):
999 if self.my_functions.has_key(event):
1001 self.my_functions[event](data)
1003 return
1005 def main():
1006 # parse command line stuff
1008 if (len(sys.argv) > 1):
1009 config = sys.argv[1]
1010 else:
1011 print "main(): No config specified, using", CONFIG
1012 config = CONFIG
1014 configuration = parse_config(config)
1016 if (configuration.has_key('error') and configuration['error']):
1017 print "main(): Error in parsing config."
1019 the_event_receiver = EventReceiver()
1021 client_params = {'broadcast_port':configuration['broadcast_port'],
1022 'broadcast_bind':configuration['broadcast_bind'],
1023 'message_port':configuration['message_port'],
1024 'name':configuration['name']}
1026 global the_client
1027 global the_engine
1029 the_client = Client(client_params)
1030 the_engine = Engine(configuration)
1032 the_client_thread = threading.Thread(target=the_client.run)
1033 # the_engine_thread = threading.Thread(target=the_engine.run)
1035 the_client_thread.start()
1036 # the_engine_thread.start()
1038 the_engine.run()
1040 the_client_thread.join()
1041 # the_engine_thread.join()
1043 return
1045 def parse_config(filename):
1046 results = {'error': 1}
1048 if (exists(filename)):
1049 dom = parse(filename)
1050 else:
1051 print "parse_config():", filename, "doesn't exist."
1052 return results
1054 if (dom.childNodes[0].nodeName == 'config'):
1055 for node in dom.childNodes[0].childNodes:
1057 if (node.nodeName == 'window_title'):
1058 results['window_title'] = node.childNodes[0].nodeValue
1060 if (node.nodeName == 'log'):
1061 results['log'] = node.childNodes[0].nodeValue
1063 if (node.nodeName == 'name'):
1064 results['name'] = node.childNodes[0].nodeValue
1066 if (node.nodeName == 'font'):
1067 results['font'] = node.childNodes[0].nodeValue
1069 if (node.nodeName == 'init'):
1070 results['init'] = node.childNodes[0].nodeValue
1072 if (node.nodeName == 'message_port'):
1073 results['message_port'] = int(node.childNodes[0].nodeValue)
1075 if (node.nodeName == 'broadcast_port'):
1076 results['broadcast_port'] = int(node.childNodes[0].nodeValue)
1078 if (node.nodeName == 'broadcast_bind'):
1079 results['broadcast_bind'] = int(node.childNodes[0].nodeValue)
1081 if (node.nodeName == 'fullscreen'):
1082 results['fullscreen'] = int(node.childNodes[0].nodeValue)
1084 if (node.nodeName == 'background_color'):
1086 string_parts = node.childNodes[0].nodeValue.split()
1087 results['background_color'] = [float(string_parts[0]), float(string_parts[1])]
1088 results['background_color'].append(float(string_parts[2]))
1089 results['background_color'].append(float(string_parts[3]))
1091 if (node.nodeName == 'window_size'):
1093 string_parts = node.childNodes[0].nodeValue.split()
1094 results['window_size'] = ((int(string_parts[0]), int(string_parts[1])))
1096 if (node.nodeName == 'gravity'):
1098 string_parts = node.childNodes[0].nodeValue.split()
1099 results['gravity'] = [float(string_parts[0]), float(string_parts[1])]
1100 results['gravity'].append(float(string_parts[2]))
1102 if (node.nodeName == 'step_size'):
1103 results['step_size'] = float(node.childNodes[0].nodeValue)
1105 if (node.nodeName == 'pack_dir'):
1106 results['pack_dir'] = node.childNodes[0].nodeValue
1108 results['error'] = 0
1110 return results
1112 if __name__ == '__main__':
1113 main()