Project

General

Profile

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

magiccube / src / main / java / org / distorted / helpers / RubikScores.java @ 032657c3

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.helpers;
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.metadata.ListObjects.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
  private 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<0 ? MULT-1 : 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
      int level = key%MULT;
155

    
156
      if( level<MULT-1 && 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(level);
172
          builderTim.append(value.record);
173
          }
174
        }
175
      }
176

    
177
    return strObj+builderObj+strLvl+builderLvl+strTim+builderTim;
178
    }
179

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

    
184
  public boolean isVerified()     { return mNameIsVerified; }
185
  public int getNumPlays()        { return mNumPlays; }
186
  public int getNumRuns()         { return mNumRuns; }
187
  public String getName()         { return mName; }
188
  public String getCountry()      { return mCountry; }
189
  public void incrementNumPlays() { mNumPlays++; }
190
  public void incrementNumRuns()  { mNumRuns++; }
191

    
192
///////////////////////////////////////////////////////////////////////////////////////////////////
193

    
194
  public int incrementNumWins()
195
    {
196
    mNumWins++;
197
    return mNumWins;
198
    }
199

    
200
///////////////////////////////////////////////////////////////////////////////////////////////////
201

    
202
  public void changeNumStars(int stars)
203
    {
204
    mNumStars += stars;
205
    if( mNumStars<0 ) mNumStars = 0;
206
    }
207

    
208
///////////////////////////////////////////////////////////////////////////////////////////////////
209

    
210
  public int getNumStars()
211
    {
212
    return mNumStars;
213
    }
214

    
215
///////////////////////////////////////////////////////////////////////////////////////////////////
216

    
217
  public void correctNumStars()
218
    {
219
    int numObjects = RubikObjectList.getNumObjects();
220

    
221
    for(int obj=0; obj<numObjects; obj++)
222
      {
223
      for(int level=0; level<=LEVELS_SHOWN; level++)
224
        {
225
        if( isSolved(obj,level) )
226
          {
227
          int numStars = computeNumStars(level+1);
228
          mNumStars += numStars;
229
          }
230
        }
231
      }
232
    }
233

    
234
///////////////////////////////////////////////////////////////////////////////////////////////////
235

    
236
  public int computeNumStars(int level)
237
    {
238
    return level>LEVELS_SHOWN ? 50 : level;
239
    }
240

    
241
///////////////////////////////////////////////////////////////////////////////////////////////////
242

    
243
  public void setName(String newName)
244
    {
245
    mName = newName;
246
    }
247

    
248
///////////////////////////////////////////////////////////////////////////////////////////////////
249

    
250
  public synchronized int setRecord(int object, int level, int record)
251
    {
252
    int key = mapKey(object,level);
253
    MapValue oldValue = mMap.get(key);
254

    
255
    if( oldValue==null )
256
      {
257
      MapValue value = new MapValue(record,0);
258
      mMap.put(key,value);
259
      return RECORD_FIRST;
260
      }
261

    
262
    long oldRecord = oldValue.record;
263

    
264
    if( oldRecord>record )
265
      {
266
      MapValue value = new MapValue(record,0);
267
      mMap.put(key,value);
268
      return RECORD_NEW;
269
      }
270

    
271
    return RECORD_NOT_NEW;
272
    }
273

    
274
///////////////////////////////////////////////////////////////////////////////////////////////////
275

    
276
  public synchronized int getRecord(int object, int level)
277
    {
278
    int key = mapKey(object,level);
279
    MapValue value = mMap.get(key);
280
    return value!=null ? value.record : NO_RECORD;
281
    }
282

    
283
///////////////////////////////////////////////////////////////////////////////////////////////////
284

    
285
  public synchronized boolean isSolved(int object, int level)
286
    {
287
    int key = mapKey(object,level);
288
    MapValue value = mMap.get(key);
289
    return value!=null && value.record<NO_RECORD;
290
    }
291

    
292
///////////////////////////////////////////////////////////////////////////////////////////////////
293

    
294
  public void setCountry(Context context)
295
    {
296
    TelephonyManager tM =((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));
297

    
298
    if( tM!=null )
299
      {
300
      mCountry = tM.getSimCountryIso();
301

    
302
      if( mCountry==null || mCountry.length()<=1 )
303
        {
304
        mCountry = tM.getNetworkCountryIso();
305
        }
306
      }
307

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

    
312
    if( mCountry.equals("do") ) mCountry = "dm";
313
    }
314

    
315
///////////////////////////////////////////////////////////////////////////////////////////////////
316

    
317
  public void setCountry(String country)
318
    {
319
    mCountry = country;
320

    
321
    if( mCountry.equals("do") ) mCountry = "dm";  // see above
322
    }
323

    
324
///////////////////////////////////////////////////////////////////////////////////////////////////
325

    
326
  public static RubikScores getInstance()
327
    {
328
    if( mThis==null ) mThis = new RubikScores();
329
    return mThis;
330
    }
331

    
332
///////////////////////////////////////////////////////////////////////////////////////////////////
333

    
334
  public synchronized void savePreferences(SharedPreferences.Editor editor)
335
    {
336
    int numObjects = RubikObjectList.getNumObjects();
337
    StringBuilder builder = new StringBuilder();
338

    
339
    for(int level=0; level<=MAX_RECORD; level++)
340
      {
341
      builder.setLength(0);
342

    
343
      for(int object=0; object<numObjects; object++)
344
        {
345
        int key = mapKey(object,level);
346
        RubikObject obj = RubikObjectList.getObject(object);
347
        MapValue value = mMap.get(key);
348

    
349
        if( obj!=null && value!=null && value.record<NO_RECORD )
350
          {
351
          builder.append(obj.getUpperName());
352
          builder.append("=");
353
          builder.append(value.record);
354
          builder.append(",");
355
          builder.append(value.submitted ? 1:0 );
356
          builder.append(" ");
357
          }
358
        }
359

    
360
      editor.putString("scores_record"+level, builder.toString());
361
      }
362

    
363
    editor.putString("scores_name"  , mName  );
364
    editor.putBoolean("scores_isVerified", mNameIsVerified);
365
    editor.putInt("scores_numPlays", mNumPlays);
366
    editor.putInt("scores_numRuns" , mNumRuns );
367
    editor.putInt("scores_deviceid", mDeviceID);
368
    editor.putInt("scores_review"  , mNumWins );   // legacy name
369
    editor.putInt("scores_numStars", mNumStars );
370
    }
371

    
372
///////////////////////////////////////////////////////////////////////////////////////////////////
373

    
374
  public synchronized void savePreferencesMinimal(SharedPreferences.Editor editor)
375
    {
376
    editor.putInt("scores_numStars", mNumStars );
377
    }
378

    
379
///////////////////////////////////////////////////////////////////////////////////////////////////
380

    
381
  public synchronized void restorePreferences(SharedPreferences preferences)
382
    {
383
    String recordStr, subStr, nameStr, timeStr, submStr, errorStr="";
384
    int start, end, equals, comma, ordinal, subm, time;
385
    boolean thereWasError = false;
386
    int numObjects = RubikObjectList.getNumObjects();
387

    
388
    for(int level=0; level<=MAX_SCRAMBLES; level++)
389
      {
390
      recordStr = preferences.getString("scores_record"+level, null);
391
      if( recordStr==null ) continue;
392
      start = end = 0;
393

    
394
      while( end!=-1 )
395
        {
396
        end = recordStr.indexOf(" ", start);
397

    
398
        if( end==-1 ) subStr = recordStr.substring(start);
399
        else          subStr = recordStr.substring(start,end);
400

    
401
        start = end+1;
402

    
403
        equals = subStr.indexOf("=");
404
        comma  = subStr.indexOf(",");
405

    
406
        if( equals>=0 && comma>=0 )
407
          {
408
          nameStr = subStr.substring(0,equals);
409
          timeStr = subStr.substring(equals+1,comma);
410
          submStr = subStr.substring(comma+1);
411

    
412
          ordinal = RubikObjectList.getOrdinal(nameStr);
413

    
414
          if( ordinal>=0 && ordinal<numObjects )
415
            {
416
            try
417
              {
418
              time = Integer.parseInt(timeStr);
419
              subm = Integer.parseInt(submStr);
420
              }
421
            catch(NumberFormatException ex)
422
              {
423
              subm = 1;
424
              time = 0;
425
              errorStr += ("error1: timeStr="+timeStr+" submStr: "+submStr+"\n");
426
              thereWasError= true;
427
              }
428

    
429
            if( subm>=0 && subm<=1 )
430
              {
431
              MapValue value = new MapValue(time,subm);
432
              int key = mapKey(ordinal,level);
433
              mMap.put(key,value);
434
              }
435
            else
436
              {
437
              errorStr += ("error1: subm="+subm+" obj: "+nameStr+"\n");
438
              thereWasError= true;
439
              }
440
            }
441
          else
442
            {
443
            errorStr += ("error2: object="+ordinal+" obj: "+nameStr+"\n");
444
            thereWasError = true;
445
            }
446
          }
447
        }
448
      }
449

    
450
    mName           = preferences.getString("scores_name"  , "" );
451
    mNameIsVerified = preferences.getBoolean("scores_isVerified", false);
452
    mNumPlays       = preferences.getInt("scores_numPlays", 0);
453
    mNumRuns        = preferences.getInt("scores_numRuns" , 0);
454
    mDeviceID       = preferences.getInt("scores_deviceid",-1);
455
    mNumWins        = preferences.getInt("scores_review"  , 0);
456
    mNumStars       = preferences.getInt("scores_numStars", 0);
457

    
458
    if( mDeviceID==-1 ) mDeviceID = privateGetDeviceID();
459

    
460
    if( thereWasError ) recordDBError(errorStr);
461
    }
462

    
463
///////////////////////////////////////////////////////////////////////////////////////////////////
464

    
465
  public int numberOfSolvedMAXes()
466
    {
467
    int numObjects = RubikObjectList.getNumObjects();
468
    int ret=0;
469

    
470
    for(int obj=0; obj<numObjects; obj++)
471
      {
472
      if( isSolved(obj,LEVELS_SHOWN) ) ret++;
473
      }
474

    
475
    return ret;
476
    }
477

    
478
///////////////////////////////////////////////////////////////////////////////////////////////////
479

    
480
  public void recordDBError(String message)
481
    {
482
    if( BuildConfig.DEBUG )
483
      {
484
      android.util.Log.e("scores", message);
485
      }
486
    else
487
      {
488
      Exception ex = new Exception(message);
489
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
490
      crashlytics.setCustomKey("scores" , message);
491
      crashlytics.recordException(ex);
492
      }
493
    }
494
  }
(7-7/10)