Advertisement
Guest User

Untitled

a guest
Dec 14th, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. package game
  2.  
  3. import java.io.File
  4. import java.util.Scanner
  5. import scala.collection.mutable.ArrayBuffer
  6.  
  7. /** Handles read/write from/to Disk.
  8. * Reading uses java.util.Scanner
  9. * Writing uses java.io
  10. */
  11. object Disk {
  12.  
  13. def loadLines() = {
  14. val fromFile = new File("score.txt" )
  15. val result: ArrayBuffer[String] = new ArrayBuffer[String](0)
  16. val scanner = new Scanner(fromFile)
  17. while(scanner.hasNextLine) {
  18. val line = scanner.nextLine
  19. if (!(line eq "")){
  20. result.append(line)
  21. }
  22. }
  23. result.toVector
  24. }
  25.  
  26. def personalScore(name: String) = {
  27. loadAllResults().filter(_._1 equals name)
  28. }
  29.  
  30. def loadAllResults() = {
  31. val output = loadLines().map(str => {
  32. val data = str.split(',')
  33. (data(0),data(1), data(2))
  34. })
  35. output.sortBy(_._2.toInt).reverse
  36. }
  37.  
  38. def appendResult(playerName: String, points: Int, time: Int, fileName: String) = {
  39. saveString("", "score.txt")
  40. val fullString = (loadLines() :+ (s"$playerName,$points,$time")).mkString("\n")
  41. saveString(fullString, fileName)
  42. }
  43.  
  44. /** Save `text` to a text file called `fileName`. */
  45. private def saveString(text: String, fileName: String): Unit = {
  46. val f = new java.io.File(fileName)
  47. val pw = new java.io.PrintWriter(f, "UTF-8")
  48. try pw.write(text) finally pw.close()
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement