diff options
author | flavio <fdanesse@gmail.com> | 2011-11-29 13:33:44 (GMT) |
---|---|---|
committer | flavio <fdanesse@gmail.com> | 2011-11-29 13:33:44 (GMT) |
commit | d5e03972be8573ba991e49371d5b488bfea10557 (patch) | |
tree | 9c3b4c2a4af27cac80769ef0dea4152863e941da | |
parent | 0eb784a6c1d5ce6e56a6ebfd86b67826e391a322 (diff) |
Integrando a gtk y re modelandoJAMTank2
-rw-r--r-- | Enlace_Red_JAMtank.py | 18 | ||||
-rw-r--r-- | Globals.py (renamed from Variables.py) | 61 | ||||
-rw-r--r-- | Graficos_JAMtank.py | 18 | ||||
-rw-r--r-- | JAMtank.py | 438 | ||||
-rw-r--r-- | Main.py | 118 | ||||
-rw-r--r-- | Manejador_de_Eventos.py | 23 | ||||
-rw-r--r-- | TCP_Server_thread_Stream.py | 62 |
7 files changed, 293 insertions, 445 deletions
diff --git a/Enlace_Red_JAMtank.py b/Enlace_Red_JAMtank.py index 0e07704..a81888b 100644 --- a/Enlace_Red_JAMtank.py +++ b/Enlace_Red_JAMtank.py @@ -1,24 +1,6 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# Enlace_Red_JAMtank.py por: -# Flavio Danesse <fdanesse@gmail.com> -# CeibalJAM! - Uruguay -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - import gc, socket, time, os, sys gc.enable() diff --git a/Variables.py b/Globals.py index 92e7fb4..e880ca2 100644 --- a/Variables.py +++ b/Globals.py @@ -1,28 +1,55 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# Variables.py por: -# Flavio Danesse <fdanesse@gmail.com> -# CeibalJAM! - Uruguay -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +import pygame, gc, sys, os, random, platform +from pygame.locals import * +gc.enable() + +if "olpc" in platform.platform(): + os.environ['SDL_AUDIODRIVER'] = 'alsa' + +BASE= os.path.dirname(__file__) +RESOLUCION= (1200,900) +IMAGENES= os.path.join(BASE, "Imagenes") +SONIDOS= os.path.join(BASE, "Sonidos") TERMINATOR = "\r\n\r\n" Tanques={} CARGA = 0 +def Traduce_posiciones(VA, VH): +# Escala eventos de Posición + eventos= pygame.event.get(pygame.MOUSEBUTTONDOWN) + for event in eventos: + x, y = event.pos + xx= x/VA + yy= y/VH + event_pos= (xx, yy) + for event in eventos: + evt = pygame.event.Event(pygame.MOUSEBUTTONDOWN, pos= event_pos, button=event.button) + pygame.event.post(evt) + + eventos= pygame.event.get(pygame.MOUSEMOTION) + for event in eventos: + x, y = event.pos + xx= x/VA + yy= y/VH + event_pos= (xx, yy) + for event in eventos: + evt = pygame.event.Event(pygame.MOUSEMOTION, pos= event_pos, rel=event.rel, buttons=event.buttons) + pygame.event.post(evt) + +def get_ip(): + ip= 'localhost' + try: + ip = string.split(string.split(commands.getoutput("ifconfig | grep Bcast"))[1],":")[1] + except: + ip = string.split(string.split(commands.getoutput("ifconfig | grep Difus"))[1],":")[1] + return ip + +def get_fondo(): + return os.path.join(IMAGENES, "fondo.png") + class Tanque(): def __init__(self, nombre): # Datos del Tanque diff --git a/Graficos_JAMtank.py b/Graficos_JAMtank.py index 4c71603..485644b 100644 --- a/Graficos_JAMtank.py +++ b/Graficos_JAMtank.py @@ -1,24 +1,6 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# Graficos_JAMtank.py por: -# Flavio Danesse <fdanesse@gmail.com> -# CeibalJAM! - Uruguay -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - import pygame, gc from pygame.locals import * @@ -1,320 +1,182 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# gtk_JAMtank_Ventana.py por: -# Flavio Danesse <fdanesse@gmail.com> -# CeibalJAM! - Uruguay -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +import os, gtk, pygtk, gobject, sys, socket, pygame -import pygame from pygame.locals import * - -import gc -gc.enable() - -import socket, SocketServer, gobject, threading, gtk, pygtk, time, string, sys, dbus, os, commands - from sugar.activity import activity -from JAMtank import JAMtank -from TCP_Server_thread_Stream import ThreadedTCPServer, ThreadedTCPRequestHandler - -DIRECTORIODEIMAGENES = os.getcwd()+"/Imagenes/" -DIRECTORIODESONIDOS = os.getcwd()+"/Sonidos/" -PUERTO = 5000 - -# ------ Inicio de Funciones de Presencia ---------- -OLPC_SESSION_BUS = "/tmp/olpc-session-bus" -PRESENCE_SERVICE = "org.laptop.Sugar.Presence" -PRESENCE_PATH = "/org/laptop/Sugar/Presence" -PRESENCE_IFACE = "org.laptop.Sugar.Presence" -BUDDY_IFACE = "org.laptop.Sugar.Presence.Buddy" - -def get_bus(): -# sugar presence - if os.path.exists(OLPC_SESSION_BUS): - address = "unix:path=%s" % OLPC_SESSION_BUS - return dbus.bus.BusConnection(address_or_type=address) - else: - if len(sys.argv) != 2: - sys.exit(1) - - if 'DBUS_SESSION_BUS_ADDRESS' in os.environ: - del os.environ['DBUS_SESSION_BUS_ADDRESS'] - - display = sys.argv[1] - os.environ['DISPLAY'] = display - return dbus.bus.BusConnection() -def get_Xos(): -# devuelve la ip y el nombre de todas las xo en la red -# En realidad devuelve el nick de todas las xo, la ip local y las ip en la mesh de las demás xo - bus = get_bus() - ps = bus.get_object(PRESENCE_SERVICE, PRESENCE_PATH) - ps_iface = dbus.Interface(ps, PRESENCE_IFACE) - buddies = map(lambda b: bus.get_object(PRESENCE_SERVICE, b), ps_iface.GetBuddies()) - - xos = [] - for buddy in buddies: - buddy_iface = dbus.Interface(buddy, BUDDY_IFACE) - try: - props = buddy_iface.GetProperties() - ip = "%s" % (props['ip4-address'].encode('utf-8')) - nick = "%s" % (props['nick'].encode('utf-8')) - xo = (ip, nick) - xos.append(xo) - - except dbus.DBusException: - pass - return xos -# ------ Fin de Funciones de Presencia ---------- - +from Main import Main +import Globals as G -class GTK_JAMtank(activity.Activity): -# Interface gtk +class JAMtank(activity.Activity): def __init__(self, handle): + activity.Activity.__init__(self, handle, False) + self.eventbox= PygameCanvas() + self.set_canvas(self.eventbox) - activity.Activity.__init__(self, handle, False) - - self.set_title("-.JAMtank (versión 1).- -. CeibalJAM! 2010.-") - - pygame.mixer.init(44100, -16, 2, 2048) - pygame.mixer.music.set_volume(1.0) - self.sonido = pygame.mixer.Sound(DIRECTORIODESONIDOS+"Menu.ogg") - - self.jamtank = None - self.servidor = None - self.modo = None - self.estado = "Presentacion" - self.nick = None - self.lista_servidores = None - self.ip = None # ip local - self.ip_server = None # ip servidor - - # Canvas - self.contenedor_principal = gtk.VBox() - - # imagen Creditos - imagen = gtk.Image() - imagen.set_from_file(DIRECTORIODEIMAGENES + "JAMtank.png") - self.contenedor_principal.pack_start(imagen, False, False, 0) - - # Lista de Servidores Activos - # self.contenedor_principal.pack_start(gtk.Label("Servidores JAMtank Actualmente Activos en la Red"), False, False, 0) - - # Lista de Servidores Activos - self.caja_servers = gtk.VBox() - viewport = gtk.ScrolledWindow() - viewport.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) - viewport.add_with_viewport(self.caja_servers) - - frame = gtk.Frame() - frame.add(viewport) - - # busca servidores JAMtank en la red - self.actualiza_servers(None) - - # Botones servidor local, actualizar lista de servidores y salir - caja_botones = gtk.VBox() - - boton_servidor = gtk.Button("Crear Nuevo Juego en Red") - boton_servidor.connect("clicked", self.set_Estado, "servidor", self.ip) - boton_servidor.connect_object("clicked", gtk.Widget.destroy, self) - - boton_scan = gtk.Button("Actualizar Lista de Juegos en la Red") - boton_scan.connect("clicked", self.actualiza_servers) - - boton_salir = gtk.Button("Salir de JAMtank") - boton_salir.connect_object("clicked", self.salir, None) - - caja_botones.pack_start(boton_servidor, True, True, 5) - caja_botones.pack_start(boton_scan, True, True, 5) - caja_botones.pack_end(boton_salir, True, True, 5) - - # imagen Teclado - imagen1 = gtk.Image() - imagen1.set_from_file(DIRECTORIODEIMAGENES + "Teclado.png") - - caja_secundaria = gtk.HBox() - caja_secundaria.pack_start(imagen1, False, False, 0) - caja_secundaria.pack_start(frame, True, True, 5) - caja_secundaria.pack_end(caja_botones, False, False, 5) - - self.contenedor_principal.pack_start(caja_secundaria, True, True, 0) - - # para introducir una IP conocida - #caja = gtk.HBox() - #etiqueta = gtk.Label("IP: ") - self.entrada = None - #conectar = gtk.Button("Conectarse a Esta IP") - #conectar.connect("clicked", self.get_connect_ip_conocida) - #caja.pack_start (etiqueta, False, False, 5) - #caja.pack_start (self.entrada, False, False, 5) - #caja.pack_start (conectar, False, False, 5) - #self.contenedor_principal.pack_start(caja, False, False, 5) - - self.set_canvas(self.contenedor_principal) + self.add_events(gtk.gdk.ALL_EVENTS_MASK) + self.connect("destroy", self.salir) self.show_all() + self.realize() - self.sonido.play(loops=-1) - - # switch gtk pygame - reloj = gobject.timeout_add(500, self.get_Juego) - - def set_entrada_ip_conocida(self): - # objetos para agregar ip de servidor conocido - caja = gtk.HBox() - etiqueta = gtk.Label("Conectarse a (IP): ") - self.entrada = gtk.Entry() - conectar = gtk.Button("Jugar") - conectar.connect("clicked", self.get_connect_ip_conocida) - caja.pack_start (etiqueta, True, True, 5) - caja.pack_start (self.entrada, True, True, 5) - caja.pack_end (conectar, True, True, 5) - caja.show_all() - self.caja_servers.pack_start(caja, False, False, 5) - - def get_connect_ip_conocida(self, widget): - # Conecta a la ip ingresada - ip = self.entrada.get_text() - if ip: - self.set_Estado(None, "cliente", ip) - gtk.Widget.destroy(self) - - def actualiza_servers(self, widget): - # Verifica tener conexión a una red + os.putenv('SDL_WINDOWID', str(self.eventbox.socket.get_id())) + gobject.idle_add(self.get_run_game) - self.lista_servidores = [] + def get_run_game(self): + print "Lanzando JAMtank." + pygame.init() + Main() + return False - # obtiene el nombre de la xo - XOs = get_Xos() - self.ip, self.nick = XOs[0] - - while not self.ip or self.ip == "localhost": - # obtiene el nombre de la xo - XOs = get_Xos() - self.ip, self.nick = XOs[0] - self.get_avisar_no_hay_ip() - - red = self.ip.split(".") - for x in range(2, 254): - ip = "%s.%s.%s.%s" % (red[0],red[1],red[2],x) - thread = threading.Thread( target=self.scan_red, args=( ip, PUERTO) ) - thread.start() - time.sleep(0.02) - - self.get_lista_xos() + def salir(self, widget): + lambda w: gtk.main_quit() + sys.exit() - def scan_red (self, ip, puerto): - # escanea la red en busca del puerto abierto para JAMtant - conexion = socket.socket() +class PygameCanvas(gtk.EventBox): + def __init__(self): + gtk.EventBox.__init__(self) + self.set_flags(gtk.CAN_FOCUS) + self.setup_events() + self.socket = gtk.Socket() + self.add(self.socket) + self.button_state = [0,0,0] + self.mouse_pos = (0,0) + + def setup_events(self): + self.set_events(gtk.gdk.KEY_PRESS | gtk.gdk.EXPOSE | gtk.gdk.POINTER_MOTION_MASK | \ + gtk.gdk.POINTER_MOTION_HINT_MASK | gtk.gdk.BUTTON_MOTION_MASK | \ + gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK) + + self.connect("key-press-event", self.keypress) + self.connect("button_press_event", self.mousedown) + self.connect("motion-notify-event", self.mousemotion) + self.connect('expose-event', self.expose) + self.connect('configure-event', self.resize) + self.connect("focus-in-event", self.set_focus) + + def keypress(self, selfmain, event, parametros= None): + nombre= gtk.gdk.keyval_name(event.keyval) + tipo= pygame.KEYDOWN + unic= str.lower(nombre) + valor= nombre try: - conexion.connect( (ip, puerto) ) - self.lista_servidores.append(ip) + valor= getattr(pygame, "K_%s" % (str.upper(nombre))) + except: + print "no has programado la traduccion de esta tecla: ", nombre + return False + evt = pygame.event.Event(tipo, key= valor, unicode= unic, mod=None) + try: + pygame.event.post(evt) except: pass - conexion.close() - - def get_lista_xos(self): - # arma la lista de xo en la red con server JAMtank corriendo - - for child in self.caja_servers: - self.caja_servers.remove(child) - - self.set_entrada_ip_conocida() - - for ip in self.lista_servidores: - caja = gtk.HBox() - lab_ip = gtk.Label(ip) - conectar = gtk.Button("Jugar") - - conectar.connect("clicked", self.set_Estado, "cliente", ip) - conectar.connect_object("clicked", gtk.Widget.destroy, self) - - caja.pack_start(lab_ip, True, True, 5) - caja.pack_end(conectar, True, True, 5) - caja.show_all() - self.caja_servers.pack_start(caja, False, False, 5) + return False - def get_avisar_no_hay_ip(self): - # Crea un cuadro de dialogo para avisar que no está conectado a ninguna red. - - dialog = gtk.Dialog("Atención !!!", None, gtk.DIALOG_MODAL, None) - - etiqueta0 = gtk.Label("No estás conectado a ninguna Red.") - dialog.vbox.pack_start(etiqueta0, True, True, 5) - - etiqueta1 = gtk.Label("JAMtank es un juego en red, debes conectarte a una Red") - dialog.vbox.pack_start(etiqueta1, True, True, 5) - - dialog.add_button("OK", 1) - dialog.add_button("Cancelar", 2) - - dialog.show_all() - - if dialog.run() == 1: + def mousedown(self, widget, event): + evt = pygame.event.Event(pygame.MOUSEBUTTONDOWN, button= event.button, pos=(int(event.x), int(event.y))) + try: + pygame.event.post(evt) + except: + pass + return False + + def mousemotion(self, widget, event): + x, y, state = event.window.get_pointer() + rel = (x - self.mouse_pos[0], y - self.mouse_pos[1]) + self.mouse_pos= (int(x), int(y)) + self.button_state = [ + state & gtk.gdk.BUTTON1_MASK and 1 or 0, + state & gtk.gdk.BUTTON2_MASK and 1 or 0, + state & gtk.gdk.BUTTON3_MASK and 1 or 0, + ] + evt = pygame.event.Event(pygame.MOUSEMOTION, pos= self.mouse_pos, rel=rel, buttons=self.button_state) + try: + pygame.event.post(evt) + except: + pass + return False + + def expose(self, event, widget): + if pygame.display.get_init(): + try: + pygame.event.post(pygame.event.Event(pygame.VIDEOEXPOSE)) + except: + pass + return False # continue processing + + def resize(self, widget, event): + evt = pygame.event.Event(pygame.VIDEORESIZE, size=(event.width,event.height), width=event.width, height=event.height) + try: + pygame.event.post(evt) + except: pass - elif dialog.run() == 2: - # sale automaticamente - sys.exit() + return False # continue processing - dialog.destroy() + def set_focus(self, container, widget): + try: + pygame.display.update() + except: + pass + self.queue_draw() + return False + +# ----------------------------------------------- +# ******** El Juego en gtk ******** +# ----------------------------------------------- +class VentanaGTK(gtk.Window): + def __init__(self): + gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL) + self.set_title("JAMtank") + self.fullscreen() + + self.socket = gtk.Socket() + self.add(self.socket) + + self.gtkplug= gtkplug() + self.socket.add_id(self.gtkplug.get_id()) + + self.add_events(gtk.gdk.ALL_EVENTS_MASK) + self.connect("destroy", self.salir) + self.connect("set-focus-child", self.refresh) + self.show_all() - def delete_event(self, widget, event, data=None): - # Cierra la ventana gtk - return gtk.FALSE + def refresh(self, widget, datos): + try: + pygame.display.update() + except: + pass + self.queue_draw() + return True def salir(self, widget): - sys.exit() - - def set_Estado(self, widget, modo, ip): - # para poder llamar al juego luego de que se cierre la ventana gtk - self.sonido.stop() pygame.quit() - self.ip_server = ip - self.modo = modo # Servidor o Cliente - self.estado = "Juego" - - #----------------------Juego pygame------------------------------------------------------------- - def get_Juego(self): - # Se llama al juego pygame - if self.estado == "Juego": - if self.modo == "servidor": - server = ThreadedTCPServer((self.ip, PUERTO), ThreadedTCPRequestHandler) - server.allow_reuse_address = True - server.socket.setblocking(0) + sys.exit() - server_thread = threading.Thread(target=server.serve_forever) - server_thread.setDaemon(True) - server_thread.start() - - self.jamtank = JAMtank(ip=self.ip, PUERTO=PUERTO) +class gtkplug(gtk.Plug): + def __init__(self): + gtk.Plug.__init__(self, 0L) + self.set_title("Ventana de Plug") + self.resolucion= (self.get_screen().get_width(),self.get_screen().get_height()) + self.eventbox= PygameCanvas() + self.add(self.eventbox) + self.ventana= None + self.show_all() - elif self.modo == "cliente": - self.jamtank = JAMtank(ip=self.ip_server, PUERTO=PUERTO) - - return False # no volver por acá - else: - pass + self.connect("embedded", self.embed_event) - return True # seguir viniendo por acá - #----------------------Juego pygame------------------------------------------------------------- + os.putenv('SDL_WINDOWID', str(self.eventbox.socket.get_id())) + gobject.idle_add(self.get_run_game) + def get_run_game(self): + pygame.init() + self.eventbox.socket.window.set_cursor(None) + Main() + return False -if __name__ == "__main__": - GTK_JAMtank() - + def embed_event(self, widget): + print "Juego embebido" +if __name__=="__main__": + VentanaGTK() + gtk.main() @@ -1,54 +1,27 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# Main.py por: -# Flavio Danesse <fdanesse@gmail.com> -# CeibalJAM! - Uruguay -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -import pygame, gc, os, string, commands, socket, SocketServer, gobject, threading +import pygame, gc, os, string, commands, socket, SocketServer, gobject, threading, gtk, pygtk, sys from pygame.locals import * from TCP_Server_thread_Stream import ThreadedTCPServer, ThreadedTCPRequestHandler gc.enable() -# Constantes para todo el Juego -RESOLUCIONMONITOR = (1200,900) -DIRECTORIODEIMAGENES = os.getcwd()+"/Imagenes/" -DIRECTORIODESONIDOS = os.getcwd()+"/Sonidos/" -MINOMBRE = os.getpid() # me identifica en el servidor -PUERTO = 5001 +#MINOMBRE= os.getpid() # me identifica en el servidor -# importación de clases para objetos del juego en el cliente from Graficos_JAMtank import Graficos_JAMtank from Manejador_de_Eventos import Manejador_de_Eventos from Jugador_JAMtank import Jugador_JAMtank from Enlace_Red_JAMtank import Enlace_Red_JAMtank -def get_ip(): - ip= 'localhost' - try: - ip = string.split(string.split(commands.getoutput("ifconfig | grep Bcast"))[1],":")[1] - except: - ip = string.split(string.split(commands.getoutput("ifconfig | grep Difus"))[1],":")[1] - return ip +import Globals as G class Main(): - def __init__(self, ip, puerto): + #def __init__(self, ip, puerto): + def __init__(self): + pass + ''' self.objetos_graficos= Graficos_JAMtank(RESOLUCIONMONITOR, DIRECTORIODEIMAGENES, DIRECTORIODESONIDOS) self.objetos_de_eventos= Manejador_de_Eventos() @@ -61,9 +34,50 @@ class Main(): self.reloj = pygame.time.Clock() - self.Run() + self.Run()''' + + # Variables para JAMatrix + self.ventana= None + self.name= "JAMtank" + self.estado= False + + # Variables del Juego + self.fondo= None + self.reloj= None + self.ambiente= None + + # Escalado + self.ventana_real= None + self.resolucionreal= None + self.VA= None + self.VH= None + + self.preset() + self.load() + self.run() + + # ----------- SETEOS ------------- + def preset(self): + pygame.display.set_mode( (0,0), pygame.DOUBLEBUF | pygame.FULLSCREEN, 0) + A, B= G.RESOLUCION + self.ventana = pygame.Surface( (A, B), flags=HWSURFACE ) + self.ventana_real= pygame.display.get_surface() + C= pygame.display.Info().current_w + D= pygame.display.Info().current_h + self.resolucionreal= (C,D) + self.VA= float(C)/float(A) + self.VH= float(D)/float(B) + + def load(self): + #self.fondo= G.get_Fondo_Inicial() + self.fondo= pygame.transform.scale(pygame.image.load(G.get_fondo()), G.RESOLUCION).convert_alpha() + #self.ambiente= G.get_ambiente() + self.reloj = pygame.time.Clock() + #pygame.mixer.music.play(-1) + self.estado= True - def Run(self): + def run(self): + ''' self.objetos_graficos.setup(Jugador_JAMtank=self.protagonista) # Iniciando pygame self.objetos_graficos.iniciar_escenario() # Levantando Escenario y Fondo self.objetos_graficos.set_menu_puntaje() # Levantando Menús para Puntajes @@ -71,12 +85,22 @@ class Main(): self.objetos_de_eventos.setup(Jugador_JAMtank=self.protagonista, Enlace_Red=self.enlace_red) self.protagonista.setup() # Configurando al jugador protagónico (el local) - self.objetos_graficos.set_menu_ip_server(self.enlace_red.direccion_servidor[0]) - pygame.time.wait(3) - self.estado = "En Juego" + self.objetos_graficos.set_menu_ip_server(self.enlace_red.direccion_servidor[0])''' - while self.estado == "En Juego": + self.ventana.blit(self.fondo, (0,0)) + pygame.display.update() + while self.estado: self.reloj.tick(35) + while gtk.events_pending(): + gtk.main_iteration(False) + G.Traduce_posiciones(self.VA, self.VH) + #self.botonesmenu.clear(self.ventana, self.fondo) + #self.botonesmenu.update() + self.handle_event() + pygame.event.clear() + self.ventana_real.blit(pygame.transform.scale(self.ventana, self.resolucionreal), (0,0)) + pygame.display.update() + ''' self.objetos_de_eventos.detectar() # recolectar datos para enviar, recordar que los objetos se actualizan cuando los datos vuelven del server self.enlace_red.buffer_de_salida = self.protagonista.get_datos_para_la_red() @@ -88,10 +112,18 @@ class Main(): self.objetos_graficos.set_menu_jugadores(self.enlace_red.get_jugadores_puntos()) # Dibuja los cambios en pantalla self.objetos_graficos.actualizar() - pygame.time.wait(1) - + pygame.time.wait(1)''' + + def handle_event(self): + for event in pygame.event.get(pygame.KEYDOWN): + tecla= event.key + if tecla== pygame.K_ESCAPE: + #return self.run_dialog_intro(None) + sys.exit() +''' if __name__ == "__main__": ip= get_ip() + server = ThreadedTCPServer((ip, PUERTO), ThreadedTCPRequestHandler) server.allow_reuse_address = True server.socket.setblocking(0) @@ -103,5 +135,5 @@ if __name__ == "__main__": if ip: Main(ip, PUERTO) else: - Main("localhost", PUERTO) + Main("localhost", PUERTO)''' diff --git a/Manejador_de_Eventos.py b/Manejador_de_Eventos.py index 242d40d..b401171 100644 --- a/Manejador_de_Eventos.py +++ b/Manejador_de_Eventos.py @@ -1,24 +1,6 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# Manejador_de_Eventos.py por: -# Flavio Danesse <fdanesse@gmail.com> -# CeibalJAM! - Uruguay -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - import pygame, gc from pygame.locals import * @@ -31,12 +13,11 @@ class Manejador_de_Eventos(): def setup(self, Jugador_JAMtank=None, Enlace_Red=None): # Configurar objetos de eventos para el juego y asociarlos al jugador local - self.red = Enlace_Red print "Seteando Eventos de Usuario para JAMtank" self.protagonista = Jugador_JAMtank - pygame.event.set_blocked([MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, JOYAXISMOTION, JOYBALLMOTION, JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN, - KEYUP, VIDEORESIZE, VIDEOEXPOSE, USEREVENT, QUIT, ACTIVEEVENT]) # bloqueados + pygame.event.set_blocked([MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN, JOYAXISMOTION, JOYBALLMOTION, + JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN,KEYUP, VIDEORESIZE, VIDEOEXPOSE, USEREVENT, QUIT, ACTIVEEVENT]) pygame.event.set_allowed([KEYDOWN]) # permitidos pygame.key.set_repeat(15, 15) # repetición de teclas diff --git a/TCP_Server_thread_Stream.py b/TCP_Server_thread_Stream.py index 5c91858..435aaf9 100644 --- a/TCP_Server_thread_Stream.py +++ b/TCP_Server_thread_Stream.py @@ -1,29 +1,11 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -# TCP_Server_thread_Stream.py por: -# Flavio Danesse <fdanesse@gmail.com> -# CeibalJAM! - Uruguay -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - import time, socket, threading, SocketServer, time from SocketServer import StreamRequestHandler from SocketServer import ThreadingTCPServer -import Variables as ESPEJO +import Globals as G class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.ThreadingTCPServer): ''' Servidor Multihilo para conexiones simultáneas. ''' @@ -99,7 +81,7 @@ class ThreadedTCPRequestHandler(SocketServer.StreamRequestHandler): def recibir_datos(self, datos): # Recibe los datos del jugador conectado - mensajes = str(datos).split(ESPEJO.TERMINATOR) + mensajes = str(datos).split(G.TERMINATOR) #print "Datos Recibidos en Servidor: ", mensajes for mensaje in mensajes: @@ -138,13 +120,13 @@ class ThreadedTCPRequestHandler(SocketServer.StreamRequestHandler): # ---------------------inicio PERSISTENCIA DE DATOS ----------------------------------- def procesar_datos_puntos(self, energia=100, puntaje=0): # hay cambios de puntaje o energía - ESPEJO.Tanques[self.client_address[0]].set_puntos(energia=energia, puntaje=puntaje) - ESPEJO.Tanques[self.client_address[0]].set_jugadores_por_informar_puntaje(ESPEJO.Tanques.keys()) + G.Tanques[self.client_address[0]].set_puntos(energia=energia, puntaje=puntaje) + G.Tanques[self.client_address[0]].set_jugadores_por_informar_puntaje(G.Tanques.keys()) def procesar_datos_balas(self, angulo=0, x=0, y=0): # ha llegado una bala - ESPEJO.Tanques[self.client_address[0]].set_bala(angulo=angulo, x=x, y=y) # crea la bala - ESPEJO.Tanques[self.client_address[0]].set_jugadores_por_informar_disparo(ESPEJO.Tanques.keys()) + G.Tanques[self.client_address[0]].set_bala(angulo=angulo, x=x, y=y) # crea la bala + G.Tanques[self.client_address[0]].set_jugadores_por_informar_disparo(G.Tanques.keys()) # pasa la lista de todos los jugadores para informar del disparo, a medida que se informa, se eliminan de la lista def procesar_datos_tanques(self, nombre=None, angulo=0, x=0, y=0): @@ -153,20 +135,20 @@ class ThreadedTCPRequestHandler(SocketServer.StreamRequestHandler): # si no hay nombre no puede procesarse return - if not self.client_address[0] in ESPEJO.Tanques.keys(): + if not self.client_address[0] in G.Tanques.keys(): # Si no existe, se agrega - ESPEJO.Tanques[self.client_address[0]] = ESPEJO.Tanque(nombre) - ESPEJO.Tanques[self.client_address[0]].set_datos_tanque(nombre=nombre, angulo=angulo, x=x, y=y) + G.Tanques[self.client_address[0]] = G.Tanque(nombre) + G.Tanques[self.client_address[0]].set_datos_tanque(nombre=nombre, angulo=angulo, x=x, y=y) else: # Si existe se actualiza - ESPEJO.Tanques[self.client_address[0]].set_datos_tanque(nombre=nombre, angulo=angulo, x=x, y=y) + G.Tanques[self.client_address[0]].set_datos_tanque(nombre=nombre, angulo=angulo, x=x, y=y) # ---------------------fin PERSISTENCIA DE DATOS ----------------------------------- def enviar_datos(self): # A quien se conectó se le envían los datos de todos, también los suyos. mensaje = "" - for jugador in ESPEJO.Tanques.values(): # para todos los jugadores. + for jugador in G.Tanques.values(): # para todos los jugadores. mensaje += jugador.get_datos_tanque() # obtener las posiciones de tanques. bala = jugador.get_bala() @@ -182,16 +164,16 @@ class ThreadedTCPRequestHandler(SocketServer.StreamRequestHandler): mensaje += jugador.get_puntos() jugador.jugadores_por_informar_puntaje.remove(self.client_address[0]) # borrar de la lista, ya se le informó - if self.client_address[0] in ESPEJO.Tanques.keys(): + if self.client_address[0] in G.Tanques.keys(): # evitar error de escaner de red de los clientes - if ESPEJO.Tanques[self.client_address[0]].desconectados: + if G.Tanques[self.client_address[0]].desconectados: # si hay información de desconexión de algún jugador - mensaje += ESPEJO.Tanques[self.client_address[0]].desconectados - ESPEJO.Tanques[self.client_address[0]].desconectados = "" + mensaje += G.Tanques[self.client_address[0]].desconectados + G.Tanques[self.client_address[0]].desconectados = "" - if len(mensaje) > ESPEJO.CARGA: - ESPEJO.CARGA = len(mensaje) - print "Carga en la red: ", ESPEJO.CARGA + if len(mensaje) > G.CARGA: + G.CARGA = len(mensaje) + print "Carga en la red: ", G.CARGA self.request.send(mensaje) def setup(self): @@ -202,13 +184,13 @@ class ThreadedTCPRequestHandler(SocketServer.StreamRequestHandler): def finish(self): # Llamado despues de la handle() para realizar cualquier método de limpieza. La implementación predeterminada no hace nada. - if self.client_address[0] in ESPEJO.Tanques.keys(): + if self.client_address[0] in G.Tanques.keys(): # si está en la lista, porque da error cuando los clientes escanean la red en busca de servers, pero no están en el juego aun. print "Server Finish" - for jugador in ESPEJO.Tanques.values(): + for jugador in G.Tanques.values(): # para informar a todos los jugadores sobre la desconexión de otro jugador - jugador.desconectados += "DES %s%s" % (ESPEJO.Tanques[self.client_address[0]].nombre, ESPEJO.TERMINATOR) - del ESPEJO.Tanques[self.client_address[0]] + jugador.desconectados += "DES %s%s" % (G.Tanques[self.client_address[0]].nombre, G.TERMINATOR) + del G.Tanques[self.client_address[0]] #return SocketServer.BaseRequestHandler.finish(self) return |