//Chess Board game: Tour of knight
//Java how to program, 5/e, Exercise 7.22
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TourOfKnight extends JApplet implements ActionListener {
int currentRow, currentColumn,number,loopCounter=0,count=1;
int[] moveNumber={0,1,2,3,4,5,6,7};
int[] vertical={-1,-2,-2,-1,1,2,2,1};
int[] horizontal={2,1,-1,-2,-2,-1,1,2};
int[][] chessBoard;
int sentinel=0;
JLabel TourLabel;
JTextArea output;
JButton playButton;
public void init()
{
Container container=getContentPane();
container.setLayout(new FlowLayout());
TourLabel= new JLabel("Game of Tour of Knight:");
container.add(TourLabel);
playButton= new JButton("Play");
container.add(playButton);
playButton.addActionListener(this);
output=new JTextArea();
output.setFont(new Font("Monospaced",Font.PLAIN,12));
container.add(output);
chessBoard=new int[8][8];
for (int i=0;i<=7;i++)
for (int j=0;j<=7;j++)
chessBoard[i][j]=0;
}
public void actionPerformed (ActionEvent event)
{
output.setText("");
output.append("The first location is: "+"["+Integer.toString(currentRow)+","
+Integer.toString(currentColumn)+"] ");
chessBoard[0][0]=1;
sentinelCalculate();
while (sentinel>0)
{
knightMove(currentRow,currentColumn,number);
//output.append("Next location is: "+"["+Integer.toString(currentRow)+","
//+Integer.toString(currentColumn)+"] ");
sentinelCalculate();
loopCounter++;
}
output.append("The last location is: "+"["+Integer.toString(currentRow)+","
+Integer.toString(currentColumn)+"] ");
output.append("The loop counter is: "+Integer.toString(loopCounter)+" ");
for (int i=0;i<=7;i++)
{
for (int j=0;j<=7;j++)
{if(chessBoard[i][j]>=10)
output.append(Integer.toString(chessBoard[i][j])+" ");
else
output.append(Integer.toString(chessBoard[i][j])+" ");}
output.append(" ");
}
//output.append("The second location is: "+"["+Integer.toString(currentRow)+","
// +Integer.toString(currentColumn)+"] ");
output.append("Total pace is: "+Integer.toString(count)+" ");
}
public void knightMove(int row, int column,int number)
{
count++;
chessBoard[currentRow][currentColumn]=count;
}
public int knightMoveCheck(int row, int column, int argument)
{
currentRow=row+=vertical[argument];
currentColumn=column+=horizontal[argument];
if (0<=row&&row<=7&&0<=column&&column<=7)
{
if (chessBoard[currentRow][currentColumn]==0)
{number=argument;
return 1;}
else
{
currentRow=row-=vertical[argument];
currentColumn=column-=horizontal[argument];
return 0;
}
}
else
{
currentRow=row-=vertical[argument];
currentColumn=column-=horizontal[argument];
}
return 0;
}
public int sentinelCalculate()
{
for (int i=0;i<=7;i++)
{
sentinel=knightMoveCheck(currentRow,currentColumn,i);
if (sentinel>0)
break;
}
return sentinel;
}
}