Creating a One-Stroke Drawing Game in Android Studio

1. Project Overview

Android One-Stroke Drawing is a puzzle game where players need to start from a point and connect all the squares in the shape with a continuous line without retracing any connected segments. The game homepage features a regular mode, a random mode, and a settings entry. The regular mode includes 8 major levels, with the first major level having 10 minor levels, while the others have 30 minor levels, increasing difficulty and a rich variety of maps.

After starting the game, players can use the display function in the bottom left corner to show the correct path, and the refresh function in the bottom right corner to clear any paths that are no longer valid. They can also skip to the next level directly. In regular mode, completed minor levels will be highlighted in color to differentiate them from uncompleted levels. The random mode generates maps using depth-first traversal and combinatorial algorithms. If the background pathfinding is enabled in settings, new maps will be continuously generated for use. The random mode also allows customization of the map in terms of rows, columns, and the number of obstacles, and players can choose to skip already completed levels and view completion records. Enabling background music in settings adds more fun to the game.

2. Development Environment

Creating a One-Stroke Drawing Game in Android Studio

3. Detailed Design

3.1. Database Design

MySql class is a custom class that inherits from SQLiteOpenHelper, primarily used for managing data storage and query operations in the game. By inheriting from SQLiteOpenHelper, it becomes easy to create, update, and query the database. In specific game development, these methods can be used as needed to store and retrieve game data.

public void insertPassedYibi(Bean_Road road){    if(checkPassedYibi(road) || road==null) return;    ContentValues values=new ContentValues();    values.put("rows",road.getRows());    values.put("columns",road.getColumns());    values.put("difficulties",road.getDifficulties());    values.put("road",road.getRoadString());    getReadableDatabase().insert("passedYibi",null,values);}

The defined constructor initializes the database name and version number, calling the parent class’s constructor. The onCreate() method is called when the database is created for the first time, used to create database tables. The code creates three tables: passedYibi, savedYibi, and errorYibi. The onUpgrade() method is called when the database version number changes, used to update the database structure. The code first deletes the existing tables, then calls onCreate() again to create new tables.

Creating a One-Stroke Drawing Game in Android Studio

checkErrorYibi() method checks if there are any data records in the errorYibi table that meet the conditions. It queries based on the passed parameters and returns a boolean indicating whether the query result exists. insertErrorYibi() method inserts new data records into the errorYibi table. Before inserting, it first calls checkErrorYibi() for duplicate checks. checkPassedYibiWithRoad() method checks if there are any data records in the passedYibi table that meet the conditions based on the roadstring parameter. checkPassedYibi() method checks if there are any data records in the passedYibi table that meet the conditions based on the passed Bean_Road object. insertPassedYibi() method inserts new data records into the passedYibi table. Before inserting, it first calls checkPassedYibi() for duplicate checks. getAllPassedYibi() method retrieves all data records from the passedYibi table and returns a Cursor object. cleanPassedYibi() method clears all data records from the passedYibi table. checkSavedYibi() method checks if there are any data records in the savedYibi table that meet the conditions based on the passed Bean_Road object.

3.2. Regular Mode

RoadFragment class is a Fragment class used to display the map in the regular mode of the game, mainly implementing the initialization of the road interface, handling button click events, managing levels and map positions, and implementing level and help functionalities. It uses the Grid_Yibi class to display the grid of roads and handles grid-related operations through the interface Grid_Yibi.yibiListener.

@Overridepublic void passed(Bean_Road road) {    if(road==null) return;    if(!firstPassed){        firstPassed=true;        getMySql().insertPassedYibi(road);        ViewUtil.getAskDialog( "","Congratulations on passing",new OtherUtil.OnCallBackListenerImpl<Boolean>(){            @Override            public void OnCallBackFirst(Boolean... params) {                goNext();            }        },"Next Level", "Forget It");    }}

In the initView() method, the interface elements are initialized, and button click events are set. When the back button is clicked, the onBackClick() method is called; when the refresh button is clicked, the grid_yibi.refreshGrid() method is called; when the help button is clicked, it calls grid_yibi.getHelp() or grid_yibi.refreshGrid() based on the ishelping flag; when the home button is clicked, it jumps to the IndexFragment page in MainActivity.

Creating a One-Stroke Drawing Game in Android Studio

In the goNext() method, it checks if the current level and map position are valid. If valid, it proceeds to the next level or the next map interface. If it is the last level, it displays a prompt. In the checkPosition() method, it checks if the current level and map position are valid. If valid, it returns true; otherwise, it shows a failure message for obtaining the map and returns false. In the getCurRoad() method, it retrieves the corresponding Bean_Road object based on the current level and map position. If the position is valid, it returns that object; otherwise, it returns null. In the passed() method, when a level is passed, this method is called. On the first pass, the passed road is recorded in the database, and a congratulatory dialog is displayed. Clicking the next level button in the dialog calls goNext() to proceed to the next level. In the setIsHelping() method, it sets the ishelping flag based on the passed isHelping parameter and updates the help button’s background image accordingly. In the isHelping() method, it returns the value of the ishelping flag.

3.3. Random Mode

RandomRoadFragment class implements the initialization of the random mode game interface, status checks, and the generation of grid roads. It includes the following functionalities: initView() method initializes the view. It first retrieves parameters such as rows, columns, and difficulty from preferences and performs corresponding initialization operations. Then it sets button click listeners and handles state settings and event processing for some view elements. Finally, it performs some asynchronous operations based on conditions, including updating text view content and executing timed tasks. It ultimately returns true. checkPassedView() method checks the views that have been passed. Based on the given road object, it determines whether the road has been passed and sets the visibility of related views accordingly. onDetach() method is called when the Fragment is unbound, used to clear animations and road queues. onDestroyView() method is called when the view is destroyed, used to remove timed tasks. initGirdRoad() method initializes the grid roads in the game. It first resets some state variables, then chooses to either retrieve road data from the database or from the queue based on conditions, or directly generate new road data. It then validates and processes the road data, updates the related views based on the results, and finally saves the road data and related information.

Creating a One-Stroke Drawing Game in Android Studio

3.4. Level List

DifficultyDetailFragment class is a subclass of BaseFragment. It has three member variables: difficultyHint (TextView for displaying level hints), returnButton (View for the back button), and recyclerView (RecyclerView for displaying level details). It implements a detailed level information interface, including level hints, a back button, and a list view for showing level details. During view initialization, it sets the content and adapter for related views based on the passed parameters. It also provides methods for handling new parameters and returning results.

@Overridepublic void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {    super.onActivityResult(requestCode, resultCode, data);    if(data!=null&&data.getExtras()!=null) getNonNullArguments().putAll(data.getExtras());    runOnUiThread(this::initView);}

getLayoutId() method: overrides the method in BaseFragment to return the layout file ID. initView() method: overrides the method in BaseFragment to initialize the view. It first retrieves the current level position, then sets the click listener for the back button. Next, it sets the layout manager for recyclerView to GridLayoutManager and specifies 5 columns. Then it sets the adapter based on the position value; if the position is within a valid range, it uses Adapter_difficulty_detail as the adapter; otherwise, it displays a hint. Finally, it sets the visibility of level hints to visible and sets the corresponding text content. It ultimately returns true to indicate successful view initialization. onNewArguments() method: overrides the method in BaseFragment, called when new parameters are passed to the Fragment. In this method, it calls initView() to initialize the view and sets the isLoaded flag to true. onActivityResult() method: overrides the method in BaseFragment, called when the target Activity of the Fragment returns a result. In this method, it checks if the returned Intent and Bundle are not null; if they are not, it adds the parameters from them to the Fragment’s parameters. Then it calls initView() on the main thread to reinitialize the view.

Creating a One-Stroke Drawing Game in Android Studio

4. Running Demonstration

5. Source Code Acquisition

Backend Reply:One-Stroke Drawing

There are also some past exciting articles you missed:

Android Implementation of Snake Game
Android Implementation of Piano Tiles
Android Implementation of Airplane War
Android Implementation of Push Boxes

Leave a Comment