]> git.scottworley.com Git - planeteer/blame_incremental - planeteer.go
Only print two significant figures for arms costs
[planeteer] / planeteer.go
... / ...
CommitLineData
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"
21import "fmt"
22import "encoding/json"
23import "os"
24import "runtime/pprof"
25import "strings"
26
27var funds = flag.Int("funds", 0,
28 "Starting funds")
29
30var start = flag.String("start", "",
31 "The planet to start at")
32
33var flight_plan_string = flag.String("flight_plan", "",
34 "Your hyper-holes for the day, comma-separated.")
35
36var end_string = flag.String("end", "",
37 "A comma-separated list of acceptable ending planets.")
38
39var planet_data_file = flag.String("planet_data_file", "planet-data",
40 "The file to read planet data from")
41
42var fuel = flag.Int("fuel", 16, "Hyper Jump power left")
43
44var hold = flag.Int("hold", 300, "Size of your cargo hold")
45
46var start_hold = flag.String("start_hold", "", "Start with a hold full of cargo")
47
48var start_edens = flag.Int("start_edens", 0,
49 "How many Eden Warp Units are you starting with?")
50
51var end_edens = flag.Int("end_edens", 0,
52 "How many Eden Warp Units would you like to keep (not use)?")
53
54var cloak = flag.Bool("cloak", false,
55 "Make sure to end with a Device of Cloaking")
56
57var drones = flag.Int("drones", 0, "Buy this many Fighter Drones")
58
59var batteries = flag.Int("batteries", 0, "Buy this many Shield Batterys")
60
61var drone_price = flag.Int("drone_price", 0, "Today's Fighter Drone price")
62
63var battery_price = flag.Int("battery_price", 0, "Today's Shield Battery price")
64
65var visit_string = flag.String("visit", "",
66 "A comma-separated list of planets to make sure to visit")
67
68var tomorrow_weight = flag.Float64("tomorrow_weight", 1.0,
69 "Weight for the expected value of tomorrow's trading. 0.0 - 1.0")
70
71var extra_stats = flag.Bool("extra_stats", true,
72 "Show additional information of possible interest")
73
74var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
75
76var visit_cache []string
77
78func 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
88var flight_plan_cache []string
89
90func 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
100var end_cache map[string]bool
101
102func 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
116type Commodity struct {
117 BasePrice int
118 CanSell bool
119 Limit int
120}
121type 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}
129type 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
136func 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
149func 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:
200const (
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
216func bint(b bool) int {
217 if b {
218 return 1
219 }
220 return 0
221}
222
223func 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
250type Value int32
251type PhysicalIndex int32
252type LogicalIndex []int
253
254func StateTableSize(dims LogicalIndex) int {
255 product := 1
256 for _, size := range dims {
257 product *= size
258 }
259 return product
260}
261
262type State struct {
263 value Value
264 from PhysicalIndex
265}
266
267const (
268 FROM_ROOT = -2147483647 + iota
269 FROM_UNINITIALIZED
270 VALUE_UNINITIALIZED
271 VALUE_BEING_EVALUATED
272 VALUE_RUBISH
273)
274
275func 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
289func 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
300func PlanetIndex(data planet_data, name string) int {
301 index, ok := data.p2i[name]
302 if !ok {
303 panic("Unknown planet " + name)
304 }
305 return index
306}
307
308func CommodityIndex(data planet_data, name string) int {
309 index, ok := data.c2i[name]
310 if !ok {
311 panic("Unknown commodity " + name)
312 }
313 return index
314}
315
316func CreateStateTable(data planet_data, dims LogicalIndex) []State {
317 table := make([]State, StateTableSize(dims))
318 for i := range table {
319 table[i].value = VALUE_UNINITIALIZED
320 table[i].from = FROM_UNINITIALIZED
321 }
322
323 addr := make(LogicalIndex, NumDimensions)
324 addr[Fuel] = *fuel
325 addr[Edens] = *start_edens
326 addr[Location] = PlanetIndex(data, *start)
327 if *start_hold != "" {
328 addr[Hold] = CommodityIndex(data,*start_hold)
329 }
330 start_index := EncodeIndex(dims, addr)
331 table[start_index].value = Value(*funds)
332 table[start_index].from = FROM_ROOT
333
334 return table
335}
336
337/* CellValue fills in the one cell at address addr by looking at all
338 * the possible ways to reach this cell and selecting the best one. */
339
340func Consider(data planet_data, dims LogicalIndex, table []State, there LogicalIndex, value_difference int, best_value *Value, best_source LogicalIndex) {
341 there_value := CellValue(data, dims, table, there)
342 if value_difference < 0 && Value(-value_difference) > there_value {
343 /* Can't afford this transition */
344 return
345 }
346 possible_value := there_value + Value(value_difference)
347 if possible_value > *best_value {
348 *best_value = possible_value
349 copy(best_source, there)
350 }
351}
352
353var cell_filled_count int
354
355func CellValue(data planet_data, dims LogicalIndex, table []State, addr LogicalIndex) Value {
356 my_index := EncodeIndex(dims, addr)
357 if table[my_index].value == VALUE_BEING_EVALUATED {
358 panic("Circular dependency")
359 }
360 if table[my_index].value != VALUE_UNINITIALIZED {
361 return table[my_index].value
362 }
363 table[my_index].value = VALUE_BEING_EVALUATED
364
365 best_value := Value(VALUE_RUBISH)
366 best_source := make(LogicalIndex, NumDimensions)
367 other := make(LogicalIndex, NumDimensions)
368 copy(other, addr)
369 planet := data.i2p[addr[Location]]
370
371 /* Travel here */
372 if addr[Traded] == 0 { /* Can't have traded immediately after traveling. */
373 other[Traded] = 1 /* Travel from states that have done trading. */
374
375 /* Travel here via a 2-fuel unit jump */
376 if addr[Fuel]+2 < dims[Fuel] {
377 other[Fuel] = addr[Fuel] + 2
378 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 2)
379 if hole_index >= len(flight_plan()) || addr[Location] != PlanetIndex(data, flight_plan()[hole_index]) {
380 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
381 if data.Planets[data.i2p[addr[Location]]].BeaconOn {
382 Consider(data, dims, table, other, 0, &best_value, best_source)
383 }
384 }
385 }
386 other[Location] = addr[Location]
387 other[Fuel] = addr[Fuel]
388 }
389
390 /* Travel here via a 1-fuel unit jump (a hyper hole) */
391 if addr[Fuel]+1 < dims[Fuel] {
392 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 1)
393 if hole_index < len(flight_plan()) && addr[Location] == PlanetIndex(data, flight_plan()[hole_index]) {
394 other[Fuel] = addr[Fuel] + 1
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[Fuel] = addr[Fuel]
400 }
401 }
402
403 /* Travel here via Eden Warp Unit */
404 if addr[Edens]+1 < dims[Edens] && addr[UnusedCargo] > 0 {
405 _, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
406 if !available {
407 other[Edens] = addr[Edens] + 1
408 if other[Hold] != 0 {
409 other[UnusedCargo] = addr[UnusedCargo] - 1
410 }
411 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
412 Consider(data, dims, table, other, 0, &best_value, best_source)
413 }
414 other[Location] = addr[Location]
415 other[UnusedCargo] = addr[UnusedCargo]
416 other[Edens] = addr[Edens]
417 }
418 }
419 other[Traded] = addr[Traded]
420 }
421
422 /* Trade */
423 if addr[Traded] == 1 {
424 other[Traded] = 0
425
426 /* Consider not trading */
427 Consider(data, dims, table, other, 0, &best_value, best_source)
428
429 if !data.Planets[data.i2p[addr[Location]]].Private {
430
431 /* Sell */
432 if addr[Hold] == 0 && addr[UnusedCargo] == 0 {
433 for other[Hold] = 0; other[Hold] < dims[Hold]; other[Hold]++ {
434 commodity := data.i2c[other[Hold]]
435 if !data.Commodities[commodity].CanSell {
436 continue
437 }
438 relative_price, available := data.Planets[planet].RelativePrices[commodity]
439 if !available {
440 // TODO: Dump cargo
441 continue
442 }
443 base_price := data.Commodities[commodity].BasePrice
444 absolute_price := float64(base_price) * float64(relative_price) / 100.0
445 sell_price := int(absolute_price * 0.9)
446
447 for other[UnusedCargo] = 0; other[UnusedCargo] < dims[UnusedCargo]; other[UnusedCargo]++ {
448 quantity := *hold - (other[UnusedCargo] + other[Cloaks] + other[Edens])
449 sale_value := quantity * sell_price
450 Consider(data, dims, table, other, sale_value, &best_value, best_source)
451 }
452 }
453 other[UnusedCargo] = addr[UnusedCargo]
454 other[Hold] = addr[Hold]
455 }
456
457 /* Buy */
458 other[Traded] = addr[Traded] /* Buy after selling */
459 if addr[Hold] != 0 {
460 commodity := data.i2c[addr[Hold]]
461 if data.Commodities[commodity].CanSell {
462 relative_price, available := data.Planets[planet].RelativePrices[commodity]
463 if available {
464 base_price := data.Commodities[commodity].BasePrice
465 absolute_price := int(float64(base_price) * float64(relative_price) / 100.0)
466 quantity := *hold - (addr[UnusedCargo] + addr[Cloaks] + addr[Edens])
467 total_price := quantity * absolute_price
468 other[Hold] = 0
469 other[UnusedCargo] = 0
470 Consider(data, dims, table, other, -total_price, &best_value, best_source)
471 other[UnusedCargo] = addr[UnusedCargo]
472 other[Hold] = addr[Hold]
473 }
474 }
475 }
476 }
477 other[Traded] = addr[Traded]
478 }
479
480 /* Buy a Device of Cloaking */
481 if addr[Cloaks] == 1 && addr[UnusedCargo] < dims[UnusedCargo]-1 {
482 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Device Of Cloakings"]
483 if available {
484 absolute_price := int(float64(data.Commodities["Device Of Cloakings"].BasePrice) * float64(relative_price) / 100.0)
485 other[Cloaks] = 0
486 if other[Hold] != 0 {
487 other[UnusedCargo] = addr[UnusedCargo] + 1
488 }
489 Consider(data, dims, table, other, -absolute_price, &best_value, best_source)
490 other[UnusedCargo] = addr[UnusedCargo]
491 other[Cloaks] = addr[Cloaks]
492 }
493 }
494
495 /* Buy Fighter Drones */
496 if addr[BuyFighters] == 1 {
497 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Fighter Drones"]
498 if available {
499 absolute_price := int(float64(data.Commodities["Fighter Drones"].BasePrice) * float64(relative_price) / 100.0)
500 other[BuyFighters] = 0
501 Consider(data, dims, table, other, -absolute_price**drones, &best_value, best_source)
502 other[BuyFighters] = addr[BuyFighters]
503 }
504 }
505
506 /* Buy Shield Batteries */
507 if addr[BuyShields] == 1 {
508 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Shield Batterys"]
509 if available {
510 absolute_price := int(float64(data.Commodities["Shield Batterys"].BasePrice) * float64(relative_price) / 100.0)
511 other[BuyShields] = 0
512 Consider(data, dims, table, other, -absolute_price**batteries, &best_value, best_source)
513 other[BuyShields] = addr[BuyShields]
514 }
515 }
516
517 /* Visit this planet */
518 for i := uint(0); i < uint(len(visit())); i++ {
519 if addr[Visit]&(1<<i) != 0 && visit()[i] == data.i2p[addr[Location]] {
520 other[Visit] = addr[Visit] & ^(1 << i)
521 Consider(data, dims, table, other, 0, &best_value, best_source)
522 }
523 }
524 other[Visit] = addr[Visit]
525
526 /* Buy Eden warp units */
527 eden_limit := data.Commodities["Eden Warp Units"].Limit
528 if addr[Edens] > 0 && addr[Edens] <= eden_limit {
529 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
530 if available {
531 absolute_price := int(float64(data.Commodities["Eden Warp Units"].BasePrice) * float64(relative_price) / 100.0)
532 for quantity := addr[Edens]; quantity > 0; quantity-- {
533 other[Edens] = addr[Edens] - quantity
534 if addr[Hold] != 0 {
535 other[UnusedCargo] = addr[UnusedCargo] + quantity
536 }
537 if other[UnusedCargo] < dims[UnusedCargo] {
538 Consider(data, dims, table, other, -absolute_price*quantity, &best_value, best_source)
539 }
540 }
541 other[Edens] = addr[Edens]
542 other[UnusedCargo] = addr[UnusedCargo]
543 }
544 }
545
546 // Check that we didn't lose track of any temporary modifications to other.
547 for i := 0; i < NumDimensions; i++ {
548 if addr[i] != other[i] {
549 panic(i)
550 }
551 }
552
553 // Sanity check: This cell was in state BEING_EVALUATED
554 // the whole time that it was being evaluated.
555 if table[my_index].value != VALUE_BEING_EVALUATED {
556 panic(my_index)
557 }
558
559 // Record our findings
560 table[my_index].value = best_value
561 table[my_index].from = EncodeIndex(dims, best_source)
562
563 // UI: Progress bar
564 cell_filled_count++
565 if cell_filled_count&0xfff == 0 {
566 print(fmt.Sprintf("\r%3.1f%%", 100*float64(cell_filled_count)/float64(StateTableSize(dims))))
567 }
568
569 return table[my_index].value
570}
571
572func FinalState(dims LogicalIndex) LogicalIndex {
573 addr := make(LogicalIndex, NumDimensions)
574 addr[Edens] = *end_edens
575 addr[Cloaks] = dims[Cloaks] - 1
576 addr[BuyFighters] = dims[BuyFighters] - 1
577 addr[BuyShields] = dims[BuyShields] - 1
578 addr[Visit] = dims[Visit] - 1
579 addr[Traded] = 1
580 addr[Hold] = 0
581 addr[UnusedCargo] = 0
582 // Fuel and Location are determined by FindBestState
583 return addr
584}
585
586func FindBestState(data planet_data, dims LogicalIndex, table []State, addr LogicalIndex) PhysicalIndex {
587 max_index := PhysicalIndex(-1)
588 max_value := 0.0
589 max_fuel := 1
590 if *fuel == 0 {
591 max_fuel = 0
592 }
593 for addr[Fuel] = 0; addr[Fuel] <= max_fuel; addr[Fuel]++ {
594 for addr[Location] = 0; addr[Location] < dims[Location]; addr[Location]++ {
595 planet := data.i2p[addr[Location]]
596 if len(end()) == 0 || end()[planet] {
597 index := EncodeIndex(dims, addr)
598 today_value := CellValue(data, dims, table, addr)
599 tomorrow_value := *tomorrow_weight * float64(*hold+data.Planets[planet].TomorrowValue)
600 value := float64(today_value) + tomorrow_value
601 if value > max_value {
602 max_value = value
603 max_index = index
604 }
605 }
606 }
607 }
608 return max_index
609}
610
611func Commas(n Value) (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
624}
625
626func 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
647func 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
663func 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
678func 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
693func DescribePath(data planet_data, dims LogicalIndex, table []State, start PhysicalIndex) (description []string) {
694 for index := start; table[index].from > FROM_ROOT; index = table[index].from {
695 if table[index].from == FROM_UNINITIALIZED {
696 panic(index)
697 }
698 var line string
699 addr := DecodeIndex(dims, index)
700 prev := DecodeIndex(dims, table[index].from)
701 if addr[Fuel] != prev[Fuel] {
702 from := data.i2p[prev[Location]]
703 to := data.i2p[addr[Location]]
704 line += fmt.Sprintf("Jump from %v to %v (%v hyper jump units)", from, to, prev[Fuel]-addr[Fuel])
705 }
706 if addr[Edens] == prev[Edens]-1 {
707 from := data.i2p[prev[Location]]
708 to := data.i2p[addr[Location]]
709 line += fmt.Sprintf("Eden warp from %v to %v", from, to)
710 }
711 if addr[Hold] != prev[Hold] {
712 if addr[Hold] == 0 {
713 quantity := *hold - (prev[UnusedCargo] + prev[Edens] + prev[Cloaks])
714 line += fmt.Sprintf("Sell %v %v", quantity, data.i2c[prev[Hold]])
715 } else if prev[Hold] == 0 {
716 quantity := *hold - (addr[UnusedCargo] + addr[Edens] + addr[Cloaks])
717 line += fmt.Sprintf("Buy %v %v", quantity, data.i2c[addr[Hold]])
718 } else {
719 panic("Switched cargo?")
720 }
721
722 }
723 if addr[Cloaks] == 1 && prev[Cloaks] == 0 {
724 // TODO: Dump cloaks, convert from cargo?
725 line += "Buy a Cloak"
726 }
727 if addr[Edens] > prev[Edens] {
728 line += fmt.Sprint("Buy ", addr[Edens]-prev[Edens], " Eden Warp Units")
729 }
730 if addr[BuyShields] == 1 && prev[BuyShields] == 0 {
731 line += fmt.Sprint("Buy ", *batteries, " Shield Batterys")
732 }
733 if addr[BuyFighters] == 1 && prev[BuyFighters] == 0 {
734 line += fmt.Sprint("Buy ", *drones, " Fighter Drones")
735 }
736 if addr[Visit] != prev[Visit] {
737 // TODO: verify that the bit chat changed is addr[Location]
738 line += fmt.Sprint("Visit ", data.i2p[addr[Location]])
739 }
740 if line == "" && addr[Hold] == prev[Hold] && addr[Traded] != prev[Traded] {
741 // The Traded dimension is for housekeeping. It doesn't directly
742 // correspond to in-game actions, so don't report transitions.
743 continue
744 }
745 if line == "" {
746 line = fmt.Sprint(prev, " -> ", addr)
747 }
748 description = append(description, fmt.Sprintf("%13v ", Commas(table[index].value))+line)
749 }
750 return
751}
752
753// (Example of a use case for generics in Go)
754func IndexPlanets(m *map[string]Planet, start_at int) (map[string]int, []string) {
755 e2i := make(map[string]int, len(*m)+start_at)
756 i2e := make([]string, len(*m)+start_at)
757 i := start_at
758 for e := range *m {
759 e2i[e] = i
760 i2e[i] = e
761 i++
762 }
763 return e2i, i2e
764}
765func IndexCommodities(m *map[string]Commodity, start_at int) (map[string]int, []string) {
766 e2i := make(map[string]int, len(*m)+start_at)
767 i2e := make([]string, len(*m)+start_at)
768 i := start_at
769 for e := range *m {
770 e2i[e] = i
771 i2e[i] = e
772 i++
773 }
774 return e2i, i2e
775}
776
777func main() {
778 flag.Parse()
779 if *start == "" || *funds == 0 {
780 print("--start and --funds are required. --help for more\n")
781 return
782 }
783 if *cpuprofile != "" {
784 f, err := os.Create(*cpuprofile)
785 if err != nil {
786 panic(err)
787 }
788 pprof.StartCPUProfile(f)
789 defer pprof.StopCPUProfile()
790 }
791 data := ReadData()
792 if *drone_price > 0 {
793 temp := data.Commodities["Fighter Drones"]
794 temp.BasePrice = *drone_price
795 data.Commodities["Fighter Drones"] = temp
796 }
797 if *battery_price > 0 {
798 temp := data.Commodities["Shield Batterys"]
799 temp.BasePrice = *battery_price
800 data.Commodities["Shield Batterys"] = temp
801 }
802 data.p2i, data.i2p = IndexPlanets(&data.Planets, 0)
803 data.c2i, data.i2c = IndexCommodities(&data.Commodities, 1)
804 dims := DimensionSizes(data)
805 table := CreateStateTable(data, dims)
806 final_state := FinalState(dims)
807 best := FindBestState(data, dims, table, final_state)
808 print("\n")
809 if best == -1 {
810 print("Cannot acheive success criteria\n")
811 return
812 }
813 description := DescribePath(data, dims, table, best)
814 for i := len(description) - 1; i >= 0; i-- {
815 fmt.Println(description[i])
816 }
817
818 if *extra_stats {
819 FighterAndShieldCost(data, dims, table, best)
820 EndEdensCost(data, dims, table, best)
821 VisitCost(data, dims, table, best)
822 EndLocationCost(data, dims, table, best)
823 }
824}