c언어 기초

c언어 포인터, pointer 프로젝트, 물고기 키우기 - 나도코딩

preferrrr 2022. 5. 31. 15:56

물고기들이 어항에 있고 어항의 물은 일정 시간마다 계속 줄어든다. 물고기를 선택하면 물이 조금씩 차는데 시간이 지날 수록 물이 줄어드는 속도는 빨라진다. 어항들의 물이 모두 사라지지 않도록 물고기들을 최대한 빨리 선택해라

 

#include <stdio.h>
#include <time.h>

int level;
int arrayFish[6];
int *cursor;

void initData();
void printfFishes();
void decreaseWater(long elapsedTime);
//int checkFishAlive();



int main_6_2project(void)
{
	long startTime = 0; // 게임 시작 시간
	long totalElapsedTIme = 0; // 총 경과 시간
	long prevElapsedTime = 0; // 직전 경과 시간 (최근에 물을 준 시간 간격)

	int num; // 어항에 몇번 물을 줄 것인지, 사용자 입력
	initData();

	cursor = arrayFish; // arrayFish는 배열이니까 arrayFish 앞에 & 붙여줄 필요 없다

	startTime = clock(); // 현재 시간을 millisecond (1000분의 1초) 단위로 반환
	while (1)
	{
		printfFishes();
		printf("몇 번 어항에 물을 주시겠어요? ");
		scanf_s("%d", &num);

		//입력값 체크
		if (num < 1 || num > 6)
		{
			printf("\n입력값이 잘못되었습니다\n");
			continue;
		}

		// 총 경과 시간
		totalElapsedTIme = (clock() - startTime) / CLOCKS_PER_SEC;
		printf("총 경과 시간 : %d 초\n", totalElapsedTIme);

		// 직전 물 준 시간 (마지막으로 물 준 시간) 이후로 흐른 시간
		prevElapsedTime = totalElapsedTIme = prevElapsedTime;
		printf("최근 경과 시간 : %ld 초\n", prevElapsedTime);

		// 어항의 물을 감소 (증발)
		decreaseWater(prevElapsedTime);

		// 사용자가 입력한 어항에 물을 준다
		// 1 어항의 물이 0이면? 물을 주지 않는다. 이미 죽어있으니
		if (cursor[num - 1] <= 0)
		{
			printf("%d 번 물고기는 이미 죽음. 물을 주지 않습니다\n", num);
		}
		// 2 어항의 물이 0이 아닌 경우? 물을 준다 ! 100을 넘지 않는지 체크
		else if (cursor[num - 1] + 1 <= 100)
		{
			//물을 준다
			printf("%d 번 어항에 물을 줍니다\n\n", num);
			cursor[num - 1] += 1; 
		}

		// 레벨업을 할 건지 확인 ( 레벨업ㅇㄴ 20초마다 한번씩 수행)
		if (totalElapsedTIme / 20 > level - 1)
		{
			// 레벨업
			level++;
			printf(" *** 축 레벨업 ! 기존 %d 레벨에서 %d레벨로 업그레이드 ***\n\n", level - 1, level);

			// 최종 레벨 5
			if (level == 5)
			{
				printf("\n\n축하합니다. 최고 레벨을 달성하였습니다. 게임을 종료합니다.");
				exit(0);
			}
		}
		// 모든 물고기가 죽었는지 확인
		if (checkFishAlive() == 0)
		{
			// 물고기 모두 죽음
			printf("모든 물고기가 죽었습니다\n");
			exit(0);
		}
		else
		{
			// 최소 한마리 이상의 물고기는 살아있음
			printf("물고기가 아직 살아있어요 !\n");
		}
		prevElapsedTime = totalElapsedTIme;
	}

	return 0;
}



void initData()
{
	level = 1; // 게임 레벨 (1-5)
	for (int i = 0; i < 6; i++)
	{
		arrayFish[i] = 100; // 어항의 물 높이 (0-100)
	}
}

void printfFishes()
{
	printf("%3d번 %3d번 %3d번 %3d번 %3d번 %3d번\n", 1, 2, 3, 4, 5, 6);
	for (int i = 0; i < 6; i++)
	{
		printf(" %4d ", arrayFish[i]);
	}
	printf("\n\n");
}

void decreaseWater(long elapsedTime)
{
	for (int i = 0; i < 6; i++)
	{
		arrayFish[i] -= (level * 3 * (int)elapsedTime);
		if (arrayFish[i] < 0)
		{
			arrayFish[i] = 0;
		}
	}
}

int checkFishAlive()
{
	for (int i = 0; i < 6; i++)
	{
		if (arrayFish[i] > 0)
			return 1; // 참 True
	}
	return 0;
}