A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© sixth 中级黑马   /  2012-11-5 22:22  /  1083 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

import java.awt.*;
import java.awt.event.*;

public class TankGame extends Frame{
Hero hero = new Hero(280,550,0);

public static void main(String args[]) {
new TankGame();
}

public TankGame() {
this.setSize(600,600);
this.setBackground(Color.BLACK);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}       
});
this.setVisible(true);
this.addKeyListener(new KeyMonitor());
}

public void paint(Graphics g) {
//画出主坦克
g.setColor(Color.YELLOW);
switch(hero.direct) {
case 0:
g.fill3DRect(hero.x, hero.y, 10, 40,false );
g.fill3DRect(hero.x+30, hero.y, 10, 40, false);
g.fill3DRect(hero.x+10, hero.y+10, 20, 20, false);
g.fillOval(hero.x+15, hero.y+10, 10, 10);
g.fillRect(hero.x+18, hero.y, 4, 10);
break;
case 1:
g.fill3DRect(hero.x, hero.y, 40, 10,false );
g.fill3DRect(hero.x, hero.y+30, 40, 10, false);
g.fill3DRect(hero.x+10, hero.y+10, 20, 20, false);
g.fillOval(hero.x+20, hero.y+15, 10, 10);
g.fillRect(hero.x+30, hero.y+18, 10, 4);
break;
case 2:
g.fill3DRect(hero.x, hero.y, 10, 40,false );
g.fill3DRect(hero.x+30, hero.y, 10, 40, false);
g.fill3DRect(hero.x+10, hero.y+10, 20, 20, false);
g.fillOval(hero.x+15, hero.y+20, 10, 10);
g.fillRect(hero.x+18, hero.y+30, 4, 10);
break;
case 3:
g.fill3DRect(hero.x, hero.y, 40, 10,false );
g.fill3DRect(hero.x, hero.y+30, 40, 10, false);
g.fill3DRect(hero.x+10, hero.y+10, 20, 20, false);
g.fillOval(hero.x+10, hero.y+15, 10, 10);
g.fillRect(hero.x, hero.y+18, 10, 4);
break;
}
repaint();
}

class KeyMonitor extends KeyAdapter {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_W) {
hero.setDirect(0);
hero.moveUp();
}
else if(e.getKeyCode() == KeyEvent.VK_D) {
hero.setDirect(1);
hero.moveRight();
}
else if(e.getKeyCode() == KeyEvent.VK_S) {
hero.setDirect(2);
hero.moveDown();
}
else if(e.getKeyCode() == KeyEvent.VK_A) {
hero.setDirect(3);
hero.moveLeft();
}
}       
}
}

坦克类:

public class Tank {
int x,y;
int speed = 2;
int direct;

Tank(int x,int y) {
this.x = x;
this.y = y;
}

public int getDirect() {
return direct;
}
public void setDirect(int direct) {       
this.direct = direct;
}

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 Hero extends Tank {
public Hero(int x,int y,int direct) {
super(x,y);
this.direct = direct;
}
public void moveUp() {
y -= speed;
}

public void moveRight() {
x += speed;
}

public void moveDown() {
y += speed;
}

public void moveLeft() {
x -= speed;
}
}

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 赞一个!

查看全部评分

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马