《2048》开发5——实现计分功能
计分显示分数方法
public class MainActivity extendsActionBarActivity { //MainAcitvity一旦构建就相当于给静态变量MainActivity赋值了,从外界可以访问到 publicMainActivity(){ mainActivity=this; } publicstatic MainActivity getMainActivity() { returnmainActivity; } privateTextView tvScore; privateTextView tvBestScore; privatestatic MainActivity mainActivity=null;//能够在外界调用MainActivity privateint score=0;//记分器 privateGameView gameView; privateButton btnNewGame; publicstatic final String SP_KEY_BEST_SCORE = "bestScore"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvScore=(TextView)findViewById(R.id.tvScore); tvBestScore=(TextView)findViewById(R.id.tvBestScore); gameView=(GameView)findViewById(R.id.gameView); btnNewGame=(Button)findViewById(R.id.btnNewGame); btnNewGame.setOnClickListener(new View.OnClickListener() { //animLayout=(AnimLayout) findViewById(R.id.animLayer); publicvoid onClick(View v) { //TODO Auto-generated method stub gameView.startGame(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } //清理积分器 public void clearScore(){ score=0; showScore(); } //计算总分 public void addScore(int s) { score+=s; showScore(); } //显示分数,并存储最高分 public void showScore() { tvScore.setText("分数为:"score+""); intmaxScore = Math.max(score, getBestScore()); saveBestScore(maxScore); showBestScore(maxScore); } //显示最高分 privatevoid showBestScore(int s) { tvBestScore.setText("最高分"+s+""); } //存储最高分 privatevoid saveBestScore(int s) { Editore = getPreferences(MODE_PRIVATE).edit(); e.putInt(SP_KEY_BEST_SCORE,s); e.commit(); } privateint getBestScore() { returngetPreferences(MODE_PRIVATE).getInt(SP_KEY_BEST_SCORE, 0); } }