Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- abstract class Game {
- def start(): Unit
- def print(board: Iterable[Int]): Unit = {
- val listToString = board.map(elem => "%2d".format(elem)).map(elem => if (elem == " 0") " " else elem)
- listToString.sliding(4, 4).map(line => line.mkString(" | ", " | ", " | ")).foreach(line => println(line))
- }
- def selectionOfGame2(input: String): Unit = {
- while (true) {
- val string = Console.readLine("Вы прошли эту игру!!!\n Играть заново : введите 'replay'" +
- " \n Выбрать другую игру: введите 'otherGame' ")
- this.input(string) match {
- case Some(g) => g.start()
- case None => println("Ты ебанулся, такой игры нету!")
- }
- }
- }
- def input(input: String): Option[Game] = {
- input match {
- case "15" => Some(new Game15())
- case "2048" => Some(new Game2048())
- case x => None
- }
- }
- def parseInput(input: String): Option[Direction] = {
- input match {
- case "j" => Some(Down)
- case "k" => Some(Up)
- case "h" => Some(Left)
- case "l" => Some(Right)
- case x =>
- println("wrong input")
- None
- }
- }
- }
- class Game15 extends Game {
- def start(): Unit = {
- val board = shuffleBoard(winBoard, 1)
- play(board)
- }
- val n = 4
- type Board = List[Int]
- val winBoard = (1 to n * n - 1).toList :+ 0
- def play(b: Board): Unit = {
- print(b)
- parseInput(Console.readLine()) match {
- case Some(d) =>
- val moved = move(b, d)
- if (moved != winBoard) {
- play(moved)
- }
- else if (b == winBoard) {
- print(b)
- println("Win")
- }
- case None =>
- println("h - Left\nj - Up\nh - Left\nl - Right")
- play(b)
- }
- }
- def shuffleBoard(b: Board, moves: Int): Board = {
- if (moves == 0) {
- b
- }
- else {
- val d = Random.shuffle(List(Up, Down, Left, Right)).head
- val moved = move(b, d)
- shuffleBoard(moved, moves - 1)
- }
- }
- def move(b: Board, d: Direction): Board = {
- d match {
- case Up => moveU(b)
- case Down => moveD(b)
- case Left => moveL(b)
- case Right => moveR(b)
- }
- }
- def moveD(b: Board): Board = {
- val index = b.indexOf(0)
- val down = index + n
- if (index <= 11) {
- swap(b, index, down)
- }
- else b
- }
- def moveU(b: Board): Board = {
- val index = b.indexOf(0)
- val up = index - n
- if (index > n - 1) {
- swap(b, index, up)
- }
- else b
- }
- def moveL(b: Board): Board = {
- val index = b.indexOf(0)
- val left = index - 1
- if (index % n != 0) {
- swap(b, index, left)
- }
- else b
- }
- def moveR(b: Board): Board = {
- val index = b.indexOf(0)
- val right = index + 1
- if (index % n != 3) {
- swap(b, index, right)
- }
- else b
- }
- def swap(board: Board, idx1: Int, idx2: Int): Board = {
- val elem1 = board(idx1)
- val elem2 = board(idx2)
- board.updated(idx1, elem2).updated(idx2, elem1)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement