O'Reilly logo

Études for Elixir by J. David Eisenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 9. Processes

Étude 9-1: Using Processes to Simulate a Card Game

There is only one étude for this chapter. You’re going to write an Elixir program that lets the computer play the card game of “War” against itself.

The Art of War

These are the rules of the game as condensed from Wikipedia, adapted to two players, and simplified further.

Two players each take 26 cards from a shuffled deck. Each person puts her top card face up on the table. Whoever has the higher value card wins that battle, takes both cards, and puts them at the bottom of her stack. What happens if the cards have the same value? Then the players go to “war.” Each person puts the next two cards from their stack face down in the pile and a third card face up. High card wins, and the winner takes all the cards for the bottom of her stack. If the cards match again, the war continues with another set of three cards from each person. If a person has fewer than three cards when a war happens, he puts in all his cards.

Repeat this entire procedure until one person has all the cards. That player wins the game. In this game, aces are considered to have the highest value, and King > Queen > Jack.

War: What is it good for?

Absolutely nothing. Well, almost nothing. War is possibly the most incredibly inane card game ever invented. It is a great way for children to spend time, and it’s perfect as an étude because

  • it is naturally implementable as processes (players) passing messages (cards)
  • there is no strategy involved in the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required