Добавить в корзинуПозвонить
Найти в Дзене
КвадроKot

6. Мини игра "Угадай число" на Kotlin?

Давайте создадим игру "Угадай число" для Android на Kotlin. Вот пошаговая инструкция для новичка: Добавьте эту строку внутри тега <application, чтобы запретить поворот экрана: //---------------------------------------------- android:screenOrientation="portrait" //---------------------------------------------- Полный манифест: //---------------------------------------------- <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.guessnumber"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:screenOrientation="portrait"
android:supportsRtl="true"
android:theme="@style/Theme.GuessNumber"
tools:targetApi="31">
<activity
android:name=".MainActivity"
andr
Оглавление

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

1. Создание проекта

  1. Запустите Android Studio.
  2. Создайте новый проект (File → New → New Project).
  3. Выберите "Empty Activity".
  4. Назовите проект (например, "GuessNumber").
  5. Убедитесь, что язык выбран Kotlin.

2. Настройка манифеста (AndroidManifest.xml)

Добавьте эту строку внутри тега <application, чтобы запретить поворот экрана:

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

android:screenOrientation="portrait"

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

Полный манифест:

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

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

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:screenOrientation="portrait"
android:supportsRtl="true"
android:theme="@style/Theme.GuessNumber"
tools:targetApi="31">
<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. Разметка интерфейса (activity_main.xml)

Замените содержимое файла на код ниже 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="20dp"
android:gravity="center">

<TextView
android:id="@+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Угадай число от 1 до 100!"
android:textSize="24sp"
android:layout_marginBottom="30dp"/>

<EditText
android:id="@+id/numberEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="Введите число"
android:minHeight="48dp"
android:padding="16dp"
android:layout_marginBottom="20dp"
android:importantForAccessibility="yes"
android:background="@android:drawable/editbox_background"/>

<Button
android:id="@+id/guessButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Проверить"
android:layout_gravity="center"
android:layout_marginBottom="20dp"/>

<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_marginBottom="20dp"/>

<Button
android:id="@+id/restartButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Новая игра"
android:layout_gravity="center"
android:visibility="gone"/>

</LinearLayout>

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

4. Код MainActivity.kt

Замените содержимое MainActivity.kt:

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

package com.example.guessnumber

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlin.random.Random

class MainActivity : AppCompatActivity() {

private lateinit var numberEditText: EditText
private lateinit var guessButton: Button
private lateinit var resultTextView: TextView
private lateinit var restartButton: Button

private var secretNumber = 0
private var attempts = 0

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

// Инициализация элементов интерфейса
numberEditText = findViewById(R.id.numberEditText)
guessButton = findViewById(R.id.
guessButton)
resultTextView = findViewById(R.id.
resultTextView)
restartButton = findViewById(R.id.
restartButton)

startNewGame()

// Обработчик нажатия кнопки "Проверить"
guessButton.setOnClickListener {
checkNumber()
}

// Обработчик кнопки "Новая игра"
restartButton.setOnClickListener {
startNewGame()
}
}

private fun startNewGame() {
// Генерируем новое число
secretNumber = Random.nextInt(1, 101)
attempts = 0
resultTextView.
text = ""
numberEditText.
text.clear()
restartButton.
visibility = Button.GONE
guessButton.isEnabled = true
}

private fun checkNumber() {
val input = numberEditText.
text.toString()

if (input.
isEmpty()) {
Toast.makeText(this, "Введите число!", Toast.
LENGTH_SHORT).show()
return
}

val userNumber = input.
toInt()
attempts++

when {
userNumber < secretNumber -> {
resultTextView.
text = "Загаданное число больше!"
}
userNumber > secretNumber -> {
resultTextView.
text = "Загаданное число меньше!"
}
else -> {
resultTextView.
text = "Поздравляем! Вы угадали за $attempts попыток!"
guessButton.
isEnabled = false
restartButton.
visibility = Button.VISIBLE
}
}

numberEditText.
text.clear()
}
}

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

5. Пояснение кода.

  1. Элементы интерфейса:
    - EditText: поле для ввода числа.
    - Button: кнопка проверки числа.
    - TextView: для отображения подсказок и результата.
    - Вторая Button: появляется после победы для новой игры.
  2. Логика игры:
    - secretNumber - случайное число от 1 до 100.
    - attempts - счетчик попыток.
    - startNewGame() - инициализирует новую игру.
    - checkNumber() - сравнивает введенное число с загаданным.
  3. Основные методы:
    - onCreate() - инициализация приложения.
    - setOnClickListener - обработчики нажатий кнопок.
    - Random.nextInt() - генерация случайного числа.

6. Запуск приложения.

  1. Нажмите кнопку "Run" (зеленая стрелка).
  2. Выберите эмулятор или подключенное устройство.
  3. Попробуйте угадать число!

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

  1. Все строки лучше выносить в ресурсы (res/values/strings.xml).
  2. Для работы с числами используйте проверку ввода try-catch.
  3. Можно добавить подсветку правильного ответа.
  4. Добавьте ограничение на максимальное число попыток.
  5. Экспериментируйте с дизайном - меняйте цвета, размеры, шрифты.

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