Example #1
0
    def shoot(self):
        target = self.pos + self.last_dir
        ents = engine.metagrid.get_entities(target.x, target.y)

        log('found %s' % ents)
        if not LAYER_BLOCKS in ents:
            FireBall(pos=target, dir=self.last_dir)
Example #2
0
    def shoot(self):
        target = self.pos + self.last_dir
        ents = engine.metagrid.get_entities(target.x, target.y)

        log('found %s' % ents)
        if not LAYER_BLOCKS in ents:
            FireBall(pos=target,dir=self.last_dir)
Example #3
0
 def add_entity(self, new_guy, moving=False):
     if hasattr(new_guy, "pos") and (new_guy.pos):
         self.metagrid.add_entity(new_guy, moving)
     else:
         if not isinstance(new_guy, Updater):
             log("Why add %s, a ghost that does not update?" % new_guy)
         self.ghosts[new_guy.id] = new_guy
Example #4
0
 def spawn_dude(self, dude=None):
     if not dude:
         log ('spawning dude for %s' % self)
         dude = Player()
     self.dude = dude 
     self.dude.owner = self
     self.dude.on_die = self.handle_player_die
     self.inform_player_of_dude()
Example #5
0
 def spawn_dude(self, dude=None):
     if not dude:
         log('spawning dude for %s' % self)
         dude = Player()
     self.dude = dude
     self.dude.owner = self
     self.dude.on_die = self.handle_player_die
     self.inform_player_of_dude()
Example #6
0
 def remove_entity(self, ent):
     if ent.layer in self.entities:
         other = self.entities.pop(ent.layer)
         return True
     log('%s was not in %s' % (ent, self.entities))
     from entity import NoSuchEntity
     import pdb
     pdb.set_trace()
     raise NoSuchEntity('No such entity %s at' % (ent))
Example #7
0
    def get_cell(self, x, y):
        x, y = self.wrap_coords(x, y)
        g_x = (x / GRID_SIZE) * GRID_SIZE
        g_y = (y / GRID_SIZE) * GRID_SIZE

        #log("%d,%d converted to %d,%d" % (x,y, g_x, g_y))
        if not (g_x, g_y) in self.cells:
            log("FATAL: unknown metagrid cell %d,%d" % (g_x, g_y))
            log('cells are: %s ' % self.cells)
            sys.exit()
        else:
            res = self.cells[(g_x, g_y)]

        return res
Example #8
0
    def use(self):
        target_pos = self.pos + self.last_dir
        dudes = engine.get_entities(target_pos.x,target_pos.y)
        move = False
        
        if self.carrying:  
            smasher = self.carrying
            for layer in [LAYER_BLOCKS, 
                          LAYER_GROUND_DETAIL,
                          LAYER_GROUND]:
                if layer in dudes: 
                    if smasher.can_smash(dudes[layer]):
                        log('%s can smash %s' % (smasher, dudes[layer]))
                        self.carrying = None
                        smasher.smash(dudes[layer])
                    break
            return
        #not carrying anything  
        #check for an item to act on
        neighbors = engine.metagrid.get_neighbors(self.pos)


        #see if you're looking at a water square
        if self.last_dir in neighbors:
            dudes = neighbors[self.last_dir]
            if not LAYER_BLOCKS in dudes and\
                dudes[LAYER_GROUND].terrain_type == 'water':

                WaterDrop(pos=self.pos+self.last_dir)
                return 

        if self.last_dir in neighbors:
            dudes = neighbors[self.last_dir]
            for layer in [LAYER_BLOCKS,
                            LAYER_GROUND_DETAIL,
                            LAYER_GROUND]:
                if layer in dudes:
                    other_guy = dudes[layer]
                    if isinstance(other_guy, Carryable):
                        self.carry_item(other_guy)
                    elif isinstance(other_guy, Consumable):
                        self.consume(other_guy)
                        other_guy.die(self)
                    else: 
                        Air(self.pos).smash(other_guy)
                    #once we've encounterd an object, we're done
                    break
Example #9
0
 def on_message(self, message):
     msg = json.loads(message)
     if 'dir' in msg:
         self.dir = DIRS[msg['dir']]
     elif 'act' in msg:
         self.act = msg['act']
     elif 'name' in msg:
         self.name = msg['name']
         if self.name in clients_by_name:
             log('We know this client: ' + self.name)
             client = clients_by_name[self.name]
             log('client has dude %s' % client.dude)
             self.spawn_dude(client.dude)
             client.die(self)
             clients_by_name[self.name] = self
         else:
             clients_by_name[self.name] = self
             self.spawn_dude(Player())
Example #10
0
 def on_message(self, message):                        
     msg = json.loads(message)
     if 'dir' in msg:
         self.dir = DIRS[msg['dir']]
     elif 'act' in msg:
         self.act = msg['act']
     elif 'name' in msg:
         self.name = msg['name']
         if self.name in clients_by_name:
             log ('We know this client: ' +self.name)
             client = clients_by_name[self.name] 
             log ('client has dude %s' % client.dude)
             self.spawn_dude(client.dude)
             client.die(self)
             clients_by_name[self.name] = self
         else:
             clients_by_name[self.name] = self
             self.spawn_dude(Player())
Example #11
0
    def __init__(self, **kwargs):

        pos = kwargs.get('pos') or None
        dist = kwargs.get('dist') or None
        if not pos or not dist:
            log('FireRing needs position and distance')
            return

        def circle_visitor(x, y):
            ents = engine.metagrid.get_entities(x, y)
            if LAYER_BLOCKS in ents:
                dude = ents[LAYER_BLOCKS]
                if isinstance(ents, Flammable):
                    Fire.burn(self, other)
                    return
            else:
                FirePuff(pos=vector2(x, y))

        engine.metagrid.visit_circle(pos.x, pos.y, dist, circle_visitor)
Example #12
0
    def use(self):
        target_pos = self.pos + self.last_dir
        dudes = engine.get_entities(target_pos.x, target_pos.y)
        move = False

        if self.carrying:
            smasher = self.carrying
            for layer in [LAYER_BLOCKS, LAYER_GROUND_DETAIL, LAYER_GROUND]:
                if layer in dudes:
                    if smasher.can_smash(dudes[layer]):
                        log('%s can smash %s' % (smasher, dudes[layer]))
                        self.carrying = None
                        smasher.smash(dudes[layer])
                    break
            return
        #not carrying anything
        #check for an item to act on
        neighbors = engine.metagrid.get_neighbors(self.pos)

        #see if you're looking at a water square
        if self.last_dir in neighbors:
            dudes = neighbors[self.last_dir]
            if not LAYER_BLOCKS in dudes and\
                dudes[LAYER_GROUND].terrain_type == 'water':

                WaterDrop(pos=self.pos + self.last_dir)
                return

        if self.last_dir in neighbors:
            dudes = neighbors[self.last_dir]
            for layer in [LAYER_BLOCKS, LAYER_GROUND_DETAIL, LAYER_GROUND]:
                if layer in dudes:
                    other_guy = dudes[layer]
                    if isinstance(other_guy, Carryable):
                        self.carry_item(other_guy)
                    elif isinstance(other_guy, Consumable):
                        self.consume(other_guy)
                        other_guy.die(self)
                    else:
                        Air(self.pos).smash(other_guy)
                    #once we've encounterd an object, we're done
                    break
Example #13
0
    def __init__(self, **kwargs):

        pos = kwargs.get('pos') or None
        dist = kwargs.get('dist') or None
        if not pos or not dist : 
            log('FireRing needs position and distance')
            return

        def circle_visitor(x,y):
            ents = engine.metagrid.get_entities(x,y)
            if  LAYER_BLOCKS in ents:
                dude = ents[LAYER_BLOCKS]
                if isinstance(ents, Flammable):
                    Fire.burn(self,other)
                    return
            else:
                FirePuff(pos=vector2(x,y))

        engine.metagrid.visit_circle(pos.x, pos.y,
                            dist, circle_visitor)
Example #14
0
        def get_real_item(item):

            if isinstance(item, unicode):
                return str(item)

            if isinstance(item, dict):
                if "_type" in item:
                    if item["_type"] == "vector2":
                        return vector2(item["vec"][0], item["vec"][1])
                    if item["_type"] == "ent":
                        log("making entity wrapper.")
                        return PersistedWrapper(item["ent_id"])

                    elif item["_type"] == "dict":
                        res = {}
                        for kvp in item["pairs"]:
                            res[get_real_item(kvp[0])] = get_real_item(kvp[1])
                        return res

            return item
Example #15
0
    def build_world(self):

        generate = True

        if generate:
            log("Generating world.")
            if USE_DATASTORE:
                self.datastore.entities.remove()

        for x in range(METAGRID_SIZE):
            for y in range(METAGRID_SIZE):
                g_x = x * GRID_SIZE
                g_y = y * GRID_SIZE
                # log('new metacell at %d, %d' % (g_x, g_y))
                cell = self.metagrid.add_cell(g_x, g_y)

                if generate and self.game:
                    self.game.new_metagrid_cell(cell)
        if generate:
            if self.game != None:
                self.game.build_world()
            self.save_world(save_terrain=True)
        else:
            log("Loading world")
            entities = self.datastore.entities.find()

            for ent in entities:
                ent_dict = {}
                for var in ent:
                    ent_dict[str(var)] = ent[var]
                guy = entity_class_registry[ent["__class__"]](**ent_dict)
            log("Load complete")
Example #16
0
    def save_world(self, save_terrain=False):

        if not USE_DATASTORE:
            return
        log("saving world..")

        for cell in self.metagrid.cells:
            self.metagrid.cells[cell].persist()
            if save_terrain:
                self.metagrid.cells[cell].persist_terrain()
        log("saving ghosts.")
        for ghost in self.ghosts:
            log("persisting %s" % self.ghosts[ghost])
            self.ghosts[ghost].persist(self.datastore)
        log("saving complete.")
Example #17
0
    def __init__(self, **kwargs):
        "Creating a new client."
        log('Creating a new client object')
        self.updates = 0
        self.dir = ZERO_VECTOR

        self.watching = {}
        self.act = None
        self.bomb = None
        self.bomb_cooldown = 0
        self.name = random.choice([
            "Chumpalicious", "Nooborama", "Wussomatic", "Llamatastic",
            "Failarious"
        ])
        self.death_count = 0
        self.kill_count = 0
        self.disconnected = False
        self.dude = None
        Entity.__init__(self)
        engine.client_manager.add_client(self)
        self.name = kwargs.get('name') or self.id
        log("%s joined the game" % self)
        clients_by_name[self.name] = self
Example #18
0
 def __init__(self, **kwargs):
     "Creating a new client." 
     log ('Creating a new client object') 
     self.updates =  0 
     self.dir = ZERO_VECTOR 
    
     self.watching = {}
     self.act = None
     self.bomb = None
     self.bomb_cooldown = 0
     self.name = random.choice([ "Chumpalicious",
                                 "Nooborama",
                                 "Wussomatic",
                                 "Llamatastic",
                                 "Failarious"])
     self.death_count = 0
     self.kill_count = 0
     self.disconnected = False
     self.dude = None
     Entity.__init__(self)
     engine.client_manager.add_client(self)
     self.name = kwargs.get('name') or self.id 
     log ("%s joined the game" % self)
     clients_by_name[self.name] = self
Example #19
0
    def build_world(self):

        #add some water 
        log ('building world: adding water')
        num_cells = (METAGRID_SIZE*GRID_SIZE)**2
        num_water_cells = int(num_cells*0.05/float(METAGRID_SIZE**2))
        for c in range(num_water_cells):
            x = random.choice(range(GRID_SIZE*METAGRID_SIZE))
            y = random.choice(range(GRID_SIZE*METAGRID_SIZE))

            engine.get_entities(x,y)[LAYER_GROUND].to_water()


        #now add some trees and fruit
        num_bomb_cells =  num_cells*2/(GRID_SIZE*GRID_SIZE)
        log('building world: adding %d bombs' % num_bomb_cells)
        choices =  { 
                         Sheep: GRID_SIZE*0.4,
                         FirePuff : GRID_SIZE*0.4,
                         Coal : GRID_SIZE*0.7,
                         Tree : GRID_SIZE*0.75,
                         Wolf : GRID_SIZE*0.3,
                         Stone: GRID_SIZE*0.3,
                         }

 
        for choice in [Tree] * 4 + \
                      [Coal] * 2 + \
                      [Stone] * 3 + \
                      [Sheep] * 2:
            
            x = random.choice(range(GRID_SIZE*METAGRID_SIZE))
            y = random.choice(range(GRID_SIZE*METAGRID_SIZE))
        

            def get_dudes():
                x = random.choice(range(GRID_SIZE*METAGRID_SIZE))
                y = random.choice(range(GRID_SIZE*METAGRID_SIZE))
                return engine.metagrid.get_entities(x,y)

            dudes = get_dudes() 
            while dudes[LAYER_GROUND].terrain_type == 'water':
                dudes = get_dudes()

            log ('got a dude')
            dudes[LAYER_GROUND].start_forest(choice, choices[choice])
Example #20
0
 def __init__(self, application, request):
     tornado.websocket.WebSocketHandler.__init__(self, application, request)
     """sets up the socket sender"""
     log('New client connected: %s' % self.request)
Example #21
0
engine.game = game
engine.build_world()

settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "static"),
    "cookie_secret": "61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
    "login_url": "/login",
    "xsrf_cookies": True,
}
application = tornado.web.Application(
    [(r"/", MainHandler), (r"/js/([A-z|0-9]+).js", JSHandler),
     (r'/ws', SocketConnectionHandler, {}),
     (r'/images/([A-z]+).png', ImageHandler)], **settings)

if __name__ == "__main__":
    log("Starting Tornado web server on port 8000!")
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8000)
    main_loop = tornado.ioloop.IOLoop.instance()
    scheduler = tornado.ioloop.PeriodicCallback(game.update,
                                                TICK_PERIOD,
                                                io_loop=main_loop)
    scheduler2 = tornado.ioloop.PeriodicCallback(engine.save_world,
                                                 TICK_PERIOD * 100,
                                                 io_loop=main_loop)

    scheduler.start()
    scheduler2.start()
    log("Server started, entering main loop.")
    main_loop.start()
Example #22
0
 def __init__(self, application, request):
     tornado.websocket.WebSocketHandler.__init__(self, application, request)
     """sets up the socket sender""" 
     log ('New client connected: %s' % self.request)
Example #23
0
    def send_deltas(self):
        if not self.dude:
            return
        #check to make sure the guy can see what's around him
        old_watching = {}
        for cell_pos in self.watching:
            old_watching[cell_pos] = True
        #we need to know how the set of what this guy's watching
        #has changed
        newly_watched = {}
        still_watching = {}
        now_watching = {}
        no_longer_watching = {}
        for dir in ALL_DIRS + [ZERO_VECTOR]:
            cell = self.get_neighbor(dir)

            if not cell:
                log('No cell for direction %s' % dir)
                import pdb
                pdb.set_trace()
            if not cell.get_pos() in old_watching:
                newly_watched[cell] = cell.get_pos()
            now_watching[cell] = cell.get_pos()

        for cell_pos in old_watching:
            cell = engine.metagrid.get_cell(cell_pos.x, cell_pos.y)
            if not cell in now_watching:
                no_longer_watching[cell] = True
            else:
                still_watching[cell] = True

        params = (len(now_watching), len(newly_watched), len(still_watching),
                  len(no_longer_watching))

        #do some sanity checks
        for cell in newly_watched:
            if cell in still_watching:
                log("%s was in newly AND still watched!" % cell)
            if cell in no_longer_watching:
                log("%s was in newly AND no longer watched!" % cell)
        for cell in still_watching:
            if cell in no_longer_watching:
                log("%s was in still and no longer watching!" % cell)
        #now go through each of these sells and send them
        #the appropriate message
        for cell in newly_watched:
            #log('now watching %s' % cell)
            if cell and cell.current_state:
                self.send(cell.current_state)
        for cell in still_watching:
            if cell and cell.last_delta and self.delta_matters(
                    cell.last_delta):
                #log('sending delta for %s' % cell)
                self.send(cell.last_delta)

        for cell in no_longer_watching:
            #log ('no longer watching %s' % cell)
            if cell and cell.drop_message:
                self.send(cell.drop_message)

        self.watching = {}
        for cell in now_watching:
            self.watching[cell.get_pos()] = True
Example #24
0
    def send_deltas(self):
        if not self.dude:
            return 
        #check to make sure the guy can see what's around him
        old_watching = {}
        for cell_pos in self.watching:
            old_watching[cell_pos] = True
        #we need to know how the set of what this guy's watching
        #has changed
        newly_watched = {}
        still_watching = {}
        now_watching = {}
        no_longer_watching = {}
        for dir in ALL_DIRS + [ZERO_VECTOR]:
            cell = self.get_neighbor(dir)

            if not cell:
                log ('No cell for direction %s' % dir)
                import pdb
                pdb.set_trace()
            if not cell.get_pos() in old_watching:                
                newly_watched[cell] = cell.get_pos()
            now_watching[cell] = cell.get_pos()

        for cell_pos in old_watching:
            cell = engine.metagrid.get_cell(cell_pos.x, cell_pos.y)
            if not cell in now_watching:
                no_longer_watching[cell] = True 
            else:
                still_watching[cell] = True 
                
        params = (len(now_watching), len(newly_watched),
                  len(still_watching), len(no_longer_watching))

        #do some sanity checks
        for cell in newly_watched:
            if cell in still_watching:
                log("%s was in newly AND still watched!" % 
                            cell)
            if cell in no_longer_watching:
                log("%s was in newly AND no longer watched!" %
                        cell)
        for cell in still_watching:
            if cell in no_longer_watching:
                log("%s was in still and no longer watching!" % cell) 
        #now go through each of these sells and send them 
        #the appropriate message
        for cell in newly_watched:
            #log('now watching %s' % cell)
            if cell and cell.current_state:
                self.send(cell.current_state)
        for cell in still_watching:
            if cell and cell.last_delta and self.delta_matters(cell.last_delta):
                #log('sending delta for %s' % cell)
                self.send(cell.last_delta) 

        for cell in no_longer_watching:
            #log ('no longer watching %s' % cell)
            if cell and cell.drop_message:
                self.send(cell.drop_message)
        
        self.watching = {} 
        for cell in now_watching:
            self.watching[cell.get_pos()] = True
Example #25
0
engine.build_world()

    
settings = {
"static_path": os.path.join(os.path.dirname(__file__), "static"),
"cookie_secret": "61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
"login_url": "/login",
"xsrf_cookies": True,
}
application = tornado.web.Application(
    [ (r"/", MainHandler),
      (r"/js/([A-z|0-9]+).js", JSHandler),
      (r'/ws', SocketConnectionHandler, { }),
      (r'/images/([A-z]+).png', ImageHandler)
    
    
    ], **settings)

if __name__ == "__main__":
    log("Starting Tornado web server on port 8000!")
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8000)
    main_loop = tornado.ioloop.IOLoop.instance();
    scheduler = tornado.ioloop.PeriodicCallback(game.update, TICK_PERIOD, io_loop = main_loop)    
    scheduler2 = tornado.ioloop.PeriodicCallback(engine.save_world,  TICK_PERIOD*100, io_loop = main_loop)    

    scheduler.start()
    scheduler2.start()
    log("Server started, entering main loop.")
    main_loop.start()