게임 개발자를 위한 C++ 문법 1-3
1. WHAT
- srand(), rand() : 난수 생성
#include <cstdlib>
#include <ctime>
srand(time(0)); // 랜덤 시드 초기화
int secretNumber = rand() % 100 + 1; // 1부터 100 사이의 랜덤 숫자
- 요즘 스타일..?
#include <random>
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dist(1, 100);
int num = dist(gen);
- Sleep() : 대기
#include <Windows.h>
Sleep(1000); // 1초 동안 기다림
Sleep(500); // 0.5초 동안 기다림
- getline() : 한 줄 입력
#include <string>
using namespace std;
string text;
getline(cin, text); // 입력을 받는 부분
- 화면 초기화
system("cls");
2.TROUBLE & FIX
- 도전X도전 실습 중 시야 처리 버그
for (int i = 0; i < WIDTH * HEIGHT; i++) {
if (i % WIDTH == 0 && i != 0) //20칸마다 줄바꿈
cout << endl;
if ((P_Plr - 40 - 2 <= i && i <= P_Plr - 40 + 2 )|| (P_Plr - 20 - 2 <= i && i <= P_Plr - 20 + 2) || (P_Plr - 2 <= i && i <= P_Plr + 2 )|| (P_Plr + 40 - 2 <= i && i <= P_Plr + 40 + 2 )||( P_Plr + 20 - 2 <= i && i <= P_Plr + 20 + 2)) {
visible(i);
}
else
cout << DISP_OUTSIDE;
}
무식하게 시야 위치 비교하기.,,,ㅋㅋㅋ

공간을 뚫어버림,,
void visible(int current, int offset) { //현재 좌표, 편차
if ( (P_Plr+offset) / WIDTH != current / WIDTH) { //행이 다르면 시야 밖 처리
cout << DISP_OUTSIDE;
return;
}
if (current == P_Plr)
cout << DISP_PLAYER;
else if (map[current] == TILE_EMPTY)
cout << DISP_EMPTY;
else if (map[current] == TILE_MON1)
cout << DISP_MON1;
else if (map[current] == TILE_MON2)
cout << DISP_MON2;
else if (map[current] == TILE_MON3)
cout << DISP_MON3;
else if (map[current] == TILE_BOSS)
cout << DISP_BOSS;
}
if (P_Plr - 40 - 2 <= i && i <= P_Plr - 40 + 2)
visible(i,-40);
else if (P_Plr - 20 - 2 <= i && i <= P_Plr - 20 + 2)
visible(i,-20);
else if (P_Plr - 2 <= i && i <= P_Plr + 2)
visible(i,0);
else if (P_Plr + 40 - 2 <= i && i <= P_Plr + 40 + 2)
visible(i,40);
else if (P_Plr + 20 - 2 <= i && i <= P_Plr + 20 + 2)
visible(i,20);
else //시야 밖
cout << DISP_OUTSIDE;
나누기를 통해 같은 행인지 비교 > -0.5와 0을 동일하게 처리하는 문제 발생..

void visible(int current) {
//반대편으로 넘어가는 시야 나머지 값 비교를 통해 처리
if((current% WIDTH <5 && P_Plr % WIDTH >15) || (current % WIDTH > 15 && P_Plr % WIDTH < 5))
{
cout << DISP_OUTSIDE;
return;
}
if (current == P_Plr)
cout << DISP_PLAYER;
else if (map[current] == TILE_EMPTY)
cout << DISP_EMPTY;
else if (map[current] == TILE_MON1)
cout << DISP_MON1;
else if (map[current] == TILE_MON2)
cout << DISP_MON2;
else if (map[current] == TILE_MON3)
cout << DISP_MON3;
else if (map[current] == TILE_BOSS)
cout << DISP_BOSS;
}
넉넉하게 잡아 양쪽 5만큼은 서로 존재 할 수 없기때문에 비교를 통해 시야 밖 처리..

더 효율적으로 값을 비교해서 시야 처리를 할 수 있는 방법을 모르겠다.,, 암튼 해결!
하드코딩 된 부분은 WIDTH로 다 바꿔주고 끝~ 재밌는 실습이었다! 👍👍👍

3. RESULT
- 미니 실습
#include <iostream>
#include <Windows.h>
using namespace std;
void formatting() { //포맷 함수
cout << "틀렸어. 컴퓨터 포맷을 진행한다." << endl;
Sleep(500);
for (int i = 0; i < 50; i++) {
cout << "▨"; //로딩 바
Sleep(300);
}
}
int main() {
cout << "당신의 컴퓨터는 바이러스에 걸렸다!"<<endl;
Sleep(1500); // 1.5초 동안 기다림
cout << "지금부터 문제를 낼테니 틀리면 그 즉시 당신의 컴퓨터는 포맷된다." << endl;
Sleep(1500);
cout << "문제: 지금 수강중인 부트캠프 이름은 무엇일까요?" << endl; //첫번째 문제
cout << "1. 스파르타클럽 오늘배움캠프 2. 스파르타클럽 내일배움캠프 3. 스파르타클럽 모레배움캠프" << endl;
int ans;
char ans2;
cin >> ans;
if (ans == 2) { //정답 맞춤
cout << "오 맞췄구나... 다음 문제를 줄게"<<endl; //두번째 문제
Sleep(1500);
cout << "dfkmdvkdslmlsdjfiejsdkmc,scd,ljfd" << endl;
Sleep(1500);
cout << "이건 무슨 뜻일까?" << endl;
cin >> ans2;
Sleep(2000);
formatting();
cout << "장난이야~" << endl;
}
else { //틀림
formatting();
}
return 0;
}
- 도전 실습
#include<iostream>
#include <string>
#include <Windows.h>
using namespace std;
int main() {
string text;
cout << "한 줄 텍스트 입력하시오.";
getline(cin, text); // 입력을 받는 부분
for (int i = 0; i < text.length(); i++) { //텍스트 길이만큼 반복
cout << text[i]; //한글자씩 출력
if (text[i] == ' ') //공백은 0.3초
Sleep(300);
else if (i < text.length() - 2 && text[i] == '.' && text[i + 1] == '.' && text[i + 2] == '.') { //. 연속 3번이면 다음줄 넘기기
cout << text[i] << text[i];
i += 2; //인덱스 2 증가
cout << endl;//다음줄
Sleep(100);
}
else
Sleep(100); //디폴트 0.1초
}
return 0;
}
- 도전X도전 실습
#include <iostream>
#include <windows.h>
using namespace std;
const int TILE_EMPTY = 0; // 빈칸
const int TILE_PLAYER = 1; // 플레이어
const int TILE_MON1 = 2; // 몬스터 A
const int TILE_MON2 = 3; // 몬스터 B
const int TILE_MON3 = 4; // 몬스터 C
const int TILE_BOSS = 5; // 보스
const char DISP_EMPTY = '-';
const char DISP_PLAYER = 'P';
const char DISP_MON1 = 'a';
const char DISP_MON2 = 'b';
const char DISP_MON3 = 'c';
const char DISP_BOSS = 'B';
// 시야 밖(#) 은 별도로 사용
const char DISP_OUTSIDE = '#';
const int WIDTH = 20;
const int HEIGHT = 10;
int map[WIDTH * HEIGHT] =
{
// 0행
0,0,0,0,0, 2,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0,
// 1행
0,0,3,0,0, 0,0,0,0,0, 0,0,0,0,4, 0,0,0,0,0,
// 2행
0,0,0,0,0, 0,0,2,0,0, 0,0,0,0,0, 0,0,0,0,0,
// 3행
0,0,0,0,0, 0,0,0,0,3, 0,0,0,0,0, 0,0,0,0,0,
// 4행
0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,2,0,0,
// 5행
0,0,0,0,0, 4,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0,
// 6행
0,3,0,0,0, 0,0,0,0,0, 0,0,0,2,0, 0,0,0,0,0,
// 7행
0,0,0,0,0, 0,0,4,0,0, 0,0,0,0,0, 0,3,0,0,0,
// 8행
0,0,0,0,0, 0,0,0,0,0, 0,2,0,0,0, 0,0,0,0,0,
// 9행
0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0, 0,0,0,5,0,
};
int P_Plr = 110; //플레이어 위치 초기화
void visible(int current) {
//반대편으로 넘어가는 시야 나머지 값 비교를 통해 처리
if((current% WIDTH <5 && P_Plr % WIDTH >WIDTH-5) || (current % WIDTH > WIDTH-5 && P_Plr % WIDTH < 5))
{
cout << DISP_OUTSIDE;
return;
}
if (current == P_Plr)
cout << DISP_PLAYER;
else if (map[current] == TILE_EMPTY)
cout << DISP_EMPTY;
else if (map[current] == TILE_MON1)
cout << DISP_MON1;
else if (map[current] == TILE_MON2)
cout << DISP_MON2;
else if (map[current] == TILE_MON3)
cout << DISP_MON3;
else if (map[current] == TILE_BOSS)
cout << DISP_BOSS;
}
void moving(char move) {
int P_Next = P_Plr;//이동 위치
switch (move) {
case 'w':
if (P_Plr >= WIDTH)
P_Next = P_Plr - WIDTH;
break;
case 's':
if (P_Plr < WIDTH * (HEIGHT - 1))
P_Next = P_Plr + WIDTH;
break;
case 'a':
if (P_Plr % WIDTH != 0)
P_Next = P_Plr - 1;
break;
case 'd':
if (P_Plr % WIDTH != 19)
P_Next = P_Plr + 1;
break;
}
//빈칸이고 이동을 한 경우만 플레이어 위치를 다음 위치로 옮김
if (map[P_Next] == TILE_EMPTY && P_Plr != P_Next)
P_Plr = P_Next;
else { //이동을 하지 못한 경우(벽)나 빈칸이 아닌 경우
cout << "Can't Move!!!" << endl;
Sleep(500);
}
}
int main() {
while (true) {
/*cout << P_Plr << endl;*/
for (int i = 0; i < WIDTH * HEIGHT; i++) {
if (i % WIDTH == 0 && i != 0) //20칸마다 줄바꿈
cout << endl;
//시야처리를 더 효율적으로 하지 못할까..?
if (P_Plr - WIDTH*2 - 2 <= i && i <= P_Plr - WIDTH*2 + 2)
visible(i);
else if (P_Plr - WIDTH - 2 <= i && i <= P_Plr - WIDTH + 2)
visible(i);
else if (P_Plr - 2 <= i && i <= P_Plr + 2)
visible(i);
else if (P_Plr + WIDTH*2 - 2 <= i && i <= P_Plr + WIDTH*2 + 2)
visible(i);
else if (P_Plr + WIDTH - 2 <= i && i <= P_Plr + WIDTH + 2)
visible(i);
else //시야 밖
cout << DISP_OUTSIDE;
}
cout << endl;
cout << "입력(상:w, 하:s, 좌:a, 우:d, 끝내기:x): "; //입력 받기
char move;
cin >> move;
if (move == 'x')//끝내기
break;
moving(move); //움직임
//화면을 초기화 할 수 있어요.
system("cls");
}
return 0;
}
4. 참고
[C++] string (문자열) 클래스 정리 및 사용법과 응용
[목차] 1. string 클래스란? 2. string 클래스의 입출력 3. string 클래스 생성 4. string 클래스 연산자 활용 5. string 클래스의 멤버 함수 6. string 클래스의 멤버 함수 사용 예시 1. string 클래스란? - C++ STL에
rebro.kr
- A && B || C == (A && B) || C
'내배캠Unreal_TIL > C++' 카테고리의 다른 글
| [C++] Google C++ Style Guide, 구글 코드 컨벤션 (1) | 2025.12.11 |
|---|---|
| [TIL] 2025-12-11 | C++ 객체지향 프로그래밍, 상속과 다형성 (0) | 2025.12.11 |
| [TIL] 2025-12-10 | C++ 포인터와 레퍼런스, 클래스와 생성자 익히기, 멤버 초기화 리스트 (0) | 2025.12.10 |
| [TIL] 2025-12-08 | C++ 가변 인자 (0) | 2025.12.08 |
| [TIL] 2025-12-05 | C++ 프로그래밍 기초, strtok 함수 (0) | 2025.12.05 |