Trying to move the view.
[krufty_fps.git] / more_test.py
blob1e3abcb6608c58f03feef9a773a152d68ae8419d
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) / 1000
509 print 'DEBUG is', self.config['window_title']
510 pygame.display.set_caption(''.join([self.config['window_title'], ' ', str(self.fps)]))
512 return
514 def process_events(self):
516 change = 0
518 for e in pygame.event.get():
519 if e.type == QUIT:
520 self.running = 0
521 print "Should be quitting..."
523 self.app.event((e))
524 change = self.app.update(self.gui_screen.surf)
526 if (change != 0):
527 self.gui_screen.refresh(change)
529 new_event = self.convertEvent(e)
530 self.events.addEvent(new_event)
532 iterating = 1
533 while iterating:
535 if self.events.size():
536 new_event = self.events.getEvent()
537 else:
538 iterating = 0
540 if not iterating:
541 return
543 if iterating:
544 for file in self.files.keys():
546 for name in self.files[file]['object_instances'].keys():
548 self.files[file]['object_instances'][name].event(new_event[0], new_event[1])
550 return
552 def convertEvent(self, e):
554 data = {}
556 if e.type == QUIT:
557 data['none'] = ''
559 if e.type == ACTIVEEVENT:
560 data['gain'] = e.gain
561 data['state'] = e.state
563 if e.type == KEYDOWN:
564 data['unicode'] = e.unicode
565 data['key'] = e.key
566 data['mod'] = e.mod
568 if e.type == KEYUP:
569 data['key'] = e.key
570 data['mod'] = e.mod
572 if e.type == MOUSEMOTION:
573 data['pos'] = e.pos
574 data['rel'] = e.rel
575 data['buttons'] = e.buttons
577 if e.type == MOUSEBUTTONUP:
578 data['pos'] = e.pos
579 data['button'] = e.button
581 if e.type == MOUSEBUTTONDOWN:
582 data['pos'] = e.pos
583 data['button'] = e.button
585 if e.type == JOYAXISMOTION:
586 data['joy'] = e.joy
587 data['axis'] = e.axis
588 data['value'] = e.value
590 if e.type == JOYBALLMOTION:
591 data['joy'] = e.joy
592 data['ball'] = e.ball
593 data['rel'] = e.rel
595 if e.type == JOYHATMOTION:
596 data['joy'] = e.joy
597 data['hat'] = e.hat
598 data['value'] = e.value
600 if e.type == JOYBUTTONUP:
601 data['joy'] = e.joy
602 data['button'] = e.button
604 if e.type == JOYBUTTONDOWN:
605 data['joy'] = e.joy
606 data['button'] = e.button
608 if e.type == VIDEORESIZE:
609 data['size'] = e.size
610 data['w'] = e.w
611 data['h'] = e.h
613 if e.type == VIDEOEXPOSE:
614 data['none'] = ''
616 if e.type == USEREVENT:
617 data['code'] = e.code
619 type = ''
621 if e.type == QUIT: type = "QUIT"
622 if e.type == ACTIVEEVENT: type = "ACTIVEEVENT"
623 if e.type == KEYDOWN: type = "KEYDOWN"
624 if e.type == KEYUP: type = "KEYUP"
625 if e.type == MOUSEMOTION : type = "MOUSEMOTION"
626 if e.type == MOUSEBUTTONUP: type = "MOUSEBUTTONUP"
627 if e.type == MOUSEBUTTONDOWN: type = "MOUSEBUTTONDOWN"
628 if e.type == JOYAXISMOTION: type = "JOYAXISMOTION"
629 if e.type == JOYBALLMOTION: type = "JOYBALLMOTION"
630 if e.type == JOYHATMOTION: type = "JOYHATMOTION"
631 if e.type == JOYBUTTONUP: type = "JOYBUTTONUP"
632 if e.type == JOYBUTTONDOWN: type = "JOYBUTTONDOWN"
633 if e.type == VIDEORESIZE: type = "VIDEORESIZE"
634 if e.type == VIDEOEXPOSE: type = "VIDEOEXPOSE"
635 if e.type == USEREVENT: type = "USEREVENT"
637 return [type, data]
639 def draw(self):
641 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
642 glLoadIdentity()
644 # draw stuff
646 glLoadIdentity()
647 self.gui_screen.display()
649 def resize(self, (width, height)):
650 if height==0:
651 height=1
652 glViewport(0, 0, width, height)
653 glMatrixMode(GL_PROJECTION)
654 glLoadIdentity()
655 gluPerspective(45, 1.0*width/height, 0.1, 100.0)
656 glMatrixMode(GL_MODELVIEW)
657 glLoadIdentity()
659 return
661 def addFile(self, filename, parent):
663 # Because I have alot of nesting in this function,
664 # I am using 2 space formatting
666 for zipfile in self.zipfiles:
668 for file in zipfile.namelist():
670 if (file == filename):
671 dom = parseString(zipfile.read(file))
673 object_instances_d = []
674 menu_instances = []
676 if dom.childNodes[0].nodeName == 'game':
677 self.files[filename] = {
678 'object_defs': {},
679 'children': [],
680 'parent': '',
681 'object_instances': {},
682 'menu_instances': {},
683 'menu_defs': {}}
685 for node in dom.childNodes[0].childNodes:
687 if (node.nodeName == 'def'):
689 for sub_node in node.childNodes:
691 if (sub_node.nodeName == 'object'):
693 temp_object_def = {}
695 for suber_node in sub_node.childNodes:
697 if (suber_node.nodeName == 'name'):
698 if len(suber_node.childNodes):
699 temp_object_def['name'] = suber_node.childNodes[0].nodeValue
701 if (suber_node.nodeName == 'script'):
702 if len(suber_node.childNodes):
703 temp_object_def['script'] = suber_node.childNodes[0].nodeValue
705 if (suber_node.nodeName == 'tangible'):
706 if len(suber_node.childNodes):
707 temp_object_def['tangible'] = suber_node.childNodes[0].nodeValue
709 if (suber_node.nodeName == 'type'):
710 if len(suber_node.childNodes):
711 temp_object_def['type'] = suber_node.childNodes[0].nodeValue
713 self.files[filename]['object_defs'][temp_object_def['name']] = temp_object_def
714 temp_object_def = {}
716 if (sub_node.nodeName == 'menu'):
718 temp_menu_def = {}
719 temp_menu_def['elements'] = {}
721 temp_element_set = {}
723 for suber_node in sub_node.childNodes:
725 if (suber_node.nodeName == 'name'):
726 temp_menu_def['name'] = suber_node.childNodes[0].nodeValue
728 if (suber_node.nodeName == 'elements'):
730 for suberer_node in suber_node.childNodes:
732 if (suberer_node.nodeType != 3 and suberer_node.nodeType != 8):
733 if (suberer_node.hasAttribute('name')):
734 temp_element_set['name'] = suberer_node.getAttribute('name')
736 if (suberer_node.hasAttribute('x')):
737 temp_element_set['x'] = int(suberer_node.getAttribute('x'))
739 if (suberer_node.hasAttribute('y')):
740 temp_element_set['y'] = int(suberer_node.getAttribute('y'))
742 if (suberer_node.hasAttribute('width')):
743 temp_element_set['width'] = int(suberer_node.getAttribute('width'))
745 if (suberer_node.hasAttribute('height')):
746 temp_element_set['height'] = int(suberer_node.getAttribute('height'))
748 if (suberer_node.hasAttribute('parent')):
749 temp_element_set['parent'] = suberer_node.getAttribute('parent')
751 if (suberer_node.hasAttribute('target')):
752 temp_element_set['target'] = suberer_node.getAttribute('target')
754 if (suberer_node.hasAttribute('text')):
755 temp_element_set['text'] = suberer_node.getAttribute('text')
757 temp_element_set['type'] = suberer_node.nodeName
758 temp_menu_def['elements'][temp_element_set['name']] = temp_element_set
759 temp_element_set = {}
761 self.files[filename]['menu_defs'][temp_menu_def['name']] = temp_menu_def
763 temp_menu_def = {}
764 temp_element_set = {}
766 if (node.nodeName == 'instance'):
768 for sub_node in node.childNodes:
770 if (sub_node.nodeName == 'object'):
771 object_instances_d.append(sub_node.childNodes[0].nodeValue)
773 if (sub_node.nodeName == 'menu'):
774 menu_instances.append(sub_node.childNodes[0].nodeValue)
776 if (parent != ''):
777 self.files[parent]['children'].append(filename)
778 self.files[filename]['parent'] = parent
780 # create instances
782 for menuname, menu_data in self.files[filename]['menu_defs'].iteritems():
783 self.files[filename]['menu_instances'][menuname] = Menu(menu_def=menu_data)
785 for menuname in menu_instances:
786 if (self.files[filename]['menu_instances'].has_key(menuname)):
787 self.files[filename]['menu_instances'][menuname].show()
789 for file in self.files.keys():
790 if self.files[file]['menu_instances'].has_key(menuname):
791 self.files[file]['menu_instances'][menuname].show()
793 for objectname in object_instances_d:
794 self.addObject(objectname)
796 return 1
797 return 0
798 # ending 2-space formatting
800 def removeFile(self, filename):
802 if (self.files.has_key(filename)):
804 for child in self.files[filename]['children']:
805 self.removeFile(child)
807 del self.files[filename]['children']
809 parent = self.files[filename]['parent']
810 self.files[parent].pop(self.files[parent]['children'].index(filename))
812 del self.files[filename]
814 return
816 def hideAllMenus(self):
818 for file, contents in self.files.iteritems():
819 for name, menu in contents['menu_instances'].iteritems():
820 menu.hide()
822 return
824 def showMenu(self, menu_name):
826 for file, contents in self.files.iteritems():
827 for name, menu in contents['menu_instances'].iteritems():
828 if contents['menu_instances'].has_key(menu_name):
829 contents['menu_instances'][menu_name].show()
831 return
833 def hideMenu(self, menu_name):
835 for file, contents in self.files:
836 for name, menu in contents['menu_instances'].iteritems():
837 if contents['menu_instances'].has_key(menu_name):
838 contents['menu_instances'][menu_name].hide()
840 return
842 def setMenu(self, menu_name):
844 self.hideAllMenus()
845 self.showMenu(menu_name)
847 return
849 def addObject(self, objectname):
851 for file in self.files.keys():
852 if self.files[file]['object_defs'].has_key(objectname):
853 self.files[file]['object_instances'][objectname] = GameObject(
854 self.files[file]['object_defs'][objectname])
856 return
858 def removeObject(self, objectname):
860 for file in self.files.keys():
861 if self.files[file]['object_defs'].has_key(objectname):
862 del self.files[file]['object_instances'][objectname]
864 return
866 def getImage(self, filename):
868 the_buf = pygame.image.load(self.getStringIOFile(filename))
870 return the_buf
872 def getStringIOFile(self, filename):
874 for zip_file in self.zipfiles:
875 for file in zip_file.namelist():
877 if (filename == file):
879 the_string_io = StringIO.StringIO()
880 print >>the_string_io, zip_file.read(file)
881 the_string_io.seek(0)
883 return the_string_io
884 return ''
886 def getStringData(self, filename):
887 for zip_file in self.zipfiles:
888 for file in zip_file.namelist():
890 if (filename == file):
891 return zip_file.read(file)
892 return ''
894 class Menu:
896 def __init__(self, menu_def):
898 self.menu_def = menu_def
899 self.widgets = {}
901 for name, element in menu_def['elements'].iteritems():
903 multiplier_x = float(the_engine.config['window_size'][0]) / 100.00
904 multiplier_y = float(the_engine.config['window_size'][1]) / 100.00
906 dx = float(element['x']) * multiplier_x
907 dy = float(element['y']) * multiplier_y
909 dwidth = float(element['width']) * multiplier_x
910 dheight = float(element['height']) * multiplier_y
912 if (element['type'] == 'button'):
913 self.widgets[name] = pgui.Button(element['text'].encode(), width=dwidth, height=dheight)
914 self.widgets[name].connect(pgui.CLICK, self.clicked, name)
916 if (element['type'] == 'image'):
917 self.widgets[name] = pgui.Image(the_engine.getImage(element['text']))
919 if (element['type'] == 'label'):
920 self.widgets[name] = pgui.Label(element['text'])
922 if (element['type'] == 'listbox'):
923 self.widgets[name] = pgui.List(width=dwidth, height=dheight)
925 if (self.widgets.has_key(name)):
926 self.widgets[name].resize(width=dwidth, height=dheight)
927 else:
928 print "Menu.__init__(): Widget type", element['type'], " not implemented yet, skipping."
930 self.hidden = 1
932 def show(self):
934 global the_engine
936 multiplier_x = float(the_engine.config['window_size'][0]) / 100.00
937 multiplier_y = float(the_engine.config['window_size'][1]) / 100.00
939 if (self.hidden == 1):
940 for name, element in self.menu_def['elements'].iteritems():
941 dx = float(element['x']) * multiplier_x
942 dy = float(element['y']) * multiplier_y
944 if self.widgets.has_key(name):
945 the_engine.main_container.add(self.widgets[name], dx, dy)
947 self.hidden = 0
949 return
951 def hide(self):
953 global the_engine
955 if (self.hidden != 1):
956 for name, element in self.menu_def['elements'].iteritems():
958 if (self.widgets.has_key(name)):
959 the_engine.main_container.remove(self.widgets[name])
961 self.hidden = 1
963 return
965 def clicked(self, button_name):
967 if self.menu_def['elements'].has_key(button_name):
969 if self.menu_def['elements'][button_name]['target'] != '':
970 exec(self.menu_def['elements'][button_name]['target'])
972 the_engine.events.addEvent(['BUTTON_CLICKED',
973 {'name': button_name, 'menu_name': self.menu_def['name']}])
975 return
977 class GameObject:
979 def __init__(self, dmold):
981 self.mold = dmold
982 global the_functions
983 global in_script
985 if self.mold['script'] != '':
987 in_script = 1
989 the_file = the_engine.getStringData(self.mold['script'])
990 if the_file != '':
991 exec(the_file)
993 in_script = 0
994 self.my_functions = the_functions
996 the_functions = {}
998 def event(self, event, data):
1000 if self.my_functions.has_key(event):
1002 self.my_functions[event](data)
1004 return
1006 def main():
1007 # parse command line stuff
1009 if (len(sys.argv) > 1):
1010 config = sys.argv[1]
1011 else:
1012 print "main(): No config specified, using", CONFIG
1013 config = CONFIG
1015 configuration = parse_config(config)
1017 if (configuration.has_key('error') and configuration['error']):
1018 print "main(): Error in parsing config."
1020 the_event_receiver = EventReceiver()
1022 client_params = {'broadcast_port':configuration['broadcast_port'],
1023 'broadcast_bind':configuration['broadcast_bind'],
1024 'message_port':configuration['message_port'],
1025 'name':configuration['name']}
1027 global the_client
1028 global the_engine
1030 the_client = Client(client_params)
1031 the_engine = Engine(configuration)
1033 the_client_thread = threading.Thread(target=the_client.run)
1034 # the_engine_thread = threading.Thread(target=the_engine.run)
1036 the_client_thread.start()
1037 # the_engine_thread.start()
1039 the_engine.run()
1041 the_client_thread.join()
1042 # the_engine_thread.join()
1044 return
1046 def parse_config(filename):
1047 results = {'error': 1}
1049 if (exists(filename)):
1050 dom = parse(filename)
1051 else:
1052 print "parse_config():", filename, "doesn't exist."
1053 return results
1055 if (dom.childNodes[0].nodeName == 'config'):
1056 for node in dom.childNodes[0].childNodes:
1058 if (node.nodeName == 'window_title'):
1059 results['window_title'] = node.childNodes[0].nodeValue
1061 if (node.nodeName == 'log'):
1062 results['log'] = node.childNodes[0].nodeValue
1064 if (node.nodeName == 'name'):
1065 results['name'] = node.childNodes[0].nodeValue
1067 if (node.nodeName == 'font'):
1068 results['font'] = node.childNodes[0].nodeValue
1070 if (node.nodeName == 'init'):
1071 results['init'] = node.childNodes[0].nodeValue
1073 if (node.nodeName == 'message_port'):
1074 results['message_port'] = int(node.childNodes[0].nodeValue)
1076 if (node.nodeName == 'broadcast_port'):
1077 results['broadcast_port'] = int(node.childNodes[0].nodeValue)
1079 if (node.nodeName == 'broadcast_bind'):
1080 results['broadcast_bind'] = int(node.childNodes[0].nodeValue)
1082 if (node.nodeName == 'fullscreen'):
1083 results['fullscreen'] = int(node.childNodes[0].nodeValue)
1085 if (node.nodeName == 'background_color'):
1087 string_parts = node.childNodes[0].nodeValue.split()
1088 results['background_color'] = [float(string_parts[0]), float(string_parts[1])]
1089 results['background_color'].append(float(string_parts[2]))
1090 results['background_color'].append(float(string_parts[3]))
1092 if (node.nodeName == 'window_size'):
1094 string_parts = node.childNodes[0].nodeValue.split()
1095 results['window_size'] = ((int(string_parts[0]), int(string_parts[1])))
1097 if (node.nodeName == 'gravity'):
1099 string_parts = node.childNodes[0].nodeValue.split()
1100 results['gravity'] = [float(string_parts[0]), float(string_parts[1])]
1101 results['gravity'].append(float(string_parts[2]))
1103 if (node.nodeName == 'step_size'):
1104 results['step_size'] = float(node.childNodes[0].nodeValue)
1106 if (node.nodeName == 'pack_dir'):
1107 results['pack_dir'] = node.childNodes[0].nodeValue
1109 results['error'] = 0
1111 return results
1113 if __name__ == '__main__':
1114 main()