Share
Explore

GSON Car Race Simulation

GSON Car Race Simulation

How to submit this:
Put all content into a Word Document - save as student name student id.docx
Upload to Classroom.

Objective

Create an Android application that simulates a car race using GSON for data serialization and deserialization.
This assignment will test your understanding of GSON, Kotlin programming, debugging techniques, and Android development principles.
In your Word Document: show log cat and debugger screen shots, just to practice using these development tools.

Requirements

Create a Car data class with the following properties:
name: String
speed: Int
acceleration: Int
handling: Int
Implement a MainActivity that does the following:
Creates a list of 5 cars with random attributes
Simulates a race over 10 rounds
Uses GSON to serialize and deserialize car data between rounds
Implements a simple race logic (e.g., speed + acceleration + handling + random factor)
Updates car positions after each round
Logs detailed information using Logcat
Determines and announces the winner after 10 rounds
Use ViewBinding for all UI interactions
Implement a "Start Race" button to begin the simulation
Display the current standings after each round in the UI
Use SharedPreferences with GSON to save and load the race state
Implement proper error handling and logging

Specific Implementation Details

Use Random() to generate initial car attributes (speed: 50-100, acceleration: 1-10, handling: 1-10)
Race Logic:
kotlin
Copy
distance += speed + (acceleration * 2) + handling + Random().nextInt(20)
Log each round's results and any car data changes
Use different Log levels (d, i, w, e) appropriately
Implement a debug flag to enable/disable verbose logging

Deliverables

A Word document containing:
Screenshots of your code (MainActivity.kt, Car.kt, activity_main.xml)
Screenshots showing the use of the debugger (at least 3 different breakpoints)
Screenshots of Logcat output showing the race progression
A brief explanation (200-300 words) of how you implemented the race logic and used GSON
Your complete Android Studio project, zipped and uploaded separately

Grading Rubric


Table 1
Criteria
Points
1
Correct implementation of Car data class
10
2
Proper use of GSON for serialization
15
3
Correct race simulation logic
20
4
Effective use of Logcat
10
5
Proper implementation of ViewBinding
10
6
Use of SharedPreferences for state saving
10
7
UI updates and "Start Race" functionality
10
8
Correct use of Random() for attributes
5
9
Proper error handling
5
10
Code readability and comments
5
11
Word document with required screenshots
15
12
Explanation of implementation
10
13
Total
125
There are no rows in this table

Instructions for Submission

Create a new Android Studio project named "GSONCarRace"
Implement the required functionality as per the specifications above
Use the debugger to set breakpoints and examine variables during execution
Capture Logcat output showing the race progression
Create a Word document with the required screenshots and explanation
Zip your entire Android Studio project folder
Submit both the Word document and the zipped project file

Tips

Refer to the Pokémon GSON battle lab for guidance on GSON usage and logging techniques
Make effective use of Kotlin's features like data classes and extension functions
Pay attention to code organization and commenting
Test your application thoroughly before submission
Good luck, and happy coding!
This assignment provides a comprehensive test of the students' understanding of GSON, Android development, and debugging techniques while building upon the concepts introduced in the Pokémon GSON battle simulation. The car race theme offers a fresh context for applying these skills, and the detailed rubric ensures clear expectations for grading.



Here's a starter MainActivity.kt file for the GSON Car Race Simulation assignment. This version demonstrates the use of random number generators and sets up the basic structure for the race simulation:
```kotlin package com.example.gsoncarrace
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import com.example.gsoncarrace.databinding.ActivityMainBinding import com.google.gson.Gson ​import kotlin.random.Random
class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val cars = mutableListOf<Car>() private var currentRound = 0 private val totalRounds = 10 private val gson = Gson() private val tag = "CarRaceSimulation"
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root)
initializeCars() setupUI() }
private fun initializeCars() { val carNames = listOf("Ferrari", "Mercedes", "Red Bull", "McLaren", "Aston Martin") for (name in carNames) { cars.add(Car( name = name, speed = Random.nextInt(50, 101), acceleration = Random.nextInt(1, 11), handling = Random.nextInt(1, 11) )) } Log.d(tag, "Cars initialized: ${gson.toJson(cars)}") }
private fun setupUI() { binding.buttonStartRace.setOnClickListener { startRace() } updateStandings() }
private fun startRace() { currentRound = 0 for (car in cars) { car.distance = 0 } simulateRace() }
private fun simulateRace() { if (currentRound < totalRounds) { currentRound++ for (car in cars) { val distance = car.speed + (car.acceleration * 2) + car.handling + Random.nextInt(20) car.distance += distance Log.i(tag, "Round $currentRound: ${car.name} moved $distance units. Total distance: ${car.distance}") } updateStandings() binding.root.postDelayed({ simulateRace() }, 1000) // Simulate next round after 1 second } else { announceWinner() } }
private fun updateStandings() { cars.sortByDescending { it.distance } val standingsText = cars.mapIndexed { index, car -> "${index + 1}. ${car.name}: ${car.distance}" }.joinToString("\n") binding.textViewStandings.text = standingsText }
private fun announceWinner() { val winner = cars.maxByOrNull { it.distance } winner?.let { val message = "${it.name} wins the race!" binding.textViewWinner.text = message Log.d(tag, message) } }
data class Car( val name: String, val speed: Int, val acceleration: Int, val handling: Int, var distance: Int = 0 ) } ```
This MainActivity.kt file includes:
1. A `Car` data class with the required properties. 2. Initialization of 5 cars with random attributes using `Random.nextInt()`. 3. Basic race simulation logic that runs for 10 rounds. 4. Use of GSON for serializing car data in logs. 5. UI updates to show current standings. 6. A "Start Race" button to begin the simulation. 7. Logging of race progress using different Log levels.
To complete the assignment, students would need to:
1. Implement SharedPreferences for saving and loading the race state. 2. Add more detailed logging and error handling. 3. Implement a debug flag for verbose logging. 4. Enhance the UI and improve the race logic as they see fit. 5. Use the debugger to examine variables during execution. 6. Capture Logcat output and create the required Word document with screenshots and explanations.
This starter code provides a solid foundation for students to build upon, demonstrating key concepts like random number generation, basic GSON usage, and the structure of the race simulation.

info

activity_main.xml

Here's an `activity_main.xml` layout file that corresponds to the MainActivity.kt we created:
```xml <?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" android:padding="16dp" tools:context=".MainActivity">
<TextView android:id="@+id/textViewTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GSON Car Race Simulation" android:textSize="24sp" android:textStyle="bold" app:layout_constraintTop_top_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" />
<Button android:id="@+id/buttonStartRace" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start Race" android:layout_marginTop="16dp" app:layout_constraintTop_toBottomOf="@id/textViewTitle" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" />
<TextView android:id="@+id/textViewStandingsTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Current Standings" android:textSize="18sp" android:textStyle="bold" android:layout_marginTop="24dp" app:layout_constraintTop_toBottomOf="@id/buttonStartRace" app:layout_constraintStart_toStartOf="parent" />
<TextView android:id="@+id/textViewStandings" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="8dp" app:layout_constraintTop_toBottomOf="@id/textViewStandingsTitle" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" />
<TextView android:id="@+id/textViewWinner" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:textStyle="bold" android:textColor="#4CAF50" android:layout_marginTop="24dp" app:layout_constraintTop_toBottomOf="@id/textViewStandings" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout> ```
This layout includes:
1. A title for the app at the top. 2. A "Start Race" button to begin the simulation. 3. A "Current Standings" section to display the race progress. 4. A TextView to announce the winner at the end of the race.
The layout uses ConstraintLayout for flexibility and easy positioning of elements. It's designed to be simple and functional, matching the starter implementation in the MainActivity.kt file.
To use this layout with ViewBinding as implemented in the MainActivity.kt:
1. Ensure ViewBinding is enabled in your app's build.gradle file:
```gradle android { ... buildFeatures { viewBinding true } } ```
2. The MainActivity.kt file is already set up to use ViewBinding with this layout. It inflates the layout and sets it as the content view in the onCreate method:
```kotlin binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) ```
3. The code uses binding to access views, for example:
```kotlin binding.buttonStartRace.setOnClickListener { ... } binding.textViewStandings.text = standingsText binding.textViewWinner.text = message ```
This layout provides a basic UI for the car race simulation. Students can further enhance it by adding more visual elements, styling, or additional features as part of their assignment.
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.