Android Studio + Kotlinで簡単なじゃんけんゲームを作る

前置き

自社待機期間もあと2日。 1カ月くらい前に作成してGooglePlayにアップして満足してた アプリを復習として作り方書いておく。アップしたアプリは下記。

5回先取じゃんけん - Apps on Google Play

GitHub - n-yata/RockPaperScissors

まずはプロジェクト作成

New ProjectからEmpty Activityを選択し『Next』ボダン
f:id:n-yata:20201228131408p:plain

アプリ名を適当に入力、Minimum SDKはAPI16にした。 (ここの設定でAndroid OSのバージョンどこまで対応するかを指定する)
f:id:n-yata:20201228131402p:plain

『Finish』ボタン押してビルド終わるまで少し待つ。 下記の画面が出たらプロジェクト作成完了。
f:id:n-yata:20201228132059p:plain

build.gradleの編集

下記の画像の通り、build.gradle(:app)の修正する。 pluginsの中に『id 'kotlin-android-extensions'』を追記し 『Sync Now』を押す
f:id:n-yata:20201228132528p:plain

画像をダウンロードして配置

じゃんけんグー・チョキ・パーの画像をフリー画像から好きなのダウンロード。 自分は下記URLから使用させてもらった。
じゃんけんのイラスト「グー・チョキ・パー」 | かわいいフリー素材集 いらすとや

画像の配置先は下記の通り。
f:id:n-yata:20201228133239p:plain

画面のレイアウトを作る

string.xmlで画面上で使用する文字を定義しとく
f:id:n-yata:20201228134456p:plain

<resources>
    <string name="app_name">5回先取じゃんけん</string>
    <string name="win_text">勝ち</string>
    <string name="lose_text">負け</string>
    <string name="gu_text">グー</string>
    <string name="choki_text">チョキ</string>
    <string name="pa_text">パー</string>
    <string name="reset_text">最初からやりなおす</string>
    <string name="yourHand_text">あなた</string>
    <string name="androidHand_text">相手</string>
</resources>

画面レイアウトはactivity_main.xmlを編集する。 f:id:n-yata:20201228133806p:plain

記載したXMLは下記のとおり。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/winText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="68dp"
        android:layout_marginLeft="68dp"
        android:layout_marginTop="16dp"
        android:text="@string/win_text"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/loseText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="64dp"
        android:layout_marginRight="64dp"
        android:text="@string/lose_text"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/guBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginBottom="100dp"
        android:text="@string/gu_text"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/chokiBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginEnd="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="30dp"
        android:text="@string/choki_text"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toTopOf="@+id/resetBtn"
        app:layout_constraintEnd_toStartOf="@+id/paBtn"
        app:layout_constraintStart_toEndOf="@+id/guBtn" />

    <Button
        android:id="@+id/paBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="32dp"
        android:layout_marginRight="32dp"
        android:layout_marginBottom="100dp"
        android:text="@string/pa_text"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <Button
        android:id="@+id/resetBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:text="@string/reset_text"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:backgroundTint="@android:color/holo_blue_dark"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <ImageView
        android:id="@+id/yourHandImage"
        android:layout_width="140dp"
        android:layout_height="180dp"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="150dp"
        app:layout_constraintBottom_toTopOf="@+id/guBtn"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/winText"
        app:srcCompat="@drawable/janken_gu" />

    <ImageView
        android:id="@+id/droidHandImage"
        android:layout_width="140dp"
        android:layout_height="180dp"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="150dp"
        app:layout_constraintBottom_toTopOf="@+id/paBtn"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/yourHandImage"
        app:layout_constraintTop_toBottomOf="@+id/loseText"
        app:srcCompat="@drawable/janken_gu" />

    <TextView
        android:id="@+id/resultText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="76dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:gravity="center_horizontal"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/yourHandText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="80dp"
        android:layout_marginLeft="80dp"
        android:text="@string/yourHand_text"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        app:layout_constraintBottom_toTopOf="@+id/yourHandImage"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/androidHandText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="80dp"
        android:layout_marginRight="80dp"
        android:text="@string/androidHand_text"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        app:layout_constraintBottom_toTopOf="@+id/droidHandImage"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

本来はデザインビューでいろいろ調整しながらだけど割愛。
公式のチュートリアルがすごくわかりやすかったです。
初めてのアプリを作成する  |  Android デベロッパー  |  Android Developers

Kotlinで処理を書いてく

1画面だけの簡単なアプリなので編集するのはMainActivityのみ。
f:id:n-yata:20201228134852p:plain

package com.nyata.rockpaperscissors

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private var yourHand = 0
    private var droidHand = 0
    private var winCount = 0
    private var loseCount = 0
    private var gameStart = false

    /**
     * アクティビティ生成時の処理
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        guBtn.setOnClickListener{
            if(gameStart) {
                yourHand = 0
                compareHand()
            }
        }

        chokiBtn.setOnClickListener{
            if(gameStart) {
                yourHand = 1
                compareHand()
            }
        }

        paBtn.setOnClickListener{
            if(gameStart) {
                yourHand = 2
                compareHand()
            }
        }

        resetBtn.setOnClickListener{
            onResume()
        }
    }

    /**
     * ユーザーの操作受付処理
     */
    override fun onResume() {
        super.onResume()
        winCount = 0
        loseCount = 0
        winText.text = getString(R.string.win_text)
        loseText.text = getString(R.string.lose_text)
        resultText.text = "じゃんけん"

        // ゲーム開始状態にする
        gameStart = true
        // リセットボタンを非表示
        resetBtn.visibility = View.INVISIBLE

    }

    /**
     * 自分とCPUの手の比較をする
     */
    private fun compareHand(){
        resultText.text = "ぽん!"
        // CPUの手をランダムで決定
        droidHand = (0..2).random()
        // 画面にイメージを表示する
        showHand()

        when(yourHand){
            // グー
            0 -> {
                if(droidHand == 0){
                    // do nothing
                }else if(droidHand == 1){
                    winCount++
                    winText.text = getString(R.string.win_text) + winCount
                }else if(droidHand == 2){
                    loseCount++
                    loseText.text = getString(R.string.lose_text) + loseCount
                }
            }
            // チョキ
            1 -> {
                if(droidHand == 0){
                    loseCount++
                    loseText.text = getString(R.string.lose_text) + loseCount
                }else if(droidHand == 1){
                    // do nothing
                }else if(droidHand == 2){
                    winCount++
                    winText.text = getString(R.string.win_text) + winCount
                }
            }
            // パー
            2 -> {
                if(droidHand == 0){
                    winCount++
                    winText.text = getString(R.string.win_text) + winCount
                }else if(droidHand == 1){
                    loseCount++
                    loseText.text = getString(R.string.lose_text) + loseCount
                }else if(droidHand == 2){
                    // do nothing
                }
            }
        }

        if(winCount == 5){
            resultText.text = "あなたの勝ちです!"
            gameStart = false
            resetBtn.visibility = View.VISIBLE
        }else if(loseCount == 5){
            resultText.text = "あなたの負けです・・・"
            gameStart = false
            resetBtn.visibility = View.VISIBLE
        }else{
            // do nothing
        }
    }

    private fun showHand(){
        when(yourHand){
            0 -> yourHandImage.setImageResource(R.drawable.janken_gu)
            1 -> yourHandImage.setImageResource(R.drawable.janken_choki)
            2 -> yourHandImage.setImageResource(R.drawable.janken_pa)
        }

        when(droidHand){
            0 -> droidHandImage.setImageResource(R.drawable.janken_gu)
            1 -> droidHandImage.setImageResource(R.drawable.janken_choki)
            2 -> droidHandImage.setImageResource(R.drawable.janken_pa)
        }
    }
}

参考にした本は下記。

www.shoeisha.co.jp