]> git.scottworley.com Git - planeteer/blame - planeteer.go
Remove 'or any later version' license choice
[planeteer] / planeteer.go
CommitLineData
d07f3caa
SW
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
3cd35cb0 6 * published by the Free Software Foundation, version 3.
d07f3caa
SW
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Affero General Public License for more details.
12 *
13 * You should have received a copy of the GNU Affero General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17package main
18
19import "flag"
c45c1bca 20import "fmt"
69d36952 21import "encoding/json"
d07f3caa 22import "os"
42f6427c 23import "runtime/pprof"
c45c1bca
SW
24import "strings"
25
330093c1
SW
26var funds = flag.Int("funds", 0,
27 "Starting funds")
28
c45c1bca
SW
29var start = flag.String("start", "",
30 "The planet to start at")
d07f3caa 31
e346cb37 32var flight_plan_string = flag.String("flight_plan", "",
63b4dbbc 33 "Your hyper-holes for the day, comma-separated.")
544108c4 34
1c1ede68 35var end_string = flag.String("end", "",
e9ff66cf 36 "A comma-separated list of acceptable ending planets.")
c45c1bca
SW
37
38var planet_data_file = flag.String("planet_data_file", "planet-data",
d07f3caa
SW
39 "The file to read planet data from")
40
63b4dbbc 41var fuel = flag.Int("fuel", 16, "Hyper Jump power left")
e9ff66cf
SW
42
43var hold = flag.Int("hold", 300, "Size of your cargo hold")
c45c1bca 44
a06dc4cb
SW
45var start_hold = flag.String("start_hold", "", "Start with a hold full of cargo")
46
c45c1bca
SW
47var start_edens = flag.Int("start_edens", 0,
48 "How many Eden Warp Units are you starting with?")
49
50var end_edens = flag.Int("end_edens", 0,
51 "How many Eden Warp Units would you like to keep (not use)?")
52
53var cloak = flag.Bool("cloak", false,
54 "Make sure to end with a Device of Cloaking")
55
e9ff66cf 56var drones = flag.Int("drones", 0, "Buy this many Fighter Drones")
c45c1bca 57
e9ff66cf 58var batteries = flag.Int("batteries", 0, "Buy this many Shield Batterys")
c45c1bca 59
76db1b3c
SW
60var drone_price = flag.Int("drone_price", 0, "Today's Fighter Drone price")
61
62var battery_price = flag.Int("battery_price", 0, "Today's Shield Battery price")
63
c45c1bca
SW
64var visit_string = flag.String("visit", "",
65 "A comma-separated list of planets to make sure to visit")
66
60025e5d
SW
67var tomorrow_weight = flag.Float64("tomorrow_weight", 1.0,
68 "Weight for the expected value of tomorrow's trading. 0.0 - 1.0")
69
bc4a3744
SW
70var extra_stats = flag.Bool("extra_stats", true,
71 "Show additional information of possible interest")
72
42f6427c
SW
73var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
74
42f6427c 75var visit_cache []string
1539cc25 76
c45c1bca 77func visit() []string {
42f6427c
SW
78 if visit_cache == nil {
79 if *visit_string == "" {
80 return nil
81 }
82 visit_cache = strings.Split(*visit_string, ",")
e346cb37 83 }
42f6427c 84 return visit_cache
c45c1bca
SW
85}
86
42f6427c 87var flight_plan_cache []string
1539cc25 88
e346cb37 89func flight_plan() []string {
42f6427c
SW
90 if flight_plan_cache == nil {
91 if *flight_plan_string == "" {
92 return nil
93 }
94 flight_plan_cache = strings.Split(*flight_plan_string, ",")
e346cb37 95 }
42f6427c 96 return flight_plan_cache
e346cb37
SW
97}
98
42f6427c 99var end_cache map[string]bool
1539cc25 100
1c1ede68 101func end() map[string]bool {
42f6427c
SW
102 if end_cache == nil {
103 if *end_string == "" {
104 return nil
105 }
106 m := make(map[string]bool)
107 for _, p := range strings.Split(*end_string, ",") {
108 m[p] = true
109 }
110 end_cache = m
1c1ede68 111 }
42f6427c 112 return end_cache
1c1ede68
SW
113}
114
9b3b3d9a 115type Commodity struct {
9b3b3d9a
SW
116 BasePrice int
117 CanSell bool
118 Limit int
119}
12bc2cd7 120type Planet struct {
60025e5d
SW
121 BeaconOn bool
122 Private bool
123 TomorrowValue int
12bc2cd7
SW
124 /* Use relative prices rather than absolute prices because you
125 can get relative prices without traveling to each planet. */
0e94bdac 126 RelativePrices map[string]int
12bc2cd7 127}
d07f3caa 128type planet_data struct {
0e94bdac
SW
129 Commodities map[string]Commodity
130 Planets map[string]Planet
e7e4bc13
SW
131 p2i, c2i map[string]int // Generated; not read from file
132 i2p, i2c []string // Generated; not read from file
d07f3caa
SW
133}
134
091c6280
SW
135func json_slurp(filename string, receptacle interface{}) error {
136 f, err := os.Open(filename)
d07f3caa 137 if err != nil {
091c6280 138 return err
d07f3caa
SW
139 }
140 defer f.Close()
091c6280
SW
141 err = json.NewDecoder(f).Decode(receptacle)
142 if err != nil {
143 return err
144 }
145 return nil
146}
147
a18532c2
SW
148func ReadData() planet_data {
149 var data planet_data
091c6280 150 err := json_slurp(*planet_data_file, &data)
d07f3caa
SW
151 if err != nil {
152 panic(err)
153 }
a18532c2 154 return data
d07f3caa
SW
155}
156
c45c1bca
SW
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.
e7e4bc13
SW
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
a16bf050
SW
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.
e346cb37
SW
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.
a16bf050
SW
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.
e346cb37
SW
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.)
a49e368f 196 *
c45c1bca
SW
197 */
198
199// The official list of dimensions:
200const (
0372f045 201 // Name Num Size Description
1539cc25
SW
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
c45c1bca
SW
212
213 NumDimensions
214)
215
216func bint(b bool) int {
0e94bdac
SW
217 if b {
218 return 1
219 }
c45c1bca
SW
220 return 0
221}
222
a29aebec 223func DimensionSizes(data planet_data) LogicalIndex {
c45c1bca 224 eden_capacity := data.Commodities["Eden Warp Units"].Limit
330093c1
SW
225 if *start_edens > eden_capacity {
226 eden_capacity = *start_edens
227 }
c45c1bca 228 cloak_capacity := bint(*cloak)
a29aebec 229 dims := make(LogicalIndex, NumDimensions)
64d87250
SW
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)
c67c206a 235 dims[Hold] = len(data.Commodities) + 1
0372f045 236 dims[Traded] = 2
76db1b3c
SW
237 dims[BuyFighters] = bint(*drones > 0) + 1
238 dims[BuyShields] = bint(*batteries > 0) + 1
64d87250 239 dims[Visit] = 1 << uint(len(visit()))
2f4ed5ca
SW
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 }
c45c1bca
SW
247 return dims
248}
249
a29aebec
SW
250type Value int32
251type PhysicalIndex int32
252type LogicalIndex []int
253
254func StateTableSize(dims LogicalIndex) int {
e346cb37 255 product := 1
c45c1bca 256 for _, size := range dims {
e346cb37 257 product *= size
c45c1bca 258 }
e346cb37 259 return product
c45c1bca
SW
260}
261
262type State struct {
fc93fd36 263 value Value
db81510d 264 from PhysicalIndex
c45c1bca
SW
265}
266
1539cc25 267const (
fb8eccbf
SW
268 FROM_ROOT = -2147483647 + iota
269 FROM_UNINITIALIZED
270 VALUE_UNINITIALIZED
271 VALUE_BEING_EVALUATED
272 VALUE_RUBISH
1539cc25 273)
0372f045 274
a29aebec 275func EncodeIndex(dims, addr LogicalIndex) PhysicalIndex {
688733e1 276 index := addr[0]
e346cb37
SW
277 if addr[0] > dims[0] {
278 panic(0)
279 }
330093c1 280 for i := 1; i < NumDimensions; i++ {
688733e1 281 if addr[i] < 0 || addr[i] >= dims[i] {
e346cb37
SW
282 panic(i)
283 }
688733e1 284 index = index*dims[i] + addr[i]
c45c1bca 285 }
db81510d 286 return PhysicalIndex(index)
c45c1bca
SW
287}
288
a29aebec 289func DecodeIndex(dims LogicalIndex, index PhysicalIndex) LogicalIndex {
db81510d 290 scratch := int(index)
a29aebec 291 addr := make(LogicalIndex, NumDimensions)
330093c1 292 for i := NumDimensions - 1; i > 0; i-- {
db81510d
SW
293 addr[i] = scratch % dims[i]
294 scratch /= dims[i]
c45c1bca 295 }
db81510d 296 addr[0] = scratch
c45c1bca
SW
297 return addr
298}
299
dd6c757d
SW
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
a29aebec 316func CreateStateTable(data planet_data, dims LogicalIndex) []State {
330093c1 317 table := make([]State, StateTableSize(dims))
0372f045 318 for i := range table {
fb8eccbf
SW
319 table[i].value = VALUE_UNINITIALIZED
320 table[i].from = FROM_UNINITIALIZED
0372f045 321 }
330093c1 322
a29aebec 323 addr := make(LogicalIndex, NumDimensions)
330093c1
SW
324 addr[Fuel] = *fuel
325 addr[Edens] = *start_edens
dd6c757d 326 addr[Location] = PlanetIndex(data, *start)
a06dc4cb 327 if *start_hold != "" {
a49e368f 328 addr[Hold] = CommodityIndex(data, *start_hold)
a06dc4cb 329 }
fb8eccbf 330 start_index := EncodeIndex(dims, addr)
fc93fd36 331 table[start_index].value = Value(*funds)
fb8eccbf 332 table[start_index].from = FROM_ROOT
330093c1
SW
333
334 return table
e346cb37
SW
335}
336
0372f045
SW
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. */
330093c1 339
a29aebec 340func Consider(data planet_data, dims LogicalIndex, table []State, there LogicalIndex, value_difference int, best_value *Value, best_source LogicalIndex) {
0372f045 341 there_value := CellValue(data, dims, table, there)
fc93fd36 342 if value_difference < 0 && Value(-value_difference) > there_value {
0372f045
SW
343 /* Can't afford this transition */
344 return
345 }
fc93fd36 346 possible_value := there_value + Value(value_difference)
0372f045
SW
347 if possible_value > *best_value {
348 *best_value = possible_value
349 copy(best_source, there)
330093c1
SW
350 }
351}
352
0372f045 353var cell_filled_count int
1539cc25 354
a29aebec 355func CellValue(data planet_data, dims LogicalIndex, table []State, addr LogicalIndex) Value {
e346cb37 356 my_index := EncodeIndex(dims, addr)
fb8eccbf 357 if table[my_index].value == VALUE_BEING_EVALUATED {
0372f045
SW
358 panic("Circular dependency")
359 }
fb8eccbf 360 if table[my_index].value != VALUE_UNINITIALIZED {
0372f045
SW
361 return table[my_index].value
362 }
fb8eccbf 363 table[my_index].value = VALUE_BEING_EVALUATED
0372f045 364
fc93fd36 365 best_value := Value(VALUE_RUBISH)
a29aebec
SW
366 best_source := make(LogicalIndex, NumDimensions)
367 other := make(LogicalIndex, NumDimensions)
e346cb37 368 copy(other, addr)
0372f045 369 planet := data.i2p[addr[Location]]
e346cb37 370
0372f045
SW
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 */
58c3880d 376 if data.Planets[data.i2p[addr[Location]]].BeaconOn && addr[Fuel]+2 < dims[Fuel] {
0372f045
SW
377 other[Fuel] = addr[Fuel] + 2
378 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 2)
dd6c757d 379 if hole_index >= len(flight_plan()) || addr[Location] != PlanetIndex(data, flight_plan()[hole_index]) {
0372f045 380 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
58c3880d 381 Consider(data, dims, table, other, 0, &best_value, best_source)
0372f045 382 }
beb45aca 383 }
0372f045
SW
384 other[Location] = addr[Location]
385 other[Fuel] = addr[Fuel]
e346cb37 386 }
e346cb37 387
0372f045
SW
388 /* Travel here via a 1-fuel unit jump (a hyper hole) */
389 if addr[Fuel]+1 < dims[Fuel] {
390 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 1)
dd6c757d 391 if hole_index < len(flight_plan()) && addr[Location] == PlanetIndex(data, flight_plan()[hole_index]) {
0372f045
SW
392 other[Fuel] = addr[Fuel] + 1
393 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
394 Consider(data, dims, table, other, 0, &best_value, best_source)
395 }
396 other[Location] = addr[Location]
397 other[Fuel] = addr[Fuel]
7b5d9d13 398 }
e346cb37 399 }
e346cb37 400
0372f045 401 /* Travel here via Eden Warp Unit */
35e3c424 402 if addr[Edens]+1 < dims[Edens] && (addr[Hold] == 0 || addr[UnusedCargo] > 0) {
0372f045
SW
403 _, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
404 if !available {
405 other[Edens] = addr[Edens] + 1
406 if other[Hold] != 0 {
407 other[UnusedCargo] = addr[UnusedCargo] - 1
408 }
409 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
410 Consider(data, dims, table, other, 0, &best_value, best_source)
411 }
412 other[Location] = addr[Location]
413 other[UnusedCargo] = addr[UnusedCargo]
414 other[Edens] = addr[Edens]
0c27c344 415 }
330093c1 416 }
0372f045 417 other[Traded] = addr[Traded]
330093c1 418 }
330093c1 419
0372f045
SW
420 /* Trade */
421 if addr[Traded] == 1 {
422 other[Traded] = 0
330093c1 423
0372f045
SW
424 /* Consider not trading */
425 Consider(data, dims, table, other, 0, &best_value, best_source)
330093c1 426
0372f045 427 if !data.Planets[data.i2p[addr[Location]]].Private {
330093c1 428
0372f045
SW
429 /* Sell */
430 if addr[Hold] == 0 && addr[UnusedCargo] == 0 {
431 for other[Hold] = 0; other[Hold] < dims[Hold]; other[Hold]++ {
432 commodity := data.i2c[other[Hold]]
433 if !data.Commodities[commodity].CanSell {
434 continue
435 }
436 relative_price, available := data.Planets[planet].RelativePrices[commodity]
437 if !available {
438 // TODO: Dump cargo
439 continue
440 }
441 base_price := data.Commodities[commodity].BasePrice
442 absolute_price := float64(base_price) * float64(relative_price) / 100.0
443 sell_price := int(absolute_price * 0.9)
444
445 for other[UnusedCargo] = 0; other[UnusedCargo] < dims[UnusedCargo]; other[UnusedCargo]++ {
446 quantity := *hold - (other[UnusedCargo] + other[Cloaks] + other[Edens])
447 sale_value := quantity * sell_price
448 Consider(data, dims, table, other, sale_value, &best_value, best_source)
449 }
450 }
451 other[UnusedCargo] = addr[UnusedCargo]
452 other[Hold] = addr[Hold]
453 }
330093c1 454
0372f045
SW
455 /* Buy */
456 other[Traded] = addr[Traded] /* Buy after selling */
457 if addr[Hold] != 0 {
458 commodity := data.i2c[addr[Hold]]
459 if data.Commodities[commodity].CanSell {
460 relative_price, available := data.Planets[planet].RelativePrices[commodity]
461 if available {
462 base_price := data.Commodities[commodity].BasePrice
463 absolute_price := int(float64(base_price) * float64(relative_price) / 100.0)
464 quantity := *hold - (addr[UnusedCargo] + addr[Cloaks] + addr[Edens])
465 total_price := quantity * absolute_price
466 other[Hold] = 0
467 other[UnusedCargo] = 0
468 Consider(data, dims, table, other, -total_price, &best_value, best_source)
469 other[UnusedCargo] = addr[UnusedCargo]
470 other[Hold] = addr[Hold]
471 }
472 }
473 }
474 }
6918cad2 475 other[Traded] = addr[Traded]
0372f045 476 }
d16f3322 477
544108c4 478 /* Buy a Device of Cloaking */
ada59973
SW
479 if addr[Cloaks] == 1 && addr[UnusedCargo] < dims[UnusedCargo]-1 {
480 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Device Of Cloakings"]
481 if available {
482 absolute_price := int(float64(data.Commodities["Device Of Cloakings"].BasePrice) * float64(relative_price) / 100.0)
483 other[Cloaks] = 0
f800f732
SW
484 if other[Hold] != 0 {
485 other[UnusedCargo] = addr[UnusedCargo] + 1
486 }
0372f045 487 Consider(data, dims, table, other, -absolute_price, &best_value, best_source)
ada59973
SW
488 other[UnusedCargo] = addr[UnusedCargo]
489 other[Cloaks] = addr[Cloaks]
490 }
491 }
76db1b3c 492
544108c4 493 /* Buy Fighter Drones */
76db1b3c
SW
494 if addr[BuyFighters] == 1 {
495 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Fighter Drones"]
496 if available {
497 absolute_price := int(float64(data.Commodities["Fighter Drones"].BasePrice) * float64(relative_price) / 100.0)
498 other[BuyFighters] = 0
1539cc25 499 Consider(data, dims, table, other, -absolute_price**drones, &best_value, best_source)
76db1b3c
SW
500 other[BuyFighters] = addr[BuyFighters]
501 }
502 }
503
544108c4 504 /* Buy Shield Batteries */
76db1b3c
SW
505 if addr[BuyShields] == 1 {
506 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Shield Batterys"]
507 if available {
508 absolute_price := int(float64(data.Commodities["Shield Batterys"].BasePrice) * float64(relative_price) / 100.0)
509 other[BuyShields] = 0
1539cc25 510 Consider(data, dims, table, other, -absolute_price**batteries, &best_value, best_source)
76db1b3c
SW
511 other[BuyShields] = addr[BuyShields]
512 }
513 }
514
544108c4 515 /* Visit this planet */
b7a6e28b 516 for i := uint(0); i < uint(len(visit())); i++ {
1539cc25 517 if addr[Visit]&(1<<i) != 0 && visit()[i] == data.i2p[addr[Location]] {
4d7362df 518 other[Visit] = addr[Visit] & ^(1 << i)
0372f045 519 Consider(data, dims, table, other, 0, &best_value, best_source)
4d7362df
SW
520 }
521 }
522 other[Visit] = addr[Visit]
76db1b3c 523
d16f3322
SW
524 /* Buy Eden warp units */
525 eden_limit := data.Commodities["Eden Warp Units"].Limit
526 if addr[Edens] > 0 && addr[Edens] <= eden_limit {
527 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
528 if available {
529 absolute_price := int(float64(data.Commodities["Eden Warp Units"].BasePrice) * float64(relative_price) / 100.0)
530 for quantity := addr[Edens]; quantity > 0; quantity-- {
531 other[Edens] = addr[Edens] - quantity
532 if addr[Hold] != 0 {
533 other[UnusedCargo] = addr[UnusedCargo] + quantity
534 }
535 if other[UnusedCargo] < dims[UnusedCargo] {
1539cc25 536 Consider(data, dims, table, other, -absolute_price*quantity, &best_value, best_source)
d16f3322
SW
537 }
538 }
539 other[Edens] = addr[Edens]
540 other[UnusedCargo] = addr[UnusedCargo]
541 }
542 }
d16f3322 543
688733e1
SW
544 // Check that we didn't lose track of any temporary modifications to other.
545 for i := 0; i < NumDimensions; i++ {
546 if addr[i] != other[i] {
547 panic(i)
548 }
549 }
550
551 // Sanity check: This cell was in state BEING_EVALUATED
552 // the whole time that it was being evaluated.
fb8eccbf 553 if table[my_index].value != VALUE_BEING_EVALUATED {
0372f045 554 panic(my_index)
e7e4bc13 555 }
688733e1
SW
556
557 // Record our findings
0372f045
SW
558 table[my_index].value = best_value
559 table[my_index].from = EncodeIndex(dims, best_source)
330093c1 560
688733e1 561 // UI: Progress bar
1539cc25 562 cell_filled_count++
c5ac83ce 563 if cell_filled_count&0xfff == 0 {
0372f045 564 print(fmt.Sprintf("\r%3.1f%%", 100*float64(cell_filled_count)/float64(StateTableSize(dims))))
fcdc120b 565 }
e7e4bc13 566
0372f045 567 return table[my_index].value
e7e4bc13
SW
568}
569
a29aebec
SW
570func FinalState(dims LogicalIndex) LogicalIndex {
571 addr := make(LogicalIndex, NumDimensions)
ad4de13f
SW
572 addr[Edens] = *end_edens
573 addr[Cloaks] = dims[Cloaks] - 1
76db1b3c
SW
574 addr[BuyFighters] = dims[BuyFighters] - 1
575 addr[BuyShields] = dims[BuyShields] - 1
ad4de13f 576 addr[Visit] = dims[Visit] - 1
0372f045 577 addr[Traded] = 1
688733e1
SW
578 addr[Hold] = 0
579 addr[UnusedCargo] = 0
7881bdfb
SW
580 // Fuel and Location are determined by FindBestState
581 return addr
582}
583
a29aebec 584func FindBestState(data planet_data, dims LogicalIndex, table []State, addr LogicalIndex) PhysicalIndex {
db81510d 585 max_index := PhysicalIndex(-1)
60025e5d 586 max_value := 0.0
688733e1
SW
587 max_fuel := 1
588 if *fuel == 0 {
589 max_fuel = 0
590 }
591 for addr[Fuel] = 0; addr[Fuel] <= max_fuel; addr[Fuel]++ {
ddef04ab 592 for addr[Location] = 0; addr[Location] < dims[Location]; addr[Location]++ {
60025e5d
SW
593 planet := data.i2p[addr[Location]]
594 if len(end()) == 0 || end()[planet] {
ddef04ab 595 index := EncodeIndex(dims, addr)
60025e5d
SW
596 today_value := CellValue(data, dims, table, addr)
597 tomorrow_value := *tomorrow_weight * float64(*hold+data.Planets[planet].TomorrowValue)
598 value := float64(today_value) + tomorrow_value
0372f045
SW
599 if value > max_value {
600 max_value = value
ddef04ab
SW
601 max_index = index
602 }
809e65f4 603 }
ad4de13f
SW
604 }
605 }
606 return max_index
607}
608
a18532c2
SW
609func Commas(n Value) string {
610 var s string
b7a6e28b
SW
611 if n < 0 {
612 panic(n)
613 }
9eafb7a4
SW
614 r := n % 1000
615 n /= 1000
616 for n > 0 {
617 s = fmt.Sprintf(",%03d", r) + s
618 r = n % 1000
619 n /= 1000
620 }
621 s = fmt.Sprint(r) + s
a18532c2 622 return s
9eafb7a4
SW
623}
624
a29aebec 625func FighterAndShieldCost(data planet_data, dims LogicalIndex, table []State, best PhysicalIndex) {
a5a4d824
SW
626 if *drones == 0 && *batteries == 0 {
627 return
628 }
629 fmt.Println()
630 if *drones > 0 {
631 final_state := FinalState(dims)
632 final_state[BuyFighters] = 0
633 alt_best := FindBestState(data, dims, table, final_state)
634 cost := table[alt_best].value - table[best].value
785c799c 635 fmt.Printf("\rDrones were %.2f each\n", float64(cost)/float64(*drones))
a5a4d824
SW
636 }
637 if *batteries > 0 {
638 final_state := FinalState(dims)
639 final_state[BuyShields] = 0
640 alt_best := FindBestState(data, dims, table, final_state)
641 cost := table[alt_best].value - table[best].value
785c799c 642 fmt.Printf("\rBatteries were %.2f each\n", float64(cost)/float64(*batteries))
a5a4d824
SW
643 }
644}
645
a29aebec 646func EndEdensCost(data planet_data, dims LogicalIndex, table []State, best PhysicalIndex) {
a5a4d824
SW
647 if *end_edens == 0 {
648 return
649 }
650 fmt.Println()
651 final_state := FinalState(dims)
652 for extra_edens := 1; extra_edens <= *end_edens; extra_edens++ {
653 final_state[Edens] = *end_edens - extra_edens
654 alt_best := FindBestState(data, dims, table, final_state)
655 extra_funds := table[alt_best].value - table[best].value
656 fmt.Println("\rUse", extra_edens, "extra edens, make an extra",
657 Commas(extra_funds), "(",
fc93fd36 658 Commas(extra_funds/Value(extra_edens)), "per eden)")
a5a4d824
SW
659 }
660}
661
a29aebec 662func VisitCost(data planet_data, dims LogicalIndex, table []State, best PhysicalIndex) {
a5a4d824
SW
663 if dims[Visit] == 1 {
664 return
665 }
666 fmt.Println()
667 final_state := FinalState(dims)
668 for i := uint(0); i < uint(len(visit())); i++ {
669 all_bits := dims[Visit] - 1
670 final_state[Visit] = all_bits & ^(1 << i)
671 alt_best := FindBestState(data, dims, table, final_state)
672 cost := table[alt_best].value - table[best].value
673 fmt.Printf("\r%11v Cost to visit %v\n", Commas(cost), visit()[i])
674 }
675}
676
a29aebec 677func EndLocationCost(data planet_data, dims LogicalIndex, table []State, best PhysicalIndex) {
a5a4d824
SW
678 if len(end()) == 0 {
679 return
680 }
681 fmt.Println()
682 final_state := FinalState(dims)
683 save_end_string := *end_string
684 *end_string = ""
685 end_cache = nil
686 alt_best := FindBestState(data, dims, table, final_state)
687 cost := table[alt_best].value - table[best].value
688 fmt.Printf("\r%11v Cost of --end %v\n", Commas(cost), save_end_string)
689 *end_string = save_end_string
690}
691
a18532c2
SW
692func DescribePath(data planet_data, dims LogicalIndex, table []State, start PhysicalIndex) []string {
693 var description []string
fb8eccbf
SW
694 for index := start; table[index].from > FROM_ROOT; index = table[index].from {
695 if table[index].from == FROM_UNINITIALIZED {
696 panic(index)
697 }
e4a1b48f 698 var line string
2f4a9ae8
SW
699 addr := DecodeIndex(dims, index)
700 prev := DecodeIndex(dims, table[index].from)
e4a1b48f 701 if addr[Fuel] != prev[Fuel] {
2f4a9ae8
SW
702 from := data.i2p[prev[Location]]
703 to := data.i2p[addr[Location]]
63b4dbbc 704 line += fmt.Sprintf("Jump from %v to %v (%v hyper jump units)", from, to, prev[Fuel]-addr[Fuel])
e4a1b48f 705 }
1539cc25 706 if addr[Edens] == prev[Edens]-1 {
e4a1b48f
SW
707 from := data.i2p[prev[Location]]
708 to := data.i2p[addr[Location]]
709 line += fmt.Sprintf("Eden warp from %v to %v", from, to)
2f4a9ae8
SW
710 }
711 if addr[Hold] != prev[Hold] {
712 if addr[Hold] == 0 {
713 quantity := *hold - (prev[UnusedCargo] + prev[Edens] + prev[Cloaks])
e4a1b48f 714 line += fmt.Sprintf("Sell %v %v", quantity, data.i2c[prev[Hold]])
2f4a9ae8
SW
715 } else if prev[Hold] == 0 {
716 quantity := *hold - (addr[UnusedCargo] + addr[Edens] + addr[Cloaks])
e4a1b48f 717 line += fmt.Sprintf("Buy %v %v", quantity, data.i2c[addr[Hold]])
2f4a9ae8
SW
718 } else {
719 panic("Switched cargo?")
720 }
721
722 }
f800f732
SW
723 if addr[Cloaks] == 1 && prev[Cloaks] == 0 {
724 // TODO: Dump cloaks, convert from cargo?
e4a1b48f
SW
725 line += "Buy a Cloak"
726 }
d16f3322 727 if addr[Edens] > prev[Edens] {
1539cc25 728 line += fmt.Sprint("Buy ", addr[Edens]-prev[Edens], " Eden Warp Units")
e4a1b48f 729 }
76db1b3c
SW
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 }
4d7362df
SW
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 }
0372f045
SW
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 }
e4a1b48f
SW
745 if line == "" {
746 line = fmt.Sprint(prev, " -> ", addr)
f800f732 747 }
1539cc25 748 description = append(description, fmt.Sprintf("%13v ", Commas(table[index].value))+line)
2f4a9ae8 749 }
a18532c2 750 return description
2f4a9ae8
SW
751}
752
c45c1bca 753// (Example of a use case for generics in Go)
e7e4bc13 754func IndexPlanets(m *map[string]Planet, start_at int) (map[string]int, []string) {
a1f10151
SW
755 e2i := make(map[string]int, len(*m)+start_at)
756 i2e := make([]string, len(*m)+start_at)
e7e4bc13 757 i := start_at
c45c1bca 758 for e := range *m {
e7e4bc13
SW
759 e2i[e] = i
760 i2e[i] = e
c45c1bca
SW
761 i++
762 }
e7e4bc13 763 return e2i, i2e
c45c1bca 764}
e7e4bc13 765func IndexCommodities(m *map[string]Commodity, start_at int) (map[string]int, []string) {
a1f10151
SW
766 e2i := make(map[string]int, len(*m)+start_at)
767 i2e := make([]string, len(*m)+start_at)
e7e4bc13 768 i := start_at
c45c1bca 769 for e := range *m {
e7e4bc13
SW
770 e2i[e] = i
771 i2e[i] = e
c45c1bca
SW
772 i++
773 }
e7e4bc13 774 return e2i, i2e
c45c1bca
SW
775}
776
d07f3caa
SW
777func main() {
778 flag.Parse()
311b26d4
SW
779 if *start == "" || *funds == 0 {
780 print("--start and --funds are required. --help for more\n")
781 return
782 }
42f6427c
SW
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 }
d07f3caa 791 data := ReadData()
76db1b3c
SW
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 }
e7e4bc13
SW
802 data.p2i, data.i2p = IndexPlanets(&data.Planets, 0)
803 data.c2i, data.i2c = IndexCommodities(&data.Commodities, 1)
c45c1bca 804 dims := DimensionSizes(data)
0372f045 805 table := CreateStateTable(data, dims)
7881bdfb
SW
806 final_state := FinalState(dims)
807 best := FindBestState(data, dims, table, final_state)
0372f045 808 print("\n")
ada59973 809 if best == -1 {
7393f03a 810 print("Cannot achieve success criteria\n")
7881bdfb
SW
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
bc4a3744
SW
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 }
d07f3caa 824}