Chained movement

 from Red Blob Games

Problem: two characters in a roguelike are chained together. If the chain is slack, they can move freely, but if the chain is taut they will pull each other along. Figure out a movement algorithm that handles this, including the chain not going through obstacles.

Keys: HJKL or arrows to move, and S to swap which end you are controlling.

The main idea is that the taut part of the chain pulls each chain section along like the game “Snake”, but the slack part of the chain remains in the same place. I tried several versions of this before I found something I liked, and the version I ended up with was much simpler than the intermediate versions, so I’m quite happy about that. The algorithm here will move the chain sections to previously occupied areas, so it has no trouble with static obstacles, corridors, rooms, etc. Try walking around the small obstacle at the bottom. To see the algorithm, use View Source and then look at the moveChainLeftEnd function.

There are situations that this simple algorithm doesn’t handle. For example, form an almost-complete square, and then keep moving around the square. Our intuition says the chain should be slack but this algorithm considers it to be taut. Diagonals might help; I don’t know. The algorithm looks locally at the parts of the chain, but in this case the chain is globally slack but not locally.

Email me , or tweet @redblobgames, or comment: