텍스트 카드 짝 맞추기 게임

공재원
∙∙조회 6

나와 팀원이 작성한 카드 짝 맞추기 게임

csharp
using System;
using System.Text;
using System.Threading;

Title();

int[] cardBoard = new int[16];
bool[] isOpened = new bool[16];

const int K_COL = 4;
const int MAX = 20;

bool gameStart = false;
Console.Write("게임을 시작하시겠습니까?: ");
string startCommand = Console.ReadLine();

if (startCommand == "Y")
{
    gameStart = true;
}

Console.Clear();
Console.Write("=== 카드 섞는 중 ===");
Thread.Sleep(1000);
Console.Clear();

string command = string.Empty;

int tryCount = 0;
int correctCount = 0;

while (gameStart)
{
    Title();
    DataBoard(cardBoard);
    isOpened = new bool[cardBoard.Length];

    tryCount = 0;
    correctCount = 0;

    do
    {
        ViewBoard(cardBoard, isOpened);
        Console.Write("첫번째 카드 행,열: ");
        command = Console.ReadLine();
        string[] firstParts = command.Split(','); 
        int row = int.Parse(firstParts[0].Trim()) - 1;
        int col = int.Parse(firstParts[1].Trim()) - 1;
        int firstIndex = row * K_COL + col;

        if (isOpened[firstIndex])
        {
            Console.WriteLine("갈!!!!");
            Thread.Sleep(1000);
            continue;
        }

        isOpened[firstIndex] = true;
        ViewBoard(cardBoard, isOpened);

        Console.Write("두번째 카드 행, 열: ");
        command = Console.ReadLine();
        string[] secondParts = command.Split(",");
        row = int.Parse(secondParts[0].Trim()) - 1;
        col = int.Parse(secondParts[1].Trim()) - 1;
        int secondIndex = row * K_COL + col;

        if (isOpened[secondIndex])
        {
            Console.WriteLine("갈!!!!");
            Thread.Sleep(1000);
            isOpened[firstIndex] = false;
            continue;
        }

        isOpened[secondIndex] = true;
        
        if (cardBoard[firstIndex] == cardBoard[secondIndex]) correctCount++;
        tryCount++;
        ViewBoard(cardBoard, isOpened);

        if (cardBoard[firstIndex] != cardBoard[secondIndex])
        {
            isOpened[firstIndex] = false;
            isOpened[secondIndex] = false;
            Console.WriteLine("안타깝네요.");
        }
        else if (cardBoard[firstIndex] == cardBoard[secondIndex])
        {
            Console.WriteLine("축하드립니다.");
        }
        Thread.Sleep(1000);
    } while (tryCount <= MAX && correctCount < 8);
    Console.WriteLine($"=== 게임 오버! ===");
    if (tryCount > MAX)
    {
        Console.WriteLine("시도 횟수를 모두 사용했습니다.");
        Console.WriteLine($"찾은 쌍: {correctCount}/8");
    }    
    else if (correctCount == 8)
    {
        Console.WriteLine("모든 쌍을 찾았습니다.");
        Console.WriteLine($"시도 회수: {tryCount}/{MAX}");
    }
    Console.WriteLine("새 게임을 하시겠습니까? (Y / N)");
    string YN = Console.ReadLine();
    if (YN == "N")
    {
        gameStart = false;
    }
}

void Title()
{
    Console.WriteLine("=== 카드 짝 맞추기 게임 ===");
    Console.WriteLine();
}

void ViewBoard(int[] consult, bool[] isOpened)
{
    Console.Clear();
    Title();
    Console.Write($"\t1열\t2열\t3열\t4열");
    for (int i = 0;i < consult.Length;i++)
    {
        if (i % K_COL == 0)
        {
            Console.Write($"\n{i / K_COL + 1}행 ");
        }
        if (!isOpened[i]) {
            Console.Write($"\t**");
        } else {
            Console.Write($"\t{consult[i]}");
        }
    }
    Console.WriteLine() ;
    Console.WriteLine() ;
    Console.WriteLine($"시도 횟수: {tryCount} / {MAX} | 맞춘 횟수: {correctCount} / 8");
}

static void DataBoard(int[] consult)
{
    int[] numbers =
    {
        1, 1,
        2, 2,
        3, 3,
        4, 4,
        5, 5,
        6, 6,
        7, 7,
        8, 8,
    };

    Random random = new Random();

    for (int i = numbers.Length - 1; i > 0; i--)
    {
        int j = random.Next(i + 1);

        int temp = numbers[i];
        numbers[i] = numbers[j];
        numbers[j] = temp;
    }

    for (int i = 0; i < consult.Length; i++)
    {
        consult[i] = numbers[i];
    }
}

선생님과 함께 짜본 카드 짝 맞추기 게임

csharp
using System;

class Program
{
    static void Main()
    {
        const int CardCount = 16;
        const int ColumCount = 4;

        int[] cards = CreateCards(CardCount);
        bool[] matched = new bool[CardCount];
        Random random = new Random();
        ShuffleCards(cards, random);

        int attemps = 0;
        int matchedParis = 0;

        while (matchedParis < CardCount / 2)
        {
            DisplayBoard(cards, matched, ColumCount, attemps, matchedParis);
            int firstIndex = ReadCardIndex("첫 번째", matched, ColumCount, -1);
            DisplayBoard(cards, matched, ColumCount, attemps, matchedParis, firstIndex);
            int secondIndex = ReadCardIndex("두 번째", matched, ColumCount, firstIndex);
            DisplayBoard(cards, matched, ColumCount, attemps, matchedParis, firstIndex, secondIndex);

            attemps++;
            bool isMatch = cards[firstIndex] == cards[secondIndex];

            if (isMatch)
            {
                matched[firstIndex] = matched[secondIndex] = true;
                matchedParis++;
            }
            DisplayBoard(cards, matched, ColumCount, attemps, matchedParis, firstIndex, secondIndex);
            Console.WriteLine(isMatch ? "매칭 성공" : "매칭 실패");

            WaitForEnter();
        }

        Console.WriteLine($"게임 클리어! 총 시도 횟수: {attemps}");
        WaitForEnter();
    }

    static int ReadCardIndex(string choiceName, bool[] matched, int columnCount, int firstIndex)
    {
        while (true)
        {
            Console.Write($"{choiceName} 카드 위치 선택 (x, y): ");
            string input = Console.ReadLine();
            string[] parts = input.Split(',');
            int i = 0;
            int j = 0;
            if(parts.Length != 2 ||
                !(int.TryParse(parts[0], out i) && int.TryParse(parts[1], out j)))
            {
                Console.WriteLine("[행, 열] 형식으로 숫자를 입력하세요.");
                continue;
            }

            int rowCount = matched.Length / columnCount;

            if (i <=  0 || i > rowCount ||  
                j <= 0 || j > columnCount)
            {
                Console.WriteLine("맞는 범위 입력해라");
                continue;
            }

            int index = (i - 1) * columnCount + (j - 1);

            if (index < 0 || index >= matched.Length)
            {
                Console.WriteLine($"0~{matched.Length - 1}까지 입력하세요.");
                continue;
            }

            if (index == firstIndex)
            {
                Console.WriteLine("같은 카드를 두 번 선택할 수 없습니다.");
                continue;
            }

            return index;
        }
    }

    static void WaitForEnter()
    {
        Console.WriteLine("확인했으면 Enter를 누르세요.");
        Console.ReadLine();
    }

    static void DisplayBoard(int[] cards, bool[] matched, int columnCount,
        int attemps, int matchedPairs, int firstIndex = -1, int secondIndex = -1)
    {
        Console.Clear();

        Console.WriteLine("=== 카드 매칭 게임 ===");
        Console.WriteLine($"시도 횟수: {attemps} / 찾은 쌍: {matchedPairs}");
        Console.WriteLine();

        Console.WriteLine( "카드 위치");
        for (int i = 0; i < cards.Length; i++)
        {
            Console.Write($"{i,4}");
            if ((i + 1) % columnCount == 0)
            {
                Console.WriteLine();
            }
        }

        Console.WriteLine();
        Console.WriteLine("현재 보드");
        for (int i = 0;i < cards.Length; i++)
        {
            bool isVisible = matched[i] || firstIndex == i || secondIndex == i;
            string face = isVisible ? cards[i].ToString() : "*";
            Console.Write($"{face,4}");

            if ((i + 1) % columnCount == 0)
            {

                Console.WriteLine();
            }
        }
    }

    static int[] CreateCards(int cardCount)
    {
        int[] cards = new int[cardCount];
        for (int i = 0; i < cards.Length; i++)
        {
            cards[i] = i / 2 + 1; // 1, 1, 2, 2, 3, 3 ..
        }
        return cards;
    }

    static void ShuffleCards(int[] cards, Random random)
    {
        for (int i = cards.Length -1; i > 0; i--)
        {
            int randomIndex = random.Next(0, i + 1);
            int temp = cards[i];
            cards[i] = cards[randomIndex];
            cards[randomIndex] = temp;
        }
    }


}

다음에 다른 게임을 만들게 될 때 참고하거나, 같은 게임을 다시 만들어 볼 때와 비교해보기 위함