]> git.scottworley.com Git - planeteer/blame - planeteer.go
Don't use 0 for uninitialized indexes
[planeteer] / planeteer.go
CommitLineData
d07f3caa
SW
1/* Planeteer: Give trade route advice for Planets: The Exploration of Space
2 * Copyright (C) 2011 Scott Worley <sworley@chkno.net>
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation, either version 3 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18package main
19
20import "flag"
c45c1bca 21import "fmt"
d07f3caa
SW
22import "json"
23import "os"
42f6427c 24import "runtime/pprof"
c45c1bca
SW
25import "strings"
26
330093c1
SW
27var funds = flag.Int("funds", 0,
28 "Starting funds")
29
c45c1bca
SW
30var start = flag.String("start", "",
31 "The planet to start at")
d07f3caa 32
e346cb37 33var flight_plan_string = flag.String("flight_plan", "",
63b4dbbc 34 "Your hyper-holes for the day, comma-separated.")
544108c4 35
1c1ede68 36var end_string = flag.String("end", "",
e9ff66cf 37 "A comma-separated list of acceptable ending planets.")
c45c1bca
SW
38
39var planet_data_file = flag.String("planet_data_file", "planet-data",
d07f3caa
SW
40 "The file to read planet data from")
41
63b4dbbc 42var fuel = flag.Int("fuel", 16, "Hyper Jump power left")
e9ff66cf
SW
43
44var hold = flag.Int("hold", 300, "Size of your cargo hold")
c45c1bca
SW
45
46var start_edens = flag.Int("start_edens", 0,
47 "How many Eden Warp Units are you starting with?")
48
49var end_edens = flag.Int("end_edens", 0,
50 "How many Eden Warp Units would you like to keep (not use)?")
51
52var cloak = flag.Bool("cloak", false,
53 "Make sure to end with a Device of Cloaking")
54
e9ff66cf 55var drones = flag.Int("drones", 0, "Buy this many Fighter Drones")
c45c1bca 56
e9ff66cf 57var batteries = flag.Int("batteries", 0, "Buy this many Shield Batterys")
c45c1bca 58
76db1b3c
SW
59var drone_price = flag.Int("drone_price", 0, "Today's Fighter Drone price")
60
61var battery_price = flag.Int("battery_price", 0, "Today's Shield Battery price")
62
c45c1bca
SW
63var visit_string = flag.String("visit", "",
64 "A comma-separated list of planets to make sure to visit")
65
42f6427c
SW
66var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
67
42f6427c 68var visit_cache []string
1539cc25 69
c45c1bca 70func visit() []string {
42f6427c
SW
71 if visit_cache == nil {
72 if *visit_string == "" {
73 return nil
74 }
75 visit_cache = strings.Split(*visit_string, ",")
e346cb37 76 }
42f6427c 77 return visit_cache
c45c1bca
SW
78}
79
42f6427c 80var flight_plan_cache []string
1539cc25 81
e346cb37 82func flight_plan() []string {
42f6427c
SW
83 if flight_plan_cache == nil {
84 if *flight_plan_string == "" {
85 return nil
86 }
87 flight_plan_cache = strings.Split(*flight_plan_string, ",")
e346cb37 88 }
42f6427c 89 return flight_plan_cache
e346cb37
SW
90}
91
42f6427c 92var end_cache map[string]bool
1539cc25 93
1c1ede68 94func end() map[string]bool {
42f6427c
SW
95 if end_cache == nil {
96 if *end_string == "" {
97 return nil
98 }
99 m := make(map[string]bool)
100 for _, p := range strings.Split(*end_string, ",") {
101 m[p] = true
102 }
103 end_cache = m
1c1ede68 104 }
42f6427c 105 return end_cache
1c1ede68
SW
106}
107
9b3b3d9a 108type Commodity struct {
9b3b3d9a
SW
109 BasePrice int
110 CanSell bool
111 Limit int
112}
12bc2cd7 113type Planet struct {
12bc2cd7 114 BeaconOn bool
1539cc25 115 Private bool
12bc2cd7
SW
116 /* Use relative prices rather than absolute prices because you
117 can get relative prices without traveling to each planet. */
0e94bdac 118 RelativePrices map[string]int
12bc2cd7 119}
d07f3caa 120type planet_data struct {
0e94bdac
SW
121 Commodities map[string]Commodity
122 Planets map[string]Planet
e7e4bc13
SW
123 p2i, c2i map[string]int // Generated; not read from file
124 i2p, i2c []string // Generated; not read from file
d07f3caa
SW
125}
126
127func ReadData() (data planet_data) {
c45c1bca 128 f, err := os.Open(*planet_data_file)
d07f3caa
SW
129 if err != nil {
130 panic(err)
131 }
132 defer f.Close()
133 err = json.NewDecoder(f).Decode(&data)
134 if err != nil {
135 panic(err)
136 }
137 return
138}
139
c45c1bca
SW
140/* This program operates by filling in a state table representing the best
141 * possible trips you could make; the ones that makes you the most money.
142 * This is feasible because we don't look at all the possible trips.
143 * We define a list of things that are germane to this game and then only
144 * consider the best outcome in each possible game state.
145 *
146 * Each cell in the table represents a state in the game. In each cell,
147 * we track two things: 1. the most money you could possibly have while in
148 * that state and 2. one possible way to get into that state with that
149 * amount of money.
150 *
151 * A basic analysis can be done with a two-dimensional table: location and
152 * fuel. planeteer-1.0 used this two-dimensional table. This version
153 * adds features mostly by adding dimensions to this table.
154 *
155 * Note that the sizes of each dimension are data driven. Many dimensions
156 * collapse to one possible value (ie, disappear) if the corresponding
157 * feature is not enabled.
e7e4bc13
SW
158 *
159 * The order of the dimensions in the list of constants below determines
160 * their layout in RAM. The cargo-based 'dimensions' are not completely
161 * independent -- some combinations are illegal and not used. They are
162 * handled as three dimensions rather than one for simplicity. Placing
163 * these dimensions first causes the unused cells in the table to be
164 * grouped together in large blocks. This keeps them from polluting
0372f045
SW
165 * cache lines, and if they are large enough, allows the memory manager
166 * to swap out entire pages.
e346cb37
SW
167 *
168 * If the table gets too big to fit in RAM:
169 * * Combine the Edens, Cloaks, and UnusedCargo dimensions. Of the
170 * 24 combinations, only 15 are legal: a 38% savings.
171 * * Reduce the size of the Fuel dimension to 3. We only ever look
172 * backwards 2 units, so just rotate the logical values through
173 * the same 3 physical addresses. This is good for an 82% savings.
174 * * Reduce the size of the Edens dimension from 3 to 2, for the
175 * same reasons as Fuel above. 33% savings.
176 * * Buy more ram. (Just sayin'. It's cheaper than you think.)
177 *
c45c1bca
SW
178 */
179
180// The official list of dimensions:
181const (
0372f045 182 // Name Num Size Description
1539cc25
SW
183 Edens = iota // 1 3 # of Eden warp units (0 - 2 typically)
184 Cloaks // 2 1-2 # of Devices of Cloaking (0 or 1)
185 UnusedCargo // 3 4 # of unused cargo spaces (0 - 3 typically)
186 Fuel // 4 17 Hyper jump power left (0 - 16)
187 Location // 5 26 Location (which planet)
188 Hold // 6 15 Cargo bay contents (a *Commodity or nil)
189 Traded // 7 2 Traded yet?
190 BuyFighters // 8 1-2 Errand: Buy fighter drones
191 BuyShields // 9 1-2 Errand: Buy shield batteries
192 Visit // 10 1-2**N Visit: Stop by these N planets in the route
c45c1bca
SW
193
194 NumDimensions
195)
196
197func bint(b bool) int {
0e94bdac
SW
198 if b {
199 return 1
200 }
c45c1bca
SW
201 return 0
202}
203
204func DimensionSizes(data planet_data) []int {
205 eden_capacity := data.Commodities["Eden Warp Units"].Limit
330093c1
SW
206 if *start_edens > eden_capacity {
207 eden_capacity = *start_edens
208 }
c45c1bca 209 cloak_capacity := bint(*cloak)
64d87250
SW
210 dims := make([]int, NumDimensions)
211 dims[Edens] = eden_capacity + 1
212 dims[Cloaks] = cloak_capacity + 1
213 dims[UnusedCargo] = eden_capacity + cloak_capacity + 1
214 dims[Fuel] = *fuel + 1
215 dims[Location] = len(data.Planets)
c67c206a 216 dims[Hold] = len(data.Commodities) + 1
0372f045 217 dims[Traded] = 2
76db1b3c
SW
218 dims[BuyFighters] = bint(*drones > 0) + 1
219 dims[BuyShields] = bint(*batteries > 0) + 1
64d87250 220 dims[Visit] = 1 << uint(len(visit()))
2f4ed5ca
SW
221
222 // Remind myself to add a line above when adding new dimensions
223 for i, dim := range dims {
224 if dim < 1 {
225 panic(i)
226 }
227 }
c45c1bca
SW
228 return dims
229}
230
231func StateTableSize(dims []int) int {
e346cb37 232 product := 1
c45c1bca 233 for _, size := range dims {
e346cb37 234 product *= size
c45c1bca 235 }
e346cb37 236 return product
c45c1bca
SW
237}
238
239type State struct {
0372f045 240 value, from int32
c45c1bca
SW
241}
242
1539cc25 243const (
fb8eccbf
SW
244 FROM_ROOT = -2147483647 + iota
245 FROM_UNINITIALIZED
246 VALUE_UNINITIALIZED
247 VALUE_BEING_EVALUATED
248 VALUE_RUBISH
1539cc25 249)
0372f045
SW
250
251func EncodeIndex(dims, addr []int) int32 {
688733e1 252 index := addr[0]
e346cb37
SW
253 if addr[0] > dims[0] {
254 panic(0)
255 }
330093c1 256 for i := 1; i < NumDimensions; i++ {
688733e1 257 if addr[i] < 0 || addr[i] >= dims[i] {
e346cb37
SW
258 panic(i)
259 }
688733e1 260 index = index*dims[i] + addr[i]
c45c1bca 261 }
688733e1 262 return int32(index)
c45c1bca
SW
263}
264
0372f045 265func DecodeIndex(dims []int, index int32) []int {
330093c1
SW
266 addr := make([]int, NumDimensions)
267 for i := NumDimensions - 1; i > 0; i-- {
0372f045
SW
268 addr[i] = int(index) % dims[i]
269 index /= int32(dims[i])
c45c1bca 270 }
0372f045 271 addr[0] = int(index)
c45c1bca
SW
272 return addr
273}
274
0372f045 275func CreateStateTable(data planet_data, dims []int) []State {
330093c1 276 table := make([]State, StateTableSize(dims))
0372f045 277 for i := range table {
fb8eccbf
SW
278 table[i].value = VALUE_UNINITIALIZED
279 table[i].from = FROM_UNINITIALIZED
0372f045 280 }
330093c1
SW
281
282 addr := make([]int, NumDimensions)
283 addr[Fuel] = *fuel
284 addr[Edens] = *start_edens
285 addr[Location] = data.p2i[*start]
0372f045 286 addr[Traded] = 1
fb8eccbf
SW
287 start_index := EncodeIndex(dims, addr)
288 table[start_index].value = int32(*funds)
289 table[start_index].from = FROM_ROOT
330093c1
SW
290
291 return table
e346cb37
SW
292}
293
0372f045
SW
294/* CellValue fills in the one cell at address addr by looking at all
295 * the possible ways to reach this cell and selecting the best one. */
330093c1 296
0372f045
SW
297func Consider(data planet_data, dims []int, table []State, there []int, value_difference int, best_value *int32, best_source []int) {
298 there_value := CellValue(data, dims, table, there)
299 if value_difference < 0 && int32(-value_difference) > there_value {
300 /* Can't afford this transition */
301 return
302 }
303 possible_value := there_value + int32(value_difference)
304 if possible_value > *best_value {
305 *best_value = possible_value
306 copy(best_source, there)
330093c1
SW
307 }
308}
309
0372f045 310var cell_filled_count int
1539cc25 311
0372f045 312func CellValue(data planet_data, dims []int, table []State, addr []int) int32 {
e346cb37 313 my_index := EncodeIndex(dims, addr)
fb8eccbf 314 if table[my_index].value == VALUE_BEING_EVALUATED {
0372f045
SW
315 panic("Circular dependency")
316 }
fb8eccbf 317 if table[my_index].value != VALUE_UNINITIALIZED {
0372f045
SW
318 return table[my_index].value
319 }
fb8eccbf 320 table[my_index].value = VALUE_BEING_EVALUATED
0372f045 321
fb8eccbf 322 best_value := int32(VALUE_RUBISH)
0372f045 323 best_source := make([]int, NumDimensions)
e346cb37
SW
324 other := make([]int, NumDimensions)
325 copy(other, addr)
0372f045 326 planet := data.i2p[addr[Location]]
e346cb37 327
0372f045
SW
328 /* Travel here */
329 if addr[Traded] == 0 { /* Can't have traded immediately after traveling. */
330 other[Traded] = 1 /* Travel from states that have done trading. */
331
332 /* Travel here via a 2-fuel unit jump */
333 if addr[Fuel]+2 < dims[Fuel] {
334 other[Fuel] = addr[Fuel] + 2
335 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 2)
336 if hole_index >= len(flight_plan()) || addr[Location] != data.p2i[flight_plan()[hole_index]] {
337 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
338 if data.Planets[data.i2p[addr[Location]]].BeaconOn {
339 Consider(data, dims, table, other, 0, &best_value, best_source)
340 }
341 }
beb45aca 342 }
0372f045
SW
343 other[Location] = addr[Location]
344 other[Fuel] = addr[Fuel]
e346cb37 345 }
e346cb37 346
0372f045
SW
347 /* Travel here via a 1-fuel unit jump (a hyper hole) */
348 if addr[Fuel]+1 < dims[Fuel] {
349 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 1)
350 if hole_index < len(flight_plan()) && addr[Location] == data.p2i[flight_plan()[hole_index]] {
351 other[Fuel] = addr[Fuel] + 1
352 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
353 Consider(data, dims, table, other, 0, &best_value, best_source)
354 }
355 other[Location] = addr[Location]
356 other[Fuel] = addr[Fuel]
7b5d9d13 357 }
e346cb37 358 }
e346cb37 359
0372f045 360 /* Travel here via Eden Warp Unit */
34db2393 361 if addr[Edens]+1 < dims[Edens] && addr[UnusedCargo] > 0 {
0372f045
SW
362 _, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
363 if !available {
364 other[Edens] = addr[Edens] + 1
365 if other[Hold] != 0 {
366 other[UnusedCargo] = addr[UnusedCargo] - 1
367 }
368 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
369 Consider(data, dims, table, other, 0, &best_value, best_source)
370 }
371 other[Location] = addr[Location]
372 other[UnusedCargo] = addr[UnusedCargo]
373 other[Edens] = addr[Edens]
0c27c344 374 }
330093c1 375 }
0372f045 376 other[Traded] = addr[Traded]
330093c1 377 }
330093c1 378
0372f045
SW
379 /* Trade */
380 if addr[Traded] == 1 {
381 other[Traded] = 0
330093c1 382
0372f045
SW
383 /* Consider not trading */
384 Consider(data, dims, table, other, 0, &best_value, best_source)
330093c1 385
0372f045 386 if !data.Planets[data.i2p[addr[Location]]].Private {
330093c1 387
0372f045
SW
388 /* Sell */
389 if addr[Hold] == 0 && addr[UnusedCargo] == 0 {
390 for other[Hold] = 0; other[Hold] < dims[Hold]; other[Hold]++ {
391 commodity := data.i2c[other[Hold]]
392 if !data.Commodities[commodity].CanSell {
393 continue
394 }
395 relative_price, available := data.Planets[planet].RelativePrices[commodity]
396 if !available {
397 // TODO: Dump cargo
398 continue
399 }
400 base_price := data.Commodities[commodity].BasePrice
401 absolute_price := float64(base_price) * float64(relative_price) / 100.0
402 sell_price := int(absolute_price * 0.9)
403
404 for other[UnusedCargo] = 0; other[UnusedCargo] < dims[UnusedCargo]; other[UnusedCargo]++ {
405 quantity := *hold - (other[UnusedCargo] + other[Cloaks] + other[Edens])
406 sale_value := quantity * sell_price
407 Consider(data, dims, table, other, sale_value, &best_value, best_source)
408 }
409 }
410 other[UnusedCargo] = addr[UnusedCargo]
411 other[Hold] = addr[Hold]
412 }
330093c1 413
0372f045
SW
414 /* Buy */
415 other[Traded] = addr[Traded] /* Buy after selling */
416 if addr[Hold] != 0 {
417 commodity := data.i2c[addr[Hold]]
418 if data.Commodities[commodity].CanSell {
419 relative_price, available := data.Planets[planet].RelativePrices[commodity]
420 if available {
421 base_price := data.Commodities[commodity].BasePrice
422 absolute_price := int(float64(base_price) * float64(relative_price) / 100.0)
423 quantity := *hold - (addr[UnusedCargo] + addr[Cloaks] + addr[Edens])
424 total_price := quantity * absolute_price
425 other[Hold] = 0
426 other[UnusedCargo] = 0
427 Consider(data, dims, table, other, -total_price, &best_value, best_source)
428 other[UnusedCargo] = addr[UnusedCargo]
429 other[Hold] = addr[Hold]
430 }
431 }
432 }
433 }
6918cad2 434 other[Traded] = addr[Traded]
0372f045 435 }
d16f3322 436
544108c4 437 /* Buy a Device of Cloaking */
ada59973
SW
438 if addr[Cloaks] == 1 && addr[UnusedCargo] < dims[UnusedCargo]-1 {
439 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Device Of Cloakings"]
440 if available {
441 absolute_price := int(float64(data.Commodities["Device Of Cloakings"].BasePrice) * float64(relative_price) / 100.0)
442 other[Cloaks] = 0
f800f732
SW
443 if other[Hold] != 0 {
444 other[UnusedCargo] = addr[UnusedCargo] + 1
445 }
0372f045 446 Consider(data, dims, table, other, -absolute_price, &best_value, best_source)
ada59973
SW
447 other[UnusedCargo] = addr[UnusedCargo]
448 other[Cloaks] = addr[Cloaks]
449 }
450 }
76db1b3c 451
544108c4 452 /* Buy Fighter Drones */
76db1b3c
SW
453 if addr[BuyFighters] == 1 {
454 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Fighter Drones"]
455 if available {
456 absolute_price := int(float64(data.Commodities["Fighter Drones"].BasePrice) * float64(relative_price) / 100.0)
457 other[BuyFighters] = 0
1539cc25 458 Consider(data, dims, table, other, -absolute_price**drones, &best_value, best_source)
76db1b3c
SW
459 other[BuyFighters] = addr[BuyFighters]
460 }
461 }
462
544108c4 463 /* Buy Shield Batteries */
76db1b3c
SW
464 if addr[BuyShields] == 1 {
465 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Shield Batterys"]
466 if available {
467 absolute_price := int(float64(data.Commodities["Shield Batterys"].BasePrice) * float64(relative_price) / 100.0)
468 other[BuyShields] = 0
1539cc25 469 Consider(data, dims, table, other, -absolute_price**batteries, &best_value, best_source)
76db1b3c
SW
470 other[BuyShields] = addr[BuyShields]
471 }
472 }
473
544108c4 474 /* Visit this planet */
4d7362df
SW
475 var i uint
476 for i = 0; i < uint(len(visit())); i++ {
1539cc25 477 if addr[Visit]&(1<<i) != 0 && visit()[i] == data.i2p[addr[Location]] {
4d7362df 478 other[Visit] = addr[Visit] & ^(1 << i)
0372f045 479 Consider(data, dims, table, other, 0, &best_value, best_source)
4d7362df
SW
480 }
481 }
482 other[Visit] = addr[Visit]
76db1b3c 483
d16f3322
SW
484 /* Buy Eden warp units */
485 eden_limit := data.Commodities["Eden Warp Units"].Limit
486 if addr[Edens] > 0 && addr[Edens] <= eden_limit {
487 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
488 if available {
489 absolute_price := int(float64(data.Commodities["Eden Warp Units"].BasePrice) * float64(relative_price) / 100.0)
490 for quantity := addr[Edens]; quantity > 0; quantity-- {
491 other[Edens] = addr[Edens] - quantity
492 if addr[Hold] != 0 {
493 other[UnusedCargo] = addr[UnusedCargo] + quantity
494 }
495 if other[UnusedCargo] < dims[UnusedCargo] {
1539cc25 496 Consider(data, dims, table, other, -absolute_price*quantity, &best_value, best_source)
d16f3322
SW
497 }
498 }
499 other[Edens] = addr[Edens]
500 other[UnusedCargo] = addr[UnusedCargo]
501 }
502 }
d16f3322 503
688733e1
SW
504 // Check that we didn't lose track of any temporary modifications to other.
505 for i := 0; i < NumDimensions; i++ {
506 if addr[i] != other[i] {
507 panic(i)
508 }
509 }
510
511 // Sanity check: This cell was in state BEING_EVALUATED
512 // the whole time that it was being evaluated.
fb8eccbf 513 if table[my_index].value != VALUE_BEING_EVALUATED {
0372f045 514 panic(my_index)
e7e4bc13 515 }
688733e1
SW
516
517 // Record our findings
0372f045
SW
518 table[my_index].value = best_value
519 table[my_index].from = EncodeIndex(dims, best_source)
330093c1 520
688733e1 521 // UI: Progress bar
1539cc25
SW
522 cell_filled_count++
523 if cell_filled_count&0xff == 0 {
0372f045 524 print(fmt.Sprintf("\r%3.1f%%", 100*float64(cell_filled_count)/float64(StateTableSize(dims))))
fcdc120b 525 }
e7e4bc13 526
0372f045 527 return table[my_index].value
e7e4bc13
SW
528}
529
0372f045 530func FindBestState(data planet_data, dims []int, table []State) int32 {
ad4de13f
SW
531 addr := make([]int, NumDimensions)
532 addr[Edens] = *end_edens
533 addr[Cloaks] = dims[Cloaks] - 1
76db1b3c
SW
534 addr[BuyFighters] = dims[BuyFighters] - 1
535 addr[BuyShields] = dims[BuyShields] - 1
ad4de13f 536 addr[Visit] = dims[Visit] - 1
0372f045 537 addr[Traded] = 1
688733e1
SW
538 addr[Hold] = 0
539 addr[UnusedCargo] = 0
0372f045
SW
540 max_index := int32(-1)
541 max_value := int32(0)
688733e1
SW
542 max_fuel := 1
543 if *fuel == 0 {
544 max_fuel = 0
545 }
546 for addr[Fuel] = 0; addr[Fuel] <= max_fuel; addr[Fuel]++ {
ddef04ab
SW
547 for addr[Location] = 0; addr[Location] < dims[Location]; addr[Location]++ {
548 if len(end()) == 0 || end()[data.i2p[addr[Location]]] {
549 index := EncodeIndex(dims, addr)
0372f045
SW
550 value := CellValue(data, dims, table, addr)
551 if value > max_value {
552 max_value = value
ddef04ab
SW
553 max_index = index
554 }
809e65f4 555 }
ad4de13f
SW
556 }
557 }
558 return max_index
559}
560
0372f045 561func Commas(n int32) (s string) {
9eafb7a4
SW
562 r := n % 1000
563 n /= 1000
564 for n > 0 {
565 s = fmt.Sprintf(",%03d", r) + s
566 r = n % 1000
567 n /= 1000
568 }
569 s = fmt.Sprint(r) + s
570 return
571}
572
0372f045 573func DescribePath(data planet_data, dims []int, table []State, start int32) (description []string) {
fb8eccbf
SW
574 for index := start; table[index].from > FROM_ROOT; index = table[index].from {
575 if table[index].from == FROM_UNINITIALIZED {
576 panic(index)
577 }
e4a1b48f 578 var line string
2f4a9ae8
SW
579 addr := DecodeIndex(dims, index)
580 prev := DecodeIndex(dims, table[index].from)
e4a1b48f 581 if addr[Fuel] != prev[Fuel] {
2f4a9ae8
SW
582 from := data.i2p[prev[Location]]
583 to := data.i2p[addr[Location]]
63b4dbbc 584 line += fmt.Sprintf("Jump from %v to %v (%v hyper jump units)", from, to, prev[Fuel]-addr[Fuel])
e4a1b48f 585 }
1539cc25 586 if addr[Edens] == prev[Edens]-1 {
e4a1b48f
SW
587 from := data.i2p[prev[Location]]
588 to := data.i2p[addr[Location]]
589 line += fmt.Sprintf("Eden warp from %v to %v", from, to)
2f4a9ae8
SW
590 }
591 if addr[Hold] != prev[Hold] {
592 if addr[Hold] == 0 {
593 quantity := *hold - (prev[UnusedCargo] + prev[Edens] + prev[Cloaks])
e4a1b48f 594 line += fmt.Sprintf("Sell %v %v", quantity, data.i2c[prev[Hold]])
2f4a9ae8
SW
595 } else if prev[Hold] == 0 {
596 quantity := *hold - (addr[UnusedCargo] + addr[Edens] + addr[Cloaks])
e4a1b48f 597 line += fmt.Sprintf("Buy %v %v", quantity, data.i2c[addr[Hold]])
2f4a9ae8
SW
598 } else {
599 panic("Switched cargo?")
600 }
601
602 }
f800f732
SW
603 if addr[Cloaks] == 1 && prev[Cloaks] == 0 {
604 // TODO: Dump cloaks, convert from cargo?
e4a1b48f
SW
605 line += "Buy a Cloak"
606 }
d16f3322 607 if addr[Edens] > prev[Edens] {
1539cc25 608 line += fmt.Sprint("Buy ", addr[Edens]-prev[Edens], " Eden Warp Units")
e4a1b48f 609 }
76db1b3c
SW
610 if addr[BuyShields] == 1 && prev[BuyShields] == 0 {
611 line += fmt.Sprint("Buy ", *batteries, " Shield Batterys")
612 }
613 if addr[BuyFighters] == 1 && prev[BuyFighters] == 0 {
614 line += fmt.Sprint("Buy ", *drones, " Fighter Drones")
615 }
4d7362df
SW
616 if addr[Visit] != prev[Visit] {
617 // TODO: verify that the bit chat changed is addr[Location]
618 line += fmt.Sprint("Visit ", data.i2p[addr[Location]])
619 }
0372f045
SW
620 if line == "" && addr[Hold] == prev[Hold] && addr[Traded] != prev[Traded] {
621 // The Traded dimension is for housekeeping. It doesn't directly
622 // correspond to in-game actions, so don't report transitions.
623 continue
624 }
e4a1b48f
SW
625 if line == "" {
626 line = fmt.Sprint(prev, " -> ", addr)
f800f732 627 }
1539cc25 628 description = append(description, fmt.Sprintf("%13v ", Commas(table[index].value))+line)
2f4a9ae8
SW
629 }
630 return
631}
632
c45c1bca 633// (Example of a use case for generics in Go)
e7e4bc13 634func IndexPlanets(m *map[string]Planet, start_at int) (map[string]int, []string) {
a1f10151
SW
635 e2i := make(map[string]int, len(*m)+start_at)
636 i2e := make([]string, len(*m)+start_at)
e7e4bc13 637 i := start_at
c45c1bca 638 for e := range *m {
e7e4bc13
SW
639 e2i[e] = i
640 i2e[i] = e
c45c1bca
SW
641 i++
642 }
e7e4bc13 643 return e2i, i2e
c45c1bca 644}
e7e4bc13 645func IndexCommodities(m *map[string]Commodity, start_at int) (map[string]int, []string) {
a1f10151
SW
646 e2i := make(map[string]int, len(*m)+start_at)
647 i2e := make([]string, len(*m)+start_at)
e7e4bc13 648 i := start_at
c45c1bca 649 for e := range *m {
e7e4bc13
SW
650 e2i[e] = i
651 i2e[i] = e
c45c1bca
SW
652 i++
653 }
e7e4bc13 654 return e2i, i2e
c45c1bca
SW
655}
656
d07f3caa
SW
657func main() {
658 flag.Parse()
311b26d4
SW
659 if *start == "" || *funds == 0 {
660 print("--start and --funds are required. --help for more\n")
661 return
662 }
42f6427c
SW
663 if *cpuprofile != "" {
664 f, err := os.Create(*cpuprofile)
665 if err != nil {
666 panic(err)
667 }
668 pprof.StartCPUProfile(f)
669 defer pprof.StopCPUProfile()
670 }
d07f3caa 671 data := ReadData()
76db1b3c
SW
672 if *drone_price > 0 {
673 temp := data.Commodities["Fighter Drones"]
674 temp.BasePrice = *drone_price
675 data.Commodities["Fighter Drones"] = temp
676 }
677 if *battery_price > 0 {
678 temp := data.Commodities["Shield Batterys"]
679 temp.BasePrice = *battery_price
680 data.Commodities["Shield Batterys"] = temp
681 }
e7e4bc13
SW
682 data.p2i, data.i2p = IndexPlanets(&data.Planets, 0)
683 data.c2i, data.i2c = IndexCommodities(&data.Commodities, 1)
c45c1bca 684 dims := DimensionSizes(data)
0372f045 685 table := CreateStateTable(data, dims)
ad4de13f 686 best := FindBestState(data, dims, table)
0372f045 687 print("\n")
ada59973
SW
688 if best == -1 {
689 print("Cannot acheive success criteria\n")
690 } else {
ada59973
SW
691 description := DescribePath(data, dims, table, best)
692 for i := len(description) - 1; i >= 0; i-- {
693 fmt.Println(description[i])
694 }
2f4a9ae8 695 }
d07f3caa 696}