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