Advertisement
Guest User

Snake.scala

a guest
Nov 15th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.29 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.     val 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.indices) {
  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.     val nextPos = body.head + dir
  59.     val growagain = nbrOfStepsSinceReset%growEvery
  60.  
  61.    // if (ÄPPLEPOSITION.isOccupyingBlockAt(nextPos)) grow()
  62.     if (growagain == 0) grow()
  63.     else if (nbrOfStepsSinceReset < startGrowingAfter) shrink()
  64.     else grow()
  65.     nbrOfStepsSinceReset += 1
  66.  
  67.   } // väx och krymp enl. regler; action om äter frukt
  68.  
  69.   def draw(): Unit = {
  70.     game.drawBlock(body.head.x, body.head.y, headColor)
  71.     body.tail.foreach(pos => game.drawBlock(pos.x, pos.y, tailColor))
  72.   }
  73.  
  74.   def erase(): Unit = {
  75.     body.foreach(pos => game.drawBlock(pos.x, pos.y, game.background))
  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