코딩메모

팀 스파르타 4주차 코딩메모

WMG1 2022. 9. 30. 00:13
반응형

gameManager.cs

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; // UI엔진 업데이트
using System.Linq;

public class gameManager : MonoBehaviour
{
    public Text timeTxt; // 외부에서 텍스트 타입의 '타임텍스트' 요청
    public GameObject card; // 외부에서 게임 오브젝트 '카드' 요청
    float time; // 소수점 타임 선언
    public static gameManager I; // 싱글톤화
    public GameObject firstCard; // 두가지를 비교하기 위해 F카드와 S카드를 알려줌
    public GameObject secondCard; // 
    public GameObject endTxt;

    private void Awake()
    {
        I = this;
    }
    // Start is called before the first frame update
    void Start()
    {
        Time.timeScale = 1f;
        int[] rtans = { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7 }; // 정수값 모음인 "르탄" {0.....}
        rtans = rtans.OrderBy(item => Random.Range(-1.0f, 1.0f)).ToArray(); // OrderBy(정렬하겠다) item(요소를) 랜덤한 순서로(-1~1사이의)Toarray(리스트의)

        for (int i = 0; i < 16; i++) // 반복임무 부여(정수 값i는 0이다 / i가 16보다 작다면 / i에 1을 더해준다) 
        {
            
            GameObject newCard = Instantiate(card); //게임오브젝트 "뉴카드" 는 필요할때마다 실시간으로 만든다 "카드"를
            newCard.transform.parent = GameObject.Find("cards").transform; // 뉴카드의 부모값은 = 게임오브젝트 "카드s" 를 찾아서 그것으로 만들어라

            float x = (i / 4) * 1.4f - 2.1f; // x값은 i를 4로 나눈값에 1.4를 곱하고 2.1f만큼 뺀다
            float y = (i % 4) * 1.4f - 3.0f; // y값은 i를 4로 나눈 나머지값에 1.4를 곱하고 3.0f만큼 뺀다
            newCard.transform.position = new Vector3(x, y, 0); // "뉴카드"의 위치값은 새로운 위치값 백터3(x,y,0)을 가진다

            string rtanName = "rtan" + rtans[i].ToString(); //문자값 르탄네임은 르탄에다가 르탄스의 i번째숫자를 불러와서 문자로 바꾼 뒤 합친다
            newCard.transform.Find("front").GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>(rtanName);
            //뉴카드의 프론트를 찾아서 그 프론트의 스프라이트 이미지를 르탄네임으로 바꿔달라
        }
    }

    // Update is called once per frame
    void Update()
    {
        time += Time.deltaTime; // 매 시간마다 타임에 타임.델타타임을 더해줘라(시간 흐르게 설정)
        timeTxt.text = time.ToString("N2"); // 타임 텍스트에 = 타임에 투스트링 값을 소수점2째자리까지 표기 (타임 텍스트에 타임의 변경사항을 적용)
        if(time >= 30.0f) // time이 30초보다 같거나 커지면
        {
            gameManager.I.GameEnd(); //게임매니저의 gameend함수를 불러온다
        }
        //팀 스파르타 답안
        //if (time > 30.0f)
        // {
        //     endTxt.SetActive(true);
        //    Time.timeScale = 0.0f;
        // }
    }
    public void isMatched()
    {
        string firstCardImages = firstCard.transform.Find("front").GetComponent<SpriteRenderer>().sprite.name; 
        // 퍼스트카드 이미지라는것은 퍼스트카드의 프론트를 찾아서 그것의 스프라이트 랜더러의 스프라이트 이름을 가져오는것
        string secondCardImages = secondCard.transform.Find("front").GetComponent<SpriteRenderer>().sprite.name;
        //위와 같음

        if(firstCardImages == secondCardImages) // 만약 첫카드와 두번째카드가 같다면
        {
            firstCard.GetComponent<card>().destroyCard(); // 첫번째 카드의 카드스크립트를 가져와서 destroyCard 함수를 실행시킴
            secondCard.GetComponent<card>().destroyCard();

            int cardLeft = GameObject.Find("cards").transform.childCount; // 정수 "카드레프트"는  카드를 찾아 트랜스폼을 가져와서 차일드카운드가 몇개인지 알아본다
            if (cardLeft == 2)
            {
                // 종료시키자!
                Time.timeScale = 0f;
                endTxt.SetActive(true);
                //Invoke("GameEnd", 1.0f); 게임종료 1초 지연 
            }
        }
        else
        {
            firstCard.GetComponent<card>().closeCard(); // 첫번째 카드의 카드스크립트를 가져와서 closeCard 함수를 실행시킴
            secondCard.GetComponent<card>().closeCard();
        }

        firstCard = null; //매칭이 끝났으면 게임매니저의 손을 비워준다 // 안비워주면 게임매니저가 계속 secondCard만 인식할것이므로
        secondCard = null;
    }

    void GameEnd()
    {
        Time.timeScale = 0f;
        endTxt.SetActive(true);
    }
}

 


 

 

card.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class card : MonoBehaviour
{
    public Animator anim;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void openCard()
    {
        anim.SetBool("isOpen", true); // 애님에 포함된 isopen의 참거짓값을 참으로 설정 
        transform.Find("front").gameObject.SetActive(true); // 트랜스폼에게 프론트 찾게하고 // 프론트의 게임오브젝트를 가지고와서 참 상태로 만듬

        transform.Find("back").gameObject.SetActive(false); // 트랜스폼에게 백 찾게하고 // 프론트의 게임오브젝트를 가지고와서 거짓 상태로 만듬
        //Animator isOpen = true
        //front SetActive = true
        //Back SetActive = False

        if (gameManager.I.firstCard == null ) // 만약 카드가 열렸을 때 / 게임매니저의 첫번째 카드 란이 공란이면
        {
            gameManager.I.firstCard = gameObject; // 지금 열린카드가 첫번째 카드다
        }
        else
        {
            gameManager.I.secondCard = gameObject; // 게임 매니저가 첫번째 카드를 아는 경우는 / 지금 카드가 두번째 카드다
            gameManager.I.isMatched();  // 게임매니저에게 isMatched 함수 요청
        }
    }

    public void destroyCard() // 외부호출 (여기선 게임매니저가 부르는함수) /
    {
        Invoke("destroyCardInvoke", 1.0f); // 부른다 1초뒤에 해당 함수를
    }

    void destroyCardInvoke() // 카드 부수기
    {
        Destroy(gameObject);
    }

    public void closeCard() // 외부호출 (여기선 게임매니저가 부르는함수) /
    {
        Invoke("closeCardInvoke", 1.0f);
    }

    void closeCardInvoke() // 카드덮기
    {
        anim.SetBool("isOpen", false); // 애니매이션 참거짓함수 isopen 거짓으로 변경
        transform.Find("back").gameObject.SetActive(true); //back의 상태값을 참으로
        transform.Find("front").gameObject.SetActive(false); //front의 상태값을 거짓으로
    }
}

 

 


 

 

endTxt.cs

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class endTxt : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void ReGame()
    {
        SceneManager.LoadScene("MainScene");
    }
}

반응형