Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class KnightProject {
- /**
- * Program: KnightProject.java
- * Purpose: Knight move problem for Yahoo! Answers
- * Creator: Chris Clarke
- * Ceated: 01.06.2015
- */
- /*
- Print out a board with the size entered by user and the knight starting position entered by user.
- Then move the knight 3 steps from it's starting position.
- The knight's move should be labelled as 0(starting position), 1, 2, etc.
- */
- public static int size;
- public static int currRow, currCol;
- public static int moveCount = 0;
- public static int[][] board;
- public static boolean canGo(int r, int c) {
- if (r>=1 && r<=size && c>=1 && c<=size)
- return true;
- return false;
- }
- public static void makeMove(int r, int c) {
- board[r][c] = ++moveCount;
- currRow = r;
- currCol = c;
- }
- public static void displayBoard() {
- for (int r=1; r<=size; r++) {
- for (int c=1; c<=size; c++) {
- if (board[r][c] == -1) {
- System.out.print(".");
- } else {
- System.out.print(board[r][c]);
- } // if
- } // for c
- System.out.println();
- } // for r
- System.out.println();
- }
- public static void chooseMove(int r, int c) {
- // there are up to 8 possible knight moves
- if (canGo(r-2, c-1)) makeMove(r-2, c-1); // 1
- else if (canGo(r-2,c+1)) makeMove(r-2, c+1); // 2
- else if (canGo(r-1,c+2)) makeMove(r-1, c+2); // 3
- else if (canGo(r+1,c+2)) makeMove(r+1,c+2); // 4
- else if (canGo(r+2,c+1)) makeMove(r+2,c+1); // 5
- else if (canGo(r+2,c-1)) makeMove(r+2,c-1); // 6
- else if (canGo(r+1,c-2)) makeMove(r+1,c-2); // 7
- else if (canGo(r-1,c-2)) makeMove(r-1,c-2); // 8
- }
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- System.out.print("What size board would you like? ");
- size = scan.nextInt();
- board = new int[size+1][size+1];
- for (int r=1; r<=size; r++) {
- for (int c=1; c<=size; c++) {
- board[r][c] = -1;
- } // for c
- } // for r
- System.out.print("Place knight on which row (1-"+size+")? ");
- currRow = scan.nextInt();
- System.out.print("Place knight on which column (1-"+size+")? ");
- currCol = scan.nextInt();
- board[currRow][currCol] = 0;
- for (int i=0; i<3; i++) {
- chooseMove(currRow, currCol);
- displayBoard();
- } // for
- } // main()
- } // class KnightProject
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement