Chat
개발자가 AI를 보조로 다루기 3/6
cs newbie
2025. 5. 2. 00:25
좋습니다!
이제 **3단계: fishing_game.cpp**를 드립니다.
이 파일은 실제 게임 흐름과 파일 입출력, 사용자 선택 등을 처리합니다.
🧱 3단계: fishing_game.cpp
📁 저장 위치:
Fishing_MUD/
└── 소스 파일/
└── fishing_game.cpp
// fishing_game.cpp
// 게임 실행 로직 구현: 물고기 데이터 로딩, 낚시터 선택, 결과 출력 및 저장
#include "fishing_game.h" // 구조체 및 함수 선언 포함
#include <iostream> // 콘솔 입출력
#include <fstream> // 파일 입출력
#include <sstream> // 문자열 스트림
#include <random> // 랜덤 선택
#include <algorithm> // 알고리즘 유틸
/// @brief 텍스트 파일에서 물고기 데이터를 불러온다.
/// @param filepath 파일 경로 (예: "data/fish_data.txt")
/// @return Fish 구조체로 이루어진 리스트 (vector)
std::vector<Fish> load_fish_data(const std::string& filepath) {
std::vector<Fish> fish_list; // 결과 저장 벡터
std::ifstream file(filepath); // 입력 파일 스트림
std::string line;
// 파일 열기 확인
if (!file.is_open()) {
std::cerr << "❌ 파일을 열 수 없습니다: " << filepath << "\n";
return fish_list; // 빈 리스트 반환
}
// 한 줄씩 읽기
while (std::getline(file, line)) {
std::istringstream iss(line); // 문자열 파싱 스트림
Fish fish;
// 5개 항목 읽기: 이름, 가격, 점수, 타입, 등급
iss >> fish.name >> fish.price >> fish.score >> fish.type >> fish.rarity;
// 필드 누락 방지
if (fish.name.empty() || fish.type.empty() || fish.rarity.empty()) {
continue;
}
fish_list.push_back(fish); // 리스트에 추가
}
return fish_list; // 전체 물고기 리스트 반환
}
/// @brief 게임을 시작한다: 낚시터 입력 → 랜덤 물고기 낚시 → 결과 출력 & 저장
void start_game() {
// 1. 물고기 데이터 불러오기
std::vector<Fish> fish_list = load_fish_data("data/fish_data.txt");
if (fish_list.empty()) {
std::cout << "❌ 물고기 데이터를 불러오지 못했습니다.\n";
return;
}
// 2. 낚시터 선택 입력 받기
std::string spot_type;
std::cout << "🎯 낚시터를 선택하세요 (freshwater, saltwater, other): ";
std::cin >> spot_type;
// 3. 랜덤 물고기 한 마리 낚기
Fish caught = catch_fish(fish_list, spot_type);
// 4. 콘솔 출력
std::cout << "\n🎣 낚은 물고기: " << caught.name << "\n";
std::cout << "💰 가격: " << caught.price << "\n";
std::cout << "⭐ 점수: " << caught.score << "\n";
std::cout << "🌊 종류: " << caught.type << "\n";
std::cout << "🧬 등급: " << caught.rarity << "\n";
// 5. 결과 파일 저장
std::ofstream out("data/last_result.txt");
if (out.is_open()) {
out << caught.name << " " << caught.price << " "
<< caught.score << " " << caught.type << "\n";
out.close();
}
}
✅ 다음은 4단계: functions.h — 기능 함수 선언부입니다.
진행할까요?