Final beautification

Now that everything else is done and the code is working correctly, it is time for the last refactoring before we start our enhancement. We want our methods to be as small as possible. In this case, that means that the Play function should have practically no logic outside the main game loop.

In general, if a method has any kind of block in it (for example, if, while, for, and so on), we want that block to be the only thing in the method. Often, there are also guard statements checking input, but that should be it. Let's refactor to follow that convention and see what the code looks like afterwards.

 In the file Mastermind.cs:

public class Mastermind
{
private readonly IInputOutput _inout;
private int _tries;

public Mastermind(IInputOutput inout)
{
_inout = inout;
}

public void Play(string password = null)
{
password = password ?? CreateRandomPassword();
var correctPositions = 0;

while (correctPositions != 4)
{
correctPositions = GuessPasswordAndCheck(password);
}

_inout.WriteLine("Congratulations you guessed the password in " +
_tries + " tries.");
}

private int GuessPasswordAndCheck(string password)
{
var guess = Guess();
return Check(guess, password);
}

private int Check(string guess, string password)
{
var checkResult = "";

for (var x = 0; x < 4; x++)
{
if (guess[x] == password[x])
{
checkResult += "+";
}
else if (password.Contains(guess[x]))
{
checkResult += "-";
}
}

_inout.WriteLine(checkResult);
return checkResult.Count(c => c == '+');
}

private string Guess()
{
_tries = _tries + 1;

_inout.Write("Take a guess: ");
var guess = _inout.ReadLine();

if (guess.Length == 4)
{
return guess.ToUpper();
}

// Password guess was wrong size - Error Message
_inout.WriteLine("Password length is 4.");
return Guess();
}

private string CreateRandomPassword()
{
// Initialize randomness
Random rand = new Random(DateTime.Now.Millisecond);

var password = new[] { 'A', 'A', 'A', 'A' };

var j = 0;

password_loop:
password[j] = (char)(rand.Next(6) + 65);
j = j + 1;

if (j < 4) goto password_loop;

return password.ToString();
}
}

There are many ways that this code could have been refactored; this is just one. Now that the code is refactored, we are ready to move on and begin working on enhancements.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.115.131