]> git.scottworley.com Git - planeteer/blob - planeteer.go
Start using named types: PhysicalIndex
[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 State struct {
251 value int32
252 from PhysicalIndex
253 }
254
255 const (
256 FROM_ROOT = -2147483647 + iota
257 FROM_UNINITIALIZED
258 VALUE_UNINITIALIZED
259 VALUE_BEING_EVALUATED
260 VALUE_RUBISH
261 )
262
263 type PhysicalIndex int32
264
265 func EncodeIndex(dims, addr []int) PhysicalIndex {
266 index := addr[0]
267 if addr[0] > dims[0] {
268 panic(0)
269 }
270 for i := 1; i < NumDimensions; i++ {
271 if addr[i] < 0 || addr[i] >= dims[i] {
272 panic(i)
273 }
274 index = index*dims[i] + addr[i]
275 }
276 return PhysicalIndex(index)
277 }
278
279 func DecodeIndex(dims []int, index PhysicalIndex) []int {
280 scratch := int(index)
281 addr := make([]int, NumDimensions)
282 for i := NumDimensions - 1; i > 0; i-- {
283 addr[i] = scratch % dims[i]
284 scratch /= dims[i]
285 }
286 addr[0] = scratch
287 return addr
288 }
289
290 func CreateStateTable(data planet_data, dims []int) []State {
291 table := make([]State, StateTableSize(dims))
292 for i := range table {
293 table[i].value = VALUE_UNINITIALIZED
294 table[i].from = FROM_UNINITIALIZED
295 }
296
297 addr := make([]int, NumDimensions)
298 addr[Fuel] = *fuel
299 addr[Edens] = *start_edens
300 addr[Location] = data.p2i[*start]
301 if *start_hold != "" {
302 addr[Hold] = data.c2i[*start_hold]
303 }
304 start_index := EncodeIndex(dims, addr)
305 table[start_index].value = int32(*funds)
306 table[start_index].from = FROM_ROOT
307
308 return table
309 }
310
311 /* CellValue fills in the one cell at address addr by looking at all
312 * the possible ways to reach this cell and selecting the best one. */
313
314 func Consider(data planet_data, dims []int, table []State, there []int, value_difference int, best_value *int32, best_source []int) {
315 there_value := CellValue(data, dims, table, there)
316 if value_difference < 0 && int32(-value_difference) > there_value {
317 /* Can't afford this transition */
318 return
319 }
320 possible_value := there_value + int32(value_difference)
321 if possible_value > *best_value {
322 *best_value = possible_value
323 copy(best_source, there)
324 }
325 }
326
327 var cell_filled_count int
328
329 func CellValue(data planet_data, dims []int, table []State, addr []int) int32 {
330 my_index := EncodeIndex(dims, addr)
331 if table[my_index].value == VALUE_BEING_EVALUATED {
332 panic("Circular dependency")
333 }
334 if table[my_index].value != VALUE_UNINITIALIZED {
335 return table[my_index].value
336 }
337 table[my_index].value = VALUE_BEING_EVALUATED
338
339 best_value := int32(VALUE_RUBISH)
340 best_source := make([]int, NumDimensions)
341 other := make([]int, NumDimensions)
342 copy(other, addr)
343 planet := data.i2p[addr[Location]]
344
345 /* Travel here */
346 if addr[Traded] == 0 { /* Can't have traded immediately after traveling. */
347 other[Traded] = 1 /* Travel from states that have done trading. */
348
349 /* Travel here via a 2-fuel unit jump */
350 if addr[Fuel]+2 < dims[Fuel] {
351 other[Fuel] = addr[Fuel] + 2
352 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 2)
353 if hole_index >= len(flight_plan()) || addr[Location] != data.p2i[flight_plan()[hole_index]] {
354 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
355 if data.Planets[data.i2p[addr[Location]]].BeaconOn {
356 Consider(data, dims, table, other, 0, &best_value, best_source)
357 }
358 }
359 }
360 other[Location] = addr[Location]
361 other[Fuel] = addr[Fuel]
362 }
363
364 /* Travel here via a 1-fuel unit jump (a hyper hole) */
365 if addr[Fuel]+1 < dims[Fuel] {
366 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 1)
367 if hole_index < len(flight_plan()) && addr[Location] == data.p2i[flight_plan()[hole_index]] {
368 other[Fuel] = addr[Fuel] + 1
369 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
370 Consider(data, dims, table, other, 0, &best_value, best_source)
371 }
372 other[Location] = addr[Location]
373 other[Fuel] = addr[Fuel]
374 }
375 }
376
377 /* Travel here via Eden Warp Unit */
378 if addr[Edens]+1 < dims[Edens] && addr[UnusedCargo] > 0 {
379 _, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
380 if !available {
381 other[Edens] = addr[Edens] + 1
382 if other[Hold] != 0 {
383 other[UnusedCargo] = addr[UnusedCargo] - 1
384 }
385 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
386 Consider(data, dims, table, other, 0, &best_value, best_source)
387 }
388 other[Location] = addr[Location]
389 other[UnusedCargo] = addr[UnusedCargo]
390 other[Edens] = addr[Edens]
391 }
392 }
393 other[Traded] = addr[Traded]
394 }
395
396 /* Trade */
397 if addr[Traded] == 1 {
398 other[Traded] = 0
399
400 /* Consider not trading */
401 Consider(data, dims, table, other, 0, &best_value, best_source)
402
403 if !data.Planets[data.i2p[addr[Location]]].Private {
404
405 /* Sell */
406 if addr[Hold] == 0 && addr[UnusedCargo] == 0 {
407 for other[Hold] = 0; other[Hold] < dims[Hold]; other[Hold]++ {
408 commodity := data.i2c[other[Hold]]
409 if !data.Commodities[commodity].CanSell {
410 continue
411 }
412 relative_price, available := data.Planets[planet].RelativePrices[commodity]
413 if !available {
414 // TODO: Dump cargo
415 continue
416 }
417 base_price := data.Commodities[commodity].BasePrice
418 absolute_price := float64(base_price) * float64(relative_price) / 100.0
419 sell_price := int(absolute_price * 0.9)
420
421 for other[UnusedCargo] = 0; other[UnusedCargo] < dims[UnusedCargo]; other[UnusedCargo]++ {
422 quantity := *hold - (other[UnusedCargo] + other[Cloaks] + other[Edens])
423 sale_value := quantity * sell_price
424 Consider(data, dims, table, other, sale_value, &best_value, best_source)
425 }
426 }
427 other[UnusedCargo] = addr[UnusedCargo]
428 other[Hold] = addr[Hold]
429 }
430
431 /* Buy */
432 other[Traded] = addr[Traded] /* Buy after selling */
433 if addr[Hold] != 0 {
434 commodity := data.i2c[addr[Hold]]
435 if data.Commodities[commodity].CanSell {
436 relative_price, available := data.Planets[planet].RelativePrices[commodity]
437 if available {
438 base_price := data.Commodities[commodity].BasePrice
439 absolute_price := int(float64(base_price) * float64(relative_price) / 100.0)
440 quantity := *hold - (addr[UnusedCargo] + addr[Cloaks] + addr[Edens])
441 total_price := quantity * absolute_price
442 other[Hold] = 0
443 other[UnusedCargo] = 0
444 Consider(data, dims, table, other, -total_price, &best_value, best_source)
445 other[UnusedCargo] = addr[UnusedCargo]
446 other[Hold] = addr[Hold]
447 }
448 }
449 }
450 }
451 other[Traded] = addr[Traded]
452 }
453
454 /* Buy a Device of Cloaking */
455 if addr[Cloaks] == 1 && addr[UnusedCargo] < dims[UnusedCargo]-1 {
456 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Device Of Cloakings"]
457 if available {
458 absolute_price := int(float64(data.Commodities["Device Of Cloakings"].BasePrice) * float64(relative_price) / 100.0)
459 other[Cloaks] = 0
460 if other[Hold] != 0 {
461 other[UnusedCargo] = addr[UnusedCargo] + 1
462 }
463 Consider(data, dims, table, other, -absolute_price, &best_value, best_source)
464 other[UnusedCargo] = addr[UnusedCargo]
465 other[Cloaks] = addr[Cloaks]
466 }
467 }
468
469 /* Buy Fighter Drones */
470 if addr[BuyFighters] == 1 {
471 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Fighter Drones"]
472 if available {
473 absolute_price := int(float64(data.Commodities["Fighter Drones"].BasePrice) * float64(relative_price) / 100.0)
474 other[BuyFighters] = 0
475 Consider(data, dims, table, other, -absolute_price**drones, &best_value, best_source)
476 other[BuyFighters] = addr[BuyFighters]
477 }
478 }
479
480 /* Buy Shield Batteries */
481 if addr[BuyShields] == 1 {
482 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Shield Batterys"]
483 if available {
484 absolute_price := int(float64(data.Commodities["Shield Batterys"].BasePrice) * float64(relative_price) / 100.0)
485 other[BuyShields] = 0
486 Consider(data, dims, table, other, -absolute_price**batteries, &best_value, best_source)
487 other[BuyShields] = addr[BuyShields]
488 }
489 }
490
491 /* Visit this planet */
492 for i := uint(0); i < uint(len(visit())); i++ {
493 if addr[Visit]&(1<<i) != 0 && visit()[i] == data.i2p[addr[Location]] {
494 other[Visit] = addr[Visit] & ^(1 << i)
495 Consider(data, dims, table, other, 0, &best_value, best_source)
496 }
497 }
498 other[Visit] = addr[Visit]
499
500 /* Buy Eden warp units */
501 eden_limit := data.Commodities["Eden Warp Units"].Limit
502 if addr[Edens] > 0 && addr[Edens] <= eden_limit {
503 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
504 if available {
505 absolute_price := int(float64(data.Commodities["Eden Warp Units"].BasePrice) * float64(relative_price) / 100.0)
506 for quantity := addr[Edens]; quantity > 0; quantity-- {
507 other[Edens] = addr[Edens] - quantity
508 if addr[Hold] != 0 {
509 other[UnusedCargo] = addr[UnusedCargo] + quantity
510 }
511 if other[UnusedCargo] < dims[UnusedCargo] {
512 Consider(data, dims, table, other, -absolute_price*quantity, &best_value, best_source)
513 }
514 }
515 other[Edens] = addr[Edens]
516 other[UnusedCargo] = addr[UnusedCargo]
517 }
518 }
519
520 // Check that we didn't lose track of any temporary modifications to other.
521 for i := 0; i < NumDimensions; i++ {
522 if addr[i] != other[i] {
523 panic(i)
524 }
525 }
526
527 // Sanity check: This cell was in state BEING_EVALUATED
528 // the whole time that it was being evaluated.
529 if table[my_index].value != VALUE_BEING_EVALUATED {
530 panic(my_index)
531 }
532
533 // Record our findings
534 table[my_index].value = best_value
535 table[my_index].from = EncodeIndex(dims, best_source)
536
537 // UI: Progress bar
538 cell_filled_count++
539 if cell_filled_count&0xfff == 0 {
540 print(fmt.Sprintf("\r%3.1f%%", 100*float64(cell_filled_count)/float64(StateTableSize(dims))))
541 }
542
543 return table[my_index].value
544 }
545
546 func FinalState(dims []int) []int {
547 addr := make([]int, NumDimensions)
548 addr[Edens] = *end_edens
549 addr[Cloaks] = dims[Cloaks] - 1
550 addr[BuyFighters] = dims[BuyFighters] - 1
551 addr[BuyShields] = dims[BuyShields] - 1
552 addr[Visit] = dims[Visit] - 1
553 addr[Traded] = 1
554 addr[Hold] = 0
555 addr[UnusedCargo] = 0
556 // Fuel and Location are determined by FindBestState
557 return addr
558 }
559
560 func FindBestState(data planet_data, dims []int, table []State, addr []int) PhysicalIndex {
561 max_index := PhysicalIndex(-1)
562 max_value := 0.0
563 max_fuel := 1
564 if *fuel == 0 {
565 max_fuel = 0
566 }
567 for addr[Fuel] = 0; addr[Fuel] <= max_fuel; addr[Fuel]++ {
568 for addr[Location] = 0; addr[Location] < dims[Location]; addr[Location]++ {
569 planet := data.i2p[addr[Location]]
570 if len(end()) == 0 || end()[planet] {
571 index := EncodeIndex(dims, addr)
572 today_value := CellValue(data, dims, table, addr)
573 tomorrow_value := *tomorrow_weight * float64(*hold+data.Planets[planet].TomorrowValue)
574 value := float64(today_value) + tomorrow_value
575 if value > max_value {
576 max_value = value
577 max_index = index
578 }
579 }
580 }
581 }
582 return max_index
583 }
584
585 func Commas(n int32) (s string) {
586 if n < 0 {
587 panic(n)
588 }
589 r := n % 1000
590 n /= 1000
591 for n > 0 {
592 s = fmt.Sprintf(",%03d", r) + s
593 r = n % 1000
594 n /= 1000
595 }
596 s = fmt.Sprint(r) + s
597 return
598 }
599
600 func FighterAndShieldCost(data planet_data, dims []int, table []State, best PhysicalIndex) {
601 if *drones == 0 && *batteries == 0 {
602 return
603 }
604 fmt.Println()
605 if *drones > 0 {
606 final_state := FinalState(dims)
607 final_state[BuyFighters] = 0
608 alt_best := FindBestState(data, dims, table, final_state)
609 cost := table[alt_best].value - table[best].value
610 fmt.Println("\rDrones were", float64(cost)/float64(*drones), "each")
611 }
612 if *batteries > 0 {
613 final_state := FinalState(dims)
614 final_state[BuyShields] = 0
615 alt_best := FindBestState(data, dims, table, final_state)
616 cost := table[alt_best].value - table[best].value
617 fmt.Println("\rBatteries were", float64(cost)/float64(*batteries), "each")
618 }
619 }
620
621 func EndEdensCost(data planet_data, dims []int, table []State, best PhysicalIndex) {
622 if *end_edens == 0 {
623 return
624 }
625 fmt.Println()
626 final_state := FinalState(dims)
627 for extra_edens := 1; extra_edens <= *end_edens; extra_edens++ {
628 final_state[Edens] = *end_edens - extra_edens
629 alt_best := FindBestState(data, dims, table, final_state)
630 extra_funds := table[alt_best].value - table[best].value
631 fmt.Println("\rUse", extra_edens, "extra edens, make an extra",
632 Commas(extra_funds), "(",
633 Commas(extra_funds/int32(extra_edens)), "per eden)")
634 }
635 }
636
637 func VisitCost(data planet_data, dims []int, table []State, best PhysicalIndex) {
638 if dims[Visit] == 1 {
639 return
640 }
641 fmt.Println()
642 final_state := FinalState(dims)
643 for i := uint(0); i < uint(len(visit())); i++ {
644 all_bits := dims[Visit] - 1
645 final_state[Visit] = all_bits & ^(1 << i)
646 alt_best := FindBestState(data, dims, table, final_state)
647 cost := table[alt_best].value - table[best].value
648 fmt.Printf("\r%11v Cost to visit %v\n", Commas(cost), visit()[i])
649 }
650 }
651
652 func EndLocationCost(data planet_data, dims []int, table []State, best PhysicalIndex) {
653 if len(end()) == 0 {
654 return
655 }
656 fmt.Println()
657 final_state := FinalState(dims)
658 save_end_string := *end_string
659 *end_string = ""
660 end_cache = nil
661 alt_best := FindBestState(data, dims, table, final_state)
662 cost := table[alt_best].value - table[best].value
663 fmt.Printf("\r%11v Cost of --end %v\n", Commas(cost), save_end_string)
664 *end_string = save_end_string
665 }
666
667 func DescribePath(data planet_data, dims []int, table []State, start PhysicalIndex) (description []string) {
668 for index := start; table[index].from > FROM_ROOT; index = table[index].from {
669 if table[index].from == FROM_UNINITIALIZED {
670 panic(index)
671 }
672 var line string
673 addr := DecodeIndex(dims, index)
674 prev := DecodeIndex(dims, table[index].from)
675 if addr[Fuel] != prev[Fuel] {
676 from := data.i2p[prev[Location]]
677 to := data.i2p[addr[Location]]
678 line += fmt.Sprintf("Jump from %v to %v (%v hyper jump units)", from, to, prev[Fuel]-addr[Fuel])
679 }
680 if addr[Edens] == prev[Edens]-1 {
681 from := data.i2p[prev[Location]]
682 to := data.i2p[addr[Location]]
683 line += fmt.Sprintf("Eden warp from %v to %v", from, to)
684 }
685 if addr[Hold] != prev[Hold] {
686 if addr[Hold] == 0 {
687 quantity := *hold - (prev[UnusedCargo] + prev[Edens] + prev[Cloaks])
688 line += fmt.Sprintf("Sell %v %v", quantity, data.i2c[prev[Hold]])
689 } else if prev[Hold] == 0 {
690 quantity := *hold - (addr[UnusedCargo] + addr[Edens] + addr[Cloaks])
691 line += fmt.Sprintf("Buy %v %v", quantity, data.i2c[addr[Hold]])
692 } else {
693 panic("Switched cargo?")
694 }
695
696 }
697 if addr[Cloaks] == 1 && prev[Cloaks] == 0 {
698 // TODO: Dump cloaks, convert from cargo?
699 line += "Buy a Cloak"
700 }
701 if addr[Edens] > prev[Edens] {
702 line += fmt.Sprint("Buy ", addr[Edens]-prev[Edens], " Eden Warp Units")
703 }
704 if addr[BuyShields] == 1 && prev[BuyShields] == 0 {
705 line += fmt.Sprint("Buy ", *batteries, " Shield Batterys")
706 }
707 if addr[BuyFighters] == 1 && prev[BuyFighters] == 0 {
708 line += fmt.Sprint("Buy ", *drones, " Fighter Drones")
709 }
710 if addr[Visit] != prev[Visit] {
711 // TODO: verify that the bit chat changed is addr[Location]
712 line += fmt.Sprint("Visit ", data.i2p[addr[Location]])
713 }
714 if line == "" && addr[Hold] == prev[Hold] && addr[Traded] != prev[Traded] {
715 // The Traded dimension is for housekeeping. It doesn't directly
716 // correspond to in-game actions, so don't report transitions.
717 continue
718 }
719 if line == "" {
720 line = fmt.Sprint(prev, " -> ", addr)
721 }
722 description = append(description, fmt.Sprintf("%13v ", Commas(table[index].value))+line)
723 }
724 return
725 }
726
727 // (Example of a use case for generics in Go)
728 func IndexPlanets(m *map[string]Planet, start_at int) (map[string]int, []string) {
729 e2i := make(map[string]int, len(*m)+start_at)
730 i2e := make([]string, len(*m)+start_at)
731 i := start_at
732 for e := range *m {
733 e2i[e] = i
734 i2e[i] = e
735 i++
736 }
737 return e2i, i2e
738 }
739 func IndexCommodities(m *map[string]Commodity, start_at int) (map[string]int, []string) {
740 e2i := make(map[string]int, len(*m)+start_at)
741 i2e := make([]string, len(*m)+start_at)
742 i := start_at
743 for e := range *m {
744 e2i[e] = i
745 i2e[i] = e
746 i++
747 }
748 return e2i, i2e
749 }
750
751 func main() {
752 flag.Parse()
753 if *start == "" || *funds == 0 {
754 print("--start and --funds are required. --help for more\n")
755 return
756 }
757 if *cpuprofile != "" {
758 f, err := os.Create(*cpuprofile)
759 if err != nil {
760 panic(err)
761 }
762 pprof.StartCPUProfile(f)
763 defer pprof.StopCPUProfile()
764 }
765 data := ReadData()
766 if *drone_price > 0 {
767 temp := data.Commodities["Fighter Drones"]
768 temp.BasePrice = *drone_price
769 data.Commodities["Fighter Drones"] = temp
770 }
771 if *battery_price > 0 {
772 temp := data.Commodities["Shield Batterys"]
773 temp.BasePrice = *battery_price
774 data.Commodities["Shield Batterys"] = temp
775 }
776 data.p2i, data.i2p = IndexPlanets(&data.Planets, 0)
777 data.c2i, data.i2c = IndexCommodities(&data.Commodities, 1)
778 dims := DimensionSizes(data)
779 table := CreateStateTable(data, dims)
780 final_state := FinalState(dims)
781 best := FindBestState(data, dims, table, final_state)
782 print("\n")
783 if best == -1 {
784 print("Cannot acheive success criteria\n")
785 return
786 }
787 description := DescribePath(data, dims, table, best)
788 for i := len(description) - 1; i >= 0; i-- {
789 fmt.Println(description[i])
790 }
791
792 if *extra_stats {
793 FighterAndShieldCost(data, dims, table, best)
794 EndEdensCost(data, dims, table, best)
795 VisitCost(data, dims, table, best)
796 EndLocationCost(data, dims, table, best)
797 }
798 }