-
Notifications
You must be signed in to change notification settings - Fork 4
/
bigbang.py
267 lines (219 loc) · 9.18 KB
/
bigbang.py
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import os
import random
import time
import uuid
import networkx as nx
from stargen import get_system_data, parse_system
from components import Commodity
def gen(total_systems=20, deadends=0, rings=0, connectivity=1):
G = nx.Graph()
print("...with {} systems, {} deadends, {} rings and {} connectivity.".format(total_systems, deadends, rings, connectivity))
starchart = {}
system_id = 1
systems = 0
potentials = [x for x in range(1, total_systems + 1)]
connected = []
dead = []
f = open('data/star_names.txt', 'r')
names = f.readlines()
names = [line.strip() for line in names]
f.close()
if total_systems < 20:
raise TooFewStarsError
if 2 * deadends > total_systems / 2.0:
raise ExcessiveDeadendsError
while systems <= total_systems:
if deadends > 0:
print("Creating deadend.")
G.add_node(system_id)
G.add_node(system_id + 1)
G.add_edge(system_id, system_id + 1)
potentials.remove(system_id)
connected.append(system_id)
deadends -= 1
system_id += 2
dead.append(system_id)
continue
if rings != 0:
ring_size = random.choice([3, 3, 5, 5, 5, 5, 5, 7, 7, 9])
ring_status = 'incomplete'
ring = []
while ring_status != 'complete':
if len(potentials) > ring_size and len(ring) < ring_size:
system = random.choice(potentials)
potentials.remove(system)
connected.append(system)
ring.append(system)
if len(ring) == ring_size:
ring_status = 'complete'
print("Forming ring... {}".format(ring))
for x in range(0, len(ring)):
if x == 0:
G.add_node(ring[-1])
G.add_node(ring[x+1])
G.add_edge(ring[-1], ring[x+1])
elif x == len(ring)-1:
G.add_node(ring[x-1])
G.add_node(ring[0])
G.add_edge(ring[x-1], ring[0])
else:
G.add_node(ring[x-1])
G.add_node(ring[x+1])
G.add_edge(ring[x-1], ring[x+1])
rings -= 1
continue
if connectivity > 0:
while potentials:
system = random.choice(potentials)
target = random.choice(connected)
G.add_edge(target, system)
potentials.remove(system)
connected.append(system)
continue
systems += 1
while not nx.is_connected(G):
elements = nx.connected_component_subgraphs(G)
choices = []
for element in elements:
choices.append(random.choice(element.nodes()))
G.add_edge(choices[0], choices[1])
# this places centrality in the node with the most jumps
central = 1
for node in G.nodes():
if len(G.neighbors(node)) > central:
central = node
centrality_jumps = len(G.neighbors(central))
print("Centrality is node {} with {} jumps...".format(central,
centrality_jumps))
# get random star name from star names list...if the list is empty use a uuid
star_names = {}
for x in range(0, total_systems):
try:
star_names[x+1] = names.pop(random.randint(0, len(names)-1))
except ValueError:
star_names[x+1] = str(uuid.uuid4())
star_names[central] = 'Centrality'
nx.set_node_attributes(G, 'name', star_names)
G.node[central]['label_fill'] = 'red'
return G
def stationgen(items):
"""Generates station."""
commodities = [Commodity(*item) for item in items]
station = {'items': {commodity.name: commodity
for commodity in commodities}}
items = station['items']
for item in items:
items[item].generate()
station['tags'] = []
for item in items:
item = items[item]
if item.price_buy > item.price_sell:
station['tags'].append("INVALID")
if station['items']['equipment'].price_buy < 400 and station['items']['equipment'].price_sell < 250:
station['tags'].append("PRODUCTION")
if station['items']['organics'].price_sell < 80:
station['tags'].append("ORBITAL HYDROPONICS")
if station['items']['ice'].price_sell < 115:
station['tags'].append("ICE MINING")
if station['items']['organics'].price_buy > 30 and station['items']['ice'].price_buy > 70 and station['items']['fuel ore'].price_buy >= 4 and station['items']['equipment'].price_buy > 500:
station['tags'].append("SUPER BUY")
return station
def getstations(target=30, total_systems=100, stock_volumes=.1, items=None):
start = time.time()
stations = []
superbuys = 0
superbuys_target = 3 + total_systems / 100
productions = 0
productions_target = 3 + total_systems / 100
mines = 0
mines_target = 5 + total_systems / 100
while len(stations) < target:
station = stationgen(items)
if superbuys < superbuys_target:
if 'SUPER BUY' in station['tags']:
stations.append(station)
superbuys += 1
elif superbuys >= superbuys_target and productions < productions_target:
if 'PRODUCTION' in station['tags']:
stations.append(station)
productions += 1
elif superbuys >= superbuys_target and productions >= productions_target and mines < mines_target:
if 'ORBITAL HYDROPONICS' in station['tags'] or 'ICE MINING' in station['tags']:
stations.append(station)
elif superbuys >= superbuys_target and productions >= productions_target and mines >= mines_target and "INVALID" not in station['tags']:
stations.append(station)
stop = time.time()
print("Stations took {} seconds to generate...".format(stop - start))
return stations
def universe(total_systems=20, deadends=0, rings=0, connectivity=1, stations='common', stock_volumes='normal', items=None):
station_density = {'sparse': .1,
'uncommmon': .15,
'common': .3,
'frequent': .45,
'dense': .6,
}
stock = {'low': .1,
'normal': .2,
'high': .3,
'epic': .4}
u = gen(total_systems, deadends, rings, connectivity)
print("Universe built.")
print("Creating stations...")
stations = getstations(target=station_density[stations] * total_systems,
total_systems=total_systems,
stock_volumes=stock[stock_volumes],
items=items)
return u, stations
# MAIN
print("Running program.")
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STARGEN_EXE_PATH = 'WinStarGen/StarGen.exe'
STARGEN_DATA_PATH = 'WinStarGen/html/StarGen.csv'
items = [('fuel ore', (1, 7, 2), (1, 10, 1), 5000, 30000),
('organics', (20, 90, 2), (20, 150, 1), 500, 20000),
('equipment', (220, 625, 2), (220, 1200, 1), 500, 20000),
('ice', (50, 150, 2), (50, 120, 1), 500, 20000)
]
print("Generating Universe...")
u, s = universe(25, 5, 1, 1, 'common', 'normal', items)
print("Generate Planetary Systems...")
# observed system types: 'Rock', 'Terrestrial', 'GasDwarf', 'Sub-Jovian', 'Jovian', 'Ice', 'Venusian', 'Martian', '1Face', 'Water', 'Asteroids'
nodes = u.nodes()
for node in nodes:
u.node[node]['system'] = parse_system(get_system_data(BASE_DIR,
STARGEN_EXE_PATH,
STARGEN_DATA_PATH)
)
print("Generate links from sectors to planetary bodies...")
planet_types = {}
for node in u.nodes():
for body in u.node[node]['system']['bodies']:
body_node_label = float(str(node) + '.' + body['planet_no'])
u.add_node(body_node_label)
u.add_edge(node, body_node_label)
btype = body['type']
if btype not in planet_types:
planet_types[btype] = [body_node_label]
else:
planet_types[btype].append(body_node_label)
print("Placing stations...")
nodes = u.nodes()
random.shuffle(nodes)
planetary_data = {}
# gather data for use in world building...ice mining on ice planets, etc
planetary_data['ice_sources'] = planet_types.get('Water', []) + planet_types.get('Ice', [])
planetary_data['terrestrials'] = planet_types.get('Terrestrial', [])
for k in planetary_data:
random.shuffle(planetary_data[k])
for node in [sector for sector in nodes if isinstance(sector, int)]:
if s != []:
new_station = s.pop()
# If it is an ice mining station place it on an appropriate body type
if 'ICE MINING' in new_station['tags']:
node = planetary_data['ice_sources'].pop()
u.node[node]['station'] = new_station
u.node[node]['fill'] = 'green'
print("Universe created!")
print("Writing Universe to file...")
nx.readwrite.write_gpickle(u, 'multiverse/universe_body_nodes_experi.uni')
print("Complete!")