?? wagon.java
字號:
import java.awt.*;public class Wagon { // Constants to represent the direction of the Wagon private final int LEFT = 0; private final int RIGHT = 1; private final int UP = 2; private final int DOWN = 3; // The size of the wagon private final int SIZE = 8; private int xPos, yPos; private int direction; //The speed of the wagon private final int SPEED = 5; public Wagon(int x, int y) { xPos = x; yPos = y; direction = UP; } //To change the facing direction of the wagon. public void faceUp(){ direction = UP; } public void faceDown(){ direction = DOWN; } public void faceLeft(){ direction = LEFT; } public void faceRight(){ direction = RIGHT; } //To move the wagon public void move(Rectangle boundary){ if(direction == UP && yPos - SIZE > boundary.y){ yPos -= SPEED; }else if(direction == DOWN && yPos + SIZE < boundary.y + boundary.height){ yPos += SPEED; }else if(direction == LEFT && xPos - SIZE > boundary.x){ xPos -= SPEED; }else if(direction == RIGHT && xPos + SIZE < boundary.x + boundary.width){ xPos += SPEED; } } //Pass the current position of the wagon public int getX(){ return xPos - SIZE; } public int getY(){ return yPos - SIZE; } public int getSize(){ return SIZE; } // Display the wagon. The direction the wagon is facing // is indicated by a narrow rectangle. public void draw(Graphics g) { // Draw the main body of the wagon g.setColor(Color.blue); g.fillRect(xPos-SIZE, yPos-SIZE, 2*SIZE, 2*SIZE); g.setColor(Color.black); g.drawRect(xPos-SIZE, yPos-SIZE, 2*SIZE, 2*SIZE); // Calculate the position of the direction indicator Rectangle directionIndicator; if (direction == UP) { directionIndicator = new Rectangle(xPos-SIZE+2, yPos-SIZE+2, 2*SIZE-4, 3); } else if (direction == DOWN) { directionIndicator = new Rectangle(xPos-SIZE+2, yPos+SIZE-5, 2*SIZE-4, 3); } else if (direction == LEFT) { directionIndicator = new Rectangle(xPos-SIZE+2, yPos-SIZE+2, 3, 2*SIZE-4); } else { directionIndicator = new Rectangle(xPos+SIZE-5, yPos-SIZE+2, 3, 2*SIZE-4); } // Draw the direction indicator g.setColor(Color.white); g.fillRect(directionIndicator.x, directionIndicator.y, directionIndicator.width, directionIndicator.height); g.setColor(Color.black); g.drawRect(directionIndicator.x, directionIndicator.y, directionIndicator.width, directionIndicator.height); }}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -