Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.mynumberspuzzle;
- import java.util.Random;
- public class Puzzle {
- // board size
- private int rows;
- private int cols;
- private Random rnd = new Random();
- // number of moves
- private int movesCount;
- // order of numbers on the game board
- private int[][] board;
- // postion of the blank
- private int blankRow, blankCol;
- public Puzzle(int rows, int cols) {
- this.rows = rows;
- this.cols = cols;
- board = new int[rows][cols];
- restart();
- }
- public void orderBoard() {
- for (int r = 0; r < rows; r++) {
- for (int c = 0; c < cols; c++) {
- board[r][c] = (r * cols + c + 1) % (rows * cols);
- }
- }
- blankRow = rows - 1;
- blankCol = cols - 1;
- }
- public void restart() {
- movesCount = 5;
- for (int r = 0; r < rows; r++) {
- for (int c = 0; c < cols; c++) {
- board[r][c] = r * cols + c;
- }
- }
- for (int s = 0; s < 20; s++) {
- int r1 = rnd.nextInt(rows);
- int c1 = rnd.nextInt(cols);
- int r2 = rnd.nextInt(rows);
- int c2 = rnd.nextInt(cols);
- swap(r1, c1, r2, c2);
- }
- }
- private void swap(int r1, int c1, int r2, int c2) {
- int temp = board[r1][c1];
- board[r1][c1] = board[r2][c2];
- board[r2][c2] = temp;
- if (board[r1][c1] == 0) {
- blankRow = r1;
- blankCol = c1;
- } else if (board[r2][c2] == 0) {
- blankRow = r2;
- blankCol = c2;
- }
- }
- public boolean move(int row, int col) {
- if (movesCount > 0) {
- boolean moveInSameRow = blankRow == row && (blankCol == col + 1 || blankCol == col - 1);
- boolean moveInSameCol = blankCol == col && (blankRow == row + 1 || blankRow == row - 1);
- if (moveInSameRow || moveInSameCol) {
- swap(row, col, blankRow, blankCol);
- movesCount--;
- return true;
- }
- }
- return false;
- }
- public boolean isGameOver() {
- for (int r = 0; r < rows; r++) {
- for (int c = 0; c < cols; c++) {
- if (board[r][c] != (r * cols + c + 1) % (rows * cols)) {
- return false;
- }
- }
- }
- return true;
- }
- public int getRows() {
- return rows;
- }
- public void setRows(int rows) {
- this.rows = rows;
- }
- public int getCols() {
- return cols;
- }
- public void setCols(int cols) {
- this.cols = cols;
- }
- public int getMovesCount() {
- return movesCount;
- }
- public void setMovesCount(int movesCount) {
- this.movesCount = movesCount;
- }
- public int[][] getBoard() {
- return board;
- }
- public void setBoard(int[][] board) {
- this.board = board;
- }
- public int getBlankRow() {
- return blankRow;
- }
- public void setBlankRow(int blankRow) {
- this.blankRow = blankRow;
- }
- public int getBlankCol() {
- return blankCol;
- }
- public void setBlankCol(int blankCol) {
- this.blankCol = blankCol;
- }
- }
Add Comment
Please, Sign In to add comment