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