Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- import java.util.Scanner;
- public class asd {
- static int row = 0;
- static int col = 0;
- static int numberOfMines = 0;
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- row = sc.nextInt();
- col = sc.nextInt();
- numberOfMines = sc.nextInt();
- sc.close();
- int[][] mineField = new int[row][col];
- placeMines(mineField);
- calcNumbers(mineField);
- countMines(mineField);
- printBoard(mineField);
- }
- public static void calcNumbers(int[][] mineFiled) {
- for (int i = 0; i < mineFiled.length; i++) {
- for (int j = 0; j < mineFiled[i].length; j++) {
- if (mineFiled[i][j] != 9) {
- mineFiled[i][j] = minesNear(mineFiled, i, j);
- }
- }
- }
- }
- public static int minesNear(int[][] mineFiled, int y, int x) {
- int mines = 0;
- // check mines in all directions
- mines += mineChecker(mineFiled, x - 1, y - 1); // NW
- mines += mineChecker(mineFiled, x - 1, y); // N
- mines += mineChecker(mineFiled, x - 1, y + 1); // NE
- mines += mineChecker(mineFiled, x, y - 1); // W
- mines += mineChecker(mineFiled, x, y + 1); // E
- mines += mineChecker(mineFiled, x + 1, y - 1); // SW
- mines += mineChecker(mineFiled, x + 1, y); // S
- mines += mineChecker(mineFiled, x + 1, y + 1); // SE
- if (mines > 0) {
- // we're changing an int to a char
- // why?!
- // http://www.asciitable.com/
- // 48 is ASCII code for '0'
- return mines;
- } else {
- return 0;
- }
- }
- public static int mineChecker(int[][] mineField, int x, int y) {
- if ((x >= 0 && x < row) && y >= 0 && y < col && mineField[x][y] == 9) {
- return 1;
- } else {
- return 0;
- }
- }
- public static void placeMines(int[][] mineField) {
- Random random = new Random();
- int minesPlaced = 0;
- while (minesPlaced < numberOfMines) {
- int x = random.nextInt(row);
- int y = random.nextInt(col);
- // make sure we don't place a mine on top of another
- if (mineField[y][x] != 9) {
- mineField[y][x] = 9;
- minesPlaced++;
- }
- }
- }
- public static void countMines(int[][] mineFiled) {
- int mines = 0;
- for (int i = 0; i < mineFiled.length; i++) {
- for (int j = 0; j < mineFiled[i].length; j++) {
- if (mineFiled[i][j] == 9)
- mines++;
- }
- }
- System.out.println(mines);
- }
- public static void printBoard(int[][] mineFiled) {
- for (int i = 0; i < mineFiled.length; i++) {
- for (int j = 0; j < mineFiled[i].length; j++) {
- System.out.print(mineFiled[i][j] + " ");
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement