DEV Community

HarmonyOS
HarmonyOS

Posted on

How can we ensure that the same level layout is regenerated consistently after closing and reopening the application?

Read the original article:How can we ensure that the same level layout is regenerated consistently after closing and reopening the application?

Question

How can we ensure that the same level layout is regenerated consistently after closing and reopening the application?

Short Answer

This behavior is achieved by modifying the PMRandom class to remove its singleton structure and maintain an independent seeded instance for each level.
Previously, the random generator was implemented as a singleton, which caused the random sequence to reset or behave inconsistently across sessions. By refactoring the class to use a simple constructor instead of a shared static instance, each level now generates its random sequence deterministically based on a fixed seed.

As a result, when the application is completely closed and reopened, the same seed value produces the exact same board configuration, ensuring that level generation remains consistent and reproducible.

class PMRandom {
    constructor(seed):
        initialize internal seed value
        generate a few initial values for randomness warm-up

    next():
        update seed using a deterministic formula
        return the next integer value

    nextFloat():
        return a normalized random float based on next()
}
Enter fullscreen mode Exit fullscreen mode

This approach guarantees that every level uses its own self-contained random generator, eliminating unwanted state sharing between runs and improving both gameplay consistency and test reproducibility.

Applicable Scenarios

  • When deterministic level generation is required across multiple app sessions.
  • For debugging or testing environments where reproducible randomness is essential.
  • When procedural content should remain identical for the same input seed (e.g., same level ID or user session).
  • To avoid global state interference from shared singleton instances in random number generation.

Written by Aycanur Ucar

Top comments (0)