Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * NOTE: THIS IS THE MAIN METHOD
- */
- package chessboard;
- public class ChessBoardMain {
- public static void main(String[] args) {
- int moves = Integer.parseInt(args[0]);
- Coordinate start = new Coordinate(0,0);
- Knight knight = new Knight(start);
- for(int j=0; j < 10; ++j){
- for(int i=0; i<moves; ++i){
- knight.move(knight);
- }
- Coordinate end = knight.getPos();
- System.out.println("(" + end.getX() + "," + end.getY() + ")");
- }
- }
- }
- /*
- * NOTE: COORDINATE CLASS
- */
- package chessboard;
- public class Coordinate {
- private int x;
- private int y;
- public Coordinate(int x, int y){
- this.x = x;
- this.y = y;
- }
- public int getX(){
- return x;
- }
- public int getY(){
- return y;
- }
- }
- /*
- * NOTE: KNIGHT CLASS, THIS IS THE MAIN BRAIN OF THE PROGRAM
- */
- package chessboard;
- import java.util.ArrayList;
- public class Knight {
- private Coordinate currentPos;
- public Knight(Coordinate currentPos){
- this.currentPos = currentPos;
- }
- public void move(Knight knight){
- Coordinate movePos = currentPos;
- int x = movePos.getX();
- int y = movePos.getY();
- ArrayList<Integer> validMove = new ArrayList<Integer>();
- if (isValid(x - 2, y + 1)) {
- validMove.add(0);
- }
- if (isValid(x - 1, y + 2)) {
- validMove.add(1);
- }
- if (isValid(x + 2, y + 2)) {
- validMove.add(2);
- }
- if (isValid(x + 2, y + 1)) {
- validMove.add(3);
- }
- if (isValid(x + 2, y - 1)) {
- validMove.add(4);
- }
- if (isValid(x + 1, y - 2)) {
- validMove.add(5);
- }
- if (isValid(x - 1, y - 2)) {
- validMove.add(6);
- }
- if (isValid(x - 2, y - 1)) {
- validMove.add(7);
- }
- int indexRand = (int) (Math.random()*(validMove.size() - 1));
- int numOption = validMove.get(indexRand);
- switch(numOption){
- case 0: currentPos = new Coordinate(x-2,y+1);
- break;
- case 1: currentPos = new Coordinate(x-1,y+2);
- break;
- case 2: currentPos = new Coordinate(x+1,y+2);
- break;
- case 3: currentPos = new Coordinate(x+2,y+1);
- break;
- case 4: currentPos = new Coordinate(x+2,y-1);
- break;
- case 5: currentPos = new Coordinate(x+1,y-2);
- break;
- case 6: currentPos = new Coordinate(x-1,y-2);
- break;
- case 7: currentPos = new Coordinate(x-2,y-1);
- break;
- }
- }
- public boolean isValid(int x, int y) {
- if(x <= 8 && y <= 8 && x >= 0 && y>=0){
- return true;
- }
- else return false;
- }
- public boolean contains(int n, int[] array){
- for(int i=0; i < array.length; ++i){
- if(array[i] == n){
- return true;
- }
- }
- return false;
- }
- public Coordinate getPos(){
- return currentPos;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement