我是初学程序员,我想让我的代码更有效率。我如何从PIECE1-PIECE 8最终整数和一个数组中取出一个数组 - image8。此外,我如何使用所述数组调用g.drawImage一次而不是8次。
public class GraphicalBoard extends Board {
final int PIECE1 = 1;
final int PIECE2 = 2;
final int PIECE3 = 3;
final int PIECE4 = 4;
final int PIECE5 = 5;
final int PIECE6 = 6;
final int PIECE7 = 7;
final int PIECE8 = 8;
final int NO_OF_PIECES = 8;
Image image1, image2, image3, image4, image5, image6, image7, image8;
final int SQUARE_SIZE = 200; // The length (in pixels) of the side of each
public GraphicalBoard() {
super();
loadResources();
}
private void loadResources() {
image1 = new ImageIcon("picOne.gif").getImage();
image2 = new ImageIcon("picTwo.gif").getImage();
image3 = new ImageIcon("picThree.gif").getImage();
image4 = new ImageIcon("picFour.gif").getImage();
image5 = new ImageIcon("picFive.gif").getImage();
image6 = new ImageIcon("picSix.gif").getImage();
image7 = new ImageIcon("picSeven.gif").getImage();
image8 = new ImageIcon("picEight.gif").getImage();
}
public void draw(Graphics g) {
// Draw the board with current pieces.
for (int row = 0; row < board.length; row++)
for (int column = 0; column < board[row].length; column++) {
// Find the x and y positions for each row and column.
int xPos = column * SQUARE_SIZE;
int yPos = row * SQUARE_SIZE;
if (board[row][column] == PIECE1)
g.drawImage(image1, xPos, yPos, null);
else if (board[row][column] == PIECE2)
g.drawImage(image2, xPos, yPos, null);
else if (board[row][column] == PIECE3)
g.drawImage(image3, xPos, yPos, null);
else if (board[row][column] == PIECE4)
g.drawImage(image4, xPos, yPos, null);
else if (board[row][column] == PIECE5)
g.drawImage(image5, xPos, yPos, null);
else if (board[row][column] == PIECE6)
g.drawImage(image6, xPos, yPos, null);
else if (board[row][column] == PIECE7)
g.drawImage(image7, xPos, yPos, null);
else if (board[row][column] == PIECE8)
g.drawImage(image8, xPos, yPos, null);
}
}
}
答案 0 :(得分:0)
使用数组可能不会使您的代码更有效,但更小,希望更好的可读性。
关于PIECES
- 你可以像这样初始化一个数组:
final int PIECES[] = new int[] {1,2,3,4,5,6,7,8};
我还会将图像文件命名为不同的名称。而不是picOne.gif
使用pic1.gif
等。然后您可以执行以下操作:
Image[] images = new Image[NO_OF_PIECES];
for(int i = 0; i < NO_OF_PIECES; i++)
images[i] = new ImageIcon("pic"+(i+1)+".gif").getImage();
什么是board
变量?
请注意,获取n维数组的长度可能有点棘手。 See here
在draw
方法中,为了更好的可读性,我会使用switch-case
代替else-if
。
还有计算:
int yPos = row * SQUARE_SIZE;
可以在第一个循环体中移动,但我想编译器很聪明,可以搞清楚。