增加本地排行榜的功能

This commit is contained in:
zhl 2020-08-07 20:45:04 +08:00
parent 04f0701940
commit 56bf90d9a2
12 changed files with 461 additions and 3 deletions

View File

@ -2,6 +2,7 @@ import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services' // Google Services plugin
apply plugin: 'org.greenrobot.greendao'
android {
compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger()
@ -170,6 +171,7 @@ dependencies {
implementation 'com.google.firebase:firebase-auth:19.3.2'
implementation 'com.google.code.gson:gson:2.7'
implementation 'com.android.support:multidex:1.0.3'
implementation 'org.greenrobot:greendao:3.3.0'
compile 'com.tencent.bugly:crashreport:latest.release'
compile 'com.tencent.bugly:nativecrashreport:latest.release'
@ -229,3 +231,10 @@ dependencies {
}
greendao {
schemaVersion 1 //
daoPackage 'com.jc.jcfw.db'// DaoMasterDaoSessionDao
// targetGenDir 'src'//DaoMasterDaoSessionDao目录
}

View File

@ -46,6 +46,16 @@
-dontwarn com.tencent.bugly.**
-keep public class com.tencent.bugly.**{*;}
-keepclassmembers class * extends org.greenrobot.greendao.AbstractDao {
public static java.lang.String TABLENAME;
}
-keep class **$Properties { *; }
# If you do NOT use SQLCipher:
-dontwarn net.sqlcipher.database.**
# If you do NOT use RxJava:
-dontwarn rx.**
-keep class * {
public private *;
}

View File

@ -13,6 +13,7 @@ import android.widget.Toast;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.jc.jcfw.util.IdUtil;
import com.jc.jcfw.util.Leaderboard;
import com.jc.jcfw.util.StorageUtil;
import com.jc.jcfw.util.StringUtil;
import com.tencent.bugly.crashreport.CrashReport;
@ -31,6 +32,7 @@ public class JcSDK {
private static Vibrator vibrator;
private static FirebaseAnalytics mFirebaseAnalytics;
private static SharedPreferences sharedPref;
private static Leaderboard leaderboard;
public static void init(Context context) {
isDebug = isApkInDebug(context);
@ -38,6 +40,11 @@ public class JcSDK {
vibrator = (Vibrator) AppActivity.app.getSystemService(Context.VIBRATOR_SERVICE);
mFirebaseAnalytics = ((AppActivity)context).getmFirebaseAnalytics();
sharedPref = PreferenceManager.getDefaultSharedPreferences(AppActivity.app);
leaderboard = Leaderboard.getInstance(sharedPref);
// String[] names = NameUtil.generateEname(1, 40);
// for(String name: names) {
// System.out.println(name);
// }
}
public static void showBanner() {
@ -167,7 +174,12 @@ public class JcSDK {
StorageUtil.removeString(sharedPref, k);
}
}
}
public static String lbTop20(String accountId) {
return leaderboard.getTop20(accountId);
}
public static String updateRank(String accountId, String name, int score) {
return leaderboard.updateRank(accountId, name, score);
}
}
}

View File

@ -0,0 +1,95 @@
package com.jc.jcfw.bean;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Index;
import org.greenrobot.greendao.annotation.Generated;
import org.json.JSONException;
import org.json.JSONObject;
@Entity(indexes = {
@Index(value = "score DESC")
})
public class RecordBean {
@Id
private Long id;
private String accountId;
private String nickname;
private int score;
private int rank;
private String day;
@Generated(hash = 1609371103)
public RecordBean(Long id, String accountId, String nickname, int score,
int rank, String day) {
this.id = id;
this.accountId = accountId;
this.nickname = nickname;
this.score = score;
this.rank = rank;
this.day = day;
}
@Generated(hash = 96196931)
public RecordBean() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public JSONObject toJSONObj() {
JSONObject obj = new JSONObject();
try {
obj.put("nickname", this.nickname);
obj.put("accountId", this.accountId);
obj.put("score", this.score);
obj.put("rank", this.rank);
} catch (JSONException ignored) {}
return obj;
}
}

View File

@ -0,0 +1,28 @@
package com.jc.jcfw.util;
import java.util.Arrays;
import java.util.Random;
public class ArrayUtils {
private static Random rand = new Random();
public static <T> void swap(T[] a, int i, int j) {
T temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static <T> void shuffle(T[] arr) {
int length = arr.length;
for (int i = length; i > 0; i--) {
int randInd = rand.nextInt(i);
swap(arr, randInd, i - 1);
}
}
public static <T> T[] concat(T[] first, T[] second) {
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
}

View File

@ -0,0 +1,20 @@
package com.jc.jcfw.util;
import android.annotation.SuppressLint;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static String getFirstWeekDay() {
Calendar calendar = Calendar.getInstance();
int min = calendar.getActualMinimum(Calendar.DAY_OF_WEEK); //获取周开始基准
int current = calendar.get(Calendar.DAY_OF_WEEK); //获取当天周内天数
calendar.add(Calendar.DAY_OF_WEEK, min-current); //当天-基准获取周开始日期
Date start = calendar.getTime();
@SuppressLint("SimpleDateFormat") DateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
return sdf.format(start);
}
}

View File

@ -0,0 +1,48 @@
package com.jc.jcfw.util;
import org.cocos2dx.javascript.AppActivity;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import cz.msebera.android.httpclient.util.EncodingUtils;
import static android.content.Context.MODE_PRIVATE;
public class FileUtil {
//写数据
public void writeFile(String fileName,String writestr) throws IOException {
try{
FileOutputStream fout = AppActivity.app.openFileOutput(fileName, MODE_PRIVATE);
byte [] bytes = writestr.getBytes();
fout.write(bytes);
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
//读数据
public String readFile(String fileName) throws IOException{
String res="";
try{
FileInputStream fin = AppActivity.app.openFileInput(fileName);
int length = fin.available();
byte [] buffer = new byte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
}
catch(Exception e){
e.printStackTrace();
}
return res;
}
}

View File

@ -0,0 +1,177 @@
package com.jc.jcfw.util;
import android.content.SharedPreferences;
import com.jc.jcfw.bean.RecordBean;
import com.jc.jcfw.db.DaoSession;
import com.jc.jcfw.db.RecordBeanDao;
import org.cocos2dx.javascript.AppActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Leaderboard {
private int scoreMax = 100000;
private int scoreMin = 80000;
private int scoreSegmented;
private int topCount = 20;
private static Leaderboard mInstance;
private final String LEADER_BOARD_KEY = "leaderboard";
private SharedPreferences sharedPref;
private JSONArray scoreList;
private String dataKey;
private RecordBeanDao recordBeanDao;
public Leaderboard(SharedPreferences sharedPref) {
this.sharedPref = sharedPref;
this.dataKey = DateUtil.getFirstWeekDay();
this.scoreSegmented = (this.scoreMax - this.scoreMin) / this.topCount;
DaoSession daoSession = AppActivity.app.getDaoSession();
recordBeanDao = daoSession.getRecordBeanDao();
this.prepareData();
}
public static Leaderboard getInstance(SharedPreferences sharedPref) {
if (null == mInstance) {
mInstance = new Leaderboard(sharedPref);
}
return mInstance;
}
private void prepareData() {
List<RecordBean> records = recordBeanDao.queryRaw("where DAY = ?", this.dataKey);
if (records == null || records.size() == 0) {
recordBeanDao.deleteAll();
records = this.generateTop();
}
}
/**
* 根据名次生成分数
* @param rank 名次
* @return score
*/
private int generateScore(int rank) {
Random random = new Random();
int scoreRandom = (int) (random.nextDouble() * scoreSegmented);
return scoreMax - scoreSegmented * rank - scoreRandom;
}
private int generateScore(int score, int isPre) {
Random random = new Random();
int scoreRandom = (int) (random.nextDouble() * 10);
return score + scoreRandom * isPre;
}
private int generateRank(int score) {
if (score >= this.scoreMin) {
int rank = (this.scoreMax - score) / this.scoreSegmented + 1;
return rank > 0 ? rank : 1;
} else {
return (this.scoreMin - score) / 10 + this.topCount;
}
}
private List<RecordBean> generateTop() {
List<RecordBean> records = new ArrayList<>();
String[] top20s = NameUtil.generateRandom(topCount);
for (int i = 0; i < topCount; i ++) {
RecordBean record = new RecordBean();
record.setAccountId("");
record.setNickname(top20s[i]);
record.setScore(generateScore(i));
record.setRank(i + 1);
record.setDay(this.dataKey);
recordBeanDao.insert(record);
records.add(record);
}
return records;
}
public String getTop20(String accountId) {
List<RecordBean> records = recordBeanDao.queryBuilder()
.orderDesc(RecordBeanDao.Properties.Score)
.limit(20)
.build().list();
List<RecordBean> myRecords = recordBeanDao.queryRaw("where ACCOUNT_ID = ?", accountId);
if (records == null || records.size() == 0) {
records = this.generateTop();
}
JSONObject obj = new JSONObject();
try {
int selfScore = 0;
int selfRank = 0;
JSONArray datas = new JSONArray();
for (int i = 0; i< records.size(); i++) {
RecordBean record = records.get(i);
datas.put(record.toJSONObj());
}
obj.put("records", datas);
if (myRecords != null && myRecords.size() > 0) {
RecordBean record = myRecords.get(0);
selfScore = record.getScore();
selfRank = record.getRank();
}
obj.put("userRank", selfRank);
obj.put("userScore", selfScore);
} catch(JSONException ignored) {
}
return obj.toString();
}
public String updateRank(String accountId, String name, int score) {
RecordBean record = recordBeanDao.queryBuilder().where(RecordBeanDao.Properties.AccountId.eq(accountId)).build().unique();
int rank = this.generateRank(score);
if (record != null) {
if (score > record.getScore()) {
record.setScore(score);
record.setRank(rank);
recordBeanDao.update(record);
}
} else {
record = new RecordBean();
record.setAccountId(accountId);
record.setScore(score);
record.setNickname(name);
record.setRank(rank);
recordBeanDao.insert(record);
}
JSONObject result = new JSONObject();
RecordBean recordPre;
if (record.getRank() > 1) {
recordPre = recordBeanDao.queryBuilder().where(RecordBeanDao.Properties.Rank.eq(record.getRank() - 1)).build().unique();
if (recordPre == null) {
recordPre = new RecordBean();
recordPre.setNickname(NameUtil.generateRandomOne());
recordPre.setScore(this.generateScore(record.getScore(), 1));
recordPre.setRank(record.getRank() - 1);
recordBeanDao.insert(recordPre);
}
try {
result.put("preRecord", recordPre.toJSONObj());
} catch(JSONException ignored) {}
}
RecordBean recordNext = recordBeanDao.queryBuilder().where(RecordBeanDao.Properties.Rank.eq(record.getRank() + 1)).build().unique();
if (recordNext == null) {
recordNext = new RecordBean();
recordNext.setNickname(NameUtil.generateRandomOne());
recordNext.setScore(this.generateScore(record.getScore(), -1));
recordNext.setRank(record.getRank() + 1);
recordBeanDao.insert(recordNext);
}
try {
result.put("userRank", record.getRank());
result.put("userScore", record.getScore());
result.put("nextRecord", recordNext.toJSONObj());
} catch(JSONException ignored) {
}
return result.toString();
}
}

File diff suppressed because one or more lines are too long

View File

@ -26,10 +26,13 @@ package org.cocos2dx.javascript;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.jc.jcfw.JcSDK;
import com.jc.jcfw.db.DaoMaster;
import com.jc.jcfw.db.DaoSession;
import com.tencent.bugly.crashreport.CrashReport;
import org.cocos2dx.lib.Cocos2dxActivity;
@ -38,6 +41,7 @@ import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
public class AppActivity extends Cocos2dxActivity {
public static AppActivity app;
private FirebaseAnalytics mFirebaseAnalytics;
private DaoSession daoSession;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -50,6 +54,7 @@ public class AppActivity extends Cocos2dxActivity {
return;
}
app = this;
intGreenDao();
// DO OTHER INITIALIZATION BELOW
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
CrashReport.initCrashReport(getApplicationContext(), "76b5e35530", false);
@ -151,4 +156,13 @@ public class AppActivity extends Cocos2dxActivity {
public FirebaseAnalytics getmFirebaseAnalytics() {
return mFirebaseAnalytics;
}
private void intGreenDao() {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "sweet.db");
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
}
public DaoSession getDaoSession() {
return daoSession;
}
}

View File

@ -165,6 +165,7 @@
</content>
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/jni/hellojavascript" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/greendao" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/apt/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/aidl_source_output_dir/debug/compileDebugAidl/out" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
@ -240,8 +241,10 @@
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="TEST" name="Gradle: androidx.multidex:multidex-instrumentation:2.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: com.google.code.gson:gson:2.7@jar" level="project" />
<orderEntry type="library" name="Gradle: org.greenrobot:greendao:3.3.0@jar" level="project" />
<orderEntry type="library" name="Gradle: com.ironsource.sdk:mediationsdk:6.15.0.1@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.collection:collection:1.1.0@jar" level="project" />
<orderEntry type="library" name="Gradle: org.greenrobot:greendao-api:3.3.0@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-common:2.3.0-alpha03@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.arch.core:core-common:2.1.0@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.annotation:annotation:1.2.0-alpha01@jar" level="project" />

View File

@ -5,11 +5,12 @@ buildscript {
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.0'
classpath 'com.google.gms:google-services:4.3.3' // Google Services plugin
classpath 'org.greenrobot:greendao-gradle-plugin:3.3.0' // add plugin
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}