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