/
GameActivity.kt
1015 lines (895 loc) · 34.4 KB
/
GameActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package dev.lucasnlm.antimine
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.format.DateUtils
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.TooltipCompat
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.core.view.doOnLayout
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Transformations
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import androidx.preference.PreferenceManager
import dev.lucasnlm.antimine.about.AboutActivity
import dev.lucasnlm.antimine.cloud.CloudSaveManager
import dev.lucasnlm.antimine.common.level.models.Difficulty
import dev.lucasnlm.antimine.common.level.models.Event
import dev.lucasnlm.antimine.common.level.models.Score
import dev.lucasnlm.antimine.common.level.models.Status
import dev.lucasnlm.antimine.common.level.repository.ISavesRepository
import dev.lucasnlm.antimine.common.level.viewmodel.GameViewModel
import dev.lucasnlm.antimine.control.ControlDialogFragment
import dev.lucasnlm.antimine.core.analytics.IAnalyticsManager
import dev.lucasnlm.antimine.core.analytics.models.Analytics
import dev.lucasnlm.antimine.core.control.ControlStyle
import dev.lucasnlm.antimine.core.preferences.IPreferencesRepository
import dev.lucasnlm.antimine.custom.CustomLevelDialogFragment
import dev.lucasnlm.antimine.history.HistoryActivity
import dev.lucasnlm.antimine.gameover.EndGameDialogFragment
import dev.lucasnlm.antimine.gameover.model.GameResult
import dev.lucasnlm.antimine.level.view.LevelFragment
import dev.lucasnlm.antimine.playgames.PlayGamesDialogFragment
import dev.lucasnlm.antimine.preferences.PreferencesActivity
import dev.lucasnlm.antimine.share.ShareManager
import dev.lucasnlm.antimine.splash.SplashActivity
import dev.lucasnlm.antimine.stats.StatsActivity
import dev.lucasnlm.antimine.support.SupportAppDialogFragment
import dev.lucasnlm.antimine.theme.ThemeActivity
import dev.lucasnlm.antimine.tutorial.view.TutorialCompleteDialogFragment
import dev.lucasnlm.antimine.tutorial.view.TutorialLevelFragment
import dev.lucasnlm.external.IBillingManager
import dev.lucasnlm.external.IInstantAppManager
import dev.lucasnlm.external.IFeatureFlagManager
import dev.lucasnlm.external.IPlayGamesManager
import dev.lucasnlm.external.ReviewWrapper
import dev.lucasnlm.external.model.PurchaseInfo
import kotlinx.android.synthetic.main.activity_game.*
import kotlinx.android.synthetic.main.activity_game.minesCount
import kotlinx.android.synthetic.main.activity_game.timer
import kotlinx.android.synthetic.main.activity_tv_game.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.singleOrNull
import org.koin.android.ext.android.inject
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.lang.Exception
class GameActivity : ThematicActivity(R.layout.activity_game), DialogInterface.OnDismissListener {
private val billingManager: IBillingManager by inject()
private val preferencesRepository: IPreferencesRepository by inject()
private val featureFlagManager: IFeatureFlagManager by inject()
private val analyticsManager: IAnalyticsManager by inject()
private val instantAppManager: IInstantAppManager by inject()
private val savesRepository: ISavesRepository by inject()
private val playGamesManager: IPlayGamesManager by inject()
private val shareViewModel: ShareManager by inject()
private val reviewWrapper: ReviewWrapper by inject()
val gameViewModel by viewModel<GameViewModel>()
private val cloudSaveManager by inject<CloudSaveManager>()
override val noActionBar: Boolean = true
private var status: Status = Status.PreGame
private var totalMines: Int = 0
private var totalArea: Int = 0
private var rightMines: Int = 0
private var currentTime: Long = 0
private var currentSaveId: Long = 0
private val areaSizeMultiplier by lazy { preferencesRepository.squareSizeMultiplier() }
private val currentRadius by lazy { preferencesRepository.squareRadius() }
private val useHelp by lazy { preferencesRepository.useHelp() }
private var gameToast: Toast? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
PreferenceManager.setDefaultValues(this, R.xml.preferences, false)
bindViewModel()
bindPlayGames()
bindToolbar()
bindDrawer()
bindNavigationMenu()
bindSwitchControlButton()
bindAds()
bindPrice()
findViewById<FrameLayout>(R.id.levelContainer).doOnLayout {
if (!isFinishing) {
if (!preferencesRepository.isTutorialCompleted()) {
loadGameTutorial()
} else {
loadGameFragment()
}
}
}
onOpenAppActions()
}
private fun bindPlayGames() {
lifecycleScope.launch {
withContext(Dispatchers.IO) {
silentGooglePlayLogin()
}
withContext(Dispatchers.Main) {
if (!isFinishing) {
invalidateOptionsMenu()
playGamesManager.showPlayPopUp(this@GameActivity)
}
}
}
}
private fun bindViewModel() = gameViewModel.apply {
Transformations
.distinctUntilChanged(eventObserver)
.observe(
this@GameActivity,
::onGameEvent,
)
retryObserver.observe(
this@GameActivity,
{
lifecycleScope.launch {
gameViewModel.retryGame(currentSaveId.toInt())
}
}
)
continueObserver.observe(
this@GameActivity,
{
lifecycleScope.launch {
gameViewModel.increaseErrorTolerance()
eventObserver.postValue(Event.ResumeGame)
}
}
)
shareObserver.observe(
this@GameActivity,
{
shareCurrentGame()
}
)
elapsedTimeSeconds.observe(
this@GameActivity,
{
timer.apply {
visibility = if (it == 0L) View.GONE else View.VISIBLE
text = DateUtils.formatElapsedTime(it)
}
currentTime = it
}
)
mineCount.observe(
this@GameActivity,
{
minesCount.apply {
visibility = View.VISIBLE
text = it.toString()
}
}
)
difficulty.observe(
this@GameActivity,
{
onChangeDifficulty(it)
}
)
field.observe(
this@GameActivity,
{ area ->
val mines = area.filter { it.hasMine }
totalArea = area.count()
totalMines = mines.count()
rightMines = mines.count { it.mark.isFlag() }
}
)
saveId.observe(
this@GameActivity,
{
currentSaveId = it
}
)
tips.observe(
this@GameActivity,
{
tipsCounter.text = it.toString()
}
)
}
override fun onBackPressed() {
when {
drawer.isDrawerOpen(GravityCompat.START) -> {
drawer.closeDrawer(GravityCompat.START)
gameViewModel.resumeGame()
}
else -> super.onBackPressed()
}
}
override fun onResume() {
super.onResume()
val willReset = restartIfNeed()
if (!willReset) {
if (status == Status.Running) {
gameViewModel.run {
refreshUserPreferences()
resumeGame()
}
analyticsManager.sentEvent(Analytics.Resume)
}
refreshAds()
}
}
override fun onPause() {
super.onPause()
if (status == Status.Running) {
gameViewModel.pauseGame()
}
if (isFinishing) {
analyticsManager.sentEvent(Analytics.Quit)
}
}
private fun bindToolbar() {
menu.apply {
TooltipCompat.setTooltipText(this, getString(R.string.open_menu))
setColorFilter(minesCount.currentTextColor)
setOnClickListener {
drawer.openDrawer(GravityCompat.START)
}
}
minesCount.setCompoundDrawablesWithIntrinsicBounds(
ContextCompat.getDrawable(this, usingTheme.assets.toolbarMine),
null,
null,
null
)
}
private fun disableShortcutIcon(hide: Boolean = false) {
tipsCounter.visibility = View.GONE
shortcutIcon.apply {
visibility = if (hide) View.GONE else View.VISIBLE
isClickable = false
animate().alpha(0.3f).start()
}
}
private fun bindSwitchControlButton() {
switchFlag.apply {
visibility = if (preferencesRepository.controlStyle() == ControlStyle.SwitchMarkOpen) {
View.VISIBLE
} else {
View.GONE
}
TooltipCompat.setTooltipText(this, getString(R.string.switch_control))
setImageResource(R.drawable.touch)
setColorFilter(minesCount.currentTextColor)
setOnClickListener {
if (preferencesRepository.openUsingSwitchControl()) {
gameViewModel.refreshUseOpenOnSwitchControl(false)
preferencesRepository.setSwitchControl(false)
setImageResource(R.drawable.flag_black)
} else {
gameViewModel.refreshUseOpenOnSwitchControl(true)
preferencesRepository.setSwitchControl(true)
setImageResource(R.drawable.touch)
}
}
}
}
private fun refreshInGameShortcut() {
if (preferencesRepository.useHelp()) {
refreshTipShortcutIcon()
} else {
refreshRetryShortcut()
}
}
private fun refreshTipShortcutIcon() {
tipsCounter.apply {
visibility = View.VISIBLE
text = gameViewModel.getTips().toString()
}
shortcutIcon.apply {
TooltipCompat.setTooltipText(this, getString(R.string.help))
setImageResource(R.drawable.tip)
setColorFilter(minesCount.currentTextColor)
visibility = View.VISIBLE
animate().alpha(1.0f).start()
setOnClickListener {
lifecycleScope.launch {
analyticsManager.sentEvent(Analytics.UseTip)
if (gameViewModel.getTips() > 0) {
if (!gameViewModel.revealRandomMine()) {
Toast.makeText(applicationContext, R.string.cant_do_it_now, Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(applicationContext, R.string.help_win_a_game, Toast.LENGTH_SHORT).show()
}
}
}
}
}
private fun refreshRetryShortcut() {
shortcutIcon.apply {
TooltipCompat.setTooltipText(this, getString(R.string.new_game))
setImageResource(R.drawable.retry)
setColorFilter(minesCount.currentTextColor)
setOnClickListener {
lifecycleScope.launch {
val confirmResign = status == Status.Running
analyticsManager.sentEvent(Analytics.TapGameReset(confirmResign))
if (confirmResign) {
newGameConfirmation {
GlobalScope.launch {
gameViewModel.startNewGame()
}
}
} else {
GlobalScope.launch {
gameViewModel.startNewGame()
}
}
}
}
}
tipsCounter.visibility = View.GONE
shortcutIcon.apply {
when (status) {
is Status.Over, is Status.Running -> {
isClickable = true
animate().alpha(1.0f).start()
}
else -> {
isClickable = false
animate().alpha(0.3f).start()
}
}
}
}
private fun bindDrawer() {
drawer.apply {
addDrawerListener(
ActionBarDrawerToggle(
this@GameActivity,
drawer,
toolbar,
R.string.open_menu,
R.string.close_menu
).apply {
syncState()
}
)
addDrawerListener(
object : DrawerLayout.DrawerListener {
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
// Empty
}
override fun onDrawerOpened(drawerView: View) {
gameViewModel.pauseGame()
analyticsManager.sentEvent(Analytics.OpenDrawer)
}
override fun onDrawerClosed(drawerView: View) {
if (hasNoOtherFocusedDialog() && hasActiveGameFragment()) {
gameViewModel.resumeGame()
}
analyticsManager.sentEvent(Analytics.CloseDrawer)
}
override fun onDrawerStateChanged(newState: Int) {
// Empty
}
}
)
if (preferencesRepository.isFirstUse() &&
(preferencesRepository.isTutorialCompleted())
) {
openDrawer(GravityCompat.START)
preferencesRepository.completeFirstUse()
}
}
}
private fun bindNavigationMenu() {
navigationView.setNavigationItemSelectedListener { item ->
var handled = true
when (item.itemId) {
R.id.standard -> changeDifficulty(Difficulty.Standard)
R.id.beginner -> changeDifficulty(Difficulty.Beginner)
R.id.intermediate -> changeDifficulty(Difficulty.Intermediate)
R.id.expert -> changeDifficulty(Difficulty.Expert)
R.id.custom -> showCustomLevelDialog()
R.id.control -> showControlDialog()
R.id.about -> showAbout()
R.id.settings -> showSettings()
R.id.rate -> openRateUsLink()
R.id.themes -> openThemes()
R.id.share_now -> shareCurrentGame()
R.id.previous_games -> openSaveHistory()
R.id.stats -> openStats()
R.id.play_games -> googlePlay()
R.id.translation -> openCrowdIn()
R.id.remove_ads -> showSupportAppDialog()
R.id.tutorial -> loadGameTutorial()
else -> handled = false
}
if (handled) {
drawer.closeDrawer(GravityCompat.START)
}
handled
}
navigationView.menu.apply {
val isNotInstant = !instantAppManager.isEnabled(applicationContext)
findItem(R.id.share_now).isVisible = isNotInstant
findItem(R.id.remove_ads).isVisible = !preferencesRepository.isPremiumEnabled() && isNotInstant
findItem(R.id.previous_games).isVisible = featureFlagManager.isGameHistoryEnabled()
findItem(R.id.rate).isVisible = featureFlagManager.isRateUsEnabled()
if (!playGamesManager.hasGooglePlayGames()) {
removeGroup(R.id.play_games_group)
}
}
}
private fun onOpenAppActions() {
if (instantAppManager.isEnabled(applicationContext)) {
// Instant App does nothing.
savesRepository.setLimit(1)
} else {
val current = preferencesRepository.getUseCount()
val shouldRequestSupport = if (billingManager.isEnabled()) {
!preferencesRepository.isPremiumEnabled()
} else {
preferencesRepository.showSupport()
}
if (current >= MIN_USAGES_TO_IAP && shouldRequestSupport) {
analyticsManager.sentEvent(Analytics.UnlockIapDialog)
showSupportAppDialog()
}
reviewWrapper.startInAppReview(this)
preferencesRepository.incrementUseCount()
}
}
private fun onChangeDifficulty(difficulty: Difficulty) {
loadGameFragment()
navigationView.menu.apply {
arrayOf(
Difficulty.Standard to findItem(R.id.standard),
Difficulty.Beginner to findItem(R.id.beginner),
Difficulty.Intermediate to findItem(R.id.intermediate),
Difficulty.Expert to findItem(R.id.expert),
Difficulty.Custom to findItem(R.id.custom)
).map {
it.second to (if (it.first == difficulty) R.drawable.checked else R.drawable.unchecked)
}.forEach { (menuItem, icon) ->
menuItem.setIcon(icon)
}
}
}
private fun loadGameFragment() {
supportFragmentManager.apply {
findFragmentByTag(TutorialLevelFragment.TAG)?.let { it ->
beginTransaction().apply {
remove(it)
commitAllowingStateLoss()
}
}
if (findFragmentByTag(LevelFragment.TAG) == null) {
beginTransaction().apply {
replace(R.id.levelContainer, LevelFragment(), LevelFragment.TAG)
setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
commitAllowingStateLoss()
}
}
}
}
private fun loadGameTutorial() {
disableShortcutIcon(false)
supportFragmentManager.apply {
findFragmentById(R.id.levelContainer)?.let { it ->
beginTransaction().apply {
remove(it)
commitAllowingStateLoss()
}
}
beginTransaction().apply {
replace(R.id.levelContainer, TutorialLevelFragment(), TutorialLevelFragment.TAG)
setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
commitAllowingStateLoss()
}
}
}
private fun newGameConfirmation(action: () -> Unit) {
AlertDialog.Builder(this).apply {
setTitle(R.string.new_game)
setMessage(R.string.retry_sure)
setPositiveButton(R.string.resume) { _, _ -> action() }
setNegativeButton(R.string.cancel, null)
show()
}
}
private fun showCustomLevelDialog() {
preferencesRepository.completeTutorial()
if (supportFragmentManager.findFragmentByTag(CustomLevelDialogFragment.TAG) == null) {
CustomLevelDialogFragment().apply {
show(supportFragmentManager, CustomLevelDialogFragment.TAG)
}
}
}
private fun showControlDialog() {
gameViewModel.pauseGame()
if (supportFragmentManager.findFragmentByTag(CustomLevelDialogFragment.TAG) == null) {
ControlDialogFragment().apply {
show(supportFragmentManager, ControlDialogFragment.TAG)
}
}
}
private fun showAbout() {
analyticsManager.sentEvent(Analytics.OpenAbout)
Intent(this, AboutActivity::class.java).apply {
startActivity(this)
}
}
private fun openThemes() {
analyticsManager.sentEvent(Analytics.OpenThemes)
Intent(this, ThemeActivity::class.java).apply {
startActivity(this)
}
}
private fun openSaveHistory() {
analyticsManager.sentEvent(Analytics.OpenSaveHistory)
Intent(this, HistoryActivity::class.java).apply {
startActivity(this)
}
}
private fun openStats() {
analyticsManager.sentEvent(Analytics.OpenStats)
Intent(this, StatsActivity::class.java).apply {
startActivity(this)
}
}
private fun showSettings() {
analyticsManager.sentEvent(Analytics.OpenSettings)
Intent(this, PreferencesActivity::class.java).apply {
startActivity(this)
}
}
private fun showCompletedTutorialDialog() {
TutorialCompleteDialogFragment().run {
showAllowingStateLoss(supportFragmentManager, TutorialCompleteDialogFragment.TAG)
}
}
private fun showEndGameDialog(gameResult: GameResult, canContinue: Boolean) {
val currentGameStatus = status
if (currentGameStatus is Status.Over && !isFinishing && !drawer.isDrawerOpen(GravityCompat.START)) {
if (supportFragmentManager.findFragmentByTag(SupportAppDialogFragment.TAG) == null &&
supportFragmentManager.findFragmentByTag(EndGameDialogFragment.TAG) == null
) {
val score = currentGameStatus.score
EndGameDialogFragment.newInstance(
gameResult,
canContinue,
score?.rightMines ?: 0,
score?.totalMines ?: 0,
currentGameStatus.time,
if (gameResult == GameResult.Victory) 2 else 1
).apply {
showAllowingStateLoss(supportFragmentManager, EndGameDialogFragment.TAG)
}
}
}
}
private fun showEndGameToast(gameResult: GameResult) {
gameToast?.cancel()
val message = when (gameResult) {
GameResult.GameOver -> R.string.you_lost
GameResult.Victory -> R.string.you_won
GameResult.Completed -> R.string.you_finished
}
gameToast = Toast.makeText(this, message, Toast.LENGTH_LONG).apply {
setGravity(Gravity.CENTER, 0, 0)
show()
}
}
private fun showEndGameAlert(gameResult: GameResult, canContinue: Boolean) {
val canShowWindow = preferencesRepository.showWindowsWhenFinishGame()
if (!isFinishing) {
if (canShowWindow) {
showEndGameDialog(gameResult, gameResult == GameResult.GameOver && canContinue)
} else {
if (gameResult != GameResult.Victory) {
gameViewModel.viewModelScope.launch {
gameViewModel.revealMines()
}
}
showEndGameToast(gameResult)
}
}
}
private fun waitAndShowEndGameAlert(gameResult: GameResult, await: Boolean, canContinue: Boolean) {
if (await && gameViewModel.explosionDelay() != 0L) {
lifecycleScope.launch {
delay((gameViewModel.explosionDelay() * 0.3).toLong())
showEndGameAlert(gameResult, canContinue)
}
} else {
showEndGameAlert(gameResult, canContinue)
}
}
private fun changeDifficulty(newDifficulty: Difficulty) {
preferencesRepository.completeTutorial()
if (status == Status.PreGame) {
lifecycleScope.launch {
gameViewModel.startNewGame(newDifficulty)
}
} else {
newGameConfirmation {
lifecycleScope.launch {
gameViewModel.startNewGame(newDifficulty)
}
}
}
}
private fun onGameEvent(event: Event) {
when (event) {
Event.ResumeGame -> {
status = Status.Running
refreshInGameShortcut()
refreshAds()
}
Event.StartNewGame -> {
gameToast?.cancel()
loadGameFragment()
status = Status.PreGame
disableShortcutIcon()
refreshAds()
}
Event.Resume, Event.Running -> {
status = Status.Running
gameViewModel.runClock()
refreshInGameShortcut()
keepScreenOn(true)
}
Event.StartTutorial -> {
status = Status.PreGame
gameViewModel.stopClock()
disableShortcutIcon(false)
loadGameTutorial()
}
Event.FinishTutorial -> {
gameViewModel.startNewGame(Difficulty.Beginner)
disableShortcutIcon()
loadGameFragment()
status = Status.Over(0, Score(4, 4, 25))
analyticsManager.sentEvent(Analytics.TutorialCompleted)
preferencesRepository.completeTutorial()
showCompletedTutorialDialog()
cloudSaveManager.uploadSave()
}
Event.Victory -> {
val isResuming = (status == Status.PreGame)
val score = Score(
rightMines,
totalMines,
totalArea
)
status = Status.Over(currentTime, score)
gameViewModel.stopClock()
gameViewModel.showAllEmptyAreas()
gameViewModel.victory()
refreshRetryShortcut()
keepScreenOn(false)
if (!isResuming) {
lifecycleScope.launch {
gameViewModel.saveGame()
gameViewModel.saveStats()
}
cloudSaveManager.uploadSave()
gameViewModel.addNewTip()
waitAndShowEndGameAlert(
gameResult = GameResult.Victory,
await = false,
canContinue = false,
)
}
}
Event.GameOver -> {
val isResuming = (status == Status.PreGame)
val score = Score(
rightMines,
totalMines,
totalArea
)
status = Status.Over(currentTime, score)
refreshRetryShortcut()
keepScreenOn(false)
gameViewModel.stopClock()
if (!isResuming) {
cloudSaveManager.uploadSave()
lifecycleScope.launch {
gameViewModel.gameOver(isResuming)
gameViewModel.saveGame()
waitAndShowEndGameAlert(
gameResult = if (gameViewModel.isCompletedWithMistakes())
GameResult.Completed else GameResult.GameOver,
await = true,
canContinue = gameViewModel.hasUnknownMines(),
)
}
}
}
else -> { }
}
}
/**
* If user change any accessibility preference, the game will restart the activity to
* apply these changes.
*/
private fun restartIfNeed(): Boolean {
return (
areaSizeMultiplier != preferencesRepository.squareSizeMultiplier() ||
currentRadius != preferencesRepository.squareRadius() ||
useHelp != preferencesRepository.useHelp()
).also {
if (it) {
finish()
startActivity(intent)
overridePendingTransition(0, 0)
}
}
}
private fun shareCurrentGame() {
val levelSetup = gameViewModel.levelSetup.value
val field = gameViewModel.field.value
lifecycleScope.launch {
shareViewModel.shareField(levelSetup, field)
}
}
private fun openRateUsLink() {
reviewWrapper.startReviewPage(this, BuildConfig.VERSION_NAME)
analyticsManager.sentEvent(Analytics.TapRatingRequest)
preferencesRepository.disableRequestRating()
}
private fun keepScreenOn(enabled: Boolean) {
if (enabled) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
private fun hasNoOtherFocusedDialog(): Boolean {
return supportFragmentManager.fragments.count {
it !is LevelFragment && it is DialogFragment
} == 0
}
private fun hasActiveGameFragment(): Boolean {
return supportFragmentManager.findFragmentByTag(LevelFragment.TAG) != null
}
override fun onDismiss(dialog: DialogInterface?) {
gameViewModel.run {
refreshUserPreferences()
resumeGame()
}
bindSwitchControlButton()
refreshAds()
}
private fun bindAds() {
refreshAds()
if (!preferencesRepository.isPremiumEnabled()) {
lifecycleScope.launchWhenCreated {
billingManager.listenPurchases().collect {
if (it is PurchaseInfo.PurchaseResult) {
if (it.unlockStatus && !isFinishing) {
refreshAds()
}
}
}
}
}
}
private fun bindPrice() {
if (billingManager.isEnabled() && !preferencesRepository.isPremiumEnabled()) {
billingManager.start()
lifecycleScope.launchWhenResumed {
billingManager.getPrice().collect { price ->
if (price.isNotBlank()) {
try {
navigationView.menu.findItem(R.id.remove_ads).apply {
actionView = TextView(baseContext).apply {
text = price
gravity = Gravity.CENTER_VERTICAL
setTextColor(ContextCompat.getColor(context, R.color.mines_around_2))
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT,
).apply {
gravity = Gravity.CENTER
}
}
}
} catch (e: Exception) {
Log.e(TAG, "Fail to create price text")
}
}
}
}
}
}
private fun refreshAds() {
val isTutorialComplete = preferencesRepository.isTutorialCompleted()
if (isTutorialComplete && !preferencesRepository.isPremiumEnabled() && billingManager.isEnabled()) {
if (!instantAppManager.isEnabled(this)) {
navigationView.menu.setGroupVisible(R.id.remove_ads_group, true)
ad_placeholder.visibility = View.VISIBLE
ad_placeholder.loadAd()
}
} else {
navigationView.menu.setGroupVisible(R.id.remove_ads_group, false)
ad_placeholder.visibility = View.GONE
}
}
private fun silentGooglePlayLogin(): Boolean {
return if (playGamesManager.hasGooglePlayGames()) {
try {
playGamesManager.silentLogin()
} catch (e: Exception) {
Log.e(TAG, "User not logged in Play Games")
false
}
} else {
false
}
}
private fun googlePlay() {
if (playGamesManager.isLogged()) {
if (supportFragmentManager.findFragmentByTag(PlayGamesDialogFragment.TAG) == null) {
PlayGamesDialogFragment().show(supportFragmentManager, PlayGamesDialogFragment.TAG)
}
} else {
playGamesManager.getLoginIntent()?.let {
ActivityCompat.startActivityForResult(this, it, GOOGLE_PLAY_REQUEST_CODE, null)
}
}
}
private fun openCrowdIn() {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://crowdin.com/project/antimine-android")))
}
private fun showSupportAppDialog() {
if (supportFragmentManager.findFragmentByTag(SupportAppDialogFragment.TAG) == null &&
!instantAppManager.isEnabled(this)
) {
lifecycleScope.launch {
if (billingManager.isEnabled()) {
SupportAppDialogFragment.newRemoveAdsSupportDialog(
applicationContext,
billingManager.getPrice().singleOrNull()
).show(supportFragmentManager, SupportAppDialogFragment.TAG)
} else {
SupportAppDialogFragment.newRequestSupportDialog(applicationContext)
.show(supportFragmentManager, SupportAppDialogFragment.TAG)
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == GOOGLE_PLAY_REQUEST_CODE) {
playGamesManager.handleLoginResult(data)
goToSplashScreen()
}
}