📄 stage.java
字号:
package com.cpiz.poptang;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 关卡数据类,用以关卡数据的持久化保存
* @author caipiz
*/
public class Stage
{
public int stageIndex = -1;
public int imgIndex = 1;
public int midIndex = 1;
public byte[][][] mapData = new byte[3][7][8];
public byte[] heroPosition = new byte[2];//英雄出生位置,英雄所在的行和列
public byte[] enemyPosition = new byte[10];// 敌人出生位置
/**
* 获取指定关卡地图数据
* @param stage 关卡号
* @return 关卡数据对象
* @throws IOException 未找到对应关卡数据文件则抛出异常
*/
public static Stage loadStage(int stageIndex) throws IOException
{
Stage stageData = new Stage();
stageData.stageIndex = stageIndex;
DataInputStream dis = new DataInputStream(Stage.class.getResourceAsStream("/stage/" + stageIndex));
// 读取地图贴图文件索引
stageData.imgIndex = dis.readInt();
// 读取地图贴图文件索引
stageData.midIndex = dis.readInt();
// 读取地图数据
byte[] map = new byte[3*7*8];
dis.read(map);// 一次性将整个地图读入一维数组中
int index = 0;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 7; j++)
{
for(int k = 0; k < 8; k++)
{
stageData.mapData[i][j][k] = map[index++];
}
}
}
// 读取英雄出生点
dis.read(stageData.heroPosition);
// 读取敌人出生点并获得敌人数目
dis.read(stageData.enemyPosition);
return stageData;
}
/**
* 存储地图数据
* @param stage 要保存为的关卡
* @throws IOException
*/
public void save(int stage) throws IOException
{
FileOutputStream os = new FileOutputStream("stage/" + stage);
DataOutputStream dos = new DataOutputStream(os);
// 写入地图贴图文件索引
dos.writeInt(imgIndex);
// 写入音乐文件索引
dos.writeInt(midIndex);
// 写入地图数据
byte[] map = new byte[3 * 7 * 8];
int index = 0;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 7; j++)
{
for(int k = 0; k < 8; k++)
{
map[index++] = mapData[i][j][k];
}
}
}
dos.write(map);// 一次性将整个地图读入一维数组中
// 写入英雄出生点
dos.write(heroPosition);
// 写入敌人出生点
dos.write(enemyPosition);
// 将数据写出文件
dos.flush();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -