Advertisement
Guest User

snek

a guest
Nov 15th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 6.81 KB | None | 0 0
  1. import scalafx.Includes._
  2. import scalafx.application.JFXApp
  3. import scalafx.scene.Scene
  4. import scalafx.scene.canvas._
  5. import scalafx.event.ActionEvent
  6. import scalafx.scene.control._
  7. import scalafx.scene.input._
  8. import scalafx.scene.image._
  9. import scalafx.scene.paint._
  10. import scalafx.animation._
  11. import scalafx.scene.shape._
  12. import scalafx.scene.image._
  13. import scalafx.scene.layout._
  14. import scalafx.scene.Group
  15. import io.Source
  16. import java.io.{PrintWriter, FileNotFoundException}
  17.  
  18. var scores = try{
  19.   val scoreSource = Source.fromFile("snakeScores.txt")
  20.   val scoreLines = scoreSource.getLines
  21.     val scores = scoreLines.map(score => HighScore(score.substring(0,score.indexOf(",")).toInt, score.substring(score.indexOf(",")+1))).toArray
  22.   scoreSource.close
  23.   scores
  24. } catch {
  25.   case e:FileNotFoundException => Array.fill(10)(HighScore(0, ""))
  26. }  
  27.  
  28. val sWidth = 600
  29. val sHeight = 600
  30.  
  31. var gameOver = false
  32. var direction = "up"
  33.  
  34. case class HighScore(score:Int, name:String)
  35. var currentScore = 0
  36.  
  37. val app = new JFXApp {
  38.   stage = new JFXApp.PrimaryStage {
  39.     title = "*+:。.。* Snake *。.。:+*"
  40.     scene = new Scene(sWidth, sHeight) {
  41.             val bg = new ImageView("https://i.imgur.com/F2wDuiV.png")
  42.  
  43.       val nameField = new TextField
  44.       nameField.layoutX = 150; nameField.layoutY = 400
  45.       nameField.promptText = "Enter your name!"
  46.             nameField.visible = false
  47.  
  48.             //snakeHead WxL = 17x17
  49.             //val snakeHead = Rectangle(17,17)
  50.             //snakeHead.fill = Color.rgb(87,81,77)
  51.       val snakeHead = new ImageView("https://i.imgur.com/yYqa1Mk.png")
  52.       snakeHead.layoutX = 300
  53.       snakeHead.layoutY = 300
  54.    
  55.             var snakeTail = List[ImageView](new ImageView("https://i.imgur.com/yYqa1Mk.png"))
  56.             snakeTail.foreach(img => img.visible = false)
  57.  
  58.             val gameOverImg = new ImageView("https://i.imgur.com/kCfn9EY.png")     
  59.             gameOverImg.visible = false
  60.  
  61.             //initial score label  
  62.             val scoreLabel = new Label(currentScore.toString)
  63.             scoreLabel.textFill = Color.rgb(87,81,77)
  64.       scoreLabel.style = "-fx-font-size: 23pt"
  65.             scoreLabel.layoutX = 18
  66.             scoreLabel.layoutY = 3
  67.  
  68.             def overlaps(square1:ImageView, square2:ImageView): Boolean = {
  69.                 val dx = square1.layoutX.value-square2.layoutX.value
  70.                 val dy = square1.layoutY.value-square2.layoutY.value
  71.                 dx*dx+dy*dy <= (17+17)*(17+17)
  72.                 }      
  73.  
  74.             //moves "forward" based on direction        
  75.             def move(dir:String, u:ImageView):Unit = {
  76.                 direction = dir
  77.                 if (dir == "up") u.layoutY = u.layoutY.value - 17
  78.                 else if (dir == "down") u.layoutY = u.layoutY.value + 17
  79.                 else if (dir == "left") u.layoutX = u.layoutX.value - 17
  80.                 else if (dir == "right") u.layoutX = u.layoutX.value + 17
  81.             }
  82.  
  83.             //pear WxL = 14x17
  84.             val pear = new ImageView("https://i.imgur.com/liCzXUT.png")
  85.             //val pear = Rectangle(15, 15); pear.fill = Color.Green
  86.             pear.layoutX =  50 + scala.util.Random.nextInt(500)
  87.             pear.layoutY = 50 + scala.util.Random.nextInt(500)
  88.  
  89.             val moveInterval = 0.1
  90.             var delaySum = 0.0
  91.       var lastTime = 0L
  92.             val snakeSpeed = 9.0
  93.       val timer = AnimationTimer(t => {
  94.                 val delta = (t - lastTime)/1e9
  95.         if (lastTime > 0) {
  96.                     delaySum += delta
  97.                     //movement:
  98.             if (!gameOver && delaySum > moveInterval){
  99.                         onKeyPressed = (ke: KeyEvent) => {
  100.                     ke.code match {
  101.                     case KeyCode.Up => if (direction != "up" && direction != "down") move("up", snakeHead)
  102.                     case KeyCode.Down => if (direction != "down" && direction != "up") move("down", snakeHead)
  103.                     case KeyCode.Left => if (direction != "left" && direction != "right") move("left", snakeHead)
  104.                     case KeyCode.Right => if (direction != "right" && direction != "left") move("right", snakeHead)
  105.                     case _ =>
  106.                             }
  107.                         }
  108.                         val newTail = new ImageView("https://i.imgur.com/yYqa1Mk.png")
  109.                         newTail.layoutX = snakeHead.layoutX.value
  110.                         newTail.layoutY = snakeHead.layoutY.value
  111.  
  112.                         content += newTail
  113.                         content -= snakeTail.last
  114.                         snakeTail = newTail :: snakeTail.init
  115.                         move(direction, snakeHead)
  116.                         delaySum = 0.0
  117.                     }
  118.                 }
  119.                 lastTime = t
  120.  
  121.                 //check for intersection:
  122.                 //if (!Shape.intersect(snakeHead, pear).boundsInLocal.value.isEmpty){
  123.                 if(overlaps(snakeHead, pear)){
  124.                     snakeTail.foreach(img => img.visible = true)
  125.  
  126.                     //add to the tail/body
  127.                     val newTail = new ImageView("https://i.imgur.com/yYqa1Mk.png")
  128.                     newTail.layoutX = snakeHead.layoutX.value
  129.                     newTail.layoutY = snakeHead.layoutY.value
  130.  
  131.                     content += newTail
  132.                     snakeTail = newTail :: snakeTail
  133.  
  134.             //spawn a new pear
  135.                     pear.layoutX = 50 + scala.util.Random.nextInt(550)
  136.             pear.layoutY = 50 + scala.util.Random.nextInt(550)
  137.  
  138.                     //update score if you intersect
  139.                     currentScore += 100
  140.                     scoreLabel.text.update(currentScore.toString)
  141.         }
  142.  
  143.                 for (i <- snakeTail.indices){
  144.                     if (overlaps(snakeHead, snakeTail(i))) gameOver = true
  145.                 }
  146.  
  147.                 //ends game if you run into the edge of the window
  148.                 if (snakeHead.layoutX.value >= 600-17 || snakeHead.layoutX.value <= 0 || snakeHead.layoutY.value <= 0 || snakeHead.layoutY.value >= 600-17) gameOver = true
  149.        
  150.                 if (gameOver){
  151.                     gameOverImg.visible = true
  152.  
  153.                     nameField.visible = true
  154.                    
  155.                     scores ++= Array(HighScore(currentScore, nameField.text.value))
  156.  
  157.                     //sorting the scores
  158.                     def insertionSort(a:Array[HighScore]):Unit = {
  159.                         for (i <- 1 until a.length){
  160.                             var j = i - 1
  161.                             var temp = a(i)
  162.                             while( j >= 0 && temp.score < a(j).score){
  163.                                 a(j+1) = a(j)
  164.                                 j -= 1
  165.                             }
  166.                             a(j+1) = temp
  167.                         }
  168.                     }
  169.                     insertionSort(scores)
  170.                     scores = scores.reverse
  171.  
  172.                     //saving the top 10 scores to "snakeScores.txt"
  173.                     val PW = new PrintWriter("snakeScores.txt")
  174.                     if (scores.length > 10){
  175.                         for (i <- 0 to 9) PW.println(scores(i).score + "," + scores(i).name)
  176.                     }
  177.                     else{
  178.                         for (i <- scores.indices) PW.println(scores(i).score + "," + scores(i).name)
  179.                         for (i <- 1 to 10 - scores.length) PW.println("0,NONE")
  180.                     }
  181.                     PW.close
  182.  
  183.                     //resets the game (if you press Enter)
  184.                     onKeyPressed = (ke: KeyEvent) => {
  185.                         if (ke.code == KeyCode.Enter){
  186.                             gameOver = false
  187.                             gameOverImg.visible = false
  188.                             nameField.visible = false
  189.                             currentScore = 0
  190.                             scoreLabel.text.update(currentScore.toString)
  191.                             snakeHead.layoutX = 300
  192.                             snakeHead.layoutY = 300
  193.                             snakeTail = List[ImageView](new ImageView("https://i.imgur.com/yYqa1Mk.png")); snakeTail.foreach(img => img.visible = false)
  194.                             direction = "up"
  195.                         }
  196.                     }
  197.                 }                
  198.       })
  199.       timer.start  
  200.  
  201.       content ++= List(bg, snakeHead, scoreLabel, pear, nameField, gameOverImg)
  202.             content ++= snakeTail.map(_.delegate)
  203.       fill = Color.rgb(209, 237, 255)
  204.     }
  205.   }
  206. }
  207.  
  208. app.main(args)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement