Code one, get one free

I don't know about you, but I'm seeing double. The pseudocode to determine a chance to win and a chance to block looks exactly the same. That means we can probably combine the Win and Block checks into one efficient function. Let's give it a shot.

Start by combining the two ComputerTakeATurn lines from this:

 square = Win();
  if(square == null) square = Block();
  if(square == null) square = CreateTrap();
  if(square == null) square = PreventTrap();

Into this:

 square = WinOrBlock();
  if(square == null) square = CreateTrap();
  if(square == null) square = PreventTrap();

I'll confess that it took quite a bit of trial and error to write a working WinOrBlock() function. As with any code, there may be better ways to accomplish the same ...

Get Unity 4.x Game Development by Example Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.