gpt4 book ai didi

机器人:最终得分和高分

转载 作者:搜寻专家 更新时间:2023-11-01 09:13:55 26 4
gpt4 key购买 nike

在完成我的 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 score/high score 比较是小菜一碟,即使我对 SQL 有基本的了解。我想我用这个小题大做。有更好的方法吗?

最佳答案

好吧,看来您只保存了最高分 - 而不是所有分数,甚至不是前 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);}

}

关于机器人:最终得分和高分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6089219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com