Serializing java.util.Random -
i'm working on small, simple game (mostly learn what's new in java 8 , javafx). 1 of features have ability seed game's random number generator can play same game friend on different system (think minecraft maps or the binding of isaac games).
i add ability save game resumed @ later time. after looking on documentation java.util.random
class, can't find way current seed of random number generator. ways have come restore random number generator after saving game either access seed via reflection @ save time , use that, or seed initial seed @ load time , call nextint()
on , on again until we've rolled forward random number generator enough before game saved.
first of all, @user2357112 points out, random
implements serializable
, , writing seed
field (along nextnextgaussian
, havenextnextgaussian
fields). have tried serializing it? should 'just work'™. other serializers, gson, work. gson.fromjson(gson.tojson(r), random.class);
returns identical object.
you don't need same random
instance, consistent one. call nextlong()
, write value save file random_seed
or whatever. initialize random
instance seed, , runs loaded file behave same. if wanted, reset random
instance in running game same seed too.
on other hand if you're generating maps or other seemingly-constant content randomly , want persist between loads, i'd think you'd better seed random
@ start, , save value describe. save on computation in chunks smaller whole level. example, split each level 10ths, , use (and save) different seed each 10th. have generate portion user's on now, , not parts they've crossed. if save current state propose, user couldn't go backwards in map (which might not problem game in particular, wouldn't great practice in general).
ux caveat: saving game's randomness seems potentially over-engineered. user, don't expect save file persist randomness. in fact, players take advantage of that, instance if die in random encounter right after saving, reloading game doesn't drop them same encounter. consider leaving game's random
unseeded , let each game unique.