Java-坦克绘制(面向对象思想)
实现过程
public class Tank{
private int x;
private int y;
public Tank(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
public class Hero extends Tank{
public Hero(int x, int y) {
super(x, y);
}
}
class GameFrame extends JFrame {
GamePanel gamePanel = null;
public void draw() {
gamePanel = new GamePanel();
this.add(gamePanel);
this.setSize(1000, 800);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
- 坦克游戏绘制区域;
- 面向对象思想:在将坦克抽象为类后,通过实现drawTank(int x, int y, Graphics g, int direction, int type)方法来绘制多个坦克对象;
import javax.swing.*;
import java.awt.*;
class GamePanel extends JPanel {
Hero hero = null;
public GamePanel() {
hero = new Hero(100, 100);
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 1000, 800);
g.setFont(new Font("楷体", Font.BOLD, 32));
g.setColor(Color.RED);
g.drawString("TankGame V0.1", 60, 40);
drawTank(hero.getX(), hero.getY(), g, 0, 0);
drawTank(hero.getX() + 100, hero.getY(), g, 0, 1);
drawTank(hero.getX(), hero.getY() + 100, g, 0, 1);
drawTank(hero.getX() + 100, hero.getY() + 100, g, 0, 0);
}
public void drawTank(int x, int y, Graphics g, int direction, int type){
switch (type){
case 0://玩家坦克
g.setColor(Color.YELLOW);
break;
case 1://敌方坦克
g.setColor(Color.CYAN);
break;
}
switch (direction){
case 0://向上坦克
g.fill3DRect(x, y, 10, 60, false);
g.fill3DRect(x+34, y, 10, 60, false);
g.fill3DRect(x+10, y+10, 24, 40, false);
g.fillOval(x+10, y+18, 24, 24 );
g.fill3DRect(x+22, y, 2, 22, false);
break;
default:
System.out.println("未处理其他方向的坦克");
break;
}
}
}
绘制效果