2011-05-22 21 views
2

私のAndroidゲームを完了すると、ユーザーはスコアをハイスコアと比較したいと思います。これを行うために、現在のハイスコアをSQLiteデータベースに保存しました。しかし、私は(動作しているようです)私の方法は、不器用と醜いだと思う:アンドロイド:最終スコアとハイスコア

//in the final score activity, which has been sent the users score from the game. 
if (extras != null){ 
      //get users score 
     SCORE = extras.getLong("Score"); 
      //create DB if necessary, otherwise open 
     startDatabase(); 

    /tv is a text view (defined outside this code snippet) 
    tv.setText("Your score: "+SCORE+" \n"+"Top Score: "+ getHighScore()); 

    } 
} 

//opens or creates a DB. If it is created insert current score. 
public void startDatabase(){ 
    SQLiteDatabase myDB = null; 


    try{  
     myDB = this.openOrCreateDatabase(DB_NAME, 0,null); 

     myDB.execSQL("CREATE TABLE IF NOT EXISTS " 
       + SCORE_TABLE 
       + " (key VARCHAR," 
       + " score NUM)"); 


    }catch(SQLException e){ 
     myDB.close(); 
     } 


    Cursor c1 = myDB.rawQuery("SELECT * FROM "+ SCORE_TABLE ,null); 

    c1.moveToNext(); 


    Long HIGHSCORE=0l; 

      //try to get current high score. 
    try{ 
    HIGHSCORE = c1.getLong(c1.getColumnIndex("score")); 
    } 

      //DB score is empty. Fill it with current score. This is the initial high     `    //score. 
    catch(IndexOutOfBoundsException e){ 
     myDB.execSQL("INSERT INTO "+ SCORE_TABLE+"(score)       
              VALUES('"+SCORE+"')"); 
     myDB.close(); 

    } 

    c1.close(); 
    myDB.close(); 

} 

次のメソッドは、現在のハイスコアを取得し、必要に応じて、新しいハイスコアを入力します。

//returns the high score. also inputs new score as high score if it is high enough. 
public long getHighScore(){ 
    SQLiteDatabase myDB = null; 

    myDB = this.openOrCreateDatabase(DB_NAME, 0,null); 

    Cursor c1 = myDB.rawQuery("SELECT * FROM "+ SCORE_TABLE ,null); 

    c1.moveToNext(); 

    Long HIGHSCORE=0l; 
    try{ 
    HIGHSCORE = c1.getLong(c1.getColumnIndex("score")); 
    } 
    catch(IndexOutOfBoundsException e){ 



    } 

    //if user score is higher than high score... 
    if(HIGHSCORE<=SCORE){ 
     myDB.execSQL("UPDATE "+ SCORE_TABLE+" SET score= '"+SCORE+"'"); 
     HIGHSCORE=SCORE; 
     myDB.close(); 
    } 

    c1.close(); 
    myDB.close(); 
    return HIGHSCORE; 
} 

特にコードは似ていません。当初、私はifnalスコア/ハイスコア比較を行うことは、私の基本的なSQLの知識を持っていても、ケーキだと思っていました。私はこれを使って丘陵からマウンテンを作ったと思う。これを行うより良い方法はありますか?

答えて

3

あなたは最高のスコアしか保存していないようですが、すべてのスコアや上位n個のスコアを保存しているわけではありません。このような場合は、共有プレビューに高得点を保存するほうが簡単でしょう。

public long getHighScore(){ 
SharedPreferences pp = PreferenceManager 
      .getDefaultSharedPreferences(context); 


if(score>pp.getLong("highscore",0l)){ 
    Editor pe=(Editor) pp.edit(); 
    pe.putLong("highscore",score); 
    pe.commit(); 
    return score; 
} else {return pp.getLong("highscore",0l);} 

} 
関連する問題