Advertisement
IvaAnd

Snake

Oct 22nd, 2020
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.00 KB | None | 0 0
  1. package Exam20200628;
  2.  
  3. import java.util.Arrays;
  4. import java.util.Scanner;
  5.  
  6. public class Snake {
  7.  
  8. public static int food = 0;
  9. public static int newRow = 0;
  10. public static int newCol = 0;
  11. public static void main(String[] args) {
  12.  
  13. Scanner scanner = new Scanner(System.in);
  14.  
  15. int n = Integer.parseInt(scanner.nextLine());
  16.  
  17. char[][] field = new char[n][n];
  18.  
  19. int snakeRow = 0;
  20. int snakeCol = 0;
  21.  
  22. for (int i = 0; i < n; i++) {
  23. String line = scanner.nextLine();
  24.  
  25. if (line.contains("S")) {
  26. snakeRow = i;
  27. snakeCol = line.indexOf("S");
  28. }
  29. char[] input = line.toCharArray();
  30. field[i] = input;
  31.  
  32. }
  33.  
  34. while (food < 10) {
  35. String direction = scanner.nextLine();
  36.  
  37. if (direction.equals("up")) {
  38. // row --
  39. newRow = snakeRow - 1;
  40. newCol = snakeCol;
  41.  
  42. } else if (direction.equals("down")) {
  43. // row ++
  44. newRow = snakeRow + 1;
  45. newCol = snakeCol;
  46.  
  47.  
  48. } else if (direction.equals("left")) {
  49. //col --
  50. newRow = snakeRow;
  51. newCol = snakeCol - 1;
  52.  
  53.  
  54. } else if (direction.equals("right")) {
  55. // col ++
  56. newRow = snakeRow;
  57. newCol = snakeCol + 1;
  58.  
  59.  
  60. }
  61. if (isOutOfBounds(newRow, newCol, field)) {
  62. field[snakeRow][snakeCol] = '.';
  63. System.out.println("Game over!");
  64. break;
  65. }
  66. if (field[newRow][newCol] == '*') {
  67. food++;
  68. }
  69. // burrow marked with 'B'
  70. else if (field[newRow][newCol] == 'B') {
  71. moovefromStartToTheExitOfBurrow(n, field);
  72. }
  73.  
  74. field[snakeRow][snakeCol] = '.';
  75. field[newRow][newCol] = 'S';
  76. snakeRow = newRow;
  77. snakeCol = newCol;
  78.  
  79.  
  80. }
  81. if (food >= 10) {
  82. System.out.println("You won! You fed the snake.");
  83. }
  84. System.out.printf("Food eaten: %d%n", food);
  85.  
  86. for (char[] symbol : field) {
  87. for (char c : symbol) {
  88. System.out.print(c);
  89. }
  90. System.out.println();
  91. }
  92.  
  93. }
  94.  
  95. public static void moovefromStartToTheExitOfBurrow(int n, char[][] field) {
  96. field[newRow][newCol] = '.';
  97. for (int row = newRow + 1; row < n; row++) {
  98. for (int col = 0; col < field[row].length; col++) {
  99. if (field[row][col] == 'B') {
  100. newRow = row;
  101. newCol = col;
  102. }
  103. }
  104.  
  105. }
  106. }
  107.  
  108. private static boolean isOutOfBounds(int row, int col, char[][] field) {
  109. return row < 0 || row >= field.length
  110. || col < 0 || col >= field[row].length;
  111. }
  112.  
  113. }
  114.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement