spacetraders

package module
v0.0.0-...-276e6e7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2021 License: Apache-2.0 Imports: 12 Imported by: 0

README

Implementing Space Traders API in Go.

Includes a cli to execute the API (and potentially play the game):

Sample CLI

$ go run example/cli/cli.go
> 
> help
- Available commands:
  <arguments> are required, [options] are optional.
  
      GetCache: GetCache [key]
      Help: Help [command]
      Load: Load [filename]
      Quit (Exit): Quit
      Save: Save [filename]
      Toggle: Toggle [window]
  
    Account:
      Account: Account
      Claim: Claim <username> <path/to/file>
      Login: Login [path/to/file]
      Logout: Logout
  
    Loans:
      AvailableLoans (lsLoans): AvailableLoans
      MyLoans: MyLoans
      PayLoan: PayLoan <loanID>
      TakeLoan: TakeLoan <type>
  
    Ships:
      BuyShip: BuyShip <location> <type>
      ListShips: ListShips <system> [filter]
      MyShips (lsShips): MyShips [filter]
  
    Flight Plans:
      CreateFlightPlan (go, fly): CreateFlightPlan <shipID> <destination>
      ShowFlightPlan (lsFlights): ShowFlightPlan <flightPlanID>
      Wait: Wait <flightPlanID>
  
    Locations:
      Distance: Distance <loc1> <loc2>
      Locations (lsLocations, lsLocs): Locations <system> [type]
      System (lsSys): System [system]
  
    Goods and Cargo:
      Buy: Buy <shipID> <good> <quantity>
      Market: Market <location>
      Sell: Sell <shipID> <good> <quantity>
  
    Automation:
      AddShipToRoute: AddShipToRoute <route name> <ship id>
      CreateTradeRoute (NewTrade, NewRoute): CreateTradeRoute <name> <location, cargo>...
      ShowTradeRoute (ShowRoute): ShowTradeRoute [name]
  
> help claim
- Claim: Claim <username> <path/to/file>
  Claims a username, saves token to specified file
> claim test20739 /tmp/test.readme

- 
> account
- test20739: Credits: 0, Ships: 0, Structures: 0, Joined: 2021/10/09 - 0 days ago
> availableloans
- amt: 200000, needs collateral: false, rate: 40, term (days): 2, type: STARTUP
> takeloan STARTUP
- Loan taken, ln-1 (ckuk0v1pl32117415s6elv1zqra), due: 2021-10-11 09:38:44.071 -0700 PDT (in 47h59m59s)
> listships OE MK-I
- JW-MK-I: Jackshaw MK-I
  speed: 1, cargo: 50, weapons: 5, plating: 5
    OE-PM-TR: 21125
  GR-MK-I: Gravager MK-I
  speed: 1, cargo: 100, weapons: 5, plating: 10
    OE-PM-TR: 42650
  EM-MK-I: Electrum MK-I
  speed: 2, cargo: 50, weapons: 10, plating: 5
    OE-PM-TR: 37750
  HM-MK-I: Hermes MK-I
  speed: 3, cargo: 50, weapons: 5, plating: 20
    OE-PM-TR: 57525
  TD-MK-I: Tiddalik MK-I
  speed: 2, cargo: 3000, weapons: 5, plating: 10
    OE-UC-AD: 473600
> buyship OE-PM-TR JW-MK-I
- New ship ID: s-1 (ckuk0v26z32126215s628np1hzo)
> myships
- s-1: Jackshaw MK-I (JW-MK-I)
  ID: ckuk0v26z32126215s628np1hzo
  Speed: 1, Max cargo: 50, Available space: 50, Weapons: 5, Plating: 5
  At OE-PM-TR (14, 18)
> buy s-1 FUEL 20
- s-1 bought 20 of FUEL for 60
> buy s-1 METALS 25
- s-1 bought 25 of METALS for 100
> myships s-1
- s-1: Jackshaw MK-I (JW-MK-I)
  ID: ckuk0v26z32126215s628np1hzo
  Speed: 1, Max cargo: 50, Available space: 5, Weapons: 5, Plating: 5
  At OE-PM-TR (14, 18)
  Cargo:
    20 of FUEL (20)
    25 of METALS (25)
> locations oe
* Using "OE" for "oe"
- 10 locations in "OE":
    OE-PM: Prime
      Type: PLANET  (13, 16)
      Traits: [METAL_ORES SOME_ARABLE_LAND]
    OE-PM-TR: Tritus
      Type: MOON  (14, 18)
      Traits: [METAL_ORES]
    OE-CR: Carth
      Type: PLANET  (10, 11)
      Traits: [METAL_ORES ARABLE_LAND RARE_METAL_ORES]
    OE-KO: Koria
      Type: PLANET  (-33, -36)
      Traits: [SOME_METAL_ORES SOME_NATURAL_CHEMICALS]
    OE-UC: Ucarro
      Type: PLANET  (74, -15)
      Traits: [SOME_METAL_ORES NATURAL_CHEMICALS]
    OE-UC-AD: Ado
      Type: MOON  (76, -14)
      Traits: [TECHNOLOGICAL_RUINS]
    OE-UC-OB: Obo
      Type: MOON  (77, -16)
      Traits: [NATURAL_CHEMICALS]
    OE-NY: Nyon
      Type: ASTEROID  (-58, 24)
      Allows construction.
    OE-BO: Bo
      Type: GAS_GIANT  (-60, -58)
      Allows construction.
      Traits: [SOME_HELIUM_3]
    OE-W-XV: Wormhole
      Type: WORMHOLE  (87, 55)
      Extensive research has revealed a partially functioning warp gate harnessing the power of an unstable but traversable wormhole.
      The scientific community has determined a means of stabilizing the ancient structure.
      Enter at your own risk.
      GET https://api.spacetraders.io/locations/OE-W-XV/structures
      POST https://api.spacetraders.io/structures/:structureId/deposit shipId=:shipId good=:goodSymbol quantity=:quantity
      POST https://api.spacetraders.io/my/warp-jumps shipId=:shipId
> createflightplan s-1 OE-PM
- Created flight plan: f-1: s-1 OE-PM-TR->OE-PM, ETA: 35s
> showflightplan f-1
- f-1: s-1 OE-PM-TR->OE-PM
    ID: ckuk0v6cd32152515s65j4dykfe
    ShipID: ckuk0v26z32126215s628np1hzo
    Arrives at: 2021-10-09 09:39:26.075 -0700 PDT, ETA: 34s
    Fuel consumed: 1, remaining: 19
    Distance: 2
> wait f-1
- Waiting 34s for f-1 (ckuk0v6cd32152515s65j4dykfe) to arrive...
  ... f-1 arrived!
> sell s-1 METALS 25
- s-1 sold 25 of METALS for 975
> 

Short IDs

Most cases where an object ID is required (e.g. cku26s3jz800715s6siwejax8), a short ID is generated that can be used instead (e.g. s-2, f-1 for the 2nd ship and the first flight plan, respectively).

In addition, a prefix is sufficient for any ID, as long as it is unique for that object type. If you have two ships, with the following IDs:

  • cku26s3jz800715s6siwejax8
  • cku26s4a7824215s6iyyhozhp

They could be referenced as cku26s3 and cku26s4.

Caching

The cli uses a cache to do argument checking for commands, e.g. ListShips will only accept known systems as an argument, while Market only takes locations where you have ships.

This behaviour can be disabled by passing --nocache to the cli, or -f as the first argument to a command.

Implemented endpoints

  • Game status - /game/status

  • List all systems - /game/systems

  • Available offers - /locations/LOCATION/marketplace

  • Account details - /my/account

  • Create flight plan - /my/flight-plans

  • Show flight plans - /my/flight-plans/FLIGHTID

  • List outstanding loans - /my/loans

  • Take out loan - /my/loans

  • Pay off a loan - /my/loans/LOANID

  • Buy cargo - /my/purchase-orders

  • Sell cargo - /my/sell-orders

  • Buy ship - /my/ships

  • List my ship - /my/ships

  • List ships for purchase - /systems/LOCATION/ship-listing

  • List locations in a system - /systems/SYSTEM/locations

  • Available loans - /types/loans

  • Claim username - /users/USERNAME/claim

Documentation

Index

Constants

View Source
const (
	LOANS       CacheKey = "loans"
	SHIPS       CacheKey = "ships"
	MYLOCATIONS CacheKey = "my locations"
	LOCATIONS   CacheKey = "all locations"
	SYSTEMS     CacheKey = "systems"
	FLIGHTS     CacheKey = "flights"
	FLIGHTDESTS CacheKey = "flight destinations"
	CARGO       CacheKey = "cargo"

	USEROBJ   CacheObjKey = "user"
	SHIPOBJ   CacheObjKey = "ship"
	ROUTEOBJ  CacheObjKey = "route"
	MARKETOBJ CacheObjKey = "market"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AccountRes

type AccountRes struct {
	User User `json:"user"`
}

type BuyRes

type BuyRes struct {
	Credits int   `json:"credits"`
	Order   Order `json:"order"`
	Ship    Ship  `json:"ship"`
}

type BuyShipRes

type BuyShipRes struct {
	Credits int  `json:"credits"`
	Ship    Ship `json:"ship"`
}

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

func GetCache

func GetCache() *Cache

func (*Cache) Add

func (c *Cache) Add(key CacheKey, data string)

Add a new value to a key, create a short if needed

func (*Cache) ClearObjs

func (c *Cache) ClearObjs(key CacheObjKey)

Clears cached objects

func (*Cache) Extend

func (c *Cache) Extend(key CacheKey, data []string, shorts []string)

Add multiple new values (both long and short) to a key Note: not creating shorts if they aren't provided

func (*Cache) RegisterUpdate

func (c *Cache) RegisterUpdate(key CacheKey, f func() error)

Define a new type, and how to update it

func (*Cache) Restore

func (c *Cache) Restore(key CacheKey) []string

Get the current cached value for a key

func (*Cache) RestoreObjs

func (c *Cache) RestoreObjs(key CacheObjKey) []interface{}

Get an arbitrary list of objects from the cache

func (*Cache) Store

func (c *Cache) Store(key CacheKey, data []string, shorts []string)

Replace a key with new longs and shorts

func (*Cache) StoreObjs

func (c *Cache) StoreObjs(key CacheObjKey, data []interface{})

Store an arbitrary list of objects

type CacheItem

type CacheItem struct {
	// contains filtered or unexported fields
}

type CacheKey

type CacheKey string

type CacheObjKey

type CacheObjKey string

type Cargo

type Cargo struct {
	Good        string `json:"good"`
	Quantity    int    `json:"quantity"`
	TotalVolume int    `json:"totalVolume"`
}

func (*Cargo) String

func (c *Cargo) String() string

type ClaimRes

type ClaimRes struct {
	Token string `json:"token"`
	User  User   `json:"user"`
}

type Client

type Client struct {
	// contains filtered or unexported fields
}

func New

func New() *Client

func (*Client) Account

func (c *Client) Account() (*User, error)

##ENDPOINT Account details - `/my/account`

func (*Client) AvailableLoans

func (c *Client) AvailableLoans() ([]Loan, error)

Loans ##ENDPOINT Available loans - `/types/loans`

func (*Client) BuyCargo

func (c *Client) BuyCargo(shipID, good string, qty int) (*Order, error)

Goods and Cargo ##ENDPOINT Buy cargo - `/my/purchase-orders`

func (*Client) BuyShip

func (c *Client) BuyShip(location, kind string) (*Ship, error)

##ENDPOINT Buy ship - `/my/ships`

func (*Client) Claim

func (c *Client) Claim(username string) (string, *User, error)

Account ##ENDPOINT Claim username - `/users/USERNAME/claim`

func (*Client) CreateFlight

func (c *Client) CreateFlight(shipID, destination string) (*FlightPlan, error)

##ENDPOINT Create flight plan - `/my/flight-plans`

func (*Client) DoPost

func (c *Client) DoPost(method, base string, args map[string]string) (string, error)

func (*Client) Get

func (c *Client) Get(base string, args map[string]string) (string, error)

func (*Client) ListLocations

func (c *Client) ListLocations(system string, kind string) ([]Location, error)

##ENDPOINT List locations in a system - `/systems/SYSTEM/locations`

func (*Client) ListShips

func (c *Client) ListShips(system string) ([]Ship, error)

Ships ##ENDPOINT List ships for purchase - `/systems/LOCATION/ship-listing`

func (*Client) ListSystems

func (c *Client) ListSystems() ([]System, error)

Systems ##ENDPOINT List all systems - `/game/systems`

func (*Client) Load

func (c *Client) Load(path string) error

func (*Client) Logout

func (c *Client) Logout() error

func (*Client) Marketplace

func (c *Client) Marketplace(loc string) ([]Offer, error)

##ENDPOINT Available offers - `/locations/LOCATION/marketplace`

func (*Client) MyLoans

func (c *Client) MyLoans() ([]Loan, error)

##ENDPOINT List outstanding loans - `/my/loans`

func (*Client) MyShips

func (c *Client) MyShips() ([]Ship, error)

##ENDPOINT List my ship - `/my/ships`

func (*Client) PayLoan

func (c *Client) PayLoan(loanID string) error

##ENDPOINT Pay off a loan - `/my/loans/LOANID`

func (*Client) Post

func (c *Client) Post(base string, args map[string]string) (string, error)

func (*Client) Put

func (c *Client) Put(base string, args map[string]string) (string, error)

func (*Client) SellCargo

func (c *Client) SellCargo(shipID, good string, qty int) (*Order, error)

##ENDPOINT Sell cargo - `/my/sell-orders`

func (*Client) ShowFlight

func (c *Client) ShowFlight(flightID string) (*FlightPlan, error)

##ENDPOINT Show flight plans - `/my/flight-plans/FLIGHTID`

func (*Client) Status

func (c *Client) Status() error

##ENDPOINT Game status - `/game/status`

func (*Client) TakeLoan

func (c *Client) TakeLoan(name string) (*Loan, error)

##ENDPOINT Take out loan - `/my/loans`

type FlightPlan

type FlightPlan struct {
	ArrivesAt              time.Time `json:"arrivesAt"`
	CreatedAt              time.Time `json:"createdAt"`
	Departure              string    `json:"departure"`
	Destination            string    `json:"destination"`
	Distance               int       `json:"distance"`
	FuelConsumed           int       `json:"fuelConsumed"`
	FuelRemaining          int       `json:"fuelRemaining"`
	ID                     string    `json:"id"`
	ShortID                string
	ShipID                 string `json:"shipId"`
	ShortShipID            string
	TerminatedAt           time.Time `json:"terminatedAt"`
	TimeRemainingInSeconds int       `json:"timeRemainingInSeconds"`
}

func (*FlightPlan) Short

func (f *FlightPlan) Short() string

func (*FlightPlan) String

func (f *FlightPlan) String() string

type FlightPlanRes

type FlightPlanRes struct {
	FlightPlan FlightPlan `json:"flightPlan"`
}

type Loan

type Loan struct {
	Due                time.Time `json:"due"`
	ID                 string    `json:"id"`
	ShortID            string
	RepaymentAmount    int    `json:"repaymentAmount"`
	Status             string `json:"status"`
	Amount             int    `json:"amount"`
	CollateralRequired bool   `json:"collateralRequired"`
	Rate               int    `json:"rate"`
	TermInDays         int    `json:"termInDays"`
	Type               string `json:"type"`
}

Core types

func (*Loan) String

func (l *Loan) String() string

type LoanRes

type LoanRes struct {
	Loans []Loan `json:"loans"`
}

type Location

type Location struct {
	Symbol             string `json:"symbol"`
	Type               string `json:"type"`
	Name               string `json:"name"`
	SystemSymbol       string
	X                  int         `json:"x"`
	Y                  int         `json:"y"`
	AllowsConstruction bool        `json:"allowsConstruction"`
	Structures         []Structure `json:"structures"`
	Traits             []string    `json:"traits"`
	Messages           []string    `json:"messages,omitempty"`
}

func (*Location) Details

func (l *Location) Details(indent int) string

func (*Location) Distance

func (l *Location) Distance(l2 *Location) float64

func (*Location) Short

func (l *Location) Short(indent int) string

type LocationsRes

type LocationsRes struct {
	Locations []Location `json:"locations"`
}

type MarketplaceRes

type MarketplaceRes struct {
	Offers []Offer `json:"marketplace"`
}

type MyLoansRes

type MyLoansRes struct {
	Loans []Loan `json:"loans"`
}

type MyShipsRes

type MyShipsRes struct {
	Credits int    `json:"credits"`
	Ships   []Ship `json:"ships"`
}

type Offer

type Offer struct {
	Symbol               string `json:"symbol"`
	VolumePerUnit        int    `json:"volumePerUnit"`
	PricePerUnit         int    `json:"pricePerUnit"`
	Spread               int    `json:"spread"`
	PurchasePricePerUnit int    `json:"purchasePricePerUnit"`
	SellPricePerUnit     int    `json:"sellPricePerUnit"`
	QuantityAvailable    int    `json:"quantityAvailable"`
}

func (*Offer) String

func (o *Offer) String() string

type Order

type Order struct {
	Good         string `json:"good"`
	PricePerUnit int    `json:"pricePerUnit"`
	Quantity     int    `json:"quantity"`
	Total        int    `json:"total"`
}

type PayLoanRes

type PayLoanRes struct {
	Credits int    `json:"credits"`
	Loans   []Loan `json:"loans"`
}

type SellRes

type SellRes struct {
	Credits int   `json:"credits"`
	Order   Order `json:"order"`
	Ship    Ship  `json:"ship"`
}

type Ship

type Ship struct {
	Cargo             []Cargo `json:"cargo"`
	Class             string  `json:"class"`
	FlightPlanID      string  `json:"flightPlanId,omitempty"`
	ShortFlightPlanID string
	FlightPlanDest    string
	ID                string `json:"id"`
	ShortID           string
	LocationName      string `json:"location"`
	Manufacturer      string `json:"manufacturer"`
	MaxCargo          int    `json:"maxCargo"`
	LoadingSpeed      int    `json:"loadingSpeed"`
	Plating           int    `json:"plating"`
	SpaceAvailable    int    `json:"spaceAvailable"`
	Speed             int    `json:"speed"`
	Type              string `json:"type"`
	Weapons           int    `json:"weapons"`
	X                 int    `json:"x"`
	Y                 int    `json:"y"`
	PurchaseLocations []struct {
		System       string `json:"system"`
		LocationName string `json:"location"`
		Price        int    `json:"price"`
	} `json:"purchaseLocations"`
	RestrictedGoods []string `json:"restrictedGoods,omitempty"`
}

func (*Ship) Filter

func (s *Ship) Filter(word string) bool

func (*Ship) FuelNeeded

func (s *Ship) FuelNeeded(src, dest *Location) int

func (*Ship) Listing

func (s *Ship) Listing() string

func (*Ship) Short

func (s *Ship) Short() string

func (*Ship) Sidebar

func (s *Ship) Sidebar() string

func (*Ship) String

func (s *Ship) String() string

type ShipListingRes

type ShipListingRes struct {
	Ships []Ship `json:"shipListings"`
}

type StatusRes

type StatusRes struct {
	Status string `json:"status"`
}

JSON responses

type Structure

type Structure struct {
	ID       string `json:"id"`
	ShortID  string
	OwnedBy  User   `json:"ownedBy"`
	Type     string `json:"type"`
	Location string `json:"location"`
}

func (Structure) Details

func (st Structure) Details(indent int) string

type System

type System struct {
	Symbol    string     `json:"symbol"`
	Name      string     `json:"name"`
	Locations []Location `json:"locations"`
}

func (System) Details

func (s System) Details(indent int) string

func (System) String

func (s System) String() string

type SystemsRes

type SystemsRes struct {
	Systems []System `json:"systems"`
}

type TakeLoanRes

type TakeLoanRes struct {
	Credits int  `json:"credits"`
	Loan    Loan `json:"loan"`
}

type User

type User struct {
	Username       string    `json:"username"`
	Credits        int       `json:"credits"`
	JoinedAt       time.Time `json:"joinedAt"`
	Loans          []Loan    `json:"loans"`
	Ships          []Ship    `json:"ships"`
	ShipCount      int       `json:"shipCount"`
	StructureCount int       `json:"structureCount"`
}

func (*User) Short

func (u *User) Short() string

func (*User) String

func (u *User) String() string

Directories

Path Synopsis
cli

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL