-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_map.py
More file actions
141 lines (115 loc) · 4.41 KB
/
generate_map.py
File metadata and controls
141 lines (115 loc) · 4.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import random
import datetime
import json
import os
WIDTH = 60
HEIGHT = 20
WALL_PROBABILITY = 0.45
ITERATIONS = 5
START_MARKER = "<" + "!-- DAILY_MAP_START --" + ">"
END_MARKER = "<" + "!-- DAILY_MAP_END --" + ">"
class MapGenerator:
def __init__(self, width, height, seed=None):
self.width = width
self.height = height
self.grid = []
if seed is None:
today_str = datetime.date.today().strftime("%Y%m%d")
self.seed = int(today_str)
else:
self.seed = seed
random.seed(self.seed)
def initialize_grid(self):
"""Randomly initialize the grid with walls and floors."""
self.grid = [[1 if random.random() < WALL_PROBABILITY else 0
for _ in range(self.width)] for _ in range(self.height)]
def count_neighbors(self, x, y):
"""Count wall neighbors around (x, y)."""
count = 0
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
nx, ny = x + i, y + j
if nx < 0 or ny < 0 or nx >= self.width or ny >= self.height:
count += 1
elif self.grid[ny][nx] == 1:
count += 1
return count
def simulation_step(self):
new_grid = [[0 for _ in range(self.width)] for _ in range(self.height)]
for y in range(self.height):
for x in range(self.width):
neighbors = self.count_neighbors(x, y)
if neighbors > 4:
new_grid[y][x] = 1
elif neighbors < 4:
new_grid[y][x] = 0
else:
new_grid[y][x] = self.grid[y][x]
self.grid = new_grid
def generate(self):
"""Run the full generation process."""
self.initialize_grid()
for _ in range(ITERATIONS):
self.simulation_step()
return self.grid
def get_ascii_art(self):
"""Convert grid to ASCII art."""
ascii_map = ""
for row in self.grid:
line = "".join(["⬛" if cell == 1 else "⬜" for cell in row])
ascii_map += line + "\n"
return ascii_map
def save_to_json(self, filename="today_map.json"):
"""Save map data to JSON file with compact grid rows."""
data = {
"date": datetime.date.today().isoformat(),
"seed": self.seed,
"width": self.width,
"height": self.height
}
with open(filename, 'w') as f:
json_str = json.dumps(data, indent=4)
f.write(json_str[:-1])
f.write(',\n "grid": [\n')
for i, row in enumerate(self.grid):
row_str = json.dumps(row)
if i < len(self.grid) - 1:
f.write(f' {row_str},\n')
else:
f.write(f' {row_str}\n')
f.write(' ]\n}')
print(f"Map data saved to {filename}")
def update_readme(ascii_art, seed):
"""Update the README.md file with the new map and link."""
readme_path = "README.md"
if not os.path.exists(readme_path):
print("README.md not found.")
return
with open(readme_path, "r", encoding="utf-8") as f:
content = f.read()
today = datetime.date.today().strftime("%Y/%m/%d")
new_section = f"{START_MARKER}\n"
new_section += f"### Today's Generated Map ({today})\n"
new_section += "```\n"
new_section += ascii_art
new_section += "```\n"
new_section += f"_Generated by Cellular Automata_\n\n"
new_section += f"[Download Map Data (JSON)](./today_map.json) | **Seed:** `{seed}`\n"
new_section += END_MARKER
if START_MARKER in content and END_MARKER in content:
before = content.split(START_MARKER)[0]
after = content.split(END_MARKER)[1]
new_content = before + new_section + after
with open(readme_path, "w", encoding="utf-8") as f:
f.write(new_content)
print("README updated successfully.")
else:
print("Markers not found in README.")
if __name__ == "__main__":
generator = MapGenerator(WIDTH, HEIGHT)
generator.generate()
generator.save_to_json()
ascii_map = generator.get_ascii_art()
update_readme(ascii_map, generator.seed)