Android Studio パズルアプリ制作(動画有り)

今回はパズルアプリを制作しました。
YouTubeに作っている動画をアップしています。
https://www.youtube.com/watch?v=0PdvGG9uXR4&list=PLhg2PHSq8bjiTy1pNH8GeNlaPq82wVC4k

```xml:strings.xml
<resources>
    <string name="app_name">PuzzleApp</string>
    <string name="text_title">Puzzle Game</string>
    <string name="btn_start_game">ゲームを始める</string>
    <string name="text_setting">パズルの大きさ設定</string>
    <string name="text_col">縦：</string>
    <string name="text_row">横：</string>
    <string name="dialog_writeNumber">整数値を入力してください</string>
    <string name="dialog_writePositive">2以上の数値を入力してください</string>
    <string name="text_clearTime">CLEAR TIME :</string>
    <string name="btn_update">シャッフル</string>
    <string name="text_back">戻る</string>
</resources>
```

```xml: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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="5"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3"
        android:gravity="center"
        android:text="@string/text_title"
        android:textSize="36sp"></TextView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:gravity="center">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="tapSetting"
            android:text="@string/text_setting"></Button>

    </LinearLayout>

</LinearLayout>
```

```java:MainActivity.java
package com.example.puzzleapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void tapSetting(View view){
        Intent intent = new Intent(MainActivity.this,SettingActivity.class);
        startActivity(intent);
    }
}
```

```xml:activity_setting.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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="10"
    tools:context=".SettingActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="5"
        android:gravity="center"
        android:text="@string/text_setting"
        android:textSize="36sp"></TextView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        android:weightSum="5">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:gravity="right"
            android:text="@string/text_row"
            android:textSize="24sp"></TextView>

        <EditText
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:gravity="left"
            android:id="@+id/edit_colSize"
            android:textSize="24sp"></EditText>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        android:weightSum="5">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:gravity="right"
            android:text="@string/text_col"
            android:textSize="24sp"></TextView>

        <EditText
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:gravity="left"
            android:id="@+id/edit_rowSize"
            android:textSize="24sp"></EditText>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:gravity="center"
        android:layout_weight="3">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/btn_start_game"
            android:onClick="tapStart"></Button>

    </LinearLayout>

</LinearLayout>
```

```java:SettingActivity.java
package com.example.puzzleapp;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class SettingActivity extends AppCompatActivity {

    EditText editRowSize, editColSize;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        editColSize = findViewById(R.id.edit_colSize);
        editRowSize = findViewById(R.id.edit_rowSize);
    }

    public void tapStart(View view) {
        try {
            Intent intent = new Intent(SettingActivity.this, GameActivity.class);
            int rowSize = Integer.parseInt(editRowSize.getText().toString());
            int colSize = Integer.parseInt(editColSize.getText().toString());
            if ((rowSize < 2) || (colSize < 2)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);
                builder.setMessage(R.string.dialog_writePositive).show();
                return;
            }
            intent.putExtra("col", colSize);
            intent.putExtra("row", rowSize);
            startActivity(intent);
        } catch (Exception e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);
            builder.setMessage(R.string.dialog_writeNumber).show();
        }
    }
}
```

```xml:border.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="3dp"
        android:color="#555"></stroke>
    <corners android:radius="5dp"></corners>
</shape>
```

```xml:activity_game.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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="6"
    tools:context=".GameActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1.4"
        android:gravity="center_horizontal|center_vertical"
        android:orientation="vertical"
        android:weightSum="3">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="@string/text_back"
                android:textSize="24sp"
                android:onClick="tapBack"></TextView>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="right"
                android:text="@string/text_clearTime"
                android:textSize="24sp"></TextView>

            <TextView
                android:id="@+id/text_clearTime"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="00:00.000"
                android:textSize="24sp"></TextView>
        </LinearLayout>

        <TextView
            android:id="@+id/text_clear"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="2"
            android:gravity="center"
            android:textSize="36sp"
            android:textStyle="bold"></TextView>


    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:layout_weight="0.6"
        android:onClick="tapRestart"
        android:text="@string/btn_update"></Button>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="4"
        android:orientation="vertical"
        android:id="@+id/linearlayout_gameScreen">

    </LinearLayout>

</LinearLayout>
```

```java:GameActivity.java
package com.example.puzzleapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Locale;

public class GameActivity extends AppCompatActivity {

    TextView clearTime, clearText;
    Handler handler;
    Runnable runnable;
    long startTime, elapsedTime;
    int shuffleTimes;
    int rowSize, colSize, tmp, n, m;
    LinearLayout gameScreen;
    TextView[] box;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

        clearText = findViewById(R.id.text_clear);
        clearTime = findViewById(R.id.text_clearTime);
        gameScreen = findViewById(R.id.linearlayout_gameScreen);
        rowSize = getIntent().getIntExtra("row", 0);
        colSize = getIntent().getIntExtra("col", 0);
        gameScreen.setWeightSum(rowSize);
        box = new TextView[rowSize * colSize];
        tmp = 0;
        shuffleTimes = rowSize * colSize * 2;

//        パズルを生成
        for (int i = 0; i < rowSize; i++) {
            LinearLayout linearLayout = new LinearLayout(GameActivity.this);
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            linearLayout.setWeightSum(colSize);
            linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 1));
            for (int j = 0; j < colSize; j++) {
                box[tmp] = new TextView(GameActivity.this);
                box[tmp].setText(String.valueOf(tmp + 1));
                box[tmp].setTextSize(100 / colSize);
                box[tmp].setGravity(Gravity.CENTER);
                box[tmp].setClickable(true);
                box[tmp].setOnClickListener(new View.OnClickListener() {
                    int i = tmp;

                    @Override
                    public void onClick(View v) {
                        checkMove(i);
                    }
                });
                box[tmp].setBackgroundResource(R.drawable.border);
                box[tmp].setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1));
                if (tmp + 1 == colSize * rowSize) {
                    box[tmp].setText("");
                }
                linearLayout.addView(box[tmp]);
                tmp++;
            }
            gameScreen.addView(linearLayout);
        }
    }

    public void tapBack(View view) {
        Intent intent = new Intent(GameActivity.this, SettingActivity.class);
        startActivity(intent);
    }

    public void onTimer() {
//        タイマー起動
        handler = new Handler();
        startTime = System.currentTimeMillis();
        runnable = new Runnable() {
            @Override
            public void run() {
                elapsedTime = System.currentTimeMillis() - startTime;
                SimpleDateFormat sdf = new SimpleDateFormat("mm:ss.SSS", Locale.US);
                clearTime.setText(sdf.format(elapsedTime));
                handler.removeCallbacks(runnable);
                handler.postDelayed(runnable, 10);
            }
        };
        handler.postDelayed(runnable, 10);
    }

    public void stopTimer() {
//        タイマーストップ
        handler.removeCallbacks(runnable);
    }

    public void tapRestart(View view) {
        onTimer();
        shuffle();
        clearText.setText("");
        for (int i = 0; i < box.length; i++) {
            box[i].setEnabled(true);
        }
    }

    public void move(TextView text1, TextView text2) {
        text2.setText(text1.getText().toString());
        text1.setText("");
    }

    public void checkMove(int i) {
//        数字の移動処理
        if ((i % colSize != 0) && (box[i - 1].getText().toString().length() == 0)) {
            move(box[i], box[i - 1]);
        } else if ((i % colSize != colSize - 1) && (box[i + 1].getText().toString().length() == 0)) {
            move(box[i], box[i + 1]);
        } else if ((i >= colSize) && (box[i - colSize].getText().toString().length() == 0)) {
            move(box[i], box[i - colSize]);
        } else if ((i < (colSize * rowSize - colSize)) && (box[i + colSize].getText().toString().length() == 0)) {
            move(box[i], box[i + colSize]);
        }
        if (clearCheck()) {
            clearText.setText("CLEAR!!");
            stopTimer();
            for (int j = 0; j < box.length; j++) {
                box[j].setEnabled(false);
            }
        }
    }

    public void shuffle() {
//        数字をシャッフル
        String tmp;
        for (int i = 0; i < shuffleTimes; i++) {
            n = (int) Math.floor(Math.random() * (box.length - 1));
            m = (int) Math.floor(Math.random() * (box.length - 1));
            if (n != m) {
                tmp = box[n].getText().toString();
                box[n].setText(box[m].getText().toString());
                box[m].setText(tmp);
            } else {
                i--;
            }
        }
    }

    public boolean clearCheck() {
        for (int i = 0; i < box.length - 1; i++) {
            if (box[i].getText().toString() != String.valueOf(i + 1)) {
                return false;
            }
        }
        return true;
    }
}
```


YouTubeに作っている動画をアップしています。
https://www.youtube.com/watch?v=0PdvGG9uXR4&list=PLhg2PHSq8bjiTy1pNH8GeNlaPq82wVC4k
以上。