# Barter system data type

My game has 4 supplies, Gold Wheat Iron Fuel, a player is allowed to select a supply to trade and what supply to receive from merchant NPCs.

Currently, when the user trades an item I have the following logic I am using c# but this is not the exact code used.

if(sellGold){
}
}
}
else if(sellIron){
}
}
}
...etc


Where the amount a player receives is calculated by multiplying the trade ratio by the amount sold.

This works, it is just rather tedious and would be a pain to add more supplies later. What would a better approach be? I'm thinking of assigning each item a value and that value is different based on the trade type, but that still involves a whole bunch of nested conditionals.

• What programming language are you working with? My first thought is you could make this easier using a new Enum type, but what you can and cannot do with Enum's will depend a lot on the programming language. – Tartle Wizard Dec 5 '16 at 22:36
• @Sys_Admin_Luddite c# edited the question to include that – kalenpw Dec 5 '16 at 22:41

It's going to be much easier if you use currency to express all prices. It doesn't have to appear in game, just something used to express the underlying value of all these supplies. Then add a buy/sell offset (or spread). Trade ratios can be calculated by dividing those prices.

For example, if we have goldBid = 1.23, goldAsk = 1.25, wheatBid = 0.34, wheatAsk = 0.38, then selling 1 gold for wheat gives you 1.23 / 0.38 = 3.23 wheat, and doing the reverse (selling 1 wheat for gold) gives you 0.34 / 1.25 = 0.27 gold.

Using a currency is not only simpler, it helps you avoid pricing mistakes that inadvertantly lead to negative cycles that can be arbitraged (a.k.a. "free money"). For example, what happens if you can trade 1 gold for 2 wheat, and 1 wheat for 2 gold?

But if you want to express all your prices manually, as is often the case in inefficient markets, the usual representation is a weighted directed graph, where edge weights represent trade prices. But a simpler representation would be a matrix, like this one:

Then you can just read off values in the matrix to get the trade ratios. In code you can represent this as a 2D array, where the dimensions are the number of assets you have.

• Using a matrix (either 2D array or nested dictionaries) would also allow you to define these values external to the game, like in a data file. This means you can make changes without a recompile (Or allow users to add new resources and/or exchange rates for modding). – MichaelHouse Dec 5 '16 at 23:36
• Thanks for the answer, I'll use the currency with Bid and Ask prices. I do like the Pokemon matrix though – kalenpw Dec 6 '16 at 0:05
• FYI the matrix is definitely more flexible, for example you can set up a situation where it's cheaper to trade A -> B -> C than A -> C (imagine if the wheat seller really doesn't want to buy gold). Depends on whether you want that extra game mechanic. – congusbongus Dec 6 '16 at 4:30