复制代码
1 /**
2 * 坦克游戏的1.0版
3 * 1.画出坦克
4 *
5 */
6 package com.test1;
7
8 import javax.swing.*;
9 import java.awt.*;
10
11 import javax.swing.JFrame;
12
13 public class MyTankGame1 extends JFrame {
14
15 MyPanel mp = null;
16 public static void main(String[] args) {
17 MyTankGame1 myTankGame1 = new MyTankGame1();
18 }
19 //构造函数
20 public MyTankGame1(){
21 mp = new MyPanel();
22 this.add(mp);
23 this.setSize(400,300);
24 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
25 this.setVisible(true);
26
27 }
28
29 }
30 //我的面板
31 class MyPanel extends Panel{
32 //定义一个我的坦克
33 Hero hero = null; //创建工作放在构造函数
34 public MyPanel(){
35 hero = new Hero(100,100);
36 }
37 //重写paint
38 public void paint(Graphics g){
39 super.paint(g);
40 //将活动区域设置背景为黑色
41 g.fillRect(0, 0, 400, 300);
42 //画出我的坦克[封装成函数]
43 this.drawTank(hero.getX(),hero.getY(),g,0,0);
44 }
45 public void drawTank(int x,int y,Graphics g,int direct,int type){
46 //1.设置颜色,画出左边的矩形
47 switch(type){
48 case 0:
49 g.setColor(Color.cyan);
50 break;
51 case 1:
52 g.setColor(Color.yellow);
53 break;
54 }
55 switch(direct){
56 case 0:
57 g.fillRect(x,y, 5, 30);
58 //2.画出右边的矩形
59 g.fillRect(x+15,y, 5, 30);
60 //3.画出中间的矩形
61 g.fill3DRect(x+5,y+5, 10, 20,false);
62 //4.画出中间的圆型
63 g.fillOval(x+5,y+10, 10, 10);
64 //5.画炮管
65 g.drawLine(x+10,y+1,x+10,y+15);
66 break;
67 }
68 }
69 }
70
71 //画坦克,分析:坦克生活在哪个区域(MyPanel中)
72
73 //坦克类
74 class Tank{
75 //坦克的横坐标
76 int x = 0;
77 int y = 0;
78 public int getX() {
79 return x;
80 }
81 public void setX(int x) {
82 this.x = x;
83 }
84 public int getY() {
85 return y;
86 }
87 public void setY(int y) {
88 this.y = y;
89 }
90
91 public Tank(int x,int y){
92 this.x = x;
93 this.y = y;
94 }
95 }
96 //我的坦克
97 class Hero extends Tank{
98 public Hero(int x,int y){
99 super(x,y);
100 }
101 }