본문 바로가기

[UE4 지뢰찾기] 지뢰 매설하기

Kwonriver 2022. 11. 30.
728x90

 

간단하게 지뢰를 매설하고 근처 지뢰 갯수를 세팅하는 함수를 만든다.

 

void ABoard::CreateBoard(int32 row, int32 column, int32 mineCount)
{
	int32 nInitMineCount = 0;
	FVector OriginLocation = GetActorLocation();
	float x, y;

	this->Row = row;
	this->Column = column;
	this->TotalMineCount = mineCount;

	for (int i = 0; i < row; i++)
	{
		TArray<ATile*> RowArray;
		y = OriginLocation.Z - i * 100;

		for (int j = 0; j < column; j++)
		{
			ATile* tile = (ATile*)GetWorld()->SpawnActor(ATile::StaticClass());
			if (tile)
			{
				x = OriginLocation.Y + j * 100;

				tile->SetActorLocation(FVector(-500, x-395, y+395));
				ChangeTileMesh(tile);

				RowArray.Emplace(tile);

				UE_LOG(LogTemp, Warning, TEXT("Row: %d, Column : %d"), i, j);
				UE_LOG(LogTemp, Warning, TEXT("x: %f, y : %f"), x, y);
			}
		}

		TileMap.Add(RowArray);
	}
	
	// 지뢰 매설하기
	SetBoardTileMine();

	// 주변 지뢰 갯수 찾기
	SetBoardTileNearMine();
}

 

일전에 만들었던 ABoard의 보드 생성함수이다.

지뢰 매설하는 함수로 SetBoardTileMine함수를 만들었으며 주변 지뢰 갯수를 찾는 함수로 SetBoardTileNearMine() 함수를 제작하였음.

 

void ABoard::SetBoardTileMine()
{
	int nMineCount = 0;

	while (nMineCount < this->TotalMineCount)
	{
		int TempRow = FMath::FRandRange(0, this->Row);
		int TempColumn = FMath::FRandRange(0, this->Column);

		auto tile = GetTileAt(TempRow, TempColumn);
		if (tile == nullptr)
			continue;

		if (tile->GetTilehasMine() == false)
		{
			tile->SetTileHasMine(true);
			nMineCount++;
		}
	}
}

 

FMath::FRandRange함수를 이용하여 랜덤으로 타일 하나를 선택함.

선택받은 타일이 정상적인 타일이고 지뢰가 아니라면 해당 타일을 지뢰로 변경함

이러한 연산을 지뢰 갯수가 게임 시작 시 설정한 지뢰 갯수 만큼 되도록 while로 반복함

 

void ABoard::SetBoardTileNearMine()
{
	// 타일의 주변 지뢰 숫자 세팅
	for (int i = 0; i < this->Row; i++)
	{
		for (int j = 0; j < this->Column; j++)
		{
			ATile* tile = GetTileAt(i, j);
			if (tile == nullptr)
				continue;

			tile->SetNearMineCount(GetNearMineCountAt(i, j));
		}
	}
}

int32 ABoard::GetNearMineCountAt(int x, int y)
{
	int32 nNearMineCount = 0;
	int8 nXArray[8] = { -1, 1, 0, 0, -1, -1, 1, 1 };
	int8 nYArray[8] = { 0, 0, -1, 1, -1, 1, -1, 1 };

	for (int i = 0; i < 8; i++)
	{
		auto tile = GetTileAt(x + nXArray[i], y + nYArray[i]);
		if (tile == nullptr)
			continue;

		if (tile->GetTilehasMine() == true)
			nNearMineCount++;
	}

	return nNearMineCount;
}

 

주변 지뢰 찾는 함수는 상, 하, 좌, 우, 좌상, 우상, 좌하, 우하 총 8방향을 찾는 연산을 진행

nXArray와 nYArry에 -1,0,1을 이용하여 위상을 설정함

아래 for에서 특정 위치의 주변 타일 지뢰를 확인하고 주변 지뢰 갯수를 저장한 뒤 반환함

반환된 갯수를 Tile에 세팅함.

728x90