Skip to content

Instantly share code, notes, and snippets.

@Yord
Created August 20, 2012 20:00
Show Gist options
  • Save Yord/3407278 to your computer and use it in GitHub Desktop.
Save Yord/3407278 to your computer and use it in GitHub Desktop.
Little Multiple Choice Programm
import util.Random
import io.Source
object MultipleChoice extends App {
implicit def colorString(string: String) = new ColoredString(string)
val buffer = Source fromFile "mc.txt"
val Line = """^([wf]):(.+)$""".r
val questions = buffer.getLines flatMap (_ match {
case Line(answer, text) => Some(Question(0, answer head, text))
case _ => None
})
clear()
loop(questions toList)
def loop(questions: List[Question]) {
val sorted = questions sortBy { case Question(correct, _, _) => (correct, Random nextInt) }
val (top5, rest) = sorted splitAt 5
val top5shuffled = Random shuffle top5
val question @ Question(correct, answer, text) = top5shuffled.head
val isCorrect = ask(question)
val updatedQuestion = if (isCorrect) question.succeeded else question.failed
loop(updatedQuestion :: top5shuffled.tail ::: rest)
}
def ask(question: Question): Boolean = {
val Question(_, answer, text) = question
println("Eingeben: wahr -> w, falsch -> f, quit -> q\n\n"+text.blue)
val isCorrect = Console readChar match {
case 'q' => System exit 1; false
case c: Char => answer == c
}
clear()
val correct = if (isCorrect) "richtig" else "falsch"
val coloredText = if (answer == 'w') text.green else text.red
println("Deine Antwort war %s!\n%s\n\n\n".format(correct, coloredText))
return isCorrect
}
def clear(): Unit = (0 to 100) foreach (_ => println(""))
case class Question(correct: Int, answer: Char, text: String) {
def succeeded = Question(correct+1, answer, text)
def failed = Question(correct-1, answer, text)
}
class ColoredString(string: String) {
def blue = Console.BLUE+string+Console.RESET
def green = Console.GREEN+string+Console.RESET
def red = Console.RED+string+Console.RESET
}
}
// "mc.txt" file syntax:
// w:Die Klasse String ist final.
// f:Jede Klasse besitzt einen Namen.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment