您的位置:首页 > 其它

坦克大战1(坦克的绘图实现)

2014-03-03 00:52 357 查看
坦克绘图的实现比较简单,可以分解为三个矩形、一个圆形以及一条直线,如图所示:


在本代码中,主要是创建了TANK类、MyTank类、MyPanel类,其作用如下:

Tank类主要实现坦克的定义,其成员变量为其的横轴和纵轴的位置;

MyTank类主要定义我军的坦克,继承Tank;MyPanel类主要实现坦克的绘图实现;

最后将其加入到JFrame中,设计窗口的属性,让其显示,创建对象即可。

程序代码如下:

/**

* 功能:绘画一个坦克

*/

package com.text3_2;

import java.awt.*;

import javax.swing.*;

public class MyTankGame_1 extends JFrame{

MyPanel mypanel=null;

public static void main(String[] args) {

MyTankGame_1 mytankgame_1=new MyTankGame_1();

}

public MyTankGame_1()

{

mypanel=new MyPanel();

this.add(mypanel);

this.setSize(400,300);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setVisible(true);

}

}

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;

}

}

class MyTank extends Tank

{

public MyTank(int x,int y){

super(x,y);

}

}

class MyPanel extends JPanel

{

MyTank hero=null;

public void paint(Graphics g)

{

super.paint(g);

g.fillRect(0, 0, 400,300);

this.drawTank(hero.getX(), hero.getY(),g,0 ,0);

}

public MyPanel()

{

hero=new MyTank(10,10);

}

public void drawTank(int x,int y,Graphics g,int direction,int type)

{

switch(type)

{

case 0:g.setColor(Color.CYAN);

break;

case 1:g.setColor(Color.BLUE);

break;

}

switch(type)

{

//向上

case 0:g.fill3DRect(x, y, 5, 30, false);

g.fill3DRect(x+15, y, 5, 30, false);

g.fill3DRect(x+5, y+5, 10, 20, false);

g.fillOval(x+5, y+10, 10, 10);

g.drawLine(x+10, y+15, x+10, y+2);

break;

}

}

}

程序运行效果如下;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: