如何在libGdx中修复此游戏序列化无限循环?

时间:2016-05-26 20:39:16

标签: java json serialization libgdx json-deserialization

我有类GameState,如下所示;

public class GameState
{
    private Array<Fleet> fleets;
    private Array<Planet> planets;
    private Array<Player> players;
    //Constructors, methods, yada yada
}

我的Fleet类的非常简化的格式是;     公共级舰队     {         私人阵列船;         私人球员所有者;

    public Fleet(Player owner)
    {
        this.owner = owner;
        this.ships = new Array<Ship>();
    }
    //Methods
}

简化Player类;

public class Player
{
    private Array<Fleet> fleets;

    public Player()
    {
        fleets = new Array<Fleet>();
    }
}

我使用libGdx Json.toJson(state);将我的游戏保存为Json格式。

我将我的信息存储在直接引用中,但这会导致一些小问题。第一个是GameState中对数据的每次引用,在序列化时,由Json读取器读取为它自己的实例。因此,如果我序列化GameState x,然后对其进行反序列化,它会在GameState中读取Array Fleetplanets并转到players,然后转到{ {1}}。每当它找到存储在fleets中的实例的原始引用之一时,它就会将其视为自己的实例。

这意味着在加载新游戏之前,两个引用将指向同一块内存,但在保存和重新加载后,它们将指向单独的内存块。此外,由于Fleet会在其中保留Ship个列表,并且每个Ship都包含一个字段形式的引用,其父级fleet,因此,Json序列化器和反序列化器将被抛入无限循环。

我尝试this,因为它似乎是最简单的方法,但正如Nathan在接受的答案中指出的那样,而不是最有效的方法。

如何简短地重新创建这个问题?

GameState类

public class GameState
{
    public Array<Player> players;

    public GameState()
    {
        this.players = new Array<Player>();
        players.add(new Player());
        players.add(new Player());
    }
}

玩家类

public class Player
{
    public Array<Fleet> fleets;

    public Player()
    {
        fleets = new Array<Fleet>();
    }

    public void addFleet(Fleet fleet)
    {
        fleets.add(fleet);
    }
}

舰队班

public class Fleet()
{
    public Player owner;

    public Fleet(Player owner)
    {
        this.owner = owner;
        this.owner.fleets.add(this);
    }
}

MainGame类

public class MainGame extends Game
{
    @Override
    public void create()
    {
        GameState state = new GameState();
        state.fleets.add(new Fleet(state.players.get(0)));
        state.fleets.add(new Fleet(state.players.get(1)));

        Json json = new Json();
        String infiniteLoopOrStackOverflowErrorHappensHere = json.toJson(state);
        state = json.fromJson(infiniteLoopOrStackOverflowErrorHappensHere);
    }
}

您应该从此处获得无限循环或StackOverflow错误。

1 个答案:

答案 0 :(得分:2)

这是深拷贝与浅拷贝的典型问题。有许多不同的技术可以处理这种情况,但对于游戏来说,处理这种情况的一种简单方法是为每个对象(或游戏实体,如果您使用的是Artemis或Ashley等ECS框架)分配唯一标识符。

序列化对象时,只需序列化一个id列表,而不是嵌套其他对象。反序列化时,您需要反序列化所有内容,然后将ID扩展为实际的对象引用。

下面我要介绍的是如何使用您提供的代码执行此操作的简单示例。

public class MainGame extends ApplicationAdapter {

    @Override
    public void create() {
        final Player player0 = new Player();
        final Player player1 = new Player();
        final Fleet fleet0 = new Fleet(player0);
        player0.fleets.add(fleet0);
        final Fleet fleet1 = new Fleet(player1);
        player1.fleets.add(fleet1);

        GameState state = new GameState();
        state.players.add(player0);
        state.players.add(player1);
        state.fleets.add(fleet0);
        state.fleets.add(fleet1);


        final Json json = new Json();
        final String infiniteLoopOrStackOverflowErrorHappensHere = json.toJson(state.toGameSaveState());
        state = json.fromJson(GameSaveState.class, infiniteLoopOrStackOverflowErrorHappensHere).toGameState();
    }
}

public abstract class BaseEntity {
    private static long idCounter = 0;

    public final long id;

    BaseEntity() {
        this(idCounter++);
    }

    BaseEntity(final long id) {
        this.id = id;
    }
}

public abstract class BaseSnapshot {
    public final long id;

    BaseSnapshot(final long id) {
        this.id = id;
    }
}

public class Fleet extends BaseEntity {
    public Player owner;

    Fleet(final long id) {
        super(id);
    }

    public Fleet(final Player owner) {
        this.owner = owner;
        //this.owner.fleets.add(this); --> Removed because this is a side-effect!
    }

    public FleetSnapshot toSnapshot() {
        return new FleetSnapshot(id, owner.id);
    }


    public static class FleetSnapshot extends BaseSnapshot {
        public final long ownerId;

        //Required for serialization
        FleetSnapshot() {
            super(-1);
            ownerId = -1;
        }

        public FleetSnapshot(final long id, final long ownerId) {
            super(id);
            this.ownerId = ownerId;
        }

        public Fleet toFleet(final Map<Long, BaseEntity> entitiesById) {
            final Fleet fleet = (Fleet)entitiesById.get(id);
            fleet.owner = (Player)entitiesById.get(ownerId);
            return fleet;
        }
    }
}

public class GameSaveState {
    public final Array<PlayerSnapshot> playerSnapshots;
    public final Array<FleetSnapshot> fleetSnapshots;

    //required for serialization
    GameSaveState() {
        playerSnapshots = null;
        fleetSnapshots = null;
    }

    public GameSaveState(final Array<PlayerSnapshot> playerSnapshots, final Array<FleetSnapshot> fleetSnapshots) {
        this.playerSnapshots = playerSnapshots;
        this.fleetSnapshots = fleetSnapshots;
    }

    public GameState toGameState() {
        final Map<Long, BaseEntity> entitiesById = constructEntitiesByIdMap();

        final GameState restoredState = new GameState();
        restoredState.players = restorePlayerEntities(entitiesById);
        restoredState.fleets = restoreFleetEntities(entitiesById);
        return restoredState;
    }

    private Map<Long, BaseEntity> constructEntitiesByIdMap() {
        final Map<Long, BaseEntity> entitiesById = new HashMap<Long, BaseEntity>();

        for (final PlayerSnapshot playerSnapshot : playerSnapshots) {
            final Player player = new Player(playerSnapshot.id);
            entitiesById.put(player.id, player);
        }

        for (final FleetSnapshot fleetSnapshot : fleetSnapshots) {
            final Fleet fleet = new Fleet(fleetSnapshot.id);
            entitiesById.put(fleet.id, fleet);
        }

        return entitiesById;
    }

    private Array<Player> restorePlayerEntities(final Map<Long, BaseEntity> entitiesById) {
        final Array<Player> restoredPlayers = new Array<Player>(playerSnapshots.size);
        for (final PlayerSnapshot playerSnapshot : playerSnapshots) {
            restoredPlayers.add(playerSnapshot.toPlayer(entitiesById));
        }
        return restoredPlayers;
    }

    private Array<Fleet> restoreFleetEntities(final Map<Long, BaseEntity> entitiesById) {
        final Array<Fleet> restoredFleets = new Array<Fleet>(fleetSnapshots.size);
        for (final FleetSnapshot fleetSnapshot : fleetSnapshots) {
            restoredFleets.add(fleetSnapshot.toFleet(entitiesById));
        }
        return restoredFleets;
    }
}

public class GameState {
    public Array<Player> players = new Array<Player>();
    public Array<Fleet> fleets = new Array<Fleet>();

    public GameSaveState toGameSaveState() {
        final Array<PlayerSnapshot> playerSnapshots = new Array<PlayerSnapshot>(players.size);
        final Array<FleetSnapshot> fleetSnapshots = new Array<FleetSnapshot>(fleets.size);

        for (final Player player : players) {
            playerSnapshots.add(player.toSnapshot());
        }

        for (final Fleet fleet : fleets) {
            fleetSnapshots.add(fleet.toSnapshot());
        }

        return new GameSaveState(playerSnapshots, fleetSnapshots);
    }
}

public class Player extends BaseEntity {
    public Array<Fleet> fleets = new Array<Fleet>();

    public Player () {}

    Player (final long id) {
        super(id);
    }

    public PlayerSnapshot toSnapshot() {
        final Array<Long> fleetIds = new Array<Long>(fleets.size);
        for(final Fleet fleet : fleets) {
            fleetIds.add(fleet.id);
        }

        return new PlayerSnapshot(id, fleetIds);
    }


    public static class PlayerSnapshot extends BaseSnapshot {
        public final Array<Long> fleetIds;

        //Required for serialization
        PlayerSnapshot() {
            super(-1);
            fleetIds = null;
        }

        public PlayerSnapshot(final long id, final Array<Long> fleetIds) {
            super(id);
            this.fleetIds = fleetIds;
        }

        public Player toPlayer(final Map<Long, BaseEntity> entitiesById) {
            final Player restoredPlayer = (Player)entitiesById.get(id);
            for (final long fleetId : fleetIds) {
                restoredPlayer.fleets.add((Fleet)entitiesById.get(fleetId));
            }
            return restoredPlayer;
        }
    }
}

这就是说,所有这个解决方案都在用你的代码修补一个基本问题。也就是说,您通过双向关系使代码紧密耦合。

您可以通过不同的方式解决此问题。

你可以使关系单向(玩家拥有许多舰队,但舰队没有参考玩家的参考)。这将帮助您遵循您为类建模所知的典型OOP技术。这也意味着查找哪个玩家拥有一支舰队可能代价高昂。您将根据所有权树而不是图表来考虑关系。这也可以限制灵活性,但这可能就足够了。

您可以将间接用于所有对象引用,并将id存储在基本对象中。然后,您将拥有一个查找服务(使用HashMap),该服务存储映射到该对象的所有实体ID。只要你想要这个对象,你就可以将id传递给服务。

我认为你可以使用LibGdx的json库支持的自定义序列化和反序列化。您需要使用ID和浅引用,因此您需要一些特殊的机制来保存/恢复链接的对象。但它会削减额外的快照类。