games: add games hub app with cross-game achievement tracking
- Commit
ecd79a7818ca006b1347b04d77c9d7162a9f81d5- Author
- Vayun Mathur <[email protected]>
- When
- 2026-06-11 20:37 UTC (5 months ago)
- Parents
d6100ad
Diff
games/app/build.gradle.kts
diff --git a/games/app/build.gradle.kts b/games/app/build.gradle.ktsnew file mode 100644index 0000000000..6b19aba112--- /dev/null+++ b/games/app/build.gradle.kts@@ -0,0 +1,15 @@+plugins {+ id("common-conventions-app")+ alias(libs.plugins.ksp)+}++android {+ defaultConfig {+ applicationId = "com.vayunmathur.games"+ }+}++dependencies {+ implementation(project(":library"))+ implementRoom(libs)+}
games/app/src/main/AndroidManifest.xml
diff --git a/games/app/src/main/AndroidManifest.xml b/games/app/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..00329be2ee--- /dev/null+++ b/games/app/src/main/AndroidManifest.xml@@ -0,0 +1,29 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <application+ android:allowBackup="true"+ android:dataExtractionRules="@xml/data_extraction_rules"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@style/Theme.General">++ <activity+ android:name="com.vayunmathur.games.MainActivity"+ android:exported="true"+ android:theme="@style/Theme.General">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>++ <provider+ android:name="com.vayunmathur.games.data.GameHubProvider"+ android:authorities="com.vayunmathur.games.provider"+ android:exported="true" />+ </application>++</manifest>
games/app/src/main/java/com/vayunmathur/games/MainActivity.kt
diff --git a/games/app/src/main/java/com/vayunmathur/games/MainActivity.kt b/games/app/src/main/java/com/vayunmathur/games/MainActivity.ktnew file mode 100644index 0000000000..a1a8445cb3--- /dev/null+++ b/games/app/src/main/java/com/vayunmathur/games/MainActivity.kt@@ -0,0 +1,316 @@+package com.vayunmathur.games++import android.content.Intent+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Card+import androidx.compose.material3.CardDefaults+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.NavigationBar+import androidx.compose.material3.NavigationBarItem+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.data.AchievementEntity+import com.vayunmathur.games.data.GameHubDatabase+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.buildDatabase+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++data class GameInfo(+ val id: String,+ val name: String,+ val packageName: String+)++val ALL_GAMES = listOf(+ GameInfo("chess", "Chess", "com.vayunmathur.games.chess"),+ GameInfo("solitaire", "Solitaire", "com.vayunmathur.games.solitaire"),+ GameInfo("pipes", "Pipes", "com.vayunmathur.games.pipes"),+ GameInfo("unblockjam", "Unblock Jam", "com.vayunmathur.games.unblockjam"),+ GameInfo("alchemist", "Alchemist", "com.vayunmathur.games.alchemist"),+ GameInfo("wordmaker", "Word Maker", "com.vayunmathur.games.wordmaker")+)++class MainActivity : ComponentActivity() {+ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()+ setContent {+ DynamicTheme {+ GameHubApp()+ }+ }+ }+}++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun GameHubApp() {+ var selectedTab by remember { mutableIntStateOf(0) }+ val tabs = listOf("Games", "Achievements", "Stats")++ Scaffold(+ topBar = {+ TopAppBar(title = { Text("Games Hub") })+ },+ bottomBar = {+ NavigationBar {+ tabs.forEachIndexed { index, title ->+ NavigationBarItem(+ selected = selectedTab == index,+ onClick = { selectedTab = index },+ icon = {+ Icon(+ painterResource(+ when (index) {+ 0 -> android.R.drawable.ic_menu_slideshow+ 1 -> android.R.drawable.btn_star_big_on+ else -> android.R.drawable.ic_menu_sort_by_size+ }+ ),+ contentDescription = title+ )+ },+ label = { Text(title) }+ )+ }+ }+ }+ ) { padding ->+ when (selectedTab) {+ 0 -> GamesGrid(Modifier.padding(padding))+ 1 -> AchievementsView(Modifier.padding(padding))+ 2 -> StatsView(Modifier.padding(padding))+ }+ }+}++@Composable+fun GamesGrid(modifier: Modifier = Modifier) {+ val context = LocalContext.current+ LazyVerticalGrid(+ columns = GridCells.Fixed(2),+ modifier = modifier.fillMaxSize(),+ contentPadding = PaddingValues(16.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ items(ALL_GAMES) { game ->+ Card(+ modifier = Modifier+ .fillMaxWidth()+ .clickable {+ val intent = context.packageManager.getLaunchIntentForPackage(game.packageName)+ if (intent != null) {+ context.startActivity(intent)+ }+ },+ shape = RoundedCornerShape(16.dp)+ ) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(24.dp),+ horizontalAlignment = Alignment.CenterHorizontally+ ) {+ Icon(+ painterResource(android.R.drawable.ic_menu_slideshow),+ contentDescription = game.name,+ modifier = Modifier.size(48.dp),+ tint = MaterialTheme.colorScheme.primary+ )+ Spacer(Modifier.height(8.dp))+ Text(+ game.name,+ style = MaterialTheme.typography.titleMedium,+ fontWeight = FontWeight.Bold+ )+ }+ }+ }+ }+}++@Composable+fun AchievementsView(modifier: Modifier = Modifier) {+ val context = LocalContext.current+ var achievements by remember { mutableStateOf<List<AchievementEntity>>(emptyList()) }+ var selectedGame by remember { mutableStateOf<String?>(null) }++ LaunchedEffect(selectedGame) {+ withContext(Dispatchers.IO) {+ val db = buildDatabase<GameHubDatabase>(context)+ achievements = if (selectedGame != null) {+ db.achievementDao().getByGame(selectedGame!!)+ } else {+ db.achievementDao().getAll()+ }+ }+ }++ Column(modifier.fillMaxSize()) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 16.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ Card(+ modifier = Modifier.clickable { selectedGame = null },+ colors = CardDefaults.cardColors(+ containerColor = if (selectedGame == null) MaterialTheme.colorScheme.primaryContainer+ else MaterialTheme.colorScheme.surfaceVariant+ )+ ) {+ Text("All", Modifier.padding(horizontal = 12.dp, vertical = 6.dp))+ }+ ALL_GAMES.forEach { game ->+ Card(+ modifier = Modifier.clickable { selectedGame = game.id },+ colors = CardDefaults.cardColors(+ containerColor = if (selectedGame == game.id) MaterialTheme.colorScheme.primaryContainer+ else MaterialTheme.colorScheme.surfaceVariant+ )+ ) {+ Text(game.name, Modifier.padding(horizontal = 12.dp, vertical = 6.dp), style = MaterialTheme.typography.labelSmall)+ }+ }+ }++ LazyColumn(+ contentPadding = PaddingValues(16.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ items(achievements) { entity ->+ Card(+ modifier = Modifier.fillMaxWidth(),+ shape = RoundedCornerShape(12.dp),+ colors = CardDefaults.cardColors(+ containerColor = if (entity.unlocked) MaterialTheme.colorScheme.secondaryContainer+ else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)+ )+ ) {+ Row(+ modifier = Modifier.padding(16.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Icon(+ painterResource(android.R.drawable.btn_star_big_on),+ contentDescription = null,+ modifier = Modifier.size(40.dp),+ tint = if (entity.unlocked) Color(0xFFFFD700) else Color.Gray+ )+ Spacer(Modifier.width(12.dp))+ Column(Modifier.weight(1f)) {+ Text(entity.name, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold)+ Text(entity.description, style = MaterialTheme.typography.bodySmall)+ val gameName = ALL_GAMES.find { it.id == entity.gameId }?.name ?: entity.gameId+ Text(gameName, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.primary)+ }+ }+ }+ }+ }+ }+}++@Composable+fun StatsView(modifier: Modifier = Modifier) {+ val context = LocalContext.current+ var totalAchievements by remember { mutableIntStateOf(0) }+ var unlockedAchievements by remember { mutableIntStateOf(0) }+ var gameStats by remember { mutableStateOf<Map<String, Pair<Int, Int>>>(emptyMap()) }++ LaunchedEffect(Unit) {+ withContext(Dispatchers.IO) {+ val db = buildDatabase<GameHubDatabase>(context)+ val all = db.achievementDao().getAll()+ totalAchievements = all.size+ unlockedAchievements = all.count { it.unlocked }+ gameStats = all.groupBy { it.gameId }.mapValues { (_, list) ->+ Pair(list.size, list.count { it.unlocked })+ }+ }+ }++ LazyColumn(+ modifier = modifier.fillMaxSize(),+ contentPadding = PaddingValues(16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ item {+ Card(+ modifier = Modifier.fillMaxWidth(),+ shape = RoundedCornerShape(16.dp)+ ) {+ Column(Modifier.padding(24.dp)) {+ Text("Overall", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)+ Spacer(Modifier.height(8.dp))+ Text("$unlockedAchievements / $totalAchievements achievements unlocked")+ }+ }+ }++ items(ALL_GAMES) { game ->+ val stats = gameStats[game.id]+ Card(+ modifier = Modifier.fillMaxWidth(),+ shape = RoundedCornerShape(12.dp)+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(16.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(Modifier.weight(1f)) {+ Text(game.name, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)+ if (stats != null) {+ Text("${stats.second} / ${stats.first} achievements", style = MaterialTheme.typography.bodySmall)+ } else {+ Text("No data yet", style = MaterialTheme.typography.bodySmall, color = Color.Gray)+ }+ }+ }+ }+ }+ }+}
games/app/src/main/java/com/vayunmathur/games/data/Daos.kt
diff --git a/games/app/src/main/java/com/vayunmathur/games/data/Daos.kt b/games/app/src/main/java/com/vayunmathur/games/data/Daos.ktnew file mode 100644index 0000000000..963d6de088--- /dev/null+++ b/games/app/src/main/java/com/vayunmathur/games/data/Daos.kt@@ -0,0 +1,48 @@+package com.vayunmathur.games.data++import androidx.room.Dao+import androidx.room.Insert+import androidx.room.OnConflictStrategy+import androidx.room.Query++@Dao+interface AchievementDao {+ @Insert(onConflict = OnConflictStrategy.IGNORE)+ suspend fun insert(entity: AchievementEntity): Long++ @Query("UPDATE achievements SET unlocked = :unlocked, unlockedAt = :unlockedAt WHERE gameId = :gameId AND achievementId = :achievementId")+ suspend fun unlock(gameId: String, achievementId: String, unlocked: Boolean, unlockedAt: Long): Int++ @Query("SELECT * FROM achievements WHERE gameId = :gameId")+ suspend fun getByGame(gameId: String): List<AchievementEntity>++ @Query("SELECT * FROM achievements WHERE gameId = :gameId AND achievementId = :achievementId LIMIT 1")+ suspend fun get(gameId: String, achievementId: String): AchievementEntity?++ @Query("SELECT * FROM achievements")+ suspend fun getAll(): List<AchievementEntity>++ @Query("DELETE FROM achievements WHERE gameId = :gameId AND achievementId = :achievementId")+ suspend fun delete(gameId: String, achievementId: String): Int++ @Query("DELETE FROM achievements WHERE gameId = :gameId")+ suspend fun deleteByGame(gameId: String): Int+}++@Dao+interface ScoreDao {+ @Insert+ suspend fun insert(entity: ScoreEntity): Long++ @Query("SELECT * FROM scores WHERE gameId = :gameId ORDER BY score DESC")+ suspend fun getByGame(gameId: String): List<ScoreEntity>++ @Query("SELECT * FROM scores WHERE gameId = :gameId AND category = :category ORDER BY score DESC")+ suspend fun getByGameAndCategory(gameId: String, category: String): List<ScoreEntity>++ @Query("SELECT * FROM scores ORDER BY score DESC")+ suspend fun getAll(): List<ScoreEntity>++ @Query("DELETE FROM scores WHERE gameId = :gameId")+ suspend fun deleteByGame(gameId: String): Int+}
games/app/src/main/java/com/vayunmathur/games/data/Entities.kt
diff --git a/games/app/src/main/java/com/vayunmathur/games/data/Entities.kt b/games/app/src/main/java/com/vayunmathur/games/data/Entities.ktnew file mode 100644index 0000000000..2fe736757f--- /dev/null+++ b/games/app/src/main/java/com/vayunmathur/games/data/Entities.kt@@ -0,0 +1,25 @@+package com.vayunmathur.games.data++import androidx.room.Entity+import androidx.room.PrimaryKey++@Entity(tableName = "achievements")+data class AchievementEntity(+ @PrimaryKey(autoGenerate = true) val id: Long = 0,+ val gameId: String,+ val achievementId: String,+ val name: String,+ val description: String,+ val iconResName: String? = null,+ val unlocked: Boolean = false,+ val unlockedAt: Long? = null+)++@Entity(tableName = "scores")+data class ScoreEntity(+ @PrimaryKey(autoGenerate = true) val id: Long = 0,+ val gameId: String,+ val category: String,+ val score: Long,+ val timestamp: Long+)
games/app/src/main/java/com/vayunmathur/games/data/GameHubDatabase.kt
diff --git a/games/app/src/main/java/com/vayunmathur/games/data/GameHubDatabase.kt b/games/app/src/main/java/com/vayunmathur/games/data/GameHubDatabase.ktnew file mode 100644index 0000000000..248812df24--- /dev/null+++ b/games/app/src/main/java/com/vayunmathur/games/data/GameHubDatabase.kt@@ -0,0 +1,10 @@+package com.vayunmathur.games.data++import androidx.room.Database+import androidx.room.RoomDatabase++@Database(entities = [AchievementEntity::class, ScoreEntity::class], version = 1)+abstract class GameHubDatabase : RoomDatabase() {+ abstract fun achievementDao(): AchievementDao+ abstract fun scoreDao(): ScoreDao+}
games/app/src/main/java/com/vayunmathur/games/data/GameHubProvider.kt
diff --git a/games/app/src/main/java/com/vayunmathur/games/data/GameHubProvider.kt b/games/app/src/main/java/com/vayunmathur/games/data/GameHubProvider.ktnew file mode 100644index 0000000000..cef3f14f08--- /dev/null+++ b/games/app/src/main/java/com/vayunmathur/games/data/GameHubProvider.kt@@ -0,0 +1,133 @@+package com.vayunmathur.games.data++import android.content.ContentProvider+import android.content.ContentValues+import android.content.UriMatcher+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import com.vayunmathur.library.util.buildDatabase+import kotlinx.coroutines.runBlocking++class GameHubProvider : ContentProvider() {++ companion object {+ private const val AUTHORITY = "com.vayunmathur.games.provider"+ private const val ACHIEVEMENTS_BY_GAME = 1+ private const val ACHIEVEMENT_BY_ID = 2+ private const val SCORES_BY_GAME = 3++ private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {+ addURI(AUTHORITY, "achievements/*", ACHIEVEMENTS_BY_GAME)+ addURI(AUTHORITY, "achievements/*/*", ACHIEVEMENT_BY_ID)+ addURI(AUTHORITY, "scores/*", SCORES_BY_GAME)+ }+ }++ private val db by lazy { buildDatabase<GameHubDatabase>(context!!) }+ private val achievementDao by lazy { db.achievementDao() }+ private val scoreDao by lazy { db.scoreDao() }++ override fun onCreate(): Boolean = true++ override fun query(+ uri: Uri, projection: Array<out String>?, selection: String?,+ selectionArgs: Array<out String>?, sortOrder: String?+ ): Cursor? {+ return when (uriMatcher.match(uri)) {+ ACHIEVEMENTS_BY_GAME -> {+ val gameId = uri.pathSegments[1]+ val entities = runBlocking { achievementDao.getByGame(gameId) }+ val cursor = MatrixCursor(arrayOf("achievement_id", "game_id", "name", "description", "icon_res_name", "unlocked", "unlocked_at"))+ for (e in entities) {+ cursor.addRow(arrayOf(e.achievementId, e.gameId, e.name, e.description, e.iconResName, if (e.unlocked) 1 else 0, e.unlockedAt ?: 0L))+ }+ cursor+ }+ SCORES_BY_GAME -> {+ val gameId = uri.pathSegments[1]+ val category = selectionArgs?.firstOrNull()+ val entities = runBlocking {+ if (category != null && selection == "category = ?") {+ scoreDao.getByGameAndCategory(gameId, category)+ } else {+ scoreDao.getByGame(gameId)+ }+ }+ val cursor = MatrixCursor(arrayOf("game_id", "category", "score", "timestamp"))+ for (e in entities) {+ cursor.addRow(arrayOf(e.gameId, e.category, e.score, e.timestamp))+ }+ cursor+ }+ else -> null+ }+ }++ override fun insert(uri: Uri, values: ContentValues?): Uri? {+ values ?: return null+ return when (uriMatcher.match(uri)) {+ ACHIEVEMENTS_BY_GAME -> {+ val entity = AchievementEntity(+ gameId = values.getAsString("game_id"),+ achievementId = values.getAsString("achievement_id"),+ name = values.getAsString("name"),+ description = values.getAsString("description"),+ iconResName = values.getAsString("icon_res_name"),+ unlocked = (values.getAsInteger("unlocked") ?: 0) == 1+ )+ runBlocking { achievementDao.insert(entity) }+ uri+ }+ SCORES_BY_GAME -> {+ val entity = ScoreEntity(+ gameId = values.getAsString("game_id"),+ category = values.getAsString("category"),+ score = values.getAsLong("score"),+ timestamp = values.getAsLong("timestamp")+ )+ runBlocking { scoreDao.insert(entity) }+ uri+ }+ else -> null+ }+ }++ override fun update(+ uri: Uri, values: ContentValues?, selection: String?,+ selectionArgs: Array<out String>?+ ): Int {+ values ?: return 0+ return when (uriMatcher.match(uri)) {+ ACHIEVEMENT_BY_ID -> {+ val gameId = uri.pathSegments[1]+ val achievementId = uri.pathSegments[2]+ val unlocked = (values.getAsInteger("unlocked") ?: 0) == 1+ val unlockedAt = values.getAsLong("unlocked_at") ?: System.currentTimeMillis()+ runBlocking { achievementDao.unlock(gameId, achievementId, unlocked, unlockedAt) }+ }+ else -> 0+ }+ }++ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {+ return when (uriMatcher.match(uri)) {+ ACHIEVEMENT_BY_ID -> {+ val gameId = uri.pathSegments[1]+ val achievementId = uri.pathSegments[2]+ runBlocking { achievementDao.delete(gameId, achievementId) }+ }+ ACHIEVEMENTS_BY_GAME -> {+ val gameId = uri.pathSegments[1]+ runBlocking { achievementDao.deleteByGame(gameId) }+ }+ SCORES_BY_GAME -> {+ val gameId = uri.pathSegments[1]+ runBlocking { scoreDao.deleteByGame(gameId) }+ }+ else -> 0+ }+ }++ override fun getType(uri: Uri): String? = null+}
games/app/src/main/res/values/strings.xml
diff --git a/games/app/src/main/res/values/strings.xml b/games/app/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..51e1036d39--- /dev/null+++ b/games/app/src/main/res/values/strings.xml@@ -0,0 +1,3 @@+<resources>+ <string name="app_name">Games Hub</string>+</resources>
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex cd7c39f5c2..90ec6b5cc3 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -57,3 +57,4 @@ include(":web") include(":camera") include(":sdk:openassistant") include(":sdk:games")+include(":games:app")