【 java版坦克大戰--繪圖技術】 繪制坦克


通過上一節,我們學會的用java繪圖。那現在就用java繪制自己坦克。

首先通過分析坦克由這幾部分組成。如圖 

 

各個部件的長寬如圖。15,10為圓心。

  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 }

上圖:

好了,坦克繪制好了。

 下一節,要坦克動起來。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM