How to dynamically scale predefined patterns in Conway's Game of Life to fit any world size?

58 Views Asked by At

I'm working on a script for Conway's Game of Life that initializes the grid with predefined patterns. These patterns are read from a JSON file which includes data specifying the pattern layout and the world size for which the pattern is designed.

The issue I'm encountering is that the predefined patterns only display correctly when the world size matches the one specified in the JSON file. If the world size is different, the patterns get truncated or misplaced.

Here's a simplified version of my current code which loads the pattern and populates the world:

def populate_world(world_size, seed_pattern=None):
    width, height = world_size
    population = {}
    if seed_pattern:
        pattern_data = cb.get_pattern(seed_pattern)
        for coord, state in pattern_data['population'].items():
            x, y = map(int, coord.strip("()").split(", "))
            if state and 0 <= x < width and 0 <= y < height:
                population[(x, y)] = {'state': cb.STATE_ALIVE, 'neighbours': calc_neighbour_positions((x, y))}
            else:
                population[(x, y)] = {'state': cb.STATE_DEAD, 'neighbours': calc_neighbour_positions((x, y))}
    # ... Rest of the code that fills out the world ...
    return population

And here is one of the JSON files containing pattern data:

{
  "world_size": [
    30,
    30
  ],
  "population": {
    "(0, 0)": null,
    "(0, 1)": null,
 # ...
"(28, 28)": {
      "state": "-",
      "neighbours": [
        [
          28,
          27
        ],
        [
          29,
          27
        ],

What I'd like to achieve is a way to make these patterns dynamic, so that they maintain their intended design regardless of the world size. For instance, if a pattern is designed for a 30x30 world, it should still be recognizable and properly placed if the world size is 50x50 or any other dimension.

Additionally, here's an example of what happens when I load a pattern with a world size of 40x20 (pattern is designed for a 30x30 world):

load a pattern with a world size of 40x20

However, the pattern I want to achieve should look like this, which maintains the same design in the corners no matter the world size:

the pattern I want

I am looking for a solution that will dynamically adapt the placement and scale of the pattern to fit any world size while keeping the integrity of its initial design intact. How can I modify my code to achieve this?

How can I modify my code to scale or adapt the pattern to fit any given world size while preserving its original design and orientation?

0

There are 0 best solutions below