2 minute read

안드로이드를 사용해 숫자 맞추기 게임을 만들어 보도록 하겠습니다.

📜숫자 맞추기 게임이란


사용자가 숫자를 입력하고 버튼을 눌러 랜덤으로 지정된 정답 숫자를 맞추는 게임입니다. 만약 숫자가 정답보다 작거나 크다면 그에 따른 텍스트가 나오며 정답일 경우에는 정답이라는 텍스트가 나오는 간단한 게임입니다.


📜구성


컴포넌트 트리는 아래와 같습니다. image

ConstraintLayout에 정답을 예측하는 Button, 어플을 꾸며줄 imageView, 2개의 textView와 숫자를 입력할 수 있는 Number text로 구성되어 있습니다.


image

ImageView를 사용해 이미지를 배치했습니다.


image

Textview를 사용해 ‘숫자 입력’ 텍스트를 배치하고, EditText를 사용해 입력 받을 수 있도록 하였습니다. 숫자를 입력하고 누르는 ‘GUESSING’버튼은 Button을 사용해 만들었고, 정답 여부를 알려주는 Text역시 Textview를 사용하였으며, 초기값은 ’Good luck’으로 지정하였습니다.


📜설명


//변수 선언
    Button btn1; //추측 버튼
    TextView result; //입력값에 따른 결과
    EditText num1; //입력 값
    int answer = 0; //정답 값

변수를 선언해 줍니다.

//id값을 가져와 연결
        btn1 = (Button)findViewById(R.id.btn1);
        num1 = (EditText) findViewById(R.id.num1);
        result = (TextView)findViewById(R.id.result);

그리고 id값을 가져와 연결합니다.

//1부터 100사이의 수를 랜덤으로 지정
        answer = new Random().nextInt(100)+1;

answer은 정답을 나타내는 변수로, 프로그램을 실행시킬 때마다 랜덤함수를 통해 정답을 지정합니다. 정답이 될 수 있는 수의 범위는 1부터 100까지의 수 중 하나인데, nextInt(100)은 0부터 99까지를 나타내므로 1을 더해 1부터 100까지 나타낼 수 있습니다.

btn1.setOnClickListener((new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = num1.getText().toString().trim(); //문자열 가져옴
                int num2 = Integer.parseInt(str); //정수형 값 가져옴
                //만약 정답과 입력값이 같다면 정답 출력
                if (answer == num2){
                    result.setText("정답!");
                }
                //만약 정답이 입력값보다 크다면 High출력
                else if (answer > num2){
                    result.setText("High!");
                }
                //만약 정답이 입력값보다 작다면 Low출력
                else if (answer < num2){
                    result.setText("Low!");
                }
            }
        }));

btn1.setOnClickListener((new View.OnClickListener() 는 btn1을 클릭했을 때, 처리되는 이벤트입니다. 변수 str은 getText()를 통해 num1변수의 문자열을 가져와 저장한 문자열 변수이고, num2는 str의 정수형 값을 가져와 저장한 정수형 변수입니다.

정답확인은 if - else문을 통해 할 수 있습니다.

1. 만약 answer(정답)과 num2(입력한 수)가 같다면 Textview인 변수result의 값이 ‘정답!’으로 설정됩니다.

2. 만약 answer(정답)이 num2(입력한 수)보다 크다면 Textview인 변수result의 값이 ‘High!’으로 설정됩니다.

3. 만약 answer(정답)이 num2(입력한 수)보다 작다면 Textview인 변수result의 값이 ‘Low!’으로 설정됩니다.

📜결과


image

image

📜코드


package com.example.guessinggame;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    //변수 선언
    Button btn1; //추측 버튼
    TextView result; //입력값에 따른 결과
    EditText num1; //입력 값
    int answer = 0; //정답 값

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

        //id값을 가져와 연결
        btn1 = (Button)findViewById(R.id.btn1);
        num1 = (EditText) findViewById(R.id.num1);
        result = (TextView)findViewById(R.id.result);
        //1부터 100사이의 수를 랜덤으로 지정
        answer = new Random().nextInt(100)+1;

        btn1.setOnClickListener((new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = num1.getText().toString().trim(); //문자열 가져옴
                int num2 = Integer.parseInt(str); //정수형 값 가져옴
                //만약 정답과 입력값이 같다면 정답 출력
                if (answer == num2){
                    result.setText("정답!");
                }
                //만약 정답이 입력값보다 크다면 High출력
                else if (answer > num2){
                    result.setText("High!");
                }
                //만약 정답이 입력값보다 작다면 Low출력
                else if (answer < num2){
                    result.setText("Low!");
                }
            }
        }));
    }
}