Castles
A competitive logic puzzle useful for teaching.
Overview
This project is inspired by an entry of FiveThirtyEight.com's weekly Riddler puzzle column:
In a distant, war-torn land, there are 10 castles. There are two warlords: you and your archenemy. Each castle has its own strategic value for a would-be conqueror. Specifically, the castles are worth 1, 2, 3, ..., 9, and 10 victory points. You and your enemy each have 100 soldiers to distribute, any way you like, to fight at any of the 10 castles. Whoever sends more soldiers to a given castle conquers that castle and wins its victory points. If you each send the same number of troops, you split the points. You don't know what distribution of forces your enemy has chosen until the battles begin. Whoever wins the most points wins the war.
For more info, see the original post here and the results of the Riddler Nation battle royale here.
Usage
Install the Package
npm install --save castles
BattlePlans
A BattlePlan
is an allocation of armies, plus some additional metadata. Two BattlePlan
s can fight according to the rules above:
const castles = require('castles')
const allToCastleTen = new castles.BattlePlan({
allocations: [0, 0, 0, 0, 0, 0, 0, 0, 0, 100],
name: 'All to Castle Ten',
author: 'Samples'
})
const allToCastleOne = new castles.BattlePlan({
allocations: [100, 0, 0, 0, 0, 0, 0, 0, 0, 0],
name: 'All to Castle One',
author: 'Samples'
})
t.is(allToCastleTen.fight(allToCastleOne), 'win')
t.is(allToCastleOne.fight(allToCastleTen), 'lose')
t.is(allToCastleTen.fight(allToCastleTen), 'tie')
Armies
An Army
has a BattlePlan
, plus a running record:
const castles = require('castles')
const allToCastleTen = new castles.Army(castles.sampleBattlePlans.allToCastleTen)
const allToCastleOne = new castles.Army(castles.sampleBattlePlans.allToCastleOne)
allToCastleTen.fight(allToCastleOne)
t.is(allToCastleTen.record, '1-0-0')
t.is(allToCastleOne.record, '0-1-0')
t.is(allToCastleTen.wins, 1)
t.is(allToCastleTen.losses, 0)
t.is(allToCastleTen.ties, 0)
t.is(allToCastleTen.score, 1)
War
Tying it all together, we can have each Army
fight each other Army
exactly once with the .war(...)
function:
const castles = require('castles')
const allBattlePlans = castles.sampleBattlePlans.all
const allArmies = allBattlePlans.map(battlePlan => new castles.Army(battlePlan))
const sortedArmies = castles.war(allArmies)
const winner = sortedArmies[0]
t.is(winner.battlePlan.name, 'All to Castle Ten')
t.is(winner.record, '2-0-0')
t.is(winner.score, 2)