]> git.scottworley.com Git - planeteer/blame - planeteer.go
Add a lot of code that isn't exercised yet.
[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"
c45c1bca
SW
24import "strings"
25
26var start = flag.String("start", "",
27 "The planet to start at")
d07f3caa 28
c45c1bca
SW
29var end = flag.String("end", "",
30 "A comma-separated list of planets to end at")
31
32var planet_data_file = flag.String("planet_data_file", "planet-data",
d07f3caa
SW
33 "The file to read planet data from")
34
c45c1bca
SW
35var fuel = flag.Int("fuel", 16,
36 "Reactor units; How many non-Eden jumps we can make " +
37 "(but remember that deviating from the flight plan " +
38 "costs two units of fuel per jump)")
39
40var start_edens = flag.Int("start_edens", 0,
41 "How many Eden Warp Units are you starting with?")
42
43var end_edens = flag.Int("end_edens", 0,
44 "How many Eden Warp Units would you like to keep (not use)?")
45
46var cloak = flag.Bool("cloak", false,
47 "Make sure to end with a Device of Cloaking")
48
49var drones = flag.Int("drones", 0,
50 "Buy this many Fighter Drones")
51
52var batteries = flag.Int("batteries", 0,
53 "Buy this many Shield Batterys")
54
55var visit_string = flag.String("visit", "",
56 "A comma-separated list of planets to make sure to visit")
57
58func visit() []string {
59 return strings.Split(*visit_string, ",")
60}
61
9b3b3d9a 62type Commodity struct {
9b3b3d9a
SW
63 BasePrice int
64 CanSell bool
65 Limit int
66}
12bc2cd7 67type Planet struct {
12bc2cd7
SW
68 BeaconOn bool
69 /* Use relative prices rather than absolute prices because you
70 can get relative prices without traveling to each planet. */
71 RelativePrices map [string] int
72}
d07f3caa 73type planet_data struct {
5f1a50e1 74 Commodities map [string] Commodity
c45c1bca
SW
75 Planets map [string] Planet
76 pi, ci map [string] int // Generated; not read from file
d07f3caa
SW
77}
78
79func ReadData() (data planet_data) {
c45c1bca 80 f, err := os.Open(*planet_data_file)
d07f3caa
SW
81 if err != nil {
82 panic(err)
83 }
84 defer f.Close()
85 err = json.NewDecoder(f).Decode(&data)
86 if err != nil {
87 panic(err)
88 }
89 return
90}
91
c45c1bca
SW
92/* This program operates by filling in a state table representing the best
93 * possible trips you could make; the ones that makes you the most money.
94 * This is feasible because we don't look at all the possible trips.
95 * We define a list of things that are germane to this game and then only
96 * consider the best outcome in each possible game state.
97 *
98 * Each cell in the table represents a state in the game. In each cell,
99 * we track two things: 1. the most money you could possibly have while in
100 * that state and 2. one possible way to get into that state with that
101 * amount of money.
102 *
103 * A basic analysis can be done with a two-dimensional table: location and
104 * fuel. planeteer-1.0 used this two-dimensional table. This version
105 * adds features mostly by adding dimensions to this table.
106 *
107 * Note that the sizes of each dimension are data driven. Many dimensions
108 * collapse to one possible value (ie, disappear) if the corresponding
109 * feature is not enabled.
110 */
111
112// The official list of dimensions:
113const (
114 // Name Num Size Description
115 Edens = iota // 1 3 # of Eden warp units (0 - 2 typically)
116 Cloaks // 2 2 # of Devices of Cloaking (0 or 1)
117 UnusedCargo // 3 4 # of unused cargo spaces (0 - 3 typically)
118 Fuel // 4 17 Reactor power left (0 - 16)
119 Location // 5 26 Location (which planet)
120 Hold // 6 15 Cargo bay contents (a *Commodity or nil)
121 NeedFighters // 7 2 Errand: Buy fighter drones (needed or not)
122 NeedShields // 8 2 Errand: Buy shield batteries (needed or not)
123 Visit // 9 2**N Visit: Stop by these N planets in the route
124
125 NumDimensions
126)
127
128func bint(b bool) int {
129 if b { return 1 }
130 return 0
131}
132
133func DimensionSizes(data planet_data) []int {
134 eden_capacity := data.Commodities["Eden Warp Units"].Limit
135 cloak_capacity := bint(*cloak)
136 dims := []int{
137 eden_capacity + 1,
138 cloak_capacity + 1,
139 eden_capacity + cloak_capacity + 1,
140 *fuel + 1,
141 len(data.Planets),
142 len(data.Commodities),
143 bint(*drones > 0) + 1,
144 bint(*batteries > 0) + 1,
145 1 << uint(len(visit())),
146 }
147 if len(dims) != NumDimensions {
148 panic("Dimensionality mismatch")
149 }
150 return dims
151}
152
153func StateTableSize(dims []int) int {
154 sum := 0
155 for _, size := range dims {
156 sum += size
157 }
158 return sum
159}
160
161type State struct {
162 funds, from int
163}
164
165func NewStateTable(dims []int) []State {
166 return make([]State, StateTableSize(dims))
167}
168
169func EncodeIndex(dims, addr []int) int {
170 index := addr[0]
171 for i := 1; i < len(dims); i++ {
172 index = index * dims[i] + addr[i]
173 }
174 return index
175}
176
177func DecodeIndex(dims []int, index int) []int {
178 addr := make([]int, len(dims))
179 for i := len(dims) - 1; i > 0; i-- {
180 addr[i] = index % dims[i]
181 index /= dims[i]
182 }
183 addr[0] = index
184 return addr
185}
186
5f1a50e1
SW
187/* What is the value of hauling 'commodity' from 'from' to 'to'?
188 * Take into account the available funds and the available cargo space. */
189func TradeValue(data planet_data,
c45c1bca 190 from, to Planet,
5f1a50e1
SW
191 commodity string,
192 initial_funds, max_quantity int) int {
193 if !data.Commodities[commodity].CanSell {
5a1593ab
SW
194 return 0
195 }
5f1a50e1 196 from_relative_price, from_available := from.RelativePrices[commodity]
5a1593ab
SW
197 if !from_available {
198 return 0
199 }
5f1a50e1 200 to_relative_price, to_available := to.RelativePrices[commodity]
5a1593ab
SW
201 if !to_available {
202 return 0
203 }
204
5f1a50e1
SW
205 base_price := data.Commodities[commodity].BasePrice
206 from_absolute_price := from_relative_price * base_price
207 to_absolute_price := to_relative_price * base_price
5a1593ab
SW
208 buy_price := from_absolute_price
209 sell_price := int(float64(to_absolute_price) * 0.9)
5f1a50e1
SW
210 var can_afford int = initial_funds / buy_price
211 quantity := can_afford
212 if quantity > max_quantity {
213 quantity = max_quantity
214 }
215 return (sell_price - buy_price) * max_quantity
5a1593ab
SW
216}
217
5f1a50e1 218func FindBestTrades(data planet_data) [][]string {
c45c1bca 219 // TODO: We can't cache this because this can change based on available funds.
5f1a50e1 220 best := make([][]string, len(data.Planets))
c45c1bca
SW
221 for from := range data.Planets {
222 best[data.pi[from]] = make([]string, len(data.Planets))
223 for to := range data.Planets {
5a1593ab 224 best_gain := 0
c45c1bca
SW
225 price_list := data.Planets[from].RelativePrices
226 if len(data.Planets[to].RelativePrices) < len(data.Planets[from].RelativePrices) {
227 price_list = data.Planets[to].RelativePrices
5f1a50e1
SW
228 }
229 for commodity := range price_list {
230 gain := TradeValue(data,
c45c1bca
SW
231 data.Planets[from],
232 data.Planets[to],
5f1a50e1
SW
233 commodity,
234 10000000,
12bc2cd7 235 1)
5a1593ab 236 if gain > best_gain {
c45c1bca 237 best[data.pi[from]][data.pi[to]] = commodity
5a1593ab
SW
238 gain = best_gain
239 }
240 }
241 }
242 }
243 return best
244}
245
c45c1bca
SW
246// (Example of a use case for generics in Go)
247func IndexPlanets(m *map [string] Planet) map [string] int {
248 index := make(map [string] int, len(*m))
249 i := 0
250 for e := range *m {
251 index[e] = i
252 i++
253 }
254 return index
255}
256func IndexCommodities(m *map [string] Commodity) map [string] int {
257 index := make(map [string] int, len(*m))
258 i := 0
259 for e := range *m {
260 index[e] = i
261 i++
262 }
263 return index
264}
265
d07f3caa
SW
266func main() {
267 flag.Parse()
268 data := ReadData()
c45c1bca
SW
269 data.pi = IndexPlanets(&data.Planets)
270 data.ci = IndexCommodities(&data.Commodities)
271 dims := DimensionSizes(data)
272 table := NewStateTable(dims)
273 table[0] = State{ 1, 1 }
5a1593ab 274 best_trades := FindBestTrades(data)
c45c1bca
SW
275
276 for from := range data.Planets {
277 for to := range data.Planets {
5a1593ab 278 best_trade := "(nothing)"
c45c1bca
SW
279 if best_trades[data.pi[from]][data.pi[to]] != "" {
280 best_trade = best_trades[data.pi[from]][data.pi[to]]
5a1593ab 281 }
c45c1bca 282 fmt.Printf("%s to %s: %s\n", from, to, best_trade)
5a1593ab
SW
283 }
284 }
d07f3caa 285}