Share
Explore

Pokemon Battle with GSON

I'll guide you through creating a simple Kotlin Android app that demonstrates the use of GSON with SharedPreferences to simulate a basic Pokémon battle.



Let's start with the basic setup and then build up the app step by step.

Step 1: Project Setup

First, create a new Android project in Android Studio with the following details:
Name: PokemonGSONBattle
Package name: com.example.pokemongsonbattle
Language: Kotlin
Minimum SDK: API 24 (Android 7.0)

Step 2: Update Gradle Files

Open the project-level build.gradle.kts file and ensure you have the latest versions of the plugins:
kotlin

// Project-level build.gradle.kts
plugins {
id("com.android.application") version "8.2.0" apply false
id("org.jetbrains.kotlin.android") version "1.9.0" apply false
}
Now, update the app-level build.gradle.kts file:
kotlin

// App-level build.gradle.kts
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}

android {
namespace = "com.example.pokemongsonbattle"
compileSdk = 34

defaultConfig {
applicationId = "com.example.pokemongsonbattle"
minSdk = 24
targetSdk = 34
versionCode = 1
versionName = "1.0"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
buildFeatures {
viewBinding = true
}
}

dependencies {
implementation("androidx.core:core-ktx:1.12.0")
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.11.0")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
implementation("com.google.code.gson:gson:2.10.1")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
}

Step 3: Create Pokemon Data Class
Create a new Kotlin file called Pokemon.kt:
kotlin
Copy
// Pokemon.kt
package com.example.pokemongsonbattle

data class Pokemon(
val name: String,
var hp: Int,
val attack: Int,
val defense: Int
)

Step 4: Update MainActivity

Now, let's update the MainActivity.kt file to implement our Pokémon battle logic using GSON and SharedPreferences:
// MainActivity.kt
package com.example.pokemongsonbattle

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.example.pokemongsonbattle.databinding.ActivityMainBinding
import com.google.gson.Gson
import kotlin.random.Random

class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var playerPokemon: Pokemon
private lateinit var enemyPokemon: Pokemon

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

setupGame()
updateUI()

binding.buttonAttack.setOnClickListener {
performBattleRound()
updateUI()
checkGameOver()
}

binding.buttonNewGame.setOnClickListener {
setupGame()
updateUI()
binding.buttonAttack.visibility = View.VISIBLE
binding.textViewResult.text = ""
}
}

private fun setupGame() {
playerPokemon = Pokemon("Pikachu", 100, 20, 10)
enemyPokemon = Pokemon("Charmander", 100, 18, 8)
saveGameState()
}

private fun performBattleRound() {
// Player attacks enemy
val playerDamage = calculateDamage(playerPokemon.attack, enemyPokemon.defense)
enemyPokemon.hp -= playerDamage

// Enemy attacks player
if (enemyPokemon.hp > 0) {
val enemyDamage = calculateDamage(enemyPokemon.attack, playerPokemon.defense)
playerPokemon.hp -= enemyDamage
}

saveGameState()
}

private fun calculateDamage(attack: Int, defense: Int): Int {
return (attack * (100 - defense) / 100.0).toInt().coerceAtLeast(1)
}

private fun updateUI() {
binding.textViewPlayerHP.text = "Player HP: ${playerPokemon.hp}"
binding.textViewEnemyHP.text = "Enemy HP: ${enemyPokemon.hp}"
}

private fun checkGameOver() {
when {
playerPokemon.hp <= 0 -> endGame("You lost!")
enemyPokemon.hp <= 0 -> endGame("You won!")
}
}

private fun endGame(result: String) {
binding.textViewResult.text = result
binding.buttonAttack.visibility = View.GONE
}

private fun saveGameState() {
val sharedPref = getPreferences(Context.MODE_PRIVATE)
with(sharedPref.edit()) {
putString("playerPokemon", Gson().toJson(playerPokemon))
putString("enemyPokemon", Gson().toJson(enemyPokemon))
apply()
}
}

private fun loadGameState() {
val sharedPref = getPreferences(Context.MODE_PRIVATE)
val playerPokemonJson = sharedPref.getString("playerPokemon", null)
val enemyPokemonJson = sharedPref.getString("enemyPokemon", null)

if (playerPokemonJson != null && enemyPokemonJson != null) {
playerPokemon = Gson().fromJson(playerPokemonJson, Pokemon::class.java)
enemyPokemon = Gson().fromJson(enemyPokemonJson, Pokemon::class.java)
} else {
setupGame()
}
}

override fun onResume() {
super.onResume()
loadGameState()
updateUI()
checkGameOver()
}
}

Step 5: Update the Layout

Update the activity_main.xml layout file:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/textViewPlayerHP"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Player HP: 100"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textViewEnemyHP"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Enemy HP: 100"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textViewPlayerHP" />

<Button
android:id="@+id/buttonAttack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Attack"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.