Card.scala 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 size = DB.withConnection { implicit c =>
  15. SQL("select count(*) from words").single(long("count"))
  16. }
  17. def exists(word: String) = DB.withConnection { implicit c =>
  18. SQL("select * from words where lower(word) = lower({word})")
  19. .on('word -> word)
  20. .list(str("word"))
  21. .nonEmpty
  22. }
  23. def add(card: Card) = DB.withTransaction { implicit c =>
  24. val id = SQL("insert into words values (default, {word})")
  25. .on('word -> card.word)
  26. .executeInsert()
  27. id.map { id =>
  28. card.taboo.map { word =>
  29. SQL("insert into taboo values (default, {id}, {word})")
  30. .on('id -> id, 'word -> word)
  31. .executeInsert()
  32. }
  33. }
  34. }
  35. def list() = DB.withConnection { implicit c =>
  36. val list = SQL("""
  37. select words.id as id, words.word as word, taboo.word as taboo
  38. from words left join taboo on word_id = words.id
  39. """)
  40. .list(int("id") ~ str("word") ~ str("taboo") map flatten)
  41. mapToCard(list)
  42. }
  43. def mapToCard(seq: Seq[(Int, String, String)]) = {
  44. seq.groupBy(_._1).map {
  45. case (id, taboos) => Card(taboos.map(_._2).head, taboos.map(_._3).toSet)
  46. }.toList
  47. }
  48. }
  49. case class Card(word: String, taboo: Set[String]) {
  50. lazy val tabooRegex = (taboo + word).flatMap(compoundWords).map { word =>
  51. ("\\b"+word.toLowerCase+"\\b").r
  52. }
  53. def compoundWords(text: String): Seq[String] = {
  54. text.split(" ") :+ text.replace(" ", "")
  55. }
  56. def isTaboo(text: String) = {
  57. val lower = text.toLowerCase
  58. // check if text contains word or anything in taboo
  59. tabooRegex.map(!_.findFirstIn(lower).isEmpty).foldLeft(false)(_ || _)
  60. }
  61. def isCorrect(text: String) = {
  62. text.toLowerCase.indexOf(word.toLowerCase) >= 0
  63. }
  64. }
  65. object CardPool {
  66. import scala.util.Random
  67. def get() = DB.withConnection { implicit c =>
  68. val list = Card.list()
  69. CardPool(Random.shuffle(list))
  70. }
  71. }
  72. case class CardPool(list: List[Card]) {
  73. var index = 0
  74. def hasNext = list.size > index
  75. def next() = {
  76. val card = list(index)
  77. index += 1
  78. card
  79. }
  80. }