1 /* Planeteer: Give trade route advice for Planets: The Exploration of Space
2 * Copyright (C) 2011 Scott Worley <sworley@chkno.net>
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.
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.
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/>.
26 var start = flag.String("start", "",
27 "The planet to start at")
29 var flight_plan_string = flag.String("flight_plan", "",
30 "Your hidey-holes for the day, comma-separated.")
32 var end = flag.String("end", "",
33 "A comma-separated list of acceptable ending planets.")
35 var planet_data_file = flag.String("planet_data_file", "planet-data",
36 "The file to read planet data from")
38 var fuel = flag.Int("fuel", 16, "Reactor units")
40 var hold = flag.Int("hold", 300, "Size of your cargo hold")
42 var start_edens = flag.Int("start_edens", 0,
43 "How many Eden Warp Units are you starting with?")
45 var end_edens = flag.Int("end_edens", 0,
46 "How many Eden Warp Units would you like to keep (not use)?")
48 var cloak = flag.Bool("cloak", false,
49 "Make sure to end with a Device of Cloaking")
51 var drones = flag.Int("drones", 0, "Buy this many Fighter Drones")
53 var batteries = flag.Int("batteries", 0, "Buy this many Shield Batterys")
55 var visit_string = flag.String("visit", "",
56 "A comma-separated list of planets to make sure to visit")
58 func visit() []string {
59 if *visit_string == "" {
62 return strings.Split(*visit_string, ",")
65 func flight_plan() []string {
66 if *flight_plan_string == "" {
69 return strings.Split(*flight_plan_string, ",")
72 type Commodity struct {
79 /* Use relative prices rather than absolute prices because you
80 can get relative prices without traveling to each planet. */
81 RelativePrices map[string]int
83 type planet_data struct {
84 Commodities map[string]Commodity
85 Planets map[string]Planet
86 p2i, c2i map[string]int // Generated; not read from file
87 i2p, i2c []string // Generated; not read from file
90 func ReadData() (data planet_data) {
91 f, err := os.Open(*planet_data_file)
96 err = json.NewDecoder(f).Decode(&data)
103 /* This program operates by filling in a state table representing the best
104 * possible trips you could make; the ones that makes you the most money.
105 * This is feasible because we don't look at all the possible trips.
106 * We define a list of things that are germane to this game and then only
107 * consider the best outcome in each possible game state.
109 * Each cell in the table represents a state in the game. In each cell,
110 * we track two things: 1. the most money you could possibly have while in
111 * that state and 2. one possible way to get into that state with that
114 * A basic analysis can be done with a two-dimensional table: location and
115 * fuel. planeteer-1.0 used this two-dimensional table. This version
116 * adds features mostly by adding dimensions to this table.
118 * Note that the sizes of each dimension are data driven. Many dimensions
119 * collapse to one possible value (ie, disappear) if the corresponding
120 * feature is not enabled.
122 * The order of the dimensions in the list of constants below determines
123 * their layout in RAM. The cargo-based 'dimensions' are not completely
124 * independent -- some combinations are illegal and not used. They are
125 * handled as three dimensions rather than one for simplicity. Placing
126 * these dimensions first causes the unused cells in the table to be
127 * grouped together in large blocks. This keeps them from polluting
128 * cache lines, and if they are large enough, prevent the memory manager
129 * from allocating pages for these areas at all.
131 * If the table gets too big to fit in RAM:
132 * * Combine the Edens, Cloaks, and UnusedCargo dimensions. Of the
133 * 24 combinations, only 15 are legal: a 38% savings.
134 * * Reduce the size of the Fuel dimension to 3. We only ever look
135 * backwards 2 units, so just rotate the logical values through
136 * the same 3 physical addresses. This is good for an 82% savings.
137 * * Reduce the size of the Edens dimension from 3 to 2, for the
138 * same reasons as Fuel above. 33% savings.
139 * * Buy more ram. (Just sayin'. It's cheaper than you think.)
143 // The official list of dimensions:
145 // Name Num Size Description
146 Edens = iota // 1 3 # of Eden warp units (0 - 2 typically)
147 Cloaks // 2 2 # of Devices of Cloaking (0 or 1)
148 UnusedCargo // 3 4 # of unused cargo spaces (0 - 3 typically)
149 Fuel // 4 17 Reactor power left (0 - 16)
150 Location // 5 26 Location (which planet)
151 Hold // 6 15 Cargo bay contents (a *Commodity or nil)
152 NeedFighters // 7 2 Errand: Buy fighter drones (needed or not)
153 NeedShields // 8 2 Errand: Buy shield batteries (needed or not)
154 Visit // 9 2**N Visit: Stop by these N planets in the route
159 func bint(b bool) int {
166 func DimensionSizes(data planet_data) []int {
167 eden_capacity := data.Commodities["Eden Warp Units"].Limit
168 cloak_capacity := bint(*cloak)
169 dims := make([]int, NumDimensions)
170 dims[Edens] = eden_capacity + 1
171 dims[Cloaks] = cloak_capacity + 1
172 dims[UnusedCargo] = eden_capacity + cloak_capacity + 1
173 dims[Fuel] = *fuel + 1
174 dims[Location] = len(data.Planets)
175 dims[Hold] = len(data.Commodities)
176 dims[NeedFighters] = bint(*drones > 0) + 1
177 dims[NeedShields] = bint(*batteries > 0) + 1
178 dims[Visit] = 1 << uint(len(visit()))
180 // Remind myself to add a line above when adding new dimensions
181 for i, dim := range dims {
189 func StateTableSize(dims []int) int {
191 for _, size := range dims {
201 func EncodeIndex(dims, addr []int) int {
203 if addr[0] > dims[0] {
206 for i := 1; i < len(dims); i++ {
207 if addr[i] > dims[i] {
210 index = index*dims[i] + addr[i]
215 func DecodeIndex(dims []int, index int) []int {
216 addr := make([]int, len(dims))
217 for i := len(dims) - 1; i > 0; i-- {
218 addr[i] = index % dims[i]
225 func InitializeStateTable(data planet_data, dims []int, table []State) {
228 /* Fill in the cell at address addr by looking at all the possible ways
229 * to reach this cell and selecting the best one.
231 * The other obvious implementation choice is to do this the other way
232 * around -- for each cell, conditionally overwrite all the other cells
233 * that are reachable *from* the considered cell. We choose gathering
234 * reads over scattering writes to avoid having to take a bunch of locks.
236 * The order that we check things here matters only for value ties. We
237 * keep the first best path. So when action order doesn't matter, the
238 * check that is performed first here will appear in the output first.
240 func FillStateTableCell(data planet_data, dims []int, table []State, addr []int) {
241 my_index := EncodeIndex(dims, addr)
242 other := make([]int, NumDimensions)
245 /* Travel here via a 2-fuel unit jump */
246 if addr[Fuel] + 2 < dims[Fuel] {
247 other[Fuel] = addr[Fuel] + 2
248 for p := 0; p < dims[Location]; p++ {
250 if table[EncodeIndex(dims, other)].value > table[my_index].value {
251 table[my_index].value = table[EncodeIndex(dims, other)].value
252 table[my_index].from = EncodeIndex(dims, other)
255 other[Location] = addr[Location]
256 other[Fuel] = addr[Fuel]
259 /* Travel here via a hidey hole */
260 if addr[Fuel] + 1 < dims[Fuel] {
261 hole_index := (dims[Fuel] - 1) - (addr[Fuel] + 1)
262 if hole_index < len(flight_plan()) {
263 other[Fuel] = addr[Fuel] + 1
264 other[Location] = data.p2i[flight_plan()[hole_index]]
265 if table[EncodeIndex(dims, other)].value > table[my_index].value {
266 table[my_index].value = table[EncodeIndex(dims, other)].value
267 table[my_index].from = EncodeIndex(dims, other)
269 other[Fuel] = addr[Fuel]
273 /* Travel here via Eden Warp Unit */
274 /* Silly: Dump Eden warp units */
275 /* Buy Eden warp units */
276 /* Buy a Device of Cloaking */
277 /* Silly: Dump a Device of Cloaking */
278 /* Buy Fighter Drones */
279 /* Buy Shield Batteries */
281 /* Sell or dump things */
282 // for commodity := range data.Commodities { }
286 /* Visit this planet */
289 func FillStateTable2(data planet_data, dims []int, table []State,
290 fuel_remaining, edens_remaining int, planet string, barrier chan<- bool) {
291 /* The dimension nesting order up to this point is important.
292 * Beyond this point, it's not important.
294 * It is very important when iterating through the Hold dimension
295 * to visit the null commodity (empty hold) first. Visiting the
296 * null commodity represents selling. Visiting it first gets the
297 * action order correct: arrive, sell, buy, leave. Visiting the
298 * null commodity after another commodity would evaluate the action
299 * sequence: arrive, buy, sell, leave. This is a useless action
300 * sequence. Because we visit the null commodity first, we do not
301 * consider these action sequences.
303 eden_capacity := data.Commodities["Eden Warp Units"].Limit
304 addr := make([]int, len(dims))
305 addr[Edens] = edens_remaining
306 addr[Fuel] = fuel_remaining
307 addr[Location] = data.p2i[planet]
308 for addr[Hold] = 0; addr[Hold] < dims[Hold]; addr[Hold]++ {
309 for addr[Cloaks] = 0; addr[Cloaks] < dims[Cloaks]; addr[Cloaks]++ {
310 for addr[UnusedCargo] = 0; addr[UnusedCargo] < dims[UnusedCargo]; addr[UnusedCargo]++ {
311 if addr[Edens]+addr[Cloaks]+addr[UnusedCargo] <=
313 for addr[NeedFighters] = 0; addr[NeedFighters] < dims[NeedFighters]; addr[NeedFighters]++ {
314 for addr[NeedShields] = 0; addr[NeedShields] < dims[NeedShields]; addr[NeedShields]++ {
315 for addr[Visit] = 0; addr[Visit] < dims[Visit]; addr[Visit]++ {
316 FillStateTableCell(data, dims, table, addr)
327 /* Filling the state table is a set of nested for loops NumDimensions deep.
328 * We split this into two procedures: 1 and 2. #1 is the outer, slowest-
329 * changing indexes. #1 fires off many calls to #2 that run in parallel.
330 * The order of the nesting of the dimensions, the order of iteration within
331 * each dimension, and where the 1 / 2 split is placed are carefully chosen
332 * to make this arrangement safe.
334 * Outermost two layers: Go from high-energy states (lots of fuel, edens) to
335 * low-energy state. These must be processed sequentially and in this order
336 * because you travel through high-energy states to get to the low-energy
339 * Third layer: Planet. This is a good layer to parallelize on. There's
340 * high enough cardinality that we don't have to mess with parallelizing
341 * multiple layers for good utilization (on 2011 machines). Each thread
342 * works on one planet's states and need not synchronize with peer threads.
344 func FillStateTable1(data planet_data, dims []int, table []State) {
345 barrier := make(chan bool, len(data.Planets))
346 eden_capacity := data.Commodities["Eden Warp Units"].Limit
347 work_units := (float64(*fuel) + 1) * (float64(eden_capacity) + 1)
349 for fuel_remaining := *fuel; fuel_remaining >= 0; fuel_remaining-- {
350 for edens_remaining := eden_capacity; edens_remaining >= 0; edens_remaining-- {
351 for planet := range data.Planets {
352 go FillStateTable2(data, dims, table, fuel_remaining,
353 edens_remaining, planet, barrier)
355 for _ = range data.Planets {
359 fmt.Printf("\r%3.0f%%", 100*work_done/work_units)
365 /* What is the value of hauling 'commodity' from 'from' to 'to'?
366 * Take into account the available funds and the available cargo space. */
367 func TradeValue(data planet_data,
370 initial_funds, max_quantity int) int {
371 if !data.Commodities[commodity].CanSell {
374 from_relative_price, from_available := from.RelativePrices[commodity]
378 to_relative_price, to_available := to.RelativePrices[commodity]
383 base_price := data.Commodities[commodity].BasePrice
384 from_absolute_price := from_relative_price * base_price
385 to_absolute_price := to_relative_price * base_price
386 buy_price := from_absolute_price
387 sell_price := int(float64(to_absolute_price) * 0.9)
388 var can_afford int = initial_funds / buy_price
389 quantity := can_afford
390 if quantity > max_quantity {
391 quantity = max_quantity
393 return (sell_price - buy_price) * max_quantity
396 func FindBestTrades(data planet_data) [][]string {
397 // TODO: We can't cache this because this can change based on available funds.
398 best := make([][]string, len(data.Planets))
399 for from := range data.Planets {
400 best[data.p2i[from]] = make([]string, len(data.Planets))
401 for to := range data.Planets {
403 price_list := data.Planets[from].RelativePrices
404 if len(data.Planets[to].RelativePrices) < len(data.Planets[from].RelativePrices) {
405 price_list = data.Planets[to].RelativePrices
407 for commodity := range price_list {
408 gain := TradeValue(data,
414 if gain > best_gain {
415 best[data.p2i[from]][data.p2i[to]] = commodity
424 // (Example of a use case for generics in Go)
425 func IndexPlanets(m *map[string]Planet, start_at int) (map[string]int, []string) {
426 e2i := make(map[string]int, len(*m)+start_at)
427 i2e := make([]string, len(*m)+start_at)
436 func IndexCommodities(m *map[string]Commodity, start_at int) (map[string]int, []string) {
437 e2i := make(map[string]int, len(*m)+start_at)
438 i2e := make([]string, len(*m)+start_at)
451 data.p2i, data.i2p = IndexPlanets(&data.Planets, 0)
452 data.c2i, data.i2c = IndexCommodities(&data.Commodities, 1)
453 dims := DimensionSizes(data)
454 table := make([]State, StateTableSize(dims))
455 InitializeStateTable(data, dims, table)
456 FillStateTable1(data, dims, table)
457 print("Going to print state table...")
458 fmt.Printf("%v", table)
459 best_trades := FindBestTrades(data)
461 for from := range data.Planets {
462 for to := range data.Planets {
463 best_trade := "(nothing)"
464 if best_trades[data.p2i[from]][data.p2i[to]] != "" {
465 best_trade = best_trades[data.p2i[from]][data.p2i[to]]
467 fmt.Printf("%s to %s: %s\n", from, to, best_trade)