Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor: link to db for stats page #51

Merged
merged 21 commits into from
Apr 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions .cirrus.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ check_android_task:
adb wait-for-device
adb shell input keyevent 82
disable_animations_script: |
adb shell settings put global window_animation_scale 0.0
adb shell settings put global transition_animation_scale 0.0
adb shell settings put global animator_duration_scale 0.0
adb shell settings put global window_animation_scale 0
adb shell settings put global transition_animation_scale 0
adb shell settings put global animator_duration_scale 0
adb shell am instrument -e disableAnalytics true
prepare_codeclimate_script: |
curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
chmod +x ./cc-test-reporter
Expand Down
21 changes: 21 additions & 0 deletions .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 6 additions & 8 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ android {
exclude 'META-INF/ASL2.0'
exclude("META-INF/*.kotlin_module")
}

testOptions {
animationsDisabled = true
}
}

dependencies {
Expand All @@ -84,21 +88,14 @@ dependencies {
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.preference:preference-ktx:1.2.0'

// androidTestImplementation 'org.jetbrains.kotlin:kotlin-test'
// androidTestImplementation(platform("org.junit:junit-bom:5.8.2"))
// androidTestImplementation("org.junit.jupiter:junit-jupiter")

implementation 'org.jetbrains.kotlin:kotlin-test'
implementation(platform("org.junit:junit-bom:5.8.2"))
implementation("org.junit.jupiter:junit-jupiter")

androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test:runner:1.4.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.4.0'
androidTestImplementation('androidx.test.espresso:espresso-contrib:3.4.0') {
exclude module: "protobuf-lite"
}

// Import the BoM for the Firebase platform
implementation platform('com.google.firebase:firebase-bom:29.3.0')

Expand All @@ -114,6 +111,7 @@ dependencies {
// When using the BoM, you don't specify versions in Firebase library dependencies
implementation 'com.google.firebase:firebase-storage-ktx'


implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.6.0-native-mt'

testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.0-native-mt'
Expand Down
26 changes: 25 additions & 1 deletion app/google-services.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,30 @@
}
},
"oauth_client": [
{
"client_id": "896605409351-3p9vl7asmio8n203nl3c5dvpltabqaef.apps.googleusercontent.com",
"client_type": 1,
"android_info": {
"package_name": "ch.epfl.sweng.rps",
"certificate_hash": "42c8abab52db9fbe6d0b5ebecabfcb7b4789c3b9"
}
},
{
"client_id": "896605409351-grb5odgm0mdgd7gm4h5h63vsu1q20isq.apps.googleusercontent.com",
"client_type": 1,
"android_info": {
"package_name": "ch.epfl.sweng.rps",
"certificate_hash": "0a546f684af290f83c0defd7aa90578ea66e64d8"
}
},
{
"client_id": "896605409351-t2onu1c6ifnkhqr99g5iq0sb3tfhuoeg.apps.googleusercontent.com",
"client_type": 1,
"android_info": {
"package_name": "ch.epfl.sweng.rps",
"certificate_hash": "dd763a19fafbd8eee2200242b0c779c82dcbc587"
}
},
{
"client_id": "896605409351-a1hlsfr6dkigthpbeul0ug46c8774uoa.apps.googleusercontent.com",
"client_type": 3
Expand All @@ -36,4 +60,4 @@
}
],
"configuration_version": "1"
}
}
116 changes: 115 additions & 1 deletion app/src/main/java/ch/epfl/sweng/rps/db/FirebaseHelper.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
package ch.epfl.sweng.rps.db

import ch.epfl.sweng.rps.models.Hand
import ch.epfl.sweng.rps.models.RoundStat
import ch.epfl.sweng.rps.models.User
import ch.epfl.sweng.rps.models.UserStat
import ch.epfl.sweng.rps.services.ServiceLocator
import java.text.SimpleDateFormat
import java.util.*
import kotlin.Exception

sealed class FirebaseHelper {
companion object {
fun processUserArguments(vararg pairs: Pair<User.Field, Any>): Map<String, Any> {
return pairs.associate { t -> t.first.value to t.second }
}


fun userFrom(uid: String, name: String?, email: String?): User {
return User(
email = email,
Expand All @@ -18,5 +24,113 @@ sealed class FirebaseHelper {
uid = uid,
)
}

private val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE)

suspend fun getStatsData(selectMode: Int): List<UserStat> {
val firebaseRepository = ServiceLocator.getInstance().getFirebaseRepository()
val userid = firebaseRepository.rawCurrentUid()
?: return listOf(
UserStat(
gameId = "gameId1",
date = dateFormat.format(Date()),
opponents = "userIdOpp",
roundMode = "1",
score = "1 - 0"
)
)
val userGameList = firebaseRepository.gamesOfUser(userid)
val allStatsResult = mutableListOf<UserStat>()
for (userGame in userGameList) {
val userStat = UserStat()
val game = firebaseRepository.getGame(userGame.id) ?: continue
val players = game.players
val opponents = mutableListOf<String>()
for (p in players) {
if (p != userid) {
val user = firebaseRepository.getUser(p)
if (user != null)
opponents.add(user.username ?: p)
}
}

val gameRounds = game.rounds
val allRoundScores = gameRounds.map { it.value.computeScores() }

val userScore = allRoundScores.asSequence().map { scores ->
val max = scores.maxOf { it.points }
if (scores.any { it.points == max && it.uid == userid && !scores.all { it.points == max } })
1
else
0

}.sum()

val roundMode = game.mode.rounds
//by default 1v1 here, so just use overall rounds minus his score
val opponentScore = roundMode.minus(userScore)
// should be shown like "3 - 2 "
val score = "$userScore - $opponentScore"
val date =
dateFormat.format(game.timestamp.toDate())
userStat.gameId = game.id
userStat.date = date
// Pass the id temporarily since I am not sure how to get name from id
userStat.opponents = opponents.joinToString(",") { it }
userStat.roundMode = roundMode.toString()
userStat.score = score

//mode filter, selectMode = 0 means by default to fetch all result
// todo: map selectMode (best of X) in UI to Game round number
if (roundMode == selectMode || selectMode == 0) {
allStatsResult.add(userStat)
}
}
return allStatsResult


}

suspend fun getMatchDetailData(gid: String): List<RoundStat> {
val userid = ServiceLocator.getInstance().getFirebaseRepository().rawCurrentUid()
?: return listOf(
RoundStat(
index = 0,
date = Date(),
userHand = Hand.PAPER,
opponentHand = Hand.SCISSORS,
outcome = Hand.Result.LOSS
)
)
val game = ServiceLocator.getInstance().getFirebaseRepository().getGame(gid)
?: throw Exception("Game not found")
// note: 1 v 1 logic, if we support pvp mode, the table should be iterated to change as well.
// get opponent user id from player list
val opponentId: String = game.players.first { it != userid }
val allDetailsList = game.rounds.entries.mapIndexed { i, round ->
val hand = round.value.hands
val score = round.value.computeScores()
// id means choice ()
val userHand = hand[userid]!!
val opponentHand = hand[opponentId]!!
val outcome = when {
score[0].uid == userid -> Hand.Result.WIN
score[0].points == 0 -> Hand.Result.TIE
else -> Hand.Result.LOSS
}

RoundStat(
outcome = outcome,
index = i,
opponentHand = opponentHand,
userHand = userHand,
date = game.timestamp.toDate()
)
}

return allDetailsList
}


}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ class FirebaseRepository(

override suspend fun updateUser(vararg pairs: Pair<User.Field, Any>) {
val arguments = FirebaseHelper.processUserArguments(*pairs)

val uid = getCurrentUid()
firebase.usersCollection.document(uid).update(arguments).await()
}
Expand Down
17 changes: 9 additions & 8 deletions app/src/main/java/ch/epfl/sweng/rps/models/Game.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ch.epfl.sweng.rps.models

import com.google.firebase.Timestamp
import java.util.*


/**
Expand All @@ -13,14 +14,14 @@ import com.google.firebase.Timestamp
* @property timestamp The timestamp of the game
*/
data class Game(
val id: String,
val players: List<String>,
val rounds: Map<String, Round>,
val current_round: Int,
val game_mode: String,
val done: Boolean,
val timestamp: Timestamp,
val player_count: Int
val id: String = "",
val players: List<String> = listOf(),
val rounds: Map<String, Round> = mapOf(),
val current_round: Int = 0,
val game_mode: String = "",
val done: Boolean = true,
val timestamp: Timestamp = Timestamp(Date(0)),
val player_count: Int = 0
) {
/**
* Represents a game mode.
Expand Down
23 changes: 22 additions & 1 deletion app/src/main/java/ch/epfl/sweng/rps/models/Hand.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,21 @@ enum class Hand(val id: Int) {
}
}

fun asEmoji(): String = when (this) {
Hand.NONE -> "❌"
Hand.ROCK -> "🪨"
Hand.PAPER -> "📄"
Hand.SCISSORS -> "✂️"
}

fun asHandEmoji(): String = when (this) {
Hand.NONE -> "❔"
Hand.ROCK -> "✊"
Hand.PAPER -> "🤚"
Hand.SCISSORS -> "✌️"
}


private fun losesTo(hand: Hand): Boolean {
val loss = when (this) {
ROCK -> listOf(PAPER)
Expand Down Expand Up @@ -44,6 +59,12 @@ enum class Hand(val id: Int) {
}

enum class Result {
WIN, LOSS, TIE
WIN, LOSS, TIE;

fun asEmoji(): String = when (this) {
WIN -> "🏆"
LOSS -> "😢"
TIE -> "🤝"
}
}
}
5 changes: 3 additions & 2 deletions app/src/main/java/ch/epfl/sweng/rps/models/Round.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ package ch.epfl.sweng.rps.models
import ch.epfl.sweng.rps.models.Hand.Result
import ch.epfl.sweng.rps.models.PointSystem.*
import com.google.firebase.Timestamp
import java.util.*

/*
* This file is part of rps-android
* pa
*/
data class Round(
val hands: Map<String, Hand>,
val timestamp: Timestamp,
val hands: Map<String, Hand> = mapOf(),
val timestamp: Timestamp = Timestamp(Date(0)),
) {
fun computeScores(pointSystem: PointSystem = DefaultPointSystem()): List<Score> {
val points = hashMapOf<String, List<Result>>()
Expand Down
11 changes: 11 additions & 0 deletions app/src/main/java/ch/epfl/sweng/rps/models/RoundStat.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ch.epfl.sweng.rps.models

import java.util.*

data class RoundStat(
val index: Int,
val date: Date,
val userHand: Hand,
val opponentHand: Hand,
val outcome: Hand.Result
)
11 changes: 11 additions & 0 deletions app/src/main/java/ch/epfl/sweng/rps/models/UserStat.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ch.epfl.sweng.rps.models

data class UserStat(

var gameId: String = "",
var date: String = "",
var opponents: String = "",
var roundMode: String = "",
var score: String = ""

)
Loading