java用接口,多态轻松实现 坦克大战案例 ,能够很好的理解多态和接口
部分源码
完整源码分享 请点击连接下载
提取码: 2i2a
效果图片
package com.itheima.domain;
import com.itheima.inter.Destroyable;
import org.itheima.game.DrawUtils;
import org.itheima.game.SoundUtils;
import java.io.IOException;
public class Blast extends Element implements Destroyable{
// 定义一个字符串数组,存储所有爆炸物图片的路径
private String[] arr = {"../TankWar2/res/img/blast_1.gif","../TankWar2/res/img/blast_2.gif",
"../TankWar2/res/img/blast_3.gif","../TankWar2/res/img/blast_4.gif","../TankWar2/res/img/blast_5.gif",
"../TankWar2/res/img/blast_6.gif","../TankWar2/res/img/blast_7.gif","../TankWar2/res/img/blast_8.gif"};
private int index;// 定义一个索引表示arr数组的索引
private int len = arr.length;// 定义一个len变量,用来记录数组的长度 默认是8
private boolean flag ;//用来记录爆炸物是否显示完了
/*
爆炸物的坐标:
bx = qx - (bw - qw)/2;
by = qy - (bh - qh)/2;
*/
public Blast(int qx, int qy,int qw,int qh,int blood) {
// 计算爆炸物的宽和高
try {
int[] arr = DrawUtils.getSize("../TankWar2/res/img/blast_1.gif");
this.width = arr[0];
this.height = arr[1];
} catch (IOException e) {
e.printStackTrace();
}
// 计算爆炸物的x坐标和y坐标
this.x = qx - (this.width - qw)/2;
this.y = qy - (this.height - qh)/2;
// 如果血量大于0,显示小爆炸物
if(blood > 0){
len = 4;
}
try {
SoundUtils.play("../TankWar2/res/snd/blast.wav");
} catch (IOException e) {
e.printStackTrace();
}
}
// 如果墙还有血量,就显示一部分爆炸物,如果墙没有了血量,那么就显示大爆炸物
@Override
public void draw() {// 一直在调用
if(index > len -1){
index = 0;
flag = true;// 显示一轮完了,应该移除爆炸物
}
try {
DrawUtils.draw(arr[index],x,y);
} catch (IOException e) {
e.printStackTrace();
}
index++;
}
/*
判断是否需要移除爆炸物
*/
public boolean isDestroy(){
return flag;
}
启动代码
*
枚举:
概述: 枚举也是一种引用数据类型
作用: 其实就是用来存储一下固定的值
格式:
public enum 枚举名{
枚举值1,
枚举值2,
枚举值3,
....
}
使用: 枚举名.枚举值
Direction dic = Direction.UP;// 定义了一个Direction枚举类型的变量dic,该变量的值是Direction.UP
dic = Direction.DOWN;
dic = Direction.LEFT;
dic = Direction.RIGHT;
Grander grander = Grander.BOY;
Grander grander1 = Grander.GIRL;
*/
public class App2 {
public static void main(String[] args) {
// 创建窗体
GameWindow gw = new GameWindow(Config.TITLE,Config.WIDTH,Config.HEIGHT,Config.FPS);
// 启动窗体
gw.start();
}
}