content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.example.weatherapp import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.weatherapp.data.WeatherRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch class WeatherViewModel: ViewModel() { private val repository = WeatherRepository() val uiState = MutableStateFlow<WeatherResponse?>(null) fun fetchWeatherData(query: String) { viewModelScope.launch { try { val weatherResponse = repository.fetchWeatherData(query) // Handle the weather response here uiState.emit(weatherResponse) Log.d("AlexK","what happened here $weatherResponse") } catch (e: Exception) { // Handle errors Log.d("AlexK","what happened here $e") } } } }
weatherApp/app/src/main/java/com/example/weatherapp/WeatherViewModel.kt
2625160567
package com.example.weatherapp import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object WeatherRetrofitClient { private const val BASE_URL = "https://api.openweathermap.org/data/2.5/" fun create(): WeatherApiService { // Create a logging interceptor val loggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY // Set your desired log level } // Create an OkHttpClient with the logging interceptor val httpClient = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(httpClient) .build() return retrofit.create(WeatherApiService::class.java) } }
weatherApp/app/src/main/java/com/example/weatherapp/WeatherRetrofitClient.kt
1887943888
package com.example.weatherapp import com.example.weatherapp.data.Main import com.example.weatherapp.data.Weather data class WeatherResponse( val name: String, val main: Main, val weather: List<Weather> )
weatherApp/app/src/main/java/com/example/weatherapp/WeatherResponse.kt
3572781112
package com.example.weatherapp import retrofit2.http.GET import retrofit2.http.Query interface WeatherApiService { @GET("weather") suspend fun getWeather( @Query("q") cityName: String, @Query("lat") latitude: Double? = null, @Query("lon") longitude: Double? = null, @Query("appid") apiKey: String ): WeatherResponse }
weatherApp/app/src/main/java/com/example/weatherapp/WeatherApiService.kt
2206329166
package com.example.weatherapp.data import com.example.weatherapp.BuildConfig import com.example.weatherapp.WeatherResponse import com.example.weatherapp.WeatherRetrofitClient class WeatherRepository { private val service = WeatherRetrofitClient.create() suspend fun fetchWeatherData(cityName: String): WeatherResponse { val apiKey = getApiKey() return service.getWeather(cityName = cityName, apiKey = apiKey) } private fun getApiKey(): String { return BuildConfig.WEATHER_API_KEY } }
weatherApp/app/src/main/java/com/example/weatherapp/data/WeatherRepository.kt
2569776161
package com.example.weatherapp.data data class Main( val temp: Float, val feels_like: Float, val temp_min: Float, val temp_max: Float, val pressure: Float, val humidity: Float )
weatherApp/app/src/main/java/com/example/weatherapp/data/Main.kt
2742520475
package com.example.weatherapp.data data class Weather( val main: String, val description: String, val icon: String )
weatherApp/app/src/main/java/com/example/weatherapp/data/Weather.kt
924031387
package com.app.movilbox import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.app.movilbox", appContext.packageName) } }
prueba_movilbox/app/src/androidTest/java/com/app/movilbox/ExampleInstrumentedTest.kt
4052940060
package com.app.movilbox import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
prueba_movilbox/app/src/test/java/com/app/movilbox/ExampleUnitTest.kt
3547878916
package com.app.movilbox.ui.home import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.app.movilbox.ui.info.Info import com.app.movilbox.ui.info.InfoViewModel import com.app.movilbox.ui.navigation.Routes import com.app.movilbox.ui.product.Product import com.app.movilbox.ui.product.ProductViewModel import com.app.movilbox.ui.theme.MovilboxTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MovilboxTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { MainNavigation() } } } } @Composable fun MainNavigation() { val navController = rememberNavController() NavigationHost(navController = navController) } @Composable fun NavigationHost(navController: NavHostController) { NavHost(navController = navController, startDestination = Routes.MainApp.route) { composable(Routes.MainApp.route) { val productViewModel = hiltViewModel<ProductViewModel>() Product(navController, productViewModel) } composable(Routes.InfoApp.route + "/{id}") { val infoViewModel = hiltViewModel<InfoViewModel>() Info(navController, infoViewModel, it.arguments?.getString("id")) } } } }
prueba_movilbox/app/src/main/java/com/app/movilbox/ui/home/MainActivity.kt
3592684348
package com.app.movilbox.ui.delete import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Build import androidx.compose.material.icons.filled.Clear import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.Dialog @Composable fun Delete( deleteProduct: () -> Unit, product: String, setShowDialog: (Boolean) -> Unit, ) { val txtField = remember { mutableStateOf(product) } Dialog(onDismissRequest = { setShowDialog(false) }) { Surface( shape = RoundedCornerShape(16.dp), color = Color.White ) { Box( contentAlignment = Alignment.Center ) { Column(modifier = Modifier.padding(20.dp)) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = "¿Delete?", style = TextStyle( fontSize = 24.sp, fontFamily = FontFamily.Default, fontWeight = FontWeight.Bold ) ) Icon( imageVector = Icons.Filled.Clear, contentDescription = "", modifier = Modifier .width(30.dp) .height(30.dp) .clickable { setShowDialog(false) } ) } Spacer(modifier = Modifier.height(20.dp)) TextField( modifier = Modifier .fillMaxWidth() .border( BorderStroke( width = 2.dp, color = Color.Black ), shape = RoundedCornerShape(50) ), colors = TextFieldDefaults.colors( focusedContainerColor = Color.Transparent, unfocusedContainerColor = Color.Transparent, disabledContainerColor = Color.Transparent, focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, ), leadingIcon = { Icon( imageVector = Icons.Filled.Build, contentDescription = "", tint = colorResource(android.R.color.holo_green_light), modifier = Modifier .width(20.dp) .height(20.dp) ) }, placeholder = { Text(text = product) }, value = product, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), onValueChange = { txtField.value = it }, enabled = false ) Spacer(modifier = Modifier.height(20.dp)) Box(modifier = Modifier.padding(40.dp, 0.dp, 40.dp, 0.dp)) { Button( onClick = { if (txtField.value.isEmpty()) { setShowDialog(false) return@Button } setShowDialog(false) deleteProduct() }, shape = RoundedCornerShape(50.dp), modifier = Modifier .fillMaxWidth() .height(50.dp) ) { Text(text = "Delete") } } } } } } }
prueba_movilbox/app/src/main/java/com/app/movilbox/ui/delete/Delete.kt
3117051261
package com.app.movilbox.ui.navigation sealed class Routes(val route: String) { data object MainApp : Routes("main") data object InfoApp : Routes("info") }
prueba_movilbox/app/src/main/java/com/app/movilbox/ui/navigation/Routes.kt
691257833
package com.app.movilbox.ui.product import android.widget.Toast import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column 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.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyRow 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.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Search import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.DockedSearchBar import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable 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.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavHostController import coil.compose.AsyncImage import coil.request.ImageRequest import com.app.movilbox.R import com.app.movilbox.domain.models.ProductModel import com.app.movilbox.ui.delete.Delete import com.app.movilbox.ui.navigation.Routes import java.util.Locale @Composable fun Product(navController: NavHostController, productViewModel: ProductViewModel) { Box( modifier = Modifier .fillMaxSize() .background(Color(0x7A00E676)) ) { Main(productViewModel, navController) } } @Composable private fun Main(productViewModel: ProductViewModel, navController: NavHostController) { val query: String by productViewModel.stateQuery.collectAsState() val filterData by productViewModel.stateFilter.collectAsState() Column( modifier = Modifier.padding(8.dp) ) { TopBar(productViewModel, query) { productViewModel.onChangedQuery(it) } Spacer(modifier = Modifier.padding(8.dp)) Box { ListCategories(Modifier.align(Alignment.Center), productViewModel) } ListProduct( productViewModel, navController, query, filterData, Modifier.align(Alignment.CenterHorizontally) ) } } @Composable private fun ListCategories(modifier: Modifier, productViewModel: ProductViewModel) { val stateCategories by productViewModel.stateCategories.collectAsState() productViewModel.getCategories() if (stateCategories.isNotEmpty()) { LazyRow { items(stateCategories) { Card( elevation = CardDefaults.cardElevation(defaultElevation = 10.dp), modifier = Modifier .padding(4.dp) .fillMaxWidth(), shape = RoundedCornerShape(10.dp) ) { Text( text = it.uppercase(Locale.getDefault()), fontSize = 10.sp, modifier = modifier .align(Alignment.CenterHorizontally) .padding(10.dp) ) } } } } } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun TopBar( productViewModel: ProductViewModel, query: String, onQuery: (String) -> Unit ) { var expand by rememberSaveable { mutableStateOf(false) } val filterList = listOf("Limpiar Filtro", "Precio", "Descuento", "Categoria", "Stock", "Marca", "Rating") Row( modifier = Modifier .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceAround ) { DockedSearchBar( modifier = Modifier .width(200.dp) .height(56.dp) .padding(0.dp), query = query, onQueryChange = { onQuery(it) }, onSearch = { productViewModel.searchProduct(query) }, active = false, onActiveChange = { }, placeholder = { Text(text = "Notebook") }, leadingIcon = { Icon( imageVector = Icons.Default.Search, contentDescription = "Search" ) }, tonalElevation = 0.dp, trailingIcon = { if (query.isNotEmpty()) { IconButton(onClick = { onQuery("") }) { Icon( imageVector = Icons.Default.Close, contentDescription = "Close" ) } } } ) { } IconButton(onClick = { /*showDialog.value = true*/ }, modifier = Modifier.size(30.dp)) { Icon( imageVector = Icons.Default.Add, contentDescription = "Add" ) } Box( modifier = Modifier .wrapContentSize(Alignment.TopEnd) ) { IconButton(onClick = { expand = !expand }, modifier = Modifier.size(25.dp)) { Icon( painter = painterResource(id = R.drawable.ic_filter), contentDescription = "Filter" ) } DropdownMenu(expanded = expand, onDismissRequest = { expand = false }) { filterList.map { DropdownMenuItem( text = { Text(text = it) }, onClick = { productViewModel.filterProducts(it) }) } } } } } @Composable private fun ListProduct( productViewModel: ProductViewModel, navController: NavHostController, query: String, filterData: Boolean, modifier: Modifier ) { val stateList by productViewModel.stateList.collectAsState() val stateDelete by productViewModel.stateDelete.collectAsState() val ctx = LocalContext.current if (stateDelete) { productViewModel.onChangedDelete() Toast.makeText(ctx, "Producto eleminado", Toast.LENGTH_LONG).show() } if (query.isEmpty() && !filterData && !stateDelete) { productViewModel.getProduct() } if (stateList.isNotEmpty()) { Spacer(modifier = Modifier.padding(8.dp)) Text( fontSize = 20.sp, fontFamily = FontFamily.SansSerif, fontStyle = FontStyle.Normal, modifier = modifier.padding(2.dp), text = "Products".uppercase(), overflow = TextOverflow.Ellipsis ) Spacer(modifier = Modifier.padding(4.dp)) LazyVerticalGrid( columns = GridCells.Adaptive(150.dp), modifier = Modifier.padding(1.dp) ) { items(stateList) { ItemProduct(it, navController, productViewModel) } } } else { Spacer(modifier = Modifier.padding(8.dp)) TextData(info = "No existe productos".uppercase(), 25.sp) } } @Composable private fun Deleteproducts( show: Boolean, productViewModel: ProductViewModel, id: Int, title: String, showDialog: (Boolean) -> Unit ) { if (show) { Delete( deleteProduct = { deleteProduct(productViewModel, id.toString()) }, product = title, setShowDialog = { showDialog(it) }) } } @Composable private fun ItemProduct( data: ProductModel, navController: NavHostController, productViewModel: ProductViewModel ) { val showDialog: MutableState<Boolean> = rememberSaveable { mutableStateOf(false) } if (showDialog.value) { Deleteproducts(showDialog.value, productViewModel, data.id, data.title) { showDialog.value = it } } Card( modifier = Modifier .padding(4.dp) .fillMaxSize() .clickable { startInfo(navController, data.id.toString()) }, shape = RoundedCornerShape(10.dp) ) { Column( modifier = Modifier.padding(8.dp) ) { AsyncImage( modifier = Modifier .height(100.dp) .fillMaxWidth(), model = ImageRequest.Builder(context = LocalContext.current) .data(data.images[0]).crossfade(true) .build(), alignment = Alignment.Center, contentDescription = data.description, contentScale = ContentScale.FillHeight, ) TextData(info = data.title, 15.sp) TextData(info = data.brand, 10.sp) Spacer(modifier = Modifier.padding(4.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { if (data.stock > 0) { TextData(info = "$ ${data.price}", 10.sp) } else { TextData(info = "No disponible", 8.sp) } TextData(info = " * ${data.rating}", 10.sp) } Spacer(modifier = Modifier.padding(4.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { IconButton(onClick = { }, modifier = Modifier.size(25.dp)) { Icon( imageVector = Icons.Default.Edit, contentDescription = "update" ) } IconButton(onClick = { showDialog.value = true }, modifier = Modifier.size(25.dp)) { Icon( imageVector = Icons.Default.Delete, contentDescription = "delete" ) } } } } } @Composable fun TextData(info: String, size: TextUnit) { Text( fontSize = size, fontStyle = FontStyle.Normal, modifier = Modifier.padding(2.dp), text = info, softWrap = false, overflow = TextOverflow.Ellipsis ) } private fun deleteProduct(productViewModel: ProductViewModel, id: String) { productViewModel.deleteProductId(id) } private fun startInfo(navController: NavHostController, id: String) { navController.navigate(Routes.InfoApp.route + "/${id}") }
prueba_movilbox/app/src/main/java/com/app/movilbox/ui/product/Product.kt
562464941
package com.app.movilbox.ui.product import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.app.movilbox.domain.models.ProductModel import com.app.movilbox.domain.repository.ProductRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class ProductViewModel @Inject constructor(private val productRepository: ProductRepository) : ViewModel() { private var _stateList = MutableStateFlow<List<ProductModel>>(emptyList()) val stateList: StateFlow<List<ProductModel>> = _stateList private var _stateCategories = MutableStateFlow<List<String>>(emptyList()) val stateCategories: StateFlow<List<String>> = _stateCategories private var _stateQuery = MutableStateFlow<String>("") val stateQuery: StateFlow<String> = _stateQuery private var _stateFilter = MutableStateFlow<Boolean>(false) val stateFilter: StateFlow<Boolean> = _stateFilter private var _stateDelete = MutableStateFlow<Boolean>(false) val stateDelete: StateFlow<Boolean> = _stateDelete fun onChangedQuery(query: String) { _stateQuery.value = query } fun onChangedDelete() { _stateDelete.value = false _stateFilter.value = false _stateQuery.value = "" } /** * get list products */ fun getProduct() { viewModelScope.launch { val result: List<ProductModel> = withContext(Dispatchers.IO) { productRepository.getProducts() } if (result.isNotEmpty()) { _stateList.value = result } } } /** * Get List categories */ fun getCategories() { viewModelScope.launch { val result: List<String> = withContext(Dispatchers.IO) { productRepository.getCategories() } if (result.isNotEmpty()) { _stateCategories.value = result } } } /** * Search product */ fun searchProduct(data: String) { viewModelScope.launch { val result: List<ProductModel> = withContext(Dispatchers.IO) { productRepository.searchProduct(data) } if (result.isNotEmpty()) { _stateList.value = result } else { _stateList.value = emptyList() } } } /** * Delete product id */ fun deleteProductId(id: String) { viewModelScope.launch { val result: ProductModel = withContext(Dispatchers.IO) { productRepository.deleteProduct(id) } if (result.title.isNotEmpty()) { _stateDelete.value = true _stateList.value = emptyList() } } } /** * Filter products of the list of productmodel */ fun filterProducts(filter: String) { _stateFilter.value = true _stateList.value = when (filter) { "Precio" -> stateList.value.sortedBy { it.price } "Descuento" -> stateList.value.sortedBy { it.discountPercentage } "Categoria" -> stateList.value.sortedBy { it.category } "Stock" -> stateList.value.sortedBy { it.stock } "Marca" -> stateList.value.sortedBy { it.brand } "Rating" -> stateList.value.sortedBy { it.rating } else -> { _stateFilter.value = false stateList.value.sortedByDescending { it.rating } } } } }
prueba_movilbox/app/src/main/java/com/app/movilbox/ui/product/ProductViewModel.kt
3731284977
package com.app.movilbox.ui.info import android.widget.Toast import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box 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.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavHostController import coil.compose.AsyncImage import coil.request.ImageRequest import com.app.movilbox.domain.models.ProductModel import com.app.movilbox.ui.product.TextData @Composable fun Info(navController: NavHostController, infoViewModel: InfoViewModel, id: String?) { Box( modifier = Modifier .fillMaxSize() .background(Color(0xB701283A)) ) { InitInfo(infoViewModel, id, navController) } } @Composable private fun InitInfo(infoViewModel: InfoViewModel, id: String?, navController: NavHostController) { val stateProduct: ProductModel by infoViewModel.stateProduct.collectAsState() val ctx = LocalContext.current if (id != "null") { infoViewModel.getProductId(id!!) } else { Toast.makeText(ctx, "Error", Toast.LENGTH_LONG).show() navController.popBackStack() } if (stateProduct.images.isNotEmpty()) { Card( elevation = CardDefaults.cardElevation(defaultElevation = 10.dp), modifier = Modifier .padding(8.dp) .fillMaxWidth(), shape = RoundedCornerShape(10.dp) ) { LazyColumn( modifier = Modifier.padding(8.dp) ) { item { TextData(info = stateProduct.title, 20.sp) Spacer(modifier = Modifier.padding(8.dp)) AsyncImage( modifier = Modifier .height(200.dp) .fillMaxWidth(), model = ImageRequest.Builder(context = LocalContext.current) .data(stateProduct.images[0]).crossfade(true).build(), alignment = Alignment.Center, contentDescription = stateProduct.description, contentScale = ContentScale.Crop, ) Spacer(modifier = Modifier.padding(8.dp)) Row( modifier = Modifier .fillMaxWidth() .padding(10.dp), horizontalArrangement = Arrangement.SpaceBetween ) { if (stateProduct.stock > 0) { TextData( info = "$${stateProduct.price} - ( ${stateProduct.discountPercentage}% )", 15.sp ) } else { TextData(info = "No disponible", 8.sp) } TextData(info = "*${stateProduct.rating}", 15.sp) } TextData(info = "Stock: ${stateProduct.stock}", 20.sp) Spacer(modifier = Modifier.padding(4.dp)) Text( fontSize = 15.sp, fontStyle = FontStyle.Normal, modifier = Modifier.padding(2.dp), text = stateProduct.description, overflow = TextOverflow.Ellipsis ) } } } } }
prueba_movilbox/app/src/main/java/com/app/movilbox/ui/info/Info.kt
3970905611
package com.app.movilbox.ui.info import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.app.movilbox.domain.models.ProductModel import com.app.movilbox.domain.repository.ProductRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class InfoViewModel @Inject constructor(private val productRepository: ProductRepository) : ViewModel() { private var _stateProduct = MutableStateFlow<ProductModel>(ProductModel()) val stateProduct: StateFlow<ProductModel> = _stateProduct /** * Get product for id */ fun getProductId(id: String) { viewModelScope.launch { val result: ProductModel = withContext(Dispatchers.IO) { productRepository.getProduct(id) } _stateProduct.value = result } } }
prueba_movilbox/app/src/main/java/com/app/movilbox/ui/info/InfoViewModel.kt
3484838461
package com.app.movilbox.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
prueba_movilbox/app/src/main/java/com/app/movilbox/ui/theme/Color.kt
981500690
package com.app.movilbox.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun MovilboxTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
prueba_movilbox/app/src/main/java/com/app/movilbox/ui/theme/Theme.kt
3489243951
package com.app.movilbox.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
prueba_movilbox/app/src/main/java/com/app/movilbox/ui/theme/Type.kt
80396373
package com.app.movilbox.data.database import androidx.room.Database import androidx.room.RoomDatabase import com.app.movilbox.data.database.dao.DaoProduct import com.app.movilbox.data.database.entities.ProductDataRoom @Database(entities = [ProductDataRoom::class], version = 1) abstract class ProductDatabase : RoomDatabase() { abstract fun daoProduct(): DaoProduct }
prueba_movilbox/app/src/main/java/com/app/movilbox/data/database/ProductDatabase.kt
2718972557
package com.app.movilbox.data.database.dao import androidx.room.Dao import androidx.room.Query import com.app.movilbox.data.database.entities.ProductDataRoom @Dao interface DaoProduct { @Query("SELECT * FROM products") suspend fun getAllProducts(): List<ProductDataRoom> }
prueba_movilbox/app/src/main/java/com/app/movilbox/data/database/dao/DaoProduct.kt
1967111172
package com.app.movilbox.data.database.entities import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.app.movilbox.domain.models.ProductModel /** * MAP DDBB */ @Entity(tableName = "products") data class ProductDataRoom( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val id: Int = 0, @ColumnInfo(name = "title") val title: String, @ColumnInfo(name = "description") val description: String, @ColumnInfo(name = "price") val price: Long, @ColumnInfo(name = "discountPercentage") val discountPercentage: Double, @ColumnInfo(name = "rating") val rating: Double, @ColumnInfo(name = "stock") val stock: Int, @ColumnInfo(name = "brand") val brand: String, @ColumnInfo(name = "category") val category: String, @ColumnInfo(name = "thumbnail") val thumbnail: String, ) { fun toDomain() = ProductModel( id, title, description, price, discountPercentage, rating, stock, brand, category, thumbnail ) }
prueba_movilbox/app/src/main/java/com/app/movilbox/data/database/entities/ProductDataRoom.kt
3776599282
package com.app.movilbox.data.response import com.app.movilbox.domain.models.Product import com.google.gson.annotations.SerializedName data class ProductResponse( @SerializedName("products") val products: List<ProductDataResponse> ) { fun toDomain() = Product(products.map { it.toDomain() }) }
prueba_movilbox/app/src/main/java/com/app/movilbox/data/response/ProductResponse.kt
3891301929
package com.app.movilbox.data.response import com.app.movilbox.domain.models.ProductModel import com.google.gson.annotations.SerializedName /** * MAP JSON OF SERVER */ data class ProductDataResponse( @SerializedName("id") val id: Int, @SerializedName("title") val title: String, @SerializedName("description") val description: String, @SerializedName("price") val price: Long, @SerializedName("discountPercentage") val discountPercentage: Double, @SerializedName("rating") val rating: Double, @SerializedName("stock") val stock: Int, @SerializedName("brand") val brand: String, @SerializedName("category") val category: String, @SerializedName("thumbnail") val thumbnail: String, @SerializedName("images") val images: List<String> ) { fun toDomain() = ProductModel( id, title, description, price, discountPercentage, rating, stock, brand, category, thumbnail, images ) }
prueba_movilbox/app/src/main/java/com/app/movilbox/data/response/ProductDataResponse.kt
3912598409
package com.app.movilbox.data.network import android.content.Context import androidx.room.Room import com.app.movilbox.data.RepositoryProductImpl import com.app.movilbox.data.RepositoryProuctRoomImpl import com.app.movilbox.data.database.ProductDatabase import com.app.movilbox.data.database.dao.DaoProduct import com.app.movilbox.domain.repository.ProductRepository import com.app.movilbox.domain.repository.ProductRepositoryRoom import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton /** * Inject function and modules */ @Module @InstallIn(SingletonComponent::class) object NetworkModule { private const val DATABASE_NAME = "movilbox" /** * Provide Retrofit */ @Provides @Singleton fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit { return Retrofit.Builder().baseUrl("https://dummyjson.com/").client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()).build() } /** * Provide interceptor for info apis */ @Provides @Singleton fun provideOkHttpClient(): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .build() } /** * Provide Service API product */ @Provides fun provideProductApiService(retrofit: Retrofit): ProductApiService { return retrofit.create(ProductApiService::class.java) } @Provides fun provideProductRepository(productApiService: ProductApiService): ProductRepository { return RepositoryProductImpl(productApiService) } /** * Provide DDBB */ @Singleton @Provides fun provideRoom(@ApplicationContext context: Context): ProductDatabase { return Room.databaseBuilder(context, ProductDatabase::class.java, DATABASE_NAME).build() } /** * Dao product */ @Singleton @Provides fun provideDaoProduct(productDatabase: ProductDatabase): DaoProduct { return productDatabase.daoProduct() } /** * Return repository implementation */ @Provides fun provideRepositoryProduct(daoProduct: DaoProduct): ProductRepositoryRoom { return RepositoryProuctRoomImpl(daoProduct) } }
prueba_movilbox/app/src/main/java/com/app/movilbox/data/network/NetworkModule.kt
2246995153
package com.app.movilbox.data.network import com.app.movilbox.data.response.ProductDataResponse import com.app.movilbox.data.response.ProductResponse import com.app.movilbox.domain.models.ProductModel import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Path import retrofit2.http.Query interface ProductApiService { @GET("/products") suspend fun getProducts(): ProductResponse @GET("/products/{id}") suspend fun getProduct(@Path("id") id: String): ProductDataResponse @GET("/products/categories") suspend fun getCategories(): List<String> @GET("/products/search") suspend fun searchProduct(@Query("q") data: String): ProductResponse @POST("/products/add") suspend fun addProduct(@Body productModel: ProductModel): List<String> @PUT("/products/products/{id}") suspend fun updateProduct( @Body productModel: ProductModel, @Path("id") id: String ): List<String> @DELETE("/products/{id}") suspend fun deleteProduct(@Path("id") id: String): ProductDataResponse }
prueba_movilbox/app/src/main/java/com/app/movilbox/data/network/ProductApiService.kt
2306349723
package com.app.movilbox.data import android.util.Log import com.app.movilbox.data.database.dao.DaoProduct import com.app.movilbox.domain.models.ProductModel import com.app.movilbox.domain.repository.ProductRepositoryRoom import javax.inject.Inject /** * Function for DDBB */ class RepositoryProuctRoomImpl @Inject constructor(private val daoProduct: DaoProduct) : ProductRepositoryRoom { override suspend fun getProducts(): List<ProductModel> { runCatching { daoProduct.getAllProducts() }.onSuccess { return it.map { data -> data.toDomain() } }.onFailure { Log.i("DDBB", "Error: ${it.message}") } return emptyList() } }
prueba_movilbox/app/src/main/java/com/app/movilbox/data/RepositoryProuctRoomImpl.kt
2638283921
package com.app.movilbox.data import android.util.Log import com.app.movilbox.data.network.ProductApiService import com.app.movilbox.domain.models.ProductModel import com.app.movilbox.domain.repository.ProductRepository import javax.inject.Inject /** * Functions for consumer api rest */ class RepositoryProductImpl @Inject constructor(private val productApiService: ProductApiService) : ProductRepository { override suspend fun getProducts(): List<ProductModel> { runCatching { productApiService.getProducts() }.onSuccess { return it.products.sortedByDescending { order -> order.rating }.map { data -> data.toDomain() } }.onFailure { Log.i("Error Api", "Error: ${it.message}") } return emptyList() } override suspend fun getProduct(id: String): ProductModel { runCatching { productApiService.getProduct(id) }.onSuccess { return it.toDomain() } .onFailure { Log.i("Error Api", "Error: ${it.message}") } return ProductModel() } override suspend fun getCategories(): List<String> { runCatching { productApiService.getCategories() }.onSuccess { return it } .onFailure { Log.i("Error Api", "Error: ${it.message}") } return emptyList() } override suspend fun searchProduct(data: String): List<ProductModel> { runCatching { productApiService.searchProduct(data) }.onSuccess { return it.products.sortedByDescending { order -> order.rating }.map { data -> data.toDomain() } }.onFailure { Log.i("Error Api", "Error: ${it.message}") } return emptyList() } override suspend fun addProduct(productModel: ProductModel): List<String> { runCatching { productApiService.addProduct(productModel) }.onSuccess { return it } .onFailure { Log.i("Error Api", "Error: ${it.message}") } return emptyList() } override suspend fun updateProduct(productModel: ProductModel, id: String): List<String> { runCatching { productApiService.updateProduct(productModel, id) }.onSuccess { return it } .onFailure { Log.i("Error Api", "Error: ${it.message}") } return emptyList() } override suspend fun deleteProduct(id: String): ProductModel { runCatching { productApiService.deleteProduct(id) }.onSuccess { return it.toDomain() } .onFailure { Log.i("Error Api", "Error: ${it.message}") } return ProductModel() } }
prueba_movilbox/app/src/main/java/com/app/movilbox/data/RepositoryProductImpl.kt
364169662
package com.app.movilbox.domain.repository import com.app.movilbox.domain.models.ProductModel interface ProductRepository { suspend fun getProducts(): List<ProductModel> suspend fun getProduct(id: String): ProductModel suspend fun getCategories(): List<String> suspend fun searchProduct(data: String): List<ProductModel> suspend fun addProduct(productModel: ProductModel): List<String> suspend fun updateProduct(productModel: ProductModel, id: String): List<String> suspend fun deleteProduct(id: String): ProductModel }
prueba_movilbox/app/src/main/java/com/app/movilbox/domain/repository/ProductRepository.kt
3936461149
package com.app.movilbox.domain.repository import com.app.movilbox.domain.models.ProductModel interface ProductRepositoryRoom { suspend fun getProducts(): List<ProductModel> }
prueba_movilbox/app/src/main/java/com/app/movilbox/domain/repository/ProductRepositoryRoom.kt
280854464
package com.app.movilbox.domain.models data class Product( val products: List<ProductModel> = emptyList() )
prueba_movilbox/app/src/main/java/com/app/movilbox/domain/models/Product.kt
3688701524
package com.app.movilbox.domain.models data class ProductModel( val id: Int = 0, val title: String = "", val description: String = "", val price: Long = 0, val discountPercentage: Double = 0.0, val rating: Double = 0.0, val stock: Int = 0, val brand: String = "", val category: String = "", val thumbnail: String = "", val images: List<String> = emptyList() )
prueba_movilbox/app/src/main/java/com/app/movilbox/domain/models/ProductModel.kt
3757019744
package com.app.movilbox import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MovilBoxApp : Application() {}
prueba_movilbox/app/src/main/java/com/app/movilbox/MovilBoxApp.kt
3544952741
package pt.isel.pdm.chess4android import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("pt.isel.pdm.chess4android", appContext.packageName) } }
ISEL-Chess4Android/Chess4Android/app/src/androidTest/java/pt/isel/pdm/chess4android/ExampleInstrumentedTest.kt
5539491
package pt.isel.pdm.chess4android import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
ISEL-Chess4Android/Chess4Android/app/src/test/java/pt/isel/pdm/chess4android/ExampleUnitTest.kt
2226971903
package pt.isel.pdm.chess4android.challenges.list import android.app.Application import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import pt.isel.pdm.chess4android.ChessApplication import pt.isel.pdm.chess4android.TAG import pt.isel.pdm.chess4android.challenges.ChallengeInfo import pt.isel.pdm.chess4android.game.GameState /** * The View Model used in the [ChallengesListActivity]. * * Challenges are created by participants and are posted to the server, awaiting acceptance. */ class ChallengesListViewModel(app: Application) : AndroidViewModel(app) { private val app = getApplication<ChessApplication>() /** * Contains the result of the last attempt to fetch the challenges list */ private val _challenges: MutableLiveData<Result<List<ChallengeInfo>>> = MutableLiveData() val challenges: LiveData<Result<List<ChallengeInfo>>> = _challenges /** * Gets the challenges list by fetching them from the server. The operation's result is exposed * through [challenges] */ fun fetchChallenges() = app.challengesRepository.fetchChallenges(onComplete = { _challenges.value = it }) /** * Contains information about the enrolment in a game. */ private val _enrolmentResult: MutableLiveData<Result<Pair<ChallengeInfo, GameState>>?> = MutableLiveData() val enrolmentResult: LiveData<Result<Pair<ChallengeInfo, GameState>>?> = _enrolmentResult /** * Tries to accept the given challenge. The result of the asynchronous operation is exposed * through [enrolmentResult] LiveData instance. */ fun tryAcceptChallenge(challengeInfo: ChallengeInfo) { val app = getApplication<ChessApplication>() Log.v(TAG, "Challenge accepted. Signalling by removing challenge from list") app.challengesRepository.withdrawChallenge( challengeId = challengeInfo.id, onComplete = { it.onSuccess { Log.v(TAG, "We successfully unpublished the challenge. Let's start the game") app.gamesRepository.createGame(challengeInfo, onComplete = { game -> _enrolmentResult.value = game }) } } ) } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/challenges/list/ChallengesListViewModel.kt
4197977744
package pt.isel.pdm.chess4android.challenges.list import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import pt.isel.pdm.chess4android.R import pt.isel.pdm.chess4android.challenges.ChallengeInfo import pt.isel.pdm.chess4android.challenges.create.CreateChallengeActivity import pt.isel.pdm.chess4android.model.Player import pt.isel.pdm.chess4android.common.stringArrayToBoardState import pt.isel.pdm.chess4android.databinding.ActivityChallengesListBinding import pt.isel.pdm.chess4android.game.GameActivity /** * The activity used to display the list of existing challenges. */ class ChallengesListActivity : AppCompatActivity() { private val binding by lazy { ActivityChallengesListBinding.inflate(layoutInflater) } private val viewModel: ChallengesListViewModel by viewModels() /** * Sets up the screen behaviour */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) binding.challengesList.setHasFixedSize(true) binding.challengesList.layoutManager = LinearLayoutManager(this) viewModel.challenges.observe(this) { result -> result.onSuccess { binding.challengesList.adapter = ChallengesListAdapter(it, ::challengeSelected) binding.refreshLayout.isRefreshing = false } result.onFailure { Toast.makeText(this, R.string.error_getting_list, Toast.LENGTH_LONG).show() } } binding.refreshLayout.setOnRefreshListener { updateChallengesList() } binding.createChallengeButton.setOnClickListener { startActivity(Intent(this, CreateChallengeActivity::class.java)) } viewModel.enrolmentResult.observe(this) { it?.onSuccess { createdGameInfo -> val intent = GameActivity.buildIntent( origin = this, turn = Player.firstToMove, local = Player.firstToMove.other, boardState = stringArrayToBoardState(createdGameInfo.second.board), challengeInfo = createdGameInfo.first ) startActivity(intent) } } } /** * The screen is about to become visible: refresh its contents. */ override fun onStart() { super.onStart() updateChallengesList() } /** * Called whenever the challenges list is to be fetched again. */ private fun updateChallengesList() { binding.refreshLayout.isRefreshing = true viewModel.fetchChallenges() } /** * Called whenever a list element is selected. The player that accepts the challenge is the * first to make a move. * * @param challenge the selected challenge */ private fun challengeSelected(challenge: ChallengeInfo) { AlertDialog.Builder(this) .setTitle(getString(R.string.accept_challenge_dialog_title, challenge.challengerName)) .setPositiveButton(R.string.accept_challenge_dialog_ok) { _, _ -> viewModel.tryAcceptChallenge(challenge) } .setNegativeButton(R.string.accept_challenge_dialog_cancel, null) .create() .show() } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/challenges/list/ChallengesListActivity.kt
417950114
package pt.isel.pdm.chess4android.challenges.list import android.animation.ValueAnimator import android.graphics.drawable.GradientDrawable import android.view.LayoutInflater import android.view.ViewGroup import android.widget.TextView import androidx.core.animation.doOnEnd import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import pt.isel.pdm.chess4android.R import pt.isel.pdm.chess4android.challenges.ChallengeInfo /** * Represents views (actually, the corresponding holder) that display the information pertaining to * a [ChallengeInfo] instance */ class ChallengeViewHolder(private val view: ViewGroup) : RecyclerView.ViewHolder(view) { private val challengerNameView: TextView = view.findViewById(R.id.challengerName) private val challengerMessageView: TextView = view.findViewById(R.id.message) /** * Starts the item selection animation and calls [onAnimationEnd] once the animation ends */ private fun startAnimation(onAnimationEnd: () -> Unit) { val animation = ValueAnimator.ofArgb( ContextCompat.getColor(view.context, R.color.list_item_background), ContextCompat.getColor(view.context, R.color.list_item_background_selected), ContextCompat.getColor(view.context, R.color.list_item_background) ) animation.addUpdateListener { animator -> val background = view.background as GradientDrawable background.setColor(animator.animatedValue as Int) } animation.duration = 400 animation.start() animation.doOnEnd { onAnimationEnd() } } /** * Used to create an association between the current view holder instance and the given * data item * * @param challenge the challenge data item * @param itemSelectedListener the function to be called whenever the item is selected */ fun bindTo(challenge: ChallengeInfo?, itemSelectedListener: (ChallengeInfo) -> Unit) { challengerNameView.text = challenge?.challengerName ?: "" challengerMessageView.text = challenge?.challengerMessage ?: "" if (challenge != null) view.setOnClickListener { itemView.isClickable = false startAnimation { itemSelectedListener(challenge) itemView.isClickable = true } } } } /** * Adapts [ChallengeInfo] instances to be displayed in a [RecyclerView] */ class ChallengesListAdapter( private val contents: List<ChallengeInfo> = emptyList(), private val itemSelectedListener: (ChallengeInfo) -> Unit = { }) : RecyclerView.Adapter<ChallengeViewHolder>() { override fun onBindViewHolder(holder: ChallengeViewHolder, position: Int) { holder.bindTo(contents[position], itemSelectedListener) } override fun getItemCount(): Int = contents.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChallengeViewHolder { val view = LayoutInflater .from(parent.context) .inflate(R.layout.recycler_view_item, parent, false) as ViewGroup return ChallengeViewHolder(view) } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/challenges/list/ChallengesListAdapter.kt
2419202500
package pt.isel.pdm.chess4android.challenges import android.util.Log import com.google.firebase.firestore.ListenerRegistration import com.google.firebase.firestore.QueryDocumentSnapshot import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import pt.isel.pdm.chess4android.TAG /** * The path of the Firestore collection that contains all the challenges */ private const val CHALLENGES_COLLECTION = "challenges" private const val CHALLENGER_NAME = "challengerName" private const val CHALLENGER_MESSAGE = "challengerMessage" /** * The repository for the Chess challenges, implemented using Firebase. */ class ChallengesRepository { /** * Fetches the list of open challenges from the backend * * Implementation note: We limit the maximum number of obtained challenges. Fetching ALL * challenges is a bad design decision because the resulting data set size is unbounded! */ fun fetchChallenges(onComplete: (Result<List<ChallengeInfo>>) -> Unit) { val limit = 30 Firebase.firestore.collection(CHALLENGES_COLLECTION) .get() .addOnSuccessListener { result -> Log.v(TAG, "Repo got list from Firestore") onComplete(Result.success(result.take(limit).map { it.toChallengeInfo() })) } .addOnFailureListener { Log.e(TAG, "Repo: An error occurred while fetching list from Firestore") Log.e(TAG, "Error was $it") onComplete(Result.failure(it)) } } /** * Publishes a challenge with the given [name] and [message]. */ fun publishChallenge( name: String, message: String, onComplete: (Result<ChallengeInfo>) -> Unit ) { Firebase.firestore.collection(CHALLENGES_COLLECTION) .add(hashMapOf(CHALLENGER_NAME to name, CHALLENGER_MESSAGE to message)) .addOnSuccessListener { onComplete(Result.success(ChallengeInfo(it.id, name, message))) } .addOnFailureListener { onComplete(Result.failure(it)) } } /** * Withdraw the challenge with the given identifier. */ fun withdrawChallenge(challengeId: String, onComplete: (Result<Unit>) -> Unit) { Firebase.firestore .collection(CHALLENGES_COLLECTION) .document(challengeId) .delete() .addOnSuccessListener { onComplete(Result.success(Unit)) } .addOnFailureListener { onComplete(Result.failure(it)) } } /** * Subscribes for changes in the challenge identified by [challengeId] */ fun subscribeToChallengeAcceptance( challengeId: String, onSubscriptionError: (Exception) -> Unit, onChallengeAccepted: () -> Unit ): ListenerRegistration { return Firebase.firestore .collection(CHALLENGES_COLLECTION) .document(challengeId) .addSnapshotListener { snapshot, error -> if (error != null) { onSubscriptionError(error) return@addSnapshotListener } if (snapshot?.exists() == false) { // Document has been removed, thereby signalling that someone accepted // the challenge onChallengeAccepted() } } } /** * Unsubscribes for changes in the challenge identified by [challengeId] */ fun unsubscribeToChallengeAcceptance(subscription: ListenerRegistration) { subscription.remove() } } /** * Extension function used to convert createdChallenge documents stored in the Firestore DB into * [ChallengeInfo] instances */ private fun QueryDocumentSnapshot.toChallengeInfo() = ChallengeInfo( id, data[CHALLENGER_NAME] as String, data[CHALLENGER_MESSAGE] as String )
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/challenges/ChallengesRepository.kt
240832346
package pt.isel.pdm.chess4android.challenges.create import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import pt.isel.pdm.chess4android.R import pt.isel.pdm.chess4android.TAG import pt.isel.pdm.chess4android.common.BoardState import pt.isel.pdm.chess4android.model.Player import pt.isel.pdm.chess4android.databinding.ActivityCreateChallengeBinding import pt.isel.pdm.chess4android.game.GameActivity /** * The activity used to create a new challenge. */ class CreateChallengeActivity : AppCompatActivity() { private val viewModel: CreateChallengeViewModel by viewModels() private val binding: ActivityCreateChallengeBinding by lazy { ActivityCreateChallengeBinding.inflate(layoutInflater) } /** * Callback method that handles the activity initiation */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) viewModel.created.observe(this) { if (it == null) displayCreateChallenge() else it.onFailure { displayError() } .onSuccess { displayWaitingForChallenger() } } viewModel.accepted.observe(this) { if (it == true) { Log.v(TAG, "Someone accepted our challenge") viewModel.created.value?.onSuccess { challenge -> val intent = GameActivity.buildIntent( origin = this, turn = Player.firstToMove, local = Player.firstToMove, boardState = BoardState(), challengeInfo = challenge ) startActivity(intent) } } } binding.action.setOnClickListener { if (viewModel.created.value == null) viewModel.createChallenge( binding.name.text.toString(), binding.message.text.toString() ) else viewModel.removeChallenge() } } /** * Displays the screen in its Create challenge state */ private fun displayCreateChallenge() { binding.action.text = getString(R.string.create_challenge_button_label) with(binding.name) { text.clear(); isEnabled = true } with(binding.message) { text.clear(); isEnabled = true } binding.loading.isVisible = false binding.waitingMessage.isVisible = false } /** * Displays the screen in its Waiting for challenge state */ private fun displayWaitingForChallenger() { binding.action.text = getString(R.string.cancel_challenge_button_label) binding.name.isEnabled = false binding.message.isEnabled = false binding.loading.isVisible = true binding.waitingMessage.isVisible = true } /** * Displays the screen in its error creating challenge state */ private fun displayError() { displayCreateChallenge() Toast .makeText(this, R.string.error_creating_challenge, Toast.LENGTH_LONG) .show() } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/challenges/create/CreateChallengeActivity.kt
1462093498
package pt.isel.pdm.chess4android.challenges.create import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.google.firebase.firestore.ListenerRegistration import pt.isel.pdm.chess4android.ChessApplication import pt.isel.pdm.chess4android.challenges.ChallengeInfo /** * The View Model to be used in the [CreateChallengeActivity]. * * Challenges are created by participants and are posted on the server, awaiting acceptance. */ class CreateChallengeViewModel(app: Application) : AndroidViewModel(app) { /** * Used to publish the result of the challenge creation operation. Null if no challenge is * currently published. */ private val _created: MutableLiveData<Result<ChallengeInfo>?> = MutableLiveData(null) val created: LiveData<Result<ChallengeInfo>?> = _created /** * Used to publish the acceptance state of the challenge */ private val _accepted: MutableLiveData<Boolean> = MutableLiveData(false) val accepted: LiveData<Boolean> = _accepted /** * Creates a challenge with the given arguments. The result is placed in [created] */ fun createChallenge(name: String, message: String) { var app = getApplication<ChessApplication>() var challenge = app.challengesRepository var publish = challenge.publishChallenge( name = name, message = message, onComplete = { _created.value = it it.onSuccess(::waitForAcceptance) } ) } /** * Withdraws the current challenge from the list of available challenges. * @throws IllegalStateException if there's no challenge currently published */ fun removeChallenge() { val currentChallenge = created.value check(currentChallenge != null && currentChallenge.isSuccess) val repo = getApplication<ChessApplication>().challengesRepository subscription?.let { repo.unsubscribeToChallengeAcceptance(it) } currentChallenge.onSuccess { repo.withdrawChallenge( challengeId = it.id, onComplete = { _created.value = null } ) } } /** * Lets cleanup. The view model is about to be destroyed. */ override fun onCleared() { if (created.value != null && created.value?.isSuccess == true) removeChallenge() } private var subscription: ListenerRegistration? = null private fun waitForAcceptance(challengeInfo: ChallengeInfo) { subscription = getApplication<ChessApplication>().challengesRepository.subscribeToChallengeAcceptance( challengeId = challengeInfo.id, onSubscriptionError = { _created.value = Result.failure(it) }, onChallengeAccepted = { _accepted.value = true }, ) } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/challenges/create/CreateChallengeViewModel.kt
2620268218
package pt.isel.pdm.chess4android.challenges import android.os.Parcelable import kotlinx.parcelize.Parcelize /** * The challenge information. * * @property [id] the challenge identifier * @property [challengerName] the challenger name * @property [challengerMessage] the challenger message */ @Parcelize data class ChallengeInfo( val id: String, val challengerName: String, val challengerMessage: String ) : Parcelable
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/challenges/ChallengeInfo.kt
3310786605
package pt.isel.pdm.chess4android.converters import androidx.room.TypeConverter import com.google.gson.Gson import com.google.gson.reflect.TypeToken import pt.isel.pdm.chess4android.daily.Game class GameConverter { var gson : Gson = Gson() @TypeConverter fun gameItemToString(gameItem: Game): String { return gson.toJson(gameItem) } @TypeConverter fun stringToGameItem(data: String): Game { return gson.fromJson(data, Game::class.java) } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/converters/GameConverter.kt
686822791
package pt.isel.pdm.chess4android.converters import androidx.room.TypeConverter import com.google.gson.Gson import com.google.gson.reflect.TypeToken import pt.isel.pdm.chess4android.common.BoardState class BoardStateConverter { var gson : Gson = Gson() @TypeConverter fun boardStateItemToString(gameItem: BoardState): String { return gson.toJson(gameItem) } @TypeConverter fun stringToBoardStateItem(data: String): BoardState { return gson.fromJson(data, BoardState::class.java) } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/converters/BoardStateConverter.kt
3140199667
package pt.isel.pdm.chess4android.converters import androidx.room.TypeConverter import com.google.gson.Gson import com.google.gson.reflect.TypeToken import pt.isel.pdm.chess4android.daily.Puzzle class PuzzleConverter { var gson : Gson = Gson() @TypeConverter fun puzzleItemToString(gameItem: Puzzle): String { return gson.toJson(gameItem) } @TypeConverter fun stringToPuzzleItem(data: String): Puzzle { return gson.fromJson(data, Puzzle::class.java) } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/converters/PuzzleConverter.kt
4136252636
package pt.isel.pdm.chess4android.converters import androidx.room.TypeConverter import java.util.* class TimeConverter { @TypeConverter fun fromTimeStamp(value : Long) = Date(value) @TypeConverter fun dateToTimeStamp(date: Date) = date.time }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/converters/TimeConverter.kt
206603484
package pt.isel.pdm.chess4android.game import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import pt.isel.pdm.chess4android.R import pt.isel.pdm.chess4android.TAG import pt.isel.pdm.chess4android.challenges.ChallengeInfo import pt.isel.pdm.chess4android.common.BoardState import pt.isel.pdm.chess4android.common.Tile import pt.isel.pdm.chess4android.common.model import pt.isel.pdm.chess4android.common.stringArrayToBoardState import pt.isel.pdm.chess4android.databinding.ActivityGameBinding import pt.isel.pdm.chess4android.model.Board import pt.isel.pdm.chess4android.model.Player private const val GAME_EXTRA = "GameActivity.GameInfoExtra" private const val LOCAL_PLAYER_EXTRA = "GameActivity.PlayerExtra" /** * The activity that displays the board. */ class GameActivity : AppCompatActivity() { companion object { fun buildIntent( origin: Context, turn: Player, local: Player, boardState: BoardState, challengeInfo: ChallengeInfo ) = Intent(origin, GameActivity::class.java) .putExtra(GAME_EXTRA, Board(turn = turn).toGameState(challengeInfo.id, boardState)) .putExtra(LOCAL_PLAYER_EXTRA, local.name) } private val binding: ActivityGameBinding by lazy { ActivityGameBinding.inflate(layoutInflater) } private val localPlayer: Player by lazy { val local = intent.getStringExtra(LOCAL_PLAYER_EXTRA) if (local != null) Player.valueOf(local) else throw IllegalArgumentException("Mandatory extra $LOCAL_PLAYER_EXTRA not present") } private val initialState: GameState by lazy { intent.getParcelableExtra<GameState>(GAME_EXTRA) ?: throw IllegalArgumentException("Mandatory extra $GAME_EXTRA not present") } private val viewModel: GameViewModel by viewModels { @Suppress("UNCHECKED_CAST") object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return GameViewModel(application, initialState, localPlayer) as T } } } /** * Callback method that handles the activity initiation */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) Log.v(TAG, "GameActivity.onCreate()") Log.v(TAG, "Local player is $localPlayer") Log.v(TAG, "Turn player is ${initialState.turn}") binding.forfeitButton.setOnClickListener { // Game End binding.boardView.tileClickedListener = null } viewModel.game.observe(this) { updateUI() } } private fun updateBoard() { binding.forfeitButton.isClickable = if (viewModel.game.value?.isSuccess == true) viewModel.localPlayer == viewModel.game.value?.getOrThrow()?.turn else false /* Gets the information from another activity */ val game = intent.getParcelableExtra<GameState>(GAME_EXTRA) var boardState = BoardState() if (game != null) { /* Transformes the string with the boardInfo from Intent to a boardState */ if (game.board != null) boardState = stringArrayToBoardState(game.board) binding.boardView.model = boardState // Game Validations binding.boardView.tileClickedListener = { tile: Tile, row: Int, column: Int -> var piece: Pair<model.Army, model.Piece>? = tile.piece // Updates the board with the player moves boardState = viewModel.makeMove(boardState, row, column, piece, game.turn) binding.boardView.model = boardState } } } private fun updateUI() { updateBoard() } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/game/GameActivity.kt
1040627537
package pt.isel.pdm.chess4android.game import android.app.Application import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import pt.isel.pdm.chess4android.ChessApplication import pt.isel.pdm.chess4android.TAG import pt.isel.pdm.chess4android.common.BoardState import pt.isel.pdm.chess4android.common.getPlayVerifier import pt.isel.pdm.chess4android.common.model import pt.isel.pdm.chess4android.common.updateModelLocalMultiplayer import pt.isel.pdm.chess4android.model.Board import pt.isel.pdm.chess4android.model.Player import pt.isel.pdm.chess4android.model.stringToPlayer /** * The Game screen view model */ class GameViewModel( app: Application, private val initialGameState: GameState, val localPlayer: Player ): AndroidViewModel(app) { private val _game: MutableLiveData<Result<Board>> by lazy { MutableLiveData(Result.success(initialGameState.toBoard())) } val game: LiveData<Result<Board>> = _game private val gameSubscription = getApplication<ChessApplication>() .gamesRepository.subscribeToGameStateChanges( challengeId = initialGameState.id, onSubscriptionError = { _game.value = Result.failure(it) }, onGameStateChange = { _game.value = Result.success(it.toBoard()) } ) /** * Makes a move at the given position. Publishes the result in [game] live data */ fun makeMove(board: BoardState, row: Int, column: Int, piece: Pair<model.Army, model.Piece>?, turn: String?) : BoardState { Log.v(TAG, "Making move at $row , $column") val player = stringToPlayer(turn) if (player == localPlayer) { var idx : Int if(turn == "WHITE") idx = 0 else idx = 1 val newBoardState = updateModelLocalMultiplayer(board,row,column, idx) // ,piece) ,idx) var status = getPlayVerifier() // Puzzle End if (status == 1) { Log.v(TAG, "Board became ${Board(turn=player).toGameState(initialGameState.id,newBoardState)}") var newBoard = Board(player,newBoardState) _game.value = Result.success(newBoard) getApplication<ChessApplication>().gamesRepository.updateGameState( gameState = Board(turn=player).toGameState(initialGameState.id,newBoardState), onComplete = { result -> result.onFailure { _game.value = Result.failure(it) } } ) } return newBoardState } return board } /** * View model is destroyed */ override fun onCleared() { super.onCleared() getApplication<ChessApplication>().gamesRepository.deleteGame( challengeId = initialGameState.id, onComplete = { } ) gameSubscription.remove() } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/game/GameViewModel.kt
4225339367
package pt.isel.pdm.chess4android.game import com.google.firebase.firestore.ListenerRegistration import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.google.gson.Gson import pt.isel.pdm.chess4android.challenges.ChallengeInfo import pt.isel.pdm.chess4android.common.BoardState import pt.isel.pdm.chess4android.model.Board import pt.isel.pdm.chess4android.model.Player /** * The path of the Firestore collection that contains all the active games */ private const val GAMES_COLLECTION = "games" private const val GAME_STATE_KEY = "game" /** * The repository for the Puzzle games, implemented using Firebase. */ class GamesRepository(private val mapper: Gson) { /** * Creates the game for the given challenge ID */ fun createGame(challenge: ChallengeInfo, onComplete: (Result<Pair<ChallengeInfo, GameState>>) -> Unit) { val gameState = Board(turn = Player.WHITE).toGameState(challenge.id, BoardState()) Firebase.firestore.collection(GAMES_COLLECTION) .document(challenge.id) .set(hashMapOf(GAME_STATE_KEY to mapper.toJson(gameState))) .addOnSuccessListener { onComplete(Result.success(Pair(challenge, gameState))) } .addOnFailureListener { onComplete(Result.failure(it)) } } /** * Updates the shared game state */ fun updateGameState(gameState: GameState, onComplete: (Result<GameState>) -> Unit) { Firebase.firestore.collection(GAMES_COLLECTION) .document(gameState.id) .set(hashMapOf(GAME_STATE_KEY to mapper.toJson(gameState))) .addOnSuccessListener { onComplete(Result.success(gameState)) } .addOnFailureListener { onComplete(Result.failure(it)) } } /** * Subscribes for changes in the challenge identified by [challengeId] */ fun subscribeToGameStateChanges( challengeId: String, onSubscriptionError: (Exception) -> Unit, onGameStateChange: (GameState) -> Unit ): ListenerRegistration { return Firebase.firestore .collection(GAMES_COLLECTION) .document(challengeId) .addSnapshotListener { snapshot, error -> if (error != null) { onSubscriptionError(error) return@addSnapshotListener } if (snapshot?.exists() == true) { val gameState = mapper.fromJson( snapshot.get(GAME_STATE_KEY) as String, GameState::class.java ) onGameStateChange(gameState) } } } /** * Deletes the shared game state for the given challenge. */ fun deleteGame(challengeId: String, onComplete: (Result<Unit>) -> Unit) { Firebase.firestore.collection(GAMES_COLLECTION) .document(challengeId) .delete() .addOnSuccessListener { onComplete(Result.success(Unit)) } .addOnFailureListener { onComplete(Result.failure(it)) } } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/game/GamesRepository.kt
410424400
package pt.isel.pdm.chess4android.game import android.os.Parcelable import kotlinx.parcelize.Parcelize import pt.isel.pdm.chess4android.common.BoardState import pt.isel.pdm.chess4android.model.Player import pt.isel.pdm.chess4android.common.boardStateToStringArray import pt.isel.pdm.chess4android.common.stringArrayToBoardState import pt.isel.pdm.chess4android.model.Board /** * Data type used to represent the game state externally, that is, when the game state crosses * process boundaries and device boundaries. */ @Parcelize data class GameState( val id: String, val turn: String?, val board: Array<String> ): Parcelable /** * Extension to create a [GameState] instance from this [Board]. */ fun Board.toGameState(gameId: String, boardState: BoardState): GameState { return GameState(id = gameId, turn = turn?.name, board = boardStateToStringArray(boardState)) } /** * Extension to create a [Board] instance from this [GameState]. */ fun GameState.toBoard() = Board( turn = if (turn != null) Player.valueOf(turn) else null, board = stringArrayToBoardState(board) )
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/game/GameState.kt
3386268827
package pt.isel.pdm.chess4android.daily import android.content.Intent import android.os.Bundle import android.util.Log import pt.isel.pdm.chess4android.challenges.create.CreateChallengeActivity import pt.isel.pdm.chess4android.challenges.list.ChallengesListActivity import pt.isel.pdm.chess4android.common.LoggingActivity import pt.isel.pdm.chess4android.credits.CreditActivity import pt.isel.pdm.chess4android.databinding.ActivityMainBinding import pt.isel.pdm.chess4android.history.HistoryActivity import pt.isel.pdm.chess4android.localGame.LocalGameActivity import pt.isel.pdm.chess4android.resolution.ResolutionActivity class MainActivity : LoggingActivity() { private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) binding.playButton.setOnClickListener{ Log.v("APP_TAG", "PLAY GAME") startActivity(Intent(this, ResolutionActivity::class.java)) } binding.pvpButton?.setOnClickListener{ Log.v("APP_TAG", "LOCAL") startActivity(Intent(this, LocalGameActivity::class.java)) } binding.historyButton?.setOnClickListener{ Log.v("APP_TAG", "HISTORY") startActivity(Intent(this, HistoryActivity::class.java)) } binding.creditsButton.setOnClickListener{ Log.v("APP_TAG", "CREDITS") startActivity(Intent(this, CreditActivity::class.java)) } } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/daily/MainActivity.kt
556819851
package pt.isel.pdm.chess4android.daily import android.os.Parcelable import kotlinx.parcelize.Parcelize import pt.isel.pdm.chess4android.common.BoardState import retrofit2.Call import retrofit2.http.GET import java.util.* @Parcelize data class Game(val id: String, val pgn: String) : Parcelable @Parcelize data class Puzzle(val id: String, val initialPly : Int, val solution : List<String>) : Parcelable @Parcelize data class DayPuzzleDTO(val game: Game, val puzzle: Puzzle, val timestamp: Date, var status: Boolean, var resolvedBoard : BoardState) : Parcelable interface DayPuzzleService { @GET("puzzle/daily") fun getDayPuzzle() : Call<DayPuzzleDTO> } /** * Represents errors while accessing the remote API. Instead of tossing around Retrofit errors, * we can use this exception to wrap them up. */ class ServiceUnavailable(message: String = "", cause: Throwable? = null) : Exception(message, cause)
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/daily/DayPuzzleService.kt
2826431544
package pt.isel.pdm.chess4android.daily import android.content.Context import android.util.Log import androidx.concurrent.futures.CallbackToFutureAdapter import androidx.work.ListenableWorker import androidx.work.WorkerParameters import com.google.common.util.concurrent.ListenableFuture import pt.isel.pdm.chess4android.common.APP_TAG import pt.isel.pdm.chess4android.common.PuzzleOfDayApplication import pt.isel.pdm.chess4android.common.PuzzleOfDayRepository /** * Definition of the background job that fetches the daily quote and stores it in the history DB. */ class DownloadDailyPuzzleWorker(appContext: Context, workerParams: WorkerParameters) : ListenableWorker(appContext, workerParams) { override fun startWork(): ListenableFuture<Result> { val app : PuzzleOfDayApplication = applicationContext as PuzzleOfDayApplication val repo = PuzzleOfDayRepository(app.puzzleOfDayService, app.historyDB.getHistoryPuzzleDao()) Log.v(APP_TAG, "Thread ${Thread.currentThread().name}: Starting DownloadDailyQuoteWorker") return CallbackToFutureAdapter.getFuture { completer -> repo.fetchPuzzleOfDay(mustSaveToDB = true) { result -> result .onSuccess { Log.v(APP_TAG, "Thread ${Thread.currentThread().name}: DownloadDailyPuzzleWorker succeeded") completer.set(Result.success()) } .onFailure { Log.v(APP_TAG, "Thread ${Thread.currentThread().name}: DownloadDailyPuzzleWorker failed") completer.setException(it) } } } } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/daily/DownloadDailyPuzzleWorker.kt
255274985
package pt.isel.pdm.chess4android.common import android.util.Log import pt.isel.pdm.chess4android.daily.* import pt.isel.pdm.chess4android.history.HistoryPuzzleDao import pt.isel.pdm.chess4android.history.PuzzleEntity import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.time.Instant import java.time.temporal.ChronoUnit import java.util.* /** * Extension function of [PuzzleEntity] to conveniently convert it to a [DayPuzzleDTO] instance. */ private fun PuzzleEntity.toPuzzleOfDayDTO() = DayPuzzleDTO( game = Game(game.id, game.pgn), puzzle = Puzzle(puzzle.id, puzzle.initialPly, puzzle.solution), status = status, timestamp = timestamp, resolvedBoard = resolvedBoard ) /** * Class repository that represents a SERVICE and a DAO */ class PuzzleOfDayRepository( private val puzzleOfDayService: DayPuzzleService, private val historyPuzzleDao: HistoryPuzzleDao ) { private val todayTimeStamp: Date = Date.from(Instant.now().truncatedTo(ChronoUnit.DAYS)) /** * Asynchronously gets the daily puzzle from the local DB, if available. * @param callback the function to be called to signal the completion of the * asynchronous operation, which is called in the MAIN THREAD. */ private fun asyncMaybeGetTodayPuzzleFromDB(callback: (Result<PuzzleEntity?>) -> Unit) { callbackAfterAsync(callback, asyncAction = { // GetLast is a synchronous function, runs in an alternative THREAD val mostRecentPuzzle = historyPuzzleDao.getLast(1).get(0) if(todayTimeStamp == mostRecentPuzzle.timestamp) { mostRecentPuzzle } else null }) } /** * Asynchronously gets the daily puzzle from the remote API. * @param callback the function to be called to signal the completion of the * asynchronous operation, which is called in the MAIN THREAD. */ private fun asyncGetTodayPuzzleFromAPI(callback: (Result<DayPuzzleDTO>) -> Unit) { puzzleOfDayService.getDayPuzzle().enqueue( object: Callback<DayPuzzleDTO> { override fun onResponse(call: Call<DayPuzzleDTO>, response: Response<DayPuzzleDTO>) { Log.v(APP_TAG, "Thread ${Thread.currentThread().name}: onResponse ") val dailyPuzzle : DayPuzzleDTO? = response.body() val result = if(response.isSuccessful && dailyPuzzle != null) { Result.success(dailyPuzzle) } else if(response.code() == 401) { Log.e( APP_TAG,"Your session has expired. Try again.") Result.failure(ServiceUnavailable()) } else { Log.e( APP_TAG,"Failed to retrieve items") Result.failure(ServiceUnavailable()) } callback(result) } override fun onFailure(call: Call<DayPuzzleDTO>, error: Throwable) { Log.v(APP_TAG, "Thread ${Thread.currentThread().name}: onFailure ") callback(Result.failure(ServiceUnavailable(cause = error))) } }) } /** * Asynchronously saves the daily quote to the local DB. * @param callback the function to be called to signal the completion of the * asynchronous operation, which is called in the MAIN THREAD. */ private fun asyncSaveToDB(dto: DayPuzzleDTO, callback: (Result<Unit>) -> Unit = { }) { callbackAfterAsync(callback) { historyPuzzleDao.insert( PuzzleEntity(id = dto.puzzle.id, game = dto.game, puzzle = dto.puzzle) ) } } /** * Asynchronously gets the quote of day, either from the local DB, if available, or from * the remote API. * * @param mustSaveToDB indicates if the operation is only considered successful if all its * steps, including saving to the local DB, succeed. If false, the operation is considered * successful regardless of the success of saving the quote in the local DB (the last step). * @param callback the function to be called to signal the completion of the * asynchronous operation, which is called in the MAIN THREAD * * Using a boolean to distinguish between both options is a questionable design decision. */ fun fetchPuzzleOfDay(mustSaveToDB: Boolean = false, callback: (Result<DayPuzzleDTO>) -> Unit ) { // 1: Check if in DB asyncMaybeGetTodayPuzzleFromDB { maybeEntity -> val maybePuzzle = maybeEntity.getOrNull() if(maybePuzzle != null) { Log.v(APP_TAG, "Thread ${Thread.currentThread().name}: Got daily puzzle from local DB") callback( Result.success(maybePuzzle.toPuzzleOfDayDTO()) ) } else { // 2: Get PUZZLE from API asyncGetTodayPuzzleFromAPI { apiResult -> apiResult.onSuccess { puzzleDTO -> Log.v(APP_TAG, "Thread ${Thread.currentThread().name}: Got daily puzzle from API") // Save to DB asyncSaveToDB(puzzleDTO) { saveToDBResult -> saveToDBResult .onSuccess { Log.v(APP_TAG, "Thread ${Thread.currentThread().name}: Saved daily puzzle to local DB") callback(Result.success(puzzleDTO)) } .onFailure { Log.e(APP_TAG, "Thread ${Thread.currentThread().name}: Failed to save daily puzzle to local DB", it) callback( if(mustSaveToDB) Result.failure(it) else Result.success(puzzleDTO) ) } } } callback(apiResult) } } } } /** * Asynchronously saves the daily quote to the local DB. * @param callback the function to be called to signal the completion of the * asynchronous operation, which is called in the MAIN THREAD. */ fun asyncUpdateDB(dto: DayPuzzleDTO, callback: (Result<Unit>) -> Unit = { }) { callbackAfterAsync(callback) { historyPuzzleDao.update( PuzzleEntity(id = dto.puzzle.id, game = dto.game, puzzle = dto.puzzle, status = dto.status, resolvedBoard = dto.resolvedBoard) ) } } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/common/PuzzleOfDayRepository.kt
670190387
package pt.isel.pdm.chess4android.common import android.app.Application import android.util.Log import androidx.room.Room import androidx.work.* import pt.isel.pdm.chess4android.daily.DayPuzzleService import pt.isel.pdm.chess4android.daily.DownloadDailyPuzzleWorker import pt.isel.pdm.chess4android.history.HistoryDataBase import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit /* private val gameTest: Game = Game("nZyFAzDd", "e4 d6 f4 Nf6 Nc3 c5 Nf3 Nc6 a3 g6 Bc4 Bg7 O-O O-O d4 cxd4 Nxd4 Qb6 Ne2 Nxe4 Be3 e5 Nf5 Qxb2 Nxg7 Kxg7") private val puzzleTest : Puzzle = Puzzle("M3qHz", 25, listOf( "a1a2","e4c3","a2b2","c3d1","f1d1")) /* val historyDB : HistoryDataBase by lazy { Room.inMemoryDatabaseBuilder(this, HistoryDataBase::class.java).build() } override fun onCreate() { super.onCreate() callbackAfterAsync({}) { historyDB.getHistoryPuzzleDao().insert(PuzzleEntity(game = gameTest, puzzle = puzzleTest, id = "1")) historyDB.getHistoryPuzzleDao().insert(PuzzleEntity(game = gameTest, puzzle = puzzleTest, id = "2")) historyDB.getHistoryPuzzleDao().insert(PuzzleEntity(game = gameTest, puzzle = puzzleTest, id = "3")) } } */ */ const val APP_TAG = "DailyPuzzle" /** * Global class for the API service */ class PuzzleOfDayApplication : Application() { init { Log.v(APP_TAG, "PuzzleOfDayApplication.init") } val puzzleOfDayService : DayPuzzleService by lazy { Retrofit.Builder() .baseUrl("https://lichess.org/api/") .addConverterFactory(GsonConverterFactory.create()) .build() .create(DayPuzzleService::class.java) } val historyDB : HistoryDataBase by lazy { Room.databaseBuilder(this, HistoryDataBase::class.java, "history_db").build() } /** * Called each time the application process is loaded */ override fun onCreate() { super.onCreate() val workRequest = PeriodicWorkRequestBuilder<DownloadDailyPuzzleWorker>(1, TimeUnit.DAYS) .setConstraints( Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .setRequiresBatteryNotLow(true) .setRequiresStorageNotLow(true) .build() ) .build() WorkManager .getInstance(this) .enqueueUniquePeriodicWork( "DownloadDailyPuzzle", ExistingPeriodicWorkPolicy.KEEP, workRequest ) } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/common/PuzzleOfDayApplication.kt
2644162554
package pt.isel.pdm.chess4android.common class model { enum class Army { WHITE, BLACK } enum class Piece { PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/common/Model.kt
4087503798
package pt.isel.pdm.chess4android.common import pt.isel.pdm.chess4android.common.model.Army import pt.isel.pdm.chess4android.common.model.Piece /** * Correspondes a letter to a board index */ fun charToIntMove(move : Char) : Int{ return when(move) { 'h', '1' -> 7 'g', '2' -> 6 'f', '3' -> 5 'e', '4' -> 4 'd', '5' -> 3 'c', '6' -> 2 'b', '7' -> 1 'a', '8' -> 0 else -> move.digitToInt() - 1 } } /** * Correspondes a letter to a Piece */ fun charToPiece(move : Char) : Piece { return when(move) { 'Q' -> Piece.QUEEN 'R' -> Piece.ROOK 'B' -> Piece.BISHOP else -> Piece.KNIGHT } } /** * See if the move is outside the TILE */ fun checkOutOfBounds(y : Int, x : Int) : Boolean { if(x < 0 || y < 0 || x > 7 || y > 7) return false return true } fun knightMove(board: Array<Array<Pair<Army, Piece>?>>, move: String, pieceId: Pair<Army, Piece>) : Array<Array<Pair<Army, Piece>?>>{ // Busca os dois ultimos caracteres que correspondem ao destino da peça var x = charToIntMove(move.get(move.length-2)) var y = charToIntMove(move.get(move.length-1)) var validator = 0 var distinguishPlay = 'x' // Jogada que representa comer outra peça if(move.length == 4) distinguishPlay = move.get(1) if(move.length <= 4 && distinguishPlay == 'x') { if(checkOutOfBounds(y-2, x-1) && board[y-2][x-1]?.equals(pieceId) == true) { validator = 1 board[y-2][x-1] = null } else if(checkOutOfBounds(y-2, x+1) && board[y-2][x+1]?.equals(pieceId) == true) { validator = 1 board[y-2][x+1] = null } else if(checkOutOfBounds(y-1, x-2) && board[y-1][x-2]?.equals(pieceId) == true) { validator = 1 board[y-1][x-2] = null } else if(checkOutOfBounds(y-1, x+2) && board[y-1][x+2]?.equals(pieceId) == true) { validator = 1 board[y-1][x+2] = null } else if(checkOutOfBounds(y+1, x-2) && board[y+1][x-2]?.equals(pieceId) == true) { validator = 1 board[y+1][x-2] = null } else if(checkOutOfBounds(y+1, x+2) && board[y+1][x+2]?.equals(pieceId) == true) { validator = 1 board[y+1][x+2] = null } else if(checkOutOfBounds(y+2, x-1) && board[y+2][x-1]?.equals(pieceId) == true) { validator = 1 board[y+2][x-1] = null } else if ( checkOutOfBounds(y+2, x+1) ) { validator = 1 board[y + 2][x + 1] = null } } else { var origin = charToIntMove(move.get(1)); var i = 0; while(i < 8) { if(board[i][origin]?.equals(pieceId) == true) { validator = 1 board[i][origin] = null } i++ } } if(validator == 1) board[y][x] = pieceId; return board; } fun towerMove(board: Array<Array<Pair<Army, Piece>?>>, move: String, pieceId: Pair<Army, Piece>) : Array<Array<Pair<Army, Piece>?>>{ // Busca os dois ultimos caracteres que correspondem ao destino da peça var x = charToIntMove(move.get(move.length-2)) var y = charToIntMove(move.get(move.length-1)) var validator = 0 var distinguishPlay = 'x' if(move.length == 4) { distinguishPlay = move.get(1) } if(move.length <= 4 && distinguishPlay == 'x') { var i = x; var clear = 0 while (i < 8 && clear != 1) { if(board[y][i]?.equals(pieceId) == true) { validator = 1 board[y][i] = null clear++ } i++ } i = x while (i >= 0 && clear != 1) { if(board[y][i]?.equals(pieceId) == true) { validator = 1 board[y][i] = null clear++ } i-- } i = y while (i < 8 && clear != 1) { if(board[i][x]?.equals(pieceId) == true) { validator = 1 board[i][x] = null clear++ } i++; } i = y while (i >= 0 && clear != 1) { if(board[i][x]?.equals(pieceId) == true) { validator = 1 board[i][x] = null clear++ } i--; } } // Move.length >= 4 else { var origin = charToIntMove(move.get(1)) if(board[y][origin]?.equals(pieceId) == true) { validator = 1 board[y][origin] = null } else { validator = 1 board[origin][x] = null } } if(validator == 1) board[y][x] = pieceId; return board; } fun RoyalityMove(board: Array<Array<Pair<Army, Piece>?>>, move: String, pieceId: Pair<Army, Piece>) : Array<Array<Pair<Army, Piece>?>> { // Busca os dois ultimos caracteres que correspondem ao destino da peça var x = charToIntMove(move.get(move.length-2)) var y = charToIntMove(move.get(move.length-1)) var k = 0 var idx = 0 var boardNumber = 0 board.iterator().forEach { a -> if(a.indexOf(pieceId) >= 0 && a.indexOf(pieceId) <= 7) { k = a.indexOf(pieceId) idx = boardNumber } boardNumber++ } board[idx][k] = null board[y][x] = pieceId; return board; } fun bishopMove(board: Array<Array<Pair<Army, Piece>?>>, move: String, pieceId: Pair<Army, Piece>) : Array<Array<Pair<Army, Piece>?>>{ // Busca os dois ultimos caracteres que correspondem ao destino da peça var x = charToIntMove(move.get(move.length-2)) var y = charToIntMove(move.get(move.length-1)) var validator = 0 var i = 0; while (i < 8) { if(checkOutOfBounds(y+i, x+i) && board[y+i][x+i]?.equals(pieceId) == true) { validator = 1 board[y+i][x+i] = null } else if(checkOutOfBounds(y+i, x-i) && board[y+i][x-i]?.equals(pieceId) == true) { validator = 1 board[y+i][x-i] = null } else if(checkOutOfBounds(y-i, x+i) && board[y-i][x+i]?.equals(pieceId) == true) { validator = 1 board[y-i][x+i] = null } else if(checkOutOfBounds(y-i, x-i) && board[y-i][x-i]?.equals(pieceId) == true) { validator = 1 board[y-i][x-i] = null } i++; } if(validator == 1) board[y][x] = pieceId; return board; } fun swapMove(board: Array<Array<Pair<Army, Piece>?>>, move: String, pieceId1: Pair<Army, Piece>, pieceId2: Pair<Army, Piece>) : Array<Array<Pair<Army, Piece>?>>{ if(move.length == 5) { if(pieceId1.first.equals(Army.WHITE)) { board[7][3] = pieceId2 board[7][2] = pieceId1 board[7][0] = null board[7][4] = null } if(pieceId1.first.equals(Army.BLACK)) { board[0][2] = pieceId1 board[0][3] = pieceId2 board[0][0] = null board[0][4] = null } } else if (move.length == 3) { if(pieceId1.first.equals(Army.WHITE)) { board[7][5] = pieceId2 board[7][6] = pieceId1 board[7][7] = null board[7][4] = null } if(pieceId1.first.equals(Army.BLACK)) { board[0][6] = pieceId1 board[0][5] = pieceId2 board[0][7] = null board[0][4] = null } } return board; } // TEMOS DE ASSUMIR A JOGADA QUANDO O PAWN CHEGA NO OUTRO LADO DO TABULEIRO E TROCA DE PEÇA fun pawnMove(board: Array<Array<Pair<Army, Piece>?>>, move: String, pieceId: Pair<Army, Piece>) : Array<Array<Pair<Army, Piece>?>> { var x : Int var y : Int var validator = 0 var piece = pieceId var checkPromotion = move.get(move.length-2) if(checkPromotion.equals('=')) { piece = Pair(pieceId.first, charToPiece(move.get(move.length-1))) x = charToIntMove(move.get(move.length-4)) y = charToIntMove(move.get(move.length-3)) } else { x = charToIntMove(move.get(move.length-2)) y = charToIntMove(move.get(move.length-1)) } if(move.length == 2) { if(checkOutOfBounds(y+1, x) && board[y+1][x]?.equals(pieceId) == true) { board[y+1][x] = null validator = 1 } else if(checkOutOfBounds(y+2, x) && board[y+2][x]?.equals(pieceId) == true) { validator = 1 board[y+2][x] = null } else if(checkOutOfBounds(y-1, x) && board[y-1][x]?.equals(pieceId) == true) { validator = 1 board[y-1][x] = null } else if(checkOutOfBounds(y-2, x) && board[y-2][x]?.equals(pieceId) == true){ validator = 1 board[y-2][x] = null } } else { var k = charToIntMove(move.get(0)) if(checkOutOfBounds(y+1, k) && board[y+1][k]?.equals(pieceId) == true) { validator = 1 board[y+1][k] = null } else if(checkOutOfBounds(y-1, k) && board[y-1][k]?.equals(pieceId) == true) { validator = 1 board[y-1][k] = null } if(checkOutOfBounds(y+2, k) && board[y+2][k]?.equals(pieceId) == true) { validator = 1 board[y+2][k] = null } else if(checkOutOfBounds(y-2, k) && board[y-2][k]?.equals(pieceId) == true) { validator = 1 board[y-2][k] = null } } if(validator == 1) board[y][x] = piece; return board; }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/common/ChessMoves.kt
1464050984
package pt.isel.pdm.chess4android.common import android.annotation.SuppressLint import android.content.Context import android.content.res.Configuration import android.graphics.Canvas import android.graphics.Paint import android.util.AttributeSet import android.widget.GridLayout import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat import pt.isel.pdm.chess4android.R import pt.isel.pdm.chess4android.common.model.Piece import pt.isel.pdm.chess4android.common.model.Army import pt.isel.pdm.chess4android.common.Tile.Type typealias TileTouchListener = (tile: Tile, row: Int, column: Int) -> Unit /** * Custom view that implements a chess board. */ @SuppressLint("ClickableViewAccessibility") class BoardView(private val ctx: Context, attrs: AttributeSet?) : GridLayout(ctx, attrs) { private val side = 8 var model: BoardState = BoardState() set(value) { field = value // Remove board view to create a new one removeAllViews() rowCount = side columnCount = side repeat(side * side) { var row = it / side var column = it % side val tile = Tile(ctx, if((row + column) % 2 == 0) Type.WHITE else Type.BLACK, side, mapOf( Pair(model.getBoard()[row][column], piecesImages.get(model.getBoard()[row][column]) )) ) tile.piece = model.getBoard()[row][column] tile.setOnClickListener { tileClickedListener?.invoke(tile, row, column) } addView(tile) } } var tileClickedListener: TileTouchListener? = null private val brush = Paint().apply { ctx.resources.getColor(R.color.chess_board_black, null) style = Paint.Style.STROKE strokeWidth = 10F } private fun createImageEntry(army: Army, piece: Piece, imageId: Int) = Pair(Pair(army, piece), VectorDrawableCompat.create(ctx.resources, imageId, null)) private val piecesImages = mapOf( createImageEntry(Army.WHITE, Piece.PAWN, R.drawable.ic_white_pawn), createImageEntry(Army.WHITE, Piece.KNIGHT, R.drawable.ic_white_knight), createImageEntry(Army.WHITE, Piece.BISHOP, R.drawable.ic_white_bishop), createImageEntry(Army.WHITE, Piece.ROOK, R.drawable.ic_white_rook), createImageEntry(Army.WHITE, Piece.QUEEN, R.drawable.ic_white_queen), createImageEntry(Army.WHITE, Piece.KING, R.drawable.ic_white_king), createImageEntry(Army.BLACK, Piece.PAWN, R.drawable.ic_black_pawn), createImageEntry(Army.BLACK, Piece.KNIGHT, R.drawable.ic_black_knight), createImageEntry(Army.BLACK, Piece.BISHOP, R.drawable.ic_black_bishop), createImageEntry(Army.BLACK, Piece.ROOK, R.drawable.ic_black_rook), createImageEntry(Army.BLACK, Piece.QUEEN, R.drawable.ic_black_queen), createImageEntry(Army.BLACK, Piece.KING, R.drawable.ic_black_king), ) override fun dispatchDraw(canvas: Canvas) { super.dispatchDraw(canvas) if (context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) { canvas.drawLine(0f, 0f, width.toFloat(), 0f, brush) canvas.drawLine(0f, height.toFloat(), width.toFloat(), height.toFloat(), brush) canvas.drawLine(0f, 0f, 0f, height.toFloat(), brush) canvas.drawLine(width.toFloat(), 0f, width.toFloat(), height.toFloat(), brush) } else { canvas.drawLine(0f, 0f, height.toFloat(), 0f, brush) canvas.drawLine(0f, height.toFloat(), height.toFloat(), height.toFloat(), brush) canvas.drawLine(0f, 0f, 0f, width.toFloat(), brush) canvas.drawLine(height.toFloat(), 0f, height.toFloat(), width.toFloat(), brush) } } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/common/BoardView.kt
666402699
package pt.isel.pdm.chess4android.common import android.os.Handler import android.os.Looper import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import java.util.concurrent.Executors /** * The executor used to execute blocking IO operations */ private val ioExecutor = Executors.newSingleThreadExecutor() private fun <T> executeAndCollectResult(asyncAction: () -> T): Result<T> = try { Result.success(asyncAction()) } catch (e: Exception) { Result.failure(e) } /** * Dispatches the execution of [asyncAction] on the appropriate thread pool. * The [asyncAction] result is published by calling, IN THE MAIN THREAD, the received [callback] */ fun <T> callbackAfterAsync(callback: (Result<T>) -> Unit, asyncAction: () -> T) { val mainHandler = Handler(Looper.getMainLooper()) ioExecutor.submit { // Execute in another Thread and post it back into the main Thread queue when it's done val result = executeAndCollectResult(asyncAction) mainHandler.post { callback(result) } } } /** * Dispatches the execution of [asyncAction] on the appropriate thread pool. * The [asyncAction] result is published to the returned [LiveData] instance */ fun <T> publishInLiveDataAfterAsync(asyncAction: () -> T): LiveData<Result<T>> { val toPublish = MutableLiveData<Result<T>>() ioExecutor.submit { val result = executeAndCollectResult(asyncAction) toPublish.postValue(result) } return toPublish }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/common/asyncUtils.kt
2304501988
package pt.isel.pdm.chess4android.common import android.content.ContentValues.TAG import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log abstract class LoggingActivity : AppCompatActivity() { init { Log.v(TAG, "init()") } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.v(TAG, "onCreate()") } override fun onStart() { super.onStart() Log.v(TAG, "onStart()") } override fun onStop() { super.onStop() Log.v(TAG, "onStop()") } override fun onDestroy() { super.onDestroy() Log.v(TAG, "onDestroy()") } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/common/LoggingActivity.kt
1596800424
package pt.isel.pdm.chess4android.common import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.view.View import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat import pt.isel.pdm.chess4android.R import pt.isel.pdm.chess4android.common.model.Piece import pt.isel.pdm.chess4android.common.model.Army /** * Custom view that implements a chess board tile. * Tiles are either black or white and can they can be empty or occupied by a chess piece. * * Implementation note: This view is not to be used with the designer tool. * You need to adapt this view to suit your needs. ;) * * @property type The tile's type (i.e. black or white) * @property tilesPerSide The number of tiles in each side of the chess board */ @SuppressLint("ViewConstructor") class Tile( private val ctx: Context, private val type: Type, private val tilesPerSide: Int, private val images: Map<Pair<Army, Piece>?, VectorDrawableCompat?>, initialPiece: Pair<Army, Piece>? = null, ) : View(ctx) { var piece: Pair<Army, Piece>? = initialPiece set(value) { field = value invalidate() } enum class Type { WHITE, BLACK } private val brush = Paint().apply { color = ctx.resources.getColor( if (type == Type.WHITE) R.color.chess_board_white else R.color.chess_board_black, null ) style = Paint.Style.FILL_AND_STROKE } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val side = Integer.min( MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec) ) setMeasuredDimension(side / tilesPerSide, side / tilesPerSide) } override fun onDraw(canvas: Canvas) { canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), brush) if (piece != null) { images[piece]?.apply { val padding = 8 setBounds(padding, padding, width-padding, height-padding) draw(canvas) } } } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/common/Tile.kt
1180389950
package pt.isel.pdm.chess4android.common fun boardStateToStringArray(boardState : BoardState) : Array<String> { var pieces : MutableList<String> = ArrayList() var board = boardState.getBoard() board.map { pairArray -> pairArray.map { pair -> pieces.add(pair.toString()) } } return pieces.toTypedArray() } private fun getArmyEntry(stringArmy: String) : model.Army { return when (stringArmy) { "BLACK" -> model.Army.BLACK else -> model.Army.WHITE } } private fun getPieceEntry(stringPiece: String) : model.Piece { return when (stringPiece) { " ROOK" -> model.Piece.ROOK " BISHOP" -> model.Piece.BISHOP " KNIGHT" -> model.Piece.KNIGHT " KING" -> model.Piece.KING " QUEEN" -> model.Piece.QUEEN else -> model.Piece.PAWN } } fun stringToPair(pairString : String) : Pair<model.Army, model.Piece>? { if(pairString.equals("null")) return null val replaced = pairString.replace("(", "") .replace(")", "") .split(",") return Pair(getArmyEntry(replaced[0]), getPieceEntry(replaced[1])) } fun stringArrayToBoardState(boardArray: Array<String>) : BoardState { var columnIdx = 0 var lineIdx = 0 var idx = 0 var line : Array<Pair<model.Army, model.Piece>?> = arrayOfNulls(8) var board : MutableList<Array<Pair<model.Army, model.Piece>?>> = mutableListOf< Array<Pair<model.Army, model.Piece>?>>() while ( columnIdx < 8 ) { while (lineIdx < 8 ) { line[lineIdx] = stringToPair(boardArray[idx]) lineIdx ++ idx ++ } board.add(columnIdx, line) columnIdx ++ lineIdx = 0 line = arrayOfNulls(8) } val boardState = BoardState() return boardState.setBoard(board.toTypedArray()) }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/common/BoardStateParcelize.kt
1822818917
package pt.isel.pdm.chess4android.common import pt.isel.pdm.chess4android.daily.DayPuzzleDTO private var solution : List<String> = mutableListOf<String>() private var solutionIndex : Int = 0 private var movingPiece : String? = null private var playIndex : Int = 0 private var playVerifier : Int = 0 private var rightPieceSelected : Boolean = false private var originCordinateX : Int = 0 private var originCordinateY : Int = 0 /** * Correspondes a Piece to a Char */ private fun PieceToCharMove(piece: Pair<model.Army, model.Piece>?) : String? { return when(piece?.second?.name) { "KNIGHT" -> "N" "BISHOP" -> "B" "ROOK" -> "R" "QUEEN" -> "Q" "KING" -> "K" "PAWN" -> "" else -> null } } /** * Updates with the information of the piece that the user wants to move (ONLY LOCAL USE) */ fun selectPiece(piece: Pair<model.Army, model.Piece>?, row: Int, column: Int) { movingPiece = PieceToCharMove(piece) originCordinateX = row originCordinateY = column playVerifier = 0 } /** * Function that swaps the KING info to a ROQUE info (ONLY LOCAL USE) */ fun roque(piece: String?) { movingPiece = piece } /** * Returns the current piece */ fun getPiece() : String? { return movingPiece } /** * Returns the status of the move (SUCESS, CHECK, ERROR, END GAME) */ fun getPlayVerifier() : Int { return playVerifier } /** * Returns the ARMY of the current move (ONLY API USE) */ fun getPlayingArmy() : String { if(playIndex % 2 == 0) return "white" return "black" } /** * Create a representation of the board with the data from the API */ fun createModel(d: DayPuzzleDTO) : BoardState { val board : BoardState = BoardState() // Reseting variables playVerifier = 0 solutionIndex = 0 movingPiece = null rightPieceSelected = false // Get the number of total plays playIndex = d.puzzle.initialPly.toString().toInt()-1 // Splits the solution movements from API with spaces solution = d.puzzle.solution.toString().replace("\"", "") .replace("[", "") .replace("]", "") .replace(",", "") .split(" ") // Splits the game movements from API with spaces var pgn = d.game.pgn.replace("\"", "") .replace("+", "") .split(" ") // Make all the plays from the API var currentPlay = 0 pgn.forEach { board.doMove(it, currentPlay); currentPlay++ } return board } /** * Updates the board with a player move (ONLY USE API) */ fun updateModel(board: BoardState, row: Int, column: Int, piece: Pair<model.Army, model.Piece>?): BoardState { var playerArmy : Int = playIndex // Checks if there is any more plays if (solutionIndex < solution.size) { // The current piece location val originY = charToIntMove(solution.get(solutionIndex).get(0)) val originX = charToIntMove(solution.get(solutionIndex).get(1)) // The destiny piece location val destinationY = solution.get(solutionIndex).get(2) val destinationX = solution.get(solutionIndex).get(3) // First click if( movingPiece == null ) { // Check if the player clicked the right piece if(originY == column && originX == row) { rightPieceSelected = true } if( getPlayingArmy().equals(piece?.first?.name,true) ) movingPiece = PieceToCharMove(piece) } // Second click else { // Checks if the destination coordinates corresponds to the tile clicked for the correct piece if(charToIntMove(destinationY) == column && charToIntMove(destinationX) == row && rightPieceSelected) { // Makes the move passing the corresponding piece with its coordinates and the Army type board.doMove( (movingPiece?.plus(destinationY.toString()).plus(destinationX.toString())), playerArmy) // Go to the next solution play solutionIndex++ playerArmy++ // After the player move, the next play is simulated by the machine if (solutionIndex < solution.size) { playVerifier = 1 // Gets the initial position of the machine piece val rivalOriginY = solution.get(solutionIndex).get(0) val rivalOriginX = solution.get(solutionIndex).get(1) // Gets the destiny position of the machine piece val rivalDestY = solution.get(solutionIndex).get(2).toString() val rivalDestX = solution.get(solutionIndex).get(3).toString() // Makes the move passing the corresponding piece fetched on the tile with the initials position, the destiny's and the color board.doMove( (PieceToCharMove(board.getBoard()[charToIntMove(rivalOriginX)][charToIntMove(rivalOriginY)]) ?.plus(rivalOriginY.toString()).plus(rivalDestY).plus(rivalDestX)), playerArmy) solutionIndex++ playerArmy++ } else playVerifier = -1 } // The player clicked on the wrong destination, resetting the play else playVerifier = 0 movingPiece = null rightPieceSelected = false } } playIndex = playerArmy return board } /** * Function that sees if the game ended or if the king is in check */ fun isGameEndOrKingCheck(boardState: BoardState, playerArmy: Int, row: Int, column: Int) { // Defines which king is checked var pieceId : Pair<model.Army, model.Piece> if(playerArmy == 1) pieceId = Pair(model.Army.WHITE, model.Piece.KING) else pieceId = Pair(model.Army.BLACK, model.Piece.KING) var kingPositionX = 0 var kingPositionY = 0 var status = -1 var boardNumber = 0 // Go to every array<Pair<model.Army, model.Piece>> and check if the opponents KING exists boardState.getBoard().iterator().forEach { pairElements -> // Check if the king is on the current row if(pairElements.indexOf(pieceId) >= 0 && pairElements.indexOf(pieceId) <= 7) { // Row and column where the king is located kingPositionX = boardState.getBoard().indexOf(pairElements) kingPositionY = pairElements.indexOf(pieceId) status = 1 } boardNumber++ } // Verify if it the opponents KING is in check if(status == 1) { var initialBoard = boardStateToStringArray(boardState) var checkBoard = stringArrayToBoardState(initialBoard) // Creates an fictional board to not affect the real board var playerMove = movingPiece.plus(column).plus(row).plus(kingPositionY).plus(kingPositionX) checkBoard.doMoveLocal(playerMove, playerArmy) var resultBoard = boardStateToStringArray(checkBoard) // Checks if the KING was ate if(!initialBoard.contentEquals(resultBoard)) { status = 3 } } // Modify the current game status for the activity playVerifier = status } /** * Updates the board with a player move (ONLY USE LOCAL) */ fun updateModelLocalMultiplayer(board: BoardState, row: Int, column: Int, playerArmy : Int) : BoardState { // Resets the move status playVerifier = 0 var initialBoard = boardStateToStringArray(board) // Gets the piece and makes his own move var currentPiece = movingPiece.plus(originCordinateY).plus(originCordinateX).plus(column).plus(row) board.doMoveLocal(currentPiece, playerArmy) // Gets the board updated after the move var resultBoard = boardStateToStringArray(board) // Checks if the board had a successful move if(!initialBoard.contentEquals(resultBoard)) { // Changes to the next player and if this move was a check or end game playVerifier = 1 isGameEndOrKingCheck(board, playerArmy, row ,column) } // Sets a bad movement and "deselects" a piece selected for the next play else playVerifier = 2 movingPiece = null return board }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/common/CreateModel.kt
2695180640
package pt.isel.pdm.chess4android.common import android.os.Parcelable import kotlinx.parcelize.Parcelize import pt.isel.pdm.chess4android.common.model.Army import pt.isel.pdm.chess4android.common.model.Piece private fun createPieceEntry(army: Army, piece: Piece) = Pair(army, piece) private val whiteRook = createPieceEntry(Army.WHITE, Piece.ROOK) private val whiteBishop = createPieceEntry(Army.WHITE, Piece.BISHOP) private val whiteKnight = createPieceEntry(Army.WHITE, Piece.KNIGHT) private val whiteKing = createPieceEntry(Army.WHITE, Piece.KING) private val whiteQueen = createPieceEntry(Army.WHITE, Piece.QUEEN) private val whitePawn = createPieceEntry(Army.WHITE, Piece.PAWN) private val blackRook = createPieceEntry(Army.BLACK, Piece.ROOK) private val blackBishop = createPieceEntry(Army.BLACK, Piece.BISHOP) private val blackKnight = createPieceEntry(Army.BLACK, Piece.KNIGHT) private val blackKing = createPieceEntry(Army.BLACK, Piece.KING) private val blackQueen = createPieceEntry(Army.BLACK, Piece.QUEEN) private val blackPawn = createPieceEntry(Army.BLACK, Piece.PAWN) @Parcelize class BoardState() : Parcelable { /** * Initial board state */ private var board : Array<Array<Pair<Army,Piece>?>> = arrayOf( arrayOf(blackRook, blackKnight, blackBishop, blackQueen, blackKing, blackBishop, blackKnight, blackRook), arrayOf(blackPawn, blackPawn, blackPawn, blackPawn, blackPawn, blackPawn, blackPawn, blackPawn), arrayOfNulls(8), arrayOfNulls(8), arrayOfNulls(8), arrayOfNulls(8), arrayOf(whitePawn, whitePawn, whitePawn, whitePawn, whitePawn, whitePawn, whitePawn, whitePawn), arrayOf(whiteRook,whiteKnight, whiteBishop, whiteQueen, whiteKing, whiteBishop, whiteKnight, whiteRook) ) /** * Changes the board by the play made in API game mode */ fun doMove(move : String, idx : Int) { if(move[0].equals('N')) { if(idx % 2 == 0) { board = knightMove(board, move, whiteKnight) } else board = knightMove(board, move, blackKnight) } else if(move[0].equals('B')) { if(idx % 2 == 0) { board = bishopMove(board, move, whiteBishop) } else board = bishopMove(board, move, blackBishop) } else if(move[0].equals('R')) { if(idx % 2 == 0) { board = towerMove(board, move, whiteRook) } else board = towerMove(board, move, blackRook) } else if(move[0].equals('K')) { if(idx % 2 == 0) { board = RoyalityMove(board, move, whiteKing) } else board = RoyalityMove(board, move, blackKing) } else if(move[0].equals('Q')) { if(idx % 2 == 0) { board = RoyalityMove(board, move, whiteQueen) } else board = RoyalityMove(board, move, blackQueen) } else if(move[0].equals('O')) { if(idx % 2 == 0) { board = swapMove(board, move, whiteKing, whiteRook) } else board = swapMove(board, move, blackKing, blackRook) } else if(idx % 2 == 0) { board = pawnMove(board, move, whitePawn) } else board = pawnMove(board, move, blackPawn) } /** * Changes the board by the play made in LOCAL game mode */ fun doMoveLocal(move : String, idx : Int) { if(move[0].equals('N')) { if(idx % 2 == 0) { board = knightMoveLocal(board, move, whiteKnight) } else board = knightMoveLocal(board, move, blackKnight) } else if(move[0].equals('B')) { if(idx % 2 == 0) { board = bishopMoveLocal(board, move, whiteBishop) } else board = bishopMoveLocal(board, move, blackBishop) } else if(move[0].equals('R')) { if(idx % 2 == 0) { board = towerMoveLocal(board, move, whiteRook) } else board = towerMoveLocal(board, move, blackRook) } else if(move[0].equals('K')) { if(idx % 2 == 0) { board = kingMoveLocal(board, move, whiteKing) } else board = kingMoveLocal(board, move, blackKing) } else if(move[0].equals('Q')) { if(idx % 2 == 0) { board = queenMoveLocal(board, move, whiteQueen) } else board = queenMoveLocal(board, move, blackQueen) } else if(move[0].equals('O')) { if(idx % 2 == 0) { board = swapMoveLocal(board, move, whiteKing, whiteRook) } else board = swapMoveLocal(board, move, blackKing, blackRook) } else if(idx % 2 == 0) { board = whitePawnMoveLocal(board, move, whitePawn) } else board = blackPawnMoveLocal(board, move, blackPawn) } /** * Returns the board */ fun getBoard() : Array<Array<Pair<Army,Piece>?>> { return board } /** * Defines a board */ fun setBoard(pairArray: Array<Array<Pair<Army,Piece>?>>) : BoardState { board = pairArray return this } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/common/BoardState.kt
3471109749
package pt.isel.pdm.chess4android.common import kotlin.math.abs // Variable that checks if the King hasn't moved private var ROQUE_REQUIREMENT = true /** * Generates a random number that corresponds to a piece to switch a Pawn to another Piece */ private fun randPiece() : model.Piece { val piece = (0..39).random() return when(piece) { 0, 4, 16, 2, 37, 15, 13, 18, 1, 35 -> model.Piece.ROOK 3, 24, 26, 32, 19, 21, 14, 9, 33, 39 -> model.Piece.KNIGHT 36, 31, 20, 28, 25, 11, 10, 6, 34, 7 -> model.Piece.BISHOP else -> model.Piece.QUEEN } } /** * Makes the movements for the KNIGHT piece */ fun knightMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>>{ // Initial position of the piece var initialY = move.get(1).digitToInt() var initialX = move.get(2).digitToInt() // Final position for the piece var destinyY = move.get(3).digitToInt() var destinyX = move.get(4).digitToInt() // Checks if the sum of the modules between the final coordinates and initial coordinates corresponds to the horse move L = (3 squares) if( (abs(destinyX-initialX) + abs(destinyY-initialY)) == 3 ){ // Removes the piece from the previous position board[initialX][initialY] = null // Puts the piece in the new position board[destinyX][destinyY] = pieceId } return board; } /** * Makes the movements for the ROOK piece */ fun towerMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>>{ // Initial position of the piece var initialY = move.get(1).digitToInt() var initialX = move.get(2).digitToInt() // Final position for the piece var destinyY = move.get(3).digitToInt() var destinyX = move.get(4).digitToInt() // Flag that indicates if there is any piece that may interrupt the movement var validator = 0 // Coordinate used to move in the tile and interrupt movement if we are in the same tile were we began var position : Int // Checks if we are in the same row if(initialX == destinyX){ if(initialY < destinyY) { position = initialY + 1 // Avoid starting in initial position while(position < destinyY && validator == 0){ if(board[destinyX][position] != null) validator = 1 // Checks if there is any piece on the way position++ } } else { position = initialY - 1 while (position > destinyY && validator == 0) { if (board[destinyX][position] != null) validator = 1 position-- } } } // Checks if we are in the same column else if(initialY == destinyY){ if(initialX < destinyX){ position = initialX + 1 while(position < destinyX && validator == 0){ if(board[position][destinyY] != null) validator = 1 position++ } } else { position = initialX - 1 while (position > destinyX && validator == 0) { if (board[position][destinyY] != null) validator = 1 position-- } } } // If we aren't in the same row or column it's an invalid move else validator = 1 // If there isn't any piece on the way and it was a valid move, // remove the piece from the previous location and put it on the destiny if(validator == 0){ board[initialX][initialY] = null board[destinyX][destinyY] = pieceId } return board; } /** * Makes the movements for the QUEEN piece */ fun queenMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>> { // Initial position of the piece var initialY = move.get(1).digitToInt() var initialX = move.get(2).digitToInt() // Final position for the piece var destinyY = move.get(3).digitToInt() var destinyX = move.get(4).digitToInt() // Flag that indicates if there is any piece that may interrupt the movement var validator = 0 // Coordinate used to move in the tile and interrupt movement if we are in the same tile were we began var position : Int // Coordinate used to move in the tile and interrupt movement if we there is any other piece in the diagonal var positionX: Int var positionY: Int // Checks if we are in the same row if(initialX == destinyX){ if(initialY < destinyY) { position = initialY + 1 // Avoid starting in initial position while(position < destinyY && validator == 0){ if(board[destinyX][position] != null) validator = 1 // Checks if there is any piece on the way position++ } } else { position = initialY - 1 while (position > destinyY && validator == 0) { if (board[destinyX][position] != null) validator = 1 position-- } } } // Checks if we are in the same column else if(initialY == destinyY){ if(initialX < destinyX){ position = initialX + 1 while(position < destinyX && validator == 0){ if(board[position][destinyY] != null) validator = 1 position++ } } else { position = initialX - 1 while (position > destinyX && validator == 0) { if (board[position][destinyY] != null) validator = 1 position-- } } } // Checks if the modules between the final coordinates and initial coordinates are equal // ( Ex: 4 moves in diagonal = 4 moves in row + 4 moves in column ) else if( abs(destinyX-initialX) == abs(destinyY-initialY) ) { // Left side bottom movement if (destinyX < initialX && destinyY < initialY) { // Change coordinates to check if there is any piece on the diagonal positionX = initialX - 1 positionY = initialY - 1 while (positionX > destinyX && positionY > destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX-- positionY-- } } // Right side top movement else if (destinyX > initialX && destinyY > initialY) { positionX = initialX + 1 positionY = initialY + 1 while (positionX < destinyX && positionY < destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX++ positionY++ } } // Right side bottom movement else if (destinyX > initialX && destinyY < initialY) { positionX = initialX + 1 positionY = initialY - 1 while (positionX < destinyX && positionY > destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX++ positionY-- } } // Left side top movement else if (destinyX < initialX && destinyY > initialY) { positionX = initialX - 1 positionY = initialY + 1 while (positionX > destinyX && positionY < destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX-- positionY++ } } } // If the other movements failed it's an invalid move else validator = 1 // If there isn't any piece on the way and it was a valid move, // remove the piece from the previous location and put it on the destiny if(validator == 0){ board[initialX][initialY] = null board[destinyX][destinyY] = pieceId } return board; } /** * Makes the movements for the KING piece */ fun kingMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>> { // Initial position of the piece var initialY = move.get(1).digitToInt() var initialX = move.get(2).digitToInt() // Final position for the piece var destinyX = move.get(4).digitToInt() var destinyY = move.get(3).digitToInt() // Checks if we are in the same row or column if(initialX == destinyX || initialY == destinyY){ // Verify if there is one tile movement in the row or in the column direction if( (abs(destinyX-initialX) + abs(destinyY-initialY)) == 1 ){ ROQUE_REQUIREMENT = false // If the king moved from the initial position he can't make the ROQUE anymore board[initialX][initialY] = null board[destinyX][destinyY] = pieceId } } // Verify if is one tile movement in the diagonal // ( Ex: 1 diagonal = 1 row + 1 column ) else if( (abs(destinyX-initialX) + abs(destinyY-initialY)) == 2 ){ ROQUE_REQUIREMENT = false board[initialX][initialY] = null board[destinyX][destinyY] = pieceId } return board; } /** * Makes the movements for the BISHOP piece */ fun bishopMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>>{ // Initial position of the piece var initialY = move.get(1).digitToInt() var initialX = move.get(2).digitToInt() // Final position for the piece var destinyY = move.get(3).digitToInt() var destinyX = move.get(4).digitToInt() // Flag that indicates if there is any piece that may interrupt the movement var validator = 0 // Coordinate used to move in the tile and interrupt movement if we there is any other piece in the diagonal var positionX: Int var positionY: Int // Checks if the modules between the final coordinates and initial coordinates are equal // ( Ex: 4 moves in diagonal = 4 moves in row + 4 moves in column ) if( abs(destinyX-initialX) == abs(destinyY-initialY) ) { // Left side bottom movement if (destinyX < initialX && destinyY < initialY) { // Change coordinates to check if there is any piece on the diagonal positionX = initialX - 1 positionY = initialY - 1 while (positionX > destinyX && positionY > destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX-- positionY-- } } // Right side top movement else if (destinyX > initialX && destinyY > initialY) { positionX = initialX + 1 positionY = initialY + 1 while (positionX < destinyX && positionY < destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX++ positionY++ } } // Right side bottom movement else if (destinyX > initialX && destinyY < initialY) { positionX = initialX + 1 positionY = initialY - 1 while (positionX < destinyX && positionY > destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX++ positionY-- } } // Left side top movement else if (destinyX < initialX && destinyY > initialY) { positionX = initialX - 1 positionY = initialY + 1 while (positionX > destinyX && positionY < destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX-- positionY++ } } } // If the other movements failed it's an invalid move else validator = 1 // If there isn't any piece on the way and it was a valid move, // remove the piece from the previous location and put it on the destiny if(validator == 0){ board[initialX][initialY] = null board[destinyX][destinyY] = pieceId } return board; } /** * Makes the movements for the ROQUE */ fun swapMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId1: Pair<model.Army, model.Piece>, pieceId2: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>>{ // Initial position of the piece var initialY = move.get(1).digitToInt() var initialX = move.get(2).digitToInt() // Final position for the piece var destinyX = move.get(4).digitToInt() var destinyY = move.get(3).digitToInt() // Flag that indicates if there is any piece that may interrupt the movement var validator = 0 // Coordinate used to move in the tile and interrupt movement if we are in the same tile were we began var position : Int // Checks if we are in the first row/column or the last row/column, if its the king, // if the destiny row is the same and the initial and if the king hasn't moved. if( (initialX == 0 || initialX == 7) && (destinyY == 0 || destinyY == 7) && initialY == 4 && (initialX == destinyX) && ROQUE_REQUIREMENT) { // Left side movement if(destinyY < initialY) { position = initialY - 1 // Avoid starting in the initial position while (position > destinyY) { if (board[destinyX][position] != null) validator = 1 // Checks if there is any piece on the way position-- } // Makes the swap if(validator == 0) { board[destinyX][3] = pieceId2 board[destinyX][2] = pieceId1 board[destinyX][0] = null board[destinyX][4] = null } } // Right side movement else { position = initialY + 1 while (position < destinyX) { if (board[destinyX][position] != null) validator = 1 position++ } // Makes the swap if(validator == 0) { board[destinyX][5] = pieceId2 board[destinyX][6] = pieceId1 board[destinyX][7] = null board[destinyX][4] = null } } } return board; } /** * Makes the movements for the black PAWN */ fun blackPawnMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>> { // Initial position of the piece var initialY = move.get(0).digitToInt() var initialX = move.get(1).digitToInt() // Final position for the piece var destinyX = move.get(3).digitToInt() var destinyY = move.get(2).digitToInt() // Flag that indicates if there is any piece that may interrupt the movement var validator = 1 // Checks if the pawn movement is on the final row var piece = pieceId if(destinyX == 7) { piece = Pair(pieceId.first, randPiece()) // Swaps the pawn to a random piece } // Movement in the same column if( abs(initialY-destinyY) == 0 ) { // First move if(initialX == 1 && (destinyX - initialX == 1 || destinyX-initialX == 2) && board[destinyX][destinyY] == null) validator = 0 else if(destinyX-initialX == 1 && board[destinyX][destinyY] == null) validator = 0 } // Movement in the diagonal else if( abs(initialY-destinyY) == 1 ){ if(destinyX-initialX == 1 && board[destinyX][destinyY] != null) validator = 0 } if(validator == 0){ board[initialX][initialY] = null board[destinyX][destinyY] = piece } return board; } /** * Makes the movements for the white PAWN */ fun whitePawnMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>> { // Initial position of the piece var initialY = move.get(0).digitToInt() var initialX = move.get(1).digitToInt() // Final position for the piece var destinyX = move.get(3).digitToInt() var destinyY = move.get(2).digitToInt() // Flag that indicates if there is any piece that may interrupt the movement var validator = 1 // Checks if the pawn movement is on the final row var piece = pieceId if(destinyX == 0) { piece = Pair(pieceId.first, randPiece()) // Swaps the pawn to a random piece } // Movement in the same column if( abs(initialY-destinyY) == 0 ) { // First move if(initialX == 6 && (initialX - destinyX == 1 || initialX - destinyX== 2) && board[destinyX][destinyY] == null) validator = 0 else if(initialX-destinyX == 1 && board[destinyX][destinyY] == null) validator = 0 } // Movement in the diagonal else if(abs(initialY-destinyY) == 1){ if(initialX-destinyX == 1 && board[destinyX][destinyY] != null) validator = 0 } if(validator == 0){ board[initialX][initialY] = null board[destinyX][destinyY] = piece } return board; }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/common/ChessMovesLocal.kt
2017938377
package pt.isel.pdm.chess4android.resolution import android.app.Application import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.SavedStateHandle import pt.isel.pdm.chess4android.common.* import pt.isel.pdm.chess4android.daily.ServiceUnavailable private const val RESOLUTION_ACTIVITY_VIEW_STATE = "ResolutionActivity.ViewState" class ResolutionView(application : Application, private val state: SavedStateHandle) : AndroidViewModel(application) { init { Log.v("APP_TAG", "ResolutionView.init()") } private val _puzzleOfDay : MutableLiveData<BoardState> = MutableLiveData() val puzzleOfDay : LiveData<BoardState> = _puzzleOfDay /** * Asynchronous operation to fetch the quote of the day from the remote server. The operation * result (if successful) is published to the associated [LiveData] instance, [puzzleOfDay]. */ fun getPuzzleOfDay() { Log.v(APP_TAG, "Thread : ${Thread.currentThread().name}: Fetching ... ") val app = getApplication<PuzzleOfDayApplication>() val repo = PuzzleOfDayRepository(app.puzzleOfDayService, app.historyDB.getHistoryPuzzleDao()) repo.fetchPuzzleOfDay { result -> result .onSuccess { puzzleDTO -> _puzzleOfDay.value = createModel(puzzleDTO) state.set(RESOLUTION_ACTIVITY_VIEW_STATE, result.getOrThrow()) } .onFailure { ServiceUnavailable(cause = it) //result.exceptionOrNull() } } Log.v(APP_TAG, "Thread : ${Thread.currentThread().name}: Return from fetching puzzle") } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/resolution/ResolutionView.kt
2872823867
package pt.isel.pdm.chess4android.resolution import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import pt.isel.pdm.chess4android.R import pt.isel.pdm.chess4android.common.* import pt.isel.pdm.chess4android.databinding.ActivityResolutionBinding class ResolutionActivity : AppCompatActivity() { private val binding by lazy { ActivityResolutionBinding.inflate(layoutInflater) } // Se não existe intancia de ViewModel até este momento cria, caso contrário obtém a instancia private val viewModel : ResolutionView by viewModels() private fun displayError() { Toast.makeText(this, R.string.get_puzzle_error, Toast.LENGTH_SHORT).show() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) binding.restartButton.isVisible = false // Vai a API e cria um tabuleiro com o pgn viewModel.getPuzzleOfDay() // Fica a escuta de alterações na board viewModel.puzzleOfDay.observe(this) { boardResult -> Log.v("APP_TAG", "Board Alteration") binding.boardView.model = boardResult if ( getPlayingArmy().equals(model.Army.BLACK.name, true) ) { binding.chessResolution.text = resources.getText(R.string.chess_moveBlack_title) } else binding.chessResolution.text = resources.getText(R.string.chess_moveWhite_title) binding.boardView.tileClickedListener = { tile: Tile, row: Int, column: Int -> var piece : Pair<model.Army, model.Piece>? = tile.piece // Atualiza a board de acordo com o click do jogador binding.boardView.model = updateModel(boardResult, row, column, piece) var status = getPlayVerifier() // Apartir do destino escolhido a peça faz uma seleção if(getPiece() == null) { if(status == 0) { Toast.makeText(applicationContext, "Bad Play", Toast.LENGTH_SHORT).show() } else if(status == 1) { Toast.makeText(applicationContext, "Nice Play", Toast.LENGTH_SHORT).show() } } // Termino do puzzle if(status == -1) { binding.chessResolution.text = resources.getText(R.string.chess_sucess_title) binding.restartButton.isVisible = true binding.restartButton.setOnClickListener { recreate() } } } } } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/resolution/ResolutionActivity.kt
3480268875
package pt.isel.pdm.chess4android.localGame import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import pt.isel.pdm.chess4android.R import pt.isel.pdm.chess4android.common.* import pt.isel.pdm.chess4android.databinding.ActivityLocalGameBinding class LocalGameActivity : AppCompatActivity() { private val binding by lazy { ActivityLocalGameBinding.inflate(layoutInflater) } /** * In the end of the turn swap the player */ private fun switchPlayerTurn(playerTurn : String) : String { if(playerTurn == "WHITE") return "BLACK" return "WHITE" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) // The game starts with the white playing binding.chessResolution.text = resources.getText(R.string.white_piece_turn) // Initialize variables var boardResult = BoardState() var playerTurn = "WHITE" var playerFlag : Int // Shows the initial board binding.boardView.model = boardResult // Button that sees if a player gave up and ends the game binding.forfeitButton.setOnClickListener { if(playerTurn == "WHITE") binding.chessResolution.text = resources.getText(R.string.white_surrender).toString() + "\n" + resources.getText(R.string.black_chess_winner).toString() else binding.chessResolution.text = resources.getText(R.string.black_surrender).toString() + "\n" + resources.getText(R.string.white_chess_winner).toString() // Disable clicks on the tile binding.boardView.tileClickedListener = null } // Game Validations binding.boardView.tileClickedListener = { tile: Tile, row: Int, column: Int -> // Gets the piece that was clicked var piece : Pair<model.Army, model.Piece>? = tile.piece if (playerTurn == "WHITE") playerFlag = 0 else playerFlag = 1 // Checks if it is the first click and updates the piece in evidence if(piece?.first?.name == playerTurn && getPiece() == null) { selectPiece(piece, row, column) } // Checks if it is the second click and avoids eating the own pieces then updates the board else if (piece?.first?.name != playerTurn && getPiece() != null ) { binding.boardView.model = updateModelLocalMultiplayer(boardResult, row, column, playerFlag) } // Checks if it is a ROQUE move (selected piece = KING and destiny tile has a ROOK with the same color) then updates the board else if(getPiece() == "K" && piece?.second == model.Piece.ROOK && piece.first.name == playerTurn) { roque("O") binding.boardView.model = updateModelLocalMultiplayer(boardResult, row, column, playerFlag) } // Checks if the player selected a wrong space (when try to eat the own piece) else { Toast.makeText(applicationContext, "Cannot make that movement", Toast.LENGTH_SHORT).show() selectPiece(null, 0, 0) } // Get the status of the play var status = getPlayVerifier() // Switch to another Player if (status == 1) { playerTurn = switchPlayerTurn(playerTurn) if (playerTurn == "WHITE") binding.chessResolution.text = resources.getText(R.string.white_piece_turn) else binding.chessResolution.text = resources.getText(R.string.black_piece_turn) } // Invalid move else if (status==2) Toast.makeText(applicationContext, "Cannot make that movement", Toast.LENGTH_SHORT).show() // Sees if the KING is in CHECK else if (status == 3) { playerTurn = switchPlayerTurn(playerTurn) if(playerTurn == "WHITE") binding.chessResolution.text = resources.getText(R.string.white_king_checked) else binding.chessResolution.text = resources.getText(R.string.black_king_checked) } // End Game else if (status == -1) { binding.forfeitButton.isVisible = false binding.boardView.tileClickedListener = null if (playerTurn == "WHITE") binding.chessResolution.text = resources.getText(R.string.white_chess_winner) else binding.chessResolution.text = resources.getText(R.string.black_chess_winner) } } } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/localGame/LocalGameActivity.kt
817736618
package pt.isel.pdm.chess4android.model /** * Enumeration type used to represent the game's players. */ enum class Player { WHITE, BLACK; companion object { val firstToMove: Player = WHITE } /** * The other player */ val other: Player get() = if (this == WHITE) BLACK else WHITE } fun stringToPlayer(turn : String?) : Player? { if(turn == "WHITE") return Player.WHITE else if(turn == "BLACK") return Player.BLACK return null }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/model/Player.kt
1650501946
package pt.isel.pdm.chess4android.model /** * The Game's board side */ const val BOARD_SIDE = 8 /** * Checks whether [value] is a valid row index */ fun isValidRow(value: Int) = value in 0 until BOARD_SIDE /** * Represents a row index in a CHESS board. * * @param value the row index. Must be in the interval 0 <= value < [BOARD_SIDE] */ data class Row(val value: Int) { init { require(isValidRow(value)) } } /** * Int extensions for expressing row indexes. */ fun Int.toRow(): Row = Row(this) val Int.Row: Row get() = toRow() /** * Checks whether [value] is a valid column index */ fun isValidColumn(value: Int) = value in 0 until BOARD_SIDE /** * Represents a column index in a CHESS board. * @param value the row number. Must be in the interval 0 <= value < [BOARD_SIDE] */ data class Column(val value: Int) { init { require(isValidColumn(value)) } } /** * Int extensions for expressing column indexes */ fun Int.toColumn(): Column = Column(this) val Int.Column: Column get() = toColumn() /** * Represents coordinates in the CHESS board */ data class Coordinate(val row: Row, val column: Column) /** * Checks whether [value] is an index that may express a valid board coordinate */ fun isInCoordinateRange(value: Int) = value < BOARD_SIDE * BOARD_SIDE /** * Extension function that converts this coordinate to a one dimensional index */ fun Coordinate.toIndex() = row.value * BOARD_SIDE + column.value /** * Int extensions for expressing board coordinates */ fun Int.toCoordinate(): Coordinate = Coordinate((this / BOARD_SIDE).Row, (this % BOARD_SIDE).Column) fun Int.toCoordinateOrNull(): Coordinate? = if (isInCoordinateRange(this)) toCoordinate() else null val Int.Coordinate: Coordinate get() = toCoordinate()
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/model/coordinates.kt
1553781164
package pt.isel.pdm.chess4android.model import pt.isel.pdm.chess4android.common.BoardState /** * Represents a Tic-Tac-Toe board. Instances are immutable. * * @property side The number of tiles per board side * @property turn The next player to move, or null if the game has already ended * @property board The board tiles */ data class Board( val turn: Player? = Player.firstToMove, private val board: BoardState = BoardState() ) /*{ /** * Overloads the indexing operator */ operator fun get(at: Coordinate): Player? = getMove(at) /** * Gets the move at the given coordinates. * * @param at the move's coordinates * @return the [Player] instance that made the move, or null if the position is empty */ fun getMove(at: Coordinate, dest: Coordinate): Player? = board[at.toIndex()] /** * Makes a move at the given coordinates and returns the new board instance. * * @param at the board's coordinate * @throws IllegalArgumentException if the position is already occupied * @throws IllegalStateException if the game has already ended * @return the new board instance */ fun makeMove(at: Coordinate): Board { require(this[at] == null) checkNotNull(turn) return Board( turn = turn.other, board = board.mapIndexed { index, elem -> if (index == at.toIndex()) turn else elem } ) } /** * Converts this instance to a list of moves. */ fun toList(): List<Player?> = board } /** * Extension function that overloads the indexing operator for [Board] instances */ operator fun Board.get(row: Row, column: Column): Player? = getMove(Coordinate(row, column)) /** * Extension function that checks whether this board's position [at] is free or not * * @param at the board's coordinate * @return true if the board position is free, false otherwise */ fun Board.isFree(at: Coordinate): Boolean = this[at] == null /** * Extension function that checks whether this board's position [at] is free or not * * @param at the board's coordinate * @return true if the board position is occupied, false otherwise */ fun Board.isNotFree(at: Coordinate): Boolean = !isFree(at) /** * Extension function that checks whether this board represents a tied game or not * * @return true if the board is a tied game, false otherwise */ fun Board.isTied(): Boolean = toList().all { it != null } */
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/model/Board.kt
1911369863
package pt.isel.pdm.chess4android.history import androidx.room.* import pt.isel.pdm.chess4android.common.BoardState import pt.isel.pdm.chess4android.converters.BoardStateConverter import pt.isel.pdm.chess4android.converters.GameConverter import pt.isel.pdm.chess4android.converters.PuzzleConverter import pt.isel.pdm.chess4android.converters.TimeConverter import pt.isel.pdm.chess4android.daily.Game import pt.isel.pdm.chess4android.daily.Puzzle import java.time.Instant import java.time.temporal.ChronoUnit import java.util.* @Entity(tableName = "history_puzzle") data class PuzzleEntity( @PrimaryKey val id: String, @TypeConverters(GameConverter::class) var game: Game, @TypeConverters(PuzzleConverter::class) val puzzle: Puzzle, @ColumnInfo(name = "status") val status: Boolean = false, @TypeConverters(BoardStateConverter::class) val resolvedBoard: BoardState = BoardState(), @TypeConverters(TimeConverter::class) val timestamp: Date = Date.from(Instant.now().truncatedTo(ChronoUnit.DAYS)), ) { fun isTodayPuzzle() : Boolean = timestamp.toInstant().compareTo(Instant.now().truncatedTo(ChronoUnit.DAYS)) == 0 } /** * The abstraction containing the supported data access operations. The actual implementation is * provided by the Room compiler. We can have as many DAOs has our design mandates. */ @Dao interface HistoryPuzzleDao { @Insert fun insert(puzzle: PuzzleEntity) @Delete fun delete(puzzle: PuzzleEntity) @Update fun update(puzzle: PuzzleEntity) @Query("SELECT * FROM history_puzzle ORDER BY id DESC LIMIT 100") fun getAll(): List<PuzzleEntity> @Query("SELECT * FROM history_puzzle ORDER BY id DESC LIMIT :count") fun getLast(count: Int): List<PuzzleEntity> } /** * The abstraction that represents the DB itself. It is also used as a DAO factory: one factory * method per DAO. */ @Database(entities = [PuzzleEntity::class], version = 1) @TypeConverters(GameConverter::class, PuzzleConverter::class, TimeConverter::class, BoardStateConverter::class) abstract class HistoryDataBase : RoomDatabase() { abstract fun getHistoryPuzzleDao(): HistoryPuzzleDao }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/history/HistoryDataAcess.kt
3182539875
package pt.isel.pdm.chess4android.history import android.animation.ValueAnimator import android.graphics.drawable.GradientDrawable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.core.animation.doOnEnd import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import pt.isel.pdm.chess4android.daily.DayPuzzleDTO import pt.isel.pdm.chess4android.R import java.text.SimpleDateFormat import java.util.* /** * Implementation of the ViewHolder pattern. Its purpose is to eliminate the need for * executing findViewById each time a reference to a view's child is required. */ class HistoryItemViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView) { private val dayView = itemView.findViewById<TextView>(R.id.day) private val puzzleIdView = itemView.findViewById<TextView>(R.id.puzzleId) private val resolvedView = itemView.findViewById<TextView>(R.id.isResolved) /** * Binds this view holder to the given puzzle item */ fun bindTo(dayPuzzleDTO: DayPuzzleDTO, onItemClick: () -> Unit) { dayView.text = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(dayPuzzleDTO.timestamp).toString() puzzleIdView.text = dayPuzzleDTO.puzzle.id if(!dayPuzzleDTO.status) resolvedView.text = "Unresolved" else resolvedView.text = "Resolved" itemView.setOnClickListener { // Avoid double click itemView.isClickable = false startAnimation { onItemClick() itemView.isClickable = true } } } /** * Starts the item selection animation and calls [onAnimationEnd] once the animation ends */ private fun startAnimation(onAnimationEnd: () -> Unit) { val animation = ValueAnimator.ofArgb( ContextCompat.getColor(itemView.context, R.color.list_item_background), ContextCompat.getColor(itemView.context, R.color.list_item_background_selected), ContextCompat.getColor(itemView.context, R.color.list_item_background) ) animation.addUpdateListener { animator -> val background = itemView.background as GradientDrawable background.setColor(animator.animatedValue as Int) } animation.duration = 400 animation.doOnEnd { onAnimationEnd() } animation.start() } } /** * Adapts items in a data set to RecycleView entries */ class HistoryAdapter( private val dataSource : List<DayPuzzleDTO>, private val onItemClick: (DayPuzzleDTO) -> Unit ) : RecyclerView.Adapter<HistoryItemViewHolder>() { /** * Factory method of view holders (and its associated views) */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HistoryItemViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_history_list, parent, false) return HistoryItemViewHolder(view) } /** * Associates a view into a new data element */ override fun onBindViewHolder(holder: HistoryItemViewHolder, position: Int) { holder.bindTo(dataSource[position]) { onItemClick(dataSource[position]) } } /** * The size of the data set */ override fun getItemCount() = dataSource.size }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/history/HistoryAdapter.kt
1102159703
package pt.isel.pdm.chess4android.history import android.app.Application import android.util.Log import androidx.lifecycle.AndroidViewModel import pt.isel.pdm.chess4android.common.PuzzleOfDayApplication import pt.isel.pdm.chess4android.common.PuzzleOfDayRepository import pt.isel.pdm.chess4android.daily.DayPuzzleDTO import pt.isel.pdm.chess4android.daily.ServiceUnavailable class PuzzleActivityViewModel(application : Application) : AndroidViewModel(application) { init { Log.v("APP_TAG", "PuzzleActivityViewModel.init()") } fun updatePuzzle(puzzledto : DayPuzzleDTO) { val app = getApplication<PuzzleOfDayApplication>() val repo = PuzzleOfDayRepository(app.puzzleOfDayService, app.historyDB.getHistoryPuzzleDao()) repo.asyncUpdateDB(puzzledto) { result -> result .onSuccess { puzzleDTO -> Result.success(puzzleDTO) } .onFailure { ServiceUnavailable(cause = it) } } } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/history/PuzzleActivityViewModel.kt
1694475650
package pt.isel.pdm.chess4android.history import android.os.Bundle import android.os.Handler import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import pt.isel.pdm.chess4android.databinding.ActivityHistoryBinding import pt.isel.pdm.chess4android.history.PuzzleActivity.Companion.buildIntent /** * Shows if we are alredy in a Activity. */ var flagActivity : Boolean = false; /** * The screen used to display the list of daily puzzles stored locally. */ class HistoryActivity : AppCompatActivity() { private val binding by lazy { ActivityHistoryBinding.inflate(layoutInflater) } private val viewModel by viewModels<HistoryActivityViewModel>() /** * Sets up the screen look and behaviour */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) binding.puzzleList.layoutManager = LinearLayoutManager(this) // Get the list of puzzles, if we haven't fetched it yet val dataSource = viewModel.history if(dataSource == null) { viewModel.loadHistory().observe(this) { flagActivity = true binding.puzzleList.adapter = HistoryAdapter(it) { puzzleDto -> startActivity(buildIntent(this, puzzleDto)) } } } else { dataSource.observe(this) { flagActivity = true binding.puzzleList.adapter = HistoryAdapter(it) { puzzleDto -> startActivity(buildIntent(this, puzzleDto)) } } } } override fun onStart() { super.onStart() if(flagActivity) { viewModel.loadHistory().observe(this) { binding.puzzleList.adapter = HistoryAdapter(it) { puzzleDto -> startActivity(buildIntent(this, puzzleDto)) } } } } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/history/HistoryActivity.kt
822796653
package pt.isel.pdm.chess4android.history import android.app.Activity import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import pt.isel.pdm.chess4android.R import pt.isel.pdm.chess4android.common.* import pt.isel.pdm.chess4android.daily.DayPuzzleDTO import pt.isel.pdm.chess4android.databinding.ActivityPuzzleBinding private const val PUZZLE_EXTRA = "PuzzleActivityLegacy.Extra.Puzzle" private const val BOARD_EXTRA = "PuzzleActivityLegacy.Extra.Board" /** * The screen used to display the a Puzzle. */ class PuzzleActivity : AppCompatActivity() { private val binding by lazy { ActivityPuzzleBinding.inflate(layoutInflater) } private val viewModel : PuzzleActivityViewModel by viewModels() companion object { fun buildIntent(origin: Activity, puzzleDto: DayPuzzleDTO): Intent { var msg = Intent(origin, PuzzleActivity::class.java) var boardState = boardStateToStringArray(puzzleDto.resolvedBoard) msg.putExtra(PUZZLE_EXTRA, puzzleDto) msg.putExtra(BOARD_EXTRA, boardState) return msg } } /** * Sets up the screen look and behaviour */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) binding.restartButton.isVisible = false; /* Gets the information from another activity */ val puzzleDTO = intent.getParcelableExtra<DayPuzzleDTO>(PUZZLE_EXTRA) val boardDTO = intent.getStringArrayExtra(BOARD_EXTRA) /* Transformes the string with the boardInfo from Intent to a boardState */ if(boardDTO != null) puzzleDTO?.resolvedBoard = stringArrayToBoardState(boardDTO) var boardResult = BoardState() if (puzzleDTO != null) { if(!puzzleDTO.status) binding.resolvedPuzzle.isVisible = false binding.restartButton.setOnClickListener { recreate() } /* Update view parameters by seeing the board result */ binding.resolvedPuzzle.setOnClickListener{ binding.boardView.model = puzzleDTO.resolvedBoard binding.chessResolution.text = resources.getText(R.string.resolution_title) binding.boardView.tileClickedListener = null binding.restartButton.isVisible = true } boardResult = createModel(puzzleDTO) binding.boardView.model = boardResult } // Game Validations if ( getPlayingArmy().equals(model.Army.BLACK.name, true) ) { binding.chessResolution.text = resources.getText(R.string.chess_moveBlack_title) } else binding.chessResolution.text = resources.getText(R.string.chess_moveWhite_title) binding.boardView.tileClickedListener = { tile: Tile, row: Int, column: Int -> var piece : Pair<model.Army, model.Piece>? = tile.piece // Updates the board with the player moves binding.boardView.model = updateModel(boardResult, row, column, piece) var status = getPlayVerifier() // Verify if the destination to the piece is the right one if(getPiece() == null) { if(status == 0) { Toast.makeText(applicationContext, "Bad Play", Toast.LENGTH_SHORT).show() } else if(status == 1) { Toast.makeText(applicationContext, "Nice Play", Toast.LENGTH_SHORT).show() } } // Puzzle End if(status == -1) { binding.chessResolution.text = resources.getText(R.string.chess_sucess_title) binding.restartButton.isVisible = true binding.resolvedPuzzle.isVisible = true binding.boardView.tileClickedListener = null // Updates the DB if (puzzleDTO != null && !puzzleDTO.status) { puzzleDTO.resolvedBoard = boardResult puzzleDTO.status = true viewModel.updatePuzzle(puzzleDTO) } } } } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/history/PuzzleActivity.kt
422876016
package pt.isel.pdm.chess4android.history import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import pt.isel.pdm.chess4android.common.PuzzleOfDayApplication import pt.isel.pdm.chess4android.common.callbackAfterAsync import pt.isel.pdm.chess4android.daily.DayPuzzleDTO /** * The actual execution host behind the quote history screen (i.e. the [HistoryActivity]). */ class HistoryActivityViewModel(application: Application) : AndroidViewModel(application) { /** * Holds a [LiveData] with the list of puzzles, or null if it has not yet been requested by * the [HistoryActivity] through a call to [loadHistory] */ var history: LiveData<List<DayPuzzleDTO>>? = null private set private val historyDAO : HistoryPuzzleDao by lazy { getApplication<PuzzleOfDayApplication>().historyDB.getHistoryPuzzleDao() } /** * Gets the puzzles list (history) from the DB. */ fun loadHistory(): LiveData<List<DayPuzzleDTO>> { val publish = MutableLiveData<List<DayPuzzleDTO>>() history = publish callbackAfterAsync( asyncAction = { // Gets a PuzzleEntity from the database and transformes into a PuzzleDTO historyDAO.getAll().map { DayPuzzleDTO(game = it.game, puzzle = it.puzzle, timestamp = it.timestamp, status = it.status, resolvedBoard = it.resolvedBoard) } }, callback = { result -> result.onSuccess { publish.value = it } result.onFailure { publish.value = emptyList() } } ) return publish } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/history/HistoryActivityViewModel.kt
4259448324
package pt.isel.pdm.chess4android import android.app.Application import com.google.gson.Gson import pt.isel.pdm.chess4android.challenges.ChallengesRepository import pt.isel.pdm.chess4android.game.GamesRepository /** * Tag to be used in all the application's log messages */ const val TAG = "Chess" /** * Contains the globally accessible objects */ class ChessApplication : Application() { private val mapper: Gson by lazy { Gson() } /** * The challenges' repository */ val challengesRepository: ChallengesRepository by lazy { ChallengesRepository() } /** * The chess repository */ val gamesRepository: GamesRepository by lazy { GamesRepository(mapper) } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/ChessApplication.kt
3327717541
package pt.isel.pdm.chess4android.credits import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.widget.ImageView import pt.isel.pdm.chess4android.common.LoggingActivity import pt.isel.pdm.chess4android.R private const val GitHubURL = "https://github.com/gustavodev1998/PDM-2122i-LI5X-G30" private const val LichessURL = "https://lichess.org/" private const val GitHubGustavoURL = "https://github.com/gustavodev1998" private const val LinkedInGustavoURL = "https://www.linkedin.com/in/gustavo-campos-8918711b4/" private const val GitHubTiagoURL = "https://github.com/TiagoCebola" private const val LinkedInTiagoURL = "https://www.linkedin.com/in/tiago-cebola-85610922a/" private const val GitHubRubenURL = "https://github.com/RubenSou" private const val LinkedInRubenURL = "https://www.linkedin.com/in/ruben-sousa-103729223" class CreditActivity : LoggingActivity() { init { Log.v("APP_TAG", "CREDITS") } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_credit) findViewById<ImageView>(R.id.lichess_logo).setOnClickListener { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(LichessURL)).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK } startActivity(intent) } /* GITHUB & LINKED ICONS REDIRECT TO OUR OWN SOCIAL MEDIA */ /* Social Gustavo */ findViewById<ImageView>(R.id.github_icon_Gustavo).setOnClickListener { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(GitHubGustavoURL)).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK } startActivity(intent) } findViewById<ImageView>(R.id.linkedin_icon_Gustavo).setOnClickListener { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(LinkedInGustavoURL)).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK } startActivity(intent) } /* Social Tiago */ findViewById<ImageView>(R.id.github_icon_Tiago).setOnClickListener { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(GitHubTiagoURL)).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK } startActivity(intent) } findViewById<ImageView>(R.id.linkedin_icon_Tiago).setOnClickListener { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(LinkedInTiagoURL)).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK } startActivity(intent) } /* Social Ruben */ findViewById<ImageView>(R.id.github_icon_Ruben).setOnClickListener { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(GitHubRubenURL)).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK } startActivity(intent) } findViewById<ImageView>(R.id.linkedin_icon_Ruben).setOnClickListener { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(LinkedInRubenURL)).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK } startActivity(intent) } } }
ISEL-Chess4Android/Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/credits/CreditActivity.kt
613966475
package com.example.tanks import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.tanks", appContext.packageName) } }
world-of-tanks/app/src/androidTest/java/com/example/tanks/ExampleInstrumentedTest.kt
126337910
package com.example.tanks import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
world-of-tanks/app/src/test/java/com/example/tanks/ExampleUnitTest.kt
2997723747
package com.example.tanks.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
world-of-tanks/app/src/main/java/com/example/tanks/ui/theme/Color.kt
3293682018
package com.example.tanks.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun TanksTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
world-of-tanks/app/src/main/java/com/example/tanks/ui/theme/Theme.kt
1353863145
package com.example.tanks.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
world-of-tanks/app/src/main/java/com/example/tanks/ui/theme/Type.kt
3607094651
package com.example.tanks import android.graphics.Path.Direction import android.os.Bundle import android.view.KeyEvent import android.view.KeyEvent.KEYCODE_DPAD_DOWN import android.view.KeyEvent.KEYCODE_DPAD_LEFT import android.view.KeyEvent.KEYCODE_DPAD_RIGHT import android.view.KeyEvent.KEYCODE_DPAD_UP import android.widget.FrameLayout import android.widget.ImageView import android.widget.LinearLayout import com.example.tanks.MyDirection.UP import com.example.tanks.MyDirection.DOWN import com.example.tanks.MyDirection.LEFT import com.example.tanks.MyDirection.RIGHT import androidx.activity.ComponentActivity import com.example.tanks.databinding.ActivityMainBinding class MainActivity : ComponentActivity() { private lateinit var binding:ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) } override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { when(keyCode) { KEYCODE_DPAD_UP -> move(UP) KEYCODE_DPAD_DOWN -> move(DOWN) KEYCODE_DPAD_LEFT -> move(LEFT) KEYCODE_DPAD_RIGHT -> move(RIGHT) } return super.onKeyDown(keyCode, event) } private fun move(direction: MyDirection){ val layoutParams = binding.MyTank.layoutParams as LinearLayout.LayoutParams when(direction) { UP -> { binding.MyTank.rotation = 0f if(layoutParams.topMargin > 0) { layoutParams.topMargin += -50 } } DOWN -> { binding.MyTank.rotation = 180f if(layoutParams.topMargin + binding.MyTank.height < (50 * 41)) { (binding.MyTank.layoutParams as LinearLayout.LayoutParams).topMargin += 50 } } LEFT -> { binding.MyTank.rotation = 270f if(layoutParams.leftMargin > 0){ layoutParams.leftMargin -= 50 } } RIGHT -> { binding.MyTank.rotation = 90f if(layoutParams.leftMargin + binding.MyTank.width < (50 * 21)) { layoutParams.leftMargin += 50 } } } binding.actionContainer.removeView(binding.MyTank) binding.actionContainer.addView(binding.MyTank) } }
world-of-tanks/app/src/main/java/com/example/tanks/MainActivity.kt
1704161058
package com.example.tanks enum class MyDirection { UP, DOWN, RIGHT, LEFT, }
world-of-tanks/app/src/main/java/com/example/tanks/MyDirection.kt
352812862
package com.example.mapd721_a1_nibhamaharjan import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.mapd721_a1_nibhamaharjan", appContext.packageName) } }
MAPD721-A1-NibhaMaharjan/app/src/androidTest/java/com/example/mapd721_a1_nibhamaharjan/ExampleInstrumentedTest.kt
12945980
package com.example.mapd721_a1_nibhamaharjan import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
MAPD721-A1-NibhaMaharjan/app/src/test/java/com/example/mapd721_a1_nibhamaharjan/ExampleUnitTest.kt
520450123
package com.example.mapd721_a1_nibhamaharjan.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
MAPD721-A1-NibhaMaharjan/app/src/main/java/com/example/mapd721_a1_nibhamaharjan/ui/theme/Color.kt
1129897545
package com.example.mapd721_a1_nibhamaharjan.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun MAPD721A1NibhaMaharjanTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
MAPD721-A1-NibhaMaharjan/app/src/main/java/com/example/mapd721_a1_nibhamaharjan/ui/theme/Theme.kt
2192310727
package com.example.mapd721_a1_nibhamaharjan.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
MAPD721-A1-NibhaMaharjan/app/src/main/java/com/example/mapd721_a1_nibhamaharjan/ui/theme/Type.kt
364192051
// Nibha Maharjan // StudentID: 301282952 // Datastore Assignment package com.example.mapd721_a1_nibhamaharjan import android.content.Context import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.* 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.text.input.PasswordVisualTransformation import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.mapd721_a1_nibhamaharjan.datastore.StoreUserEmail import com.example.mapd721_a1_nibhamaharjan.ui.theme.MAPD721A1NibhaMaharjanTheme import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MAPD721A1NibhaMaharjanTheme { // A surface container Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { MainScreen(this) // Pass the activity context } } } } } @Composable fun MainScreen(activity: ComponentActivity) { // context val context = activity.applicationContext // scope val scope = rememberCoroutineScope() // datastore Email val dataStore = StoreUserEmail(context) // get saved name email and id var nameState by remember { mutableStateOf("Nibha Maharjan") } var emailState by remember { mutableStateOf("[email protected]") } var idState by remember { mutableStateOf("301282952") } // Load saved data on composition start DisposableEffect(Unit) { scope.launch { nameState = dataStore.getName.first() ?: nameState emailState = dataStore.getEmail.first() ?: emailState idState = dataStore.getId.first() ?: idState } onDispose { } } Column(modifier = Modifier.fillMaxSize()) { // Input fields for saving and loading data Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) .background(MaterialTheme.colorScheme.background) ) { Text( modifier = Modifier .padding(16.dp, top = 30.dp), text = "Email", color = Color.Gray, fontSize = 12.sp ) // email field OutlinedTextField( modifier = Modifier .padding(start = 16.dp, end = 16.dp) .fillMaxWidth(), value = emailState, onValueChange = { emailState = it }, ) OutlinedTextField( modifier = Modifier .padding(start = 16.dp, end = 16.dp) .fillMaxWidth(), value = nameState, onValueChange = { nameState = it }, label = { Text(text = "Name", color = Color.Gray, fontSize = 12.sp) }, ) OutlinedTextField( modifier = Modifier .padding(start = 16.dp, end = 16.dp) .fillMaxWidth(), value = idState, onValueChange = { idState = it }, label = { Text(text = "ID", color = Color.Gray, fontSize = 12.sp) }, ) Spacer(modifier = Modifier.height(20.dp)) // Save, Load, Clear buttons Row( modifier = Modifier .fillMaxWidth() ) { // Save button Button( modifier = Modifier .weight(1f) .height(60.dp) .padding(end = 8.dp), onClick = { // launch the class in a coroutine scope scope.launch { dataStore.saveEmail(nameState, emailState, idState) showToast(context, "Data saved") // Clear input fields after saving emailState = "" nameState = "" idState = "" } }, colors = ButtonDefaults.buttonColors( contentColor = Color.White, containerColor = Color.Blue ) ) { // button text Text( text = "Save", fontSize = 18.sp ) } // Load button Button( modifier = Modifier .weight(1f) .height(60.dp) .padding(horizontal = 8.dp), onClick = { // launch the class in a coroutine scope scope.launch { // Load data and update the fields nameState = dataStore.getName.first() ?: "" emailState = dataStore.getEmail.first() ?: "" idState = dataStore.getId.first() ?: "" showToast(context, "Data loaded: Name=$nameState, Email=$emailState, ID=$idState") } }, colors = ButtonDefaults.buttonColors( contentColor = Color.White, containerColor = Color.Cyan ) ) { // button text Text( text = "Load", fontSize = 18.sp ) } // Clear button Button( modifier = Modifier .weight(1f) .height(60.dp) .padding(start = 8.dp), onClick = { // launch the class in a coroutine scope scope.launch { // Clear data dataStore.saveEmail("", "", "") // Clear input fields emailState = "" nameState = "" idState = "" showToast(context, "Data cleared") } }, colors = ButtonDefaults.buttonColors( contentColor = Color.White, containerColor = Color.LightGray ) ) { // button text Text( text = "Clear", fontSize = 18.sp ) } } Spacer(modifier = Modifier.height(300.dp)) } // Display saved data Box( modifier = Modifier .fillMaxWidth() .background(Color.White) .padding(16.dp), contentAlignment = Alignment.TopStart ) { Text( text = "Name: Nibha Maharjan\nEmail: [email protected]\nID: 301282952", color = Color.Black, fontSize = 18.sp ) } } } fun showToast(context: Context, message: String) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() } @Preview(showBackground = true) @Composable fun DefaultPreview() { MAPD721A1NibhaMaharjanTheme { MainScreen(ComponentActivity()) } }
MAPD721-A1-NibhaMaharjan/app/src/main/java/com/example/mapd721_a1_nibhamaharjan/MainActivity.kt
3306249710
// StoreUserEmail.kt package com.example.mapd721_a1_nibhamaharjan.datastore import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map class StoreUserEmail(private val context: Context) { companion object { private val Context.dataStore: DataStore<Preferences> by preferencesDataStore("UserEmail") val USER_NAME_KEY = stringPreferencesKey("user_name") val USER_EMAIL_KEY = stringPreferencesKey("user_email") val USER_ID_KEY = stringPreferencesKey("user_id") } val getName: Flow<String?> = context.dataStore.data .map { preferences -> preferences[USER_NAME_KEY] } val getEmail: Flow<String?> = context.dataStore.data .map { preferences -> preferences[USER_EMAIL_KEY] } val getId: Flow<String?> = context.dataStore.data .map { preferences -> preferences[USER_ID_KEY] } suspend fun saveEmail(name: String, email: String, id: String) { context.dataStore.edit { preferences -> preferences[USER_NAME_KEY] = name preferences[USER_EMAIL_KEY] = email preferences[USER_ID_KEY] = id } } suspend fun clearData() { context.dataStore.edit { preferences -> preferences.remove(USER_NAME_KEY) preferences.remove(USER_EMAIL_KEY) preferences.remove(USER_ID_KEY) } } }
MAPD721-A1-NibhaMaharjan/app/src/main/java/com/example/mapd721_a1_nibhamaharjan/datastore/StoreUserEmail.kt
2274061742
package com.example.socialmediaapp import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.socialmediaapp", appContext.packageName) } }
social-media-project/app/src/androidTest/java/com/example/socialmediaapp/ExampleInstrumentedTest.kt
3893377650
package com.example.socialmediaapp import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
social-media-project/app/src/test/kotlin/com/example/socialmediaapp/ExampleUnitTest.kt
3463657089
package com.example.socialmediaapp.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
social-media-project/app/src/main/Kotlin/com/example/socialmediaapp/ui/theme/Color.kt
1530162580
package com.example.socialmediaapp.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun SocialMediaAppTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
social-media-project/app/src/main/Kotlin/com/example/socialmediaapp/ui/theme/Theme.kt
1206185761
package com.example.socialmediaapp.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
social-media-project/app/src/main/Kotlin/com/example/socialmediaapp/ui/theme/Type.kt
1948019685
package com.example.socialmediaapp import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import com.example.socialmediaapp.Utils.UserUtils import com.example.socialmediaapp.auth.AuthenticationActivity import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.firebase.auth.FirebaseAuth class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (FirebaseAuth.getInstance().currentUser ==null) { val intent = Intent(this, AuthenticationActivity::class.java) startActivity(intent) } UserUtils.getCurrentUser() setfragment(FeedFragment()) val bottomnavview:BottomNavigationView = findViewById(R.id.bottomnavigationview) bottomnavview.setOnNavigationItemSelectedListener { when (it.itemId) { R.id.feed->{ setfragment(FeedFragment()) } R.id.Search->{ setfragment(SearchFragment()) } R.id.chatroom->{ setfragment(ChatRoomFragment()) } R.id.profile->{ setfragment(ProfileFragment()) } } true } } private fun setfragment(fragment: Fragment){ supportFragmentManager.beginTransaction() .replace(R.id.fragment_container,fragment) .commit() } }
social-media-project/app/src/main/Kotlin/com/example/socialmediaapp/MainActivity.kt
2328834588
package com.example.socialmediaapp import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.ImageView import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.socialmediaapp.Adapter.Chat_Adapter import com.example.socialmediaapp.Model.Messege import com.example.socialmediaapp.Utils.UserUtils import com.firebase.ui.firestore.FirestoreRecyclerOptions import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.Query class ChatFragment : Fragment() { var ChatroomId:String?=null lateinit var chatadapter:Chat_Adapter lateinit var chatrecyclerview:RecyclerView override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_chat, container, false) } @SuppressLint("SuspiciousIndentation") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val bundle=this.arguments if (bundle!=null) { ChatroomId = bundle.getString("ChatroomId") } chatrecyclerview=view.findViewById(R.id.Chat_recycler_view) setuprecyclerView() val enteredMessege:EditText=view.findViewById(R.id.enter_messege) val sendMessege:ImageView=view.findViewById(R.id.send_messege_icon) sendMessege.setOnClickListener { if (enteredMessege.text.isNullOrEmpty()) return@setOnClickListener val chattext=enteredMessege.text.toString() val firestore=FirebaseFirestore.getInstance() .collection("ChatRooms").document(ChatroomId!!).collection("Messages") val chat=Messege(chattext,UserUtils.user!!,System.currentTimeMillis(),ChatroomId!!) firestore.document().set(chat).addOnCanceledListener { chatrecyclerview.scrollToPosition(chatrecyclerview.adapter?.itemCount!! - 1) enteredMessege.text.clear() } } } fun setuprecyclerView(){ val firestore=FirebaseFirestore.getInstance() val query=firestore.collection("ChatRooms").document(ChatroomId!!).collection("Messages") .orderBy("time",Query.Direction.ASCENDING) val RecyclerViewOptions=FirestoreRecyclerOptions.Builder<Messege>().setQuery(query,Messege::class.java).build() chatadapter= Chat_Adapter(RecyclerViewOptions) chatrecyclerview.adapter=chatadapter chatrecyclerview.layoutManager=LinearLayoutManager(context) } override fun onStart() { super.onStart() chatadapter.startListening() } override fun onStop() { super.onStop() chatadapter.stopListening() } }
social-media-project/app/src/main/Kotlin/com/example/socialmediaapp/ChatFragment.kt
682222389