Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class KnightsTourMK2
- {
- int[][] board = new int[9][9];
- //board[1][1] = 1;
- int[][] moves = {{0, 1, 2, 2, 1 , -1, -2, -2, -1},
- {0, -2, -1, 1, 2, 2, 1, -1, -2}};
- int counter = 2;
- public KnightsTourMK2()
- {
- board[1][1]= 1;
- }
- public void move(int counter, int x, int y)
- {
- int moveTo = (int)( Math.random() * 8 + 1);
- if(!checkSpots(x, y))
- return;
- while(!validMove(x, y, moveTo)){
- moveTo = (int)( Math.random() * 8 + 1);
- }
- board[x][y] = counter;
- x += moves[0][moveTo];
- y += moves[1][moveTo];
- move(++counter, x, y);
- }
- public Boolean checkSpots(int x, int y)
- {
- //going through 8 positions to check
- for(int i = 1; i < 9; i++){
- if(validMove(x, y, i))
- return true;
- }
- return false;
- }
- public Boolean validMove(int x, int y, int move)
- {
- if(x + moves[0][move] <= 0 || x + moves[0][move] >= 9)
- return false;
- if(y + moves[1][move] <= 0 || y + moves[1][move] >= 9)
- return false;
- if(board[x + moves[0][move]][y + moves[1][move]]!= 0)
- return false;
- return true;
- }
- public void printBoard(){
- System.out.println(" 1 2 3 4 5 6 7 8");
- for(int i = 1; i < 9; i++)
- {
- System.out.print(i + " ");
- for(int j = 1; j < 9; j++)
- {
- if(board[i][j] < 10)
- System.out.print(" " + board[i][j]);
- else
- System.out.print(" " + board[i][j]);
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement