4월 15일 학습 내용

박도일·2022년 4월 15일
0

4월 학습내용

목록 보기
8/17

구조체

  • 절차적 프로그래밍 ex)순서도
    -> 1) 순서대로
    -> 2) 순서를 '제어'
    -> 3) 원하는 기능 구현

추상화
-> 현상을 간략화/기호화/보편화 해서 표현한것
-> 주로 배열, 구조체, 함수를 이용해서 추상화를 한다.

  • 추상화가 왜 필요한가
    코드는 사람이 짜는 것이기 때문에!
    -> 다른 사람이 코드를 해석하기 편리해야 한다.
    -> 다른 사람이 인수인계를 받아서 유지보수 하기 편리해야 한다.
    -> 다른 사람들과 함께 공동으로 코드를 만들기 편리해야 한다.

배열 : 속성이 동일한 여러 개의 데이터를 같은 이름과 순서를 지정한 연속된 번호로 서로 연관 되어 있음을 표시함으로서 추상화함
구조체 : 데이터(자료형)을 실제로 쓰이는 데이터끼리 묶어서 추상화
함수 : 프로세스(코드)를 특정 기능 단위로 묶어서 추상화 한다.

최악의 추상화 -> 추상화 단계를 상승시키는 과정

  • 구조적 프로그래밍
    -> 소스코드의 의도/의미를 파악할 수 있도록 구조적으로 나누는 프로그래밍
    -> 데이터 구조화 ex) 배열, 리스트, 구조체 등. (자료구조)
    -> 프로세스 구조화 ex) 함수 등.
  • 객체지향 프로그래밍

구조체

-> 변수를 모아 놓은 집합체
-> 특정 변수들이 무언가의 하위 개념으로 묶일 수 있을 때
ex) studentName[10], studentAge[10], studentKorScore[10] ....
위 변수들은 '학생'의 'XXX'로 나뉘어져있다.
∴ 이름, 나이, 국어점수, 석차 등등을 '학생'이라는 구조체로 묶어서 사용
1. 구조체를 정의하는 위치 : 구조체가 사용되는 함수의 앞에 정의한다.
2. 구조체 정의 방법

struct 구조체 이름{
	구조체 안의 하위 변수들
};

ex)

struct student {
    string name;
    int age;
    int homeTown;
    int pride;
}seoyeon, jaehyuk; //처럼 구조체 끝나는 중괄호 뒤에 변수를 미리 선언할 수 있다.
// 위에 따르면 name, age, homeTown, pride를 하위변수를 가진 구조체 student형성

- 구조체는 일종의 우리가 새롭게 만든 데이터 형.
3. 구조체 사용 방법

student abcd (구조체를 사용할 변수이름)

abcd.name
abcd.age
abcd.homeTown
abcd.pride
// 형식으로 사용 가능 
  • 구조체 안에서 사용 가능한 변수
    • 일반적인 변수(int, float, string 등), 배열, 먼저 선언된 구조체, 클래스 등 대부분 사용가능

4. 구조체 선언과 초기화
. 기본적으로 구조체 변수의 개념은 배열 변수의 개념과 동일
. int a[3] = { 50, 70, 80 };
. 구조체 변수도 다음과 같이 선언과 같이 초기화를 진행 할 수 있다.

탈출게임 구조체 추가하여 심화버전

#include <iostream>
#include <string>
#include <conio.h>
#include <Windows.h>

using namespace std;

struct player {
	int stamina;
	char inputMoveKey;
	int playerXPosition;
	int playerYPosition;
};

struct escape {
	int escapeXPosition;
	int escapeYPosition;
};

struct field { //0:평지, 1:벽, 2:숲, 3:늪지
	int map[20][20];
	int mapmemory[20][20];
	int wallCount;
	int forestCount;
	int swampCount;
};

struct control {
	bool isClear = false;
	int stageCount;
	int inputStage;
	int failCount;
	int fieldCheckNum;
};

int main()
{
	system("mode con: cols=100 lines=40");
	srand(time(NULL));
	int x = 0, y = 0; // for문을 위한 변수
	player person = { 60,0,0,0 };
	escape escap;
	field map;
	control menu;
	
	menu.stageCount = 1;
	menu.failCount = 0;
	
	cout << "플레이 하고싶은 스테이지의 수를 입력하세요 >> _";
	cin >> menu.inputStage;

	while (1) {
		for (x = 0; x < 20; x++) { //맵 전부 평지화
			for (y = 0; y < 20; y++) {
				map.map[x][y] = 0;
			}
		}

		x = rand() % 5 + 15;
		y = rand() % 5 + 15;
		map.map[x][y] = 9;
		escap.escapeXPosition = x;
		escap.escapeYPosition = y;

		person.playerXPosition = 0;
		person.playerYPosition = 0;
		map.map[person.playerXPosition][person.playerYPosition] = 7;

		map.wallCount = 0;
		map.forestCount = 0;
		map.swampCount = 0;
		while (map.wallCount != 20 && map.forestCount != 20 && map.swampCount != 20) { // 1사분면 지형처리
			x = rand() % 10;
			y = rand() % 10;
			menu.fieldCheckNum = rand() % 3 + 1;
			if (x != 0 && y != 0 && menu.fieldCheckNum == 1 && map.map[x][y] != 2 && map.map[x][y] != 3 && map.map[x][y] != 7) {
				map.map[x][y] = 1;
				map.wallCount++;
			}
			else if (x != 0 && y != 0 && menu.fieldCheckNum == 2 && map.map[x][y] != 1 && map.map[x][y] != 3 && map.map[x][y] != 7) {
				map.map[x][y] = 2;
				map.forestCount++;
			}
			else if (x != 0 && y != 0 && menu.fieldCheckNum == 3 && map.map[x][y] != 1 && map.map[x][y] != 2 && map.map[x][y] != 7) {
				map.map[x][y] = 3;
				map.swampCount++;
			}
		}

		map.wallCount = 0;
		map.forestCount = 0;
		map.swampCount = 0;
		while (map.wallCount != 20 && map.forestCount != 20 && map.swampCount != 20) { // 2사분면 지형처리
			x = rand() % 10;
			y = rand() % 10 + 10;
			menu.fieldCheckNum = rand() % 3 + 1;
			if (menu.fieldCheckNum == 1 && map.map[x][y] != 2 && map.map[x][y] != 3) {
				map.map[x][y] = 1;
				map.wallCount++;
			}
			else if (menu.fieldCheckNum == 2 && map.map[x][y] != 1 && map.map[x][y] != 3) {
				map.map[x][y] = 2;
				map.forestCount++;
			}
			else if (menu.fieldCheckNum == 3 && map.map[x][y] != 1 && map.map[x][y] != 2) {
				map.map[x][y] = 3;
				map.swampCount++;
			}
		}

		map.wallCount = 0;
		map.forestCount = 0;
		map.swampCount = 0;
		while (map.wallCount != 20 && map.forestCount != 20 && map.swampCount != 20) { // 3사분면 지형처리
			x = rand() % 10 + 10;
			y = rand() % 10;
			menu.fieldCheckNum = rand() % 3 + 1;
			if (menu.fieldCheckNum == 1 && map.map[x][y] != 2 && map.map[x][y] != 3) {
				map.map[x][y] = 1;
				map.wallCount++;
			}
			else if (menu.fieldCheckNum == 2 && map.map[x][y] != 1 && map.map[x][y] != 3) {
				map.map[x][y] = 2;
				map.forestCount++;
			}
			else if (menu.fieldCheckNum == 3 && map.map[x][y] != 1 && map.map[x][y] != 2) {
				map.map[x][y] = 3;
				map.swampCount++;
			}
		}

		map.wallCount = 0;
		map.forestCount = 0;
		map.swampCount = 0;
		while (map.wallCount != 20 && map.forestCount != 20 && map.swampCount != 20) { // 4사분면 지형처리
			x = rand() % 10 + 10;
			y = rand() % 10 + 10;
			menu.fieldCheckNum = rand() % 3 + 1;
			if (menu.fieldCheckNum == 1 && map.map[x][y] != 2 && map.map[x][y] != 3 && (x != escap.escapeXPosition && y != escap.escapeYPosition) ) {
				map.map[x][y] = 1;
				map.wallCount++;
			}
			else if (menu.fieldCheckNum == 2 && map.map[x][y] != 1 && map.map[x][y] != 3 && (x != escap.escapeXPosition && y != escap.escapeYPosition) ) {
				map.map[x][y] = 2;
				map.forestCount++;
			}
			else if (menu.fieldCheckNum == 3 && map.map[x][y] != 1 && map.map[x][y] != 2 && (x != escap.escapeXPosition && y != escap.escapeYPosition) ) {
				map.map[x][y] = 3;
				map.swampCount++;
			}
		}
		for (x = 0; x < 20; x++) {
			for (y = 0; y < 20; y++) {
				map.mapmemory[x][y] = map.map[x][y];
			}
		}
		while (1) {
			for (x = 0; x < 20; x++) {
				for (y = 0; y < 20; y++) {
					map.map[x][y] = map.mapmemory[x][y];
				}
			}
			map.map[0][0] = 0;
			map.map[person.playerXPosition][person.playerYPosition] = 7;
			system("cls");
			cout << "\t┌───────────────────────┐" << endl;
			cout << "\t│    남은스태미너 : " << person.stamina << "\t│" << endl;
			cout << "\t└───────────────────────┘" << endl;
			cout << "\t     << " << menu.stageCount << " 스테이지 >>" << endl;
			cout << "\t   << 남은 기회 - " << 3 - menu.failCount << " >>" << endl;
			cout << "\t << 남은 스테이지 - " << menu.inputStage - menu.stageCount << " >>" << endl;
			cout << "■■■■■■■■■■■■■■■■■■■■■■" << endl;
			for (x = 0; x < 20; x++) {
				cout << "■";
				for (y = 0; y < 20; y++) {
					if (map.map[x][y] == 0) {
						cout << "  ";
					}
					else if (map.map[x][y] == 1) {
						if (person.playerXPosition - 2 <= x && person.playerXPosition + 2 >= x && person.playerYPosition - 2 <= y && person.playerYPosition + 2 >= y) {
							cout << "■";
						}
						else {
							cout << "  ";
						}
					}
					else if (map.map[x][y] == 2) {
						if (person.playerXPosition - 2 <= x && person.playerXPosition + 2 >= x && person.playerYPosition - 2 <= y && person.playerYPosition + 2 >= y) {
							cout << "♠";
						}
						else {
							cout << "  ";
						}
					}
					else if (map.map[x][y] == 3) {
						if (person.playerXPosition - 2 <= x && person.playerXPosition + 1 >= x && person.playerYPosition - 2 <= y && person.playerYPosition + 2 >= y) {
							cout << "▩";
						}
						else {
							cout << "  ";
						}
					}
					else if (map.map[x][y] == 7) {
						cout << "●";
					}
					else if (map.map[x][y] == 9) {
						cout << "E";
					}
				}
				cout << "■" << endl;
			}
			cout << "■■■■■■■■■■■■■■■■■■■■■■" << endl;
			cout << " ■ : 벽 /   : 길(이동시 스태미너 1소모)/ ♠ : 숲(이동시 스태미너 2소모)" << endl;
			cout << " ▩ : 늪(이동시 스태미너 3소모) / E : 탈출구" << endl;

			cout << "이동 => w : 위 / s : 아래 / a : 왼쪽 / b : 오른쪽" << endl;

			person.inputMoveKey = _getch();
			if (person.inputMoveKey >= 65 && person.inputMoveKey <= 90) { //입력한게 대문자였을경우 소문자로 변환
				person.inputMoveKey += 32;
			}
			switch (person.inputMoveKey) {
			case 'w': //위쪽 이동
				if (person.playerXPosition != 0 && map.map[person.playerXPosition - 1][person.playerYPosition] != 1) { //배열에서[0][]일경우 위쪽으로 이동할 수 없어야함
					map.map[person.playerXPosition][person.playerYPosition] = 0;
					person.playerXPosition--;
					if (map.map[person.playerXPosition][person.playerYPosition] == 2) {
						person.stamina -= 2;
					}
					else if (map.map[person.playerXPosition][person.playerYPosition] == 3) {
						person.stamina -= 3;
					}
					else
					{
						person.stamina--;
					}
				}
				break;
			case 'a': //왼쪽 이동
				if (person.playerYPosition != 0 && map.map[person.playerXPosition][person.playerYPosition - 1] != 1) { //배열에서 [][0]일경우 왼쪽으로 이동 할 수 없어야함
					if (map.map[person.playerXPosition][person.playerYPosition - 1] == 5) {
					}
					map.map[person.playerXPosition][person.playerYPosition] = 0;
					person.playerYPosition--;
					if (map.map[person.playerXPosition][person.playerYPosition] == 2) {
						person.stamina -= 2;
					}
					else if (map.map[person.playerXPosition][person.playerYPosition] == 3) {
						person.stamina -= 3;
					}
					else
					{
						person.stamina--;
					}
				}
				break;
			case 's': //아래쪽 이동
				if (person.playerXPosition != 19 && map.map[person.playerXPosition + 1][person.playerYPosition] != 1) { //배열에서 [20][]일경우 아래쪽으로 이동 할 수 없어야함
					if (map.map[person.playerXPosition + 1][person.playerYPosition] == 5) {
					}
					map.map[person.playerXPosition][person.playerYPosition] = 0;
					person.playerXPosition++;
					if (map.map[person.playerXPosition][person.playerYPosition] == 2) {
						person.stamina -= 2;
					}
					else if (map.map[person.playerXPosition][person.playerYPosition] == 3) {
						person.stamina -= 3;
					}
					else
					{
						person.stamina--;
					}
				}
				break;
			case 'd': //오른쪽 이동
				if (person.playerYPosition != 19 && map.map[person.playerXPosition][person.playerYPosition + 1] != 1) { //배열에서 [][20]일경우 오른쪽으로 이동 할 수 없어야함
					if (map.map[person.playerXPosition][person.playerYPosition + 1] == 5) {
					}
					map.map[person.playerXPosition][person.playerYPosition] = 0;
					person.playerYPosition++;
					if (map.map[person.playerXPosition][person.playerYPosition] == 2) {
						person.stamina -= 2;
					}
					else if (map.map[person.playerXPosition][person.playerYPosition] == 3) {
						person.stamina -= 3;
					}
					else
					{
						person.stamina--;
					}
				}
				break;
			}
			if (person.playerXPosition == escap.escapeXPosition && person.playerYPosition == escap.escapeYPosition) {
				person.stamina = 60;
				menu.stageCount++;
				break;
			}
			else if (person.stamina <= 0) {
				system("cls");
				cout << endl << endl;
				cout << "\t\t┌───────────────────────────────────────────┐" << endl;
				cout << "\t\t│   탈출에 실패했습니다. 남은 기회 확인 중  │" << endl;
				cout << "\t\t└───────────────────────────────────────────┘" << endl;
				person.stamina = 60;
				menu.failCount++;
				Sleep(2000);
				break;
			}
		}
		if (menu.stageCount > menu.inputStage) {
			menu.isClear = true;
			break;
		}
		else if (menu.failCount > 5) {
			menu.isClear = false;
			break;
		}
	}
	if (menu.isClear) {
		system("cls");
		cout << endl;
		cout << "  ■    ■    ■■    ■    ■    ■    ■■■    ■■■■" << endl;
		cout << "   ■  ■   ■    ■  ■    ■   ■     ■    ■  ■" << endl;
		cout << "     ■     ■    ■  ■    ■          ■■■    ■■■■" << endl;
		cout << "     ■     ■    ■  ■    ■          ■  ■    ■" << endl;
		cout << "     ■       ■■      ■■            ■    ■  ■■■■" << endl;
		cout << endl;
		cout << "  ■■■■    ■■■    ■■■    ■■    ■■■    ■■■■" << endl;
		cout << "  ■        ■        ■        ■    ■  ■    ■  ■" << endl;
		cout << "  ■■■■  ■■■■  ■        ■■■■  ■■■■  ■■■■" << endl;
		cout << "  ■              ■  ■        ■    ■  ■        ■" << endl;
		cout << "  ■■■■  ■■■      ■■■  ■    ■  ■        ■■■■" << endl;
		cout << endl;
		cout << "    ■■■  ■        ■■■■    ■■    ■■■    ■  ■" << endl;
		cout << "  ■        ■        ■        ■    ■  ■    ■  ■  ■" << endl;
		cout << "  ■        ■        ■■■■  ■■■■  ■■■    ■  ■" << endl;
		cout << "  ■        ■        ■        ■    ■  ■  ■          " << endl;
		cout << "    ■■■  ■■■■  ■■■■  ■    ■  ■    ■  ■  ■" << endl << endl;
		cout << "\t\t┌────────────────────────────┐" << endl;
		cout << "\t\t│     탈출에 성공했습니다.   │" << endl;
		cout << "\t\t└────────────────────────────┘" << endl;
	}
	else {
		system("cls");
		cout << endl;
		cout << "  ■    ■    ■■    ■    ■    ■    ■■■    ■■■■" << endl;
		cout << "   ■  ■   ■    ■  ■    ■   ■     ■    ■  ■" << endl;
		cout << "     ■     ■    ■  ■    ■          ■■■    ■■■■" << endl;
		cout << "     ■     ■    ■  ■    ■          ■  ■    ■" << endl;
		cout << "     ■       ■■      ■■            ■    ■  ■■■■" << endl;
		cout << endl;
		cout << "  ■    ■     ■■    ■■■■■" << endl;
		cout << "  ■■  ■   ■    ■      ■" << endl;
		cout << "  ■ ■ ■   ■    ■      ■" << endl;
		cout << "  ■  ■■   ■    ■      ■" << endl;
		cout << "  ■    ■     ■■        ■" << endl;
		cout << endl;
		cout << "  ■■■■    ■■■    ■■■    ■■    ■■■    ■■■■" << endl;
		cout << "  ■        ■        ■        ■    ■  ■    ■  ■" << endl;
		cout << "  ■■■■  ■■■■  ■        ■■■■  ■■■■  ■■■■" << endl;
		cout << "  ■              ■  ■        ■    ■  ■        ■" << endl;
		cout << "  ■■■■  ■■■      ■■■  ■    ■  ■        ■■■■" << endl;
		cout << "\t\t┌────────────────────────────┐" << endl;
		cout << "\t\t│     탈출에 실패했습니다.   │" << endl;
		cout << "\t\t└────────────────────────────┘" << endl;
	}
}

Viusal Studio 학습내용

 /*
    구조체
    1. 절차적
    2. 구조적
    3. 객체지향적

    ### 추상화 ###
    C언어에서 코드를
    추상화 하는데 사용되는 삼총사 : 배열, 구조체, 함수
    추상화 : 현상을 간략화 / 기호화 / 보편화 해서 표현한것
    코드에서 추상화가 필요한 이유 : 코드는 사람이 짜는 것이기 때문에
    다른 사람이 코드를 해석하기 편리해야 하고
    다른 사람이 인수인계받아서 유지보수 하기 편리해야 하고
    다른 사람들과 함께 공동으로 코드를 만들기 편리해야하고
    
    - 배열 : 속성이 동일한 여러 개의 데이터를 같은 이름과 순서를 지정한 연속된 번호로 서로 연관 되어 있음을 표시함으로서 추상화함
    - 구조체 : 데이터(자료형)을 실제로 쓰이는 데이터끼리 묶어서 추상화
    - 함수 : 프로세스(코드)를 특정 기능 단위로 묶어서 추상화

    최악의 추상화 -> 추상화 단계를 상승시키는 과정
    string a, b, c;             // <- 최악의 추상화
    string a[3];                // <- 위보다는 좀 낫다
    string name1, name2, name3; // <- 조금 더 나아지고
    string studentName[3];      // <- 위의 것보다 의도가 명료하게 드러나기 떄문에 좋은 추상화다.
*/

/*
    구조체
    - 변수를 모아 놓은 집합체
    - 특정 변수들이 무언가의 하위 개념으로 묶일 수 있을 때
    - studentName[10], studentAge[10], studentKorScore[10] ....
    - 위 변수들은 '학생'의 XXX로
    ∴ 이름, 나이, 국어점수, 석차 등등을 '학생'이라는 구조체로 묶어서 사용

    1. 구조체를 정의하는 위치 : 구조체가 사용되는 함수의 앞에 정의한다.
    { 해당 함수의 바깥쪽 앞(위) }
    2. 구조체 정의의 방법
    struct 구조체 변수 명 {
        구조체 안에 들어갈 하위 변수들;
    };
    -> 구조체는 일종의 우리가 새롭게 만든 데이터형.

    3. 구조체 선언과 초기화
    기본적으로 구조체 변수의 개념은 배열 변수의 개념과 동일
    int a[3] = { 50, 70, 80 };
    구조체 변수도 다음과 같이 선언과 같이 초기화를 진행 할 수 있다.

    player.HP = player.HP - monster[n].dmg;
*/
#include <iostream>
#include <conio.h>
#include <cstdlib>
#include <Windows.h>
#include <string>

using namespace std;
//구초체 정의 위치
struct score {
    int kor;
    int eng;
    int math;
};

struct student {
    string name; //일반 변수 사용 가능
    int monthlyScore[10]; //배열도 사용가능
    int age;
    string homeTown;
    int pride;
    score myScore; //미리 정의한 구조체도 변수로 사용 가능
}seoyeon,jaehyuk; //처럼 중괄호 뒤에 변수 이름을 미리 선언할 수 있다.
// name, age, homeTown, pride라는 하위 변수를 가지고 있는 student라는 구조체를 정의 한다.

int main() // 지금 우리가 쓰고있는 유일한 함수
{

    //구조체 사용 방법
    student doil;
    doil.name = "박도일";      // 구조체를 사용하는 변수의 이름값
    doil.age = 27;            //구조체를 사용하는 변수의 나이값
    doil.homeTown = "전주";       //구조체를 사용하는 변수의 고향값
    doil.pride = 97;            //구조체를 사용하는 변수의 자신감값

    doil.myScore.eng = 70;
    doil.myScore.kor = 75;
    doil.monthlyScore[0] = 90;
    
    score myScore = { 50, 80, 90 }; //배열을 초기화 하듯 구조체도 초기화 가능.
    cout << myScore.kor << " " << myScore.eng << " " << myScore.math << endl;
    //monster a = { "고블린", 79, 55.12f, true, 100 }; 처럼 다양한 변수가 있는 구조체에도 한번에 초기화 가능.

    //초간단 실습. student 구조체를 사용해서 자기 자신의 정보를 입력하고 확인해보자.
    cout << doil.name << endl;
    cout << doil.age << endl;
    cout << doil.homeTown << endl;
    cout << doil.pride << endl;
    cout << doil.monthlyScore[0] << endl;

    /*
        과제 : 미궁탈출 게임의 업데이트 
        사용할 수 있는 모든 요소에 구조체를 활용해서 소스코드를 개선하기.
        맵 타일에 지형 정보를 넣고(숲, 늪, 평지)
        player : 피로도를 넣고
        플레이어가 어느 지형에 있는지, 플레이어의 피로도가 얼마인지 (숲-2, 늪-3, 평지-1)
    */

}
profile
개발자가 되고 싶은 사람

0개의 댓글