跳到正文

个人记录

琪露诺可爱

QWQ_SczyYA约 83 分钟
原文

这是 2026年10月31日 存档的第 2 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年10月28日
收录
2026年10月29日
更新
2026年11月11日
篇幅
约 83 分钟

版本

  1. v3当前
  2. v2
  3. v1
C++
#define _USE_MATH_DEFINES
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <iomanip>
#include <windows.h>

const int W = 64;
const int H = 32;
const float PLAYER_VIS_R = 1.2f;
const float PLAYER_HIT_R = 0.4f;
const float GRAZE_R = 1.4f;
const float BULLET_R = 0.7f;
const float PLAYER_SPEED = 13.f;
const float PLAYER_SPEED_SLOW = PLAYER_SPEED * 0.35f;
const int FRAME_DELAY = 1;
const float FIXED_DT = 1.0f / 60.0f;

const int C_BLACK = 0;
const int C_BLUE = 1;
const int C_GREEN = 2;
const int C_CYAN = 3;
const int C_RED = 4;
const int C_MAGENTA = 5;
const int C_YELLOW = 6;
const int C_WHITE = 7;
const int C_GRAY = 8;
const int C_LBLUE = 9;
const int C_LGREEN = 10;
const int C_LCYAN = 11;
const int C_LRED = 12;
const int C_LMAGENTA = 13;
const int C_LYELLOW = 14;
const int C_BRIGHT = 15;

const float RAND_ANGLE = -99999.f;   // 谱面里写 rand 时使用

const int COLOR_LINE = C_LRED;
const int COLOR_AIM = C_RED;
const int COLOR_CIRCLE = C_LYELLOW;
const int COLOR_FAN = C_CYAN;
const int COLOR_SPIRAL = C_LMAGENTA;
const int COLOR_BOUNCE = C_LCYAN;
const int COLOR_ACCEL = C_MAGENTA;
const int COLOR_DELAY = C_YELLOW;
const int COLOR_PLAYER = C_LGREEN;
const int COLOR_UI = C_LBLUE;
const int COLOR_WARN = C_LRED;
const int COLOR_INFO = C_LCYAN;
const int COLOR_TITLE = C_LYELLOW;
const int COLOR_BLASTER   = C_LYELLOW;   // 炮台黄
const int COLOR_LASER     = C_BRIGHT;    // 激光亮白
const int COLOR_BLASTER_W = C_LRED;      // 炮台警告暗红

const float BULLET_BASE_SPEED = 20.f;
const float ENDLESS_SPAWN_BASE = 0.14f;
const float ENDLESS_SPAWN_MIN = 0.04f;
const float ENDLESS_SPAWN_MAX = 0.45f;
const float SPIRAL_ROT_SPEED = 2.4f;
const float SPIRAL_EXPAND_RATE = 0.38f;
const int CIRCLE_MIN_CNT = 12;
const int CIRCLE_RAND_ADD = 10;
const int FAN_CNT = 10;
const float FAN_MIN_DEG = 30.f;
const float FAN_MAX_DEG = 80.f;
const float MAX_MULT = 3.0f;
const float COMBO_DECAY = 4.0f;
const float COMBO_GAIN_RATE = 0.08f;
const float SCORE_BASE = 10.0f;
const float GRAZE_SCORE = 25.0f;
const float TYPEWRITER_SPEED = 0.04f;

bool god_mode = false;

template<typename T> T clamp(T v, T lo, T hi) {
	if(v < lo) return lo;
	if(v > hi) return hi;
	return v;
}

void set_color(int c) {
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
void reset_color() {
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), C_WHITE);
}

// 用 API 清屏替代 clear_screen():无进程开销、无缓冲竞态、不闪烁
void clear_screen() {
    std::cout.flush();                    // 先冲掉 cout 缓冲,杜绝竞态
    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    DWORD written = 0;
    COORD home = {0, 0};
    if(GetConsoleScreenBufferInfo(h, &csbi)) {
        DWORD cells = (DWORD)csbi.dwSize.X * csbi.dwSize.Y;
        FillConsoleOutputCharacterA(h, ' ', cells, home, &written);
        FillConsoleOutputAttribute(h, C_WHITE, cells, home, &written);
        SetConsoleCursorPosition(h, home);
    }
}

bool key[256] = {false};
bool last_key[256] = {false};
void update_key() {
    for(int i = 0; i < 256; i++) last_key[i] = key[i];
    for(int i = 0; i < 256; i++)
        key[i] = (GetAsyncKeyState(i) & 0x8000) != 0;
}

enum BulletType { B_LINE, B_AIM, B_CIRCLE, B_FAN, B_SPIRAL, B_BOUNCE, B_ACCEL, B_DELAY, B_BLASTER, B_BLASTER_AIM };
struct Bullet {
	BulletType type {};
	float x {};
	float y {};
	float vx {};
	float vy {};
	float speed {};
	float acc = 0.f;			// M8:全部字段默认初始化消除UB
	float delay_timer = 0.f;
	float spiral_ang = 0.f;
	float spiral_x0 = 0.f;		// S1修复螺旋:保存螺旋发射原点X
	float spiral_y0 = 0.f;		// S1修复螺旋:保存螺旋发射原点Y
	float birth = 0.f;
	int bounce_left = 0;
	char ch = '*';
	int col = C_WHITE;
	bool active = false;
};

struct NoteEvent {
	float time;
	float x, y;
	BulletType type;
	std::vector<float> args;
};

// 【新增】单关卡结构(DIY/内置关卡统一)
struct DanStage {
	std::string name;
	std::vector<std::string> pages; // 多页剧情,每页打字机
	float diff_mult;
	float base_speed;
	std::vector<NoteEvent> notes;
};

struct DialogueState {
    bool active = false;
    bool finished = true;
    int page_idx = 0;
    int char_idx = 0;
    float timer = 0.f;
    std::vector<std::string> *pages = nullptr;

    void start(std::vector<std::string> &p) {
        pages = &p;
        page_idx = 0;
        char_idx = 0;
        timer = 0.f;
        active = !p.empty();
        finished = p.empty();
    }
    void stop() {
        active = false;
        finished = true;
        pages = nullptr;
    }
    int cur_len() const {
        if(!pages || page_idx < 0 || page_idx >= (int)pages->size()) return 0;
        return (int)(*pages)[page_idx].size();
    }
    bool page_done() const { return char_idx >= cur_len(); }

    void update(float dt) {
        if(!active) return;
        if(page_done()) { timer = 0.f; return; }   // 本页打完,停止累加
        timer += dt;
        while(timer >= TYPEWRITER_SPEED && !page_done()) {
            timer -= TYPEWRITER_SPEED;
            char_idx++;
        }
    }
    void fast_forward() {
        if(active) char_idx = cur_len();            // 上限就是本页长度
    }
    bool next_page() {
        if(!active) return false;
        page_idx++;
        char_idx = 0;
        timer = 0.f;
        if(page_idx >= (int)pages->size()) {
            active = false;
            finished = true;
            return false;
        }
        return true;
    }
    std::string get_display() const {
        if(!active || !pages || page_idx < 0 || page_idx >= (int)pages->size()) return "";
        const std::string &s = (*pages)[page_idx];
        int n = char_idx;
        if(n < 0) n = 0;
        if(n > (int)s.size()) n = (int)s.size();
        return s.substr(0, n);
    }
    int page_count() const { return pages ? (int)pages->size() : 0; }
};

enum GameMode { MODE_CHALLENGE, MODE_ENDLESS, MODE_DIY };
enum OverlayState { OVERLAY_NONE, OVERLAY_HELP, OVERLAY_STORY, OVERLAY_CLEARWAIT };
enum Difficulty { D_EASY, D_NORMAL, D_HARD };
float diff_rate;

struct ScoreMgr {
	unsigned long long score;
	float combo;
	float combo_timer;
	float mult;
	void reset() {
		score = 0;
		combo = 0;
		mult = 1.0f;
		combo_timer = 0;
	}
	void hurt() {
		combo = 0;
		mult = 1.0f;
		combo_timer = 0;
	}
	void add(float val) {
		score += (unsigned long long)llround(val);
	}
	void add_tick(float dt, float diff_mult) {
		float add = SCORE_BASE * dt * mult * diff_mult;
		score += (unsigned long long)llround(add);
		if(combo > 0) {
			combo += dt;
			mult = clamp(1.0f + combo * COMBO_GAIN_RATE, 1.0f, MAX_MULT);
		}
	}
	void tick(float dt) {
		if(combo_timer > 0) {
			combo_timer -= dt;
			if(combo_timer <= 0) hurt();
		}
	}
	void refresh_combo() {
		combo_timer = COMBO_DECAY;
		if(combo <= 0) combo = 0.01f;
	}
};
struct Player {
	float x, y;
	int hp;
	int max_hp;
	float invincible;
};

std::vector<Bullet> bullets;
std::vector<DanStage> dan_stage_list; // 内置挑战关卡列表
std::vector<DanStage> diy_stage_list; // DIY加载的多关卡
ScoreMgr sc;
Player pl;
GameMode gmode;
OverlayState overlay = OVERLAY_NONE;
float overlay_timer = 0.f;
int cur_stage_idx = 0;
int note_ptr = 0;
float game_timer;
bool running;
bool gameover;
bool win;
float spawn_t;
DialogueState dlg;

char get_bullet_ch(BulletType t) {
	switch(t) {
		case B_LINE:
			return '#';
		case B_AIM:
			return '@';
		case B_CIRCLE:
			return 'O';
		case B_FAN:
			return '%';
		case B_SPIRAL:
			return '&';
		case B_BOUNCE:
			return '?';
		case B_ACCEL:
			return '!';
		case B_DELAY:
			return '+';
		case B_BLASTER:
		case B_BLASTER_AIM:
			return 'D';
		default:
			return '*';
	}
}
int get_bullet_color(BulletType t) {
	switch(t) {
		case B_LINE:
			return COLOR_LINE;
		case B_AIM:
			return COLOR_AIM;
		case B_CIRCLE:
			return COLOR_CIRCLE;
		case B_FAN:
			return COLOR_FAN;
		case B_SPIRAL:
			return COLOR_SPIRAL;
		case B_BOUNCE:
			return COLOR_BOUNCE;
		case B_ACCEL:
			return COLOR_ACCEL;
		case B_DELAY:
			return COLOR_DELAY;
		case B_BLASTER:
		case B_BLASTER_AIM:
			return 'D';
		default:
			return C_WHITE;
	}
}
BulletType str2type(const std::string& s) {
	if(s=="line") return B_LINE;
	if(s=="aim") return B_AIM;
	if(s=="circle") return B_CIRCLE;
	if(s=="fan") return B_FAN;
	if(s=="spiral") return B_SPIRAL;
	if(s=="bounce") return B_BOUNCE;
	if(s=="accel") return B_ACCEL;
	if(s=="delay") return B_DELAY;
	if(s=="blaster") return B_BLASTER;
	if(s=="blaster_aim") return B_BLASTER_AIM;
	return B_LINE;
}
std::string type2str(BulletType t) {
	switch(t) {
		case B_LINE:
			return "line";
		case B_AIM:
			return "aim";
		case B_CIRCLE:
			return "circle";
		case B_FAN:
			return "fan";
		case B_SPIRAL:
			return "spiral";
		case B_BOUNCE:
			return "bounce";
		case B_ACCEL:
			return "accel";
		case B_DELAY:
			return "delay";
		case B_BLASTER:
			return "blaster";
		case B_BLASTER_AIM:
			return "blaster_aim";
		default:
			return "line";
	}
}

// 难度弹量系数:简单 65%,普通 85%,困难 100%
float get_bullet_count_mult() {
	if(diff_rate <= 0.65f) return 0.65f;
	if(diff_rate <= 1.00f) return 0.85f;
	return 1.0f;
}

void spawn_bullet(BulletType type, float sx, float sy, float vx, float vy, float sp, std::vector<float> args, float now_t) {
	Bullet b;
	b.type = type;
	b.x = sx;
	b.y = sy;
	b.vx = vx;
	b.vy = vy;
	b.speed = sp;
	b.birth = now_t;
	b.bounce_left = 3;
	b.ch = get_bullet_ch(type);
	b.col = get_bullet_color(type);
	b.active = true;
	if(type == B_ACCEL) {
		b.acc = args.size()>=1 ? args[0] : 60.f;
	}
	if(type == B_DELAY) {
		b.delay_timer = args.size()>=1 ? args[0] : 1.2f;
	}
	// S1螺旋弹:记录发射原点
	if(type == B_SPIRAL) {
		b.spiral_x0 = sx;
		b.spiral_y0 = sy;
		if(args.size()>=2)
			b.spiral_ang = args[1] * (float)M_PI / 180.0f;
		else
			b.spiral_ang = 2.0f * (float)M_PI * (rand() / (RAND_MAX + 1.0));
	}
	bullets.push_back(b);
}

void spawn_event(const NoteEvent& e, float px, float py, float now_t, float spd_scale = 1.0f) {
	auto A = [](const std::vector<float>& v, size_t i, float def = 0.f) -> float {
	    if(i >= v.size()) return def;
	    return (v[i] == RAND_ANGLE) ? (float)(rand() % 360) : v[i];
	};
	float base_sp = BULLET_BASE_SPEED * spd_scale;
	if(e.type == B_LINE) {
		float ang = A(e.args,0) * M_PI/180;
		spawn_bullet(B_LINE, e.x, e.y, cos(ang)*base_sp, sin(ang)*base_sp, base_sp, {}, now_t);
	} else if(e.type == B_AIM) {
		float dx = px - e.x;
		float dy = py - e.y;
		float len = hypot(dx, dy);
		if(len < 1e-3) return;
		spawn_bullet(B_AIM, e.x, e.y, dx/len*base_sp, dy/len*base_sp, base_sp, {}, now_t);
	} else if(e.type == B_CIRCLE) {
		int cnt = (int)e.args[0];
		cnt = clamp((int)(cnt * get_bullet_count_mult()), 1, 64);
		for(int i=0; i<cnt; i++) {
			float ang = 2*(float)M_PI * i / cnt;
			spawn_bullet(B_CIRCLE, e.x, e.y, cos(ang)*base_sp, sin(ang)*base_sp, base_sp, {}, now_t);
		}
	} else if(e.type == B_FAN) {
		int cnt = (int)e.args[0];
		cnt = clamp((int)(cnt * get_bullet_count_mult()), 2, 64);
		float total_deg = clamp(e.args[1], 5.0f, 120.0f);
		float start_ang = A(e.args,2) * M_PI/180;
		float d_ang = total_deg * (float)M_PI / 180.0 / (cnt-1);
		for(int i=0; i<cnt; i++) {
			float ang = start_ang + i*d_ang;
			spawn_bullet(B_FAN, e.x, e.y, cos(ang)*base_sp, sin(ang)*base_sp, base_sp, {}, now_t);
		}
	} else if(e.type == B_SPIRAL) {
		// M7修复死参数 args[0]:螺旋臂数量
		int arm_count = (int)e.args[0];
		arm_count = clamp(arm_count,1,8);
		for(int a=0; a<arm_count; a++) {
			std::vector<float> new_args = e.args;
			float arm_offset_rad = 2*(float)M_PI * a / arm_count;
			if(new_args.size()>=2)
				new_args[1] += arm_offset_rad * 180.0f/(float)M_PI;
			else
				new_args.push_back( arm_offset_rad *180.0f/(float)M_PI );
			spawn_bullet(B_SPIRAL, e.x, e.y,0,0,base_sp, new_args, now_t);
		}
	} else if(e.type == B_BOUNCE) {
		float ang = A(e.args,0) * M_PI/180;
		std::vector<float> arg_copy = e.args;
		spawn_bullet(B_BOUNCE, e.x, e.y, cos(ang)*base_sp, sin(ang)*base_sp, base_sp, arg_copy, now_t);
		// 读取bounce_left,修改刚生成子弹
		Bullet &last = bullets.back();
		last.bounce_left = (int)e.args[1];
	} else if(e.type == B_ACCEL) {
		float ang = A(e.args,0) * M_PI/180;
		float a = e.args[1];
		spawn_bullet(B_ACCEL, e.x, e.y, cos(ang)*base_sp*0.4f, sin(ang)*base_sp*0.4f, base_sp*0.4f, {a}, now_t);
	} else if(e.type == B_DELAY) {
		float ang = A(e.args,0) * M_PI/180;
		float dt = e.args[1];
		spawn_bullet(B_DELAY, e.x, e.y, cos(ang)*base_sp, sin(ang)*base_sp, base_sp, {dt}, now_t);
	} else if(e.type == B_BLASTER) {
		Bullet b;
		b.type = B_BLASTER;
		b.x = e.x;
		b.y = e.y;
		b.vx = b.vy = 0;
		b.spiral_ang = A(e.args,0) * M_PI/180.f;
		b.delay_timer = e.args.size() >= 2 ? e.args[1] : 0.8f;
		b.acc         = e.args.size() >= 3 ? e.args[2] : 0.35f;
		b.speed       = e.args.size() >= 4 ? e.args[3] : 30.f;
		b.birth = now_t;
		b.bounce_left = 0;
		b.ch = 'D';
		b.col = COLOR_BLASTER;
		b.active = true;
		bullets.push_back(b);
	} else if(e.type == B_BLASTER_AIM) {
		Bullet b;
		b.type = B_BLASTER_AIM;
		b.x = e.x;
		b.y = e.y;
		b.vx = b.vy = 0;
		float dx = px - e.x, dy = py - e.y;
		b.spiral_ang = atan2(dy, dx);
		b.delay_timer = e.args.size() >= 1 ? e.args[0] : 0.8f;
		b.acc         = e.args.size() >= 2 ? e.args[1] : 0.35f;
		b.speed       = e.args.size() >= 3 ? e.args[2] : 30.f;
		b.birth = now_t;
		b.bounce_left = 0;
		b.ch = 'D';
		b.col = COLOR_BLASTER;
		b.active = true;
		bullets.push_back(b);
	}
}

static int need_args(BulletType t) {
	switch(t) {
		case B_LINE:
			return 1;
		case B_AIM:
			return 0;
		case B_CIRCLE:
			return 1;
		case B_FAN:
			return 3;
		case B_BOUNCE:
			return 2;
		case B_ACCEL:
			return 2;
		case B_DELAY:
			return 2;
		case B_BLASTER:
			return 1;      // 至少角度
		case B_BLASTER_AIM:
			return 0;      // 自动瞄准
		case B_SPIRAL:
			return 2; // M7修复:args[0]=臂数 args[1]=初始角度
		default:
			return 0;
	}
}
static std::string tolower_str(std::string s) {
	for(auto &ch : s) ch = tolower(static_cast<unsigned char>(ch));
	return s;
}

// 【重写】加载带多stage、page、diff的danmaku文件
void load_danmaku(const std::string& fname, std::vector<DanStage> &out_list) {
	out_list.clear();
	std::ifstream f(fname);
	if(!f.is_open()) {
		set_color(COLOR_WARN);
		std::cout << "\n警告:无法打开 " << fname << ",DIY模式无弹幕!\n";
		reset_color();
		Sleep(600);
		return;
	}
	std::string line;
	DanStage cur_st;
	bool in_stage = false;
	while(getline(f, line)) {
		size_t cmt_pos = line.find("//");
		if(cmt_pos != std::string::npos) line = line.substr(0, cmt_pos);
		std::stringstream ss(line);
		std::string tok;
		ss >> tok;
		if(tok == "stage") {
			if(in_stage) {
				out_list.push_back(cur_st);
				cur_st = DanStage {};
			}
			in_stage = true;
			cur_st.diff_mult = 1.0f;
			cur_st.base_speed = 1.0f;
		} else if(tok == "}") {
			if(in_stage) {
				out_list.push_back(cur_st);
				cur_st = DanStage {};
				in_stage = false;
			}
		} else if(tok == "name") {
			std::string rest;
			getline(ss, rest);
			size_t q1 = rest.find('"');
			size_t q2 = rest.find('"', q1+1);
			if(q1 != std::string::npos && q2 != std::string::npos) {
				cur_st.name = rest.substr(q1+1, q2-q1-1);
			}
		} else if(tok == "page") {
			std::string rest;
			getline(ss, rest);
			size_t q1 = rest.find('"');
			size_t q2 = rest.find('"', q1+1);
			if(q1 != std::string::npos && q2 != std::string::npos) {
				cur_st.pages.push_back(rest.substr(q1+1, q2-q1-1));
			}
		} else if(tok == "diff") {
			float v;
			if(ss >> v) cur_st.diff_mult = v;
		} else if(tok == "base_speed") {
			float v;
			if(ss >> v) cur_st.base_speed = v;
		} else if(tok == "note") {
			NoteEvent ne;
			std::string tname;
			ss >> ne.time >> ne.x >> ne.y >> tname;
			ne.type = str2type(tname);
std::string argtok;
while(ss >> argtok) {
    if(argtok == "rand" || argtok == "r") {
        ne.args.push_back(RAND_ANGLE);
    } else {
        try { ne.args.push_back(std::stof(argtok)); }
        catch(...) { /* 非法参数,跳过该 note 或记警告 */ }
    }
}
			int req = need_args(ne.type);
			if((int)ne.args.size() >= req) {
				ne.time = clamp(ne.time, 0.0f, 999.0f);
				ne.x = clamp(ne.x, -2.0f, W+2.0f);
				ne.y = clamp(ne.y, -2.0f, H+2.0f);
				cur_st.notes.push_back(ne);
			}
		}
	}
	if(in_stage) {
		out_list.push_back(cur_st);
	}
	for(auto &s : out_list) {
		std::sort(s.notes.begin(), s.notes.end(), [](const NoteEvent& a, const NoteEvent& b) {
			return a.time < b.time;
		});
	}
	set_color(COLOR_INFO);
	std::cout << "成功加载谱面:" << fname << ",关卡数量:" << out_list.size() << "\n";
	reset_color();
	Sleep(600);
}

struct DirItem {
	bool is_dir;
	std::string display_name;
	std::string full_path;
};
std::vector<DirItem> scan_dir(const std::string& base) {
	std::vector<DirItem> res;
	std::string pattern = base + "\\*";
	WIN32_FIND_DATAA fd;
	HANDLE hFind = FindFirstFileA(pattern.c_str(), &fd);
	if(hFind == INVALID_HANDLE_VALUE) return res;
	do {
		std::string name = fd.cFileName;
		if(name == "." || name == "..") continue;
		std::string full = base + "/" + name;
		bool isd = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
		if(isd) {
			res.push_back({true, name, full});
		} else {
			std::string low = tolower_str(name);
			if(low.size() >= 9 && low.substr(low.size()-8) == ".danmaku") {
				res.push_back({false, name, full});
			}
		}
	} while(FindNextFileA(hFind, &fd));
	FindClose(hFind);
	std::sort(res.begin(), res.end(), [](const DirItem& a, const DirItem& b) {
		if(a.is_dir != b.is_dir) return a.is_dir > b.is_dir;
		return a.display_name < b.display_name;
	});
	return res;
}

std::string select_dan_file() {
	const int VIEW_H = 12;
	std::string cur_path = ".";
	while(true) {
		auto items = scan_dir(cur_path);
		if(items.empty()) {
			clear_screen();
			set_color(COLOR_WARN);
			std::cout << "当前目录【" << cur_path << "】为空\n";
			reset_color();
			Sleep(800);
			if(cur_path == ".") return "";
			size_t pos = cur_path.find_last_of('/');
			if(pos == std::string::npos) cur_path = ".";
			else cur_path = cur_path.substr(0, pos);
			continue;
		}
		int sel = 0;
		while(true) {
			update_key();
			clear_screen();
			set_color(COLOR_TITLE);
			std::cout << "==== 选择DIY弹幕谱 ====\n";
			std::cout << "当前目录:" << cur_path << "\n\n";
			reset_color();
			std::cout << "↑ ↓切换 | 回车进入文件夹/选中谱子 | B返回上级 | ESC返回菜单\n\n";
			int top = clamp(sel - VIEW_H, 0, (int)items.size()-1);
			int bot = clamp(sel + VIEW_H, 0, (int)items.size()-1);
			if(top > 0) std::cout << "        ↑ 更多上方\n";
			for(int i=top; i<=bot; i++) {
				if(i == sel) {
					set_color(COLOR_PLAYER);
					if(items[i].is_dir)
						std::cout << " > [文件夹] " << items[i].display_name << "\n";
					else
						std::cout << " > [谱子] " << items[i].display_name << "\n";
				} else {
					if(items[i].is_dir)
						std::cout << "   [文件夹] " << items[i].display_name << "\n";
					else
						std::cout << "   [谱子] " << items[i].display_name << "\n";
				}
				reset_color();
			}
			if(bot < (int)items.size()-1) std::cout << "        ↓ 更多下方\n";
			if(key[VK_UP] && !last_key[VK_UP]) sel = clamp(sel-1, 0, (int)items.size()-1);
			if(key[VK_DOWN] && !last_key[VK_DOWN]) sel = clamp(sel+1, 0, (int)items.size()-1);
			if(key['B'] && !last_key['B']) {
				if(cur_path == ".") continue;
				size_t pos = cur_path.find_last_of('/');
				if(pos == std::string::npos) cur_path = ".";
				else cur_path = cur_path.substr(0, pos);
				break;
			}
			if(key[VK_RETURN] && !last_key[VK_RETURN]) {
				if(items[sel].is_dir) {
					cur_path = items[sel].full_path;
					break;
				} else {
					return items[sel].full_path;
				}
			}
			if(key[VK_ESCAPE] && !last_key[VK_ESCAPE]) {
				return "";
			}
			Sleep(80);
		}
	}
}

// 【新增】预览面板:显示关卡信息,等待确认进入
bool preview_stage(const DanStage &st) {
	clear_screen();
	while(true) {
		update_key();
		clear_screen();
		set_color(COLOR_TITLE);
		std::cout << "==== 关卡预览 ====\n";
		reset_color();
		std::cout << "关卡名:" << st.name << "\n";
		std::cout << "本关难度倍率:" << st.diff_mult << "\n";
		std::cout << "弹幕速度倍率:" << st.base_speed << "\n";
		std::cout << "剧情页数:" << st.pages.size() << "\n";
		std::cout << "弹幕事件数量:" << st.notes.size() << "\n\n";
		set_color(COLOR_INFO);
		std::cout << "按 C 开始挑战 | ESC 返回\n";
		reset_color();
		if(key['C'] && !last_key['C']) {
			return true;
		}
		if(key[VK_ESCAPE] && !last_key[VK_ESCAPE]) {
			return false;
		}
		Sleep(80);
	}
}

void enter_stage(int sid, std::vector<DanStage> &list) {
	if(sid >= (int)list.size()) {
		win = true;
		return;
	}
	cur_stage_idx = sid;
	note_ptr = 0;
	game_timer = 0;
	bullets.clear();
	clear_screen();
	if(list[sid].pages.empty()) {
		overlay = OVERLAY_NONE;      // 无剧情直接开打
		dlg.active = false;
	} else {
		overlay = OVERLAY_STORY;
		dlg.start(list[sid].pages);
	}
}

void reset_game(GameMode m) {
	gmode = m;
	bullets.clear();
	game_timer = 0;
	spawn_t = 0.0f;
	sc.reset();
	pl.x = W/2.f;
	pl.y = H-6;
	pl.hp = 5;
	pl.max_hp = 5;
	pl.invincible = 0;
	gameover = false;
	win = false;
	overlay = OVERLAY_NONE;
	overlay_timer = 0;
	note_ptr = 0;
	memset(key, 0, sizeof(key));
	memset(last_key, 0, sizeof(last_key));
	clear_screen(); // M1修复重置游戏清屏
}

void build_builtin_stages() {
	DanStage tuto;
	tuto.name = "教学关 · 基础躲避";
	tuto.pages = {"欢迎来到弹幕世界", "WASD移动,Shift低速", "X跳过打字,C继续剧情"};
	tuto.diff_mult = 0.8f;
	tuto.base_speed = 0.8f;
	tuto.notes = {
		{1.0f,32,8, B_CIRCLE, {10}},
		{2.5f,16,8, B_AIM, {}},
		{2.5f,48,8, B_AIM, {}},
		{4.0f,32,8, B_FAN, {7,60,180}},
	};
	dan_stage_list.push_back(tuto);

	DanStage s1;
	s1.name = "符卡一 · 环舞";
	s1.pages = {"环形弹幕向四周散开", "寻找空隙躲避"};
	s1.diff_mult = 1.0f;
	s1.base_speed = 1.1f;
	s1.notes = {
		{0.5f,32,7, B_CIRCLE, {14}},
		{2.0f,32,7, B_CIRCLE, {16}},
		{3.2f,12,8, B_AIM, {}},
		{3.2f,52,8, B_AIM, {}},
		{4.5f,32,7, B_FAN, {10,70,180}},
		{6.5f,32,7, B_CIRCLE, {18}},
	};
	dan_stage_list.push_back(s1);

	DanStage s2;
	s2.name = "符卡二 · 回旋";
	s2.pages = {"螺旋弹幕缓缓扩张", "不要被逼到角落"};
	s2.diff_mult = 1.1f;
	s2.base_speed = 1.25f;
	s2.notes = {
		{0.5f,32,6, B_SPIRAL, {2}}, // args[0]=螺旋臂数量
		{2.5f,10,8, B_BOUNCE, {30,2}},
		{2.5f,54,8, B_BOUNCE, {150,2}},
		{4.8f,32,6, B_FAN, {10,75,180}},
		{6.8f,32,6, B_SPIRAL, {2, 180.0f}},
	};
	dan_stage_list.push_back(s2);

	DanStage s3;
	s3.name = "符卡三 · 疾行";
	s3.pages = {"加速弹越飞越快", "反弹弹可在墙上来回弹"};
	s3.diff_mult = 1.2f;
	s3.base_speed = 1.4f;
	s3.notes = {
		{0.5f,32,6, B_ACCEL, {90,80}},
		{1.8f,16,6, B_BOUNCE, {45,2}},
		{1.8f,48,6, B_BOUNCE, {135,2}},
		{3.5f,32,6, B_DELAY, {90,1.0}},
		{5.2f,32,6, B_CIRCLE, {20}},
		{5.8f,32,6, B_SPIRAL, {2}},
	};
	dan_stage_list.push_back(s3);

	DanStage s4;
	s4.name = "符卡四 · 龙息";
	s4.pages = {"龙骨炮蓄力时显示 3x3 警告框", "看到 D 立刻离开射线方向", "激光是线段,斜着也能命中"};
	s4.diff_mult = 1.15f;
	s4.base_speed = 1.3f;
	s4.notes = {
		{0.5f, 32, 4,  B_BLASTER,     {90}},
		{0.5f, 10, 16, B_BLASTER,     {0}},
		{0.5f, 54, 16, B_BLASTER,     {180}},
		{2.2f, 32, 4,  B_BLASTER_AIM, {}},
		{3.8f, 16, 16, B_BLASTER,     {45}},
		{3.8f, 48, 16, B_BLASTER,     {135}},
		{5.5f, 32, 4,  B_BLASTER_AIM, {0.7f, 0.4f, 40}},
	};
	dan_stage_list.push_back(s4);
}

void bullet_update(float dt) {
	if(overlay != OVERLAY_NONE || gameover || win) return;
	for(auto& b : bullets) {
		if(!b.active) continue;
		if(b.type == B_DELAY && b.delay_timer > 0) {
			b.delay_timer -= dt;
			if(b.delay_timer > 0) {
				if(b.x < -2 || b.x > W+2 || b.y < -2 || b.y > H+2) b.active = false;
				continue;
			}
		}
		if(b.type == B_BLASTER || b.type == B_BLASTER_AIM) {
			if(b.delay_timer > 0) {
				b.delay_timer -= dt;
				if(b.delay_timer < 0) b.delay_timer = 0;
			} else {
				b.acc -= dt;
				if(b.acc <= 0) b.active = false;
			}
			continue;
		}
		if(b.type == B_ACCEL) {
			float len = hypot(b.vx, b.vy);
			if(len > 1e-3) {
				b.vx += b.vx / len * b.acc * dt;
				b.vy += b.vy / len * b.acc * dt;
			}
		}
		if(b.type == B_SPIRAL) {
			// ========= S1修复螺旋弹运动学 正确公式 =========
			b.spiral_ang += dt * SPIRAL_ROT_SPEED;
			float life = game_timer - b.birth;
			float vr = b.speed * SPIRAL_EXPAND_RATE;
			float r = vr * life;
			b.x = b.spiral_x0 + r * cos(b.spiral_ang);
			b.y = b.spiral_y0 + r * sin(b.spiral_ang);
		} else {
			b.x += b.vx * dt;
			b.y += b.vy * dt;
		}
		if(b.type == B_BOUNCE) {
			const float wall_margin = BULLET_R + 0.05f;
			if(b.x < wall_margin || b.x > W - wall_margin) {
				b.vx *= -1;
				b.x = clamp(b.x, wall_margin, W-wall_margin);
				b.bounce_left--;
				if(b.bounce_left <=0) b.active = false;
			}
			if(b.y < wall_margin || b.y > H - wall_margin) {
				b.vy *= -1;
				b.y = clamp(b.y, wall_margin, H-wall_margin);
				b.bounce_left--;
				if(b.bounce_left <=0) b.active = false;
			}
		} else {
			if(b.x < -2 || b.x > W+2 || b.y < -2 || b.y > H+2) {
				b.active = false;
			}
		}
	}
	bullets.erase(std::remove_if(bullets.begin(), bullets.end(), [](const Bullet& b) {
		return !b.active;
	}), bullets.end());
}

void player_update(float dt) {
	if(gameover || win || overlay != OVERLAY_NONE) return;
	float dx=0, dy=0;
	if(key['W']) dy -=1;
	if(key['S']) dy +=1;
	if(key['A']) dx -=1;
	if(key['D']) dx +=1;
	float len = hypot(dx, dy);
	bool slow_key = key[VK_LSHIFT] || key[VK_RSHIFT];
	float sp = slow_key ? PLAYER_SPEED_SLOW : PLAYER_SPEED;
	if(len > 1e-3) {
		dx /= len;
		dy /= len;
	}
	pl.x += dx * sp * dt;
	pl.y += dy * sp * dt;
	pl.x = clamp(pl.x, 1.0f, (float)(W-2));
	pl.y = clamp(pl.y, 1.0f, (float)(H-2));
	if(pl.invincible > 0) pl.invincible -= dt;
}

float point_seg_dist(float px, float py, float x0, float y0, float x1, float y1) {
	float dx = x1 - x0, dy = y1 - y0;
	float len2 = dx * dx + dy * dy;
	if(len2 < 1e-6f) return hypot(px - x0, py - y0);
	float t = ((px - x0) * dx + (py - y0) * dy) / len2;
	t = clamp(t, 0.0f, 1.0f);
	float cx = x0 + t * dx, cy = y0 + t * dy;
	return hypot(px - cx, py - cy);
}

bool collision_and_graze_check() {
	if(gameover || win || pl.invincible>0 || overlay != OVERLAY_NONE) return false;
	bool grazed = false;
	for(auto& b : bullets) {
		if(!b.active) continue;
		if(b.type == B_DELAY && b.delay_timer > 0) continue;
		if(b.type == B_BLASTER || b.type == B_BLASTER_AIM) {
			if(b.delay_timer > 0) continue;   // 蓄力不伤害
			float x1 = b.x + cos(b.spiral_ang) * b.speed;
			float y1 = b.y + sin(b.spiral_ang) * b.speed;
			float d = point_seg_dist(pl.x, pl.y, b.x, b.y, x1, y1);
			if(d < PLAYER_HIT_R + 0.5f) {
				if(!god_mode) {
					pl.hp--;
					pl.invincible = 1.2f;
					sc.hurt();
					if(pl.hp <= 0) gameover = true;
				}
				return false;
			}
			if(!grazed && d < GRAZE_R + 0.8f) grazed = true;
			continue;
		}
		float dx = b.x - pl.x;
		float dy = b.y - pl.y;
		float dist = hypot(dx, dy);
		if(dist < PLAYER_HIT_R + BULLET_R) {
			if(!god_mode) {
				pl.hp--;
				pl.invincible = 1.2f;
				sc.hurt();
				if(pl.hp <= 0) gameover = true;
			}
			return false;
		}
		if(!grazed && dist < GRAZE_R + BULLET_R) {
			grazed = true;
		}
	}
	if(grazed) {
		sc.add(GRAZE_SCORE * sc.mult);
		sc.refresh_combo();
	}
	return grazed;
}

void spawn_logic(float dt, std::vector<DanStage> &stage_list) {
	if(gameover || win || overlay != OVERLAY_NONE) return;
	if(gmode == MODE_CHALLENGE || gmode == MODE_DIY) {
		DanStage &st = stage_list[cur_stage_idx];
		while(note_ptr < (int)st.notes.size() && st.notes[note_ptr].time <= game_timer) {
			// M6 + M9修复:全局diff_rate ×关卡diff_mult,共同缩放弹幕速度
			float total_speed_scale = st.base_speed * st.diff_mult * diff_rate;
			spawn_event(st.notes[note_ptr], pl.x, pl.y, game_timer, total_speed_scale);
			note_ptr++;
		}
		if(note_ptr >= (int)st.notes.size() && bullets.empty()) {
			overlay = OVERLAY_CLEARWAIT;
		}
	} else if(gmode == MODE_ENDLESS) {
		spawn_t += dt;
		float sp_int = clamp(ENDLESS_SPAWN_BASE / diff_rate / get_bullet_count_mult(), ENDLESS_SPAWN_MIN, ENDLESS_SPAWN_MAX);
		if(spawn_t > sp_int) {
			spawn_t = 0;
			NoteEvent e;
			e.x = 1 + rand()%(W-2);
			e.y = 2 + rand()%(H/3);
			int r = rand()%10;
			if(r == 8) e.type = B_BLASTER;
			else if(r == 9) e.type = B_BLASTER_AIM;
			else e.type = (BulletType)r;
			if(e.type == B_LINE) e.args = {(float)(rand()%360)};
			else if(e.type == B_AIM) {}
			else if(e.type == B_CIRCLE) e.args = {(float)(CIRCLE_MIN_CNT + rand()%CIRCLE_RAND_ADD)};
			else if(e.type == B_FAN) {
				int fan_cnt = FAN_CNT;
				float fan_total = FAN_MIN_DEG + (FAN_MAX_DEG - FAN_MIN_DEG) * (rand() / (RAND_MAX + 1.0f));
				float dx = pl.x - e.x;
				float dy = pl.y - e.y;
				float center_deg = atan2(dy, dx) * 180.0 / (float)M_PI;
				float start_deg = center_deg - fan_total / 2.0f;
				e.args = {(float)fan_cnt, fan_total, start_deg};
			} else if(e.type == B_SPIRAL) e.args = {2.0f, 0.f};
			else if(e.type == B_BOUNCE) e.args = {(float)(rand()%360), 2.f};
			else if(e.type == B_ACCEL) e.args = {(float)(rand()%360), 75.f};
			else if(e.type == B_DELAY) e.args = {(float)(rand()%360), 0.9f};
			else if(e.type == B_BLASTER) e.args = {(float)(rand()%360)};
			else if(e.type == B_BLASTER_AIM) {}
			spawn_event(e, pl.x, pl.y, game_timer);
		}
	}
}
void render(std::vector<DanStage> &stage_list) {
	COORD pos = {0,0};
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
	char buf[H][W+1];
	int color_buf[H][W];
	for(int y=0; y<H; y++) {
		for(int x=0; x<W; x++) {
			buf[y][x]=' ';
			color_buf[y][x]=C_WHITE;
		}
		buf[y][W] = '\0';
	}
	for(int x=0; x<W; x++) buf[0][x] = '-', buf[H-1][x] = '-';
	for(int y=0; y<H; y++) buf[y][0] = '|', buf[y][W-1] = '|';

	for(auto& b : bullets) {
		if(!b.active) continue;
		if(b.type == B_DELAY && b.delay_timer > 0) continue;

		// ===== 龙骨炮:蓄力警告 + 激光 =====
		if(b.type == B_BLASTER || b.type == B_BLASTER_AIM) {
			float ca = cos(b.spiral_ang), sa = sin(b.spiral_ang);
			int bx = (int)(b.x + 0.5f);
			int by = (int)(b.y + 0.5f);

			if(b.delay_timer > 0) {
				// ---- 蓄力阶段:3×3 警告框 + 闪烁 + 虚线预警 ----
				bool blink = fmod(b.delay_timer * 6.0f, 1.0f) < 0.5f;

				// 3×3 炮台框
				for(int dy = -1; dy <= 1; dy++) {
					for(int dx = -1; dx <= 1; dx++) {
						int nx = bx + dx, ny = by + dy;
						if(nx < 1 || nx >= W-1 || ny < 1 || ny >= H-1) continue;
						if(dx == 0 && dy == 0) {
							buf[ny][nx] = blink ? 'D' : '!';
							color_buf[ny][nx] = blink ? C_BRIGHT : C_LRED;
						} else {
							buf[ny][nx] = '.';
							color_buf[ny][nx] = C_LRED;
						}
					}
				}

				// 激光路径虚线预警(每 2 格一个)
				for(float t = 2.0f; t <= b.speed; t += 2.0f) {
					int lx = (int)(b.x + ca * t + 0.5f);
					int ly = (int)(b.y + sa * t + 0.5f);
					if(lx < 1 || lx >= W-1 || ly < 1 || ly >= H-1) continue;
					buf[ly][lx] = blink ? ':' : '.';
					color_buf[ly][lx] = C_LRED;
				}
			} else {
				// ---- 激光阶段:亮白密集粗线 ----
				char lch = '=';
				if(fabs(ca) < 0.35f) lch = '|';
				else if(fabs(sa) < 0.35f) lch = '-';
				else lch = (ca * sa > 0) ? '\\' : '/';

				// 步长 0.4,密集覆盖
				for(float t = 0; t <= b.speed; t += 0.4f) {
					int lx = (int)(b.x + ca * t + 0.5f);
					int ly = (int)(b.y + sa * t + 0.5f);
					if(lx < 1 || lx >= W-1 || ly < 1 || ly >= H-1) continue;
					buf[ly][lx] = lch;
					color_buf[ly][lx] = C_BRIGHT;
				}

				// 炮口 D 也显示
				if(bx >= 1 && bx < W-1 && by >= 1 && by < H-1) {
					buf[by][bx] = 'D';
					color_buf[by][bx] = C_BRIGHT;
				}
			}
			continue;
		}

		// ===== 普通子弹 =====
		int bx = (int)(b.x + 0.5f);
		int by = (int)(b.y + 0.5f);
		if(bx >= 1 && bx < W-1 && by >= 1 && by < H-1) {
			buf[by][bx] = b.ch;
			color_buf[by][bx] = b.col;
		}
	}
	int px = (int)(pl.x + 0.5f);
	int py = (int)(pl.y + 0.5f);
	bool draw_player = true;
	if(pl.invincible > 0 && fmod(pl.invincible*12,1)>=0.5) draw_player = false;
	if(draw_player && px>=1 && px<W-1 && py>=1 && py<H-1) {
		buf[py][px] = '*';
		color_buf[py][px] = COLOR_PLAYER;
	}

	// 渲染屏幕画面,不再每行reset
	for(int y=0; y<H; y++) {
		int lastcol = color_buf[y][0];
		set_color(lastcol);
		for(int x=0; x<W; x++) {
			if(color_buf[y][x] != lastcol) {
				lastcol = color_buf[y][x];
				set_color(lastcol);
			}
			std::cout << buf[y][x];
		}
		std::cout << "\n";
	}
	reset_color(); // 画面渲染完统一重置颜色!

	set_color(COLOR_UI);
	std::cout << "HP:" << pl.hp << "/" << pl.max_hp
	          << "  Score:" << sc.score
	          << "  x" << sc.mult;
	if(gmode == MODE_CHALLENGE || gmode == MODE_DIY) {
		std::cout << "  Stage:" << cur_stage_idx+1 << "/" << stage_list.size();
	}
	bool slow_key = key[VK_LSHIFT] || key[VK_RSHIFT];
	if(slow_key) std::cout << " [SLOW]";
	if(god_mode) {
		set_color(C_LMAGENTA);
		std::cout << " [GOD]";
		set_color(COLOR_UI);
	}
	if(gameover) {
		set_color(COLOR_WARN);
		std::cout << "  GAME OVER";
	}
	if(win) {
		set_color(COLOR_FAN);
		std::cout << "  ALL CLEAR!";
	}
	reset_color();
	std::cout << "\n";

	if(overlay == OVERLAY_HELP) {
		set_color(COLOR_TITLE);
		std::cout << "\n==== HELP ====\n";
		std::cout << "WASD移动 | Shift低速 | R重开 | H帮助 | ESC返回菜单\n";
		std::cout << "X:快进当前剧情页 | C:下一页剧情 / 通关后进入下一关\n";
		std::cout << "#直线 @自机狙 O环 %扇形 &螺旋 ?反弹 !加速 +滞留\n";
		std::cout << "任意键关闭帮助\n";
		reset_color();
	}
	if(overlay == OVERLAY_STORY) {
		set_color(COLOR_INFO);
		std::cout << "\n==== " << stage_list[cur_stage_idx].name << " ====\n";
		std::cout << dlg.get_display();
		if(dlg.active) {
			std::cout << "\nX=快进 | C=下一页";
		}
		reset_color();
	}
	if(overlay == OVERLAY_CLEARWAIT) {
		set_color(COLOR_FAN);
		std::cout << "\n==== 本关Clear! ====\n";
		std::cout << "按 C 进入下一关";
		reset_color();
	}
	if(overlay == OVERLAY_NONE) {
		std::cout << std::string(W, ' ') << "\n";
		std::cout << std::string(W, ' ') << "\n";
	}
}


bool select_god() {
	clear_screen();
	set_color(COLOR_TITLE);
	std::cout << "==== 无敌模式 ====\n\n";
	reset_color();
	std::cout << "↑ ↓ 选择,回车确认\n\n";
	std::string opt[] = {"关闭无敌", "开启无敌"};
	int sel = 0;
	while(true) {
		update_key();
		clear_screen();
		set_color(COLOR_TITLE);
		std::cout << "==== 无敌模式 ====\n\n";
		reset_color();
		std::cout << "↑ ↓ 选择,回车确认\n\n";
		for(int i=0; i<2; i++) {
			if(i == sel) {
				set_color(COLOR_PLAYER);
				std::cout << " > " << opt[i] << "\n";
			} else {
				std::cout << " " << opt[i] << "\n";
			}
			reset_color();
		}
		if(key[VK_UP] && !last_key[VK_UP]) {
			sel = clamp(sel-1,0,1);
		}
		if(key[VK_DOWN] && !last_key[VK_DOWN]) {
			sel = clamp(sel+1,0,1);
		}
		if(key[VK_RETURN] && !last_key[VK_RETURN]) {
			return sel == 1;
		}
		if(key[VK_ESCAPE] && !last_key[VK_ESCAPE]) {
			return false;
		}
		Sleep(80);
	}
}
Difficulty select_diff() {
	clear_screen();
	set_color(COLOR_TITLE);
	std::cout << "==== 难度选择 ====\n\n";
	reset_color();
	std::cout << "↑ ↓ 选择,回车确认\n\n";
	std::string opt[] = {"简单", "普通", "困难"};
	int sel = 1;
	while(true) {
		update_key();
		clear_screen();
		set_color(COLOR_TITLE);
		std::cout << "==== 难度选择 ====\n\n";
		reset_color();
		std::cout << "↑ ↓ 选择,回车确认\n\n";
		for(int i=0; i<3; i++) {
			if(i == sel) {
				set_color(COLOR_PLAYER);
				std::cout << " > " << opt[i] << "\n";
			} else {
				std::cout << " " << opt[i] << "\n";
			}
			reset_color();
		}
		if(key[VK_UP] && !last_key[VK_UP]) {
			sel = clamp(sel-1,0,2);
		}
		if(key[VK_DOWN] && !last_key[VK_DOWN]) {
			sel = clamp(sel+1,0,2);
		}
		if(key[VK_RETURN] && !last_key[VK_RETURN]) {
			if(sel ==0) diff_rate = 0.65f;
			if(sel ==1) diff_rate = 1.00f;
			if(sel ==2) diff_rate = 1.40f;
			return (Difficulty)sel;
		}
		if(key[VK_ESCAPE] && !last_key[VK_ESCAPE]) {
			diff_rate = 1.00f;
			return D_NORMAL;
		}
		Sleep(80);
	}
}
GameMode main_menu() {
	clear_screen();
	set_color(COLOR_TITLE);
	std::cout << "=====================\n";
	std::cout << " 控制台弹幕游戏\n";
	std::cout << "=====================\n\n";
	reset_color();
	std::string opt[] = {"挑战模式", "无尽模式", "DIY弹幕", "退出"};
	int sel = 0;
	while(true) {
		update_key();
		clear_screen();
		set_color(COLOR_TITLE);
		std::cout << "=====================\n"
		          << " 控制台弹幕游戏\n"
		          << "=====================\n\n" << std::flush;
		reset_color();
		std::cout << "↑ ↓ 选择,回车确认\n\n";
		for(int i=0; i<4; i++) {
			if(i == sel) {
				set_color(COLOR_PLAYER);
				std::cout << " > " << opt[i] << "\n";
			} else {
				std::cout << " " << opt[i] << "\n";
			}
			reset_color();
		}
		if(key[VK_UP] && !last_key[VK_UP]) {
			sel = clamp(sel-1,0,3);
		}
		if(key[VK_DOWN] && !last_key[VK_DOWN]) {
			sel = clamp(sel+1,0,3);
		}
		if(key[VK_RETURN] && !last_key[VK_RETURN]) {
			if(sel == 0) return MODE_CHALLENGE;
			if(sel == 1) return MODE_ENDLESS;
			if(sel == 2) return MODE_DIY;
			if(sel == 3) exit(0);
		}
		if(key[VK_ESCAPE] && !last_key[VK_ESCAPE]) {
			return MODE_CHALLENGE;
		}
		Sleep(80);
	}
}

int main() {
	HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

	// 安全地设置窗口大小:先扩缓冲 → 缩窗口 → 缩缓冲
	{
		CONSOLE_SCREEN_BUFFER_INFO csbi;
		GetConsoleScreenBufferInfo(hConsole, &csbi);
		SHORT tw = (SHORT)(W + 6);
		SHORT th = (SHORT)(H + 12);
		if(csbi.dwSize.X < tw || csbi.dwSize.Y < th) {
			COORD big;
			big.X = csbi.dwSize.X > tw ? csbi.dwSize.X : tw;
			big.Y = csbi.dwSize.Y > th ? csbi.dwSize.Y : th;
			SetConsoleScreenBufferSize(hConsole, big);
		}
		SMALL_RECT winRect = {0, 0, (SHORT)(tw-1), (SHORT)(th-1)};
		SetConsoleWindowInfo(hConsole, TRUE, &winRect);
		COORD bufSize;
		bufSize.X = tw;
		bufSize.Y = th;
		SetConsoleScreenBufferSize(hConsole, bufSize);
	}

	srand((unsigned)time(NULL));
	build_builtin_stages();
	CONSOLE_CURSOR_INFO info;
	info.dwSize = 1;
	info.bVisible = FALSE;
	SetConsoleCursorInfo(hConsole, &info);

	float accumulator = 0.f;
	DWORD prev_tick = GetTickCount();

	while(true) {
		std::string danfile;
		GameMode md = main_menu();
		std::vector<DanStage> *use_list = nullptr;
		bool start_ok = false;

		if(md == MODE_DIY) {
			danfile = select_dan_file();
			if(danfile.empty()) continue;
			load_danmaku(danfile, diy_stage_list);
			if(diy_stage_list.empty()) continue;
			use_list = &diy_stage_list;
			god_mode = select_god();
			select_diff();
			reset_game(md);
			cur_stage_idx = 0;
			if(!preview_stage((*use_list)[cur_stage_idx])) continue;
			enter_stage(0, *use_list);
			start_ok = true;
		} else if(md == MODE_CHALLENGE) {
			use_list = &dan_stage_list;
			god_mode = select_god();
			select_diff();
			reset_game(md);
			cur_stage_idx = 0;
			if(!preview_stage((*use_list)[cur_stage_idx])) continue;
			enter_stage(0, *use_list);
			start_ok = true;
		} else if(md == MODE_ENDLESS) {
			use_list = nullptr;
			god_mode = select_god();
			select_diff();
			reset_game(md);
			start_ok = true;
		}
		if(!start_ok) continue;

		running = true;
		accumulator = 0.f;
		prev_tick = GetTickCount();

		while(running) {
			DWORD now_tick = GetTickCount();
			float real_dt = (now_tick - prev_tick) / 1000.0f;
			prev_tick = now_tick;
			if(real_dt > 0.2f) real_dt = 0.2f;
			accumulator += real_dt;
			if(accumulator > 0.25f) accumulator = 0.25f;

			update_key();

// ---------- 全局快捷键(剧情期间禁用会冲突的键) ----------
if(key[VK_ESCAPE] && !last_key[VK_ESCAPE]) { running = false; break; }

if(overlay != OVERLAY_STORY && overlay != OVERLAY_CLEARWAIT) {
    if(key['H'] && !last_key['H']) {
        overlay = (overlay == OVERLAY_HELP) ? OVERLAY_NONE : OVERLAY_HELP;
        clear_screen();
    }
    if(key['R'] && !last_key['R']) {
        // ... 保持你原有的 R 重开逻辑,把 system("cls") 换成 clear_screen() ...
    }
}

// ---------- 剧情状态:独立处理,不推进游戏时间 ----------
if(overlay == OVERLAY_STORY) {
    accumulator = 0.f;                       // 剧情期间彻底冻结游戏时钟
    dlg.update(real_dt);                     // 打字机按真实时间推进

    if(key['X'] && !last_key['X']) dlg.fast_forward();

    if(key['C'] && !last_key['C']) {
        // 允许随时翻页(即使没打完),也可改成 if(dlg.page_done())
        if(!dlg.next_page()) {
            overlay = OVERLAY_NONE;
            dlg.stop();
            clear_screen();                  // 干净地回到游戏画面
        }
    }

    if(use_list) render(*use_list);
    else render(dan_stage_list);
    Sleep(FRAME_DELAY);
    continue;                                // 跳过一切游戏逻辑
}

// ---------- 正常游戏 ----------
accumulator += real_dt;
if(accumulator > 0.25f) accumulator = 0.25f;

if(key['C'] && !last_key['C'] && overlay == OVERLAY_CLEARWAIT && use_list != nullptr) {
    cur_stage_idx++;
    if(cur_stage_idx >= (int)use_list->size()) {
        win = true;
        overlay = OVERLAY_NONE;
    } else {
        if(!preview_stage((*use_list)[cur_stage_idx])) { running = false; break; }
        enter_stage(cur_stage_idx, *use_list);
    }
}

while(accumulator >= FIXED_DT) {
    if(!gameover && !win && overlay == OVERLAY_NONE) {
        game_timer += FIXED_DT;
        sc.add_tick(FIXED_DT, diff_rate);
        sc.tick(FIXED_DT);
    }
    spawn_logic(FIXED_DT, use_list ? *use_list : dan_stage_list);
    bullet_update(FIXED_DT);
    player_update(FIXED_DT);
    collision_and_graze_check();
    accumulator -= FIXED_DT;
}

if(use_list) render(*use_list);
else render(dan_stage_list);
update_key();          // 渲染后再采一次,缩小边沿丢失窗口
Sleep(FRAME_DELAY);
		}
	}
	reset_color();
	return 0;
}

附带谱子(ANSI编码,.danmaku文件)

danmaku
stage
name "反弹子+龙骨炮"
page "无伤就可以出新手村了"
diff 0.5
base_speed 2.0
note 0.5  32 4  bounce rand 30
note 1.0   8 6  bounce rand 30
note 1.5  55 5  bounce rand 30
note 2.0  20 8  bounce rand 30
note 2.0   4 2  blaster_aim 0.7 0.4 45
note 2.5  44 3  bounce rand 30
note 3.0  12 7  bounce rand 30
note 3.5  50 6  bounce rand 20
note 4.0  28 5  bounce rand 30
note 4.0  60 2  blaster_aim 0.7 0.4 45
note 4.5  60 8  bounce rand 30
note 5.0  16 4  bounce rand 20
note 5.5  38 6  bounce rand 30
note 6.0   6 5  bounce rand 30
note 6.0   4 2  blaster_aim 0.6 0.4 50
note 6.5  52 7  bounce rand 20
note 7.0  24 3  bounce rand 30
note 7.5  46 8  bounce rand 30
note 8.0  10 6  bounce rand 20
note 8.0  60 2  blaster_aim 0.6 0.4 50
note 8.5  34 4  bounce rand 30
note 9.0  58 5  bounce rand 30
note 9.5  18 7  bounce rand 20
note 10.0 40 6  bounce rand 30
note 10.0 32 2  blaster_aim 0.5 0.5 55
}