Advertisement
Guest User

snake

a guest
Oct 22nd, 2019
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. package o1.snake
  2.  
  3. import o1._
  4. import scala.util.Random
  5. import SnakeGame._
  6.  
  7.  
  8. // This companion object provides aConstants and an utility function.
  9. object SnakeGame {
  10.  
  11. // The height and width of the game area, measured in squares that can hold
  12. // a single segment of a snake.
  13. val SizeInSquares = 40
  14.  
  15. // Randomly returns the position of a single square on the grid, excluding the
  16. // very edges (where no food can appear and which kill the snake if it enters).
  17. def randomLocationOnGrid() = {
  18. new GridPos(Random.nextInt(SizeInSquares - 2) + 1,
  19. Random.nextInt(SizeInSquares - 2) + 1)
  20. }
  21.  
  22. }
  23.  
  24.  
  25.  
  26. // Represents games of Snake. A SnakeGame object is mutable: it tracks the
  27. // position and heading of a snake as well as the position of a food item that
  28. // is available for the snake to eat next.
  29. class SnakeGame(initialPos: GridPos, initialHeading: CompassDir) {
  30.  
  31. private var segments = Vector(initialPos) // container: the locations of every segment of the snake, in order from head to tail
  32. var snakeHeading = initialHeading // most-recent holder (the direction most recently set for the snake)
  33. var nextFood = randomLocationOnGrid() // most-recent holder (a changing random location for the next available food item)
  34.  
  35. def snakeSegments = this.segments
  36.  
  37. def isOver: Boolean = {
  38. val head = this.segments.head
  39. val validCoords = 1 until SizeInSquares
  40. val collidedWithWall = (!validCoords.contains(head.x) || !validCoords.contains(head.y))
  41. val pom = segments.drop(1).exists(_==segments(0))
  42. val result = (collidedWithWall || pom)
  43. result
  44. }
  45. //val pom = segments.drop(1).exists(_==segments(0))
  46. //val result = (collidedWithWall && pom)
  47. //result
  48.  
  49. // This gets repeatedly called as the game progresses. It advances the snake by
  50. // one square in its current heading. In case the snake finds food, it grows by
  51. // one segment, the current nextFood vanishes and new food is placed in a random location.
  52. def advance() = {
  53. if(segments(0).neighbor(snakeHeading)==nextFood)
  54. {
  55. segments = segments(0).neighbor(snakeHeading) +: segments
  56. nextFood=randomLocationOnGrid()
  57. }
  58. else
  59. {
  60. // segments(0) = segments(0).neighbor(snakeHeading)
  61. // for (i <- 1 to segments.size-2 )
  62. // {
  63. // segments(i)=segments(i+1)
  64. // }
  65. var pom = segments.init
  66. pom = segments(0).neighbor(snakeHeading) +: pom
  67. segments=pom
  68. }
  69. }
  70.  
  71.  
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement