Saturday, November 6, 2010

Validating user inputs… oh no you didn’t!

One of the challenges we decided to take on in this project is to allow the user to interact with the game through the console. This was not something that was in the original Java version, so it involved a bit more than just porting over code from one language to another.

Allowing the user to enter information means that validation was going to be necessary. Like many other languages, Scala allows for the use of regular expressions as a common way to check data. However, there are a few implementations that Scala allows for which are not typical in other languages.
 
Pattern emailParser = Pattern.compile("([\\w\\d\\-\\_]+)(\\+\\d+)?@([\\w\\d\\-\\.]+)"); 

String s = "zippy@scalaisgreat.com";
Matcher m = emailParser.matcher(s);
if (m.matches())
{
String name = m.group(1);
String num = m.group(2);
String domain = m.group(3);

System.out.printf("Name: [%s], Num: [%s], Domain: [%s]\n", name, num, domain);
}

//**********************************//

val EmailParser = """([\w\d\-\_]+)(\+\d+)?@([\w\d\-\.]+)""".r
val s = "zippy@scalaisgreat.com"
val EmailParser(name, num, domain) = s
printf("Name: %s, Domain: %s\n", name, domain)

//**********************************//

if (Pattern.compile("\\d+").matcher("abc 123 @#$").find) println("ok")



The following format was used in our implementation to take in the user input on the command prompt and validated it using Regular Expressions:

def readConsole{
println("Type \"Quit\" if you would like to end the game")
println("Enter position to move from and to in \"[A-H][1-8] [A-H][1-8]\" format:")
val positionParser = "([A-H])([1-8]) ([A-H])([1-8])".r
val s = Console.readLine

s.toUpperCase match {
// check user entered position in (Col1, Row1, Col2, Row2) format
case positionParser(cy1, cx1, cy2, cx2) => {
print("You entered to move from ")
printf("Col:%s Row:%s to Col:%s Row:%s", cy1, cx1, cy2, cx2)
println

// convert user entered X values to int
val x1 = cx1.toInt
val x2 = cx2.toInt

// lookup the user entered values for Y and find their respective position in colConversionArray
val y1 = colConversionArray.indexOf(cy1)+1
val y2 = colConversionArray.indexOf(cy2)+1

makeMove(y1, x1, y2, x2
)
}

// If user enters 'quit' (case insensitive), then sets the userQuit flag to true and prints message
case "QUIT" => {
userQuit = true
println("Thanks for playing Scala Checkers!")
}

// Catch all non-matching entries
case _ => println ("Incorrect position, try again")
}

No comments:

Post a Comment