Найти в Дзене
КвадроKot

7. Мини игра "Викторина" на Kotlin?

Давайте создадим простую игру "Викторину" для Android. Вот пошаговая инструкция: 1. Создайте новый проект в Android Studio. 2. Файл манифеста (AndroidManifest.xml). //---------------------------------------------- <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.quizapp">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.QuizApp">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest> //-----------------

Давайте создадим простую игру "Викторину" для Android. Вот пошаговая инструкция:

1. Создайте новый проект в Android Studio.

  • Выберите "Empty Activity"
  • Назовите проект "QuizApp"
  • Язык: Kotlin

2. Файл манифеста (AndroidManifest.xml).

//----------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.quizapp">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.QuizApp">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

//----------------------------------------------

Пояснение: Этот файл определяет основную активность приложения.

3. Макет активности (res/layout/activity_main.xml).

//----------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:id="@+id/tvScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/score"
android:textSize="18sp"/>

<TextView
android:id="@+id/tvQuestion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textSize="20sp"/>

<Button
android:id="@+id/btnOption1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Option 1"
android:contentDescription="Вариант ответа 1"/>

<Button
android:id="@+id/btnOption2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Option 2"
android:contentDescription="Вариант ответа 2"/>

<Button
android:id="@+id/btnOption3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Option 3"
android:contentDescription="Вариант ответа 3"/>

<Button
android:id="@+id/btnOption4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Option 4"
android:contentDescription="Вариант ответа 4"/>

</LinearLayout>

//----------------------------------------------

4. Класс MainActivity.kt

//----------------------------------------------

package com.example.quizapp
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
// Объявляем элементы UI
private lateinit var tvQuestion: TextView
private lateinit var tvScore: TextView
private lateinit var btnOptions: List<Button>

// Данные викторины
private val questions = listOf(
Question(
"Какая планета ближе всего к Солнцу?",
listOf("Венера", "Марс", "Меркурий", "Земля"),
2
),
Question(
"Сколько цветов в радуге?",
listOf("5", "7", "6", "8"),
1
)
)

private var currentQuestion = 0
private var score = 0

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.
activity_main)

// Инициализация UI элементов
tvQuestion = findViewById(R.id.tvQuestion)
tvScore = findViewById(R.id.
tvScore)
btnOptions =
listOf(
findViewById(R.id.
btnOption1),
findViewById(R.id.
btnOption2),
findViewById(R.id.
btnOption3),
findViewById(R.id.
btnOption4)
)

// Настройка обработчиков кликов
btnOptions.forEachIndexed { index, button ->
button.setOnClickListener {
checkAnswer(index)
}
}

showQuestion()
}

private fun showQuestion() {
if(currentQuestion >= questions.size) {
// Показать финальный результат
Toast.makeText(this, "Игра окончена! Ваш счет: $score", Toast.LENGTH_LONG).show()
return
}

val question = questions[currentQuestion]
tvQuestion.
text = question.text
tvScore.
text = getString(R.string.score, score)

question.answers.
forEachIndexed { index, answer ->
btnOptions[index].text = answer
}
}

private fun checkAnswer(selectedIndex: Int) {
val correctAnswerIndex = questions[currentQuestion].correctAnswer
if(selectedIndex == correctAnswerIndex) {
score++
Toast.makeText(this, "Верно!", Toast.
LENGTH_SHORT).show()
} else {
Toast.makeText(this,
"Неверно! Правильный ответ: ${questions[currentQuestion].answers[correctAnswerIndex]}",
Toast.
LENGTH_LONG).show()
}

currentQuestion++
showQuestion()
}
}

// Класс для хранения данных вопроса
data class Question(
val text: String,
val answers: List<String>,
val correctAnswer: Int
// Индекс правильного ответа (начиная с 0)
)

//----------------------------------------------

Пояснение кода:

  • Question - data class для хранения вопроса, вариантов ответов и индекса правильного ответа
  • showQuestion() - отображает текущий вопрос и варианты ответов
  • checkAnswer() - проверяет выбранный ответ и обновляет счет
  • При достижении последнего вопроса показывается финальный счет

5. Добавьте строковые ресурсы (res/values/strings.xml).

//----------------------------------------------

<resources>
<string name="app_name">Quiz App</string>
<string name="score">Счет: %d</string>
</resources>

//----------------------------------------------

Как это работает:

  1. При запуске отображается первый вопрос.
  2. Пользователь выбирает вариант ответа.
  3. Приложение проверяет правильность ответа.
  4. Обновляется счет и показывается следующий вопрос.
  5. После последнего вопроса показывается финальный счет.

Советы для улучшения:

  • Добавьте больше вопросов.
  • Реализуйте переход между вопросами с анимацией.
  • Добавьте разные категории вопросов.
  • Сохраняйте результаты в SharedPreferences.
  • Добавьте таймер для ответов.

Этот пример демонстрирует основные принципы:

  • Работу с UI элементами.
  • Обработку кликов.
  • Работу с коллекциями данных.
  • Основы архитектуры Android-приложения.

Вы можете модифицировать код, добавляя новые функции по мере изучения Android-разработки!