]> git.scottworley.com Git - planeteer/blame - planeteer.go
--tomorrow_weight feature, with data
[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
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"
c45c1bca 21import "fmt"
d07f3caa
SW
22import "json"
23import "os"
42f6427c 24import "runtime/pprof"
c45c1bca
SW
25import "strings"
26
330093c1
SW
27var funds = flag.Int("funds", 0,
28 "Starting funds")
29
c45c1bca
SW
30var start = flag.String("start", "",
31 "The planet to start at")
d07f3caa 32
e346cb37 33var flight_plan_string = flag.String("flight_plan", "",
63b4dbbc 34 "Your hyper-holes for the day, comma-separated.")
544108c4 35
1c1ede68 36var end_string = flag.String("end", "",
e9ff66cf 37 "A comma-separated list of acceptable ending planets.")
c45c1bca
SW
38
39var planet_data_file = flag.String("planet_data_file", "planet-data",
d07f3caa
SW
40 "The file to read planet data from")
41
63b4dbbc 42var fuel = flag.Int("fuel", 16, "Hyper Jump power left")
e9ff66cf
SW
43
44var hold = flag.Int("hold", 300, "Size of your cargo hold")
c45c1bca 45
a06dc4cb
SW
46var start_hold = flag.String("start_hold", "", "Start with a hold full of cargo")
47
c45c1bca
SW
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
e9ff66cf 57var drones = flag.Int("drones", 0, "Buy this many Fighter Drones")
c45c1bca 58
e9ff66cf 59var batteries = flag.Int("batteries", 0, "Buy this many Shield Batterys")
c45c1bca 60
76db1b3c
SW
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
c45c1bca
SW
65var visit_string = flag.String("visit", "",
66 "A comma-separated list of planets to make sure to visit")
67
60025e5d
SW
68var tomorrow_weight = flag.Float64("tomorrow_weight", 1.0,
69 "Weight for the expected value of tomorrow's trading. 0.0 - 1.0")
70
42f6427c
SW
71var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
72
42f6427c 73var visit_cache []string
1539cc25 74
c45c1bca 75func visit() []string {
42f6427c
SW
76 if visit_cache == nil {
77 if *visit_string == "" {
78 return nil
79 }
80 visit_cache = strings.Split(*visit_string, ",")
e346cb37 81 }
42f6427c 82 return visit_cache
c45c1bca
SW
83}
84
42f6427c 85var flight_plan_cache []string
1539cc25 86
e346cb37 87func flight_plan() []string {
42f6427c
SW
88 if flight_plan_cache == nil {
89 if *flight_plan_string == "" {
90 return nil
91 }
92 flight_plan_cache = strings.Split(*flight_plan_string, ",")
e346cb37 93 }
42f6427c 94 return flight_plan_cache
e346cb37
SW
95}
96
42f6427c 97var end_cache map[string]bool
1539cc25 98
1c1ede68 99func end() map[string]bool {
42f6427c
SW
100 if end_cache == nil {
101 if *end_string == "" {
102 return nil
103 }
104 m := make(map[string]bool)
105 for _, p := range strings.Split(*end_string, ",") {
106 m[p] = true
107 }
108 end_cache = m
1c1ede68 109 }
42f6427c 110 return end_cache
1c1ede68
SW
111}
112
9b3b3d9a 113type Commodity struct {
9b3b3d9a
SW
114 BasePrice int
115 CanSell bool
116 Limit int
117}
12bc2cd7 118type Planet struct {
60025e5d
SW
119 BeaconOn bool
120 Private bool
121 TomorrowValue int
12bc2cd7
SW
122 /* Use relative prices rather than absolute prices because you
123 can get relative prices without traveling to each planet. */
0e94bdac 124 RelativePrices map[string]int
12bc2cd7 125}
d07f3caa 126type planet_data struct {
0e94bdac
SW
127 Commodities map[string]Commodity
128 Planets map[string]Planet
e7e4bc13
SW
129 p2i, c2i map[string]int // Generated; not read from file
130 i2p, i2c []string // Generated; not read from file
d07f3caa
SW
131}
132
133func ReadData() (data planet_data) {
c45c1bca 134 f, err := os.Open(*planet_data_file)
d07f3caa
SW
135 if err != nil {
136 panic(err)
137 }
138 defer f.Close()
139 err = json.NewDecoder(f).Decode(&data)
140 if err != nil {
141 panic(err)
142 }
143 return
144}
145
c45c1bca
SW
146/* This program operates by filling in a state table representing the best
147 * possible trips you could make; the ones that makes you the most money.
148 * This is feasible because we don't look at all the possible trips.
149 * We define a list of things that are germane to this game and then only
150 * consider the best outcome in each possible game state.
151 *
152 * Each cell in the table represents a state in the game. In each cell,
153 * we track two things: 1. the most money you could possibly have while in
154 * that state and 2. one possible way to get into that state with that
155 * amount of money.
156 *
157 * A basic analysis can be done with a two-dimensional table: location and
158 * fuel. planeteer-1.0 used this two-dimensional table. This version
159 * adds features mostly by adding dimensions to this table.
160 *
161 * Note that the sizes of each dimension are data driven. Many dimensions
162 * collapse to one possible value (ie, disappear) if the corresponding
163 * feature is not enabled.
e7e4bc13
SW
164 *
165 * The order of the dimensions in the list of constants below determines
166 * their layout in RAM. The cargo-based 'dimensions' are not completely
167 * independent -- some combinations are illegal and not used. They are
168 * handled as three dimensions rather than one for simplicity. Placing
169 * these dimensions first causes the unused cells in the table to be
170 * grouped together in large blocks. This keeps them from polluting
0372f045
SW
171 * cache lines, and if they are large enough, allows the memory manager
172 * to swap out entire pages.
e346cb37
SW
173 *
174 * If the table gets too big to fit in RAM:
175 * * Combine the Edens, Cloaks, and UnusedCargo dimensions. Of the
176 * 24 combinations, only 15 are legal: a 38% savings.
177 * * Reduce the size of the Fuel dimension to 3. We only ever look
178 * backwards 2 units, so just rotate the logical values through
179 * the same 3 physical addresses. This is good for an 82% savings.
180 * * Reduce the size of the Edens dimension from 3 to 2, for the
181 * same reasons as Fuel above. 33% savings.
182 * * Buy more ram. (Just sayin'. It's cheaper than you think.)
183 *
c45c1bca
SW
184 */
185
186// The official list of dimensions:
187const (
0372f045 188 // Name Num Size Description
1539cc25
SW
189 Edens = iota // 1 3 # of Eden warp units (0 - 2 typically)
190 Cloaks // 2 1-2 # of Devices of Cloaking (0 or 1)
191 UnusedCargo // 3 4 # of unused cargo spaces (0 - 3 typically)
192 Fuel // 4 17 Hyper jump power left (0 - 16)
193 Location // 5 26 Location (which planet)
194 Hold // 6 15 Cargo bay contents (a *Commodity or nil)
195 Traded // 7 2 Traded yet?
196 BuyFighters // 8 1-2 Errand: Buy fighter drones
197 BuyShields // 9 1-2 Errand: Buy shield batteries
198 Visit // 10 1-2**N Visit: Stop by these N planets in the route
c45c1bca
SW
199
200 NumDimensions
201)
202
203func bint(b bool) int {
0e94bdac
SW
204 if b {
205 return 1
206 }
c45c1bca
SW
207 return 0
208}
209
210func DimensionSizes(data planet_data) []int {
211 eden_capacity := data.Commodities["Eden Warp Units"].Limit
330093c1
SW
212 if *start_edens > eden_capacity {
213 eden_capacity = *start_edens
214 }
c45c1bca 215 cloak_capacity := bint(*cloak)
64d87250
SW
216 dims := make([]int, NumDimensions)
217 dims[Edens] = eden_capacity + 1
218 dims[Cloaks] = cloak_capacity + 1
219 dims[UnusedCargo] = eden_capacity + cloak_capacity + 1
220 dims[Fuel] = *fuel + 1
221 dims[Location] = len(data.Planets)
c67c206a 222 dims[Hold] = len(data.Commodities) + 1
0372f045 223 dims[Traded] = 2
76db1b3c
SW
224 dims[BuyFighters] = bint(*drones > 0) + 1
225 dims[BuyShields] = bint(*batteries > 0) + 1
64d87250 226 dims[Visit] = 1 << uint(len(visit()))
2f4ed5ca
SW
227
228 // Remind myself to add a line above when adding new dimensions
229 for i, dim := range dims {
230 if dim < 1 {
231 panic(i)
232 }
233 }
c45c1bca
SW
234 return dims
235}
236
237func StateTableSize(dims []int) int {
e346cb37 238 product := 1
c45c1bca 239 for _, size := range dims {
e346cb37 240 product *= size
c45c1bca 241 }
e346cb37 242 return product
c45c1bca
SW
243}
244
245type State struct {
0372f045 246 value, from int32
c45c1bca
SW
247}
248
1539cc25 249const (
fb8eccbf
SW
250 FROM_ROOT = -2147483647 + iota
251 FROM_UNINITIALIZED
252 VALUE_UNINITIALIZED
253 VALUE_BEING_EVALUATED
254 VALUE_RUBISH
1539cc25 255)
0372f045
SW
256
257func EncodeIndex(dims, addr []int) int32 {
688733e1 258 index := addr[0]
e346cb37
SW
259 if addr[0] > dims[0] {
260 panic(0)
261 }
330093c1 262 for i := 1; i < NumDimensions; i++ {
688733e1 263 if addr[i] < 0 || addr[i] >= dims[i] {
e346cb37
SW
264 panic(i)
265 }
688733e1 266 index = index*dims[i] + addr[i]
c45c1bca 267 }
688733e1 268 return int32(index)
c45c1bca
SW
269}
270
0372f045 271func DecodeIndex(dims []int, index int32) []int {
330093c1
SW
272 addr := make([]int, NumDimensions)
273 for i := NumDimensions - 1; i > 0; i-- {
0372f045
SW
274 addr[i] = int(index) % dims[i]
275 index /= int32(dims[i])
c45c1bca 276 }
0372f045 277 addr[0] = int(index)
c45c1bca
SW
278 return addr
279}
280
0372f045 281func CreateStateTable(data planet_data, dims []int) []State {
330093c1 282 table := make([]State, StateTableSize(dims))
0372f045 283 for i := range table {
fb8eccbf
SW
284 table[i].value = VALUE_UNINITIALIZED
285 table[i].from = FROM_UNINITIALIZED
0372f045 286 }
330093c1
SW
287
288 addr := make([]int, NumDimensions)
289 addr[Fuel] = *fuel
290 addr[Edens] = *start_edens
291 addr[Location] = data.p2i[*start]
a06dc4cb
SW
292 if *start_hold != "" {
293 addr[Hold] = data.c2i[*start_hold]
294 }
fb8eccbf
SW
295 start_index := EncodeIndex(dims, addr)
296 table[start_index].value = int32(*funds)
297 table[start_index].from = FROM_ROOT
330093c1
SW
298
299 return table
e346cb37
SW
300}
301
0372f045
SW
302/* CellValue fills in the one cell at address addr by looking at all
303 * the possible ways to reach this cell and selecting the best one. */
330093c1 304
0372f045
SW
305func Consider(data planet_data, dims []int, table []State, there []int, value_difference int, best_value *int32, best_source []int) {
306 there_value := CellValue(data, dims, table, there)
307 if value_difference < 0 && int32(-value_difference) > there_value {
308 /* Can't afford this transition */
309 return
310 }
311 possible_value := there_value + int32(value_difference)
312 if possible_value > *best_value {
313 *best_value = possible_value
314 copy(best_source, there)
330093c1
SW
315 }
316}
317
0372f045 318var cell_filled_count int
1539cc25 319
0372f045 320func CellValue(data planet_data, dims []int, table []State, addr []int) int32 {
e346cb37 321 my_index := EncodeIndex(dims, addr)
fb8eccbf 322 if table[my_index].value == VALUE_BEING_EVALUATED {
0372f045
SW
323 panic("Circular dependency")
324 }
fb8eccbf 325 if table[my_index].value != VALUE_UNINITIALIZED {
0372f045
SW
326 return table[my_index].value
327 }
fb8eccbf 328 table[my_index].value = VALUE_BEING_EVALUATED
0372f045 329
fb8eccbf 330 best_value := int32(VALUE_RUBISH)
0372f045 331 best_source := make([]int, NumDimensions)
e346cb37
SW
332 other := make([]int, NumDimensions)
333 copy(other, addr)
0372f045 334 planet := data.i2p[addr[Location]]
e346cb37 335
0372f045
SW
336 /* Travel here */
337 if addr[Traded] == 0 { /* Can't have traded immediately after traveling. */
338 other[Traded] = 1 /* Travel from states that have done trading. */
339
340 /* Travel here via a 2-fuel unit jump */
341 if addr[Fuel]+2 < dims[Fuel] {
342 other[Fuel] = addr[Fuel] + 2
343 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 2)
344 if hole_index >= len(flight_plan()) || addr[Location] != data.p2i[flight_plan()[hole_index]] {
345 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
346 if data.Planets[data.i2p[addr[Location]]].BeaconOn {
347 Consider(data, dims, table, other, 0, &best_value, best_source)
348 }
349 }
beb45aca 350 }
0372f045
SW
351 other[Location] = addr[Location]
352 other[Fuel] = addr[Fuel]
e346cb37 353 }
e346cb37 354
0372f045
SW
355 /* Travel here via a 1-fuel unit jump (a hyper hole) */
356 if addr[Fuel]+1 < dims[Fuel] {
357 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 1)
358 if hole_index < len(flight_plan()) && addr[Location] == data.p2i[flight_plan()[hole_index]] {
359 other[Fuel] = addr[Fuel] + 1
360 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
361 Consider(data, dims, table, other, 0, &best_value, best_source)
362 }
363 other[Location] = addr[Location]
364 other[Fuel] = addr[Fuel]
7b5d9d13 365 }
e346cb37 366 }
e346cb37 367
0372f045 368 /* Travel here via Eden Warp Unit */
34db2393 369 if addr[Edens]+1 < dims[Edens] && addr[UnusedCargo] > 0 {
0372f045
SW
370 _, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
371 if !available {
372 other[Edens] = addr[Edens] + 1
373 if other[Hold] != 0 {
374 other[UnusedCargo] = addr[UnusedCargo] - 1
375 }
376 for other[Location] = 0; other[Location] < dims[Location]; other[Location]++ {
377 Consider(data, dims, table, other, 0, &best_value, best_source)
378 }
379 other[Location] = addr[Location]
380 other[UnusedCargo] = addr[UnusedCargo]
381 other[Edens] = addr[Edens]
0c27c344 382 }
330093c1 383 }
0372f045 384 other[Traded] = addr[Traded]
330093c1 385 }
330093c1 386
0372f045
SW
387 /* Trade */
388 if addr[Traded] == 1 {
389 other[Traded] = 0
330093c1 390
0372f045
SW
391 /* Consider not trading */
392 Consider(data, dims, table, other, 0, &best_value, best_source)
330093c1 393
0372f045 394 if !data.Planets[data.i2p[addr[Location]]].Private {
330093c1 395
0372f045
SW
396 /* Sell */
397 if addr[Hold] == 0 && addr[UnusedCargo] == 0 {
398 for other[Hold] = 0; other[Hold] < dims[Hold]; other[Hold]++ {
399 commodity := data.i2c[other[Hold]]
400 if !data.Commodities[commodity].CanSell {
401 continue
402 }
403 relative_price, available := data.Planets[planet].RelativePrices[commodity]
404 if !available {
405 // TODO: Dump cargo
406 continue
407 }
408 base_price := data.Commodities[commodity].BasePrice
409 absolute_price := float64(base_price) * float64(relative_price) / 100.0
410 sell_price := int(absolute_price * 0.9)
411
412 for other[UnusedCargo] = 0; other[UnusedCargo] < dims[UnusedCargo]; other[UnusedCargo]++ {
413 quantity := *hold - (other[UnusedCargo] + other[Cloaks] + other[Edens])
414 sale_value := quantity * sell_price
415 Consider(data, dims, table, other, sale_value, &best_value, best_source)
416 }
417 }
418 other[UnusedCargo] = addr[UnusedCargo]
419 other[Hold] = addr[Hold]
420 }
330093c1 421
0372f045
SW
422 /* Buy */
423 other[Traded] = addr[Traded] /* Buy after selling */
424 if addr[Hold] != 0 {
425 commodity := data.i2c[addr[Hold]]
426 if data.Commodities[commodity].CanSell {
427 relative_price, available := data.Planets[planet].RelativePrices[commodity]
428 if available {
429 base_price := data.Commodities[commodity].BasePrice
430 absolute_price := int(float64(base_price) * float64(relative_price) / 100.0)
431 quantity := *hold - (addr[UnusedCargo] + addr[Cloaks] + addr[Edens])
432 total_price := quantity * absolute_price
433 other[Hold] = 0
434 other[UnusedCargo] = 0
435 Consider(data, dims, table, other, -total_price, &best_value, best_source)
436 other[UnusedCargo] = addr[UnusedCargo]
437 other[Hold] = addr[Hold]
438 }
439 }
440 }
441 }
6918cad2 442 other[Traded] = addr[Traded]
0372f045 443 }
d16f3322 444
544108c4 445 /* Buy a Device of Cloaking */
ada59973
SW
446 if addr[Cloaks] == 1 && addr[UnusedCargo] < dims[UnusedCargo]-1 {
447 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Device Of Cloakings"]
448 if available {
449 absolute_price := int(float64(data.Commodities["Device Of Cloakings"].BasePrice) * float64(relative_price) / 100.0)
450 other[Cloaks] = 0
f800f732
SW
451 if other[Hold] != 0 {
452 other[UnusedCargo] = addr[UnusedCargo] + 1
453 }
0372f045 454 Consider(data, dims, table, other, -absolute_price, &best_value, best_source)
ada59973
SW
455 other[UnusedCargo] = addr[UnusedCargo]
456 other[Cloaks] = addr[Cloaks]
457 }
458 }
76db1b3c 459
544108c4 460 /* Buy Fighter Drones */
76db1b3c
SW
461 if addr[BuyFighters] == 1 {
462 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Fighter Drones"]
463 if available {
464 absolute_price := int(float64(data.Commodities["Fighter Drones"].BasePrice) * float64(relative_price) / 100.0)
465 other[BuyFighters] = 0
1539cc25 466 Consider(data, dims, table, other, -absolute_price**drones, &best_value, best_source)
76db1b3c
SW
467 other[BuyFighters] = addr[BuyFighters]
468 }
469 }
470
544108c4 471 /* Buy Shield Batteries */
76db1b3c
SW
472 if addr[BuyShields] == 1 {
473 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Shield Batterys"]
474 if available {
475 absolute_price := int(float64(data.Commodities["Shield Batterys"].BasePrice) * float64(relative_price) / 100.0)
476 other[BuyShields] = 0
1539cc25 477 Consider(data, dims, table, other, -absolute_price**batteries, &best_value, best_source)
76db1b3c
SW
478 other[BuyShields] = addr[BuyShields]
479 }
480 }
481
544108c4 482 /* Visit this planet */
4d7362df
SW
483 var i uint
484 for i = 0; i < uint(len(visit())); i++ {
1539cc25 485 if addr[Visit]&(1<<i) != 0 && visit()[i] == data.i2p[addr[Location]] {
4d7362df 486 other[Visit] = addr[Visit] & ^(1 << i)
0372f045 487 Consider(data, dims, table, other, 0, &best_value, best_source)
4d7362df
SW
488 }
489 }
490 other[Visit] = addr[Visit]
76db1b3c 491
d16f3322
SW
492 /* Buy Eden warp units */
493 eden_limit := data.Commodities["Eden Warp Units"].Limit
494 if addr[Edens] > 0 && addr[Edens] <= eden_limit {
495 relative_price, available := data.Planets[data.i2p[addr[Location]]].RelativePrices["Eden Warp Units"]
496 if available {
497 absolute_price := int(float64(data.Commodities["Eden Warp Units"].BasePrice) * float64(relative_price) / 100.0)
498 for quantity := addr[Edens]; quantity > 0; quantity-- {
499 other[Edens] = addr[Edens] - quantity
500 if addr[Hold] != 0 {
501 other[UnusedCargo] = addr[UnusedCargo] + quantity
502 }
503 if other[UnusedCargo] < dims[UnusedCargo] {
1539cc25 504 Consider(data, dims, table, other, -absolute_price*quantity, &best_value, best_source)
d16f3322
SW
505 }
506 }
507 other[Edens] = addr[Edens]
508 other[UnusedCargo] = addr[UnusedCargo]
509 }
510 }
d16f3322 511
688733e1
SW
512 // Check that we didn't lose track of any temporary modifications to other.
513 for i := 0; i < NumDimensions; i++ {
514 if addr[i] != other[i] {
515 panic(i)
516 }
517 }
518
519 // Sanity check: This cell was in state BEING_EVALUATED
520 // the whole time that it was being evaluated.
fb8eccbf 521 if table[my_index].value != VALUE_BEING_EVALUATED {
0372f045 522 panic(my_index)
e7e4bc13 523 }
688733e1
SW
524
525 // Record our findings
0372f045
SW
526 table[my_index].value = best_value
527 table[my_index].from = EncodeIndex(dims, best_source)
330093c1 528
688733e1 529 // UI: Progress bar
1539cc25 530 cell_filled_count++
c5ac83ce 531 if cell_filled_count&0xfff == 0 {
0372f045 532 print(fmt.Sprintf("\r%3.1f%%", 100*float64(cell_filled_count)/float64(StateTableSize(dims))))
fcdc120b 533 }
e7e4bc13 534
0372f045 535 return table[my_index].value
e7e4bc13
SW
536}
537
0372f045 538func FindBestState(data planet_data, dims []int, table []State) int32 {
ad4de13f
SW
539 addr := make([]int, NumDimensions)
540 addr[Edens] = *end_edens
541 addr[Cloaks] = dims[Cloaks] - 1
76db1b3c
SW
542 addr[BuyFighters] = dims[BuyFighters] - 1
543 addr[BuyShields] = dims[BuyShields] - 1
ad4de13f 544 addr[Visit] = dims[Visit] - 1
0372f045 545 addr[Traded] = 1
688733e1
SW
546 addr[Hold] = 0
547 addr[UnusedCargo] = 0
0372f045 548 max_index := int32(-1)
60025e5d 549 max_value := 0.0
688733e1
SW
550 max_fuel := 1
551 if *fuel == 0 {
552 max_fuel = 0
553 }
554 for addr[Fuel] = 0; addr[Fuel] <= max_fuel; addr[Fuel]++ {
ddef04ab 555 for addr[Location] = 0; addr[Location] < dims[Location]; addr[Location]++ {
60025e5d
SW
556 planet := data.i2p[addr[Location]]
557 if len(end()) == 0 || end()[planet] {
ddef04ab 558 index := EncodeIndex(dims, addr)
60025e5d
SW
559 today_value := CellValue(data, dims, table, addr)
560 tomorrow_value := *tomorrow_weight * float64(*hold+data.Planets[planet].TomorrowValue)
561 value := float64(today_value) + tomorrow_value
0372f045
SW
562 if value > max_value {
563 max_value = value
ddef04ab
SW
564 max_index = index
565 }
809e65f4 566 }
ad4de13f
SW
567 }
568 }
569 return max_index
570}
571
0372f045 572func Commas(n int32) (s string) {
9eafb7a4
SW
573 r := n % 1000
574 n /= 1000
575 for n > 0 {
576 s = fmt.Sprintf(",%03d", r) + s
577 r = n % 1000
578 n /= 1000
579 }
580 s = fmt.Sprint(r) + s
581 return
582}
583
0372f045 584func DescribePath(data planet_data, dims []int, table []State, start int32) (description []string) {
fb8eccbf
SW
585 for index := start; table[index].from > FROM_ROOT; index = table[index].from {
586 if table[index].from == FROM_UNINITIALIZED {
587 panic(index)
588 }
e4a1b48f 589 var line string
2f4a9ae8
SW
590 addr := DecodeIndex(dims, index)
591 prev := DecodeIndex(dims, table[index].from)
e4a1b48f 592 if addr[Fuel] != prev[Fuel] {
2f4a9ae8
SW
593 from := data.i2p[prev[Location]]
594 to := data.i2p[addr[Location]]
63b4dbbc 595 line += fmt.Sprintf("Jump from %v to %v (%v hyper jump units)", from, to, prev[Fuel]-addr[Fuel])
e4a1b48f 596 }
1539cc25 597 if addr[Edens] == prev[Edens]-1 {
e4a1b48f
SW
598 from := data.i2p[prev[Location]]
599 to := data.i2p[addr[Location]]
600 line += fmt.Sprintf("Eden warp from %v to %v", from, to)
2f4a9ae8
SW
601 }
602 if addr[Hold] != prev[Hold] {
603 if addr[Hold] == 0 {
604 quantity := *hold - (prev[UnusedCargo] + prev[Edens] + prev[Cloaks])
e4a1b48f 605 line += fmt.Sprintf("Sell %v %v", quantity, data.i2c[prev[Hold]])
2f4a9ae8
SW
606 } else if prev[Hold] == 0 {
607 quantity := *hold - (addr[UnusedCargo] + addr[Edens] + addr[Cloaks])
e4a1b48f 608 line += fmt.Sprintf("Buy %v %v", quantity, data.i2c[addr[Hold]])
2f4a9ae8
SW
609 } else {
610 panic("Switched cargo?")
611 }
612
613 }
f800f732
SW
614 if addr[Cloaks] == 1 && prev[Cloaks] == 0 {
615 // TODO: Dump cloaks, convert from cargo?
e4a1b48f
SW
616 line += "Buy a Cloak"
617 }
d16f3322 618 if addr[Edens] > prev[Edens] {
1539cc25 619 line += fmt.Sprint("Buy ", addr[Edens]-prev[Edens], " Eden Warp Units")
e4a1b48f 620 }
76db1b3c
SW
621 if addr[BuyShields] == 1 && prev[BuyShields] == 0 {
622 line += fmt.Sprint("Buy ", *batteries, " Shield Batterys")
623 }
624 if addr[BuyFighters] == 1 && prev[BuyFighters] == 0 {
625 line += fmt.Sprint("Buy ", *drones, " Fighter Drones")
626 }
4d7362df
SW
627 if addr[Visit] != prev[Visit] {
628 // TODO: verify that the bit chat changed is addr[Location]
629 line += fmt.Sprint("Visit ", data.i2p[addr[Location]])
630 }
0372f045
SW
631 if line == "" && addr[Hold] == prev[Hold] && addr[Traded] != prev[Traded] {
632 // The Traded dimension is for housekeeping. It doesn't directly
633 // correspond to in-game actions, so don't report transitions.
634 continue
635 }
e4a1b48f
SW
636 if line == "" {
637 line = fmt.Sprint(prev, " -> ", addr)
f800f732 638 }
1539cc25 639 description = append(description, fmt.Sprintf("%13v ", Commas(table[index].value))+line)
2f4a9ae8
SW
640 }
641 return
642}
643
c45c1bca 644// (Example of a use case for generics in Go)
e7e4bc13 645func IndexPlanets(m *map[string]Planet, start_at int) (map[string]int, []string) {
a1f10151
SW
646 e2i := make(map[string]int, len(*m)+start_at)
647 i2e := make([]string, len(*m)+start_at)
e7e4bc13 648 i := start_at
c45c1bca 649 for e := range *m {
e7e4bc13
SW
650 e2i[e] = i
651 i2e[i] = e
c45c1bca
SW
652 i++
653 }
e7e4bc13 654 return e2i, i2e
c45c1bca 655}
e7e4bc13 656func IndexCommodities(m *map[string]Commodity, start_at int) (map[string]int, []string) {
a1f10151
SW
657 e2i := make(map[string]int, len(*m)+start_at)
658 i2e := make([]string, len(*m)+start_at)
e7e4bc13 659 i := start_at
c45c1bca 660 for e := range *m {
e7e4bc13
SW
661 e2i[e] = i
662 i2e[i] = e
c45c1bca
SW
663 i++
664 }
e7e4bc13 665 return e2i, i2e
c45c1bca
SW
666}
667
d07f3caa
SW
668func main() {
669 flag.Parse()
311b26d4
SW
670 if *start == "" || *funds == 0 {
671 print("--start and --funds are required. --help for more\n")
672 return
673 }
42f6427c
SW
674 if *cpuprofile != "" {
675 f, err := os.Create(*cpuprofile)
676 if err != nil {
677 panic(err)
678 }
679 pprof.StartCPUProfile(f)
680 defer pprof.StopCPUProfile()
681 }
d07f3caa 682 data := ReadData()
76db1b3c
SW
683 if *drone_price > 0 {
684 temp := data.Commodities["Fighter Drones"]
685 temp.BasePrice = *drone_price
686 data.Commodities["Fighter Drones"] = temp
687 }
688 if *battery_price > 0 {
689 temp := data.Commodities["Shield Batterys"]
690 temp.BasePrice = *battery_price
691 data.Commodities["Shield Batterys"] = temp
692 }
e7e4bc13
SW
693 data.p2i, data.i2p = IndexPlanets(&data.Planets, 0)
694 data.c2i, data.i2c = IndexCommodities(&data.Commodities, 1)
c45c1bca 695 dims := DimensionSizes(data)
0372f045 696 table := CreateStateTable(data, dims)
ad4de13f 697 best := FindBestState(data, dims, table)
0372f045 698 print("\n")
ada59973
SW
699 if best == -1 {
700 print("Cannot acheive success criteria\n")
701 } else {
ada59973
SW
702 description := DescribePath(data, dims, table, best)
703 for i := len(description) - 1; i >= 0; i-- {
704 fmt.Println(description[i])
705 }
2f4a9ae8 706 }
d07f3caa 707}