Advertisement
Guest User

Snake.scala

a guest
Nov 14th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.22 KB | None | 0 0
  1. package snake
  2.  
  3. class Snake (
  4.   val initPos: Pos,
  5.   val initDir: Dir,
  6.   val headColor: java.awt.Color,
  7.   val tailColor: java.awt.Color,
  8.   val game: SnakeGame
  9. ) extends CanMove {
  10.   var dir: Dir = initDir
  11.  
  12.   val initBody: List[Pos] = List(initPos + initDir, initPos)
  13.  
  14.   val body: scala.collection.mutable.Buffer[Pos] = initBody.toBuffer
  15.  
  16.   val initTailSize: Int = 10 // välj själv vad som är lagom svårt
  17.  
  18.    var nbrOfStepsSinceReset = 0
  19.    val growEvery = 10
  20.    val startGrowingAfter = 400
  21.    var nbrOfApples = 0
  22.  
  23.   def reset(): Unit = {
  24.     body.remove(0, body.length)
  25.     initBody.indices.foreach(i => body.append(initBody(i)))
  26.   }
  27.        // återställ starttillstånd, ge rätt svanslängd
  28.  
  29.   def grow(): Unit = {    //koden är skriven som så att huvudet ligger vid index (0)!
  30.     var nextPos = body.head + dir
  31.     body.prepend(nextPos)
  32.  
  33.   }    // väx i rätt riktning med extra svansposition
  34.  
  35.   def shrink(): Unit = {
  36.     if (body.length > 2) body.drop(1).last
  37.   } // krymp svansen om kroppslängden är större än 2
  38.  
  39.   def isOccupyingBlockAt(p: Pos): Boolean = {
  40.     // body.contains(p)
  41.     var checkBody = false
  42.     for (i <- body.length) {
  43.       if (p == i) checkBody = true
  44.     }
  45.     checkBody
  46.   }    // kolla om p finns i kroppen
  47.  
  48.   def isHeadCollision(other: Snake): Boolean = {
  49.     body.head == other.body.head
  50.   } // kolla om huvudena krockar
  51.  
  52.   def isTailCollision(other: Snake): Boolean = {
  53.     if (other.body.tail.contains(body.head)) true
  54.     else false
  55.   } // mitt huvud i annans svans
  56.  
  57.   def move(): Unit = {
  58.     var nextPos = body.head + dir
  59.     if ("äpple position".isOccupyingBlockAt(nextPos)) grow()
  60.     if (nbrOfStepsSinceReset < startGrowingAfter) shrink()
  61.     nbrOfStepsSinceReset += 1
  62.  
  63.   } // väx och krymp enl. regler; action om äter frukt
  64.  
  65.   def draw(): Unit = {
  66.     game.drawBlock(body.head.x, body.head.y, headColor)
  67.     for (i <- 1 until body.length) {
  68.       game.drawBlock(i, i, tailColor)
  69.     }
  70.   }
  71.  
  72.   def erase(): Unit = {
  73.     for(i <- 0 to body.length){
  74.     game.drawBlock(body(i).x, body(i).y, game.background)
  75.     }
  76.   }
  77.  
  78.   override def toString =  // bra vid println-debugging
  79.     body.map(p => (p.x, p.y)).mkString(">:)", "~", s" going $dir")
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement