Advertisement
Guest User

Untitled

a guest
Jan 26th, 2015
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 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 = 1;
  8.     int col = 1;
  9.    
  10.     public void start () {
  11.         board[row][col] = 1;
  12.     }
  13.     public void play () {
  14.         Random dhanya = new Random ();
  15.         for (int i = 1; i <= 64; i++) {
  16.             int random = dhanya.nextInt(8) + 1;
  17.             if (row + horizontal[random] < 1 || row + horizontal[random] > 8 || col + vertical[random] < 1 || col + vertical[random] > 8 || board[row + horizontal[random]][col + vertical[random]] != 0) {
  18.                 for (int j = 1; j <= 8; j++) {
  19.                     if (row + horizontal[random] < 1 || row + horizontal[random] > 8 || col + vertical[random] < 1 || col + vertical[random] > 8 || board[row + horizontal[random]][col + vertical[random]] != 0) {
  20.                         if (j == 8) {
  21.                             break;
  22.                         }
  23.                     }
  24.                     else {
  25.                         row = row + horizontal[j];
  26.                         col = col + horizontal[j];
  27.                         board[row][col] = i;
  28.                     }
  29.                 }
  30.             }
  31.             else {
  32.                 row = row + horizontal[random];
  33.                 col = col + horizontal[random];
  34.                 board[row][col] = i;
  35.             }
  36.         }
  37.  
  38.     }
  39.  
  40.     public void printTable() {
  41.         for (int row = 0; row < board.length; row++) {
  42.             for (int col = 0; col < board[row].length; col++) {
  43.                 System.out.printf("%4d", board[row][col]);
  44.             }
  45.             System.out.println();
  46.         }
  47.     }
  48.  
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement