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 goal, but this is the solution I painstakingly arrived at. I will step through the conclusions I reached in building this function. As you read, picture the mountains of crumpled-up paper and torn-out hair that led to this amazing breakthrough...