Advertisement
Guest User

Untitled

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