]> git.scottworley.com Git - planeteer/blob - planeteer.go
187da80034e77aa6de1596e37058002f94103fff
[planeteer] / planeteer.go
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
18 package main
19
20 import "flag"
21 import "fmt"
22 import "encoding/json"
23 import "os"
24 import "runtime/pprof"
25 import "strings"
26
27 var funds = flag.Int("funds", 0,
28 "Starting funds")
29
30 var start = flag.String("start", "",
31 "The planet to start at")
32
33 var flight_plan_string = flag.String("flight_plan", "",
34 "Your hyper-holes for the day, comma-separated.")
35
36 var end_string = flag.String("end", "",
37 "A comma-separated list of acceptable ending planets.")
38
39 var planet_data_file = flag.String("planet_data_file", "planet-data",
40 "The file to read planet data from")
41
42 var fuel = flag.Int("fuel", 16, "Hyper Jump power left")
43
44 var hold = flag.Int("hold", 300, "Size of your cargo hold")
45
46 var start_hold = flag.String("start_hold", "", "Start with a hold full of cargo")
47
48 var start_edens = flag.Int("start_edens", 0,
49 "How many Eden Warp Units are you starting with?")
50
51 var end_edens = flag.Int("end_edens", 0,
52 "How many Eden Warp Units would you like to keep (not use)?")
53
54 var cloak = flag.Bool("cloak", false,
55 "Make sure to end with a Device of Cloaking")
56
57 var drones = flag.Int("drones", 0, "Buy this many Fighter Drones")
58
59 var batteries = flag.Int("batteries", 0, "Buy this many Shield Batterys")
60
61 var drone_price = flag.Int("drone_price", 0, "Today's Fighter Drone price")
62
63 var battery_price = flag.Int("battery_price", 0, "Today's Shield Battery price")
64
65 var visit_string = flag.String("visit", "",
66 "A comma-separated list of planets to make sure to visit")
67
68 var tomorrow_weight = flag.Float64("tomorrow_weight", 1.0,
69 "Weight for the expected value of tomorrow's trading. 0.0 - 1.0")
70
71 var extra_stats = flag.Bool("extra_stats", true,
72 "Show additional information of possible interest")
73
74 var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
75
76 var visit_cache []string
77
78 func visit() []string {
79 if visit_cache == nil {
80 if *visit_string == "" {
81 return nil
82 }
83 visit_cache = strings.Split(*visit_string, ",")
84 }
85 return visit_cache
86 }
87
88 var flight_plan_cache []string
89
90 func flight_plan() []string {
91 if flight_plan_cache == nil {
92 if *flight_plan_string == "" {
93 return nil
94 }
95 flight_plan_cache = strings.Split(*flight_plan_string, ",")
96 }
97 return flight_plan_cache
98 }
99
100 var end_cache map[string]bool
101
102 func end() map[string]bool {
103 if end_cache == nil {
104 if *end_string == "" {
105 return nil
106 }
107 m := make(map[string]bool)
108 for _, p := range strings.Split(*end_string, ",") {
109 m[p] = true
110 }
111 end_cache = m
112 }
113 return end_cache
114 }
115
116 type Commodity struct {
117 BasePrice int
118 CanSell bool
119 Limit int
120 }
121 type Planet struct {
122 BeaconOn bool
123 Private bool
124 TomorrowValue int
125 /* Use relative prices rather than absolute prices because you
126 can get relative prices without traveling to each planet. */
127 RelativePrices map[string]int
128 }
129 type planet_data struct {
130 Commodities map[string]Commodity
131 Planets map[string]Planet
132 p2i, c2i map[string]int // Generated; not read from file
133 i2p, i2c []string // Generated; not read from file
134 }
135
136 func json_slurp(filename string, receptacle interface{}) error {
137 f, err := os.Open(filename)
138 if err != nil {
139 return err
140 }
141 defer f.Close()
142 err = json.NewDecoder(f).Decode(receptacle)
143 if err != nil {
144 return err
145 }
146 return nil
147 }
148
149 func ReadData() planet_data {
150 var data planet_data
151 err := json_slurp(*planet_data_file, &data)
152 if err != nil {
153 panic(err)
154 }
155 return data
156 }
157
158 /* This program operates by filling in a state table representing the best
159 * possible trips you could make; the ones that makes you the most money.
160 * This is feasible because we don't look at all the possible trips.
161 * We define a list of things that are germane to this game and then only
162 * consider the best outcome in each possible game state.
163 *
164 * Each cell in the table represents a state in the game. In each cell,
165 * we track two things: 1. the most money you could possibly have while in
166 * that state and 2. one possible way to get into that state with that
167 * amount of money.
168 *
169 * A basic analysis can be done with a two-dimensional table: location and
170 * fuel. planeteer-1.0 used this two-dimensional table. This version
171 * adds features mostly by adding dimensions to this table.
172 *
173 * Note that the sizes of each dimension are data driven. Many dimensions
174 * collapse to one possible value (ie, disappear) if the corresponding
175 * feature is not enabled.
176 *
177 * The order of the dimensions in the list of constants below determines
178 * their layout in RAM. The cargo-based 'dimensions' are not completely
179 * independent -- some combinations are illegal and not used. They are
180 * handled as three dimensions rather than one for simplicity. Placing
181 * these dimensions first causes the unused cells in the table to be
182 * grouped together in large blocks. This keeps the unused cells from
183 * polluting cache lines, and if the spans of unused cells are large
184 * enough, allows the memory manager to swap out entire pages.
185 *
186 * If the table gets too big to fit in RAM:
187 * * Combine the Edens, Cloaks, and UnusedCargo dimensions. Of the
188 * 24 combinations, only 15 are legal: a 38% savings.
189 * * Reduce the size of the Fuel dimension to 3. Explicit iteration
190 * only ever needs to look backwards 2 units, so the logical values
191 * can rotate through the same 3 physical addresses. This would be
192 * good for an 82% savings. Note that explicit iteration went away
193 * in 0372f045.
194 * * Reduce the size of the Edens dimension from 3 to 2, for the
195 * same reasons as Fuel above. 33% savings.
196 * * Buy more ram. (Just sayin'. It's cheaper than you think.)
197 *
198 */
199
200 // The official list of dimensions:
201 const (
202 // Name Num Size Description
203 Edens = iota // 1 3 # of Eden warp units (0 - 2 typically)
204 Cloaks // 2 1-2 # of Devices of Cloaking (0 or 1)
205 UnusedCargo // 3 4 # of unused cargo spaces (0 - 3 typically)
206 Fuel // 4 17 Hyper jump power left (0 - 16)
207 Location // 5 26 Location (which planet)
208 Hold // 6 15 Cargo bay contents (a *Commodity or nil)
209 Traded // 7 2 Traded yet?
210 BuyFighters // 8 1-2 Errand: Buy fighter drones
211 BuyShields // 9 1-2 Errand: Buy shield batteries
212 Visit // 10 1-2**N Visit: Stop by these N planets in the route
213
214 NumDimensions
215 )
216
217 func bint(b bool) int {
218 if b {
219 return 1
220 }
221 return 0
222 }
223
224 func DimensionSizes(data planet_data) LogicalIndex {
225 eden_capacity := data.Commodities["Eden Warp Units"].Limit
226 if *start_edens > eden_capacity {
227 eden_capacity = *start_edens
228 }
229 cloak_capacity := bint(*cloak)
230 dims := make(LogicalIndex, NumDimensions)
231 dims[Edens] = eden_capacity + 1
232 dims[Cloaks] = cloak_capacity + 1
233 dims[UnusedCargo] = eden_capacity + cloak_capacity + 1
234 dims[Fuel] = *fuel + 1
235 dims[Location] = len(data.Planets)
236 dims[Hold] = len(data.Commodities) + 1
237 dims[Traded] = 2
238 dims[BuyFighters] = bint(*drones > 0) + 1
239 dims[BuyShields] = bint(*batteries > 0) + 1
240 dims[Visit] = 1 << uint(len(visit()))
241
242 // Remind myself to add a line above when adding new dimensions
243 for i, dim := range dims {
244 if dim < 1 {
245 panic(i)
246 }
247 }
248 return dims
249 }
250
251 type Value int32
252 type PhysicalIndex int32
253 type LogicalIndex []int
254
255 func StateTableSize(dims LogicalIndex) int {
256 product := 1
257 for _, size := range dims {
258 product *= size
259 }
260 return product
261 }
262
263 type State struct {
264 value Value
265 from PhysicalIndex
266 }
267
268 const (
269 FROM_ROOT = -2147483647 + iota
270 FROM_UNINITIALIZED
271 VALUE_UNINITIALIZED
272 VALUE_BEING_EVALUATED
273 VALUE_RUBISH
274 )
275
276 func EncodeIndex(dims, addr LogicalIndex) PhysicalIndex {
277 index := addr[0]
278 if addr[0] > dims[0] {
279 panic(0)
280 }
281 for i := 1; i < NumDimensions; i++ {
282 if addr[i] < 0 || addr[i] >= dims[i] {
283 panic(i)
284 }
285 index = index*dims[i] + addr[i]
286 }
287 return PhysicalIndex(index)
288 }
289
290 func DecodeIndex(dims LogicalIndex, index PhysicalIndex) LogicalIndex {
291 scratch := int(index)
292 addr := make(LogicalIndex, NumDimensions)
293 for i := NumDimensions - 1; i > 0; i-- {
294 addr[i] = scratch % dims[i]
295 scratch /= dims[i]
296 }
297 addr[0] = scratch
298 return addr
299 }
300
301 func PlanetIndex(data planet_data, name string) int {
302 index, ok := data.p2i[name]
303 if !ok {
304 panic("Unknown planet " + name)
305 }
306 return index
307 }
308
309 func CommodityIndex(data planet_data, name string) int {
310 index, ok := data.c2i[name]
311 if !ok {
312 panic("Unknown commodity " + name)
313 }
314 return index
315 }
316
317 func CreateStateTable(data planet_data, dims LogicalIndex) []State {
318 table := make([]State, StateTableSize(dims))
319 for i := range table {
320 table[i].value = VALUE_UNINITIALIZED
321 table[i].from = FROM_UNINITIALIZED
322 }
323
324 addr := make(LogicalIndex, NumDimensions)
325 addr[Fuel] = *fuel
326 addr[Edens] = *start_edens
327 addr[Location] = PlanetIndex(data, *start)
328 if *start_hold != "" {
329 addr[Hold] = CommodityIndex(data, *start_hold)
330 }
331 start_index := EncodeIndex(dims, addr)
332 table[start_index].value = Value(*funds)
333 table[start_index].from = FROM_ROOT
334
335 return table
336 }
337
338 /* CellValue fills in the one cell at address addr by looking at all
339 * the possible ways to reach this cell and selecting the best one. */
340
341 func Consider(data planet_data, dims LogicalIndex, table []State, there LogicalIndex, value_difference int, best_value *Value, best_source LogicalIndex) {
342 there_value := CellValue(data, dims, table, there)
343 if value_difference < 0 && Value(-value_difference) > there_value {
344 /* Can't afford this transition */
345 return
346 }
347 possible_value := there_value + Value(value_difference)
348 if possible_value > *best_value {
349 *best_value = possible_value
350 copy(best_source, there)
351 }
352 }
353
354 var cell_filled_count int
355
356 func CellValue(data planet_data, dims LogicalIndex, table []State, addr LogicalIndex) Value {
357 my_index := EncodeIndex(dims, addr)
358 if table[my_index].value == VALUE_BEING_EVALUATED {
359 panic("Circular dependency")
360 }
361 if table[my_index].value != VALUE_UNINITIALIZED {
362 return table[my_index].value
363 }
364 table[my_index].value = VALUE_BEING_EVALUATED
365
366 best_value := Value(VALUE_RUBISH)
367 best_source := make(LogicalIndex, NumDimensions)
368 other := make(LogicalIndex, NumDimensions)
369 copy(other, addr)
370 planet := data.i2p[addr[Location]]
371
372 /* Travel here */
373 if addr[Traded] == 0 { /* Can't have traded immediately after traveling. */
374 other[Traded] = 1 /* Travel from states that have done trading. */
375
376 /* Travel here via a 2-fuel unit jump */
377 if data.Planets[data.i2p[addr[Location]]].BeaconOn && addr[Fuel]+2 < dims[Fuel] {
378 other[Fuel] = addr[Fuel] + 2
379 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 2)
380 if hole_index >= len(flight_plan()) || addr[Location] != PlanetIndex(data, flight_plan()[hole_index]) {
381 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
382 Consider(data, dims, table, other, 0, &best_value, best_source)
383 }
384 }
385 other[Location] = addr[Location]
386 other[Fuel] = addr[Fuel]
387 }
388
389 /* Travel here via a 1-fuel unit jump (a hyper hole) */
390 if addr[Fuel]+1 < dims[Fuel] {
391 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 1)
392 if hole_index < len(flight_plan()) && addr[Location] == PlanetIndex(data, flight_plan()[hole_index]) {
393 other[Fuel] = addr[Fuel] + 1
394 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
395 Consider(data, dims, table, other, 0, &best_value, best_source)
396 }
397 other[Location] = addr[Location]
398 other[Fuel] = addr[Fuel]
399 }
400 }
401
402 /* Travel here via Eden Warp Unit */
403 if addr[Edens]+1 < dims[Edens] && (addr[Hold] == 0 || addr[UnusedCargo] > 0) {
404 _, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
405 if !available {
406 other[Edens] = addr[Edens] + 1
407 if other[Hold] != 0 {
408 other[UnusedCargo] = addr[UnusedCargo] - 1
409 }
410 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
411 Consider(data, dims, table, other, 0, &best_value, best_source)
412 }
413 other[Location] = addr[Location]
414 other[UnusedCargo] = addr[UnusedCargo]
415 other[Edens] = addr[Edens]
416 }
417 }
418 other[Traded] = addr[Traded]
419 }
420
421 /* Trade */
422 if addr[Traded] == 1 {
423 other[Traded] = 0
424
425 /* Consider not trading */
426 Consider(data, dims, table, other, 0, &best_value, best_source)
427
428 if !data.Planets[data.i2p[addr[Location]]].Private {
429
430 /* Sell */
431 if addr[Hold] == 0 && addr[UnusedCargo] == 0 {
432 for other[Hold] = 0; other[Hold] < dims[Hold]; other[Hold]++ {
433 commodity := data.i2c[other[Hold]]
434 if !data.Commodities[commodity].CanSell {
435 continue
436 }
437 relative_price, available := data.Planets[planet].RelativePrices[commodity]
438 if !available {
439 // TODO: Dump cargo
440 continue
441 }
442 base_price := data.Commodities[commodity].BasePrice
443 absolute_price := float64(base_price) * float64(relative_price) / 100.0
444 sell_price := int(absolute_price * 0.9)
445
446 for other[UnusedCargo] = 0; other[UnusedCargo] < dims[UnusedCargo]; other[UnusedCargo]++ {
447 quantity := *hold - (other[UnusedCargo] + other[Cloaks] + other[Edens])
448 sale_value := quantity * sell_price
449 Consider(data, dims, table, other, sale_value, &best_value, best_source)
450 }
451 }
452 other[UnusedCargo] = addr[UnusedCargo]
453 other[Hold] = addr[Hold]
454 }
455
456 /* Buy */
457 other[Traded] = addr[Traded] /* Buy after selling */
458 if addr[Hold] != 0 {
459 commodity := data.i2c[addr[Hold]]
460 if data.Commodities[commodity].CanSell {
461 relative_price, available := data.Planets[planet].RelativePrices[commodity]
462 if available {
463 base_price := data.Commodities[commodity].BasePrice
464 absolute_price := int(float64(base_price) * float64(relative_price) / 100.0)
465 quantity := *hold - (addr[UnusedCargo] + addr[Cloaks] + addr[Edens])
466 total_price := quantity * absolute_price
467 other[Hold] = 0
468 other[UnusedCargo] = 0
469 Consider(data, dims, table, other, -total_price, &best_value, best_source)
470 other[UnusedCargo] = addr[UnusedCargo]
471 other[Hold] = addr[Hold]
472 }
473 }
474 }
475 }
476 other[Traded] = addr[Traded]
477 }
478
479 /* Buy a Device of Cloaking */
480 if addr[Cloaks] == 1 && addr[UnusedCargo] < dims[UnusedCargo]-1 {
481 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Device Of Cloakings"]
482 if available {
483 absolute_price := int(float64(data.Commodities["Device Of Cloakings"].BasePrice) * float64(relative_price) / 100.0)
484 other[Cloaks] = 0
485 if other[Hold] != 0 {
486 other[UnusedCargo] = addr[UnusedCargo] + 1
487 }
488 Consider(data, dims, table, other, -absolute_price, &best_value, best_source)
489 other[UnusedCargo] = addr[UnusedCargo]
490 other[Cloaks] = addr[Cloaks]
491 }
492 }
493
494 /* Buy Fighter Drones */
495 if addr[BuyFighters] == 1 {
496 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Fighter Drones"]
497 if available {
498 absolute_price := int(float64(data.Commodities["Fighter Drones"].BasePrice) * float64(relative_price) / 100.0)
499 other[BuyFighters] = 0
500 Consider(data, dims, table, other, -absolute_price**drones, &best_value, best_source)
501 other[BuyFighters] = addr[BuyFighters]
502 }
503 }
504
505 /* Buy Shield Batteries */
506 if addr[BuyShields] == 1 {
507 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Shield Batterys"]
508 if available {
509 absolute_price := int(float64(data.Commodities["Shield Batterys"].BasePrice) * float64(relative_price) / 100.0)
510 other[BuyShields] = 0
511 Consider(data, dims, table, other, -absolute_price**batteries, &best_value, best_source)
512 other[BuyShields] = addr[BuyShields]
513 }
514 }
515
516 /* Visit this planet */
517 for i := uint(0); i < uint(len(visit())); i++ {
518 if addr[Visit]&(1<<i) != 0 && visit()[i] == data.i2p[addr[Location]] {
519 other[Visit] = addr[Visit] & ^(1 << i)
520 Consider(data, dims, table, other, 0, &best_value, best_source)
521 }
522 }
523 other[Visit] = addr[Visit]
524
525 /* Buy Eden warp units */
526 eden_limit := data.Commodities["Eden Warp Units"].Limit
527 if addr[Edens] > 0 && addr[Edens] <= eden_limit {
528 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
529 if available {
530 absolute_price := int(float64(data.Commodities["Eden Warp Units"].BasePrice) * float64(relative_price) / 100.0)
531 for quantity := addr[Edens]; quantity > 0; quantity-- {
532 other[Edens] = addr[Edens] - quantity
533 if addr[Hold] != 0 {
534 other[UnusedCargo] = addr[UnusedCargo] + quantity
535 }
536 if other[UnusedCargo] < dims[UnusedCargo] {
537 Consider(data, dims, table, other, -absolute_price*quantity, &best_value, best_source)
538 }
539 }
540 other[Edens] = addr[Edens]
541 other[UnusedCargo] = addr[UnusedCargo]
542 }
543 }
544
545 // Check that we didn't lose track of any temporary modifications to other.
546 for i := 0; i < NumDimensions; i++ {
547 if addr[i] != other[i] {
548 panic(i)
549 }
550 }
551
552 // Sanity check: This cell was in state BEING_EVALUATED
553 // the whole time that it was being evaluated.
554 if table[my_index].value != VALUE_BEING_EVALUATED {
555 panic(my_index)
556 }
557
558 // Record our findings
559 table[my_index].value = best_value
560 table[my_index].from = EncodeIndex(dims, best_source)
561
562 // UI: Progress bar
563 cell_filled_count++
564 if cell_filled_count&0xfff == 0 {
565 print(fmt.Sprintf("\r%3.1f%%", 100*float64(cell_filled_count)/float64(StateTableSize(dims))))
566 }
567
568 return table[my_index].value
569 }
570
571 func FinalState(dims LogicalIndex) LogicalIndex {
572 addr := make(LogicalIndex, NumDimensions)
573 addr[Edens] = *end_edens
574 addr[Cloaks] = dims[Cloaks] - 1
575 addr[BuyFighters] = dims[BuyFighters] - 1
576 addr[BuyShields] = dims[BuyShields] - 1
577 addr[Visit] = dims[Visit] - 1
578 addr[Traded] = 1
579 addr[Hold] = 0
580 addr[UnusedCargo] = 0
581 // Fuel and Location are determined by FindBestState
582 return addr
583 }
584
585 func FindBestState(data planet_data, dims LogicalIndex, table []State, addr LogicalIndex) PhysicalIndex {
586 max_index := PhysicalIndex(-1)
587 max_value := 0.0
588 max_fuel := 1
589 if *fuel == 0 {
590 max_fuel = 0
591 }
592 for addr[Fuel] = 0; addr[Fuel] <= max_fuel; addr[Fuel]++ {
593 for addr[Location] = 0; addr[Location] < dims[Location]; addr[Location]++ {
594 planet := data.i2p[addr[Location]]
595 if len(end()) == 0 || end()[planet] {
596 index := EncodeIndex(dims, addr)
597 today_value := CellValue(data, dims, table, addr)
598 tomorrow_value := *tomorrow_weight * float64(*hold+data.Planets[planet].TomorrowValue)
599 value := float64(today_value) + tomorrow_value
600 if value > max_value {
601 max_value = value
602 max_index = index
603 }
604 }
605 }
606 }
607 return max_index
608 }
609
610 func Commas(n Value) string {
611 var s string
612 if n < 0 {
613 panic(n)
614 }
615 r := n % 1000
616 n /= 1000
617 for n > 0 {
618 s = fmt.Sprintf(",%03d", r) + s
619 r = n % 1000
620 n /= 1000
621 }
622 s = fmt.Sprint(r) + s
623 return s
624 }
625
626 func FighterAndShieldCost(data planet_data, dims LogicalIndex, table []State, best PhysicalIndex) {
627 if *drones == 0 && *batteries == 0 {
628 return
629 }
630 fmt.Println()
631 if *drones > 0 {
632 final_state := FinalState(dims)
633 final_state[BuyFighters] = 0
634 alt_best := FindBestState(data, dims, table, final_state)
635 cost := table[alt_best].value - table[best].value
636 fmt.Printf("\rDrones were %.2f each\n", float64(cost)/float64(*drones))
637 }
638 if *batteries > 0 {
639 final_state := FinalState(dims)
640 final_state[BuyShields] = 0
641 alt_best := FindBestState(data, dims, table, final_state)
642 cost := table[alt_best].value - table[best].value
643 fmt.Printf("\rBatteries were %.2f each\n", float64(cost)/float64(*batteries))
644 }
645 }
646
647 func EndEdensCost(data planet_data, dims LogicalIndex, table []State, best PhysicalIndex) {
648 if *end_edens == 0 {
649 return
650 }
651 fmt.Println()
652 final_state := FinalState(dims)
653 for extra_edens := 1; extra_edens <= *end_edens; extra_edens++ {
654 final_state[Edens] = *end_edens - extra_edens
655 alt_best := FindBestState(data, dims, table, final_state)
656 extra_funds := table[alt_best].value - table[best].value
657 fmt.Println("\rUse", extra_edens, "extra edens, make an extra",
658 Commas(extra_funds), "(",
659 Commas(extra_funds/Value(extra_edens)), "per eden)")
660 }
661 }
662
663 func VisitCost(data planet_data, dims LogicalIndex, table []State, best PhysicalIndex) {
664 if dims[Visit] == 1 {
665 return
666 }
667 fmt.Println()
668 final_state := FinalState(dims)
669 for i := uint(0); i < uint(len(visit())); i++ {
670 all_bits := dims[Visit] - 1
671 final_state[Visit] = all_bits & ^(1 << i)
672 alt_best := FindBestState(data, dims, table, final_state)
673 cost := table[alt_best].value - table[best].value
674 fmt.Printf("\r%11v Cost to visit %v\n", Commas(cost), visit()[i])
675 }
676 }
677
678 func EndLocationCost(data planet_data, dims LogicalIndex, table []State, best PhysicalIndex) {
679 if len(end()) == 0 {
680 return
681 }
682 fmt.Println()
683 final_state := FinalState(dims)
684 save_end_string := *end_string
685 *end_string = ""
686 end_cache = nil
687 alt_best := FindBestState(data, dims, table, final_state)
688 cost := table[alt_best].value - table[best].value
689 fmt.Printf("\r%11v Cost of --end %v\n", Commas(cost), save_end_string)
690 *end_string = save_end_string
691 }
692
693 func DescribePath(data planet_data, dims LogicalIndex, table []State, start PhysicalIndex) []string {
694 var description []string
695 for index := start; table[index].from > FROM_ROOT; index = table[index].from {
696 if table[index].from == FROM_UNINITIALIZED {
697 panic(index)
698 }
699 var line string
700 addr := DecodeIndex(dims, index)
701 prev := DecodeIndex(dims, table[index].from)
702 if addr[Fuel] != prev[Fuel] {
703 from := data.i2p[prev[Location]]
704 to := data.i2p[addr[Location]]
705 line += fmt.Sprintf("Jump from %v to %v (%v hyper jump units)", from, to, prev[Fuel]-addr[Fuel])
706 }
707 if addr[Edens] == prev[Edens]-1 {
708 from := data.i2p[prev[Location]]
709 to := data.i2p[addr[Location]]
710 line += fmt.Sprintf("Eden warp from %v to %v", from, to)
711 }
712 if addr[Hold] != prev[Hold] {
713 if addr[Hold] == 0 {
714 quantity := *hold - (prev[UnusedCargo] + prev[Edens] + prev[Cloaks])
715 line += fmt.Sprintf("Sell %v %v", quantity, data.i2c[prev[Hold]])
716 } else if prev[Hold] == 0 {
717 quantity := *hold - (addr[UnusedCargo] + addr[Edens] + addr[Cloaks])
718 line += fmt.Sprintf("Buy %v %v", quantity, data.i2c[addr[Hold]])
719 } else {
720 panic("Switched cargo?")
721 }
722
723 }
724 if addr[Cloaks] == 1 && prev[Cloaks] == 0 {
725 // TODO: Dump cloaks, convert from cargo?
726 line += "Buy a Cloak"
727 }
728 if addr[Edens] > prev[Edens] {
729 line += fmt.Sprint("Buy ", addr[Edens]-prev[Edens], " Eden Warp Units")
730 }
731 if addr[BuyShields] == 1 && prev[BuyShields] == 0 {
732 line += fmt.Sprint("Buy ", *batteries, " Shield Batterys")
733 }
734 if addr[BuyFighters] == 1 && prev[BuyFighters] == 0 {
735 line += fmt.Sprint("Buy ", *drones, " Fighter Drones")
736 }
737 if addr[Visit] != prev[Visit] {
738 // TODO: verify that the bit chat changed is addr[Location]
739 line += fmt.Sprint("Visit ", data.i2p[addr[Location]])
740 }
741 if line == "" && addr[Hold] == prev[Hold] && addr[Traded] != prev[Traded] {
742 // The Traded dimension is for housekeeping. It doesn't directly
743 // correspond to in-game actions, so don't report transitions.
744 continue
745 }
746 if line == "" {
747 line = fmt.Sprint(prev, " -> ", addr)
748 }
749 description = append(description, fmt.Sprintf("%13v ", Commas(table[index].value))+line)
750 }
751 return description
752 }
753
754 // (Example of a use case for generics in Go)
755 func IndexPlanets(m *map[string]Planet, start_at int) (map[string]int, []string) {
756 e2i := make(map[string]int, len(*m)+start_at)
757 i2e := make([]string, len(*m)+start_at)
758 i := start_at
759 for e := range *m {
760 e2i[e] = i
761 i2e[i] = e
762 i++
763 }
764 return e2i, i2e
765 }
766 func IndexCommodities(m *map[string]Commodity, start_at int) (map[string]int, []string) {
767 e2i := make(map[string]int, len(*m)+start_at)
768 i2e := make([]string, len(*m)+start_at)
769 i := start_at
770 for e := range *m {
771 e2i[e] = i
772 i2e[i] = e
773 i++
774 }
775 return e2i, i2e
776 }
777
778 func main() {
779 flag.Parse()
780 if *start == "" || *funds == 0 {
781 print("--start and --funds are required. --help for more\n")
782 return
783 }
784 if *cpuprofile != "" {
785 f, err := os.Create(*cpuprofile)
786 if err != nil {
787 panic(err)
788 }
789 pprof.StartCPUProfile(f)
790 defer pprof.StopCPUProfile()
791 }
792 data := ReadData()
793 if *drone_price > 0 {
794 temp := data.Commodities["Fighter Drones"]
795 temp.BasePrice = *drone_price
796 data.Commodities["Fighter Drones"] = temp
797 }
798 if *battery_price > 0 {
799 temp := data.Commodities["Shield Batterys"]
800 temp.BasePrice = *battery_price
801 data.Commodities["Shield Batterys"] = temp
802 }
803 data.p2i, data.i2p = IndexPlanets(&data.Planets, 0)
804 data.c2i, data.i2c = IndexCommodities(&data.Commodities, 1)
805 dims := DimensionSizes(data)
806 table := CreateStateTable(data, dims)
807 final_state := FinalState(dims)
808 best := FindBestState(data, dims, table, final_state)
809 print("\n")
810 if best == -1 {
811 print("Cannot achieve success criteria\n")
812 return
813 }
814 description := DescribePath(data, dims, table, best)
815 for i := len(description) - 1; i >= 0; i-- {
816 fmt.Println(description[i])
817 }
818
819 if *extra_stats {
820 FighterAndShieldCost(data, dims, table, best)
821 EndEdensCost(data, dims, table, best)
822 VisitCost(data, dims, table, best)
823 EndLocationCost(data, dims, table, best)
824 }
825 }