package com.example.memory data class Card(val imageId: Int, val value: Int) { var isFaceUp = false } package com.example.memory class Game(private val size: Int) { private val images = mutableListOf( R.drawable.card_back1, R.drawable.card_back2, R.drawable.card_back3, R.drawable.card_back4, R.drawable.card_back5, R.drawable.card_back6, R.drawable.card_back7, R.drawable.card_back8 ) val cards = MutableList(size) { Card(images[it / 2], it / 2) } fun shuffleCards() { cards.shuffle() } fun checkCards(firstIndex: Int, secondIndex: Int): Boolean { return cards[firstIndex].imageId == cards[secondIndex].imageId } } package com.example.memory import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.graphics.drawable.LayerDrawable import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.GridLayout import android.widget.ImageButton import androidx.constraintlayout.helper.widget.Layer import androidx.core.content.ContextCompat class Memory : AppCompatActivity() { private lateinit var game: Game private lateinit var gridLayout: GridLayout private var selectedCardIndex: Int? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_memory) gridLayout = findViewById(R.id.gridLayout) game = Game(16) game.shuffleCards() for (i in 0 until gridLayout.childCount) { val cardButton = gridLayout.getChildAt(i) as ImageButton val card = game.cards[i] updateCard(cardButton, card) cardButton.setOnClickListener { card.isFaceUp = !card.isFaceUp updateCard(cardButton, card) if (selectedCardIndex != null) { if (game.checkCards(selectedCardIndex!!, i)) { hideCards(selectedCardIndex!!, i) }else { val prevCardButton = gridLayout.getChildAt(selectedCardIndex!!) as ImageButton val prevCard = game.cards[selectedCardIndex!!] prevCard.isFaceUp = false updateCard(prevCardButton, prevCard) selectedCardIndex = null } }else{ selectedCardIndex = i } } } } private fun updateCard(cardButton: ImageButton, card: Card) { val resourceId = if (card.isFaceUp) { R.color.white // Use a color resource instead of ColorDrawable } else { resources.getIdentifier("card_back_${card.value}", "drawable", packageName) } cardButton.setImageDrawable( if (resourceId == 0) { // The resource was not found, so use a placeholder drawable ContextCompat.getDrawable(this, R.drawable.placeholder)!! } else { ContextCompat.getDrawable(this, resourceId)!! } ) } private fun hideCards(index1: Int, index2: Int) { val cardButton1 = gridLayout.getChildAt(index1) as ImageButton val cardButton2 = gridLayout.getChildAt(index2) as ImageButton cardButton1.isClickable = false cardButton2.isClickable = false } }