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