Project

General

Profile

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

magiccube / src / main / java / org / distorted / external / RubikScores.java @ 7bb30586

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

    
25
import static org.distorted.objectlib.main.ObjectType.MAX_SCRAMBLES;
26

    
27
///////////////////////////////////////////////////////////////////////////////////////////////////
28
// hold my own scores, and some other statistics.
29

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

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

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

    
50
  private static class MapValue
51
    {
52
    int record;
53
    boolean submitted;
54

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

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

    
64
///////////////////////////////////////////////////////////////////////////////////////////////////
65

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

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

    
73
    mNameIsVerified = false;
74

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

    
82
///////////////////////////////////////////////////////////////////////////////////////////////////
83

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

    
89
///////////////////////////////////////////////////////////////////////////////////////////////////
90

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

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

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

    
109
///////////////////////////////////////////////////////////////////////////////////////////////////
110

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

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

    
122
///////////////////////////////////////////////////////////////////////////////////////////////////
123

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

    
129
///////////////////////////////////////////////////////////////////////////////////////////////////
130

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

    
139
    return false;
140
    }
141

    
142
///////////////////////////////////////////////////////////////////////////////////////////////////
143

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

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

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

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

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

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

    
179
///////////////////////////////////////////////////////////////////////////////////////////////////
180
// Public API
181
///////////////////////////////////////////////////////////////////////////////////////////////////
182

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

    
188
///////////////////////////////////////////////////////////////////////////////////////////////////
189

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

    
195
///////////////////////////////////////////////////////////////////////////////////////////////////
196

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

    
202
///////////////////////////////////////////////////////////////////////////////////////////////////
203

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

    
209
///////////////////////////////////////////////////////////////////////////////////////////////////
210

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

    
216
///////////////////////////////////////////////////////////////////////////////////////////////////
217

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

    
223
///////////////////////////////////////////////////////////////////////////////////////////////////
224

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

    
230
///////////////////////////////////////////////////////////////////////////////////////////////////
231

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

    
238
///////////////////////////////////////////////////////////////////////////////////////////////////
239

    
240
  public void changeNumStars(int stars)
241
    {
242
    mNumStars += stars;
243
    if( mNumStars<0 ) mNumStars = 0;
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<=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, int 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 int 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 savePreferencesMinimal(SharedPreferences.Editor editor)
413
    {
414
    editor.putInt("scores_numStars", mNumStars );
415
    }
416

    
417
///////////////////////////////////////////////////////////////////////////////////////////////////
418

    
419
  public synchronized void restorePreferences(SharedPreferences preferences)
420
    {
421
    String recordStr, subStr, nameStr, timeStr, submStr, errorStr="";
422
    int start, end, equals, comma, ordinal, subm, time;
423
    boolean thereWasError = false;
424
    int numObjects = RubikObjectList.getNumObjects();
425

    
426
    for(int level=0; level<=MAX_SCRAMBLES; level++)
427
      {
428
      recordStr = preferences.getString("scores_record"+level, null);
429
      if( recordStr==null ) continue;
430
      start = end = 0;
431

    
432
      while( end!=-1 )
433
        {
434
        end = recordStr.indexOf(" ", start);
435

    
436
        if( end==-1 ) subStr = recordStr.substring(start);
437
        else          subStr = recordStr.substring(start,end);
438

    
439
        start = end+1;
440

    
441
        equals = subStr.indexOf("=");
442
        comma  = subStr.indexOf(",");
443

    
444
        if( equals>=0 && comma>=0 )
445
          {
446
          nameStr = subStr.substring(0,equals);
447
          timeStr = subStr.substring(equals+1,comma);
448
          submStr = subStr.substring(comma+1);
449

    
450
          ordinal = RubikObjectList.getOrdinal(nameStr);
451

    
452
          if( ordinal>=0 && ordinal<numObjects )
453
            {
454
            try
455
              {
456
              time = Integer.parseInt(timeStr);
457
              subm = Integer.parseInt(submStr);
458
              }
459
            catch(NumberFormatException ex)
460
              {
461
              subm = 1;
462
              time = 0;
463
              errorStr += ("error1: timeStr="+timeStr+" submStr: "+submStr+"\n");
464
              thereWasError= true;
465
              }
466

    
467
            if( subm>=0 && subm<=1 )
468
              {
469
              MapValue value = new MapValue(time,subm);
470
              int key = mapKey(ordinal,level);
471
              mMap.put(key,value);
472
              }
473
            else
474
              {
475
              errorStr += ("error1: subm="+subm+" obj: "+nameStr+"\n");
476
              thereWasError= true;
477
              }
478
            }
479
          else
480
            {
481
            errorStr += ("error2: object="+ordinal+" obj: "+nameStr+"\n");
482
            thereWasError = true;
483
            }
484
          }
485
        }
486
      }
487

    
488
    mName           = preferences.getString("scores_name"  , "" );
489
    mNameIsVerified = preferences.getBoolean("scores_isVerified", false);
490
    mNumPlays       = preferences.getInt("scores_numPlays", 0);
491
    mNumRuns        = preferences.getInt("scores_numRuns" , 0);
492
    mDeviceID       = preferences.getInt("scores_deviceid",-1);
493
    mNumWins        = preferences.getInt("scores_review"  , 0);
494
    mNumStars       = preferences.getInt("scores_numStars", 0);
495

    
496
    if( mDeviceID==-1 ) mDeviceID = privateGetDeviceID();
497

    
498
    if( thereWasError ) recordDBError(errorStr);
499
    }
500

    
501
///////////////////////////////////////////////////////////////////////////////////////////////////
502

    
503
  public int numberOfSolvedMAXes()
504
    {
505
    int numObjects = RubikObjectList.getNumObjects();
506
    int ret=0;
507

    
508
    for(int obj=0; obj<numObjects; obj++)
509
      {
510
      if( isSolved(obj,LEVELS_SHOWN) ) ret++;
511
      }
512

    
513
    return ret;
514
    }
515

    
516
///////////////////////////////////////////////////////////////////////////////////////////////////
517

    
518
  public void recordDBError(String message)
519
    {
520
    if( BuildConfig.DEBUG )
521
      {
522
      android.util.Log.e("scores", message);
523
      }
524
    else
525
      {
526
      Exception ex = new Exception(message);
527
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
528
      crashlytics.setCustomKey("scores" , message);
529
      crashlytics.recordException(ex);
530
      }
531
    }
532
  }
(3-3/4)