본문 바로가기
프로그래밍/C 언어(코딩)

C언어] 슬라이딩 퍼즐-1

by 곰나나 2023. 12. 30.

[슬라이딩 퍼즐]

툴 버전 : Visual Studio 2022

 

슬라이딩 퍼즐 기본 틀 키를 입력 받아서 움직이고 서로 칸을 교체 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// 슬라이딩 퍼즐
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
 
#define ROWS 4
#define COLS 5
 
//& 퍼즐 상태를 나타내는 구조체
typedef struct 
{
    int board[ROWS][COLS];
    int emptyRow, emptyCol;
} PuzzleState;
 
//& 퍼즐 상태를 출력하는 함수
void printPuzzle(const PuzzleState* state)
{
    printf("\t 이동키 : ←:w, →:d, ↑:w, ↓:s, q:종료 \n\n");
    for (int i = 0; i < ROWS; ++i)
    {
        for (int j = 0; j < COLS; ++j)
        {
            printf("\t %2d ", state->board[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}//printPuzzle
 
//& 빈 칸을 이동시키는 함수
void moveEmptyCell(PuzzleState* state, int moveRow, int moveCol)
{
    int newRow = state->emptyRow + moveRow;
    int newCol = state->emptyCol + moveCol;
 
    //& 이동 가능한 위치인지 확인
    if (newRow >= 0 && newRow < ROWS && newCol >= 0 && newCol < COLS)
    {
        //& 빈 칸과 인접한 칸을 교환
        state->board[state->emptyRow][state->emptyCol] = state->board[newRow][newCol];
        state->board[newRow][newCol] = 0;
        state->emptyRow = newRow;
        state->emptyCol = newCol;
    }
}//moveEmptyCell
 
 
int main()
{
    //& 초기 퍼즐 상태(초기 상태: 4x5 크기 퍼즐의 빈 칸은 (3, 4))
    PuzzleState currentState = {
        {{12345},
         {678910},
         {1112131415},
         {161718190}},
        3,
        4 }; 
 
 
    while (1)
    {
        //& 콘솔 화면 지우기 (Windows용)
        system("cls"); 
 
        printPuzzle(&currentState);
 
        char ch = _getch(); //& 키 입력 대기
 
        //& 키에 따라 빈 칸 이동
        switch (ch)
        {
            //& (위-1,0), (아래 1,0), (왼0,-1), (오 0,1)
        case 'w':
            moveEmptyCell(&currentState, -10); 
            break;
        case 's':
            moveEmptyCell(&currentState, 10); 
            break;
        case 'a':
            moveEmptyCell(&currentState, 0-1);
            break;
        case 'd':
            moveEmptyCell(&currentState, 01); 
            break;
        case 'q':
            printf("게임 종료\n");
            return 0;
        }
    }
 
    return 0;
}//main
cs

728x90

'프로그래밍 > C 언어(코딩)' 카테고리의 다른 글

C언어] 슬라이딩 퍼즐-3  (1) 2023.12.31
C언어] 슬라이딩 퍼즐-2  (1) 2023.12.31
C언어] 성적표  (0) 2023.12.22
C언어] 시간 함수  (1) 2023.12.22
C언어] 문자열 입력 받아서 출력 하기  (0) 2023.12.22