Advertisement
Guest User

Untitled

a guest
Jan 27th, 2015
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | None | 0 0
  1. import java.util.Random;
  2. public class KnightsTour1 {
  3.  
  4.     int[][] board = new int[8][8];
  5.     int[] horizontal = {1, 2, 2, 1, -1, -2, -2, -1};
  6.     int[] vertical = {-2, -1, 1, 2, 2, 1, -1, -2};
  7.     int row = 0;
  8.     int col = 0;
  9.     int end = 0;
  10.    
  11.     public void start () {
  12.         board[row][col] = 1;
  13.     }
  14.     public void play () {
  15.         Random dhanya = new Random ();
  16.         for (int i = 2; i <= 64; i++) {
  17.             int random = dhanya.nextInt(8);
  18.             if (row + horizontal[random] < 0 || row + horizontal[random] > 7 || col + vertical[random] < 0 || col + vertical[random] > 7 || board[row + horizontal[random]][col + vertical[random]] != 0) {
  19.                 for (int j = 1; j < 8; j++) {
  20.                     if (row + horizontal[j] < 0 || row + horizontal[j] > 7 || col + vertical[j] < 0 || col + vertical[j] > 7 || board[row + horizontal[j]][col + vertical[j]] != 0) {
  21.                         if (j == 8) {
  22.                             end = i;
  23.                             i = 64;
  24.                         }
  25.                     }
  26.                     else {
  27.                         row = row + horizontal[j];
  28.                         col = col + vertical[j];
  29.                         board[row][col] = i;
  30.                         end = i;
  31.                         break;
  32.                     }
  33.                 }
  34.             }
  35.             else {
  36.                 row = row + horizontal[random];
  37.                 col = col + vertical[random];
  38.                 board[row][col] = i;
  39.                 end = i;
  40.             }
  41.         }
  42.  
  43.     }
  44.  
  45.     public void printTable() {
  46.         for (int i = 0; i <= 8; i++) {
  47.             if (i == 0) {
  48.                 System.out.printf("%4s", " ");
  49.             }
  50.             else
  51.             System.out.printf("%4d", i);
  52.         }
  53.         System.out.println();
  54.         for (int row = 0; row < board.length; row++) {
  55.             System.out.printf("%4d", row + 1);
  56.             for (int col = 0; col < board[row].length; col++) {
  57.                 System.out.printf("%4d", board[row][col]);
  58.             }
  59.             System.out.println();
  60.         }
  61.         System.out.println("\t" + end + " Squares Were Visited.");
  62.     }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement