前几日用Java写了个小游戏tankwar现在想用Android再写一下。
首先我考虑一下我需要的元素(战场、我方tank、敌方tank、子弹),然后就是他们之间的关系:
1.战场中包含我方tank、敌方tank、子弹,
2.tank中包括我方、敌方tank和子弹。
战场我决定用自定义view :War,
1 public class War extends View { 2 3 4 public War(Context context, AttributeSet attrs) { 5 super(context, attrs); 6 } 7 8 @Override 9 protected void onDraw(Canvas canvas) { 10 super.onDraw(canvas); 11 } 12 }
在War中先画一个我方tank
先将建我方tank的class并且继承tank,tank里是坦克的一些属性
1 public class tank { 2 private int x;//x坐标 3 private int y;//y坐标 4 private int direct;//tank朝向 5 private int Color;//tank颜色 6 private boolean lived;//tank是否存活 7 8 public int getColor() { 9 return Color; 10 } 11 12 public void setColor(int color) { 13 Color = color; 14 } 15 16 public int getDirect() { 17 return direct; 18 } 19 20 public void setDirect(int direct) { 21 this.direct = direct; 22 } 23 24 public boolean isLived() { 25 return lived; 26 } 27 28 public void setLived(boolean lived) { 29 this.lived = lived; 30 } 31 32 public int getX() { 33 return x; 34 } 35 36 public void setX(int x) { 37 this.x = x; 38 } 39 40 public int getY() { 41 return y; 42 } 43 44 public void setY(int y) { 45 this.y = y; 46 } 47 }
public class myTank extends tank { public myTank(int x,int y,int direct,int color){ //初始化属性 setLived(true); setColor(0); setDirect((int)(Math.random()*4)); setX((int)(Math.random()*300)); setY((int)(Math.random()*300)); } }
在War中添加一个方法画坦克drawtank现在的War就是这样的
1 public class War extends View { 2 Paint pt; 3 myTank mt;//我方tank 4 public War(Context context, AttributeSet attrs) { 5 super(context, attrs); 6 mt = new myTank(); 7 } 8 9 @Override 10 protected void onDraw(Canvas canvas) { 11 super.onDraw(canvas); 12 if(mt.isLived()){ 13 drawtank(mt.getX(),mt.getY(), 14 mt.getColor(),mt.getDirect(),canvas); 15 } 16 17 } 18 private void drawtank(int x,int y,int color,int direct,Canvas c){ 19 switch(color){ 20 case 0: 21 pt = new Paint();pt.setColor(Color.RED);break; 22 } 23 switch (direct){ 24 case 0://up 25 c.drawRect(x,y,x+10,y+30,pt);//left 26 c.drawRect(x+30,y,x+40,y+30,pt);//right 27 //c.drawArc(x+5,y+2,x+15,y+12,0,360,true,p); 28 c.drawCircle(x+20,y+15,10,pt); 29 c.drawRect(x+18,y,x+22,y+15,pt);break;//midd 30 } 31 } 32 }
坦克的大小是试出来的
接着要在activity_main.xml中添加War
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.administrator.tankwar.MainActivity"> <com.example.administrator.tankwar.War android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
这样就画出来了一个小坦克在手机上
原文:http://www.cnblogs.com/lazy0-0/p/6464125.html