Following is the SV code for knight tour. On each randomisation, we get the next position of knight.
The concept is simple, based on which we derived the constraints.
- knight should operate within boundaries of the chess board.
- knight can move on any direction if it does not violate point (1).
- The position of the knight can be taken as row, col.
- At best it can move in 8 directions
- If row is incremented/decremented by 2 positions, column can move 1 position from the latest row pos.
- If row is incremented/decremented by 1 position, column can move 2 position from the latest row pos.
- The position is calculated based on the board length, current row and column.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | class knight_walk; parameter int N = 5; int row; int col; rand int next_row; rand int next_col; rand int pos; function new (); row = $urandom_range(0,N-1); col = $urandom_range(0,N-1); pos = N*row + col; $display(" INITIAL POS:%0d ROW:%0d COL:%0d",pos,row,col); endfunction constraint c_knight { solve next_row before next_col; next_row inside { row+2,row-2,row+1,row-1 }; next_col inside { col+2,col-2,col+1,col-1 }; next_row inside {[0:4]}; next_col inside {[0:4]}; if( next_row inside {row+2,row-2} ) { next_col inside {col+1,col-1}; } else { next_col inside {col+2,col-2}; } } function void post_randomize(); row = next_row; col = next_col; pos = row*N+col; $display("POST_RANDOMIZE:: POS:%0d ROW:%0d COL:%0d",pos,row,col); endfunction endclass: knight_walk module top; knight_walk chess; initial begin chess = new; repeat(4) void'(chess.randomize()); end endmodule: top |
INITIAL POS:3 ROW:0 COL:3
POST_RANDOMIZE:: POS:12 ROW:2 COL:2
POST_RANDOMIZE:: POS:19 ROW:3 COL:4
POST_RANDOMIZE:: POS:8 ROW:1 COL:3
POST_RANDOMIZE:: POS:1 ROW:0 COL:1
POST_RANDOMIZE:: POS:8 ROW:1 COL:3
POST_RANDOMIZE:: POS:1 ROW:0 COL:1
POST_RANDOMIZE:: POS:8 ROW:1 COL:3
POST_RANDOMIZE:: POS:1 ROW:0 COL:1
POST_RANDOMIZE:: POS:8 ROW:1 COL:3
POST_RANDOMIZE:: POS:11 ROW:2 COL:1
V C S S i m u l a t i o n R e p o r t