这一篇的内容主要是在上一篇的基础上,加入分数计算(包括当前分数和最高分数)、游戏结束的判断以及游戏界面的重置这三个部分的功能。
package com.example.t2048;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* 该类用于保存和读取最高分
* @author Mr.Wang
*
*/
public class TopScore {
private SharedPreferences sp;
public TopScore(Context context){
//读取perference文件,如果没有,则会创建一个名为TopScore的文件
sp = context.getSharedPreferences("TopScore", context.MODE_PRIVATE);
}
/**
* 用于读取最高分
* @return 最高分
*/
public int getTopScode(){
//对去键“TopScore”对应的值
int topScore = sp.getInt("TopScore", 0);
return topScore;
}
/**
* 用于写入最高分
* @param topScore 新的最高分
*/
public void setTopScode(int topScore){
//使用Editor类写入perference文件
Editor editor = sp.edit();
editor.putInt("TopScore", topScore);
editor.commit();
}
}
/**
* 该方法用于更新分数
* @param add 新增的分数
*/
public void updateScore(int add){
score += add;
scoreText.setText(score+"");
if(score>topScore.getTopScode())
topScore.setTopScode(score);
topScoreText.setText(topScore.getTopScode()+"");
} /**
* 清空界面,重新初始化
*/
public void reset(){
spaceList.clear();
numberList.clear();
score = 0;
gridLayout.removeAllViews();
init();
} /**
* 通过格子对应的横纵坐标来获取其对应的数字
* @param x 横坐标
* @param y 纵坐标
* @return 格子对应数字的指数
*/
public int getNumberByXY(int x,int y){
if(x<0 || x>3 || y<0 || y>3)
return -1;
else {
int order = stuffList.indexOf(4*x+y);
return numberList.get(order) ;
}
}
/**
* 判断是否还有可以合并的数字格
* @return 有这返回true
*/
public boolean hasChance(){
for(int x = 0;x<=3;x++){
for(int y=0;y<=3;y++){
if(y<3){
if(getNumberByXY(x,y)==getNumberByXY(x, y+1))
return true;
}
if(x<3){
if(getNumberByXY(x,y)==getNumberByXY(x+1, y))
return true;
}
}
}
return false;
}
public void over(){
new AlertDialog.Builder(this)
.setTitle("哎!结束了")
.setMessage("游戏结束,您的本局的分数是"+score+"分,继续加油哦!")
.setPositiveButton("重新开始",new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
reset();
}
})
.setNegativeButton("结束游戏", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.this.finish();
}
}).show();
}从零开始开发Android版2048 (四) 分数、重置、结束
原文地址:http://blog.csdn.net/xiapinnong/article/details/24777099