Android遊戲之設定讀寫與得分

Android遊戲之抽象『屏幕』

在遊戲啟動需從磁盤讀取遊戲選項與得分.在GLSurfaceView.Renderer.onSurfaceCreated()中讀取讀取.首先確立文檔名

String  filename = “settings.dat”;

打開文檔並返回輸入流

InputStream file = FileIO.ReadFile(filename);

打開讀取器

InputStreamReader stream = new InputStreamReader(file);

打開讀取緩存

BufferedReader in = new BufferedReader(stream);

String text;

讀取遊戲前五個最高得分

int[]   highscores = new int[] {0,0,0,0,0};// 高分榜

for(int i=0;i<5;++i){

讀取一行文本,並轉換為得分.

text = in.readLine();

highscores[i] = Integer.parseInt(text);

}

用戶可能關閉音量

text = in.readLine();

boolean soundEnabled = Boolean.parseBoolean(text);

讀取遊戲音量.值為浮點數(0~1)

text = in.readLine();

float soundVolume = Float.parseFloat(text);

遊戲關卡整數值大於1

text = in.readLine();

int     level = Integer.parseInt(text);

道具量整數值大於或等於零

text = in.readLine();

int     bombs = Integer.parseInt(text);

讀取完畢關閉讀取緩存

in.close();

 

在遊戲退出時需將所有選項與得分寫入磁盤.在GLSurfaceView.onPause()中保存.打開文檔並返回輸出流

OutputStream file = FileIO.WriteFile(filename);

打開寫入器

OutputStreamWriter stream = new OutputStreamWriter(file);

打開寫入緩存

BufferedWriter out = new BufferedWriter(stream);

寫入遊戲五個最高得分

for(int i=0;i<5; i++){

out.write(Integer.toString(highscores[i]));

寫入換行

out.write(“\r”);

}

寫入聲音開關

out.write(Boolean.toString(soundEnabled));

out.write(“\r”);

寫入音量值(0~1)浮點數

out.write(Float.toString(soundVolume));

out.write(“\r”);

寫入當前關卡整數值

out.write(Integer.toString(level));

out.write(“\r”);

寫入道具量整數值

out.write(Integer.toString(bombs));

out.write(“\r”);

關閉寫入緩存

out.close();

 

加入得分並進行高分排序

public static void addScore(int score){

for(int i=0;i<5; ++i){

if(highscores[i] < score){

for(int j=4; j>i; –j)

highscores[j] = highscores[j-1];// 往後移

highscores[i] = score;// 插入分數

break;

}

}

 

評論