(Note: The source code for this installment can be found here)

Switch statements allow us to control the flow of our football simulation.  In this installment, we will use a switch statement to control our players’ behavior.

As we said in the previous installment, we have the following positions in our game:

// offense
const QB int = 0
const RB int = 1
const WR int = 2
const OL int = 3

// defense
const DL int = 4
const LB int = 5
const DB int = 6

So we will put case statements in the doOffense() and doDefense() functions to control the actions. Let’s do the offense first.

func handlePlayerChannel(players

// panic()
A couple things to note here. Notice the panic() function in the default case. This causes the program to fail if something terrible happens. In this case, if we see a position we don’t understand, we want the program to fail.

So we run the program and see what we get.

Quarter back!
Running back!
Quarter back!
Running back!
Running back!
Running back!
Wide receivers!
Wide receivers!
Wide receivers!
Wide receivers!
Wide receivers!
Offensive lineman!
...

Great, we have 2 quarterbacks (which is expected), 4 running backs, and more. But what about the defense? Let’s add a second channel for defense, so instead of having all players fill the playerChan, they can fill the offPlayerChan and defPlayerChan.

// replace this
var playerChan = make(chan Player)

// with this
var offPlayerChan = make(chan Player)
var defPlayerChan = make(chan Player)

And while we’re at it, let’s change the doOffense() and doDefense() functions to use the appropriate channel.

func doOffense() {
	for _, player := range stallions.Players {
             offPlayerChan

And naturally we’ll need to add another Go routine to handle defense. So let’s make another modification.

// replace this
go handlePlayerChannel(playerChan)

// with this
go handleOffPlayerChannel(offPlayerChan)
go handleDefPlayerChannel(defPlayerChan)

And now I’ll update the handlePlayerChan to focus on offense only, and I’ll add a second channel to handle the defense.

func handleOffPlayerChannel(players

If I run the program again I see the right number of positions now.

Quarter back!
Running back!
Defensive line!
Running back!
Defensive line!
Wide receivers!
Defensive line!
Wide receivers!
Defensive line!
Wide receivers!
Line baker!
Wide receivers!
Line baker!
Wide receivers!
Line baker!
Defensive back!
Offensive lineman!
Defensive back!
Offensive lineman!
Defensive back!
Offensive lineman!
Defensive back!

// Summary
In this installment we were introduced to the switch statement which allows us to control the flow of behavior for our football teams. We also looked at the panic() function, which can be used for fatal exceptions.

In our next installment, we’re going to learn how to synchronize our player’s actions across multiple Go routines using the sync package.

Continue to part 5.