1
0

Card.scala 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package models
  2. import anorm._
  3. import anorm.SqlParser._
  4. import play.api.db._
  5. import play.api.libs.json._
  6. import play.api.Play.current
  7. object Card {
  8. implicit val writes = new Writes[Card] {
  9. def writes(o: Card) = Json.obj(
  10. "word" -> o.word,
  11. "taboo" -> o.taboo
  12. )
  13. }
  14. def add(card: Card) = DB.withTransaction { implicit c =>
  15. val id = SQL("insert into words values (default, {word})")
  16. .on('word -> card.word)
  17. .executeInsert()
  18. id.map { id =>
  19. card.taboo.map { word =>
  20. SQL("insert into taboo values (default, {id}, {word})")
  21. .on('id -> id, 'word -> word)
  22. .executeInsert()
  23. }
  24. }
  25. }
  26. def list() = DB.withConnection { implicit c =>
  27. val list = SQL("""
  28. select words.word as word, taboo.word as taboo
  29. from words left join taboo on word_id = words.id
  30. """)
  31. .list(str("word") ~ str("taboo") map flatten)
  32. mapToCard(list)
  33. }
  34. def mapToCard(seq: Seq[(String, String)]) = {
  35. seq.groupBy(_._1).map {
  36. case (word, taboos) => Card(word, taboos.map(_._2).toSet)
  37. }.toList
  38. }
  39. }
  40. case class Card(word: String, taboo: Set[String]) {
  41. lazy val tabooRegex = (taboo + word).map { word =>
  42. ("\\b"+word.toLowerCase+"\\b").r
  43. }
  44. def isTaboo(text: String) = {
  45. val lower = text.toLowerCase
  46. // check if text contains word or anything in taboo
  47. tabooRegex.map(!_.findFirstIn(lower).isEmpty).foldLeft(false)(_ || _)
  48. }
  49. def isCorrect(text: String) = {
  50. text.toLowerCase.indexOf(word.toLowerCase) >= 0
  51. }
  52. }
  53. object CardPool {
  54. import scala.util.Random
  55. def get() = DB.withConnection { implicit c =>
  56. val list = Card.list()
  57. CardPool(Random.shuffle(list))
  58. }
  59. }
  60. case class CardPool(list: List[Card]) {
  61. var index = 0
  62. def hasNext = list.size > index
  63. def next() = {
  64. val card = list(index)
  65. index += 1
  66. card
  67. }
  68. }