Advertisement
gluten_free_feeling

dfasdf

Feb 9th, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1.  
  2. public class KnightsTourMK2
  3. {
  4. int[][] board = new int[9][9];
  5. //board[1][1] = 1;
  6. int[][] moves = {{0, 1, 2, 2, 1 , -1, -2, -2, -1},
  7. {0, -2, -1, 1, 2, 2, 1, -1, -2}};
  8. int counter = 2;
  9. public KnightsTourMK2()
  10. {
  11. board[1][1]= 1;
  12. }
  13. public void move(int counter, int x, int y)
  14. {
  15. int moveTo = (int)( Math.random() * 8 + 1);
  16. if(!checkSpots(x, y))
  17. return;
  18.  
  19. while(!validMove(x, y, moveTo)){
  20. moveTo = (int)( Math.random() * 8 + 1);
  21. }
  22. board[x][y] = counter;
  23. x += moves[0][moveTo];
  24. y += moves[1][moveTo];
  25. move(++counter, x, y);
  26. }
  27. public Boolean checkSpots(int x, int y)
  28. {
  29. //going through 8 positions to check
  30. for(int i = 1; i < 9; i++){
  31. if(validMove(x, y, i))
  32. return true;
  33.  
  34. }
  35. return false;
  36. }
  37. public Boolean validMove(int x, int y, int move)
  38. {
  39. if(x + moves[0][move] <= 0 || x + moves[0][move] >= 9)
  40. return false;
  41. if(y + moves[1][move] <= 0 || y + moves[1][move] >= 9)
  42. return false;
  43. if(board[x + moves[0][move]][y + moves[1][move]]!= 0)
  44. return false;
  45. return true;
  46. }
  47. public void printBoard(){
  48. System.out.println(" 1 2 3 4 5 6 7 8");
  49. for(int i = 1; i < 9; i++)
  50. {
  51. System.out.print(i + " ");
  52. for(int j = 1; j < 9; j++)
  53. {
  54. if(board[i][j] < 10)
  55. System.out.print(" " + board[i][j]);
  56. else
  57. System.out.print(" " + board[i][j]);
  58. }
  59. System.out.println();
  60. }
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement