项目代码
https://github.com/yinhai1114/Java_Learning_Code/tree/main/IDEA_Chapter20/src
增加功能
1.防止敌人坦克重叠运动
2.记录玩家的成绩,存盘退出
3.记录当时的敌人坦克坐标,存盘退出
4.玩游戏时,可以选择是开新游戏还是继续上局游戏
1.防止敌人坦克重叠运动
这个功能想蛮久的。因为一开始的想法是判断矩形有没有进去,但是这样判断的话,左右的矩形和上下的矩形都是一样,所以判断方向会把02或者13直接判断,后面看了老师的改用方向的角判断
1.判断是否碰撞
该方法完成了是否碰撞的判断,传入的tank和tank分别为this和enemy,testDirect代表测试方向是否可行,因为总感觉就当前方向不太合适。返回的int代表当前方向为错误方向,即走不过去
public static int tankScopeIf(Tank tank, Tank tank1, int testDirect) {
if (testDirect == 0) {
switch (tank1.getDirect()) {
case 0:
case 2:
//左上角坐标[tank.getX - 20 ,tank.getY - 30]
if (tank.getX() - 20 >= tank1.getX() - 20
&& tank.getX() - 20 <= tank1.getX() + 20
&& tank.getY() - 30 >= tank1.getY() - 30
&& tank.getY() - 30 <= tank1.getY() + 30) {
return 0;
}
//右上角坐标[tank.getX + 20 , tank.getY - 30]
if (tank.getX() + 20 >= tank1.getX() - 20
&& tank.getX() + 20 <= tank1.getX() + 20
&& tank.getY() - 30 >= tank1.getY() - 30
&& tank.getY() - 30 <= tank1.getY() + 30) {
return 0;
}
break;
case 1:
case 3:
//左上角坐标[tank.getX - 20 ,tank.getY - 30]
if (tank.getX() - 20 >= tank1.getX() - 30
&& tank.getX() - 20 <= tank1.getX() + 30
&& tank.getY() - 30 >= tank1.getY() - 20
&& tank.getY() - 30 <= tank1.getY() + 20) {
return 0;
}
//右上角坐标[tank.getX + 20 , tank.getY - 30]
if (tank.getX() + 20 >= tank1.getX() - 30
&& tank.getX() + 20 <= tank1.getX() + 30
&& tank.getY() - 30 >= tank1.getY() - 20
&& tank.getY() - 30 <= tank1.getY() + 20) {
return 0;
}
break;
}
} else if (testDirect == 2) {
switch (tank1.getDirect()) {
case 0:
case 2:
//左下角坐标[tank.getX - 20 ,tank.getY + 30]
if (tank.getX() - 20 >= tank1.getX() - 20
&& tank.getX() - 20 <= tank1.getX() + 20
&& tank.getY() + 30 >= tank1.getY() - 30
&& tank.getY() + 30 <= tank1.getY() + 30) {
return 2;
}
//右下角坐标[tank.getX + 20 , tank.getY + 30]
if (tank.getX() + 20 >= tank1.getX() - 20
&& tank.getX() + 20 <= tank1.getX() + 20
&& tank.getY() + 30 >= tank1.getY() - 30
&& tank.getY() + 30 <= tank1.getY() + 30) {
return 2;
}
break;
case 1:
case 3:
//左下角坐标[tank.getX - 20 ,tank.getY + 30]
if (tank.getX() - 20 >= tank1.getX() - 30
&& tank.getX() - 20 <= tank1.getX() + 30
&& tank.getY() + 30 >= tank1.getY() - 20
&& tank.getY() + 30 <= tank1.getY() + 20) {
return 2;
}
//右下角坐标[tank.getX + 20 , tank.getY + 30]
if (tank.getX() + 20 >= tank1.getX() - 30
&& tank.getX() + 20 <= tank1.getX() + 30
&& tank.getY() + 30 >= tank1.getY() - 20
&& tank.getY() + 30 <= tank1.getY() + 20) {
return 2;
}
break;
}
} else if (testDirect == 1) {
switch (tank1.getDirect()) {
case 0:
case 2:
//右上角坐标[tank.getX + 30 ,tank.getY - 20]
if (tank.getX() + 30 >= tank1.getX() - 20
&& tank.getX() + 30 <= tank1.getX() + 20
&& tank.getY() - 20 >= tank1.getY() - 30
&& tank.getY() - 20 <= tank1.getY() + 30) {
return 1;
}
//右下角坐标[tank.getX + 30 , tank.getY + 20]
if (tank.getX() + 30 >= tank1.getX() - 20
&& tank.getX() + 30 <= tank1.getX() + 20
&& tank.getY() + 20 >= tank1.getY() - 30
&& tank.getY() + 20 <= tank1.getY() + 30) {
return 1;
}
break;
case 1:
case 3:
//右上角坐标[tank.getX + 30 ,tank.getY - 20]
if (tank.getX() + 30 >= tank1.getX() - 30
&& tank.getX() + 30 <= tank1.getX() + 30
&& tank.getY() - 20 >= tank1.getY() - 20
&& tank.getY() - 20 <= tank1.getY() + 20) {
return 1;
}
//右下角坐标[tank.getX + 30 , tank.getY + 20]
if (tank.getX() + 30 >= tank1.getX() - 30
&& tank.getX() + 30 <= tank1.getX() + 30
&& tank.getY() + 20 >= tank1.getY() - 20
&& tank.getY() + 20 <= tank1.getY() + 20) {
return 1;
}
break;
}
} else if (testDirect == 3) {
switch (tank1.getDirect()) {
case 0:
case 2:
//左上角坐标[tank.getX - 30 ,tank.getY - 20]
if (tank.getX() - 30 >= tank1.getX() - 20
&& tank.getX() - 30 <= tank1.getX() + 20
&& tank.getY() - 20 >= tank1.getY() - 30
&& tank.getY() - 20 <= tank1.getY() + 30) {
return 3;
}
//左下角坐标[tank.getX - 30 , tank.getY + 20]
if (tank.getX() - 30 >= tank1.getX() - 20
&& tank.getX() - 30 <= tank1.getX() + 20
&& tank.getY() + 20 >= tank1.getY() - 30
&& tank.getY() + 20 <= tank1.getY() + 30) {
return 3;
}
break;
case 1:
case 3:
//左上角坐标[tank.getX - 30 ,tank.getY - 20]
if (tank.getX() - 30 >= tank1.getX() - 30
&& tank.getX() - 30 <= tank1.getX() + 30
&& tank.getY() - 20 >= tank1.getY() - 20
&& tank.getY() - 20 <= tank1.getY() + 20) {
return 3;
}
//左下角坐标[tank.getX - 30 , tank.getY + 20]
if (tank.getX() - 30 >= tank1.getX() - 30
&& tank.getX() - 30 <= tank1.getX() + 30
&& tank.getY() + 20 >= tank1.getY() - 20
&& tank.getY() + 20 <= tank1.getY() + 20) {
return 3;
}
break;
}
}
return -1;
}
}
2.接收错误方向
该方法先调用了地图范围判断,如果判断错误就把该方向计入有墙的方向,随后判断tank之间是否相互碰撞,如果传入四个值0123代表四个方向,如果返回的不是-1代表该方向无法前进,随后该方法返回一个列表
public Vector<Integer> getSafeDirect() {
Vector<Integer> safeDirects = new Vector<>();
Vector<Integer> wrongDirects = new Vector<>();
int direct;
int cantMove;
int haveHellDirect = -1;
for (int i = 0; i < 4; i++) {
safeDirects.add(i);
}
for (int i = 0; i < 4; i++) {
if (Map.scopeIf(this, i)) {
haveHellDirect = i;
wrongDirects.add(haveHellDirect);
}
}
for (int i = 0; i < enemies.size(); i++) {
Enemy enemy = enemies.get(i);
if (this == enemy) {
continue;
}
for (int j = 0; j < 4; j++) {
if ((cantMove = Map.tankScopeIf(this, enemy, j)) != -1) {
wrongDirects.add(cantMove);
}
}
}
safeDirects.removeAll(wrongDirects);
System.out.println("不能移动的方向" + wrongDirects);
return safeDirects;
}
3.设置坦克方向
该方法完成了对安全方向的接受,接收到安全的方向后判断是否为空,为空代表没有方向安全,直接return,然后判断当前方向是否安全,安全就移动,然后移动的次数计数器count++,如果没有安全的方向,在安全方向里随机一个出来设置为该坦克的方向。
最后判断移动的次数,如果是5次以上就随机转向,然后重置计数
public void randomMove() {
Vector<Integer> safeDirects = getSafeDirect();
if (safeDirects.isEmpty()) {
System.out.println("该敌人无法移动");
return;
}
if (safeDirects.contains(this.getDirect())) {
move();
count++;
}else {
int index = (int) (Math.random() * safeDirects.size());//0-size
setDirect(safeDirects.get(index));
}
if (count >= (int) (Math.random() * 40) && count > 5) {//当移动的次数大于某个值的时候,改变方向,0-39的范围
int index = (int) (Math.random() * safeDirects.size());//0-size
setDirect(safeDirects.get(index));
count = 0;//计数为0
}
}
2.记录玩家的成绩,存盘退出
创建一个记录类,该类内实现记录击毁数量,输出字符流写入硬盘。
public class Recorder {
//定义变量,记录击毁坦克数量
private static int destroyEnemy = 0;
private static FileWriter fileWriter = null;
private static BufferedWriter bufferedWriter = null;
private static String recordPath = "src\\com\\yinhai\\tankgame1_5\\DestroyEnemyCount.txt";
public static int getDestroyEnemy() {
return destroyEnemy;
}
public static void setDestroyEnemy(int destroyEnemy) {
Recorder.destroyEnemy = destroyEnemy;
}
public static void addDestroyEnemyCount(){
destroyEnemy++;
}
public static void keepRecord() {
try {
bufferedWriter = new BufferedWriter(new FileWriter(recordPath,true));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss E");
String format = sdf.format(new Date()); // format:将日期转换成指定格式的字符串
bufferedWriter.write( format + " 坦克大战游戏击毁数量为 " + destroyEnemy + "\n");
} catch (IOException e) {
e.printStackTrace();
}finally {
if(bufferedWriter != null){
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
3.记录当时的敌人坦克坐标/方向,存盘退出
在keepRecord增加功能,遍历敌人列表,保存X Y 和 方向,记得在开始游戏的时候在构造器或者能调用的地方使用set方法指向该enemies,不然一直都是null
for (int i = 0; i < enemies.size(); i++) {
Enemy enemy = enemies.get(i);
if(enemy.isLive()){
//保存该信息
String record = "敌人信息" + i + " " + enemy.getX() + " "
+ enemy.getY() + " " + enemy.getDirect() + "\r\n";
//写入到文件
bufferedWriter.write(record);
}
}
4.玩游戏时,可以选择是开新游戏还是继续上局游戏
可以使用对象流保存,但是最好不要更改已有的代码,所以新开一个类Node,该类拥有X Y direct,然后定义一个Vector列表保存Node,Node保存敌人的信息
该nodeHero类用于保存hero的基本信息,如击杀数等
public class Node implements Serializable {
private int x;
private int y;
private int direct;
}
public class NodeHero extends Node{
private int destroyEnemyCount;
public NodeHero(int x, int y, int direct,int destroyEnemyCount) {
super(x, y, direct);
this.destroyEnemyCount = destroyEnemyCount;
}
public int getDestroyEnemyCount() {
return destroyEnemyCount;
}
}
接着在ReadCoder类内编写方法,记录信息。save方法用于保存数据到nodes内,定义输出流,将Vector<Node>(该类实现Serilizeable接口)直接输出为文件存盘。如果需要读取,调用recovery方法,该方法使用对象输入流,将该文件反序列化为对象,然后返回该nodes
private static Vector<Enemy> enemies = null;
private static Hero hero = null;
private static Vector<Node> nodes = null;
public static Vector<Node> recoveryEnemies() {
try {
nodes = new Vector<>();
objectInputStream = new ObjectInputStream(new FileInputStream(recordEnemyInfoPath));
nodes =(Vector<Node>)objectInputStream.readObject();
System.out.println("读取完毕");
return nodes;
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
System.out.println("无上局游戏记录");
System.exit(0);
}
finally {
try {
if (objectInputStream != null) {
objectInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void saveNode() throws IOException {
nodes = new Vector<>();
if(hero.isLife()){
nodes.add(0,new NodeHero(hero.getX(),hero.getY(), hero.getDirect(),Recorder.destroyEnemy));
}else{
nodes.add(0,null);
}
for (int i = 0; i < enemies.size(); i++) {
Enemy enemy = enemies.get(i);
if(enemy.isLive()){
nodes.add(new Node(enemy.getX(),enemy.getY(),enemy.getDirect()));
}
}
if (!nodes.isEmpty()){
objectOutputStream.writeObject(nodes);
}
}
然后分别在程序关闭以及开始的地方调用这两个方法,例如save方法在程序关闭时调用
public class YinhaiTankGame01 extends JFrame {
MyPanel myPanel = null;
public static void main(String[] args) {
YinhaiTankGame01 yinhaiTankGame01 = new YinhaiTankGame01();
}
public YinhaiTankGame01(){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入1:新游戏 2:上一局游戏");
String key = scanner.next();
myPanel = new MyPanel(key);
this.add(myPanel);
this.setSize(1600,900);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.addKeyListener(myPanel);
new Thread(myPanel).start();
//增加响应关闭窗口的处理
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("检测到关闭窗口");
Recorder.keepRecord();
System.exit(0);
}
});
}
}
使用了addWindowListener方法,当检测到关闭窗口时保存数据,在创建画板时传入key值,用于在画板的构造器内判断是否继续游戏,在该画板内如果为1,开始新游戏,将原先构造器的内容放入case语句块内即可,如果为1,调用获取记录方法,获得nodes,然后将nodes的属性分别赋给hero与enemy。
public MyPanel(String key) {
switch (key){
case "1":
int xInitialize = 0;
int yInitialize = 100;
int count = 0;
for (int i = 0; i < enemyNum; i++) {
count++;
if ((xInitialize = 100 * (count)) >= 1500) {
yInitialize += 100;
count = 0;
}
if (yInitialize >= 800) {
break;
}
Enemy enemy = new Enemy(xInitialize, yInitialize, 10);
hero = new Hero(800, 450, 10.0);//初始化位置
Thread thread = new Thread(enemy);
thread.start();
enemy.setHero(hero);
enemies.add(enemy);
enemy.setEnemies(enemies);
Recorder.setEnemies(enemies);
Recorder.setHero(hero);
}
break;
case "2"://继续上次游戏
nodes = Recorder.recoveryEnemies();
if (nodes == null){
System.out.println("无上局游戏记录");
return;
}
if(nodes.get(0) == null){
System.out.println("hero 死亡上局游戏无法继续");
}else{
NodeHero nodeHero =(NodeHero)nodes.get(0);
hero = new Hero(nodeHero.getX(),nodeHero.getY(),10);
hero.setDirect(nodeHero.getDirect());
Recorder.setDestroyEnemy(nodeHero.getDestroyEnemyCount());
}
for (int i = 1; i < nodes.size(); i++) {
Node node = nodes.get(i);
Enemy enemy = new Enemy(node.getX(),node.getY(),10);
enemy.setDirect(node.getDirect());
Thread thread = new Thread(enemy);
thread.start();
enemy.setHero(hero);
enemies.add(enemy);
enemy.setEnemies(enemies);
Recorder.setEnemies(enemies);
Recorder.setHero(hero);
}
break;
default:
System.out.println("错误的输入");
}
5.在开始游戏的时候添加音乐
调用该API在画板绘图完成的时候启动该线程即可
package com.yinhai.tankgame1_5;
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
/**
* @author 韩顺平
* @version 1.0
*/
public class AePlayWave extends Thread {
private String filename;
public AePlayWave(String wavfile) { //构造器 , 指定文件
filename = wavfile;
}
public void run() {
File soundFile = new File(filename);
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (Exception e1) {
e1.printStackTrace();
return;
}
AudioFormat format = audioInputStream.getFormat();
SourceDataLine auline = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
} catch (Exception e) {
e.printStackTrace();
return;
}
auline.start();
int nBytesRead = 0;
//这是缓冲
byte[] abData = new byte[512];
try {
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
auline.drain();
auline.close();
}
}
}
6.增加判断,如果文件不存在不开启游戏
使用File类的文件查找即可
总结:
思路还算清晰,但是在对象流是否能精准的拿到多个对象的最后一个对象上查了很久,结论是不行,所以改用列表的方式序列化。然后就是要多写,确实不写起来很难用好面向对象的理念。重叠的想了非常久,老师的方法更简洁一点,如果当前方向走不了就随机给个方向再判断。我的想法就是全部枚举出来错误的方向,然后不走那个方向即可。