using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
// 게임의 상태를 정의하는 열거형 (Intro, Playing, Dead 세 가지 상태)
public enum GameState {
Intro, // 게임 시작 전 상태
Playing, // 게임 진행 중 상태
Dead // 플레이어 사망 상태
}
public class GameManager : MonoBehaviour
{
// Singleton 패턴으로 GameManager 인스턴스를 관리
public static GameManager Instance;
// 현재 게임 상태 저장
public GameState State = GameState.Intro;
// 게임 시작 시간 및 플레이어의 목숨 수
public float PlayStartTime;
public int lives = 3;
[Header("References")] // Unity Inspector에서 섹션 구분
public GameObject IntroUI; // 게임 시작 화면 UI
public GameObject DeadUI; // 사망 후 화면 UI
public GameObject EnemySpawner; // 적 스포너
public GameObject FoodSpawner; // 음식 스포너
public GameObject GoldenSpawner; // 황금 아이템 스포너
public Player PlayerScript; // 플레이어 스크립트
public TMP_Text scoreText; // 점수 및 UI 텍스트
private void Awake() {
// Singleton 초기화
if (Instance == null){
Instance = this;
}
}
void Start()
{
// 게임 시작 시 Intro UI 활성화
IntroUI.SetActive(true);
}
// 현재 점수를 계산하는 함수 (게임 시작 후 경과 시간)
float CalculateScore() {
return Time.time - PlayStartTime;
}
// 최고 점수를 저장하는 함수
void SavehighScore() {
int score = Mathf.FloorToInt(CalculateScore()); // 현재 점수를 정수로 변환
int currentHighScore = PlayerPrefs.GetInt("highScore"); // 기존 최고 점수 가져오기
// 새로운 점수가 기존 점수보다 높으면 갱신
if (score > currentHighScore) {
PlayerPrefs.SetInt("highScore", score);
PlayerPrefs.Save();
}
}
// 저장된 최고 점수를 가져오는 함수
int GetHighScore() {
return PlayerPrefs.GetInt("highScore");
}
// 게임 진행 속도를 계산하는 함수 (시간이 지남에 따라 속도가 빨라짐)
public float CalculateGameSpeed() {
if (State != GameState.Playing) {
return 5f; // 게임이 진행 중이 아니면 기본 속도 반환
}
// 경과 시간에 비례하여 속도 증가 (최대 30f로 제한)
float speed = 8f + (0.5f * Mathf.Floor(CalculateScore() / 10f));
return Mathf.Min(speed, 30f);
}
void Update()
{
// 게임 상태에 따라 UI를 업데이트
if (State == GameState.Playing) {
scoreText.text = "Score: " + Mathf.FloorToInt(CalculateScore());
} else if (State == GameState.Dead) {
scoreText.text = "High Score: " + GetHighScore();
}
// Intro 상태에서 스페이스바를 누르면 게임 시작
if (State == GameState.Intro && Input.GetKeyDown(KeyCode.Space)) {
State = GameState.Playing;
IntroUI.SetActive(false); // Intro UI 비활성화
EnemySpawner.SetActive(true); // 적 스포너 활성화
FoodSpawner.SetActive(true); // 음식 스포너 활성화
GoldenSpawner.SetActive(true); // 황금 스포너 활성화
PlayStartTime = Time.time; // 게임 시작 시간 기록
}
// Playing 상태에서 목숨이 0이 되면 게임 오버 처리
if (State == GameState.Playing && lives == 0) {
PlayerScript.KillPlayer(); // 플레이어 사망 처리
EnemySpawner.SetActive(false); // 모든 스포너 비활성화
FoodSpawner.SetActive(false);
GoldenSpawner.SetActive(false);
DeadUI.SetActive(true); // Dead UI 활성화
Transform startButton = DeadUI.transform.Find("start_button");
if (startButton != null)
{
startButton.gameObject.SetActive(true); // start_button만 활성화
}
State = GameState.Dead; // 상태를 Dead로 변경
SavehighScore(); // 최고 점수 저장
}
// Dead 상태에서 스페이스바를 누르면 게임 재시작
if (State == GameState.Dead && Input.GetKeyDown(KeyCode.Space)) {
SceneManager.LoadScene("SampleScene"); // 현재 씬 재로딩
}
}
}