Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Exam20200628;
- import java.util.Arrays;
- import java.util.Scanner;
- public class Snake {
- public static int food = 0;
- public static int newRow = 0;
- public static int newCol = 0;
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int n = Integer.parseInt(scanner.nextLine());
- char[][] field = new char[n][n];
- int snakeRow = 0;
- int snakeCol = 0;
- for (int i = 0; i < n; i++) {
- String line = scanner.nextLine();
- if (line.contains("S")) {
- snakeRow = i;
- snakeCol = line.indexOf("S");
- }
- char[] input = line.toCharArray();
- field[i] = input;
- }
- while (food < 10) {
- String direction = scanner.nextLine();
- if (direction.equals("up")) {
- // row --
- newRow = snakeRow - 1;
- newCol = snakeCol;
- } else if (direction.equals("down")) {
- // row ++
- newRow = snakeRow + 1;
- newCol = snakeCol;
- } else if (direction.equals("left")) {
- //col --
- newRow = snakeRow;
- newCol = snakeCol - 1;
- } else if (direction.equals("right")) {
- // col ++
- newRow = snakeRow;
- newCol = snakeCol + 1;
- }
- if (isOutOfBounds(newRow, newCol, field)) {
- field[snakeRow][snakeCol] = '.';
- System.out.println("Game over!");
- break;
- }
- if (field[newRow][newCol] == '*') {
- food++;
- }
- // burrow marked with 'B'
- else if (field[newRow][newCol] == 'B') {
- moovefromStartToTheExitOfBurrow(n, field);
- }
- field[snakeRow][snakeCol] = '.';
- field[newRow][newCol] = 'S';
- snakeRow = newRow;
- snakeCol = newCol;
- }
- if (food >= 10) {
- System.out.println("You won! You fed the snake.");
- }
- System.out.printf("Food eaten: %d%n", food);
- for (char[] symbol : field) {
- for (char c : symbol) {
- System.out.print(c);
- }
- System.out.println();
- }
- }
- public static void moovefromStartToTheExitOfBurrow(int n, char[][] field) {
- field[newRow][newCol] = '.';
- for (int row = newRow + 1; row < n; row++) {
- for (int col = 0; col < field[row].length; col++) {
- if (field[row][col] == 'B') {
- newRow = row;
- newCol = col;
- }
- }
- }
- }
- private static boolean isOutOfBounds(int row, int col, char[][] field) {
- return row < 0 || row >= field.length
- || col < 0 || col >= field[row].length;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement