class Lienzo(gtk.DrawingArea): def __init__(self, ventana): """""" super(Lienzo, self).__init__() #Cambiar el color de fondo de la ventana self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0,0,0)) # Pedir el tamano de la ventana self.set_size_request(WINDOW_SIZE,WINDOW_SIZE) #Asignar la ventana que recibe de paramentro a la ventana que se #utilizara en el lienzo self.ventana=ventana #expose-event es una propiedad de DrawingArea que le dice como #dibujares, aqui le decimos que utilize nuestra funcion paint #para ese evento en vez del que trae por defaul. self.connect("expose-event", self.paint) #reconocer cuando oprimes y sueltas el mouse self.connect("button_press_event",self.button_press) self.connect("button_release_event",self.button_release) self.connect("motion_notify_event",self.actualizar_dragged) self.set_events(gtk.gdk.BUTTON_PRESS_MASK|gtk.gdk.BUTTON_RELEASE_MASK|gtk.gdk.POINTER_MOTION_MASK) #Inicializar todos los valores self.init_simulation(None) self.hud=Hud() #celulas self.annealedCells=cellList+stationList self.virus=vir self.annealingCompleted=False self.initialized=False self.allVisited=False self.visitedCells=0 self.nextCell=None self.draggingObject = None self.corriendo = True self.bestEnergy=0 self.currentEnergy=0 self.currentTemp=0 self.objetoSeleccionado=[] def actualizar_dragged(self,widget,event): if self.draggingObject: self.draggingObject.posX=event.x self.draggingObject.posY=event.y def on_timer(self): self.update() return True def init_simulation(self,widget): """Inicializacion de valores""" gobject.timeout_add(20, self.on_timer) def update(self): self.queue_draw() if self.annealingCompleted and not vir[0].isDead: self.set_virus_vel() vir[0].update() for cell in self.annealedCells: cell.update(); def set_virus_vel(self): if not self.initialized: self.initialized=True vir[0].posX=self.annealedCells[0].get_center()[0]-(vir[0].width/2) vir[0].posY=self.annealedCells[0].get_center()[1]-(vir[0].height/2) self.nextCell=self.annealedCells[0] [vCenterX,vCenterY]=vir[0].get_center() [cCenterX,cCenterY]=self.nextCell.get_center() deltaX=abs(vCenterX-cCenterX) deltaY=abs(vCenterY-cCenterY) if vCenterX>cCenterX: vir[0].velX=-1.0*self.vel_with_delta(deltaX,deltaY,'X') elif vCenterX<cCenterX: vir[0].velX=1.0*self.vel_with_delta(deltaX,deltaY,'X') else: vir[0].velX=0 if vCenterY>cCenterY: vir[0].velY=-1.0*self.vel_with_delta(deltaX,deltaY,'Y') elif vCenterY<cCenterY: vir[0].velY=1.0*self.vel_with_delta(deltaX,deltaY,'Y') else: vir[0].velY=0 if (vCenterX>cCenterX-1 and vCenterX<cCenterX+1) and (vCenterY>cCenterY-1 and vCenterY<cCenterY+1): if self.nextCell in self.annealedCells: self.nextCell.isDead="True" if self.nextCell.get_type()=="Health Station": self.nextCell.alpha=(0.2); if self.nextCell.get_type()=="Cell" and not vir[0].isDead: self.nextCell.deltaRot=0; self.nextCell.alpha=0.2; self.visitedCells=1+self.annealedCells.index(self.nextCell) if self.visitedCells==len(self.annealedCells): self.allVisited=True lastCell=self.nextCell if not self.allVisited: self.nextCell=self.annealedCells[self.visitedCells] vir[0].hp-=self.distance(lastCell, self.nextCell) if isinstance(lastCell,HealthStation): vir[0].hp+=lastCell.healRatio if vir[0].hp>vir[0].maxHp: vir[0].hp=vir[0].maxHp if vir[0].transHp<=0: vir[0].isDead=True def distance(self,a, b): return sqrt(pow(a.posX - b.posX,2) + pow(a.posY - b.posY,2)) def vel_with_delta(self,deltaX,deltaY,axis): if axis=='X': if deltaX>deltaY: return 1 else: return deltaX/deltaY else: if deltaY>deltaX: return 1 else: return deltaY/deltaX def paint(self, widget, event): """Nuestro metodo de pintado propio""" #Se crea un widget de cairo que despues se usara para desplegar #todo en la ventana cr = widget.window.cairo_create() #Le decimos a cairo que pinte su widget por primera vez. cr.set_source_rgb(0,0,0) cr.paint() #pintar a los agentes #display_lines(cr, self.annealedCells) display_simulation(cr,vir,self.annealedCells) self.hud.display(cr, vir+self.annealedCells) cr.move_to(5,15) text="Temperature = %f" % self.currentTemp cr.show_text(text) cr.move_to(5,30) text="Best Energy = %f" % self.bestEnergy cr.show_text(text) cr.move_to(5,45) text="Current Energy = %f" % self.currentEnergy cr.show_text(text) #pintar efecto de selección sobre un agente if self.objetoSeleccionado: cr.set_line_width(2) cr.set_source_rgba(random.random(), 1, random.random(), 0.3) cr.rectangle(self.objetoSeleccionado.posX-20,self.objetoSeleccionado.posY-20, self.objetoSeleccionado.width+40, self.objetoSeleccionado.height+40) cr.stroke() #pintar la información del agente seleccionado #Para drag & drop def button_press(self,widget,event): if event.button == 1: self.objetoSeleccionado=[] lstTemp = antibodyList+vir+self.annealedCells for ob in lstTemp: if ob.drag(event.x,event.y): self.draggingObject = ob self.objetoSeleccionado=ob break def button_release(self,widget,event): if self.draggingObject: self.draggingObject.drop(event.x,event.y) self.draggingObject = None def pausar(self): self.corriendo=False def correr(self): self.corriendo=True def regenerar(self): for cell in self.annealedCells: cell.isDead=False if isinstance(cell,Cell): cell.hp=cell.maxHp cell.deltaRot = 0.05*random.choice([1,-1]) cell.status=None cell.isAvailable=True cell.alpha=1 vir[0].hp=1000 vir[0].transHp=1000 vir[0].isDead=False self.annealingCompleted=False self.initialized=False self.allVisited=False self.visitedCells=0 self.nextCell=None self.bestEnergy=0 self.currentEnergy=0 self.currentTemp=0
def main(): logg.info('Starting the main function') #Instancing, etc. main_view = View().from_rect( FloatRect(0, 0, PP_WIDTH, PP_HEIGHT + BAR_HEIGHT)) window = RenderWindow( VideoMode(PP_WIDTH * SCALE, (PP_HEIGHT + BAR_HEIGHT) * SCALE), GAME_TITLE + ' v.' + GAME_VERSION) window.framerate_limit = 61 window.view = main_view # INITIALIZE TEXTURES HERE OR AFTER \o/ TEXTURE_WALL = Texture.load_from_file('main/walls.png') TEXTURE_BAR = Texture.load_from_file('main/bar.png') TEXTURE_HUDWEAPONS = Texture.load_from_file('main/hud_weapons.png') TEXTURE_FACES = Texture.load_from_file('main/faces.png') TEXTURE_NUMBERS = Texture.load_from_file('main/numbers.png') TEXTURE_WEAPONS = Texture.load_from_file('main/weapons.png') TEXTURE_ENEMIES = Texture.load_from_file('main/test.png') #Create an instance for all game variables and loop functions # and set the level to TESTLEVEL game = Gameworld(TEXTURE_ENEMIES) game.create_dict_map() game.player.gamemap = game.current_level game.init_physics() game.physics.mob_bodies(game.entities) #prepare the hud hud = Hud(player=game.player, background=TEXTURE_BAR, faces=TEXTURE_FACES, hudweapons=TEXTURE_HUDWEAPONS, weapons=TEXTURE_WEAPONS, numbers=TEXTURE_NUMBERS) #prepare the wall textures wall_sprites = game.create_wall_sprite_list(TEXTURE_WALL) rays = Raycaster(player=game.player, sprites=wall_sprites, gamemap=game.current_level) #prepare other stuff player_action = '' running = True nofocus = False ## # MAIN LOOP ## logg.info('Main loop starting...') while running: #iterate events for event in window.iter_events(): if event.type == Event.CLOSED or player_action == 'quit': running = False if event.type == Event.LOST_FOCUS: nofocus = True elif event.type == Event.GAINED_FOCUS: nofocus = False if event.type == Event.KEY_RELEASED: if game.player.bob > 0: #level the headbobbing game.player.bob -= .5 elif game.player.bob < 0: game.player.bob += .5 game.player.strafing = False #disable speed limiter for moving in 2 axii window.clear(Color(235, 235, 235, 255)) #clear the window of everything for sprite in wall_sprites: #draw walls window.draw(sprite) #draw entities here for entity in game.entities: if entity.visible == True: for sprite_slice in entity.sprite: window.draw(sprite_slice) hud.display(window) #draw the hud debug_txt = text('[' + str(draw_fps(frame)) + '] ' + str("{0:.2f}".format(game.player.ux)) + '(' + str(game.player.x) + '),' + str("{0:.2f}".format(game.player.uy)) + '(' + str(game.player.y) + '):' + str(game.player.heading), style=1) window.draw(debug_txt) wall_sprites = rays.texture_slices( rays.cast_rays(), wall_sprites, game.player.bob) #determine which walls to display #determine wich entities to display and prepare for entity in game.entities: #calculate the distance of entities to the player entity.distance_to_player(game.player) # print(str(round(entity.distance, 2)) + " " + str(entity.x) + "," + str(entity.y)) game.entities.sort(key=lambda x: x.distance, reverse=True) #sort entities based on the distance for entity in game.entities: entity.set_sprite_for_display(game.player, rays.distances) ### # TIMERS ### if game.player.attack_delay > 0 and game.player.attack == True: game.player.attack_delay -= 1 elif game.player.attack == True and game.player.attack_delay == 0: game.player.attack = False game.player.attack_delay = 2 elif game.player.attack == False and game.player.attack_delay > 0: game.player.attack_delay -= 1 if len(game.doors) != 0: # print('lol doors') for door in game.doors: # print(door.openess) state = door.open_close() # print(state) if state == 'done': # print('removing doors') game.doors.remove(door) game.physics.world.ClearForces() if not nofocus: player_action = game.handle_keys() #player input game.physics.world.Step(1.0 / 60.0, 10, 8) game.player.update_position() for entity in game.entities: entity.update_position() window.display() #blit to window window.close() logg.info('Terminating. Have a nice day.') logg.info('Average FPS: %s', round(average_fps / all_frames, 2))
def main(): logg.info("Starting the main function") # Instancing, etc. main_view = View().from_rect(FloatRect(0, 0, PP_WIDTH, PP_HEIGHT + BAR_HEIGHT)) window = RenderWindow( VideoMode(PP_WIDTH * SCALE, (PP_HEIGHT + BAR_HEIGHT) * SCALE), GAME_TITLE + " v." + GAME_VERSION ) window.framerate_limit = 61 window.view = main_view # INITIALIZE TEXTURES HERE OR AFTER \o/ TEXTURE_WALL = Texture.load_from_file("main/walls.png") TEXTURE_BAR = Texture.load_from_file("main/bar.png") TEXTURE_HUDWEAPONS = Texture.load_from_file("main/hud_weapons.png") TEXTURE_FACES = Texture.load_from_file("main/faces.png") TEXTURE_NUMBERS = Texture.load_from_file("main/numbers.png") TEXTURE_WEAPONS = Texture.load_from_file("main/weapons.png") TEXTURE_ENEMIES = Texture.load_from_file("main/test.png") # Create an instance for all game variables and loop functions # and set the level to TESTLEVEL game = Gameworld(TEXTURE_ENEMIES) game.create_dict_map() game.player.gamemap = game.current_level game.init_physics() game.physics.mob_bodies(game.entities) # prepare the hud hud = Hud( player=game.player, background=TEXTURE_BAR, faces=TEXTURE_FACES, hudweapons=TEXTURE_HUDWEAPONS, weapons=TEXTURE_WEAPONS, numbers=TEXTURE_NUMBERS, ) # prepare the wall textures wall_sprites = game.create_wall_sprite_list(TEXTURE_WALL) rays = Raycaster(player=game.player, sprites=wall_sprites, gamemap=game.current_level) # prepare other stuff player_action = "" running = True nofocus = False ## # MAIN LOOP ## logg.info("Main loop starting...") while running: # iterate events for event in window.iter_events(): if event.type == Event.CLOSED or player_action == "quit": running = False if event.type == Event.LOST_FOCUS: nofocus = True elif event.type == Event.GAINED_FOCUS: nofocus = False if event.type == Event.KEY_RELEASED: if game.player.bob > 0: # level the headbobbing game.player.bob -= 0.5 elif game.player.bob < 0: game.player.bob += 0.5 game.player.strafing = False # disable speed limiter for moving in 2 axii window.clear(Color(235, 235, 235, 255)) # clear the window of everything for sprite in wall_sprites: # draw walls window.draw(sprite) # draw entities here for entity in game.entities: if entity.visible == True: for sprite_slice in entity.sprite: window.draw(sprite_slice) hud.display(window) # draw the hud debug_txt = text( "[" + str(draw_fps(frame)) + "] " + str("{0:.2f}".format(game.player.ux)) + "(" + str(game.player.x) + ")," + str("{0:.2f}".format(game.player.uy)) + "(" + str(game.player.y) + "):" + str(game.player.heading), style=1, ) window.draw(debug_txt) wall_sprites = rays.texture_slices( rays.cast_rays(), wall_sprites, game.player.bob ) # determine which walls to display # determine wich entities to display and prepare for entity in game.entities: # calculate the distance of entities to the player entity.distance_to_player(game.player) # print(str(round(entity.distance, 2)) + " " + str(entity.x) + "," + str(entity.y)) game.entities.sort(key=lambda x: x.distance, reverse=True) # sort entities based on the distance for entity in game.entities: entity.set_sprite_for_display(game.player, rays.distances) ### # TIMERS ### if game.player.attack_delay > 0 and game.player.attack == True: game.player.attack_delay -= 1 elif game.player.attack == True and game.player.attack_delay == 0: game.player.attack = False game.player.attack_delay = 2 elif game.player.attack == False and game.player.attack_delay > 0: game.player.attack_delay -= 1 if len(game.doors) != 0: # print('lol doors') for door in game.doors: # print(door.openess) state = door.open_close() # print(state) if state == "done": # print('removing doors') game.doors.remove(door) game.physics.world.ClearForces() if not nofocus: player_action = game.handle_keys() # player input game.physics.world.Step(1.0 / 60.0, 10, 8) game.player.update_position() for entity in game.entities: entity.update_position() window.display() # blit to window window.close() logg.info("Terminating. Have a nice day.") logg.info("Average FPS: %s", round(average_fps / all_frames, 2))