Beispiel #1
0
def init(self):
    print_log("\t Creating monsters...")
    self.create_object(200, Bat)
    self.create_object(100, Zombie)
    self.create_object(100, Lych)
    self.create_object(100, Ghast)
    self.create_object(10, Cat)
    def _run(self):
        "запуск сервера"

        self.running = True

        self.insock.listen(self.listen_num)
        self.outsock.listen(self.listen_num)
        
        #регистрируем сокеты на ожидание подключений
        self._register_in(self.insock.fileno())
        self._register_in(self.outsock.fileno())

        log_data = (self.hostname, IN_PORT, OUT_PORT, self.poll_engine)
        print_log('\nServer running at %s:(%s,%s) multiplexer: %s \n' % log_data)

        try:
            #запускаем sender
            self._sender_thread.start()
        
            #запускаем мультиплексор
            self._run_poll()
        except:
            self._handle_exception(*exc_info())

        finally:
            self.stop()
    def _handle_accept(self, stream):
        "прием одного из двух соединений"
        assert stream in (IN, OUT)

        if stream is IN:
            sock = self.insock
            s_name = 'input'

        else:
            sock = self.outsock
            s_name = 'output'

        conn, (address, fileno) = sock.accept()
        conn.setblocking(0)

        print_log('%s Connection from %s (%s)' % (s_name, fileno, address))
        
        if address not in self._address_buf:
            self._address_buf[address] = conn
        else:
            buf_address = self._address_buf.pop(address)

            if stream == IN:
                self._accept_client(conn, buf_address)

            else:
                self._accept_client(buf_address, conn)
Beispiel #4
0
def init(self):
    print_log('\t Creating monsters...')
    self.create_object(200, Bat)
    self.create_object(100, Zombie)
    self.create_object(100, Lych)
    self.create_object(100, Ghast)
    self.create_object(10, Cat)
 def save(self, force=False):
     if force:
         worlds_objects = self.save_objects()
         data = compress(dumps(worlds_objects))
         with open(PICKLE_PATH % self.mapname, 'wb') as w_file:
             w_file.write(data)
             print_log('world %s saved' % self.name)
Beispiel #6
0
    def _handle_accept(self, stream):
        "прием одного из двух соединений"
        assert stream in (IN, OUT)

        if stream is IN:
            sock = self.insock
            s_name = 'input'

        else:
            sock = self.outsock
            s_name = 'output'

        conn, (address, fileno) = sock.accept()
        conn.setblocking(0)

        print_log('%s Connection from %s (%s)' % (s_name, fileno, address))

        if address not in self._address_buf:
            self._address_buf[address] = conn
        else:
            buf_address = self._address_buf.pop(address)

            if stream == IN:
                self._accept_client(conn, buf_address)

            else:
                self._accept_client(buf_address, conn)
Beispiel #7
0
    def _run(self):
        "запуск сервера"

        self.running = True

        self.insock.listen(self.listen_num)
        self.outsock.listen(self.listen_num)

        #регистрируем сокеты на ожидание подключений
        self._register_in(self.insock.fileno())
        self._register_in(self.outsock.fileno())

        log_data = (self.hostname, IN_PORT, OUT_PORT, self.poll_engine)
        print_log('\nServer running at %s:(%s,%s) multiplexer: %s \n' %
                  log_data)

        try:
            #запускаем sender
            self._sender_thread.start()

            #запускаем мультиплексор
            self._run_poll()
        except:
            self._handle_exception(*exc_info())

        finally:
            self.stop()
 def save(self, force = False):
     if force:
         worlds_objects = self.save_objects()
         data = compress(dumps(worlds_objects))
         with open(PICKLE_PATH % self.mapname, 'wb') as w_file:
             w_file.write(data)
             print_log('world %s saved' % self.name)
Beispiel #9
0
 def start(self):
     print_log('Starting world "%s"' % self.name)
     result = self.load_objects()
     if not result:
         print_log('Generating world "%s", this could take a while' % self.name)
         self.generate_func(self)
     self.init_func(self)
Beispiel #10
0
def init(self):     
        print_log('\t Creating monsters...')

        self.create_object(200, Bat)
        self.create_object(200, Zombie)
        self.create_object(50, Lych)
        self.create_object(50, Ghast)
        self.create_object(30, Cat)
Beispiel #11
0
def generate(self):
    print_log("\t Creating teleports...")
    self.create_item(150, GetTeleport(UpStair, "underground"))

    print_log("\t Creating decorartions...")
    self.create_item(10000, Stone)
    self.create_item(10000, Mushroom)
    self.create_item(200, Rubble)
    self.create_item(400, choice(items))
Beispiel #12
0
def generate(self):
    print_log('\t Creating teleports...')
    self.create_item(150, GetTeleport(UpStair, 'underground'))

    print_log('\t Creating decorartions...')
    self.create_item(10000, Stone)
    self.create_item(10000, Mushroom)
    self.create_item(200, Rubble)
    self.create_item(400, choice(items))
Beispiel #13
0
 def get_location(self, position):
     "возвращает слокацию"
     
     i, j = (position / TILESIZE / LOCATIONSIZE).get()
     try:
         return self.locations[i][j]
     except IndexError as Error:
         print_log('Warning: invalid location cord %s[%s:%s]' % (self.name,i, j))
         raise Error
Beispiel #14
0
    def game_quit(self, name):
        "выход игрока из игры"

        print_log('%s quit' % name)
        game.remove_guided(name)

        game.guided_changed = True
    
    
                
Beispiel #15
0
    def clear_static_objects(self):
        "удаляет статические оъекты добавленные для удаления"
        if self.remove_static_list:
            for name, force in self.remove_static_list.items():
                if name in self.static_objects:
                    player = self.static_objects[name]
                    self.remove_object(player, force)
                else:
                    print_log("Warning: clear_static_objects, %s not in location list" % name)

            self.remove_static_list.clear()
def load_map(mapname): 
    map_file = WORLD_PATH % mapname + 'map.marshal.zlib'
    map_image = WORLD_PATH % mapname + 'map.png'
    dict_file = WORLD_PATH % mapname + 'tiledict.py'

    
    if os.path.exists(map_file):
        with  open(map_file,'rb') as mapfile:
            readed = mapfile.read()
        try:
            decompressed = decompress(readed)
            tmap = loads(decompressed)
        except Exception as error:
            print_log('Error: "%s" while loading %s' % (error, map_file))
        else:
            print_log('\t map loaded from data file')
            tilemap, size, background =  tmap
            return tilemap, size, background
    else:
        print_log("\t map data file doesn't exist")

    print_log('Generating tilemap "for" %s' % mapname)
    from PIL import Image
    

    tiledict = imp.load_source('tiledict',dict_file).tiledict

    counter = Counter()
    image = Image.open(map_image)
    size = image.size
    m = image.load()
    
    tilemap =[]
    for i in range(size[0]):
        row=[]
        for j in range(size[1]):
            color = m[i,j][:3]
            tile = tiledict[color]
            counter[tile]+=1
            row.append(tile)
        tilemap.append(row)
        
    print_log('\tmap loaded:',size)
    
    
    background = counter.most_common()[0][0]

    saved_map = bytes(compress(dumps((tilemap, size[0], background))))

    with open(map_file,'wb') as mapfile:
        mapfile.write(saved_map)
    
    return tilemap, size[0], background
Beispiel #17
0
    def clear_static_objects(self):
        "удаляет статические оъекты добавленные для удаления"
        if self.remove_static_list:
            for name, force in self.remove_static_list.items():
                if name in self.static_objects:
                    player = self.static_objects[name]
                    self.remove_object(player, force)
                else:
                    print_log(
                        'Warning: clear_static_objects, %s not in location list'
                        % name)

            self.remove_static_list.clear()
Beispiel #18
0
def generate(self):
    print_log('\t Creating teleports...')

    self.create_item(200, GetTeleport(Stair, 'ground'))
    self.create_item(150, GetTeleport(DeepCave, 'underground2'))

    print_log('\t Creating decorartions...')

    self.create_item(6000, Mushroom)
    self.create_item(100, WaterFlower)
    self.create_item(5000, Stone)
    self.create_item(50, Rubble)

    self.create_item(200, choice(items))
Beispiel #19
0
def load_map(mapname):
    map_file = WORLD_PATH % mapname + 'map.marshal.zlib'
    map_image = WORLD_PATH % mapname + 'map.png'
    dict_file = WORLD_PATH % mapname + 'tiledict.py'

    if os.path.exists(map_file):
        with open(map_file, 'rb') as mapfile:
            readed = mapfile.read()
        try:
            decompressed = decompress(readed)
            tmap = loads(decompressed)
        except Exception as error:
            print_log('Error: "%s" while loading %s' % (error, map_file))
        else:
            print_log('\t map loaded from data file')
            tilemap, size, background = tmap
            return tilemap, size, background
    else:
        print_log("\t map data file doesn't exist")

    print_log('Generating tilemap "for" %s' % mapname)
    from PIL import Image

    tiledict = imp.load_source('tiledict', dict_file).tiledict

    counter = Counter()
    image = Image.open(map_image)
    size = image.size
    m = image.load()

    tilemap = []
    for i in range(size[0]):
        row = []
        for j in range(size[1]):
            color = m[i, j][:3]
            tile = tiledict[color]
            counter[tile] += 1
            row.append(tile)
        tilemap.append(row)

    print_log('\tmap loaded:', size)

    background = counter.most_common()[0][0]

    saved_map = bytes(compress(dumps((tilemap, size[0], background))))

    with open(map_file, 'wb') as mapfile:
        mapfile.write(saved_map)

    return tilemap, size[0], background
Beispiel #20
0
def generate(self):
        print_log('\t Creating teleports...')

        self.create_item(200, GetTeleport(Stair, 'ground'))
        self.create_item(150, GetTeleport(DeepCave, 'underground2'))
        
        print_log('\t Creating decorartions...')

        self.create_item(6000, Mushroom)
        self.create_item(100, WaterFlower)
        self.create_item(5000, Stone)
        self.create_item(50, Rubble)

        self.create_item(200, choice(items))
Beispiel #21
0
    def game_connect(self, name):
        "создание нового игрока"

        #выбираем позицию для нового игрока
        position = game.mainworld.choice_position(Player, ask_player=True)
        #создаем игрока
        new_player = Player(name, position)
        game.mainworld.new_object(new_player)
        
        game.guided_changed = True
        print_log('New player %s' % name)

        #оставляем сообщение о подключении
        yield ServerAccept()
        for message in new_player.accept_response():
            yield message
Beispiel #22
0
    def stop(self, stop_reason=''):
        "остановка всего сервера"
        #считаем среднее время на раунд
        print_log('%s \n GameServer stopping...' % str(stop_reason))

        try:
            self.server.stop()
        finally:
            count = len(self.r_times)
            if count:
                all_time = sum(self.r_times)
                m_time = all_time / count
                print_log('median time %s/%s = %s' % (all_time, count, m_time))

            if isinstance(stop_reason, BaseException):
                raise stop_reason
Beispiel #23
0
    def stop(self, stop_reason=''):
        "остановка всего сервера"
        #считаем среднее время на раунд
        print_log('%s \n GameServer stopping...' % str(stop_reason))

        try:
            self.server.stop()
        finally:
            count = len(self.r_times)
            if count:
                all_time = sum(self.r_times)
                m_time = all_time / count
                print_log('median time %s/%s = %s' % (all_time, count, m_time))

            if isinstance(stop_reason, BaseException):
                raise stop_reason
    def load_objects(self):
        if self.world_exists():
            print_log('Loading world %s from pickle' % self.name)
            with open(PICKLE_PATH % self.mapname, 'rb') as w_file:
                data = w_file.read()
            worlds_objects = loads(decompress(data))

            for object_type, data in worlds_objects:
                #print_log 'loading', object_type, data
                object_type = self.get_class(object_type)
                data = object_type.__load__(*data)
                player = object_type(*data)
                self.new_object(player)
            return True
        else:
            print_log("world pickle doesn't exist")
            return False
    def load_objects(self):
        if self.world_exists():
            print_log('Loading world %s from pickle' % self.name)
            with open(PICKLE_PATH % self.mapname, 'rb') as w_file:
                data = w_file.read()
            worlds_objects = loads(decompress(data))

            for object_type, data in worlds_objects:
                #print_log 'loading', object_type, data
                object_type = self.get_class(object_type)
                data = object_type.__load__(*data)
                player = object_type(*data)
                self.new_object(player)
            return True
        else:
            print_log("world pickle doesn't exist")
            return False
Beispiel #26
0
 def add_event(self, name, object_type, position, vector, action, args=(), timeout=0):
     "добавляет событие"
     event = Event(name, object_type, position, action, args, timeout)
     
     i, j = self.get_loc_cord(position).get()
     try:
         self.locations[i][j].add_event(event)
     except IndexError:
         print_log('location IndexError', i,j)
 
     if vector:
         alt_position = position + vector
         event = Event(name, object_type, alt_position, action, args, timeout)
         i, j = self.get_loc_cord(alt_position).get()
         try:
             self.locations[i][j].add_event(event)
         except IndexError:
             print_log('location IndexError %s[%s:%s] %s' (self.name, i, j, name))
    def _handle_close(self, client_name, message):
        "хэндлер на закрытие подключения"

        print_log('Closing %s: %s' % (client_name, message))
        
        self._closed.put_nowait(client_name)
        
        infileno = self.clients[client_name].insock.fileno()
        outfileno = self.clients[client_name].outsock.fileno()
        
        self._unregister(infileno)
        
        del self.infilenos[infileno]
        del self.outfilenos[outfileno]
    
        #закрываем подключения и удаляем
        self.clients[client_name].insock.close()
        self.clients[client_name].outsock.close()
        del self.clients[client_name]
Beispiel #28
0
    def _handle_close(self, client_name, message):
        "хэндлер на закрытие подключения"

        print_log('Closing %s: %s' % (client_name, message))

        self._closed.put_nowait(client_name)

        infileno = self.clients[client_name].insock.fileno()
        outfileno = self.clients[client_name].outsock.fileno()

        self._unregister(infileno)

        del self.infilenos[infileno]
        del self.outfilenos[outfileno]

        #закрываем подключения и удаляем
        self.clients[client_name].insock.close()
        self.clients[client_name].outsock.close()
        del self.clients[client_name]
    def _accept_client(self, insock, outsock):
        "регистрация клиента, после того как он подключился к обоим сокетам"

        client_name = 'player_%s' % self.client_counter
        self.client_counter += 1
        
        self.clients[client_name] = client_tuple(insock, outsock, receivable(insock))
        
        insock_fileno = insock.fileno()
        outsock_fileno = outsock.fileno()
        
        self.infilenos[insock_fileno] = client_name
        self.outfilenos[outsock_fileno] = client_name
        
        self._register_in(insock_fileno)

        print_log('accepting_client %s' % client_name)

        #реагируем на появление нового клиента
        self._accepted.put_nowait(client_name)
Beispiel #30
0
    def _accept_client(self, insock, outsock):
        "регистрация клиента, после того как он подключился к обоим сокетам"

        client_name = 'player_%s' % self.client_counter
        self.client_counter += 1

        self.clients[client_name] = client_tuple(insock, outsock,
                                                 receivable(insock))

        insock_fileno = insock.fileno()
        outsock_fileno = outsock.fileno()

        self.infilenos[insock_fileno] = client_name
        self.outfilenos[outsock_fileno] = client_name

        self._register_in(insock_fileno)

        print_log('accepting_client %s' % client_name)

        #реагируем на появление нового клиента
        self._accepted.put_nowait(client_name)
    def _run_poll(self):
        print_log("Start polling")
        while not self._stop_event.is_set():
            event_pairs = self._poller.poll()
            while event_pairs:
                fileno, event = event_pairs.pop()
                try:
                    if fileno == self.in_fileno:
                        self._handle_accept(IN)

                    elif fileno == self.out_fileno:
                        self._handle_accept(OUT)

                    elif event == EPOLLIN:
                        if fileno in self.infilenos:
                            client_name = self.infilenos[fileno]
                            self._handle_read(client_name)

                    elif event == EPOLLHUP:
                        self._handle_error(Error, fileno, event)

                except socket_error as Error:
                    print_log("socket_error", Error)
                    self._handle_error(Error, fileno, event)
        print_log("polling end")
Beispiel #32
0
    def _run_poll(self):
        print_log('Start polling')
        while not self._stop_event.is_set():
            event_pairs = self._poller.poll()
            while event_pairs:
                fileno, event = event_pairs.pop()
                try:
                    if fileno == self.in_fileno:
                        self._handle_accept(IN)

                    elif fileno == self.out_fileno:
                        self._handle_accept(OUT)

                    elif event == EPOLLIN:
                        if fileno in self.infilenos:
                            client_name = self.infilenos[fileno]
                            self._handle_read(client_name)

                    elif event == EPOLLHUP:
                        self._handle_error(Error, fileno, event)

                except socket_error as Error:
                    print_log('socket_error', Error)
                    self._handle_error(Error, fileno, event)
        print_log('polling end')
    def stop(self, reason=None):
        "остановка сервера"
        if self.running:
            print_log('SocketServer stopping..')

            self._unregister(self.in_fileno)
            self._unregister(self.out_fileno)
                
            self.insock.close()
            self.outsock.close()

            self._stop_event.set()

            #closing queues
            self._accepted.close()
            self._closed.close()
            self._requestes.close()
            self._responses.close()

            print_log('Waiting for sender thread')
            self._sender_thread._Thread__stop()
            self._sender_thread.join()

            self.running = False
Beispiel #34
0
    def stop(self, reason=None):
        "остановка сервера"
        if self.running:
            print_log('SocketServer stopping..')

            self._unregister(self.in_fileno)
            self._unregister(self.out_fileno)

            self.insock.close()
            self.outsock.close()

            self._stop_event.set()

            #closing queues
            self._accepted.close()
            self._closed.close()
            self._requestes.close()
            self._responses.close()

            print_log('Waiting for sender thread')
            self._sender_thread._Thread__stop()
            self._sender_thread.join()

            self.running = False
Beispiel #35
0
 def start(self):
     print_log('Engine initialization...')
     
     self.worlds = {}
     self.worlds['ground'] = MetaWorld(self, 'ground')
     self.worlds['underground'] = MetaWorld(self, 'underground')
     self.worlds['underground2'] = MetaWorld(self, 'underground2')
     self.mainworld = self.worlds['ground']
     
     for world in self.worlds.values():
         print_log('\n world %s initialization' % world.name)
         world.start()
         world.save(True)
     
     print_log('\n Engine initialization complete. \n')
Beispiel #36
0
    def start(self):
        print_log('Engine initialization...')

        self.worlds = {}
        self.worlds['ground'] = MetaWorld(self, 'ground')
        self.worlds['underground'] = MetaWorld(self, 'underground')
        self.worlds['underground2'] = MetaWorld(self, 'underground2')
        self.mainworld = self.worlds['ground']

        for world in self.worlds.values():
            print_log('\n world %s initialization' % world.name)
            world.start()
            world.save(True)

        print_log('\n Engine initialization complete. \n')
Beispiel #37
0
    def _sender(self):
        "поток отправляющий ответы из очереди"
        try:
            while not self._stop_event.is_set():
                client_name, response = self._responses.get()
                if client_name in self.clients:
                    sock = self.clients[client_name].outsock
                    try:
                        send(sock, response)
                    except socket_error as error:
                        print_log('sender error', str(error))
            print_log('sender stop')

        except Exception as error:
            print_log('snder', error)
            self._handle_exception(*exc_info())
    def _sender(self):
        "поток отправляющий ответы из очереди"
        try:
            while not self._stop_event.is_set():
                client_name, response = self._responses.get()
                if client_name in self.clients:
                    sock = self.clients[client_name].outsock
                    try:
                        send(sock, response)
                    except socket_error as error:
                        print_log('sender error', str(error))
            print_log('sender stop')

        except Exception as error:
            print_log('snder', error)
            self._handle_exception(*exc_info())
Beispiel #39
0
def generate(self):
        print_log('Generating world, this can take a while...')
        print_log('\t Creating teleports...')

        self.create_item(200, GetTeleport(Cave, 'underground'))
        
        print_log('\t Creating decorartions...')

        self.create_item(5000, Stone)
        self.create_item(5000, Mushroom)
        self.create_item(7000, Plant)
        self.create_item(20000, Flower)
        self.create_item(1500, WaterFlower) 
        self.create_item(300, BigWaterFlower) 
        self.create_item(13000, AloneTree)
        self.create_item(1000, AloneBush)
        self.create_item(100, WindMill)

        self.create_item(100, choice(items))
    def _run_poll(self):
        "ожидание входящих пакетов с совкетов, обработка новых подключений"
        print_log("Start polling")
        while not self.stop_event.is_set():
            print_log("polling")
            # смотрим новые подключения и на чтение
            insocks = [client.insock for client in self.clients.values()]
            timeout = SERVER_TIMER * 1.5  # - (time()-t)
            events = select([self.insock, self.outsock] + insocks, [], [], timeout)[0]
            for sock in events:
                fileno = sock.fileno()
                if fileno == self.in_fileno:
                    self._handle_accept(IN)
                elif fileno == self.out_fileno:
                    self._handle_accept(OUT)
                else:
                    client_name = self.infilenos[fileno]
                    self._handle_read(client_name)
            self.write_all()

        print_log("Stop polling")
Beispiel #41
0
    def _run_poll(self):
        "ожидание входящих пакетов с совкетов, обработка новых подключений"
        print_log('Start polling')
        while not self.stop_event.is_set():
            print_log('polling')
            #смотрим новые подключения и на чтение
            insocks = [client.insock for client in self.clients.values()]
            timeout = SERVER_TIMER * 1.5  #- (time()-t)
            events = select([self.insock, self.outsock] + insocks, [], [],
                            timeout)[0]
            for sock in events:
                fileno = sock.fileno()
                if fileno == self.in_fileno:
                    self._handle_accept(IN)
                elif fileno == self.out_fileno:
                    self._handle_accept(OUT)
                else:
                    client_name = self.infilenos[fileno]
                    self._handle_read(client_name)
            self.write_all()

        print_log('Stop polling')
Beispiel #42
0
 def unset_activity(self):
     key = self.cord.get()
     if key in self.world.active_locations:
         del self.world.active_locations[key]
     else:
         print_log("key error", key)
Beispiel #43
0
 def unset_activity(self):
     key = self.cord.get()
     if key in self.world.active_locations:
         del self.world.active_locations[key]
     else:
         print_log('key error', key)
Beispiel #44
0
    def start(self):
        print_log('Running...')
        stop_reason = 'None'
        try:
            self.server.start()
            print_log('GameServer running')
            t = time()
            while 1:
                if not self.server.excp.empty():
                    print_log('error in SocketServer')
                    stop_reason = self.server.excp.get_nowait()
                    break

                r_time = time()

                self.game_worker()

                self.r_times.append(time() - r_time)

                delta = time() - t
                timeout = SERVER_TIMER - delta if delta < SERVER_TIMER else 0
                t = time()
                sleep(timeout)
            print_log('game loop end')

        except KeyboardInterrupt:
            stop_reason = 'KeyboardInterrupt'
            self.game.save()
            print_log('stop_reason:', stop_reason)

        except:
            except_type, except_class, tb = exc_info()
            print_log('exception!', except_type, except_class)
            for line in traceback.extract_tb(tb):
                print_log(line)

        finally:
            print_log('game loop exit')

            self.stop(stop_reason)
            sys_exit()
 def __init__(self, mapname):
     self.mapname = mapname
     print_log('loading map %s ...' % self.mapname)
     self.map, self.size, self.background = load_map(mapname)
Beispiel #46
0
    def start(self):
        print_log('Running...')
        stop_reason = 'None'
        try:
            self.server.start()
            print_log('GameServer running')
            t = time()
            while 1:
                if not self.server.excp.empty():
                    print_log('error in SocketServer')
                    stop_reason = self.server.excp.get_nowait()
                    break

                r_time = time()
            
                self.game_worker()
                
                self.r_times.append(time() - r_time)
                
                delta = time() - t
                timeout = SERVER_TIMER - delta if delta < SERVER_TIMER else 0
                t = time()
                sleep(timeout)
            print_log('game loop end')

        except KeyboardInterrupt:
            stop_reason = 'KeyboardInterrupt'
            self.game.save()
            print_log('stop_reason:', stop_reason)

        except:
            except_type, except_class, tb = exc_info()
            print_log('exception!', except_type, except_class)
            for line in traceback.extract_tb(tb):
                print_log(line)

        finally:
            print_log('game loop exit')
         
            self.stop(stop_reason)
            sys_exit()
 def __init__(self, mapname):
     self.mapname = mapname
     print_log('loading map %s ...' % self.mapname)
     self.map, self.size, self.background = load_map(mapname)