Example #1
0
 def parse_event(event_dict):
     new_playlist = get_element(event_dict, "playlist")
     if new_playlist:
         return MusicEvent(new_playlist)
     else:
         log("Invalid arg playlist for MusicEvent",1)
         return None
Example #2
0
 def execute_event(self, name):
     log(str(self.event[name]))
     try:
         if self.event[name]:
             self.event[name].execute()
     except KeyError as e:
         log("Error: No such event: %s"%(name)+str(e), 1)
Example #3
0
    def parse_image(image_data, pos, size, angle):
        if pos is None:
            log("Invalid arg pos not defined for Image", 1)
            return None
        path = get_element(image_data, "path")
        if path is not None:
            path = CONST.path_prefix + path

        parallax_factor = get_element(image_data, "parallax_factor")
        if parallax_factor is None:
            parallax_factor = 1.0

        image = Image(pos, size=size, angle=angle, path=path, parallax_factor=parallax_factor)

        tmp = get_element(image_data, "tmp")
        if tmp is not None:
            image.tmp = tmp
        else:
            image.tmp = False

        anim_data = get_element(image_data, "anim")
        if anim_data:
            image.anim = Animation.parse_animation(anim_data, image)
        image.init_image(size)
        return image
Example #4
0
def init():
    global update_thread, self_id,sock
    data = "ID_REQUEST;"
    new_id_request = None

    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((HOST, PORT))
        sock.sendall(data)
        new_id_request = sock.recv(1024)
    except socket.error as e:
        sock.close()
        sock = None
        log("Network init: "+str(e),1)
        return

    self_id = new_id_request.split(";")[1]

    get_thread = Thread(target=client_get)
    get_thread.daemon = True
    get_thread.start()

    set_thread = Thread(target=client_set)
    set_thread.daemon = True
    set_thread.start()
Example #5
0
def linear_distribution(rogue_map, type_nmb, radius):
    size = Vector2(len(rogue_map),len(rogue_map[0]))
    #generate map
    for i in range(size.x):
        for j in range(size.y):
            log(str(i)+" "+str(j))
            around_tile = [0 for x in range(type_nmb)]
            radius_list = range(radius+1)
            radius_list.extend(map((lambda n: -n),range(1,radius+1)))
            for x in radius_list:
                for y in radius_list:
                    if rogue_map[(i-x)%size.x][(j-y)%size.y] == 0:
                        continue
                    else:
                        around_tile[rogue_map[(i-x)%size.x][(j-y)%size.y]-1]+=1
            total_value = 0
            for x in around_tile:
                total_value += x+1
            dice_value = random.random()
            tile_index = 0


            prob = 0.0
            while prob+(float(around_tile[tile_index]+1)/total_value) < dice_value:
                #log(str(dice_value)+str(around_tile)+str(tile_index))
                prob += (float(around_tile[tile_index]+1)/total_value)
                tile_index+=1
            rogue_map[i][j] = tile_index+1
Example #6
0
 def parse_event(event_dict):
     value_name = get_element(event_dict, "name")
     if value_name:
         return IncreaseValueEvent(value_name)
     else:
         log("Invalid arg for IncreaseValueEvent", 1)
         return None
Example #7
0
 def parse_event(event_dict):
     path = get_element(event_dict, "path")
     if path:
         return SoundEvent(path)
     else:
         log("Invalid arg path for SoundEvent",1)
         return None
Example #8
0
def get_players_request():
    global sock
    try:
        if not sock:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((HOST, PORT))
        sock.sendall("GET_REQUEST;")
        get_request_nmb = sock.recv(1024)
        #log(get_request_nmb)
        try:
            nmb = int(get_request_nmb.split(';')[1])
            sock.sendall("%i;"%nmb)

            length = 5
            for i in range(nmb):
                get_request_data = sock.recv(1024)
                #log(get_request_data)
                """Position"""
                parsed_data = get_request_data.split(';')
                parsed_data[1] = parsed_data[1].split(',')
                parsed_data[1] = Vector2(int(float(parsed_data[1][0])), int(float(parsed_data[1][1])))
                """Frame"""
                parsed_data[3] = int(parsed_data[3])

                """update players position"""
                players[parsed_data[0]] = parsed_data
                sock.sendall("NEXT")
        except IndexError:
            pass
    except socket.error as e:
        sock.close()
        sock = None
        log("Network get: "+str(e),1)
        return
Example #9
0
 def parse_event(event_dict):
     value_name = get_element(event_dict, "name")
     new_value = get_element(event_dict, "value")
     if value_name and new_value:
         return SetValueEvent(value_name, new_value)
     else:
         log("Invalid arg for IncreaseValueEvent", 1)
         return None
Example #10
0
 def load_image(self, name, tmp=False):
     try:
         self.img_name[name] = pookoo.texture.Texture(CONST.path_prefix+name)
     except Exception as e:
         log(str(e), 1)
         return None
     if tmp:
         self.tmp_images.append(name)
     return self.img_name[name]
Example #11
0
def write_json(filename,data):
    try:
        json_file = open(filename,mode='w')
    except IOError as e:
        from engine.const import log
        log("Writing file error: "+filename+" "+str(e),1)
        return None
    json_file.write(json.dumps(obj=data,indent=4))
    json_file.close()
    return True
Example #12
0
def save_level(level):
    """Save the level from editor only
    it loads the level JSON file and write the modification"""
    '''Load written level data'''
    level_data = load_json(level.filename)
    objects_list = get_element(level_data, "objects")
    for layer_index, layer in enumerate(level.objects):
        for image in layer:
            if isinstance(image,GameObject):
                object_id = image.id
                object_data = next((x for x in objects_list if x['id'] == object_id), None)
                if not object_data:
                    '''Add GameObject or Image in Level JSON dict'''
                    object_id = get_last_object_id()
                    set_last_object_id(object_id+1)
                    object_data = {"id": object_id}
                    objects_list.append(object_data)
                    if isinstance(image,GameObject):
                        object_data["type"] = "GameObject"
                    elif isinstance(image, Image):
                        object_data["type"] = "Image"
                        object_data["path"] = image.path
                object_data["pos"] = image.pos.get_list()
                object_data["angle"] = image.angle
                object_data["size"] = image.size.get_list()
                object_data["layer"] = layer_index + 1
                if image.body and not get_element(object_data, "physic_objects"):
                    """Add physic description

                    TODO:
                    -circle shape
                    -none middle pos for fixtures"""
                    physic_objects = {}
                    if CONST.render == 'sfml':
                        import Box2D as b2
                        if image.body.type == b2.b2_staticBody:
                            physic_objects["type"] = "static"
                        elif image.body.type == b2.b2_kinematicBody:
                            physic_objects["type"] = "kinematic"
                        elif image.body.type == b2.b2_dynamicBody:
                            physic_objects["type"] = "dynamic"
                        body_fixtures = []
                        for fixture in image.body.fixtures:
                            fixture_data = {}
                            if isinstance(fixture.userData, Number):
                                fixture_data["user_data"] = fixture.userData
                            if isinstance(fixture.shape,b2.b2PolygonShape):
                                fixture_data["type"] = "box"

                            body_fixtures.append(fixture_data)
                        physic_objects["fixtures"] = body_fixtures
                    object_data["physic_objects"] = physic_objects

    log(objects_list)
    write_json(level.filename,level_data)
Example #13
0
 def __div__(self, v):
     try:
         if v.__class__ == Vector2:
             return Vector2(float(self.x)/v.x, float(self.y)/v.y)
         elif isinstance(v, Number):
             return Vector2(self.x/float(v), self.y/float(v))
         else:
             raise TypeError("Vector can only divide numbers or Vector, type given: %s"%(str(type(v))))
         return None
     except ZeroDivisionError:
         log("Error: Division by zero with: "+str(self.get_tuple())+", "+str(v.get_tuple()),1)
         return None
Example #14
0
def client_set():
    log("START UPDATE SERVER")
    from engine.init import engine
    udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    while not engine.finish:
        (pos, state, frame) = get_player()
        if state != "":
            udp_sock.sendto("SET_REQUEST;"+str(self_id)+";"
                        +pos.get_string() +";"
                        +state+";"
                        +str(frame)+";"
                        , (HOST, PORT+2))
Example #15
0
    def init_actions(self):
        actions = None

        if isinstance(CONST.actions, CONST.string_type):
            actions = load_json(CONST.actions)
        elif isinstance(CONST.actions, dict):
            actions = CONST.actions
        else:
            log("Error: could not load actions, Undefined type: "+str(type(CONST.actions)), 1)
            return
        for key in actions.items():
            log(key)
            add_button(key[0], key[1])
Example #16
0
def parse_event_type_json(event_dict, parent_event=None, object=None):
    event = None
    event_type = get_element(event_dict, "type")
    if event_type and isinstance(event_type, CONST.string_type):
        for c in event_type:
            if c != "." and c != "_" and not c.isalpha():
                log("Error: Invalid character type for event type (only alphanumeric '.' and '_'): " + event_type, 1)
                return None
    elif event_type is None:
        event_type = ""

    if event_type:
        dir_list = event_type.split(".")

        module_name = ".".join(dir_list[0 : len(dir_list) - 1])
        class_name = dir_list[len(dir_list) - 1]
        log("Loading: " + module_name + "." + class_name)
        try:
            exec("""from %s import %s""" % (module_name, class_name))
        except ImportError as e:
            log("Error while importing " + event_type + " " + str(e), 1)
            return None

        try:
            d = locals()
            exec("""event = %s.parse_event(event_dict)""" % class_name, globals(), d)
            event = d["event"]
        except Exception as e:
            log("Error initializing event: " + str(e), 1)
            return None
    next_event_dict = get_element(event_dict, "next_event")
    if next_event_dict:
        event.next_event = parse_event_json(next_event_dict)
    return event
Example #17
0
    def loop(self,screen):
        log("LOLOLO")
        if self.get_loading_state():
            switch_level(GameState(CONST.startup))
            return

        img_manager.draw_rect(engine.screen,Vector2(),Rect(Vector2(), engine.get_screen_size()),(255,255,255))
        self.counter = (self.counter + 1) % self.anim_length
        if self.counter == 0:
            self.text_points += "."
            if self.text_points == '....':
                self.text_points = ""
            self.loading_text.set_text("Loading"+self.text_points)
        self.loading_text.loop(screen,Vector2())
Example #18
0
 def __init__(self,*args):
     if args is None:
         log("Error: giving None as Vector2 arg",1)
         return
     try:
         self.x = 0.0
         self.y = 0.0
         self.length = 0.0
         if len(args) == 2:
             self.x = args[0]
             self.y = args[1]
         elif len(args) == 1:
             if args[0] is None:
                 log("Error: giving None as Vector2 arg",1)
                 return
             if not isinstance(args[0], Vector2):
                 self.x = args[0][0]
                 self.y = args[0][1]
             else:
                 self.x = args[0].x
                 self.y = args[0].y
         self.length = math.sqrt(self.x**2+self.y**2)
     except IndexError as e:
         log("Error: Vector2 with argument: "+str(args)+ "|"+str(e), 1)
         ex_type, ex, tb = sys.exc_info()
         traceback.print_tb(tb)
     except AttributeError as e:
         log("Error: Vector2 with attribute error: "+str(args)+ "|"+str(e), 1)
         ex_type, ex, tb = sys.exc_info()
         traceback.print_tb(tb)
Example #19
0
    def add_box(body, pos, size, angle=0,data=None,sensor=False,density=1):
        if not (body and pos and size):
            log("Invalid arg body pos size in box creation",1)
            return None
        center_pos = pixel2meter(pos)
        polygon_shape = b2PolygonShape()
        polygon_shape.SetAsBox(pixel2meter(size.x), pixel2meter(size.y),
                               b2Vec2(center_pos.get_tuple()), angle*math.pi/180.0)
        fixture_def = b2FixtureDef()
        fixture_def.density = density
        fixture_def.shape = polygon_shape

        fixture_def.userData = data
        fixture_def.isSensor = sensor
        return body.CreateFixture(fixture_def)
Example #20
0
 def check_click(self, mouse_pos, screen_pos):
     if CONST.debug:
         from game_object.text import Text
         if isinstance(self, Text):
             log("Check click for text: "+self.text)
     if not self.screen_relative:
         point_pos = screen_pos + mouse_pos
     else:
         point_pos = mouse_pos
     if self.click_rect and not self.screen_relative:
         return self.click_rect.collide_point(point_pos)
     elif self.rect:
         return self.rect.collide_point(point_pos)
     else:
         return False
Example #21
0
 def parse_event(event_dict):
     name = get_element(event_dict, "name")
     value = get_element(event_dict, "value")
     if not (name and value):
         log("Invalid arg name and value for ConditionnalEvent", 1)
         return None
     if_event = None
     if_event_dict = get_element(event_dict, "if_event")
     if if_event_dict:
         if_event = parse_event_json(if_event_dict)
     else_event = None
     else_event_dict = get_element(event_dict, "else_event")
     if else_event_dict:
         else_event = parse_event_json(else_event_dict)
     return ConditionnalEvent(name, value, if_event, else_event)
Example #22
0
    def parse_image(image_data, pos, size, angle):
        if pos is None:
            log("Invalid arg pos not defined for Image",1)
            return None
        path = get_element(image_data, "path")
        if path is not None:
            path = CONST.path_prefix+path

        image = Image(pos, size=size, angle=angle)


        anim_data = get_element(image_data, "anim")
        if anim_data:
            image.anim = Animation.parse_animation(anim_data, image)
        image.init_image(size)
        return image
Example #23
0
def set_request(pos, state, frame):
    global sock
    """Change the position of the player on the server"""

    """Set correct pos, state, frame"""
    try:
        if not sock:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((HOST, PORT))
        sock.sendall("SET_REQUEST;"+str(self_id)+";"+pos.get_string() +";"+state+";"+str(frame)+";")
        sock.recv(1024)
    except socket.error as e:
        sock.close()
        sock = None
        log("Network set: "+str(e),1)
        return
Example #24
0
    def load_image(self, name, tmp=False):
        if name is None:
            return None
        try:
            self.img_name[name]
        except KeyError:
            try:
                log("Load sfml texture: "+name)
                self.img_name[name] = sfml.Texture.from_file(name)
            except IOError as e:
                log(str(e), 1)
                return None
            if tmp:
                self.tmp_images.append(name)

        return sfml.Sprite(self.img_name[name])
Example #25
0
    def add_circle(body, pos, radius, sensor=False, data=None, density=1):
        if not (body and pos and radius):
            log("Invalid arg body pos radius in circle creation",1)
            return None
        center_pos = pixel2meter(pos)

        circle_shape = b2CircleShape()
        circle_shape.pos = pixel2meter(pos).get_tuple()
        circle_shape.radius = pixel2meter(radius)

        fixture_def = b2FixtureDef()
        fixture_def.density = density
        fixture_def.shape = circle_shape
        fixture_def.userData = data
        fixture_def.isSensor = sensor

        return body.CreateFixture(fixture_def)
Example #26
0
def load_font(name,size):
    '''Use pixel size'''
    global fonts
    if CONST.render == 'pookoo' or CONST.render == 'kivy':
        log("Font not yet implemented",1)
        return

    try:
        fonts[name]
    except KeyError:
        try:
            if CONST.render == 'sfml':
                fonts[name] = sfml.Font.from_file(name)
        except IOError:
            if CONST.render == 'sfml':
                return None
    return fonts[name]
Example #27
0
def client_get():
    log("START UPDATE SERVER")
    from engine.init import engine
    udp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    while not engine.finish:
        udp_sock.sendto("GET_REQUEST;%s"%self_id, (HOST, PORT+1))
        get_player_data = udp_sock.recv(1024)
        """Position"""
        parsed_data = get_player_data.split(';')
        parsed_data[1] = parsed_data[1].split(',')
        parsed_data[1] = Vector2(int(float(parsed_data[1][0])), int(float(parsed_data[1][1])))
        """Frame"""
        parsed_data[3] = int(parsed_data[3])

        """update players position"""
        players_lock.acquire()
        players[parsed_data[0]] = parsed_data
        players_lock.release()
Example #28
0
    def loop(self):
        add_button('quit', ['LCTRL+q'])
        add_button('reset', ['r'])
        while not self.finish:
            self.pre_update()
            update_event()

            self.finish = get_button('quit')

            f = level_manager.update_level()

            if f == 0:
                log("No scene loaded",1)
                break
            else:
                f(self.screen)
            if get_button('reset'):
                from levels.gamestate import GameState
                level_manager.switch_level(GameState(CONST.startup))
            self.post_update()
Example #29
0
    def update_event(self):
        """
        Update the states of Input Event
        """
        window = self.screen
        input_manager.update_joy_event()
        for event in window.events:
            input_manager.update_keyboard_event(event)

            if type(event) is sfml.CloseEvent:
                self.finish = True
            elif type(event) is sfml.MouseButtonEvent:

                screen_ratio = float(self.screen_size.y) / Vector2(self.screen.size).y
                from levels.gamestate import GameState

                if get_level().__class__ == GameState:
                    log((Vector2(event.position) * screen_ratio + get_level().screen_pos).get_tuple())
            elif type(event) is sfml.ResizeEvent:
                new_size = event.size
Example #30
0
def get_players_request():
    global sock
    log("GET_REQUEST")
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((HOST, PORT))
        sock.sendall("GET_REQUEST;")
        get_request_data = sock.recv(1024)
        log(get_request_data)
        try:
            nmb = int(get_request_data.split(';')[1])
            length = 5
            for i in range(nmb):
                """Position"""
                parsed_data = get_request_data.split(';')[length*i+2:length*i+7]
                log(parsed_data)
                parsed_data[1] = parsed_data[1].split(',')
                parsed_data[1] = Vector2(int(float(parsed_data[1][0])), int(float(parsed_data[1][1])))
                """Frame"""
                parsed_data[3] = int(parsed_data[3])

                """update players position"""
                players[parsed_data[0]] = parsed_data
        except IndexError:
            pass
    finally:
        sock.close()