Exemple #1
0
def save_to_json(sim, fname="sim"):
    """ Saves a simulation's state as a .json file. """

    fname = get_file_path(fname, "json")

    with open(fname, 'w') as savefile:

        # Collect all data to be saved
        data = {"lifetime": sim.lifetime, "particles": list()}

        # Go over each entity and save its properties
        for e in sim.entities:

            if issubclass(type(e), particle.ForceParticle):
                try:
                    p_data = dict()
                    p_data["type"] = str(type(e))
                    p_data["pos"] = e.pos
                    p_data["velocity"] = e.velocity
                    p_data["mass"] = e.mass
                    p_data["size"] = e.size
                    p_data["can_move"] = e._can_move
                    p_data["paused"] = e.paused
                    data["particles"].append(p_data)
                except AttributeError as e:
                    Logger.log_warning(
                        "Corrupt particle. Can't save particle.")
                    Logger.log_exception(e)
                    continue

        # Dump data to json
        json.dump(data, savefile)
def create_particle(data):
    """ Accepts data and creates particle according to it. """

    # Get particle type
    type_raw = None
    try:
        type_raw = data["type"]
    except KeyError as ke:
        Logger.log_warning("No particle type data. Can't spawn particle.")
        Logger.log_exception(ke)
        return None

    t = type_raw
    if type(type_raw) is str:
        # Get actual class reference
        t = get_particle_type(type_raw)

    if t is None:
        Logger.log_warning("Unrecognized particle type. Can't spawn particle.")
        return None

    # Construct particle
    p = None
    try:
        pos = data["pos"]
        p = t(pos[0], pos[1])
    except KeyError as ke:
        Logger.log_warning("Incomplete particle data. Can't spawn particle.")
        Logger.log_exception(ke)
        return None

    # Set particle attributes
    try:
        p.mass = data["mass"]
        p.velocity = data["velocity"]
        p.size = data["size"]
        p._can_move = data["can_move"]
        p.paused = data["paused"]
    except KeyError as ke:
        Logger.log_info("Missing particle data.")
        Logger.log_exception(ke)

    return p