Project

General

Profile

Download (14.5 KB) Statistics
| Branch: | Tag: | Revision:

magiccube / src / main / java / org / distorted / external / RubikScores.java @ 00fcfefa

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2020 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Magic Cube.                                                              //
5
//                                                                                               //
6
// Magic Cube is proprietary software licensed under an EULA which you should have received      //
7
// along with the code. If not, check https://distorted.org/magic/License-Magic-Cube.html        //
8
///////////////////////////////////////////////////////////////////////////////////////////////////
9

    
10
package org.distorted.external;
11

    
12
import java.util.HashMap;
13
import java.util.UUID;
14

    
15
import android.content.Context;
16
import android.content.SharedPreferences;
17
import android.telephony.TelephonyManager;
18

    
19
import com.google.firebase.crashlytics.FirebaseCrashlytics;
20

    
21
import org.distorted.main.BuildConfig;
22
import org.distorted.objects.RubikObject;
23
import org.distorted.objects.RubikObjectList;
24
import org.distorted.screens.RubikScreenPlay;
25

    
26
import static org.distorted.objectlib.main.ObjectType.MAX_SCRAMBLES;
27
import static org.distorted.screens.RubikScreenPlay.LEVELS_SHOWN;
28

    
29
///////////////////////////////////////////////////////////////////////////////////////////////////
30
// hold my own scores, and some other statistics.
31

    
32
public class RubikScores
33
  {
34
  public static final int RECORD_FIRST   = 0;
35
  public static final int RECORD_NEW     = 1;
36
  public static final int RECORD_NOT_NEW = 2;
37

    
38
  public static final int MAX_RECORD = 10;
39
  public static final int MULT = 1000000;
40
  public static final long NO_RECORD = Long.MAX_VALUE;
41
  private static RubikScores mThis;
42

    
43
  private String mName, mCountry;
44
  private boolean mNameIsVerified;
45
  private int mNumRuns;
46
  private int mNumPlays;
47
  private int mNumWins;
48
  private int mDeviceID;
49
  private int mNumStars;
50

    
51
  private static class MapValue
52
    {
53
    long record;
54
    boolean submitted;
55

    
56
    MapValue(long rec,int sub)
57
      {
58
      record    = rec;
59
      submitted = sub!=0;
60
      }
61
    }
62

    
63
  private final HashMap<Integer,MapValue> mMap;
64

    
65
///////////////////////////////////////////////////////////////////////////////////////////////////
66

    
67
  private RubikScores()
68
    {
69
    mMap = new HashMap<>();
70

    
71
    mName = "";
72
    mCountry = "un";
73

    
74
    mNameIsVerified = false;
75

    
76
    mNumPlays= -1;
77
    mNumRuns = -1;
78
    mDeviceID= -1;
79
    mNumWins =  0;
80
    mNumStars=  0;
81
    }
82

    
83
///////////////////////////////////////////////////////////////////////////////////////////////////
84

    
85
  private int mapKey(int object,int level)
86
    {
87
    return object*MULT + level;
88
    }
89

    
90
///////////////////////////////////////////////////////////////////////////////////////////////////
91

    
92
  private int privateGetDeviceID()
93
    {
94
    int id;
95

    
96
    try
97
      {
98
      String s = UUID.randomUUID().toString();
99
      id = s.hashCode();
100
      }
101
    catch(Exception ex)
102
      {
103
      id = 0;
104
      android.util.Log.e("scores", "Exception in getDeviceID()");
105
      }
106

    
107
    return id<0 ? -id : id;
108
    }
109

    
110
///////////////////////////////////////////////////////////////////////////////////////////////////
111

    
112
  synchronized void successfulSubmit()
113
    {
114
    mNameIsVerified = true;
115

    
116
    for(int key: mMap.keySet())
117
      {
118
      MapValue value = mMap.get(key);
119
      if( value!=null ) value.submitted = true;
120
      }
121
    }
122

    
123
///////////////////////////////////////////////////////////////////////////////////////////////////
124

    
125
  int getDeviceID()
126
    {
127
    return mDeviceID;
128
    }
129

    
130
///////////////////////////////////////////////////////////////////////////////////////////////////
131

    
132
  synchronized boolean thereAreUnsubmittedRecords()
133
    {
134
    for(int key: mMap.keySet())
135
      {
136
      MapValue value = mMap.get(key);
137
      if( value!=null && !value.submitted && value.record<NO_RECORD) return true;
138
      }
139

    
140
    return false;
141
    }
142

    
143
///////////////////////////////////////////////////////////////////////////////////////////////////
144

    
145
  synchronized String getRecordList(String strObj, String strLvl, String strTim)
146
    {
147
    StringBuilder builderObj = new StringBuilder();
148
    StringBuilder builderLvl = new StringBuilder();
149
    StringBuilder builderTim = new StringBuilder();
150
    boolean first = true;
151

    
152
    for(int key: mMap.keySet())
153
      {
154
      MapValue value = mMap.get(key);
155

    
156
      if( value!=null && !value.submitted && value.record<NO_RECORD)
157
        {
158
        if( !first )
159
          {
160
          builderObj.append(',');
161
          builderLvl.append(',');
162
          builderTim.append(',');
163
          }
164
        first=false;
165

    
166
        RubikObject object = RubikObjectList.getObject(key/MULT);
167

    
168
        if( object!=null )
169
          {
170
          builderObj.append(object.getUpperName());
171
          builderLvl.append(key%MULT);
172
          builderTim.append(value.record);
173
          }
174
        }
175
      }
176

    
177
    return strObj+builderObj.toString()+strLvl+builderLvl.toString()+strTim+builderTim.toString();
178
    }
179

    
180
///////////////////////////////////////////////////////////////////////////////////////////////////
181
// Public API
182
///////////////////////////////////////////////////////////////////////////////////////////////////
183

    
184
  public boolean isVerified()
185
    {
186
    return mNameIsVerified;
187
    }
188

    
189
///////////////////////////////////////////////////////////////////////////////////////////////////
190

    
191
  public int getNumPlays()
192
    {
193
    return mNumPlays;
194
    }
195

    
196
///////////////////////////////////////////////////////////////////////////////////////////////////
197

    
198
  public int getNumRuns()
199
    {
200
    return mNumRuns;
201
    }
202

    
203
///////////////////////////////////////////////////////////////////////////////////////////////////
204

    
205
  public String getName()
206
    {
207
    return mName;
208
    }
209

    
210
///////////////////////////////////////////////////////////////////////////////////////////////////
211

    
212
  public String getCountry()
213
    {
214
    return mCountry;
215
    }
216

    
217
///////////////////////////////////////////////////////////////////////////////////////////////////
218

    
219
  public void incrementNumPlays()
220
    {
221
    mNumPlays++;
222
    }
223

    
224
///////////////////////////////////////////////////////////////////////////////////////////////////
225

    
226
  public void incrementNumRuns()
227
    {
228
    mNumRuns++;
229
    }
230

    
231
///////////////////////////////////////////////////////////////////////////////////////////////////
232

    
233
  public int incrementNumWins()
234
    {
235
    mNumWins++;
236
    return mNumWins;
237
    }
238

    
239
///////////////////////////////////////////////////////////////////////////////////////////////////
240

    
241
  public void changeNumStars(int stars)
242
    {
243
    mNumStars += stars;
244
    }
245

    
246
///////////////////////////////////////////////////////////////////////////////////////////////////
247

    
248
  public int getNumStars()
249
    {
250
    return mNumStars;
251
    }
252

    
253
///////////////////////////////////////////////////////////////////////////////////////////////////
254

    
255
  public void correctNumStars()
256
    {
257
    int numObjects = RubikObjectList.getNumObjects();
258

    
259
    for(int obj=0; obj<numObjects; obj++)
260
      {
261
      for(int level=0; level<=RubikScreenPlay.LEVELS_SHOWN; level++)
262
        {
263
        if( isSolved(obj,level) )
264
          {
265
          int numStars = computeNumStars(level+1);
266
          mNumStars += numStars;
267
          }
268
        }
269
      }
270
    }
271

    
272
///////////////////////////////////////////////////////////////////////////////////////////////////
273

    
274
  public int computeNumStars(int level)
275
    {
276
    return level>=LEVELS_SHOWN ? 50 : level;
277
    }
278

    
279
///////////////////////////////////////////////////////////////////////////////////////////////////
280

    
281
  public void setName(String newName)
282
    {
283
    mName = newName;
284
    }
285

    
286
///////////////////////////////////////////////////////////////////////////////////////////////////
287

    
288
  public synchronized int setRecord(int object, int level, long record)
289
    {
290
    int key = mapKey(object,level);
291
    MapValue oldValue = mMap.get(key);
292

    
293
    if( oldValue==null )
294
      {
295
      MapValue value = new MapValue(record,0);
296
      mMap.put(key,value);
297
      return RECORD_FIRST;
298
      }
299

    
300
    long oldRecord = oldValue.record;
301

    
302
    if( oldRecord>record)
303
      {
304
      MapValue value = new MapValue(record,0);
305
      mMap.put(key,value);
306
      return RECORD_NEW;
307
      }
308

    
309
    return RECORD_NOT_NEW;
310
    }
311

    
312
///////////////////////////////////////////////////////////////////////////////////////////////////
313

    
314
  public synchronized long getRecord(int object, int level)
315
    {
316
    int key = mapKey(object,level);
317
    MapValue value = mMap.get(key);
318
    return value!=null ? value.record : NO_RECORD;
319
    }
320

    
321
///////////////////////////////////////////////////////////////////////////////////////////////////
322

    
323
  public synchronized boolean isSolved(int object, int level)
324
    {
325
    int key = mapKey(object,level);
326
    MapValue value = mMap.get(key);
327
    return value!=null && value.record<NO_RECORD;
328
    }
329

    
330
///////////////////////////////////////////////////////////////////////////////////////////////////
331

    
332
  public void setCountry(Context context)
333
    {
334
    TelephonyManager tM =((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));
335

    
336
    if( tM!=null )
337
      {
338
      mCountry = tM.getSimCountryIso();
339

    
340
      if( mCountry==null || mCountry.length()<=1 )
341
        {
342
        mCountry = tM.getNetworkCountryIso();
343
        }
344
      }
345

    
346
    // Special case: Dominicana. Its ISO-3166-alpha-2 country code is 'do' which we can't have here
347
    // because we later on map this to a resource name (the flag) and 'do' is a reserved Java keyword
348
    // and can't be a resource name.
349

    
350
    if( mCountry.equals("do") ) mCountry = "dm";
351
    }
352

    
353
///////////////////////////////////////////////////////////////////////////////////////////////////
354

    
355
  public void setCountry(String country)
356
    {
357
    mCountry = country;
358

    
359
    if( mCountry.equals("do") ) mCountry = "dm";  // see above
360
    }
361

    
362
///////////////////////////////////////////////////////////////////////////////////////////////////
363

    
364
  public static RubikScores getInstance()
365
    {
366
    if( mThis==null ) mThis = new RubikScores();
367
    return mThis;
368
    }
369

    
370
///////////////////////////////////////////////////////////////////////////////////////////////////
371

    
372
  public synchronized void savePreferences(SharedPreferences.Editor editor)
373
    {
374
    int numObjects = RubikObjectList.getNumObjects();
375
    StringBuilder builder = new StringBuilder();
376

    
377
    for(int level=0; level<=MAX_RECORD; level++)
378
      {
379
      builder.setLength(0);
380

    
381
      for(int object=0; object<numObjects; object++)
382
        {
383
        int key = mapKey(object,level);
384
        RubikObject obj = RubikObjectList.getObject(object);
385
        MapValue value = mMap.get(key);
386

    
387
        if( obj!=null && value!=null && value.record<NO_RECORD )
388
          {
389
          builder.append(obj.getUpperName());
390
          builder.append("=");
391
          builder.append(value.record);
392
          builder.append(",");
393
          builder.append(value.submitted ? 1:0 );
394
          builder.append(" ");
395
          }
396
        }
397

    
398
      editor.putString("scores_record"+level, builder.toString());
399
      }
400

    
401
    editor.putString("scores_name"  , mName  );
402
    editor.putBoolean("scores_isVerified", mNameIsVerified);
403
    editor.putInt("scores_numPlays", mNumPlays);
404
    editor.putInt("scores_numRuns" , mNumRuns );
405
    editor.putInt("scores_deviceid", mDeviceID);
406
    editor.putInt("scores_review"  , mNumWins );   // legacy name
407
    editor.putInt("scores_numStars", mNumStars );
408
    }
409

    
410
///////////////////////////////////////////////////////////////////////////////////////////////////
411

    
412
  public synchronized void restorePreferences(SharedPreferences preferences)
413
    {
414
    String recordStr, subStr, nameStr, timeStr, submStr, errorStr="";
415
    int start, end, equals, comma, ordinal, subm;
416
    long time;
417
    boolean thereWasError = false;
418
    int numObjects = RubikObjectList.getNumObjects();
419

    
420
    for(int level=0; level<=MAX_SCRAMBLES; level++)
421
      {
422
      recordStr = preferences.getString("scores_record"+level, null);
423
      if( recordStr==null ) continue;
424
      start = end = 0;
425

    
426
      while( end!=-1 )
427
        {
428
        end = recordStr.indexOf(" ", start);
429

    
430
        if( end==-1 ) subStr = recordStr.substring(start);
431
        else          subStr = recordStr.substring(start,end);
432

    
433
        start = end+1;
434

    
435
        equals = subStr.indexOf("=");
436
        comma  = subStr.indexOf(",");
437

    
438
        if( equals>=0 && comma>=0 )
439
          {
440
          nameStr = subStr.substring(0,equals);
441
          timeStr = subStr.substring(equals+1,comma);
442
          submStr = subStr.substring(comma+1);
443

    
444
          ordinal = RubikObjectList.getOrdinal(nameStr);
445

    
446
          if( ordinal>=0 && ordinal<numObjects )
447
            {
448
            time = Long.parseLong(timeStr);
449
            subm = Integer.parseInt(submStr);
450

    
451
            if( subm>=0 && subm<=1 )
452
              {
453
              MapValue value = new MapValue(time,subm);
454
              int key = mapKey(ordinal,level);
455
              mMap.put(key,value);
456
              }
457
            else
458
              {
459
              errorStr += ("error1: subm="+subm+" obj: "+nameStr+"\n");
460
              thereWasError= true;
461
              }
462
            }
463
          else
464
            {
465
            errorStr += ("error2: object="+ordinal+" obj: "+nameStr+"\n");
466
            thereWasError = true;
467
            }
468
          }
469
        }
470
      }
471

    
472
    mName           = preferences.getString("scores_name"  , "" );
473
    mNameIsVerified = preferences.getBoolean("scores_isVerified", false);
474
    mNumPlays       = preferences.getInt("scores_numPlays", 0);
475
    mNumRuns        = preferences.getInt("scores_numRuns" , 0);
476
    mDeviceID       = preferences.getInt("scores_deviceid",-1);
477
    mNumWins        = preferences.getInt("scores_review"  , 0);
478
    mNumStars       = preferences.getInt("scores_numStars", 0);
479

    
480
    if( mDeviceID==-1 ) mDeviceID = privateGetDeviceID();
481

    
482
    if( thereWasError ) recordDBError(errorStr);
483
    }
484

    
485
///////////////////////////////////////////////////////////////////////////////////////////////////
486

    
487
  public int numberOfSolvedMAXes()
488
    {
489
    int numObjects = RubikObjectList.getNumObjects();
490
    int ret=0, level = RubikScreenPlay.LEVELS_SHOWN;
491

    
492
    for(int obj=0; obj<numObjects; obj++)
493
      {
494
      if( isSolved(obj,level) ) ret++;
495
      }
496

    
497
    return ret;
498
    }
499

    
500
///////////////////////////////////////////////////////////////////////////////////////////////////
501

    
502
  public void recordDBError(String message)
503
    {
504
    if( BuildConfig.DEBUG )
505
      {
506
      android.util.Log.e("scores", message);
507
      }
508
    else
509
      {
510
      Exception ex = new Exception(message);
511
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
512
      crashlytics.setCustomKey("scores" , message);
513
      crashlytics.recordException(ex);
514
      }
515
    }
516
  }
(3-3/4)