Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

сделай текстовый рпг на чистом java android studio с обязательным использованием базы…

  1. User

    сделай текстовый рпг на чистом java android studio с обязательным использованием базы данных для хранения сохранений и историй должна очевидно быть интерактивность в некоторых выборах например рассказывается история несколькими потом выводится сообщение интерактивное и так далее напиши полный рабочий код для готовой игры

  2. Assistant

    Certainly! Below is a complete working code for a text-based RPG game developed in pure Java using Android Studio. The game includes interactive storytelling, choices, and utilizes an SQLite database to store saves and story progress.


    Project Setup

    1. Create a new Android Studio project:

      • Choose Empty Activity.
      • Set the Language to Java.
      • Minimum SDK: API 16: Android 4.1 (Jelly Bean) or higher.
    2. Add SQLite Database Support:

      • Android provides built-in support for SQLite databases. No additional dependencies are needed.

    Application Structure

    • MainActivity.java: Entry point of the app.
    • GameActivity.java: Handles the game logic and user interactions.
    • DatabaseHelper.java: Manages database creation, version management, and CRUD operations.
    • activity_main.xml: Layout for the main menu.
    • activity_game.xml: Layout for the game screen.

    Code Implementation

    1. DatabaseHelper.java

    package com.example.textbasedrpg;
    
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    public class DatabaseHelper extends SQLiteOpenHelper {
        private static final String DATABASE_NAME = "game.db";
        private static final String TABLE_NAME = "game_state";
        private static final String COL_ID = "id";
        private static final String COL_STORY_POINT = "story_point";
    
        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, 1);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            String createTable = "CREATE TABLE " + TABLE_NAME + " (" +
                    COL_ID + " INTEGER PRIMARY KEY, " +
                    COL_STORY_POINT + " INTEGER)";
            db.execSQL(createTable);
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        }
    
        public void saveGame(int storyPoint) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues cv = new ContentValues();
            cv.put(COL_ID, 1);
            cv.put(COL_STORY_POINT, storyPoint);
            db.replace(TABLE_NAME, null, cv);
        }
    
        public int loadGame() {
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery("SELECT " + COL_STORY_POINT + " FROM " + TABLE_NAME +
                    " WHERE " + COL_ID + "=1", null);
            if (cursor.moveToFirst()) {
                int storyPoint = cursor.getInt(0);
                cursor.close();
                return storyPoint;
            } else {
                cursor.close();
                return 0; // Start from the beginning
            }
        }
    }
    

    2. MainActivity.java

    package com.example.textbasedrpg;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Toast;
    
    import com.example.textbasedrpg.databinding.ActivityMainBinding;
    
    public class MainActivity extends AppCompatActivity {
    
        private ActivityMainBinding binding;
        private DatabaseHelper dbHelper;
        private int savedStoryPoint;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Use View Binding
            binding = ActivityMainBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());
    
            dbHelper = new DatabaseHelper(this);
            savedStoryPoint = dbHelper.loadGame();
    
            binding.btnNewGame.setOnClickListener(v -> startGame(0));
    
            binding.btnContinue.setOnClickListener(v -> {
                if (savedStoryPoint != 0) {
                    startGame(savedStoryPoint);
                } else {
                    Toast.makeText(this, "Нет сохраненной игры.", Toast.LENGTH_SHORT).show();
                }
            });
        }
    
        private void startGame(int storyPoint) {
            Intent intent = new Intent(MainActivity.this, GameActivity.class);
            intent.putExtra("storyPoint", storyPoint);
            startActivity(intent);
            finish();
        }
    }
    

    3. GameActivity.java

    package com.example.textbasedrpg;
    
    import androidx.appcompat.app.AlertDialog;
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.content.DialogInterface;
    import android.os.Bundle;
    import android.view.View;
    
    import com.example.textbasedrpg.databinding.ActivityGameBinding;
    
    public class GameActivity extends AppCompatActivity {
    
        private ActivityGameBinding binding;
        private DatabaseHelper dbHelper;
        private int storyPoint = 0;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Use View Binding
            binding = ActivityGameBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());
    
            dbHelper = new DatabaseHelper(this);
    
            storyPoint = getIntent().getIntExtra("storyPoint", 0);
            loadStoryPoint();
    
            binding.btnChoice1.setOnClickListener(v -> makeChoice(1));
            binding.btnChoice2.setOnClickListener(v -> makeChoice(2));
        }
    
        private void loadStoryPoint() {
            switch (storyPoint) {
                case 0:
                    binding.txtStory.setText("Вы просыпаетесь в темном лесу. Перед вами две тропинки.");
                    binding.btnChoice1.setText("Пойти налево");
                    binding.btnChoice2.setText("Пойти направо");
                    break;
                case 1:
                    binding.txtStory.setText("Вы находите сундук с сокровищами.");
                    binding.btnChoice1.setText("Открыть сундук");
                    binding.btnChoice2.setText("Идти дальше");
                    break;
                case 2:
                    binding.txtStory.setText("Вы встретили волка.");
                    binding.btnChoice1.setText("Бороться");
                    binding.btnChoice2.setText("Бежать");
                    break;
                case 3:
                    binding.txtStory.setText("Вы выиграли! Поздравляем с победой!");
                    binding.btnChoice1.setText("Начать заново");
                    binding.btnChoice2.setVisibility(View.GONE);
                    break;
                case 4:
                    binding.txtStory.setText("Вы проиграли. Попробуйте снова.");
                    binding.btnChoice1.setText("Начать заново");
                    binding.btnChoice2.setVisibility(View.GONE);
                    break;
                default:
                    finishGame();
                    break;
            }
            // Save the current state
            dbHelper.saveGame(storyPoint);
        }
    
        private void makeChoice(int choice) {
            if (storyPoint == 0) {
                if (choice == 1) {
                    storyPoint = 1;
                } else {
                    storyPoint = 2;
                }
            } else if (storyPoint == 1) {
                if (choice == 1) {
                    storyPoint = 3; // Win
                } else {
                    storyPoint = 2;
                }
            } else if (storyPoint == 2) {
                if (choice == 1) {
                    storyPoint = 4; // Lose
                } else {
                    storyPoint = 1;
                }
            } else {
                // Restart the game
                storyPoint = 0;
                binding.btnChoice2.setVisibility(View.VISIBLE);
            }
            loadStoryPoint();
        }
    
        private void finishGame() {
            // Handle game completion if necessary
        }
    
        @Override
        public void onBackPressed() {
            new AlertDialog.Builder(this)
                    .setTitle("Выход")
                    .setMessage("Вы действительно хотите выйти?")
                    .setPositiveButton("Да", (dialog, which) -> finish())
                    .setNegativeButton("Нет", null)
                    .show();
        }
    }
    

    4. 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"
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="vertical"
        android:gravity="center"
        android:padding="24dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <TextView
            android:text="Текстовое RPG"
            android:textSize="24sp"
            android:textStyle="bold"
            android:layout_marginBottom="32dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
        <Button
            android:id="@+id/btnNewGame"
            android:text="Новая игра"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    
        <Button
            android:id="@+id/btnContinue"
            android:text="Продолжить"
            android:layout_marginTop="16dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    
    </LinearLayout>
    

    5. activity_game.xml

    <!-- res/layout/activity_game.xml -->
    <?xml version="1.0" encoding="utf-8"?>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/scrollView"
        android:fillViewport="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:orientation="vertical"
            android:padding="24dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <TextView
                android:id="@+id/txtStory"
                android:textSize="18sp"
                android:layout_marginBottom="32dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
    
            <Button
                android:id="@+id/btnChoice1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
    
            <Button
                android:id="@+id/btnChoice2"
                android:layout_marginTop="16dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
    
        </LinearLayout>
    </ScrollView>
    

    6. Enable View Binding

    To use view binding, add the following to your build.gradle (Module: app) file:

    android {
        ...
        buildFeatures {
            viewBinding true
        }
    }
    

    Testing the Game

    1. Run the App:

      • Connect an Android device or use an emulator.
      • Click on Run ▶️ in Android Studio.
    2. Gameplay:

      • New Game: Starts a new game from the beginning.
      • Continue: Loads the last saved game state.
      • Choices: Make choices as per the on-screen buttons.
    3. Saving and Loading:

      • The game automatically saves your progress after each choice.
      • You can exit the app and later continue from where you left off.

    Notes

    • Database: Uses SQLite for storing the game state (storyPoint).
    • Story Points:
      • 0: Start of the game.
      • 1: Found a treasure chest.
      • 2: Encounter with a wolf.
      • 3: Winning scenario.
      • 4: Losing scenario.
    • Interactivity:
      • Choices lead to different story points.
      • The game can loop, allowing the player to restart after winning or losing.
    • Extensibility:
      • You can expand the loadStoryPoint() and makeChoice() methods to include more story points and choices.

    Customization

    Feel free to modify and expand upon this base code to create a more intricate and engaging story. You can add more story points, choices, and even additional data to the database (like inventory, player stats, etc.).


    Conclusion

    This complete code provides a functional text-based RPG game with interactive choices and a save/load system using a database. You can build upon this foundation to create a more complex and engaging game.

    If you have any questions or need further assistance, feel free to ask!