一点万用
小板子
#include<bits/stdc++.h>
using namespace std;
#define int long long//
#define ll long long
#define endl '\n'
constexpr int maxn=1e6+10;
constexpr int maxm=1e4+10;
constexpr ll INF=(LLONG_MAX>>1)-1ll;//1e9
constexpr int MOD=0;
void solve()
{
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
// ll T;cin >> T ;while(T--)
solve();
}变量全集+快读快写
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second
#define rep(i,a,b) for(ll i=(a);i<=(b);i++)
#define per(i,a,b) for(ll i=(a);i>=(b);i--)
#define debug(x) cerr << #x <<" = "<< x << endl
constexpr ll maxn=5e5+10;
constexpr ll maxm=1e4+10;
constexpr ll maxl=8e4+10;
constexpr ll MOD=1e9+7;
constexpr ll INF=(LLONG_MAX>>1)-1ll;
constexpr ll inf=1e9;
constexpr double pi=acos(-1);
constexpr double eps=1e-9;
ll a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,r,u,v,w,x,y,z;
ll T,len,ans,res,ret,cnt,__,st[maxn],sum[maxn],dp[maxm],ndp[maxm][maxm];
ll mi=INF,mx=-INF,inv[maxn],fac[maxn],ifac[maxn],phi[maxn],mu[maxn];
ll in[maxn],out[maxn],dfn[maxn],low[maxn],fa[maxn][20],depth[maxn];
ll lz[maxn<<2],L[maxn],R[maxn],pre[maxn],suf[maxn],diff[maxn];
ll son[maxn],color[maxn],answers[maxn],head[maxn],to[maxn<<1];
ll nxt[maxn<<1],w[maxn<<1],ecnt,id[maxn],rk[maxn],idx,enums;
ll bit[maxn],seg[maxn<<1],laz[maxn],ST[maxn][25],step,dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
ll sr[maxn],___[maxn];//输入
string s,t;
bool ok,isprime[maxn];
char S;
vector<ll> prime;
vector<vector<ll>> gra;
vector<pair<ll,ll>> G[maxm];
pair<ll,ll> piar[maxn];
map<ll,ll> ma;
/*priority_*/queue<ll> q;
unordered_map<ll,ll> ump;
unordered_set<ll> uset;
deque<ll> dq;
multiset<ll> ms;
priority_queue<ll,vector<ll>,greater<ll>> pq_min;
template<typename anytype>
void read(anytype &x)
{
x=0;
char ch=getchar();
ll f=1;
while(!isdigit(ch))
{
if(ch=='-') f=-1;
ch=getchar();
}
while(isdigit(ch))
{
x=x*10+ch-'0';
ch=getchar();
}
x*=f;
}
template<typename anytype>
void write(anytype x)
{
if(x<0)
{
putchar('-');
x=-x;
}
if(x>9) write(x/10);
putchar(x%10+'0');
}
void solve()
{
}
signed main()
{
// cin >> T;while(T--)
solve();
}少量初始化
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second
#define rep(i,a,b) for(ll i=(a);i<=(b);i++)
#define per(i,a,b) for(ll i=(a);i>=(b);i--)
#define debug(x) cerr << #x <<" = "<< x << endl
constexpr ll maxn=5e5+10;
constexpr ll maxm=1e4+10;
constexpr ll maxl=8e4+10;
constexpr ll MOD=1e9+7;
constexpr ll INF=(LLONG_MAX>>1)-1ll;
constexpr ll inf=1e9;
constexpr double pi=acos(-1);
constexpr double eps=1e-9;
ll a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,r,u,v,x,y,z;
ll T,len,ans,res,ret,cnt,__,st[maxn],sum[maxn],dp[maxm],ndp[maxm][maxm];
ll mi=INF,mx=-INF,inv[maxn],fac[maxn],ifac[maxn],phi[maxn],mu[maxn];
ll in[maxn],out[maxn],dfn[maxn],low[maxn],fa[maxn][20],depth[maxn];
ll lz[maxn<<2],L[maxn],R[maxn],pre[maxn],suf[maxn],diff[maxn];
ll son[maxn],color[maxn],answers[maxn],head[maxn],to[maxn<<1];
ll nxt[maxn<<1],w[maxn<<1],ecnt,id[maxn],rk[maxn],idx,enums;
ll bit[maxn],seg[maxn<<1],laz[maxn],ST[maxn][25],step,dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
ll sr[maxn],___[maxn];//输入
string s,t;
bool ok,isprime[maxn];
char S;
vector<ll> prime;
vector<vector<ll>> gra;
vector<pair<ll,ll>> G[maxm];
pair<ll,ll> piar[maxn];
map<ll,ll> ma;
/*priority_*/queue<ll> q;
unordered_map<ll,ll> ump;
unordered_set<ll> uset;
deque<ll> dq;
multiset<ll> ms;
priority_queue<ll,vector<ll>,greater<ll>> pq_min;
template<typename anytype>
void read(anytype &x)
{
x=0;
char ch=getchar();
ll f=1;
while(!isdigit(ch))
{
if(ch=='-') f=-1;
ch=getchar();
}
while(isdigit(ch))
{
x=x*10+ch-'0';
ch=getchar();
}
x*=f;
}
template<typename anytype>
void write(anytype x)
{
if(x<0)
{
putchar('-');
x=-x;
}
if(x>9) write(x/10);
putchar(x%10+'0');
}
ll gcd(ll a,ll b)
{
return b?gcd(b,a%b):a;
}
ll lcm(ll a,ll b)
{
return a/gcd(a,b)*b;
}
ll qpow(ll a,ll b,ll mo)
{
ll ret=1;
while(b)
{
if(b&1) ret=ret*a%mo;
b>>=1;
a=a*a%mo;
}
return ret;
}
void init()
{
fac[0]=1;
rep(i,1,maxn-1) fac[i]=fac[i-1]*i%MOD;
ifac[maxn-1]=qpow(fac[maxn-1],MOD-2,MOD);
per(i,maxn-2,0) ifac[i]=ifac[i+1]*(i+1)%MOD;
inv[1]=1;
rep(i,2,maxn-1) inv[i]=(MOD-MOD/i)*inv[MOD%i]%MOD;
fill(isprime,isprime+maxn,1);
isprime[0]=isprime[1]=0;
phi[1]=1;
mu[1]=1;
rep(i,2,maxn - 1)
{
if(isprime[i])
{
prime.pb(i);
phi[i]=i-1;
mu[i]=-1;
}
for(ll j=0; j<prime.size() && i * prime[j]<maxn; j++)
{
ll p=prime[j];
isprime[i*p]=0;
if(!(i%p))
{
phi[i * p]=phi[i]*p;
mu[i * p]=0;
break;
}
else
{
phi[i * p]=phi[i]*(p-1);
mu[i * p]=-mu[i];
}
}
}
rep(i,1,maxn - 1)
{
fa[i][0]=i;
}
}
void solve()
{
}
signed main()
{
// cin >> T;while(T--)
solve();
}永乐大典!!!
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second
#define rep(i,a,b) for(ll i=(a);i<=(b);i++)
#define per(i,a,b) for(ll i=(a);i>=(b);i--)
#define debug(x) cerr << #x <<" = "<< x << endl
constexpr ll maxn=5e5+10;
constexpr ll maxm=1e4+10;
constexpr ll maxl=8e4+10;
constexpr ll MOD=1e9+7;
constexpr ll INF=(LLONG_MAX>>1)-1ll;
constexpr ll inf=1e9;
constexpr double pi=acos(-1);
constexpr double eps=1e-9;
ll a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,r,u,v,x,y,z;
ll T,len,ans,res,ret,cnt,__,st[maxn],sum[maxn],dp[maxm],ndp[maxm][maxm];
ll mi=INF,mx=-INF,inv[maxn],fac[maxn],ifac[maxn],phi[maxn],mu[maxn];
ll in[maxn],out[maxn],dfn[maxn],low[maxn],fa[maxn][20],depth[maxn];
ll lz[maxn<<2],L[maxn],R[maxn],pre[maxn],suf[maxn],diff[maxn];
ll son[maxn],color[maxn],answers[maxn],head[maxn],to[maxn<<1];
ll nxt[maxn<<1],w[maxn<<1],ecnt,id[maxn],rk[maxn],idx,enums;
ll bit[maxn],seg[maxn<<1],laz[maxn],ST[maxn][25],step,dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
ll sr[maxn],___[maxn];
string s,t;
bool ok,isprime[maxn];
char S;
vector<ll> prime;
vector<vector<ll>> gra;
vector<pair<ll,ll>> G[maxm];
pair<ll,ll> piar[maxn];
map<ll,ll> ma;
/*priority_*/queue<ll> q;
unordered_map<ll,ll> ump;
unordered_set<ll> uset;
deque<ll> dq;
multiset<ll> ms;
priority_queue<ll,vector<ll>,greater<ll>> pq_min;
template<typename anytype>
void read(anytype &x)
{
x=0;
char ch=getchar();
ll f=1;
while(!isdigit(ch))
{
if(ch=='-') f=-1;
ch=getchar();
}
while(isdigit(ch))
{
x=x*10+ch-'0';
ch=getchar();
}
x*=f;
}
template<typename anytype>
void write(anytype x)
{
if(x<0)
{
putchar('-');
x=-x;
}
if(x>9) write(x/10);
putchar(x%10+'0');
}
ll gcd(ll a,ll b)
{
return b?gcd(b,a%b):a;
}
ll lcm(ll a,ll b)
{
return a/gcd(a,b)*b;
}
ll qpow(ll a,ll b,ll mo)
{
ll ret=1;
while(b)
{
if(b&1) ret=ret*a%mo;
b>>=1;
a=a*a%mo;
}
return ret;
}
ll exgcd(ll a,ll b,ll &x,ll &y)
{
if(!b)
{
x=1;
y=0;
return a;
}
ll d=exgcd(b,a%b,y,x);
y-=a/b*x;
return d;
}
//init
void init()
{
fac[0]=1;
rep(i,1,maxn-1) fac[i]=fac[i-1]*i%MOD;
ifac[maxn-1]=qpow(fac[maxn-1],MOD-2,MOD);
per(i,maxn-2,0) ifac[i]=ifac[i+1]*(i+1)%MOD;
inv[1]=1;
rep(i,2,maxn-1) inv[i]=(MOD-MOD/i)*inv[MOD%i]%MOD;
fill(isprime,isprime+maxn,1);
isprime[0]=isprime[1]=0;
phi[1]=1;
mu[1]=1;
rep(i,2,maxn-1)
{
if(isprime[i])
{
prime.pb(i);
phi[i]=i-1;
mu[i]=-1;
}
for(ll j=0; j<prime.size() && i*prime[j]<maxn; j++)
{
ll p=prime[j];
isprime[i*p]=0;
if(i%p==0)
{
phi[i*p]=phi[i]*p;
mu[i*p]=0;
break;
}
else
{
phi[i*p]=phi[i]*(p-1);
mu[i*p]=-mu[i];
}
}
}
rep(i,1,maxn-1) fa[i][0]=i;
memset(head,-1,sizeof(head));
ecnt=0;
}
//DSU
ll ufs[maxn], sz[maxn];
ll find(ll x)
{
return ufs[x]==x?x:ufs[x]=find(ufs[x]);
}
void unite(ll a,ll b)
{
a=find(a);
b=find(b);
if(a==b) return;
if(sz[a]<sz[b]) swap(a,b);
ufs[b]=a;
sz[a]+=sz[b];
}
void init_ufs()
{
rep(i,1,maxn-1) ufs[i]=i, sz[i]=1;
}
//Trie
struct Trie
{
int ch[maxn][26], val[maxn], tot;
Trie()
{
memset(ch[0],0,sizeof(ch[0]));
val[0]=0;
tot=0;
}
void insert(char *s)
{
int u=0;
for(int i=0; s[i]; i++)
{
int c=s[i]-'a';
if(!ch[u][c])
{
ch[u][c]=++tot;
memset(ch[tot],0,sizeof(ch[tot]));
val[tot]=0;
}
u=ch[u][c];
}
val[u]++;
}
int query(char *s)
{
int u=0;
for(int i=0; s[i]; i++)
{
int c=s[i]-'a';
if(!ch[u][c]) return 0;
u=ch[u][c];
}
return val[u];
}
};
//Ac
struct AhoCorasick
{
int ch[maxn][26], fail[maxn], val[maxn], tot;
void init()
{
tot=0;
memset(ch[0],0,sizeof(ch[0]));
fail[0]=val[0]=0;
}
void insert(char *s)
{
int u=0;
for(int i=0; s[i]; i++)
{
int c=s[i]-'a';
if(!ch[u][c])
{
ch[u][c]=++tot;
memset(ch[tot],0,sizeof(ch[tot]));
val[tot]=0;
}
u=ch[u][c];
}
val[u]++;
}
void build()
{
queue<int> q;
for(int c=0; c<26; c++)
{
if(ch[0][c])
{
fail[ch[0][c]]=0;
q.push(ch[0][c]);
}
}
while(!q.empty())
{
int u=q.front();
q.pop();
for(int c=0; c<26; c++)
{
int v=ch[u][c];
if(v)
{
fail[v]=ch[fail[u]][c];
q.push(v);
}
else
{
ch[u][c]=ch[fail[u]][c];
}
}
}
}
int query(char *s)
{
int u=0, res=0;
for(int i=0; s[i]; i++)
{
u=ch[u][s[i]-'a'];
for(int t=u; t && val[t]!=-1; t=fail[t])
{
res += val[t];
val[t]=-1;
}
}
return res;
}
};
//Z
vector<int> z_function(string s)
{
int n=s.size();
vector<int> z(n);
int l=0,r=0;
for(int i=1; i<n; i++)
{
if(i<=r) z[i]=min(r-i+1, z[i-l]);
while(i+z[i]<n && s[z[i]]==s[i+z[i]]) z[i]++;
if(i+z[i]-1>r) l=i, r=i+z[i]-1;
}
return z;
}
//Seg
struct SegTree
{
ll sum[maxn<<2], lazy[maxn<<2];
void pushup(int rt)
{
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void pushdown(int rt,int l,int r)
{
if(lazy[rt])
{
int mid=(l+r)>>1;
lazy[rt<<1]+=lazy[rt];
lazy[rt<<1|1]+=lazy[rt];
sum[rt<<1]+=lazy[rt]*(mid-l+1);
sum[rt<<1|1]+=lazy[rt]*(r-mid);
lazy[rt]=0;
}
}
void build(int rt,int l,int r,ll arr[])
{
lazy[rt]=0;
if(l==r)
{
sum[rt]=arr[l];
return;
}
int mid=(l+r)>>1;
build(rt<<1,l,mid,arr);
build(rt<<1|1,mid+1,r,arr);
pushup(rt);
}
void update(int rt,int l,int r,int ql,int qr,ll val)
{
if(ql<=l && r<=qr)
{
sum[rt]+=val*(r-l+1);
lazy[rt]+=val;
return;
}
pushdown(rt,l,r);
int mid=(l+r)>>1;
if(ql<=mid) update(rt<<1,l,mid,ql,qr,val);
if(qr>mid) update(rt<<1|1,mid+1,r,ql,qr,val);
pushup(rt);
}
ll query(int rt,int l,int r,int ql,int qr)
{
if(ql<=l && r<=qr) return sum[rt];
pushdown(rt,l,r);
int mid=(l+r)>>1;
ll res=0;
if(ql<=mid) res+=query(rt<<1,l,mid,ql,qr);
if(qr>mid) res+=query(rt<<1|1,mid+1,r,ql,qr);
return res;
}
};
//Splay
struct Treap
{
int ch[maxn][2], sz[maxn], val[maxn], pri[maxn], tot;
void init()
{
tot=0;
ch[0][0]=ch[0][1]=0;
sz[0]=0;
}
int newnode(int v)
{
++tot;
ch[tot][0]=ch[tot][1]=0;
sz[tot]=1;
val[tot]=v;
pri[tot]=rand();
return tot;
}
void pushup(int x)
{
sz[x]=sz[ch[x][0]]+sz[ch[x][1]]+1;
}
void split(int rt,int k,int &x,int &y)
{
if(!rt)
{
x=y=0;
return;
}
if(val[rt]<=k)
{
x=rt;
split(ch[rt][1],k,ch[rt][1],y);
}
else
{
y=rt;
split(ch[rt][0],k,x,ch[rt][0]);
}
pushup(rt);
}
int merge(int x,int y)
{
if(!x || !y) return x+y;
if(pri[x]<pri[y])
{
ch[x][1]=merge(ch[x][1],y);
pushup(x);
return x;
}
else
{
ch[y][0]=merge(x,ch[y][0]);
pushup(y);
return y;
}
}
void insert(int &rt,int v)
{
int x,y;
split(rt,v,x,y);
rt=merge(merge(x,newnode(v)),y);
}
void erase(int &rt,int v)
{
int x,y,z;
split(rt,v,x,z);
split(x,v-1,x,y);
y=merge(ch[y][0],ch[y][1]);
rt=merge(merge(x,y),z);
}
int get_kth(int rt,int k)
{
while(true)
{
int ls=sz[ch[rt][0]];
if(k<=ls) rt=ch[rt][0];
else if(k==ls+1) return val[rt];
else
{
k-=ls+1;
rt=ch[rt][1];
}
}
}
int get_rank(int &rt,int v)
{
int x,y;
split(rt,v-1,x,y);
int ans=sz[x]+1;
rt=merge(x,y);
return ans;
}
int get_prev(int &rt,int v)
{
int x,y;
split(rt,v-1,x,y);
int ans=-1;
if(x)
{
int cur=x;
while(ch[cur][1]) cur=ch[cur][1];
ans=val[cur];
}
rt=merge(x,y);
return ans;
}
int get_next(int &rt,int v)
{
int x,y;
split(rt,v,x,y);
int ans=-1;
if(y)
{
int cur=y;
while(ch[cur][0]) cur=ch[cur][0];
ans=val[cur];
}
rt=merge(x,y);
return ans;
}
};
struct Edge
{
int to, w;
};
vector<Edge> G_dij[maxn];
ll dis[maxn];
bool vis[maxn];
void add_edge(int u,int v,int w)
{
G_dij[u].pb({v,w});
}
void dijkstra(int s)
{
priority_queue<pair<ll,int>, vector<pair<ll,int>>, greater<pair<ll,int>>> pq;
fill(dis, dis+maxn, INF);
memset(vis, 0, sizeof(vis));
dis[s]=0;
pq.push({0,s});
while(!pq.empty())
{
auto cur=pq.top();
pq.pop();
int u=cur.se;
if(vis[u]) continue;
vis[u]=1;
for(auto e:G_dij[u])
{
int v=e.to, w=e.w;
if(dis[v]>dis[u]+w)
{
dis[v]=dis[u]+w;
pq.push({dis[v],v});
}
}
}
}
vector<pair<int,int>> G_spfa[maxn];
ll dist_spfa[maxn];
bool inq[maxn];
bool spfa(int s, int n)
{
fill(dist_spfa, dist_spfa+maxn, INF);
memset(inq,0,sizeof(inq));
deque<int> dq;
dist_spfa[s]=0;
dq.pb(s);
inq[s]=1;
static int cnt[maxn];
fill(cnt,cnt+maxn,0);
while(!dq.empty())
{
int u=dq.front();
dq.pop_front();
inq[u]=0;
for(auto &e:G_spfa[u])
{
int v=e.fi, w=e.se;
if(dist_spfa[v]>dist_spfa[u]+w)
{
dist_spfa[v]=dist_spfa[u]+w;
if(!inq[v])
{
if(!dq.empty() && dist_spfa[v]<dist_spfa[dq.front()]) dq.push_front(v);
else dq.push_back(v);
inq[v]=1;
if(++cnt[v]>n) return false;
}
}
}
}
return true;
}
vector<vector<ll>> johnson(int n, vector<vector<pair<int,ll>>> &G)
{
vector<vector<pair<int,ll>>> G2 = G;
for(int i=1; i<=n; i++) G2[0].pb({i,0});
fill(dist_spfa, dist_spfa+maxn, INF);
memset(inq,0,sizeof(inq));
deque<int> dq;
dist_spfa[0]=0;
dq.pb(0);
inq[0]=1;
bool neg=spfa(0,n);
vector<vector<pair<int,ll>>> G3=G;
for(int u=1; u<=n; u++)
for(auto &e:G3[u])
e.se += dist_spfa[u] - dist_spfa[e.fi];
vector<vector<ll>> ans(n+1, vector<ll>(n+1, INF));
for(int s=1; s<=n; s++)
{
dijkstra(s);
for(int v=1; v<=n; v++) if(dis[v]<INF) ans[s][v] = dis[v] - dist_spfa[s] + dist_spfa[v];
}
return ans;
}
//最大流
struct EK
{
struct Edge
{
int to, rev;
ll cap;
};
vector<Edge> G[maxn];
void addEdge(int u,int v,ll cap)
{
G[u].pb({v, (int)G[v].size(), cap});
G[v].pb({u, (int)G[u].size()-1, 0});
}
ll maxflow(int s,int t)
{
ll flow=0;
while(true)
{
vector<int> preV(maxn,-1), preE(maxn,-1);
queue<int> q;
q.push(s);
while(!q.empty())
{
int u=q.front();
q.pop();
if(u==t) break;
for(int i=0; i<G[u].size(); i++)
{
Edge &e=G[u][i];
if(e.cap>0 && preV[e.to]==-1)
{
preV[e.to]=u;
preE[e.to]=i;
q.push(e.to);
}
}
}
if(preV[t]==-1) break;
ll f=INF;
for(int v=t; v!=s; v=preV[v])
{
int u=preV[v], e=preE[v];
f=min(f, G[u][e].cap);
}
for(int v=t; v!=s; v=preV[v])
{
int u=preV[v], e=preE[v];
G[u][e].cap-=f;
G[v][G[u][e].rev].cap+=f;
}
flow+=f;
}
return flow;
}
};
struct HLPP
{
struct Edge
{
int to, rev;
ll cap;
};
vector<Edge> G[maxn];
ll excess[maxn];
int height[maxn], gap[maxn<<1], n;
priority_queue<pair<int,int>> pq;
void addEdge(int u,int v,ll cap)
{
G[u].pb({v, (int)G[v].size(), cap});
G[v].pb({u, (int)G[u].size()-1, 0});
}
void push(int u, Edge &e)
{
if(e.cap<=0) return;
int v=e.to;
ll d=min(excess[u], e.cap);
e.cap-=d;
G[v][e.rev].cap+=d;
excess[u]-=d;
excess[v]+=d;
if(v!=0 && v!=n-1 && excess[v]>0) pq.push({height[v], v});
}
void relabel(int u)
{
int minH=INF;
for(auto &e:G[u])
{
if(e.cap>0) minH=min(minH, height[e.to]);
}
if(minH<INF)
{
gap[height[u]]--;
height[u]=minH+1;
gap[height[u]]++;
}
}
ll maxflow(int s,int t)
{
n=maxn;
excess[s]=INF;
height[s]=n;
for(auto &e:G[s])
{
if(e.cap>0)
{
ll d=e.cap;
excess[e.to]+=d;
e.cap=0;
G[e.to][e.rev].cap+=d;
if(e.to!=t && excess[e.to]>0)
pq.push({height[e.to],e.to});
}
}
while(!pq.empty())
{
int u=pq.top().se;
pq.pop();
if(excess[u]<=0) continue;
for(auto &e:G[u])
{
if(e.cap>0 && height[u]==height[e.to]+1)
{
push(u,e);
if(excess[u]==0) break;
}
}
if(excess[u]>0)
{
relabel(u);
if(height[u]<=n) pq.push({height[u], u});
}
}
return excess[t];
}
};
void solve()
{
}
signed main()
{
init();
solve();
return 0;
}游戏大全
成功作品
植物大战僵尸
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <windows.h>
#include <conio.h>
#include <locale.h>
#include <string>
#include <fstream>
#include <set>
#include <map>
#include <utility>
using namespace std;
#if defined(_MSC_VER)
#pragma execution_character_set("gbk")
#elif defined(__MINGW32__) || defined(__MINGW64__)
#pragma GCC execution_character_set("gbk")
#endif
const int R = 5;
const int C = 12;
// ==================== 游戏全局变量 ====================
int s = 50;
int rnd = 0;
int tz = 0;
int mode = 1;
float globalHpMultiplier = 1.0f;
bool hp[R][C] = {false};
bool cp[R][C] = {true};
int ht[R][C] = {0};
enum PT { PEA, SUN, ICE, NUT, DOOM, TWH, GAT };
enum ZT { NRM, CONE, ICEZ, BKT, GNT, NSP, FB, DANCER };
struct P {
int x, y, cd, hp;
PT t;
P(int a, int b, PT tt) : x(a), y(b), cd(0), hp(5), t(tt) {
if (tt == NUT) hp = 15;
if (tt == TWH) hp = 9;
}
};
struct Z {
int x, y, hp, mhp, bcd;
bool slow;
int st;
ZT t;
bool frozen;
int frozenLeft;
Z(int a, int b, ZT tt) : x(a), y(b), bcd(0), slow(false), st(0), t(tt),
frozen(false), frozenLeft(0) {
if (tt == NRM) hp = 3;
if (tt == CONE) hp = 6;
if (tt == ICEZ) hp = 4;
if (tt == BKT) hp = 10;
if (tt == GNT) hp = 50;
if (tt == NSP) hp = 12;
if (tt == FB) hp = 15;
if (tt == DANCER) hp = 20;
if (mode == 2) { hp *= 2; }
else if (mode == 3) { hp *= 3; }
hp = (int)(hp * globalHpMultiplier);
mhp = hp;
}
};
vector<P> ps;
vector<Z> zs;
// ==================== 卡牌数据 ====================
struct CardInfo {
int id;
string name;
string type;
string desc;
int price;
int cooldown;
};
CardInfo allCards[] = {
{1, "时空裂缝", "active", "将所有僵尸传送回最右侧", 250, 35}, // 描述已修改
{14, "时间冻结", "active", "冻结场上所有僵尸3回合", 80, 10},
{18, "双重防线", "active", "每行最右免费种坚果", 60, 20},
{17, "巨人之力", "active", "斩杀最左侧僵尸", 50, 10},
{15, "紧急呼救", "active", "立即获得300阳光", 40, 30},
{16, "毁灭轰炸", "active", "对所有僵尸造成100点伤害", 100, 30},
{6, "快速生长", "passive", "攻击植物冷却-1帧", 30, 0}
};
const int CARD_COUNT = 7;
// ==================== 持久化数据 ====================
int gold = 0;
set<int> ownedCards;
const string GOLD_FILE = "gold.txt";
const string COLLECTION_FILE = "collection.txt";
map<int, int> cooldowns;
set<int> activeCards;
// ==================== 前置声明 ====================
void cls();
void d();
void useActiveAbility();
void shop();
int playGame();
bool hasPlant(int x, int y);
void spawnFBByDancer(int dx, int dy);
int getAszInterval();
int getWaveInterval();
void swz();
void asz();
int getPlantAttackCD(PT type);
void clearInputBuffer();
// ==================== 辅助函数 ====================
void clearInputBuffer() {
cin.clear();
cin.ignore(10000, '\n');
}
void loadData() {
ifstream fin(GOLD_FILE);
if (fin.is_open()) {
fin >> gold;
fin.close();
} else {
gold = 0;
}
fin.open(COLLECTION_FILE);
if (fin.is_open()) {
int id;
while (fin >> id) ownedCards.insert(id);
fin.close();
}
}
void saveData() {
ofstream fout(GOLD_FILE);
if (fout.is_open()) {
fout << gold;
fout.close();
}
fout.open(COLLECTION_FILE);
if (fout.is_open()) {
for (int id : ownedCards) fout << id << endl;
fout.close();
}
}
void cls() {
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
COORD topLeft = {0, 0};
DWORD len;
if (GetConsoleScreenBufferInfo(hOut, &csbi)) {
DWORD size = csbi.dwSize.X * csbi.dwSize.Y;
FillConsoleOutputCharacter(hOut, ' ', size, topLeft, &len);
FillConsoleOutputAttribute(hOut, csbi.wAttributes, size, topLeft, &len);
SetConsoleCursorPosition(hOut, topLeft);
}
}
bool hasPlant(int x, int y) {
for (auto &p : ps) if (p.x == x && p.y == y) return true;
return false;
}
void spawnFBByDancer(int dx, int dy) {
for (int i = 0; i < 4; i++) {
int offX = 1 + (i % 2);
int offY = i / 2;
if (dy + offY < R && dx + offX < C) {
zs.emplace_back(dx + offX, dy + offY, FB);
tz++;
}
}
}
int getAszInterval() {
if (mode == 1) return 12;
if (mode == 2) return 8;
return 5;
}
int getWaveInterval() {
if (mode == 1) return 35;
if (mode == 2) return 25;
return 18;
}
void swz() {
int b = 3 + rand() % 2;
int cnt = (rnd >= 200) ? b * 2 : b;
if (mode == 2) cnt = cnt + cnt / 2;
if (mode == 3) cnt = cnt * 2;
for (int i = 0; i < cnt; i++) {
int r = rand() % R;
ZT t;
if (tz < 5) {
t = (rand() % 2) ? ICEZ : NRM;
} else if (tz < 10) {
int rn = rand() % 3;
t = (rn == 0) ? NRM : (rn == 1) ? CONE : ICEZ;
} else {
int mr = (rnd >= 100) ? 8 : (rnd >= 75) ? 6 : (rnd >= 50) ? 5 : 4;
int rn = rand() % mr;
if (rn == 0) t = NRM;
else if (rn == 1) t = CONE;
else if (rn == 2) t = ICEZ;
else if (rn == 3) t = BKT;
else if (rn == 4) t = NSP;
else if (rn == 5 && mr >= 6) t = FB;
else if (rn == 6 && mr >= 7) t = GNT;
else if (rn == 7 && mr >= 8) t = DANCER;
else t = NRM;
}
zs.emplace_back(C - 1, r, t);
tz++;
}
}
void asz() {
if (rnd <= 3) return;
if (rnd % getAszInterval() != 0) return;
int r = rand() % R;
ZT t;
if (tz < 5) {
t = (rand() % 2) ? ICEZ : NRM;
} else if (tz < 10) {
int rn = rand() % 3;
t = (rn == 0) ? NRM : (rn == 1) ? CONE : ICEZ;
} else {
int mr = (rnd >= 100) ? 8 : (rnd >= 75) ? 6 : (rnd >= 50) ? 5 : 4;
int rn = rand() % mr;
if (rn == 0) t = NRM;
else if (rn == 1) t = CONE;
else if (rn == 2) t = ICEZ;
else if (rn == 3) t = BKT;
else if (rn == 4) t = NSP;
else if (rn == 5 && mr >= 6) t = FB;
else if (rn == 6 && mr >= 7) t = GNT;
else if (rn == 7 && mr >= 8) t = DANCER;
else t = NRM;
}
zs.emplace_back(C - 1, r, t);
tz++;
}
int getPlantAttackCD(PT type) {
if (type == SUN) return 3;
if (activeCards.count(6)) return 1;
return 2;
}
// ==================== 主动技能 ====================
void useActiveAbility() {
vector<CardInfo*> available;
for (auto &c : allCards) {
if (c.type == "active" && activeCards.count(c.id) && cooldowns[c.id] <= 0) {
available.push_back(&c);
}
}
if (available.empty()) {
cout << "没有可用的主动技能或全部在冷却中。" << endl;
return;
}
cls();
cout << "=====================================" << endl;
cout << " 选择要使用的主动技能" << endl;
cout << "=====================================" << endl;
for (size_t i = 0; i < available.size(); ++i) {
cout << i+1 << ". " << available[i]->name << " - " << available[i]->desc << endl;
}
cout << "0. 取消" << endl;
cout << "-------------------------------------" << endl;
cout << "请输入编号:";
int choice;
cin >> choice;
while (choice < 0 || choice > (int)available.size()) {
cout << "输入无效,重新选择:";
clearInputBuffer();
cin >> choice;
}
if (choice == 0) return;
CardInfo* card = available[choice-1];
switch (card->id) {
case 1: { // 时空裂缝:所有僵尸回最右侧
int cnt = 0;
for (auto &z : zs) {
if (z.hp > 0) {
z.x = C - 1;
cnt++;
}
}
cout << "【时空裂缝】所有 " << cnt << " 只僵尸被传送回最右侧!" << endl;
break;
}
case 14: {
int cnt = 0;
for (auto &z : zs) {
if (z.hp > 0) {
z.frozen = true;
z.frozenLeft = 3;
cnt++;
}
}
cout << "【时间冻结】冻结了 " << cnt << " 只僵尸3回合!" << endl;
break;
}
case 18: {
bool planted = false;
for (int row = 0; row < R; ++row) {
int col = C - 1;
if (cp[row][col] && !hp[row][col]) {
ps.emplace_back(col, row, NUT);
hp[row][col] = true;
planted = true;
}
}
cout << (planted ? "【双重防线】每行最右侧已免费种植坚果!" : "【双重防线】没有可种植的位置。") << endl;
break;
}
case 17: {
Z* target = nullptr;
int minX = C + 1;
for (auto &z : zs) {
if (z.hp > 0) {
if (z.x < minX) { minX = z.x; target = &z; }
}
}
if (target) {
cout << "【巨人之力】斩杀位于(" << target->x+1 << "," << target->y+1 << ")的僵尸!" << endl;
target->hp = 0;
} else {
cout << "【巨人之力】场上没有僵尸。" << endl;
}
break;
}
case 15: {
s += 300;
cout << "【紧急呼救】获得300阳光!当前阳光:" << s << endl;
break;
}
case 16: {
int cnt = 0;
for (auto &z : zs) {
if (z.hp > 0) { z.hp -= 100; cnt++; }
}
cout << "【毁灭轰炸】对 " << cnt << " 只僵尸造成100点伤害!" << endl;
break;
}
}
cooldowns[card->id] = card->cooldown;
cout << "技能 " << card->name << " 进入冷却,剩余 " << card->cooldown << " 回合。" << endl;
system("pause");
}
// ==================== 商店界面 ====================
void shop() {
while (true) {
cls();
cout << "=====================================" << endl;
cout << " 卡牌商店" << endl;
cout << "=====================================" << endl;
cout << "当前金币: " << gold << endl;
cout << "-------------------------------------" << endl;
cout << "编号 名称 类型 价格 状态" << endl;
cout << "-------------------------------------" << endl;
for (int i = 0; i < CARD_COUNT; ++i) {
cout << i+1 << ". " << allCards[i].name << " ";
cout << (allCards[i].type == "active" ? "[主动]" : "[被动]") << " ";
cout << allCards[i].price << "金 ";
if (ownedCards.count(allCards[i].id))
cout << "已拥有";
else
cout << "未购买";
cout << endl;
}
cout << "0. 返回主菜单" << endl;
cout << "-------------------------------------" << endl;
cout << "请输入编号购买:";
int choice;
cin >> choice;
if (choice == 0) break;
if (choice < 1 || choice > CARD_COUNT) {
cout << "无效选择。"; system("pause"); continue;
}
int idx = choice - 1;
if (ownedCards.count(allCards[idx].id)) {
cout << "你已经拥有这张卡牌了!" << endl;
system("pause");
continue;
}
if (gold < allCards[idx].price) {
cout << "金币不足!需要 " << allCards[idx].price << " 金。" << endl;
system("pause");
continue;
}
gold -= allCards[idx].price;
ownedCards.insert(allCards[idx].id);
saveData();
cout << "购买成功!获得卡牌:" << allCards[idx].name << endl;
system("pause");
}
}
// ==================== 游戏主流程 ====================
int playGame() {
s = 50;
rnd = 0;
tz = 0;
globalHpMultiplier = 1.0f;
ps.clear();
zs.clear();
cooldowns.clear();
activeCards = ownedCards;
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
cp[i][j] = true;
ht[i][j] = 0;
hp[i][j] = false;
}
}
d();
bool hpd = false;
bool gameOver = false;
const DWORD TICK_DURATION = 1200;
DWORD tickStart = GetTickCount();
while (!gameOver) {
while (_kbhit()) {
char op;
cin >> op;
int r, c;
if (op == 'f' || op == 'F') {
useActiveAbility();
d();
}
else {
if (!(cin >> r >> c)) {
clearInputBuffer();
cout << "输入格式错误,请使用:指令 行 列" << endl;
d();
continue;
}
r--; c--;
if (op == 'd') {
if (r >= 0 && r < R && c >= 0 && c < C) {
for (auto it = ps.begin(); it != ps.end(); ++it) {
if (it->x == c && it->y == r) {
hp[r][c] = false;
ps.erase(it);
break;
}
}
}
}
else if (op == 'p') {
if (r >= 0 && r < R && c >= 0 && c < C && s >= 100 && !hp[r][c] && cp[r][c]) {
ps.emplace_back(c, r, PEA); hp[r][c] = true; s -= 100;
}
}
else if (op == 's') {
if (r >= 0 && r < R && c >= 0 && c < C && s >= 50 && !hp[r][c] && cp[r][c]) {
ps.emplace_back(c, r, SUN); hp[r][c] = true; s -= 50;
}
}
else if (op == 'i') {
if (r >= 0 && r < R && c >= 0 && c < C && s >= 175 && !hp[r][c] && cp[r][c]) {
ps.emplace_back(c, r, ICE); hp[r][c] = true; s -= 175;
}
}
else if (op == 'n') {
if (r >= 0 && r < R && c >= 0 && c < C && s >= 50 && !hp[r][c] && cp[r][c]) {
ps.emplace_back(c, r, NUT); hp[r][c] = true; s -= 50;
}
}
else if (op == 'm') {
if (r >= 0 && r < R && c >= 0 && c < C && s >= 175 && !hp[r][c] && cp[r][c]) {
s -= 175;
for (int dy = -2; dy <= 2; dy++) {
for (int dx = -2; dx <= 2; dx++) {
int nx = c + dx, ny = r + dy;
if (nx >= 0 && nx < C && ny >= 0 && ny < R) {
for (auto &z : zs) if (z.x == nx && z.y == ny) z.hp -= 30;
}
}
}
cp[r][c] = false;
ht[r][c] = 50;
}
}
else if (op == 't') {
if (r >= 0 && r < R && c >= 0 && c < C && s >= 225 && !hp[r][c] && cp[r][c]) {
ps.emplace_back(c, r, TWH); hp[r][c] = true; s -= 225;
}
}
else if (op == 'g') {
if (r >= 0 && r < R && c >= 0 && c < C && s >= 400 && !hp[r][c] && cp[r][c]) {
ps.emplace_back(c, r, GAT); hp[r][c] = true; s -= 400;
}
}
}
d();
}
DWORD now = GetTickCount();
if (now - tickStart >= TICK_DURATION) {
tickStart = now;
rnd++;
// 禁种坑恢复
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
if (ht[i][j] > 0) {
ht[i][j]--;
if (ht[i][j] <= 0) cp[i][j] = true;
}
}
}
for (auto &cd : cooldowns) {
if (cd.second > 0) cd.second--;
}
if (rnd >= 150 && !hpd) {
globalHpMultiplier *= 2.0f;
hpd = true;
for (auto &z : zs) {
z.hp *= 2;
z.mhp *= 2;
}
}
if (rnd % getWaveInterval() == 0 && rnd > 0) swz();
asz();
if (rnd % 5 == 0) {
vector<pair<int, int>> dancers;
for (auto &z : zs) if (z.t == DANCER) dancers.emplace_back(z.x, z.y);
for (auto &p : dancers) spawnFBByDancer(p.first, p.second);
}
for (auto &z : zs) {
if (z.frozen) {
z.frozenLeft--;
if (z.frozenLeft <= 0) z.frozen = false;
}
}
for (auto &z : zs) {
if (z.slow) { z.st--; if (z.st <= 0) z.slow = false; }
}
for (auto &p : ps) p.cd++;
for (auto &p : ps) {
if (p.t == SUN && p.cd >= 3) { s += 25; p.cd = 0; }
}
for (auto &p : ps) {
if (p.t == TWH) {
for (auto &z : zs) {
if (z.x == p.x && z.y == p.y && z.hp > 0) {
if (z.t == NSP && z.hp > z.mhp / 2 && (z.hp - 3) <= z.mhp / 2)
z.hp = z.mhp / 2;
else z.hp -= 3;
}
}
int leftX = p.x - 1;
if (leftX >= 0) {
for (auto &z : zs) {
if (z.x == leftX && z.y == p.y && z.hp > 0) {
if (z.t == NSP && z.hp > z.mhp / 2 && (z.hp - 3) <= z.mhp / 2)
z.hp = z.mhp / 2;
else z.hp -= 3;
}
}
}
}
}
for (auto &p : ps) {
if (p.t == PEA && p.cd >= getPlantAttackCD(PEA)) {
for (auto &z : zs) {
if (z.y == p.y && z.x >= p.x && z.hp > 0) {
if (z.t == NSP && z.hp > z.mhp / 2 && (z.hp - 1) <= z.mhp / 2)
z.hp = z.mhp / 2;
else z.hp--;
p.cd = 0; break;
}
}
}
}
for (auto &p : ps) {
if (p.t == GAT && p.cd >= getPlantAttackCD(GAT)) {
for (auto &z : zs) {
if (z.y == p.y && z.x >= p.x && z.hp > 0) {
for (int i = 0; i < 4; i++) {
if (z.t == NSP && z.hp > z.mhp / 2 && (z.hp - 1) <= z.mhp / 2)
z.hp = z.mhp / 2;
else z.hp--;
if (z.hp <= 0) break;
}
p.cd = 0; break;
}
}
}
}
for (auto &p : ps) {
if (p.t == ICE && p.cd >= getPlantAttackCD(ICE)) {
for (auto &z : zs) {
if (z.y == p.y && z.x >= p.x && z.hp > 0) {
if (z.t == NSP && z.hp > z.mhp / 2 && (z.hp - 1) <= z.mhp / 2)
z.hp = z.mhp / 2;
else { z.hp--; z.slow = true; z.st = 2; }
p.cd = 0; break;
}
}
}
}
for (auto &z : zs) {
if (z.hp <= 0 || z.frozen) continue;
bool hasBlock = false;
for (auto &p : ps) {
if (p.x == z.x && p.y == z.y) {
if (z.t == GNT) {
hasBlock = true;
if (p.t == TWH) { p.hp--; z.hp -= 3; }
else p.hp = 0;
int lx = z.x - 1;
for (auto &p2 : ps) {
if (p2.x == lx && p2.y == z.y) {
if (p2.t == TWH) { p2.hp--; z.hp -= 3; }
else p2.hp = 0;
break;
}
}
} else if (p.t == TWH) {
hasBlock = false;
} else {
hasBlock = true;
int dmg = 1;
if (z.t == FB) dmg = 2;
if (z.t == NSP && z.hp <= z.mhp / 2) dmg = 5;
z.bcd++;
if (z.bcd >= 2) { p.hp -= dmg; z.bcd = 0; }
}
break;
}
}
if (hasBlock || z.slow) continue;
if (z.t == GNT) { if (rnd % 2 == 0) z.x--; }
else if (z.t == FB) {
int nx1 = z.x - 1, nx2 = z.x - 2;
bool b1 = (nx1 >= 0) ? hasPlant(nx1, z.y) : true;
bool b2 = (nx2 >= 0) ? hasPlant(nx2, z.y) : true;
if (!b1 && !b2) z.x -= 2;
else if (!b1) z.x -= 1;
} else if (z.t == NSP && z.hp <= z.mhp / 2) {
int nx1 = z.x - 1, nx2 = z.x - 2;
bool b1 = (nx1 >= 0) ? hasPlant(nx1, z.y) : true;
bool b2 = (nx2 >= 0) ? hasPlant(nx2, z.y) : true;
if (!b1 && !b2) z.x -= 2;
else if (!b1) z.x -= 1;
} else {
z.x--;
}
}
vector<P> np;
for (auto &p : ps) {
if (p.hp > 0) np.push_back(p);
else hp[p.y][p.x] = false;
}
ps = np;
vector<Z> nz;
for (auto &z : zs) {
if (z.hp <= 0) continue;
if (z.x < 0) { gameOver = true; break; }
nz.push_back(z);
}
zs = nz;
s += 5;
d();
if (gameOver) {
cls();
int killed = tz - zs.size();
int earnedGold = rnd + killed / 2;
gold += earnedGold;
saveData();
cout << "=====================================" << endl;
cout << " 游戏结束" << endl;
cout << "=====================================" << endl;
cout << "僵尸吃掉了你的脑子!" << endl;
cout << "-------------------------------------" << endl;
cout << "坚持回合数: " << rnd << endl;
cout << "击杀僵尸: " << killed << endl;
cout << "获得金币: " << earnedGold << " (总金币: " << gold << ")" << endl;
cout << "=====================================" << endl;
system("pause");
return earnedGold;
}
}
Sleep(20);
}
return 0;
}
// ==================== 绘制函数 ====================
void d() {
cls();
cout << "=====================================" << endl;
cout << " 控制台植物大战僵尸" << endl;
cout << "=====================================" << endl;
cout << "模式: " << (mode==1?"简单":(mode==2?"困难":"噩梦"));
cout << " | 阳光: " << s << " | 回合: " << rnd << " | 僵尸数: " << tz;
cout << endl;
cout << "已激活卡牌: ";
if (activeCards.empty()) cout << "无";
else {
vector<string> names;
for (int id : activeCards) {
for (auto &c : allCards) if (c.id == id) { names.push_back(c.name); break; }
}
for (size_t i = 0; i < names.size(); ++i) {
cout << names[i];
if (i < names.size()-1) cout << ", ";
}
}
cout << endl;
cout << "操作: 指令 行 列 (F 主动技能)" << endl;
cout << "p豌豆 s向日葵 i寒冰 n坚果 m毁灭菇 t地刺 g机枪 d铲除" << endl;
cout << "=====================================" << endl;
cout << "列号: 1 2 3 4 5 6 7 8 9 10 11 12" << endl;
cout << "-------------------------------------" << endl;
char mp[R][C];
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
mp[i][j] = '-';
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++)
if (!cp[i][j]) mp[i][j] = 'X';
for (auto &p : ps) {
char ch = '?';
switch (p.t) {
case SUN: ch = 'S'; break;
case PEA: ch = 'P'; break;
case ICE: ch = 'I'; break;
case NUT: ch = 'W'; break;
case DOOM: ch = 'M'; break;
case TWH: ch = 't'; break;
case GAT: ch = 'g'; break;
}
mp[p.y][p.x] = ch;
}
for (auto &z : zs) {
if (z.hp <= 0) continue;
char ch = '?';
switch (z.t) {
case NRM: ch = 'Z'; break;
case CONE: ch = 'L'; break;
case ICEZ: ch = 'B'; break;
case BKT: ch = 'T'; break;
case GNT: ch = 'G'; break;
case NSP: ch = 'K'; break;
case FB: ch = 'F'; break;
case DANCER: ch = 'V'; break;
}
mp[z.y][z.x] = ch;
}
for (int i = 0; i < R; i++) {
cout << "第" << i+1 << "行: ";
for (int j = 0; j < C; j++) cout << mp[i][j] << " ";
cout << endl;
}
cout << "=====================================" << endl;
cout << "植物: S葵 P豌 I寒 W坚 M菇 t刺 g机" << endl;
cout << "僵尸: Z普 L障 B冰 T桶 G巨 K报 F球 V舞" << endl;
cout << "地形: -空地 X禁种" << endl;
cout << "=====================================" << endl;
}
// ==================== 主菜单 ====================
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
setlocale(LC_ALL, "chs");
SetConsoleCP(936);
SetConsoleOutputCP(936);
srand((unsigned)time(0));
loadData();
while (true) {
cls();
cout << "=====================================" << endl;
cout << " 控制台植物大战僵尸" << endl;
cout << "=====================================" << endl;
cout << "金币: " << gold << " 卡牌: " << ownedCards.size() << "/" << CARD_COUNT << endl;
cout << "1. 开始新游戏" << endl;
cout << "2. 卡牌商店" << endl;
cout << "3. 退出" << endl;
cout << "-------------------------------------" << endl;
cout << "请选择: ";
int choice;
cin >> choice;
switch (choice) {
case 1:
cls();
cout << "请选择难度:1.简单 2.困难 3.噩梦:";
cin >> mode;
while (mode < 1 || mode > 3) {
cout << "无效,重新选择(1-3):";
cin >> mode;
}
playGame();
break;
case 2:
shop();
break;
case 3:
saveData();
return 0;
default:
cout << "无效选择。";
system("pause");
}
}
return 0;
}取石子游戏
#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <thread>
#include <chrono>
#include <limits>
#include <algorithm>
#include <ctime>
using namespace std;
class StoneGame {
private:
struct Pile {
int stones;
int effect; // 0=回血, 1=攻击, 2=扣血, 3=陷阱
bool revealed;
Pile(int s, int e) : stones(s), effect(e), revealed(false) {}
};
vector<Pile> piles;
int playerHp, aiHp;
const int maxHp = 10;
enum Difficulty {
EASY = 1,
HARD = 2,
NIGHTMARE = 3,
HELL = 4
};
Difficulty currentDifficulty;
int playerSkill;
bool skillUsed;
bool skillDoubleDamage;
bool skillNoHeal;
bool skillRevealAll;
bool skillEmptyPileAlways;
mt19937 rng;
bool gameOver;
int turn;
vector<string> aiLog;
// ----- 安全输入(支持0返回) -----
int safeInputInt(const string& prompt, int minVal, int maxVal, bool allowZero = false) {
int value;
while (true) {
cout << prompt;
cin >> value;
if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "输入无效,请输入数字!\n";
continue;
}
if (allowZero && value == 0) return 0;
if (value < minVal || value > maxVal) {
cout << "请输入 " << minVal << "-" << maxVal << " 之间的数字!\n";
continue;
}
break;
}
return value;
}
string getDifficultyName(Difficulty d) {
switch(d) {
case EASY: return "简单";
case HARD: return "困难";
case NIGHTMARE: return "噩梦";
case HELL: return "地狱";
default: return "未知";
}
}
string getDifficultyColor(Difficulty d) {
switch(d) {
case EASY: return "[绿色]";
case HARD: return "[黄色]";
case NIGHTMARE: return "[红色]";
case HELL: return "[🔥地狱🔥]";
default: return "";
}
}
public:
StoneGame() : rng(random_device{}()), gameOver(false), turn(0),
playerHp(10), aiHp(10),
playerSkill(0), skillUsed(false),
skillDoubleDamage(false), skillNoHeal(false),
skillRevealAll(false), skillEmptyPileAlways(false) {
system("chcp 65001 > nul");
selectDifficulty();
selectSkill();
generatePiles();
}
void clearScreen() {
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}
void selectDifficulty() {
clearScreen();
cout << "========================================\n";
cout << " 取石子·血战 \n";
cout << "========================================\n\n";
cout << "请选择游戏难度:\n\n";
cout << "1. 简单 [新手友好]\n";
cout << " - AI随机行动,经常犯错\n\n";
cout << "2. 困难 [当前推荐]\n";
cout << " - AI智能评估,偶尔失误\n\n";
cout << "3. 噩梦 [硬核挑战]\n";
cout << " - AI精确计算,优先攻击\n";
cout << " - 能预判玩家技能效果\n\n";
cout << "4. 地狱 [终极考验]\n";
cout << " - AI预知所有效果,策略无懈可击\n";
cout << " - 能模拟玩家行动做出最优应对\n\n";
cout << "========================================\n";
int choice = safeInputInt("请选择难度(1-4): ", 1, 4);
currentDifficulty = static_cast<Difficulty>(choice);
cout << "\n你选择了: " << getDifficultyColor(currentDifficulty)
<< " " << getDifficultyName(currentDifficulty) << "\n";
this_thread::sleep_for(chrono::milliseconds(1500));
}
void selectSkill() {
clearScreen();
cout << "========================================\n";
cout << " 取石子·血战 \n";
cout << "========================================\n\n";
cout << "当前难度: " << getDifficultyColor(currentDifficulty)
<< " " << getDifficultyName(currentDifficulty) << "\n\n";
cout << "请选择你的技能:\n\n";
cout << "1. 对赌协议 - 每回合摸取整个石子堆\n";
cout << "2. 崩碎殒命 - 所有伤害翻倍,无法回血\n";
cout << "3. 明牌决斗 - 显示所有石子堆效果\n\n";
cout << "========================================\n";
playerSkill = safeInputInt("请输入1-3选择技能: ", 1, 3);
cout << "\n你选择了: ";
if (playerSkill == 1) cout << "【对赌协议】";
else if (playerSkill == 2) cout << "【崩碎殒命】";
else if (playerSkill == 3) cout << "【明牌决斗】";
cout << "\n";
this_thread::sleep_for(chrono::milliseconds(1500));
}
void generatePiles() {
piles.clear();
uniform_int_distribution<int> pileCount(3, 5);
uniform_int_distribution<int> stoneCount(1, 7);
uniform_int_distribution<int> effectType(0, 3);
int numPiles = pileCount(rng);
for (int i = 0; i < numPiles; ++i) {
piles.push_back(Pile(stoneCount(rng), effectType(rng)));
}
}
void revealAllPiles() {
for (int i = 0; i < (int)piles.size(); ++i) {
piles[i].revealed = true;
}
}
string getEffectName(int effect) {
if (effect == 0) return "回血";
if (effect == 1) return "攻击";
if (effect == 2) return "扣血";
if (effect == 3) return "陷阱";
return "未知";
}
string getEffectEmoji(int effect) {
if (effect == 0) return "❤️";
if (effect == 1) return "⚔️";
if (effect == 2) return "💔";
if (effect == 3) return "💀";
return "❓";
}
void addAILog(string message) {
aiLog.push_back(message);
if (aiLog.size() > 5) {
aiLog.erase(aiLog.begin());
}
}
void displayState() {
clearScreen();
cout << "========================================\n";
cout << " 取石子·血战 \n";
cout << "========================================\n\n";
cout << "难度: " << getDifficultyColor(currentDifficulty)
<< " " << getDifficultyName(currentDifficulty) << "\n";
cout << "你的HP: " << playerHp << "/" << maxHp << " ";
for (int i = 0; i < playerHp; ++i) cout << "❤️";
cout << "\n";
cout << "AI的HP: " << aiHp << "/" << maxHp << " ";
for (int i = 0; i < aiHp; ++i) cout << "❤️";
cout << "\n";
cout << "你的技能: ";
if (playerSkill == 1) cout << "【对赌协议】";
else if (playerSkill == 2) cout << "【崩碎殒命】";
else if (playerSkill == 3) cout << "【明牌决斗】";
if (!skillUsed) cout << " [可用]";
else cout << " [已激活]";
cout << "\n\n";
cout << "石子堆:\n";
for (int i = 0; i < (int)piles.size(); ++i) {
cout << "堆" << i+1 << ": " << piles[i].stones << "枚 ";
if (piles[i].revealed || skillRevealAll) {
cout << getEffectEmoji(piles[i].effect)
<< "[" << getEffectName(piles[i].effect) << "]";
} else {
cout << "❓[未知]";
}
cout << "\n";
}
if (!aiLog.empty()) {
cout << "\n--- AI最近行动 ---\n";
for (int i = 0; i < (int)aiLog.size(); ++i) {
cout << aiLog[i] << "\n";
}
}
cout << "========================================\n";
}
void useSkill() {
if (skillUsed) {
cout << "技能已使用!\n";
return;
}
if (playerSkill == 1) {
skillEmptyPileAlways = true;
skillUsed = true;
cout << "你使用【对赌协议】!之后每回合摸取将消耗整个石子堆。\n";
}
else if (playerSkill == 2) {
skillDoubleDamage = true;
skillNoHeal = true;
skillUsed = true;
cout << "你使用【崩碎殒命】!所有伤害翻倍,无法回血。\n";
}
else if (playerSkill == 3) {
skillRevealAll = true;
revealAllPiles();
skillUsed = true;
cout << "你使用【明牌决斗】!所有效果立即可见。\n";
}
this_thread::sleep_for(chrono::milliseconds(1500));
}
void applyEffect(int effect, int count, bool isPlayer) {
int& actorHp = isPlayer ? playerHp : aiHp;
int& targetHp = isPlayer ? aiHp : playerHp;
for (int i = 0; i < count; ++i) {
if (effect == 0) {
if (!skillNoHeal) {
actorHp = min(maxHp, actorHp + 1);
if (isPlayer) cout << " ❤️ 你恢复了1点HP\n";
else cout << " ❤️ AI恢复了1点HP\n";
} else {
if (isPlayer) cout << " ⛔ 无法回血!\n";
else cout << " ⛔ AI无法回血!\n";
}
}
else if (effect == 1) {
int damage = skillDoubleDamage ? 2 : 1;
targetHp = max(0, targetHp - damage);
if (isPlayer)
cout << " ⚔️ 你对AI造成" << damage << "点伤害\n";
else
cout << " ⚔️ AI对你造成" << damage << "点伤害\n";
}
else if (effect == 2) {
int damage = skillDoubleDamage ? 2 : 1;
actorHp = max(0, actorHp - damage);
if (isPlayer) cout << " 💔 你受到" << damage << "点伤害\n";
else cout << " 💔 AI受到" << damage << "点伤害\n";
}
else if (effect == 3) {
int selfDamage = skillDoubleDamage ? 2 : 1;
int targetDamage = skillDoubleDamage ? 2 : 1;
actorHp = max(0, actorHp - selfDamage);
targetHp = max(0, targetHp - targetDamage);
if (isPlayer) {
cout << " 💀 陷阱触发!你受到" << selfDamage
<< "点伤害,AI受到" << targetDamage << "点伤害\n";
} else {
cout << " 💀 陷阱触发!AI受到" << selfDamage
<< "点伤害,你受到" << targetDamage << "点伤害\n";
}
}
}
}
bool takeStones(int pileIndex, int count, bool isPlayer) {
if (pileIndex < 0 || pileIndex >= (int)piles.size()) return false;
if (count < 1) return false;
if (piles[pileIndex].stones < count) {
cout << "石子不够!只有 " << piles[pileIndex].stones << " 枚\n";
return false;
}
if (skillEmptyPileAlways) {
count = piles[pileIndex].stones;
if (isPlayer) {
cout << " [对赌协议] 摸取整个堆!\n";
} else {
addAILog("[对赌协议] AI摸取整个堆!");
}
}
piles[pileIndex].stones -= count;
if (!piles[pileIndex].revealed) {
piles[pileIndex].revealed = true;
if (isPlayer) {
cout << " 🔍 首次摸取,揭示效果:" << getEffectEmoji(piles[pileIndex].effect)
<< getEffectName(piles[pileIndex].effect) << "\n";
} else {
string msg = "AI首次摸取堆" + to_string(pileIndex + 1) + ",效果:" + getEffectName(piles[pileIndex].effect);
cout << " 🔍 " << msg << "\n";
addAILog(msg);
}
}
applyEffect(piles[pileIndex].effect, count, isPlayer);
if (allPilesEmpty()) {
cout << "\n 🔄 所有石子堆已空,重新生成!\n";
generatePiles();
if (skillRevealAll) {
revealAllPiles();
}
}
return true;
}
bool allPilesEmpty() const {
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0) return false;
}
return true;
}
// ---------- 增强型AI评估(调整权重) ----------
bool isPileKnownToAI(int pileIndex) const {
const Pile& pile = piles[pileIndex];
return pile.revealed || skillRevealAll || currentDifficulty == HELL;
}
double evaluatePileAdvanced(int pileIndex, bool considerEmptyRisk = true) {
Pile& pile = piles[pileIndex];
double score = 0.0;
int totalStones = pile.stones;
if (totalStones == 0) return -999999;
bool known = isPileKnownToAI(pileIndex);
bool playerNoHeal = skillUsed && playerSkill == 2;
bool playerEmptyAll = skillUsed && playerSkill == 1;
if (!known) {
score += 2.0;
if (aiHp <= 2) score += 8.0;
if (aiHp <= 4) score += 3.0;
if (playerHp <= 2) score += 5.0;
return score;
}
int effect = pile.effect;
switch(effect) {
case 0: { // 回血
if (playerNoHeal) {
score = -5.0;
} else {
int healAmount = min(1, maxHp - aiHp);
// 回血基础价值提高,低血量加成加大
score += healAmount * 2.8 * totalStones;
if (aiHp <= 4) score += 8.0 * totalStones;
if (aiHp <= 2) score += 15.0 * totalStones;
}
break;
}
case 1: { // 攻击 - 降低基础权重,但击杀加成保留
int damage = skillDoubleDamage ? 2 : 1;
score += damage * 2.0 * totalStones; // 从3.0降到2.0
// 击杀加成
if (playerHp <= damage * totalStones) score += 25.0;
if (playerHp <= 3) score += 5.0;
if (playerEmptyAll) {
score += 5.0 * totalStones; // 对赌协议下抢攻击价值稍降
}
break;
}
case 2: { // 扣血
int damage = skillDoubleDamage ? 2 : 1;
int totalDmg = damage * totalStones;
score -= totalDmg * 3.5;
if (aiHp <= totalDmg) score -= 40.0;
if (aiHp <= 4) score -= 15.0;
if (considerEmptyRisk && totalStones >= 3) score -= 10.0;
if (skillDoubleDamage) score -= totalDmg * 1.5;
if (aiHp <= 2 && aiHp > totalDmg) score += 5.0;
break;
}
case 3: { // 陷阱
int damage = skillDoubleDamage ? 2 : 1;
int selfDmg = damage * totalStones;
int targetDmg = damage * totalStones;
score -= selfDmg * 3.0;
score += targetDmg * 2.0;
if (aiHp <= selfDmg) score -= 50.0;
if (playerHp <= targetDmg) score += 20.0;
if (aiHp <= 4) score -= 20.0;
if (considerEmptyRisk && totalStones >= 3) score -= 15.0;
if (skillDoubleDamage) score -= selfDmg * 1.5;
if (aiHp <= 3 && aiHp > selfDmg) score += 6.0;
break;
}
}
return score;
}
int getBestTakeCountAdvanced(int pileIndex) {
Pile& pile = piles[pileIndex];
int maxTake = min(3, pile.stones);
int bestCount = 1;
double bestScore = -999999;
bool known = isPileKnownToAI(pileIndex);
bool playerEmptyAll = skillUsed && playerSkill == 1;
for (int j = 1; j <= maxTake; ++j) {
double score = evaluateActionAdvanced(pileIndex, j);
if (known && pile.effect == 1 && playerEmptyAll) {
score += 2.0 * j;
}
if (known && (pile.effect == 2 || pile.effect == 3)) {
if (aiHp <= 2) {
int damage = skillDoubleDamage ? 2 : 1;
int totalDmg = damage * pile.stones;
if (aiHp > totalDmg) {
score += 5.0 * j;
}
} else {
if (j > 1) score -= 3.0 * (j - 1);
if (j == pile.stones) score -= 5.0;
}
}
if (!known && aiHp <= 2) {
score += 4.0 * j;
}
if (score > bestScore) {
bestScore = score;
bestCount = j;
}
}
return bestCount;
}
double evaluateActionAdvanced(int pileIndex, int count) {
Pile& pile = piles[pileIndex];
double score = 0.0;
bool known = isPileKnownToAI(pileIndex);
bool playerEmptyAll = skillUsed && playerSkill == 1;
if (!known) {
score += 2.0;
if (count == 1) score += 1.0;
if (count > 1) score -= 0.5 * (count - 1);
if (aiHp <= 2) score += 5.0 * count;
return score;
}
int effect = pile.effect;
switch(effect) {
case 0:
if (skillNoHeal) score = -5.0;
else {
score += count * 2.8;
if (aiHp <= 4) score += 4.0 * count;
if (aiHp <= 2) score += 8.0 * count;
}
break;
case 1: {
int damage = skillDoubleDamage ? 2 : 1;
score += count * damage * 2.0;
if (playerHp <= count * damage) score += 20.0;
if (playerEmptyAll) score += 1.5 * count;
break;
}
case 2: {
int damage = skillDoubleDamage ? 2 : 1;
score -= count * damage * 4.0;
if (aiHp <= count * damage) score -= 30.0;
if (aiHp <= 4) score -= 12.0;
if (skillDoubleDamage) score -= count * damage * 2.0;
if (aiHp <= 2 && aiHp > count * damage) score += 8.0;
break;
}
case 3: {
int damage = skillDoubleDamage ? 2 : 1;
score -= count * damage * 3.5;
score += count * damage * 2.0;
if (aiHp <= count * damage) score -= 35.0;
if (aiHp <= 4) score -= 15.0;
if (skillDoubleDamage) score -= count * damage * 2.0;
if (aiHp <= 2 && aiHp > count * damage) score += 10.0;
break;
}
}
return score;
}
// ---------- AI策略选择(增强版) ----------
pair<int, int> aiChooseAction() {
vector<int> availablePiles;
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0) availablePiles.push_back(i);
}
if (availablePiles.empty()) return {-1, -1};
uniform_int_distribution<int> randomPile(0, availablePiles.size() - 1);
switch(currentDifficulty) {
case EASY: {
if (uniform_int_distribution<int>(1, 100)(rng) <= 40) {
int idx = availablePiles[randomPile(rng)];
int maxTake = min(3, piles[idx].stones);
int cnt = uniform_int_distribution<int>(1, maxTake)(rng);
return {idx, cnt};
}
return aiEvaluateWithRandomness(0.4);
}
case HARD: {
return aiEvaluateWithRandomness(0.15);
}
case NIGHTMARE: {
return aiNightmareEvaluate();
}
case HELL: {
return aiHellEvaluate();
}
default:
return aiNightmareEvaluate();
}
}
pair<int, int> aiEvaluateWithRandomness(double mistakeRate) {
int bestPileIndex = -1;
double bestScore = -999999;
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0) {
double score = evaluatePileAdvanced(i);
if (uniform_real_distribution<double>(0,1)(rng) < mistakeRate) {
score += uniform_real_distribution<double>(-8,8)(rng);
}
if (score > bestScore) {
bestScore = score;
bestPileIndex = i;
}
}
}
if (bestPileIndex == -1) return {-1,-1};
int take;
if (skillEmptyPileAlways) take = piles[bestPileIndex].stones;
else take = getBestTakeCountAdvanced(bestPileIndex);
return {bestPileIndex, take};
}
// 噩梦难度:平衡进攻与防守,优先保命
pair<int, int> aiNightmareEvaluate() {
int bestPileIndex = -1;
double bestScore = -999999;
bool playerRevealedAll = skillUsed && playerSkill == 3;
bool playerEmptyAll = skillUsed && playerSkill == 1;
bool playerNoHeal = skillUsed && playerSkill == 2;
// 1. 如果玩家明牌,抢攻击堆(但只有能击杀或大堆才抢)
if (playerRevealedAll) {
// 先看能否直接获胜
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && piles[i].effect == 1) {
int damage = skillDoubleDamage ? 2 : 1;
if (playerHp <= damage * piles[i].stones) {
return {i, min(3, piles[i].stones)};
}
}
}
// 否则选评估最高的攻击堆(但权重已降)
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && piles[i].effect == 1) {
double score = evaluatePileAdvanced(i);
score += 8.0; // 攻击加成降低
if (score > bestScore) {
bestScore = score;
bestPileIndex = i;
}
}
}
if (bestPileIndex != -1) {
int take = skillEmptyPileAlways ? piles[bestPileIndex].stones : min(3, piles[bestPileIndex].stones);
return {bestPileIndex, take};
}
}
// 2. 崩碎殒命:完全避免扣血/陷阱,优先攻击或未知
if (playerNoHeal) {
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && piles[i].effect == 1) {
double score = evaluatePileAdvanced(i);
score += 8.0;
if (score > bestScore) {
bestScore = score;
bestPileIndex = i;
}
}
}
if (bestPileIndex == -1) {
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && !isPileKnownToAI(i)) {
bestPileIndex = i;
bestScore = 999999;
break;
}
}
if (bestPileIndex == -1) {
// 只能选扣血/陷阱,但必须不致命
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && (piles[i].effect == 2 || piles[i].effect == 3)) {
int damage = skillDoubleDamage ? 2 : 1;
if (aiHp > damage * piles[i].stones) {
bestPileIndex = i;
break;
}
}
}
}
}
if (bestPileIndex != -1) {
int take = skillEmptyPileAlways ? piles[bestPileIndex].stones : 1;
return {bestPileIndex, take};
}
}
// 3. 对赌协议:抢攻击堆,但回血堆优先级也提高
if (playerEmptyAll) {
// 能直接获胜?
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && piles[i].effect == 1) {
int damage = skillDoubleDamage ? 2 : 1;
if (playerHp <= damage * piles[i].stones) {
return {i, min(3, piles[i].stones)};
}
}
}
// 否则选评估最高的攻击或回血
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0) {
double score = evaluatePileAdvanced(i);
if (piles[i].effect == 1) score += 6.0;
if (piles[i].effect == 0 && !skillNoHeal) score += 4.0;
if (score > bestScore) {
bestScore = score;
bestPileIndex = i;
}
}
}
if (bestPileIndex != -1) {
int take = skillEmptyPileAlways ? piles[bestPileIndex].stones : min(3, piles[bestPileIndex].stones);
return {bestPileIndex, take};
}
}
// 4. 常规噩梦逻辑 - 优先保命(回血),再考虑攻击
// 先看能否直接击杀
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && isPileKnownToAI(i) && piles[i].effect == 1) {
int damage = skillDoubleDamage ? 2 : 1;
if (playerHp <= damage * piles[i].stones) {
return {i, min(3, piles[i].stones)};
}
}
}
// 低血量搏命:优先未知或攻击,但回血价值也高
if (aiHp <= 2) {
// 优先回血(如果能活)
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && piles[i].effect == 0 && !skillNoHeal) {
int heal = piles[i].stones;
if (aiHp + heal > 2) {
return {i, min(3, piles[i].stones)};
}
}
}
// 其次未知
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && !isPileKnownToAI(i)) {
int take = skillEmptyPileAlways ? piles[i].stones : min(3, piles[i].stones);
return {i, take};
}
}
// 最后攻击
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && piles[i].effect == 1) {
int take = skillEmptyPileAlways ? piles[i].stones : min(3, piles[i].stones);
return {i, take};
}
}
}
// 正常评估
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0) {
double score = evaluatePileAdvanced(i);
// 回血在低血量时已经自带高分,不用额外加
if (isPileKnownToAI(i) && piles[i].effect == 1) {
score += 6.0; // 攻击加成适度
}
if (isPileKnownToAI(i) && (piles[i].effect == 2 || piles[i].effect == 3)) {
if (aiHp <= 4) score -= 15.0;
if (aiHp <= 2) score -= 30.0;
}
if (score > bestScore) {
bestScore = score;
bestPileIndex = i;
}
}
}
if (bestPileIndex == -1) return {-1,-1};
int take;
if (skillEmptyPileAlways) take = piles[bestPileIndex].stones;
else {
take = getBestTakeCountAdvanced(bestPileIndex);
if (isPileKnownToAI(bestPileIndex) && piles[bestPileIndex].effect == 1) {
take = min(3, piles[bestPileIndex].stones);
}
if (isPileKnownToAI(bestPileIndex) && (piles[bestPileIndex].effect == 2 || piles[bestPileIndex].effect == 3)) {
if (aiHp > 2) take = 1;
else {
int damage = skillDoubleDamage ? 2 : 1;
if (aiHp > damage * piles[bestPileIndex].stones) {
take = min(2, piles[bestPileIndex].stones);
}
}
}
}
return {bestPileIndex, take};
}
// 地狱难度:完美权衡,绝对最优
pair<int, int> aiHellEvaluate() {
bool playerRevealedAll = skillUsed && playerSkill == 3;
bool playerEmptyAll = skillUsed && playerSkill == 1;
bool playerNoHeal = skillUsed && playerSkill == 2;
// 1. 直接获胜
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && piles[i].effect == 1) {
int damage = skillDoubleDamage ? 2 : 1;
if (playerHp <= damage * piles[i].stones) {
return {i, min(3, piles[i].stones)};
}
}
}
// 2. 如果AI血量低,优先回血(如果可以)
if (aiHp <= 3) {
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && piles[i].effect == 0 && !skillNoHeal) {
int heal = piles[i].stones;
if (aiHp + heal > 3) {
return {i, min(3, piles[i].stones)};
}
}
}
}
// 3. 玩家明牌:抢攻击堆,但只抢大的
if (playerRevealedAll) {
int bestAttackIdx = -1;
int maxStones = 0;
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && piles[i].effect == 1 && piles[i].stones > maxStones) {
maxStones = piles[i].stones;
bestAttackIdx = i;
}
}
if (bestAttackIdx != -1) {
int take = skillEmptyPileAlways ? piles[bestAttackIdx].stones : min(3, piles[bestAttackIdx].stones);
return {bestAttackIdx, take};
}
}
// 4. 对赌协议:抢攻击堆,但也考虑回血
if (playerEmptyAll) {
// 优先攻击
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && piles[i].effect == 1) {
return {i, min(3, piles[i].stones)};
}
}
// 没有攻击则回血
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && piles[i].effect == 0 && !skillNoHeal) {
return {i, min(3, piles[i].stones)};
}
}
}
// 5. 崩碎殒命:绝对避免扣血/陷阱,优先攻击或未知
if (playerNoHeal) {
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && piles[i].effect == 1) {
return {i, min(3, piles[i].stones)};
}
}
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && !piles[i].revealed) {
return {i, min(3, piles[i].stones)};
}
}
// 只能选扣血/陷阱,但确保不致命
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && (piles[i].effect == 2 || piles[i].effect == 3)) {
int damage = skillDoubleDamage ? 2 : 1;
if (aiHp > damage * piles[i].stones) {
return {i, 1};
}
}
}
}
// 6. 低血量搏命(但已经处理回血)
if (aiHp <= 2) {
// 优先攻击(如果能赢)
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && piles[i].effect == 1) {
int damage = skillDoubleDamage ? 2 : 1;
if (playerHp <= damage * piles[i].stones) {
return {i, min(3, piles[i].stones)};
}
}
}
// 其次陷阱(同归于尽可能赢)
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0 && piles[i].effect == 3) {
int damage = skillDoubleDamage ? 2 : 1;
if (playerHp <= damage * piles[i].stones) {
return {i, min(3, piles[i].stones)};
}
}
}
}
// 7. 常规地狱评估:绝对避免致命,综合评分
int bestIdx = -1;
double bestScore = -999999;
for (int i = 0; i < (int)piles.size(); ++i) {
if (piles[i].stones > 0) {
double score = evaluatePileAdvanced(i, true);
// 如果会导致AI死亡,大幅惩罚
if (piles[i].effect == 2 || piles[i].effect == 3) {
int damage = skillDoubleDamage ? 2 : 1;
int total = damage * piles[i].stones;
if (aiHp <= total) score -= 100.0;
}
// 攻击加成降低
if (piles[i].effect == 1) score += 5.0;
// 回血在低血量已有高分
if (piles[i].effect == 0 && !skillNoHeal) score += 3.0;
if (score > bestScore) {
bestScore = score;
bestIdx = i;
}
}
}
if (bestIdx == -1) return {-1,-1};
int take;
if (skillEmptyPileAlways) take = piles[bestIdx].stones;
else {
take = getBestTakeCountAdvanced(bestIdx);
if (piles[bestIdx].effect == 1 || piles[bestIdx].effect == 0) {
take = min(3, piles[bestIdx].stones);
} else {
if (aiHp > 2) take = 1;
else {
int damage = skillDoubleDamage ? 2 : 1;
if (aiHp > damage * piles[bestIdx].stones) {
take = min(2, piles[bestIdx].stones);
} else {
take = 1;
}
}
}
}
return {bestIdx, take};
}
void aiTurn() {
displayState();
cout << "\n============== AI回合 ==============\n";
auto [bestPileIndex, stonesToTake] = aiChooseAction();
if (bestPileIndex != -1 && stonesToTake > 0) {
cout << "AI从堆" << bestPileIndex + 1 << "摸取" << stonesToTake << "枚石子";
string tag;
switch(currentDifficulty) {
case EASY: tag = "[简单]"; break;
case HARD: tag = "[困难]"; break;
case NIGHTMARE: tag = "[噩梦⚡]"; break;
case HELL: tag = "[地狱🔥]"; break;
}
cout << " " << tag << "\n";
addAILog("AI从堆" + to_string(bestPileIndex+1) + "摸取" + to_string(stonesToTake) + "枚 " + tag);
takeStones(bestPileIndex, stonesToTake, false);
} else {
cout << "AI无法行动,跳过回合\n";
addAILog("AI跳过回合");
}
this_thread::sleep_for(chrono::milliseconds(1500));
}
// ---------- 玩家回合(支持0返回) ----------
void playerTurn() {
displayState();
cout << "\n============== 你的回合 ==============\n";
bool actionTaken = false;
while (!actionTaken) {
cout << "\n选择行动:\n";
cout << "1. 摸取石子\n";
if (!skillUsed) {
cout << "2. 使用技能 (";
if (playerSkill == 1) cout << "对赌协议";
else if (playerSkill == 2) cout << "崩碎殒命";
else if (playerSkill == 3) cout << "明牌决斗";
cout << ")\n";
}
int choice = safeInputInt("请选择: ", 1, skillUsed ? 1 : 2);
if (choice == 1) {
bool pileChosen = false;
while (!pileChosen) {
int pileChoice = safeInputInt("选择石子堆(1-" + to_string(piles.size()) + ", 0返回): ", 1, piles.size(), true);
if (pileChoice == 0) {
break;
}
pileChoice--;
if (skillEmptyPileAlways) {
int takeCount = piles[pileChoice].stones;
cout << "【对赌协议】自动摸取全部 " << takeCount << " 枚\n";
if (takeStones(pileChoice, takeCount, true)) {
actionTaken = true;
pileChosen = true;
} else {
cout << "无效行动!请重试\n";
}
} else {
bool countChosen = false;
while (!countChosen) {
int maxTake = min(3, piles[pileChoice].stones);
int take = safeInputInt("摸取数量(1-" + to_string(maxTake) + ", 0返回): ", 1, maxTake, true);
if (take == 0) {
break;
}
if (takeStones(pileChoice, take, true)) {
actionTaken = true;
countChosen = true;
pileChosen = true;
} else {
cout << "无效行动!请重试\n";
}
}
}
}
} else if (choice == 2 && !skillUsed) {
useSkill();
actionTaken = true;
}
}
}
bool checkGameOver() {
if (playerHp <= 0 || aiHp <= 0) {
gameOver = true;
displayState();
cout << "\n============== 游戏结束 ==============\n";
if (playerHp <= 0 && aiHp <= 0) {
cout << "⚔️ 同归于尽!平局!\n";
} else if (playerHp <= 0) {
cout << "💀 你死了!AI获胜!\n";
} else {
cout << "🎉 AI被击败!你获胜!\n";
cout << "你征服了 " << getDifficultyColor(currentDifficulty)
<< " " << getDifficultyName(currentDifficulty) << " 难度!\n";
}
cout << "最终HP - 你: " << playerHp << ", AI: " << aiHp << "\n";
return true;
}
return false;
}
void run() {
while (!gameOver) {
if (turn == 0) {
playerTurn();
if (checkGameOver()) break;
turn = 1;
} else {
aiTurn();
if (checkGameOver()) break;
turn = 0;
}
}
}
};
int main() {
system("chcp 65001 > nul");
while (true) {
StoneGame game;
game.run();
cout << "\n是否重新开始?(y/n): ";
char choice;
cin >> choice;
if (choice != 'y' && choice != 'Y') break;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return 0;
}自然演化
/*
* 演化沙盒 v25 - 万物生长 (G键)
* 编译: g++ -std=c++17 -pthread -o evo_sandbox evo_sandbox.cpp
*/
#include <iostream>
#include <vector>
#include <random>
#include <thread>
#include <chrono>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#ifdef _WIN32
#include <conio.h>
#include <windows.h>
#else
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#endif
// ---------- 常量 ----------
const int GRID_W = 60;
const int GRID_H = 20;
const int MAX_PREY = 150;
const int MAX_PREDATOR = 40;
const int MAX_FOOD = 35;
const double FOOD_ENERGY = 100.0;
const double MUTATION_INIT = 0.2;
const double FOOD_SPAWN_RATE = 0.3;
const int STAT_INTERVAL = 10;
const double MIN_DIST = 1.0;
const int DISASTER_INTERVAL = 100;
const double PREY_SENSE_SCALE = 15.0;
const double PREY_SENSE_MIN = 2.0;
const double PRED_SENSE_SCALE = 12.0;
const double PRED_SENSE_MIN = 3.0;
// 植物
const double PLANT_ENERGY = 150.0;
const double PLANT_SPAWN_RATE = 0.05;
const double PLANT_GROWTH_RATE = 0.08;
const int GROWTH_BOOST_DURATION = 30; // 万物生长持续世代数
const int GROWTH_BOOST_PLANTS = 5; // 立即生成的植物数量
// ---------- 结构体 ----------
struct Creature {
double x, y, vx, vy;
double energy;
double metabolism;
double senseRange;
double repThresh;
int age;
bool alive = true;
};
struct Predator {
double x, y, vx, vy;
double energy;
double metabolism;
double senseRange;
double repThresh;
int age;
bool alive = true;
};
struct Food {
int x, y;
double energy;
};
struct Plant {
int x, y;
};
// ---------- 随机引擎 ----------
std::mt19937 rng(std::random_device{}());
// ---------- 跨平台输入 ----------
class Input {
public:
static bool kbhit() {
#ifdef _WIN32
return _kbhit();
#else
struct termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
int ch = getchar();
if (ch != EOF) ungetc(ch, stdin);
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch != EOF;
#endif
}
static int getch() {
#ifdef _WIN32
return _getch();
#else
struct termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
int ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
#endif
}
};
void clearScreen() {
#ifdef _WIN32
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos = {0, 0};
SetConsoleCursorPosition(hOut, pos);
#else
std::cout << "\033[2J\033[H";
#endif
}
// ---------- 环境管理 ----------
class Environment {
public:
std::vector<Plant> plants;
int growthBoostTimer; // 剩余生长加速世代数
Environment() : growthBoostTimer(0) {
std::uniform_int_distribution<int> xDist(1, GRID_W-2);
std::uniform_int_distribution<int> yDist(1, GRID_H-2);
for (int i = 0; i < 10; ++i) {
int x = xDist(rng), y = yDist(rng);
if (!isPlantAt(x, y)) plants.push_back({x, y});
}
}
void update() {
// 生长加速计时器
if (growthBoostTimer > 0)
growthBoostTimer--;
// 随机新生
if (std::bernoulli_distribution(PLANT_SPAWN_RATE)(rng)) {
std::uniform_int_distribution<int> xDist(1, GRID_W-2);
std::uniform_int_distribution<int> yDist(1, GRID_H-2);
int x = xDist(rng), y = yDist(rng);
if (!isPlantAt(x, y)) plants.push_back({x, y});
}
// 扩散生长(可能受加速影响)
double effectiveGrowthRate = PLANT_GROWTH_RATE;
if (growthBoostTimer > 0)
effectiveGrowthRate *= 4.0;
std::vector<std::pair<int,int>> newPlants;
for (auto& p : plants) {
if (std::bernoulli_distribution(effectiveGrowthRate)(rng)) {
std::uniform_int_distribution<int> offset(-1, 1);
int nx = p.x + offset(rng);
int ny = p.y + offset(rng);
if (nx >= 1 && nx < GRID_W-1 && ny >= 1 && ny < GRID_H-1 && !isPlantAt(nx, ny))
newPlants.push_back({nx, ny});
}
}
for (auto& np : newPlants) {
if (!isPlantAt(np.first, np.second))
plants.push_back({np.first, np.second});
}
}
bool isPlantAt(int x, int y) const {
for (auto& p : plants)
if (p.x == x && p.y == y) return true;
return false;
}
void spawnPlantManual() {
std::uniform_int_distribution<int> xDist(1, GRID_W-2);
std::uniform_int_distribution<int> yDist(1, GRID_H-2);
int x = xDist(rng), y = yDist(rng);
if (!isPlantAt(x, y)) {
plants.push_back({x, y});
}
}
// 触发万物生长
void activateGrowthBoost() {
// 立即生成植物
for (int i = 0; i < GROWTH_BOOST_PLANTS; ++i)
spawnPlantManual();
// 设置加速计时器(如果已有加速则叠加时间)
growthBoostTimer += GROWTH_BOOST_DURATION;
}
};
// ---------- 主模拟 ----------
class EvoSim {
private:
std::vector<Creature> prey;
std::vector<Predator> predators;
std::vector<Food> foods;
Environment env;
double mutationRate;
double foodSpawnRate;
int generation;
bool paused;
double avgPreyMetab, avgPreySense, avgPreyRep;
double avgPredMetab, avgPredSense, avgPredRep;
int disasterTimer;
std::string lastDisaster;
double preySenseFromMetab(double m) { return std::max(PREY_SENSE_MIN, m * PREY_SENSE_SCALE); }
double predSenseFromMetab(double m) { return std::max(PRED_SENSE_MIN, m * PRED_SENSE_SCALE); }
void pushApart(double& x1, double& y1, double& x2, double& y2) {
double dx = x1 - x2, dy = y1 - y2;
double dist = std::sqrt(dx*dx + dy*dy);
if (dist < MIN_DIST && dist > 0.001) {
double overlap = MIN_DIST - dist;
x1 += (dx/dist) * overlap * 0.5;
y1 += (dy/dist) * overlap * 0.5;
x2 -= (dx/dist) * overlap * 0.5;
y2 -= (dy/dist) * overlap * 0.5;
}
}
void clamp(double& x, double& y) {
if (x < 1) x = 1; if (x > GRID_W-1) x = GRID_W-1;
if (y < 1) y = 1; if (y > GRID_H-1) y = GRID_H-1;
}
void resolveOverlaps() {
for (size_t i=0; i<prey.size(); ++i)
for (size_t j=i+1; j<prey.size(); ++j)
pushApart(prey[i].x, prey[i].y, prey[j].x, prey[j].y);
for (size_t i=0; i<predators.size(); ++i)
for (size_t j=i+1; j<predators.size(); ++j)
pushApart(predators[i].x, predators[i].y, predators[j].x, predators[j].y);
for (auto& p : predators)
for (auto& c : prey)
pushApart(p.x, p.y, c.x, c.y);
for (auto& c : prey) clamp(c.x, c.y);
for (auto& p : predators) clamp(p.x, p.y);
}
void spawnFood() {
if (foods.size() >= MAX_FOOD) return;
std::uniform_int_distribution<int> xDist(1, GRID_W-2), yDist(1, GRID_H-2);
int x = xDist(rng), y = yDist(rng);
if (env.isPlantAt(x, y)) return;
foods.push_back({x, y, FOOD_ENERGY});
}
void triggerDisaster() {
std::uniform_int_distribution<int> type(0, 4);
switch(type(rng)) {
case 0: if (!foods.empty()) foods.resize(foods.size()/2); lastDisaster="饥荒"; break;
case 1: { int kill = prey.size()*0.3; std::shuffle(prey.begin(), prey.end(), rng);
for (int i=0; i<kill; ++i) prey[i].alive = false; lastDisaster="瘟疫"; break; }
case 2: { int kill = predators.size()*0.2; std::shuffle(predators.begin(), predators.end(), rng);
for (int i=0; i<kill; ++i) predators[i].alive = false; lastDisaster="风暴"; break; }
case 3: for (auto& c : prey) c.metabolism *= 2.0;
for (auto& p : predators) p.metabolism *= 2.0; lastDisaster="毒藻"; break;
case 4: for (auto& c : prey) c.senseRange *= 0.5;
for (auto& p : predators) p.senseRange *= 0.5; lastDisaster="火山灰"; break;
}
}
void spawnPreyManual() {
if (prey.size() >= MAX_PREY) return;
std::uniform_real_distribution<double> posX(1.0, GRID_W-2.0);
std::uniform_real_distribution<double> posY(1.0, GRID_H-2.0);
std::normal_distribution<double> trait(0.0, 0.5);
Creature c;
c.x = posX(rng); c.y = posY(rng);
c.vx = c.vy = 0; c.energy = 80.0;
c.metabolism = std::max(0.1, 0.3 + trait(rng)*0.05);
c.senseRange = preySenseFromMetab(c.metabolism);
c.repThresh = 60.0 + trait(rng)*10;
c.age = 0;
prey.push_back(c);
}
void spawnPredatorManual() {
if (predators.size() >= MAX_PREDATOR) return;
std::uniform_real_distribution<double> posX(1.0, GRID_W-2.0);
std::uniform_real_distribution<double> posY(1.0, GRID_H-2.0);
std::normal_distribution<double> trait(0.0, 0.5);
Predator p;
p.x = posX(rng); p.y = posY(rng);
p.vx = p.vy = 0; p.energy = 80.0;
p.metabolism = std::max(0.15, 0.5 + trait(rng)*0.1);
p.senseRange = predSenseFromMetab(p.metabolism);
p.repThresh = 120.0 + trait(rng)*30;
p.age = 0;
predators.push_back(p);
}
public:
EvoSim() : mutationRate(MUTATION_INIT), foodSpawnRate(FOOD_SPAWN_RATE),
generation(0), paused(false), disasterTimer(DISASTER_INTERVAL) {
std::uniform_real_distribution<double> posX(1.0, GRID_W-2.0), posY(1.0, GRID_H-2.0);
std::normal_distribution<double> trait(0.0, 0.5);
for (int i=0; i<25; ++i) {
Creature c;
c.x = posX(rng); c.y = posY(rng);
c.vx = c.vy = 0; c.energy = 80.0;
c.metabolism = std::max(0.1, 0.3 + trait(rng)*0.05);
c.senseRange = preySenseFromMetab(c.metabolism);
c.repThresh = 60.0 + trait(rng)*10;
c.age = 0;
prey.push_back(c);
}
for (int i=0; i<6; ++i) {
Predator p;
p.x = posX(rng); p.y = posY(rng);
p.vx = p.vy = 0; p.energy = 80.0;
p.metabolism = std::max(0.15, 0.5 + trait(rng)*0.1);
p.senseRange = predSenseFromMetab(p.metabolism);
p.repThresh = 120.0 + trait(rng)*30;
p.age = 0;
predators.push_back(p);
}
for (int i=0; i<15; ++i) spawnFood();
resolveOverlaps();
}
void update() {
if (paused) return;
if (--disasterTimer <= 0) { triggerDisaster(); disasterTimer = DISASTER_INTERVAL; }
env.update();
if (std::bernoulli_distribution(foodSpawnRate)(rng)) spawnFood();
// ---------- 猎物 ----------
for (auto& c : prey) {
if (!c.alive) continue;
c.age++; if (c.age > 500) { c.alive = false; continue; }
c.energy -= c.metabolism;
if (c.energy <= 0) { c.alive = false; continue; }
double fleeDist2 = c.senseRange * c.senseRange;
const Predator* nearPred = nullptr;
double minPredDist2 = fleeDist2;
for (auto& p : predators) {
double dx = p.x - c.x, dy = p.y - c.y;
double d2 = dx*dx + dy*dy;
if (d2 < minPredDist2) { minPredDist2 = d2; nearPred = &p; }
}
if (nearPred) {
double dx = c.x - nearPred->x, dy = c.y - nearPred->y;
double len = std::sqrt(dx*dx + dy*dy);
if (len > 0.1) { c.vx = (dx/len)*0.6; c.vy = (dy/len)*0.6; }
} else {
double minFoodDist2 = c.senseRange * c.senseRange;
double targetX = 0, targetY = 0;
bool hasTarget = false;
for (auto& f : foods) {
double dx = f.x - c.x, dy = f.y - c.y;
double d2 = dx*dx + dy*dy;
if (d2 < minFoodDist2) { minFoodDist2 = d2; targetX = f.x; targetY = f.y; hasTarget = true; }
}
for (auto& pl : env.plants) {
double dx = pl.x - c.x, dy = pl.y - c.y;
double d2 = dx*dx + dy*dy;
if (d2 < minFoodDist2) { minFoodDist2 = d2; targetX = pl.x; targetY = pl.y; hasTarget = true; }
}
if (hasTarget) {
double dx = targetX - c.x, dy = targetY - c.y;
double len = std::sqrt(dx*dx + dy*dy);
if (len > 0.1) { c.vx = (dx/len)*0.4; c.vy = (dy/len)*0.4; }
} else {
std::normal_distribution<double> turn(0.0,0.3);
c.vx += turn(rng)*0.1; c.vy += turn(rng)*0.1;
double sp = std::sqrt(c.vx*c.vx + c.vy*c.vy);
if (sp > 0.6) { c.vx = c.vx/sp*0.6; c.vy = c.vy/sp*0.6; }
}
}
c.x += c.vx; c.y += c.vy;
clamp(c.x, c.y);
for (auto& f : foods) {
if (std::abs(c.x - f.x) < 1.0 && std::abs(c.y - f.y) < 1.0) {
c.energy += f.energy; f.energy = 0; break;
}
}
for (size_t i = 0; i < env.plants.size(); ++i) {
auto& pl = env.plants[i];
if (std::abs(c.x - pl.x) < 1.0 && std::abs(c.y - pl.y) < 1.0) {
c.energy += PLANT_ENERGY;
env.plants.erase(env.plants.begin() + i);
break;
}
}
if (c.energy >= c.repThresh && prey.size() < MAX_PREY) {
c.energy /= 2.0;
Creature baby = c;
baby.energy = c.energy; baby.age = 0;
std::normal_distribution<double> mut(0.0, mutationRate);
baby.metabolism = std::max(0.1, c.metabolism + mut(rng)*0.1);
baby.senseRange = preySenseFromMetab(baby.metabolism);
baby.repThresh = std::max(40.0, c.repThresh + mut(rng)*10.0);
baby.x += mut(rng)*0.5; baby.y += mut(rng)*0.5;
prey.push_back(baby);
}
}
// ---------- 捕食者 ----------
for (auto& p : predators) {
if (!p.alive) continue;
p.age++; if (p.age > 300) { p.alive = false; continue; }
p.energy -= p.metabolism;
if (p.energy <= 0) { p.alive = false; continue; }
const Creature* target = nullptr;
double minDist2 = p.senseRange * p.senseRange;
for (auto& c : prey) {
double dx = c.x - p.x, dy = c.y - p.y;
double d2 = dx*dx + dy*dy;
if (d2 < minDist2) { minDist2 = d2; target = &c; }
}
if (target) {
double dx = target->x - p.x, dy = target->y - p.y;
double len = std::sqrt(dx*dx + dy*dy);
if (len > 0.1) { p.vx = (dx/len)*0.6; p.vy = (dy/len)*0.6; }
} else {
std::normal_distribution<double> turn(0.0,0.3);
p.vx += turn(rng)*0.1; p.vy += turn(rng)*0.1;
double sp = std::sqrt(p.vx*p.vx + p.vy*p.vy);
if (sp > 0.8) { p.vx = p.vx/sp*0.8; p.vy = p.vy/sp*0.8; }
}
p.x += p.vx; p.y += p.vy;
clamp(p.x, p.y);
for (auto& c : prey) {
if (std::abs(p.x-c.x)<1.0 && std::abs(p.y-c.y)<1.0) {
p.energy += c.energy * 0.8; c.alive = false;
break;
}
}
if (p.energy >= p.repThresh && predators.size() < MAX_PREDATOR) {
p.energy /= 2.0;
Predator baby = p;
baby.energy = p.energy; baby.age = 0;
std::normal_distribution<double> mut(0.0, mutationRate);
baby.metabolism = std::max(0.15, p.metabolism + mut(rng)*0.15);
baby.senseRange = predSenseFromMetab(baby.metabolism);
baby.repThresh = std::max(60.0, p.repThresh + mut(rng)*15.0);
baby.x += mut(rng)*0.5; baby.y += mut(rng)*0.5;
predators.push_back(baby);
}
}
prey.erase(std::remove_if(prey.begin(), prey.end(), [](Creature& c){return !c.alive;}), prey.end());
predators.erase(std::remove_if(predators.begin(), predators.end(), [](Predator& p){return !p.alive;}), predators.end());
foods.erase(std::remove_if(foods.begin(), foods.end(), [](Food& f){return f.energy<=0;}), foods.end());
resolveOverlaps();
generation++;
}
void calcStats() {
if (generation % STAT_INTERVAL != 0) return;
double m1=0,s1=0,r1=0;
for (auto& c : prey) { m1+=c.metabolism; s1+=c.senseRange; r1+=c.repThresh; }
if (!prey.empty()) { avgPreyMetab=m1/prey.size(); avgPreySense=s1/prey.size(); avgPreyRep=r1/prey.size(); }
double m2=0,s2=0,r2=0;
for (auto& p : predators) { m2+=p.metabolism; s2+=p.senseRange; r2+=p.repThresh; }
if (!predators.empty()) { avgPredMetab=m2/predators.size(); avgPredSense=s2/predators.size(); avgPredRep=r2/predators.size(); }
}
void render() {
clearScreen();
std::vector<std::string> grid(GRID_H, std::string(GRID_W, ' '));
for (int y=0; y<GRID_H; ++y) grid[y][0] = grid[y][GRID_W-1] = '#';
for (int x=0; x<GRID_W; ++x) grid[0][x] = grid[GRID_H-1][x] = '#';
for (auto& pl : env.plants) grid[pl.y][pl.x] = '*';
for (auto& f : foods) if (f.energy > 0) grid[f.y][f.x] = '+';
for (auto& c : prey) { int cx=c.x, cy=c.y; if (cy>0&&cy<GRID_H-1&&cx>0&&cx<GRID_W-1) grid[cy][cx]='@'; }
for (auto& p : predators) { int cx=p.x, cy=p.y; if (cy>0&&cy<GRID_H-1&&cx>0&&cx<GRID_W-1) grid[cy][cx]='X'; }
for (auto& row : grid) std::cout << row << "\n";
std::cout << "猎物:" << prey.size() << " 捕食者:" << predators.size()
<< " 植物:" << env.plants.size() << " 食物:" << foods.size()
<< " 世代:" << generation << " 变异率:" << mutationRate
<< " 食物率:" << foodSpawnRate;
if (env.growthBoostTimer > 0)
std::cout << " 生长加速:" << env.growthBoostTimer;
if (!lastDisaster.empty()) std::cout << " 灾害:" << lastDisaster;
std::cout << "\n猎物 代谢:" << avgPreyMetab << " 感知:" << avgPreySense << " 繁殖阈:" << avgPreyRep;
std::cout << "\n捕食者 代谢:" << avgPredMetab << " 感知:" << avgPredSense << " 繁殖阈:" << avgPredRep;
std::cout << "\n[↑↓变异率] [←→食物率] [P]植物 [C]猎物 [X]捕食者 [G]万物生长 [空格暂停] [Q退出]";
}
void handleInput() {
if (!Input::kbhit()) return;
int c = Input::getch();
switch(c) {
case 72: case 'w': mutationRate = std::min(1.0, mutationRate+0.05); break;
case 80: case 's': mutationRate = std::max(0.0, mutationRate-0.05); break;
case 75: case 'a': foodSpawnRate = std::max(0.0, foodSpawnRate-0.05); break;
case 77: case 'd': foodSpawnRate = std::min(1.0, foodSpawnRate+0.05); break;
case ' ': paused = !paused; break;
case 'q': case 'Q': exit(0);
case 'p': env.spawnPlantManual(); break;
case 'c': spawnPreyManual(); break;
case 'x': spawnPredatorManual(); break;
case 'g': env.activateGrowthBoost(); break; // 万物生长
default: break;
}
}
void run() {
while (true) {
handleInput();
update();
calcStats();
render();
std::this_thread::sleep_for(std::chrono::milliseconds(400));
}
}
};
int main() {
EvoSim sim;
sim.run();
return 0;
}免疫战线
/*
* 免疫战线 - 细胞凋亡不清除免疫力
* 编译: g++ -std=c++17 -o immune_war immune_war.cpp
* 运行: ./immune_war
*/
#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <algorithm>
#include <limits>
std::mt19937 rng(std::random_device{}());
int difficulty = 1;
int immuneLife = 15;
int virusLife = 15;
int immuneShield = 0;
int hematopoiesis = 0;
int atp = 3;
int rna = 2;
int turnCount = 0;
bool gameOver = false;
bool playerWin = false;
std::vector<std::string> immuneDeck, immuneHand, immuneDiscard;
std::vector<std::string> virusDeck, virusHand, virusDiscard;
std::vector<std::string> immuneDebuffs;
bool hasLatent = false;
bool phagocytosisBlocked = false;
bool neutralizeNext = false;
int complementDamage = 1;
std::string lastVirusAction = "无";
const int HAND_MAX = 5;
int bonusRNA = 0;
struct Card {
std::string name;
int cost;
bool isImmune;
std::string description;
};
std::vector<Card> immuneCards = {
{"吞噬作用", 2, true, "优先移除一个感染减益;若无感染但有潜伏,则潜伏削弱为一层感染"},
{"抗体中和", 3, true, "抵消病毒本回合一张牌,回复3血"},
{"屏障生成", 2, true, "获得3点免疫力"},
{"造血干细胞", 3, true, "获得一层造血 (每回合+1ATP)"},
{"骨髓动员", 3, true, "回复4血,获得2点免疫力"},
{"胸腺选择", 1, true, "查看牌库顶5张,选1张入手,获得1免疫力"},
{"补体激活", 2, true, "对母巢造成1伤,本局每次使用后伤害+1"},
{"炎症风暴", 2, true, "双方各受4伤,自己回复2血,获得3ATP"}
};
std::vector<Card> virusCards = {
{"持续感染", 2, false, "给免疫核心增加一个感染减益 (每回合开始造成1伤)"},
{"潜伏感染", 3, false, "放置潜伏减益 (每回合结束若未用吞噬/抗原呈递则2伤)"},
{"免疫逃逸", 3, false, "免疫方下回合无法使用吞噬/抗原呈递,造成2伤(无视护盾)"},
{"毒素释放", 2, false, "移除一层造血,免疫方下回合ATP-1"},
{"细胞凋亡", 5, false, "造成6伤,移除所有造血层数,不影响免疫力"}, // 修改描述
{"病毒复制", 3, false, "回复病毒母巢4点生命,抽一张牌"}
};
void shuffleDeck(std::vector<std::string>& deck) {
std::shuffle(deck.begin(), deck.end(), rng);
}
void buildDecks() {
immuneDeck.clear(); immuneDiscard.clear();
virusDeck.clear(); virusDiscard.clear();
for (auto& c : immuneCards)
for (int i = 0; i < 2; ++i) immuneDeck.push_back(c.name);
int virusCardCount = 3;
if (difficulty == 3) virusCardCount = 4;
for (auto& c : virusCards)
for (int i = 0; i < virusCardCount; ++i) virusDeck.push_back(c.name);
shuffleDeck(immuneDeck);
shuffleDeck(virusDeck);
}
void drawCards(std::vector<std::string>& deck, std::vector<std::string>& hand,
std::vector<std::string>& discard, int count) {
for (int i = 0; i < count; ++i) {
if (hand.size() >= HAND_MAX) break;
if (deck.empty()) {
if (discard.empty()) break;
deck = std::move(discard);
discard.clear();
shuffleDeck(deck);
}
hand.push_back(deck.back());
deck.pop_back();
}
}
void removeFromHand(std::vector<std::string>& hand, const std::string& name,
std::vector<std::string>& discard) {
auto it = std::find(hand.begin(), hand.end(), name);
if (it != hand.end()) {
hand.erase(it);
discard.push_back(name);
}
}
Card findCard(const std::string& name, bool isImmune) {
if (isImmune) {
for (auto& c : immuneCards) if (c.name == name) return c;
} else {
for (auto& c : virusCards) if (c.name == name) return c;
}
return {"", 0, true, ""};
}
void dealDamageToImmune(int dmg, bool ignoreShield = false) {
if (ignoreShield) {
immuneLife -= dmg;
} else {
if (immuneShield > 0) {
int blocked = std::min(immuneShield, dmg);
immuneShield -= blocked;
dmg -= blocked;
}
immuneLife -= dmg;
}
if (immuneLife < 0) immuneLife = 0;
if (immuneLife <= 0) {
gameOver = true;
playerWin = false;
}
}
void dealDamageToVirus(int dmg) {
if (gameOver) return;
int actualDamage = dmg;
virusLife -= actualDamage;
if (virusLife <= 0) {
virusLife = 0;
gameOver = true;
playerWin = true;
return;
}
if (difficulty == 3) {
bonusRNA += actualDamage;
}
}
void applyInfectionDebuffs() {
int count = std::count(immuneDebuffs.begin(), immuneDebuffs.end(), "感染");
dealDamageToImmune(count);
}
std::string aiChooseCard() {
std::vector<std::string> affordable;
for (auto& name : virusHand) {
if (findCard(name, false).cost <= rna) affordable.push_back(name);
}
if (affordable.empty()) return "";
if (virusLife < 5) {
auto it = std::find(affordable.begin(), affordable.end(), "病毒复制");
if (it != affordable.end()) return "病毒复制";
}
if (difficulty == 0) {
if (std::find(affordable.begin(), affordable.end(), "持续感染") != affordable.end())
return "持续感染";
if (!hasLatent && std::find(affordable.begin(), affordable.end(), "潜伏感染") != affordable.end())
return "潜伏感染";
return "";
}
if (difficulty == 1) {
if (std::find(affordable.begin(), affordable.end(), "持续感染") != affordable.end())
return "持续感染";
if (!hasLatent && std::find(affordable.begin(), affordable.end(), "潜伏感染") != affordable.end())
return "潜伏感染";
if (std::find(affordable.begin(), affordable.end(), "毒素释放") != affordable.end())
return "毒素释放";
if (std::find(affordable.begin(), affordable.end(), "免疫逃逸") != affordable.end())
return "免疫逃逸";
if (std::find(affordable.begin(), affordable.end(), "细胞凋亡") != affordable.end())
return "细胞凋亡";
return affordable[0];
}
if (std::find(affordable.begin(), affordable.end(), "细胞凋亡") != affordable.end())
return "细胞凋亡";
if (std::find(affordable.begin(), affordable.end(), "免疫逃逸") != affordable.end())
return "免疫逃逸";
if (std::find(affordable.begin(), affordable.end(), "持续感染") != affordable.end())
return "持续感染";
if (!hasLatent && std::find(affordable.begin(), affordable.end(), "潜伏感染") != affordable.end())
return "潜伏感染";
if (std::find(affordable.begin(), affordable.end(), "毒素释放") != affordable.end())
return "毒素释放";
auto it = std::find(affordable.begin(), affordable.end(), "病毒复制");
if (it != affordable.end()) return "病毒复制";
return affordable[0];
}
void executeVirusCard(const std::string& cardName) {
Card c = findCard(cardName, false);
rna -= c.cost;
removeFromHand(virusHand, cardName, virusDiscard);
lastVirusAction = cardName;
if (cardName == "持续感染") {
immuneDebuffs.push_back("感染");
std::cout << "病毒使用了持续感染。\n";
} else if (cardName == "潜伏感染") {
if (!hasLatent) {
hasLatent = true;
std::cout << "病毒使用了潜伏感染。\n";
} else {
dealDamageToImmune(2);
std::cout << "潜伏感染已存在,造成2点伤害。\n";
}
} else if (cardName == "免疫逃逸") {
phagocytosisBlocked = true;
dealDamageToImmune(2, true);
std::cout << "病毒使用了免疫逃逸,造成2点穿甲伤害。\n";
} else if (cardName == "毒素释放") {
if (hematopoiesis > 0) {
hematopoiesis--;
std::cout << "病毒使用了毒素释放,移除一层造血。\n";
} else {
dealDamageToImmune(1);
std::cout << "毒素释放无效,造成1点伤害。\n";
}
} else if (cardName == "细胞凋亡") {
dealDamageToImmune(6);
// 不清除免疫力,仅移除造血层数
if (hematopoiesis > 0) {
hematopoiesis = 0;
std::cout << "病毒使用了细胞凋亡!造成6点伤害,移除所有造血层数。\n";
} else {
std::cout << "病毒使用了细胞凋亡!造成6点伤害。\n";
}
} else if (cardName == "病毒复制") {
virusLife += 4;
drawCards(virusDeck, virusHand, virusDiscard, 1);
std::cout << "病毒使用了病毒复制,回复4点生命并抽一张牌。\n";
}
}
void render() {
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
const char* diffStr[] = {"简单", "困难", "地狱", "噩梦"};
std::cout << "======== 免疫战线 [难度: " << diffStr[difficulty] << "] ======== 回合 " << turnCount << "\n";
std::cout << "免疫核心 生命: " << immuneLife << " 免疫力: " << immuneShield
<< " 造血: " << hematopoiesis << "\n";
std::cout << "病毒母巢 生命: " << virusLife << "\n";
std::cout << "ATP: " << atp << " RNA: " << rna << "\n";
std::cout << "免疫减益: ";
int infCount = std::count(immuneDebuffs.begin(), immuneDebuffs.end(), "感染");
if (infCount == 0 && !hasLatent) std::cout << "无";
else {
if (infCount > 0) std::cout << infCount << "层感染 ";
if (hasLatent) std::cout << "[潜伏]";
}
std::cout << "\n\n免疫手牌 (" << immuneHand.size() << "/" << HAND_MAX << "):\n";
for (size_t i = 0; i < immuneHand.size(); ++i) {
Card c = findCard(immuneHand[i], true);
std::cout << " [" << i+1 << "] " << c.name << " (费" << c.cost << ") " << c.description << "\n";
}
std::cout << "\n病毒手牌: " << virusHand.size() << "张\n";
if (lastVirusAction != "无")
std::cout << "上回合病毒出牌: " << lastVirusAction << "\n";
std::cout << "\n命令: 输入牌编号使用, 0跳过回合\n> ";
}
int main() {
std::cout << "选择难度 (0=简单 1=困难 2=地狱 3=噩梦): ";
std::cin >> difficulty;
if (difficulty < 0) difficulty = 0;
if (difficulty > 3) difficulty = 3;
switch(difficulty) {
case 0: immuneLife = 20; virusLife = 12; immuneShield = 3; break;
case 1: immuneLife = 15; virusLife = 15; immuneShield = 0; break;
case 2: immuneLife = 12; virusLife = 18; immuneShield = 0; break;
case 3: immuneLife = 10; virusLife = 22; immuneShield = 0; break;
}
hematopoiesis = 0;
bonusRNA = 0;
gameOver = false;
playerWin = false;
buildDecks();
drawCards(immuneDeck, immuneHand, immuneDiscard, 3);
drawCards(virusDeck, virusHand, virusDiscard, 2);
while (!gameOver) {
turnCount++;
phagocytosisBlocked = false;
int baseATP = 3;
int baseRNA = 2;
if (difficulty == 2) baseRNA = 3;
if (difficulty == 3) baseRNA = 4;
atp = baseATP + hematopoiesis;
int infCount = std::count(immuneDebuffs.begin(), immuneDebuffs.end(), "感染");
rna = baseRNA + infCount + bonusRNA;
bonusRNA = 0;
applyInfectionDebuffs();
if (gameOver) break;
drawCards(immuneDeck, immuneHand, immuneDiscard, 2);
drawCards(virusDeck, virusHand, virusDiscard, 1);
bool immuneTurnDone = false;
bool usedPhagocytosis = false;
while (!immuneTurnDone && !gameOver) {
render();
int choice;
std::cin >> choice;
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "无效输入\n";
continue;
}
if (choice == 0) { immuneTurnDone = true; break; }
int index = choice - 1;
if (index < 0 || index >= (int)immuneHand.size()) { std::cout << "编号无效\n"; continue; }
std::string cardName = immuneHand[index];
Card card = findCard(cardName, true);
if (card.cost > atp) { std::cout << "ATP不足\n"; continue; }
if (phagocytosisBlocked && cardName == "吞噬作用") {
std::cout << "受免疫逃逸影响,本回合无法使用该牌\n";
continue;
}
atp -= card.cost;
removeFromHand(immuneHand, cardName, immuneDiscard);
if (cardName == "吞噬作用") {
usedPhagocytosis = true;
if (!immuneDebuffs.empty()) {
auto it = std::find(immuneDebuffs.begin(), immuneDebuffs.end(), "感染");
if (it != immuneDebuffs.end()) {
immuneDebuffs.erase(it);
std::cout << "吞噬作用移除了一个感染减益。\n";
} else if (hasLatent) {
hasLatent = false;
immuneDebuffs.push_back("感染");
std::cout << "吞噬作用将潜伏感染削弱为一层感染。\n";
} else {
std::cout << "没有减益可移除。\n";
}
} else if (hasLatent) {
hasLatent = false;
immuneDebuffs.push_back("感染");
std::cout << "吞噬作用将潜伏感染削弱为一层感染。\n";
} else {
std::cout << "没有减益可移除。\n";
}
dealDamageToVirus(2);
if (gameOver) break;
std::cout << "对病毒母巢造成2点伤害。\n";
} else if (cardName == "抗体中和") {
neutralizeNext = true;
immuneLife += 3;
if (immuneLife > 20) immuneLife = 20;
std::cout << "回复3点生命,并将抵消病毒下一张牌。\n";
} else if (cardName == "屏障生成") {
immuneShield += 3;
std::cout << "获得3点免疫力。\n";
} else if (cardName == "造血干细胞") {
hematopoiesis++;
std::cout << "获得一层造血。\n";
} else if (cardName == "骨髓动员") {
immuneLife += 4; if (immuneLife > 20) immuneLife = 20;
immuneShield += 2;
std::cout << "回复4血,获得2免疫力。\n";
} else if (cardName == "胸腺选择") {
std::vector<std::string> top5;
int cnt = 0;
while (cnt < 5 && (!immuneDeck.empty() || !immuneDiscard.empty())) {
if (immuneDeck.empty()) {
immuneDeck = std::move(immuneDiscard);
immuneDiscard.clear();
shuffleDeck(immuneDeck);
}
top5.push_back(immuneDeck.back());
immuneDeck.pop_back();
cnt++;
}
if (!top5.empty()) {
std::cout << "牌库顶5张: ";
for (size_t i=0; i<top5.size(); ++i) std::cout << "[" << i+1 << "]" << top5[i] << " ";
std::cout << "\n选择一张加入手牌 (编号): ";
int sel; std::cin >> sel;
if (sel >= 1 && sel <= (int)top5.size()) {
immuneHand.push_back(top5[sel-1]);
top5.erase(top5.begin() + sel - 1);
}
for (auto& c : top5) immuneDeck.insert(immuneDeck.begin(), c);
}
immuneShield += 1;
std::cout << "获得1点免疫力。\n";
} else if (cardName == "补体激活") {
dealDamageToVirus(complementDamage);
if (gameOver) break;
std::cout << "造成" << complementDamage << "点伤害。";
complementDamage++;
} else if (cardName == "炎症风暴") {
dealDamageToImmune(4);
dealDamageToVirus(4);
if (gameOver) break;
immuneLife += 2; if (immuneLife > 20) immuneLife = 20;
atp += 3;
std::cout << "双方各受4伤,免疫核心回复2点生命,获得3 ATP。\n";
}
if (!gameOver) {
std::cout << "是否继续出牌?(1=是,0=结束回合): ";
int cont; std::cin >> cont;
if (cont == 0) immuneTurnDone = true;
}
}
if (gameOver) break;
if (hasLatent && !usedPhagocytosis) {
std::cout << "潜伏感染触发:免疫核心受到2点伤害。\n";
dealDamageToImmune(2);
if (gameOver) break;
}
if (virusLife > 0) {
std::string virusCard = aiChooseCard();
if (!virusCard.empty()) {
if (neutralizeNext) {
std::cout << "抗体中和生效!病毒牌被抵消。\n";
neutralizeNext = false;
lastVirusAction = "被抵消";
removeFromHand(virusHand, virusCard, virusDiscard);
} else {
executeVirusCard(virusCard);
}
}
if (difficulty == 3 && virusLife > 0) {
virusLife += 2;
std::cout << "噩梦难度:病毒自动回复2点生命(无上限)。\n";
}
}
if (immuneLife <= 0) {
gameOver = true;
playerWin = false;
} else if (virusLife <= 0) {
gameOver = true;
playerWin = true;
} else if (immuneDeck.empty() && immuneDiscard.empty() && immuneHand.empty()) {
gameOver = true;
playerWin = false;
} else if (virusDeck.empty() && virusDiscard.empty() && virusHand.empty()) {
gameOver = true;
playerWin = true;
}
}
std::cout << "\n游戏结束。";
if (playerWin) std::cout << "免疫胜利!\n";
else std::cout << "病毒胜利...\n";
std::cout << "最终生命: 免疫 " << immuneLife << " 病毒 " << virusLife << "\n";
return 0;
}监视诡异
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <chrono>
#include <thread>
#include <iomanip>
#include <limits>
#include <string>
#ifdef _WIN32
#include <conio.h>
#include <windows.h>
#else
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
int _kbhit() {
struct termios oldt, newt;
int ch, oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF) { ungetc(ch, stdin); return 1; }
return 0;
}
char _getch() { return getchar(); }
#endif
using namespace std::chrono;
class Game {
private:
static const int ROOM_COUNT = 5;
static const int MAX_BULLETS = 20;
static constexpr double MAX_SPEED = 30.0;
static constexpr double DAY_SECONDS = 30.0;
static constexpr int FULL_SUPPLY_DAY = 5;
static constexpr double COLLAPSE_THRESHOLD = 200.0;
static constexpr int FEAR_HITS_NEEDED = 5;
std::vector<double> progress;
std::vector<double> collapseDamage; // 累计有效伤害
std::vector<int> collapseDaysLeft;
std::vector<int> fearHits;
int monitorIndex;
int day;
int bullets;
double currentSpeedMax;
bool gameOver;
std::string message;
double randTriangle(double maxVal) {
if (maxVal <= 0.0) return 0.0;
double u = static_cast<double>(rand()) / RAND_MAX;
return maxVal * (1.0 - std::sqrt(1.0 - u));
}
void enableANSI() {
#ifdef _WIN32
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD dwMode = 0;
GetConsoleMode(hOut, &dwMode);
dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(hOut, dwMode);
#endif
}
void clearScreen() {
std::cout << "\033[2J\033[H" << std::flush;
}
bool checkFailure() {
for (double p : progress) {
if (p >= 100.0) {
gameOver = true;
return true;
}
}
return false;
}
void updateMonsters(double dt) {
for (int i = 0; i < ROOM_COUNT; ++i) {
if (i == monitorIndex || collapseDaysLeft[i] > 0) continue;
double advance = randTriangle(currentSpeedMax) * dt;
progress[i] += advance;
if (progress[i] > 100.0) progress[i] = 100.0;
}
}
void shoot() {
if (bullets <= 0) {
message = "子弹已用尽!";
return;
}
int idx = monitorIndex;
double retreat = 30.0 + static_cast<double>(rand()) / RAND_MAX * 60.0;
double before = progress[idx];
progress[idx] -= retreat;
if (progress[idx] < 0.0) progress[idx] = 0.0;
// 有效伤害 = 实际减少的进度(不计算溢出部分)
double actualDamage = before - progress[idx];
collapseDamage[idx] += actualDamage;
bullets--;
// 崩塌判定
bool collapseTriggered = false;
if (collapseDaysLeft[idx] == 0 && collapseDamage[idx] >= COLLAPSE_THRESHOLD) {
progress[idx] -= 50.0;
if (progress[idx] < 0.0) progress[idx] = 0.0;
collapseDaysLeft[idx] = 2;
collapseTriggered = true;
}
// 畏缩击中计数(无论是否溢出,只要开枪就计数)
fearHits[idx]++;
bool fearTriggered = false;
if (fearHits[idx] >= FEAR_HITS_NEEDED) {
progress[idx] = 0.0;
fearHits[idx] = 0;
fearTriggered = true;
}
// 信息
char buf[200];
std::string extra;
if (collapseTriggered) extra += "【崩塌!进度-50%,停止2天】";
if (fearTriggered) extra += "【畏缩!进度清空】";
snprintf(buf, sizeof(buf), "开枪!房间 %d 后退 %.1f%%%s", idx + 1, actualDamage, extra.c_str());
message = buf;
}
void switchMonitor(int idx) {
monitorIndex = idx;
char buf[64];
std::string state;
if (collapseDaysLeft[idx] > 0)
state = " [崩塌中 " + std::to_string(collapseDaysLeft[idx]) + "天]";
snprintf(buf, sizeof(buf), "切换至房间 %d%s", idx + 1, state.c_str());
message = buf;
}
void displayHUD(steady_clock::time_point dayStart) {
auto now = steady_clock::now();
double elapsed = duration<double>(now - dayStart).count();
double remain = DAY_SECONDS - elapsed;
if (remain < 0.0) remain = 0.0;
int idx = monitorIndex;
std::string stateStr;
if (collapseDaysLeft[idx] > 0)
stateStr += " [崩塌" + std::to_string(collapseDaysLeft[idx]) + "天]";
if (fearHits[idx] > 0)
stateStr += " [畏缩" + std::to_string(fearHits[idx]) + "/5]";
std::cout << "\033[2J\033[H" << std::flush;
std::cout << "======== 第 " << day << " 天 ========\n"
<< "当前房间: " << (idx + 1) << stateStr << "\n"
<< " 进度: " << std::fixed << std::setprecision(1) << progress[idx] << "%\n"
<< " 有效累计伤害: " << std::setprecision(1) << collapseDamage[idx] << "/" << COLLAPSE_THRESHOLD << "%\n"
<< "子弹: " << bullets << "/" << MAX_BULLETS
<< " 剩余时间: " << std::setprecision(1) << remain << "s\n"
<< "怪物速度上限: " << currentSpeedMax << "%/秒\n"
<< "下次补满: 第 " << ((day / FULL_SUPPLY_DAY) * FULL_SUPPLY_DAY + FULL_SUPPLY_DAY) << " 天\n"
<< "---------------------------------\n"
<< "[0] 开枪 [1-5] 切换监控\n"
<< "信息: " << message << "\n"
<< std::flush;
message.clear();
}
void displayAllRooms() {
std::cout << "\n===== 各房间进度 =====\n";
for (int i = 0; i < ROOM_COUNT; ++i) {
std::cout << "房间 " << (i + 1) << ": "
<< std::fixed << std::setprecision(1) << progress[i] << "%";
if (collapseDaysLeft[i] > 0)
std::cout << " [崩塌" << collapseDaysLeft[i] << "天]";
if (fearHits[i] > 0)
std::cout << " [畏缩" << fearHits[i] << "/5]";
std::cout << " 累计伤害: " << collapseDamage[i] << "%\n";
}
std::cout << "======================\n";
}
void flushInput() {
while (_kbhit()) _getch();
}
void dailyUpdate() {
for (int i = 0; i < ROOM_COUNT; ++i) {
if (collapseDaysLeft[i] > 0) {
collapseDaysLeft[i]--;
if (collapseDaysLeft[i] == 0) {
collapseDamage[i] = 0.0;
}
}
}
}
public:
Game() : progress(ROOM_COUNT, 0.0), collapseDamage(ROOM_COUNT, 0.0),
collapseDaysLeft(ROOM_COUNT, 0), fearHits(ROOM_COUNT, 0),
monitorIndex(0), day(1), bullets(MAX_BULLETS), currentSpeedMax(3.0), gameOver(false) {
srand(static_cast<unsigned int>(time(nullptr)));
enableANSI();
}
void runDay() {
dailyUpdate();
if (day % FULL_SUPPLY_DAY == 0) {
bullets = MAX_BULLETS;
message = "补给日!子弹补满至 " + std::to_string(MAX_BULLETS) + " 发!";
} else {
bullets += 5;
if (bullets > MAX_BULLETS) bullets = MAX_BULLETS;
char buf[64];
snprintf(buf, sizeof(buf), "获得5发子弹(%d/%d)", bullets, MAX_BULLETS);
message = buf;
}
auto dayStart = steady_clock::now();
auto lastRender = dayStart;
while (!gameOver) {
auto now = steady_clock::now();
double elapsed = duration<double>(now - dayStart).count();
if (elapsed >= DAY_SECONDS) break;
if (duration<double>(now - lastRender).count() >= 0.15) {
double dt = duration<double>(now - lastRender).count();
updateMonsters(dt);
lastRender = now;
if (checkFailure()) return;
while (_kbhit()) {
char ch = _getch();
if (ch == '0') {
shoot();
if (checkFailure()) return;
} else if (ch >= '1' && ch <= '5') {
switchMonitor(ch - '1');
}
}
displayHUD(dayStart);
}
std::this_thread::sleep_for(milliseconds(20));
}
}
void run() {
clearScreen();
std::cout << "怪物逼近中!每天30秒,速度3%→4%→…→30%/秒\n"
<< "[0] 开枪(击退30~90%) [1-5] 切换监控\n"
<< "子弹上限20发,初始20发,每天+5,每5天补满\n"
<< "崩塌:有效累计伤害达200%触发(进度-50%,停止2天)\n"
<< "畏缩:被击中5次触发(进度清空)\n"
<< "按回车开始...";
std::cin.get();
while (!gameOver) {
runDay();
if (gameOver) break;
clearScreen();
std::cout << "=== 第 " << day << " 天结束 ===\n";
displayAllRooms();
currentSpeedMax += 1.0;
if (currentSpeedMax > MAX_SPEED) currentSpeedMax = MAX_SPEED;
std::cout << "按回车进入第 " << (day + 1) << " 天...";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get();
++day;
}
clearScreen();
std::cout << "\n===== 游戏结束 =====\n";
displayAllRooms();
std::cout << "你存活了 " << day << " 天。\n";
std::cout << "\n请关闭控制台窗口退出..." << std::endl;
while (true) {
std::this_thread::sleep_for(seconds(1));
}
}
};
int main() {
Game game;
game.run();
return 0;
}地下城世界
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <limits>
#include <set>
#include <memory>
#include <functional>
using namespace std;
// ==================== 跨平台清屏 ====================
void clearScreen() {
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}
void pauseForEnter() {
cout << "\n按回车键继续...";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.get();
}
int randomInt(int min, int max) {
return rand() % (max - min + 1) + min;
}
// ==================== 暴击计算 ====================
int applyCrit(int baseDamage, float critRate, float critMulti, float universalRate, float universalMulti, bool &isCrit) {
float finalRate = critRate + universalRate;
float finalMulti = critMulti + universalMulti;
isCrit = false;
if (finalRate > 1.0f) {
float extraMulti = finalRate - 1.0f;
finalMulti += extraMulti;
isCrit = true;
return max(1, (int)floor(baseDamage * finalMulti));
}
if ((float)rand() / RAND_MAX < finalRate) {
isCrit = true;
return max(1, (int)floor(baseDamage * finalMulti));
}
return baseDamage;
}
int applyCrit(int baseDamage, float critRate, float critMulti, float universalRate, float universalMulti) {
bool dummy;
return applyCrit(baseDamage, critRate, critMulti, universalRate, universalMulti, dummy);
}
// ==================== 状态系统 ====================
struct Status {
string name;
int remainingTurns;
int delayedDamage;
int shieldAmount;
int buffValue; // 未使用,保留扩展
};
// ==================== 角色基类 ====================
class Character {
public:
string name;
int hp, maxHp;
int stamina, maxStamina;
int mana, maxMana;
int atkPhys, defPhys;
int atkMag, defMag;
int atkSpirit, spiritStr;
int speed, dodge;
int masteryPhys, masteryMag;
float critRatePhys, critMultiPhys;
float critRateMag, critMultiMag;
float universalCritRate, universalCritMulti;
vector<Status> statusList;
Character() {
hp = maxHp = 20; stamina = maxStamina = 10; mana = maxMana = 10;
atkPhys = defPhys = 5; atkMag = defMag = 5; atkSpirit = spiritStr = 5;
speed = 3; dodge = 0;
masteryPhys = masteryMag = 0;
critRatePhys = critRateMag = 0.0f; critMultiPhys = critMultiMag = 1.5f;
universalCritRate = universalCritMulti = 0.0f;
}
virtual ~Character() {}
bool hasStatus(const string& s) const {
for (auto& st : statusList) if (st.name == s) return true;
return false;
}
void addStatus(Status s) { statusList.push_back(s); }
void removeStatus(const string& s) {
statusList.erase(remove_if(statusList.begin(), statusList.end(),
[&](Status& st) { return st.name == s; }), statusList.end());
}
void updateStatuses() {
for (auto it = statusList.begin(); it != statusList.end(); ) {
if (it->remainingTurns > 0) {
if (--(it->remainingTurns) == 0) {
// 处理临时增益到期
if (it->name == "天使之羽") {
critRatePhys -= 0.5f;
critRateMag -= 0.5f;
} else if (it->name == "恶魔契约") {
atkPhys /= 2; atkMag /= 2; atkSpirit /= 2;
defPhys /= 2; defMag /= 2;
}
it = statusList.erase(it); continue;
}
} else if (it->remainingTurns == -1) {
++it; continue;
}
++it;
}
}
int getCurrentDodge() const {
int base = dodge;
if (hasStatus("风沙术闪避")) base += 5;
return min(base, 100);
}
void takeDamage(int damage) {
if (damage <= 0) return;
if (hasStatus("不屈")) { if (hp - damage <= 0) damage = hp - 1; }
for (auto& st : statusList) {
if (st.name == "水之盾" || st.name == "盾护") {
if (st.shieldAmount >= damage) {
st.shieldAmount -= damage;
cout << " 护盾吸收了 " << damage << " 点伤害,剩余护盾 " << st.shieldAmount << "\n";
return;
} else {
damage -= st.shieldAmount;
cout << " 护盾吸收 " << st.shieldAmount << " 点伤害,被击破!\n";
st.shieldAmount = 0;
removeStatus(st.name);
break;
}
}
}
if (damage > 0) hp -= damage;
}
};
// ==================== 前向声明 ====================
class Player;
class Enemy;
// ==================== 技能库 ====================
struct SkillData {
string name; int costStamina, costMana; int price, levelReq; string description;
int type, damageType; float multiplier; int fixedDamage; float delayedMultiplier;
string specialStatus; float selfDamageRatio; bool oncePerBattle; int minSpiritStr; int buffValue; bool usePhysMastery;
};
vector<SkillData> skillLibrary = {
// 物理
{"劈斩",1,0,0,1,"物理 2.0倍",0,0,2.0f,0,0.0f,"",0.0f,false,0,0,false},
{"重击",3,0,0,1,"物理 2.5倍+5",0,0,2.5f,5,0.0f,"",0.0f,false,0,0,false},
{"二连斩",3,0,7,1,"首击2.0倍,下回合追2.0",1,0,2.0f,0,2.0f,"二连斩追击",0.0f,false,0,0,false},
{"闪击",2,0,10,1,"物理 2.0倍,下回合先手",2,0,2.0f,0,0.0f,"先手保证",0.0f,false,0,0,false},
{"舍命相搏",5,0,20,5,"物理 5.0倍,反伤20%",3,0,5.0f,0,0.0f,"",0.2f,false,0,0,false},
{"盾护",2,0,20,1,"获得5+k*体精点护盾",6,-1,0.0f,0,0.0f,"",0.0f,false,0,0,true},
// 法术
{"火球术",0,3,0,1,"法术 2.0倍伤害",5,2,2.0f,0,0.0f,"",0.0f,false,0,0,false},
{"冰晶术",0,3,30,5,"法术 (3+k)+法攻",9,2,1.0f,0,0.0f,"",0.0f,false,0,0,false},
{"水之盾",0,2,20,1,"获得5+k*法精点护盾",6,-1,0.0f,0,0.0f,"",0.0f,false,0,0,false},
{"风沙术",0,3,30,10,"闪避率+5%,持续到战斗结束",7,-1,0.0f,0,0.0f,"风沙术闪避",0.0f,false,0,5,false},
{"圣光术",0,4,40,10,"法术伤害 10+3*法攻",5,2,3.0f,10,0.0f,"",0.0f,false,0,0,false},
// 精神
{"精神冲击",0,0,30,10,"精神伤害 (己方强度/敌方强度)*精攻",4,1,1.0f,0,0.0f,"",0.0f,true,1,0,false},
{"精神爆裂",0,0,50,20,"精神伤害 (精攻+精强)/max(敌强-己强,1)",8,1,1.0f,0,0.0f,"",0.0f,true,1,0,false}
};
class Skill {
public: SkillData data; Skill(const SkillData& d) : data(d) {} virtual void execute(Character& user, Character& target) = 0; virtual ~Skill() {}
};
class PhysicalDamageSkill : public Skill { public: PhysicalDamageSkill(const SkillData& d) : Skill(d) {} void execute(Character& user, Character& target) override; };
class DelayedDamageSkill : public Skill { public: DelayedDamageSkill(const SkillData& d) : Skill(d) {} void execute(Character& user, Character& target) override; };
class StatusSkill : public Skill { public: StatusSkill(const SkillData& d) : Skill(d) {} void execute(Character& user, Character& target) override; };
class RecoilSkill : public Skill { public: RecoilSkill(const SkillData& d) : Skill(d) {} void execute(Character& user, Character& target) override; };
class SpiritSkill : public Skill { public: SpiritSkill(const SkillData& d) : Skill(d) {} void execute(Character& user, Character& target) override; };
class MagicDamageSkill : public Skill { public: MagicDamageSkill(const SkillData& d) : Skill(d) {} void execute(Character& user, Character& target) override; };
class ShieldSkill : public Skill { public: ShieldSkill(const SkillData& d) : Skill(d) {} void execute(Character& user, Character& target) override; };
class BuffDodgeSkill : public Skill { public: BuffDodgeSkill(const SkillData& d) : Skill(d) {} void execute(Character& user, Character& target) override; };
class SpiritBurstSkill : public Skill { public: SpiritBurstSkill(const SkillData& d) : Skill(d) {} void execute(Character& user, Character& target) override; };
class IceCrystalSkill : public Skill { public: IceCrystalSkill(const SkillData& d) : Skill(d) {} void execute(Character& user, Character& target) override; };
SkillData getSkillData(const string& name) { for (auto& d : skillLibrary) if (d.name == name) return d; return skillLibrary[0]; }
unique_ptr<Skill> createSkill(const string& name) {
SkillData d = getSkillData(name);
switch (d.type) {
case 0: return make_unique<PhysicalDamageSkill>(d); case 1: return make_unique<DelayedDamageSkill>(d);
case 2: return make_unique<StatusSkill>(d); case 3: return make_unique<RecoilSkill>(d);
case 4: return make_unique<SpiritSkill>(d); case 5: return make_unique<MagicDamageSkill>(d);
case 6: return make_unique<ShieldSkill>(d); case 7: return make_unique<BuffDodgeSkill>(d);
case 8: return make_unique<SpiritBurstSkill>(d); case 9: return make_unique<IceCrystalSkill>(d);
default: return nullptr;
}
}
// ==================== 职业库(含成长) ====================
struct ClassData {
string name;
int hp, stamina, mana;
int atkPhys, defPhys, atkMag, defMag, atkSpirit, spiritStr;
int speed, dodge, masteryPhys, masteryMag;
float critRatePhys, critMultiPhys, critRateMag, critMultiMag;
vector<string> initialSkills;
int hpGrowth, staminaGrowth, manaGrowth;
int atkPhysGrowth, atkMagGrowth, atkSpiritGrowth;
int defPhysGrowth, defMagGrowth;
int speedGrowth, spiritStrGrowth;
};
vector<ClassData> classLibrary = {
{"平民", 20,10,10, 5,5,5,5,5,5, 3,0,0,0, 0.0f,1.5f,0.0f,1.5f, {"劈斩","重击","火球术"}, 5,2,2, 2,2,2, 2,2, 1,2},
{"战士", 21,15,5, 7,7,2,3,3,2, 3,0,2,0, 0.05f,1.6f,0.0f,1.3f, {"劈斩","重击","盾护"}, 6,2,1, 3,1,1, 3,2, 1,1}
};
// ==================== 装备系统 ====================
enum EquipmentSlot {
SLOT_MAIN_WEAPON, SLOT_SUB_WEAPON, SLOT_ARMOR, SLOT_PANTS, SLOT_BOOTS, SLOT_HELMET,
SLOT_RING, SLOT_NECKLACE, SLOT_BRACELET, SLOT_BELT, SLOT_EARRING, SLOT_GLOVES, SLOT_COUNT
};
struct Equipment {
string name, templateName; int slot, price, level;
int bonusAtkPhys, bonusDefPhys, bonusAtkMag, bonusDefMag, bonusSpeed;
int bonusMasteryPhys, bonusMasteryMag;
float bonusCritRatePhys, bonusCritMultiPhys, bonusCritRateMag, bonusCritMultiMag;
float bonusUniversalCritRate, bonusUniversalCritMulti;
};
struct EquipmentTemplate { string name; int slot, price; function<void(Equipment&, int)> applyStats; };
vector<EquipmentTemplate> equipmentTemplates;
void initEquipmentTemplates() {
// 主装备20金
equipmentTemplates.push_back({"学徒铁剑", SLOT_MAIN_WEAPON, 20, [](Equipment& eq, int t) { eq.bonusAtkPhys = 3 + t/3; }});
equipmentTemplates.push_back({"学徒法杖", SLOT_MAIN_WEAPON, 20, [](Equipment& eq, int t) { eq.bonusAtkMag = 3 + t/3; }});
equipmentTemplates.push_back({"学徒盾牌", SLOT_SUB_WEAPON, 20, [](Equipment& eq, int t) { eq.bonusDefPhys = 3 + t/3; }});
equipmentTemplates.push_back({"学徒宝石", SLOT_SUB_WEAPON, 20, [](Equipment& eq, int t) { eq.bonusDefMag = 3 + t/3; }});
equipmentTemplates.push_back({"骑士头盔", SLOT_HELMET, 20, [](Equipment& eq, int t) { eq.bonusDefPhys = t/3; eq.bonusDefMag = t/4; }});
equipmentTemplates.push_back({"巫师帽", SLOT_HELMET, 20, [](Equipment& eq, int t) { eq.bonusDefPhys = t/4; eq.bonusDefMag = t/3; }});
equipmentTemplates.push_back({"骑士盔甲", SLOT_ARMOR, 20, [](Equipment& eq, int t) { eq.bonusDefPhys = t/3; eq.bonusAtkPhys = t/4; }});
equipmentTemplates.push_back({"巫师斗篷", SLOT_ARMOR, 20, [](Equipment& eq, int t) { eq.bonusDefMag = t/3; eq.bonusAtkMag = t/4; }});
equipmentTemplates.push_back({"骑士腿护", SLOT_PANTS, 20, [](Equipment& eq, int t) { eq.bonusDefPhys = t/4; eq.bonusAtkPhys = t/3; }});
equipmentTemplates.push_back({"巫师披风", SLOT_PANTS, 20, [](Equipment& eq, int t) { eq.bonusDefMag = t/4; eq.bonusAtkMag = t/3; }});
equipmentTemplates.push_back({"骑士战靴", SLOT_BOOTS, 20, [](Equipment& eq, int t) { eq.bonusDefPhys = t/4; eq.bonusSpeed = t/7; }});
equipmentTemplates.push_back({"巫师靴子", SLOT_BOOTS, 20, [](Equipment& eq, int t) { eq.bonusDefMag = t/4; eq.bonusSpeed = t/7; }});
// 副装备50金
equipmentTemplates.push_back({"天命之子的垂怜", SLOT_RING, 50, [](Equipment& eq, int t) { eq.bonusUniversalCritRate = 0.15f; }});
equipmentTemplates.push_back({"天命之子的爱惜", SLOT_NECKLACE, 50, [](Equipment& eq, int t) { eq.bonusUniversalCritRate = 0.05f; }});
equipmentTemplates.push_back({"天命之子的象征", SLOT_BRACELET, 50, [](Equipment& eq, int t) { eq.bonusUniversalCritMulti = 0.10f; }});
equipmentTemplates.push_back({"天命之子的尊贵", SLOT_BELT, 50, [](Equipment& eq, int t) { eq.bonusUniversalCritRate = 0.03f; eq.bonusUniversalCritMulti = 0.03f; }});
equipmentTemplates.push_back({"天命之子的憧憬", SLOT_EARRING, 50, [](Equipment& eq, int t) { eq.bonusUniversalCritMulti = 0.03f + t/15.0f; }});
equipmentTemplates.push_back({"天命之子的赠予", SLOT_GLOVES, 50, [](Equipment& eq, int t) { eq.bonusUniversalCritRate = 0.03f + t/15.0f; }});
equipmentTemplates.push_back({"战斗狂人的热血", SLOT_RING, 50, [](Equipment& eq, int t) { eq.bonusMasteryPhys = 10; eq.bonusCritRatePhys = 0.05f; }});
equipmentTemplates.push_back({"战斗狂人的技巧", SLOT_NECKLACE, 50, [](Equipment& eq, int t) { eq.bonusMasteryPhys = 15; }});
equipmentTemplates.push_back({"战斗狂人的斗气", SLOT_BRACELET, 50, [](Equipment& eq, int t) { eq.bonusCritRatePhys = 0.05f; eq.bonusCritMultiPhys = 0.10f; }});
equipmentTemplates.push_back({"战斗狂人的尊严", SLOT_BELT, 50, [](Equipment& eq, int t) { eq.bonusCritMultiPhys = 0.10f; }});
equipmentTemplates.push_back({"战斗狂人的名声", SLOT_EARRING, 50, [](Equipment& eq, int t) { eq.bonusMasteryPhys = 3 + t/10; }});
equipmentTemplates.push_back({"战斗狂人的赋予", SLOT_GLOVES, 50, [](Equipment& eq, int t) { eq.bonusMasteryPhys = t/8; }});
equipmentTemplates.push_back({"大学者的冷静", SLOT_RING, 50, [](Equipment& eq, int t) { eq.bonusMasteryMag = 10; eq.bonusCritRateMag = 0.05f; }});
equipmentTemplates.push_back({"大学者的解法", SLOT_NECKLACE, 50, [](Equipment& eq, int t) { eq.bonusMasteryMag = 15; }});
equipmentTemplates.push_back({"大学者的思维", SLOT_BRACELET, 50, [](Equipment& eq, int t) { eq.bonusCritRateMag = 0.05f; eq.bonusCritMultiMag = 0.10f; }});
equipmentTemplates.push_back({"大学者的学识", SLOT_BELT, 50, [](Equipment& eq, int t) { eq.bonusCritMultiMag = 0.10f; }});
equipmentTemplates.push_back({"大学者的才华", SLOT_EARRING, 50, [](Equipment& eq, int t) { eq.bonusMasteryMag = 3 + t/10; }});
equipmentTemplates.push_back({"大学者的给予", SLOT_GLOVES, 50, [](Equipment& eq, int t) { eq.bonusMasteryMag = t/8; }});
}
Equipment generateEquipment(const string& templateName, int level) {
for (auto& t : equipmentTemplates) {
if (t.name == templateName) {
Equipment eq;
eq.name = t.name; eq.templateName = t.name; eq.slot = t.slot; eq.price = t.price; eq.level = level;
eq.bonusAtkPhys = eq.bonusDefPhys = eq.bonusAtkMag = eq.bonusDefMag = eq.bonusSpeed = 0;
eq.bonusMasteryPhys = eq.bonusMasteryMag = 0;
eq.bonusCritRatePhys = eq.bonusCritMultiPhys = eq.bonusCritRateMag = eq.bonusCritMultiMag = 0.0f;
eq.bonusUniversalCritRate = eq.bonusUniversalCritMulti = 0.0f;
t.applyStats(eq, level);
return eq;
}
}
return Equipment();
}
// ==================== 道具库 ====================
struct ItemData { string name; int price; string description; int type; };
vector<ItemData> itemLibrary = {
{"医疗瓶",5,"恢复5+2*k血量",0}, {"体力瓶子",5,"恢复2+k体力",1}, {"法力瓶子",5,"恢复2+k法力",2},
{"补给药瓶",20,"恢复5+2*k血量,2+k体力和法力",3}, {"祝福药剂",50,"血量、法力、体力回满",4},
{"封印卷轴",30,"敌方下回合只能普攻",5}, {"天使之羽",50,"+50%暴击率 3回合",6},
{"恶魔契约",50,"全属性翻倍 2回合",7}, {"审判法槌",50,"造成真实伤害 1次",8}, {"不屈",100,"强行锁血3回合",9}
};
// ==================== 玩家类 ====================
class Player : public Character {
public:
int level, exp, gold;
vector<unique_ptr<Skill>> skills;
ClassData myClass;
set<string> usedOnceSkillsThisBattle;
unique_ptr<Equipment> equipment[SLOT_COUNT];
vector<unique_ptr<Equipment>> equipmentInventory;
int battleK, skillsUsedThisTurn, itemsUsedThisTurn, currentFloor;
map<string, int> inventory;
set<string> usedPhysSkills, usedMagSkills;
Player(const ClassData& cd) : myClass(cd), battleK(1), currentFloor(1) {
name = ""; level = 1; exp = 0; gold = 0;
maxHp = hp = cd.hp; maxStamina = stamina = cd.stamina; maxMana = mana = cd.mana;
atkPhys = cd.atkPhys; defPhys = cd.defPhys; atkMag = cd.atkMag; defMag = cd.defMag;
atkSpirit = cd.atkSpirit; spiritStr = cd.spiritStr; speed = cd.speed; dodge = cd.dodge;
masteryPhys = cd.masteryPhys; masteryMag = cd.masteryMag;
critRatePhys = cd.critRatePhys; critMultiPhys = cd.critMultiPhys;
critRateMag = cd.critRateMag; critMultiMag = cd.critMultiMag;
universalCritRate = universalCritMulti = 0.0f;
for (auto& sn : cd.initialSkills) skills.push_back(createSkill(sn));
skillsUsedThisTurn = itemsUsedThisTurn = 0;
}
// 禁止拷贝,允许移动
Player(const Player&) = delete;
Player& operator=(const Player&) = delete;
Player(Player&& other) noexcept : Character(other), myClass(other.myClass) {
level = other.level; exp = other.exp; gold = other.gold;
skills = move(other.skills);
for (int i = 0; i < SLOT_COUNT; ++i) equipment[i] = move(other.equipment[i]);
equipmentInventory = move(other.equipmentInventory);
inventory = move(other.inventory);
battleK = other.battleK; currentFloor = other.currentFloor;
usedOnceSkillsThisBattle = move(other.usedOnceSkillsThisBattle);
usedPhysSkills = move(other.usedPhysSkills);
usedMagSkills = move(other.usedMagSkills);
}
Player& operator=(Player&& other) noexcept {
if (this != &other) {
Character::operator=(other);
level = other.level; exp = other.exp; gold = other.gold;
skills = move(other.skills);
for (int i = 0; i < SLOT_COUNT; ++i) equipment[i] = move(other.equipment[i]);
equipmentInventory = move(other.equipmentInventory);
inventory = move(other.inventory);
battleK = other.battleK; currentFloor = other.currentFloor;
usedOnceSkillsThisBattle = move(other.usedOnceSkillsThisBattle);
usedPhysSkills = move(other.usedPhysSkills);
usedMagSkills = move(other.usedMagSkills);
}
return *this;
}
void resetOncePerBattle() { usedOnceSkillsThisBattle.clear(); usedPhysSkills.clear(); usedMagSkills.clear(); }
void resetTurnActions() { skillsUsedThisTurn = itemsUsedThisTurn = 0; }
void resetBaseStats() {
const ClassData& cd = myClass;
maxHp = cd.hp; maxStamina = cd.stamina; maxMana = cd.mana;
atkPhys = cd.atkPhys; defPhys = cd.defPhys; atkMag = cd.atkMag; defMag = cd.defMag;
atkSpirit = cd.atkSpirit; spiritStr = cd.spiritStr; speed = cd.speed; dodge = cd.dodge;
masteryPhys = cd.masteryPhys; masteryMag = cd.masteryMag;
critRatePhys = cd.critRatePhys; critMultiPhys = cd.critMultiPhys;
critRateMag = cd.critRateMag; critMultiMag = cd.critMultiMag;
universalCritRate = universalCritMulti = 0.0f;
for (int i = 1; i < level; ++i) {
maxHp += cd.hpGrowth; maxStamina += cd.staminaGrowth; maxMana += cd.manaGrowth;
atkPhys += cd.atkPhysGrowth; atkMag += cd.atkMagGrowth; atkSpirit += cd.atkSpiritGrowth;
defPhys += cd.defPhysGrowth; defMag += cd.defMagGrowth;
speed += cd.speedGrowth; spiritStr += cd.spiritStrGrowth;
}
hp = maxHp; stamina = maxStamina; mana = maxMana;
}
void applyEquipment(Equipment* eq) {
if (!eq) return;
atkPhys += eq->bonusAtkPhys; defPhys += eq->bonusDefPhys; atkMag += eq->bonusAtkMag; defMag += eq->bonusDefMag;
speed += eq->bonusSpeed; masteryPhys += eq->bonusMasteryPhys; masteryMag += eq->bonusMasteryMag;
critRatePhys += eq->bonusCritRatePhys; critMultiPhys += eq->bonusCritMultiPhys;
critRateMag += eq->bonusCritRateMag; critMultiMag += eq->bonusCritMultiMag;
universalCritRate += eq->bonusUniversalCritRate; universalCritMulti += eq->bonusUniversalCritMulti;
}
void removeEquipment(Equipment* eq) {
if (!eq) return;
atkPhys -= eq->bonusAtkPhys; defPhys -= eq->bonusDefPhys; atkMag -= eq->bonusAtkMag; defMag -= eq->bonusDefMag;
speed -= eq->bonusSpeed; masteryPhys -= eq->bonusMasteryPhys; masteryMag -= eq->bonusMasteryMag;
critRatePhys -= eq->bonusCritRatePhys; critMultiPhys -= eq->bonusCritMultiPhys;
critRateMag -= eq->bonusCritRateMag; critMultiMag -= eq->bonusCritMultiMag;
universalCritRate -= eq->bonusUniversalCritRate; universalCritMulti -= eq->bonusUniversalCritMulti;
}
void equipItem(unique_ptr<Equipment> eq, int slot) {
if (slot < 0 || slot >= SLOT_COUNT || !eq) return;
if (equipment[slot]) {
removeEquipment(equipment[slot].get());
equipmentInventory.push_back(move(equipment[slot]));
}
applyEquipment(eq.get());
equipment[slot] = move(eq);
}
void equipFromInventory(int invIndex) {
if (invIndex < 0 || invIndex >= (int)equipmentInventory.size()) return;
unique_ptr<Equipment> eq = move(equipmentInventory[invIndex]);
equipmentInventory.erase(equipmentInventory.begin() + invIndex);
int slot = eq->slot;
if (equipment[slot]) {
removeEquipment(equipment[slot].get());
equipmentInventory.push_back(move(equipment[slot]));
}
applyEquipment(eq.get());
equipment[slot] = move(eq);
}
void unequipSlot(int slot) {
if (slot < 0 || slot >= SLOT_COUNT || !equipment[slot]) return;
removeEquipment(equipment[slot].get());
equipmentInventory.push_back(move(equipment[slot]));
}
int expToLevel(int lvl) {
if (lvl <= 1) return 0;
int total = 0;
for (int i = 2; i <= lvl; ++i) {
if (i <= 5) total += 5; else if (i <= 20) total += 10; else if (i <= 50) total += 30; else total += 50;
}
return total;
}
int expForNextLevel() { return expToLevel(level+1) - expToLevel(level); }
void gainExp(int amount) {
exp += amount;
while (level < 100 && exp >= expToLevel(level+1)) levelUp();
}
void levelUp() {
level++;
maxHp += myClass.hpGrowth; hp += 2; if (hp > maxHp) hp = maxHp;
maxStamina += myClass.staminaGrowth; maxMana += myClass.manaGrowth;
atkPhys += myClass.atkPhysGrowth; atkMag += myClass.atkMagGrowth; atkSpirit += myClass.atkSpiritGrowth;
defPhys += myClass.defPhysGrowth; defMag += myClass.defMagGrowth;
speed += myClass.speedGrowth; spiritStr += myClass.spiritStrGrowth;
clearScreen(); cout << " *** 升级!当前等级 " << level << " ***\n";
}
bool learnSkill(unique_ptr<Skill> skill) {
if (level < skill->data.levelReq) { cout << "等级不足!\n"; return false; }
if (gold < skill->data.price) { cout << "金币不足!\n"; return false; }
gold -= skill->data.price;
skills.push_back(move(skill));
cout << "学会新技能:" << skills.back()->data.name << "!\n";
pauseForEnter();
return true;
}
bool hasSkill(const string& name) const {
for (auto& s : skills) if (s->data.name == name) return true;
return false;
}
void saveToFile(const string& filename) {
ofstream out(filename, ios::binary);
if (!out) { cout << "存档失败!\n"; return; }
out.write((char*)&level, sizeof(level));
out.write((char*)&exp, sizeof(exp));
out.write((char*)&gold, sizeof(gold));
size_t len = myClass.name.size(); out.write((char*)&len, sizeof(len)); out.write(myClass.name.c_str(), len);
size_t skillCount = skills.size(); out.write((char*)&skillCount, sizeof(skillCount));
for (auto& s : skills) {
len = s->data.name.size(); out.write((char*)&len, sizeof(len)); out.write(s->data.name.c_str(), len);
}
for (int i = 0; i < SLOT_COUNT; ++i) {
if (equipment[i]) {
out.write((char*)&i, sizeof(i)); out.write((char*)&equipment[i]->level, sizeof(equipment[i]->level));
len = equipment[i]->templateName.size(); out.write((char*)&len, sizeof(len)); out.write(equipment[i]->templateName.c_str(), len);
}
}
int endSlot = -1; out.write((char*)&endSlot, sizeof(endSlot));
size_t invCount = equipmentInventory.size(); out.write((char*)&invCount, sizeof(invCount));
for (auto& e : equipmentInventory) {
out.write((char*)&e->level, sizeof(e->level));
len = e->templateName.size(); out.write((char*)&len, sizeof(len)); out.write(e->templateName.c_str(), len);
}
size_t itemCount = inventory.size(); out.write((char*)&itemCount, sizeof(itemCount));
for (auto& it : inventory) {
len = it.first.size(); out.write((char*)&len, sizeof(len)); out.write(it.first.c_str(), len);
out.write((char*)&it.second, sizeof(it.second));
}
out.write((char*)¤tFloor, sizeof(currentFloor));
out.close();
}
static Player loadFromFile(const string& filename) {
ifstream in(filename, ios::binary);
if (!in) { cout << "读档失败,创建新角色。\n"; return createCharacter(); }
int level, exp, gold, currentFloor;
in.read((char*)&level, sizeof(level));
in.read((char*)&exp, sizeof(exp));
in.read((char*)&gold, sizeof(gold));
size_t len; in.read((char*)&len, sizeof(len));
char* buffer = new char[len+1]; in.read(buffer, len); buffer[len]='\0';
string className(buffer); delete[] buffer;
ClassData chosenClass = classLibrary[0];
for (auto& cd : classLibrary) if (cd.name == className) { chosenClass = cd; break; }
Player p(chosenClass);
p.level = level; p.exp = exp; p.gold = gold;
p.resetBaseStats();
size_t skillCount; in.read((char*)&skillCount, sizeof(skillCount));
for (size_t i = 0; i < skillCount; ++i) {
in.read((char*)&len, sizeof(len)); buffer = new char[len+1]; in.read(buffer, len); buffer[len]='\0';
string skillName(buffer); delete[] buffer;
p.skills.push_back(createSkill(skillName));
}
while (true) {
int slot; in.read((char*)&slot, sizeof(slot)); if (slot == -1) break;
int lv; in.read((char*)&lv, sizeof(lv));
in.read((char*)&len, sizeof(len)); buffer = new char[len+1]; in.read(buffer, len); buffer[len]='\0';
string tplName(buffer); delete[] buffer;
auto eq = make_unique<Equipment>(generateEquipment(tplName, lv));
p.equipItem(move(eq), slot);
}
size_t invCount; in.read((char*)&invCount, sizeof(invCount));
for (size_t i = 0; i < invCount; ++i) {
int lv; in.read((char*)&lv, sizeof(lv));
in.read((char*)&len, sizeof(len)); buffer = new char[len+1]; in.read(buffer, len); buffer[len]='\0';
string tplName(buffer); delete[] buffer;
p.equipmentInventory.push_back(make_unique<Equipment>(generateEquipment(tplName, lv)));
}
size_t itemCount; in.read((char*)&itemCount, sizeof(itemCount));
for (size_t i = 0; i < itemCount; ++i) {
in.read((char*)&len, sizeof(len)); buffer = new char[len+1]; in.read(buffer, len); buffer[len]='\0';
string itemName(buffer); delete[] buffer;
int qty; in.read((char*)&qty, sizeof(qty));
p.inventory[itemName] = qty;
}
in.read((char*)¤tFloor, sizeof(currentFloor));
p.currentFloor = currentFloor;
in.close();
return p;
}
static Player createCharacter();
};
// ==================== 怪物库(新数值) ====================
struct MonsterTemplate {
string name;
double baseHp, hpPerK;
double atkPhysBase, atkPhysPerK;
double atkMagBase, atkMagPerK;
double defPhysBase, defPhysPerK;
double defMagBase, defMagPerK;
double speedBase, speedPerK;
double dodgeDivisor;
vector<string> skills;
};
vector<MonsterTemplate> monsterLibrary = {
{"小哥布林", 5, 1.5, 3,1, 2,1, 3,1, 2,1, 1,1, 10.0, {}},
{"哥布林", 5, 2, 5,1.5,2,1, 3,1.5,2,1, 1,1, 10.0, {"劈斩"}},
{"大哥布林", 6, 2.5, 3,2, 2,1, 5,1.5,2,2, 2,1, 9.0, {"劈斩","闪击"}},
{"哥布林酋长", 7, 3, 3,2.5,2,1, 5,2, 6,2, 3,1, 7.0, {"劈斩","闪击","舍命相搏"}},
{"哥布林祭司", 10,3.5, 3,3, 2,4, 5,3, 6,4, 3,2.0/3.0, 10.0, {"劈斩","火球术","冰晶术","水之盾"}}
};
class Enemy : public Character {
public:
int expDrop, goldDrop;
string enemyType;
vector<unique_ptr<Skill>> skills;
void takeAction(Player& player) {
if (hasStatus("封印")) {
cout << " " << name << " 被封印,只能进行普通攻击!\n";
if (rand() % 100 < player.getCurrentDodge()) {
cout << " 攻击被闪避!\n";
return;
}
int base = max(1, atkPhys - player.defPhys);
bool crit; int dmg = applyCrit(base, critRatePhys, critMultiPhys, 0, 0, crit);
player.takeDamage(dmg);
cout << " " << name << " 攻击造成 " << dmg << " 点伤害。";
if (crit) cout << "(暴击!)";
cout << "\n";
return;
}
if (skills.empty() || rand() % 100 < 40) {
if (rand() % 100 < player.getCurrentDodge()) {
cout << " " << name << " 的攻击被闪避!\n";
return;
}
int base = max(1, atkPhys - player.defPhys);
bool crit; int dmg = applyCrit(base, critRatePhys, critMultiPhys, 0, 0, crit);
player.takeDamage(dmg);
cout << " " << name << " 攻击造成 " << dmg << " 点伤害。";
if (crit) cout << "(暴击!)";
cout << "\n";
} else {
int idx = rand() % skills.size();
cout << " " << name << " 使用了 " << skills[idx]->data.name << "!\n";
skills[idx]->execute(*this, player);
}
}
};
int getK(int currentFloor) { return (currentFloor - 1) / 3 + 1; }
Enemy createEnemy(const string& type, int currentFloor) {
int k = getK(currentFloor);
const MonsterTemplate* tmpl = nullptr;
for (auto& t : monsterLibrary) if (t.name == type) { tmpl = &t; break; }
Enemy e;
e.name = tmpl->name; e.enemyType = tmpl->name;
e.maxStamina = e.stamina = 9999; e.maxMana = e.mana = 9999;
e.atkSpirit = e.spiritStr = 1; e.masteryPhys = e.masteryMag = 0;
e.critRatePhys = e.critRateMag = 0.0f; e.critMultiPhys = e.critMultiMag = 1.5f;
e.maxHp = tmpl->baseHp + (int)(k * tmpl->hpPerK);
e.atkPhys = tmpl->atkPhysBase + k * tmpl->atkPhysPerK;
e.atkMag = tmpl->atkMagBase + k * tmpl->atkMagPerK;
e.defPhys = tmpl->defPhysBase + (int)(k * tmpl->defPhysPerK);
e.defMag = tmpl->defMagBase + (int)(k * tmpl->defMagPerK);
e.speed = tmpl->speedBase + (int)(k * tmpl->speedPerK);
e.dodge = min((int)(k / tmpl->dodgeDivisor), 10);
if (type == "哥布林祭司") {
e.masteryMag = 20 + k;
e.spiritStr = 2;
e.critRateMag = 0.05f;
e.critMultiMag = 1.6f;
}
for (const string& sn : tmpl->skills) {
SkillData sd = getSkillData(sn);
if (k >= sd.levelReq) e.skills.push_back(createSkill(sn));
}
if (type == "小哥布林" || type == "哥布林") { e.expDrop = randomInt(1, 3); e.goldDrop = randomInt(1, 2); }
else if (type == "大哥布林") { e.expDrop = randomInt(2, 5); e.goldDrop = randomInt(3, 5); }
else if (type == "哥布林酋长") { e.expDrop = randomInt(3, 10); e.goldDrop = randomInt(5, 7); }
else { e.expDrop = randomInt(5, 15); e.goldDrop = randomInt(10, 15); }
e.hp = e.maxHp;
return e;
}
Enemy spawnEnemy(int currentFloor) {
int roll = rand() % 20;
if (roll < 10) return createEnemy("小哥布林", currentFloor);
else if (roll < 16) return createEnemy("哥布林", currentFloor);
else if (roll < 19) return createEnemy("大哥布林", currentFloor);
else return createEnemy("哥布林祭司", currentFloor);
}
// ==================== 技能执行 ====================
void PhysicalDamageSkill::execute(Character& user, Character& target) {
if (rand() % 100 < target.getCurrentDodge()) { cout << " 攻击被闪避!\n"; return; }
float raw = user.atkPhys * data.multiplier + data.fixedDamage - target.defPhys;
int baseDmg = max(1, (int)floor(raw));
bool crit; int dmg = applyCrit(baseDmg, user.critRatePhys, user.critMultiPhys, user.universalCritRate, user.universalCritMulti, crit);
Player* p = dynamic_cast<Player*>(&user);
if (p) {
if (p->usedPhysSkills.find(data.name) == p->usedPhysSkills.end()) {
float bonus = 1.0f + p->masteryPhys / 100.0f;
dmg = (int)(dmg * bonus);
cout << " [精通加成:" << p->masteryPhys << "%]";
}
p->usedPhysSkills.insert(data.name);
}
target.takeDamage(dmg);
cout << " 造成 " << dmg << " 点伤害。";
if (crit) cout << "(暴击!)";
cout << "\n";
}
void DelayedDamageSkill::execute(Character& user, Character& target) {
if (rand() % 100 < target.getCurrentDodge()) { cout << " 第一击被闪避!\n"; return; }
float raw = user.atkPhys * data.multiplier - target.defPhys;
int baseDmg = max(1, (int)floor(raw));
bool crit; int dmg = applyCrit(baseDmg, user.critRatePhys, user.critMultiPhys, user.universalCritRate, user.universalCritMulti, crit);
Player* p = dynamic_cast<Player*>(&user);
if (p) {
if (p->usedPhysSkills.find(data.name) == p->usedPhysSkills.end()) {
float bonus = 1.0f + p->masteryPhys / 100.0f;
dmg = (int)(dmg * bonus);
cout << " [精通加成:" << p->masteryPhys << "%]";
}
p->usedPhysSkills.insert(data.name);
}
target.takeDamage(dmg);
cout << " 第一击造成 " << dmg << " 点伤害。";
if (crit) cout << "(暴击!)";
cout << ",下回合将自动追击。\n";
int followRaw = max(1, (int)floor(user.atkPhys * data.delayedMultiplier - target.defPhys));
bool followCrit; int followDmg = applyCrit(followRaw, user.critRatePhys, user.critMultiPhys, user.universalCritRate, user.universalCritMulti, followCrit);
Status delay; delay.name = data.specialStatus; delay.remainingTurns = 2; delay.delayedDamage = followDmg;
target.addStatus(delay);
}
void StatusSkill::execute(Character& user, Character& target) {
if (rand() % 100 < target.getCurrentDodge()) { cout << " 攻击被闪避!\n"; return; }
float raw = user.atkPhys * data.multiplier - target.defPhys;
int baseDmg = max(1, (int)floor(raw));
bool crit; int dmg = applyCrit(baseDmg, user.critRatePhys, user.critMultiPhys, user.universalCritRate, user.universalCritMulti, crit);
Player* p = dynamic_cast<Player*>(&user);
if (p) {
if (p->usedPhysSkills.find(data.name) == p->usedPhysSkills.end()) {
float bonus = 1.0f + p->masteryPhys / 100.0f;
dmg = (int)(dmg * bonus);
cout << " [精通加成:" << p->masteryPhys << "%]";
}
p->usedPhysSkills.insert(data.name);
}
target.takeDamage(dmg);
cout << " 造成 " << dmg << " 点伤害。";
if (crit) cout << "(暴击!)";
if (data.specialStatus == "先手保证") {
Status fs; fs.name = "先手保证"; fs.remainingTurns = 1; user.addStatus(fs);
cout << " 下回合将先手!";
}
cout << "\n";
}
void RecoilSkill::execute(Character& user, Character& target) {
if (rand() % 100 < target.getCurrentDodge()) { cout << " 攻击被闪避!\n"; return; }
float raw = user.atkPhys * data.multiplier - target.defPhys;
int baseDmg = max(1, (int)floor(raw));
bool crit; int dmg = applyCrit(baseDmg, user.critRatePhys, user.critMultiPhys, user.universalCritRate, user.universalCritMulti, crit);
Player* p = dynamic_cast<Player*>(&user);
if (p) {
if (p->usedPhysSkills.find(data.name) == p->usedPhysSkills.end()) {
float bonus = 1.0f + p->masteryPhys / 100.0f;
dmg = (int)(dmg * bonus);
cout << " [精通加成:" << p->masteryPhys << "%]";
}
p->usedPhysSkills.insert(data.name);
}
target.takeDamage(dmg);
int recoil = max(1, (int)floor(dmg * data.selfDamageRatio));
user.takeDamage(recoil);
cout << " 造成 " << dmg << " 点伤害,自身受到反伤 " << recoil << " 点。";
if (crit) cout << "(暴击!)";
cout << "\n";
}
void MagicDamageSkill::execute(Character& user, Character& target) {
if (rand() % 100 < target.getCurrentDodge()) { cout << " 法术攻击被闪避!\n"; return; }
float raw = user.atkMag * data.multiplier + data.fixedDamage - target.defMag;
int baseDmg = max(1, (int)floor(raw));
bool crit; int dmg = applyCrit(baseDmg, user.critRateMag, user.critMultiMag, user.universalCritRate, user.universalCritMulti, crit);
Player* p = dynamic_cast<Player*>(&user);
if (p) {
if (p->usedMagSkills.find(data.name) == p->usedMagSkills.end()) {
float bonus = 1.0f + p->masteryMag / 100.0f;
dmg = (int)(dmg * bonus);
cout << " [精通加成:" << p->masteryMag << "%]";
}
p->usedMagSkills.insert(data.name);
}
target.takeDamage(dmg);
cout << " 造成 " << dmg << " 点法术伤害。";
if (crit) cout << "(暴击!)";
cout << "\n";
}
void IceCrystalSkill::execute(Character& user, Character& target) {
if (rand() % 100 < target.getCurrentDodge()) { cout << " 法术攻击被闪避!\n"; return; }
Player* p = dynamic_cast<Player*>(&user);
int k = p ? p->battleK : 1;
float raw = (3 + k) + user.atkMag * data.multiplier - target.defMag;
int baseDmg = max(1, (int)floor(raw));
bool crit; int dmg = applyCrit(baseDmg, user.critRateMag, user.critMultiMag, user.universalCritRate, user.universalCritMulti, crit);
if (p) {
if (p->usedMagSkills.find(data.name) == p->usedMagSkills.end()) {
float bonus = 1.0f + p->masteryMag / 100.0f;
dmg = (int)(dmg * bonus);
cout << " [精通加成:" << p->masteryMag << "%]";
}
p->usedMagSkills.insert(data.name);
}
target.takeDamage(dmg);
cout << " 造成 " << dmg << " 点法术伤害。";
if (crit) cout << "(暴击!)";
cout << "\n";
}
void SpiritSkill::execute(Character& user, Character& target) {
if (rand() % 100 < target.getCurrentDodge()) { cout << " 精神攻击被闪避!\n"; return; }
int enemyStr = target.spiritStr; if (enemyStr < 1) enemyStr = 1;
float ratio = (float)user.spiritStr / enemyStr;
float raw = ratio * user.atkSpirit * data.multiplier;
int dmg = max(1, (int)floor(raw));
target.takeDamage(dmg);
cout << " 精神冲击造成 " << dmg << " 点伤害。\n";
}
void SpiritBurstSkill::execute(Character& user, Character& target) {
if (rand() % 100 < target.getCurrentDodge()) { cout << " 精神攻击被闪避!\n"; return; }
int diff = target.spiritStr - user.spiritStr; if (diff < 1) diff = 1;
float raw = (float)(user.atkSpirit + user.spiritStr) / diff;
int dmg = max(1, (int)floor(raw));
target.takeDamage(dmg);
cout << " 精神爆裂造成 " << dmg << " 点伤害。\n";
}
void ShieldSkill::execute(Character& user, Character& target) {
Player* p = dynamic_cast<Player*>(&user);
int shieldAmount = 5;
if (p) {
if (data.usePhysMastery) shieldAmount += p->battleK * p->masteryPhys;
else shieldAmount += p->battleK * p->masteryMag;
}
string statusName = data.usePhysMastery ? "盾护" : "水之盾";
if (user.hasStatus(statusName)) user.removeStatus(statusName);
Status s; s.name = statusName; s.remainingTurns = -1; s.shieldAmount = shieldAmount;
user.addStatus(s);
cout << " 获得 " << shieldAmount << " 点护盾。\n";
}
void BuffDodgeSkill::execute(Character& user, Character& target) {
if (user.hasStatus("风沙术闪避")) { cout << " 已经处于风沙术状态。\n"; return; }
Status s; s.name = "风沙术闪避"; s.remainingTurns = -1;
user.addStatus(s);
cout << " 闪避率提升5%,持续到战斗结束。\n";
}
// ==================== 显示函数 ====================
void showPlayerStatus(Player& p) {
clearScreen();
int currentExp = p.exp - p.expToLevel(p.level); int needed = p.expForNextLevel();
cout << "\n=== 玩家状态 ===\n";
cout << "职业:" << p.myClass.name << " 等级:" << p.level << " 经验:" << currentExp << "/" << needed << " 金币:" << p.gold << "\n";
cout << "生命:" << p.hp << "/" << p.maxHp << " 体力:" << p.stamina << "/" << p.maxStamina << " 法力:" << p.mana << "/" << p.maxMana << "\n";
cout << "物攻:" << p.atkPhys << " 法攻:" << p.atkMag << " 精攻:" << p.atkSpirit << "\n";
cout << "物防:" << p.defPhys << " 法防:" << p.defMag << " 速度:" << p.speed << " 闪避:" << p.getCurrentDodge() << "%\n";
cout << "精神强度:" << p.spiritStr << " 体精:" << p.masteryPhys << " 法精:" << p.masteryMag << "\n";
cout << "物暴率:" << p.critRatePhys*100 << "% 物暴倍率:" << p.critMultiPhys*100 << "%\n";
cout << "法暴率:" << p.critRateMag*100 << "% 法暴倍率:" << p.critMultiMag*100 << "%\n";
cout << "万能暴率:" << p.universalCritRate*100 << "% 万能暴伤:" << p.universalCritMulti*100 << "%\n";
cout << "当前层数:" << p.currentFloor << "\n";
cout << "已学技能: "; for (auto& s : p.skills) cout << s->data.name << " ";
auto eqName = [&](int i) -> string { return p.equipment[i] ? p.equipment[i]->name + " Lv." + to_string(p.equipment[i]->level) : "无"; };
cout << "\n--- 已装备 ---\n";
for (int i = 0; i < 6; ++i) cout << i+1 << ". [" << eqName(i) << "] ";
cout << "\n";
for (int i = 6; i < 12; ++i) cout << i+1 << ". [" << eqName(i) << "] ";
cout << "\n--- 背包 ---\n";
for (auto& it : p.inventory) if (it.second > 0) cout << it.first << " x" << it.second << "\n";
cout << "装备背包: " << p.equipmentInventory.size() << "件\n";
cout << "================\n"; pauseForEnter();
}
void showEnemyStatus(Enemy& e) {
clearScreen();
cout << "\n--- 敌人: " << e.name << " ---\n";
cout << "生命:" << e.hp << "/" << e.maxHp << " 速度:" << e.speed << " 闪避:" << e.getCurrentDodge() << "%\n";
cout << "物攻:" << e.atkPhys << " 物防:" << e.defPhys << " 法攻:" << e.atkMag << " 法防:" << e.defMag << "\n";
cout << "精神强度:" << e.spiritStr << "\n"; pauseForEnter();
}
void processDelayedAttack(Player& player, Enemy& enemy) {
if (enemy.hasStatus("二连斩追击")) {
int dmg = 0; for (auto& st : enemy.statusList) if (st.name == "二连斩追击") { dmg = st.delayedDamage; break; }
if (rand() % 100 < enemy.getCurrentDodge()) { cout << " 二连斩追击被闪避!\n"; }
else { enemy.takeDamage(dmg); cout << " 二连斩追击造成 " << dmg << " 点伤害。\n"; }
enemy.removeStatus("二连斩追击");
}
if (player.hasStatus("二连斩追击")) {
int dmg = 0; for (auto& st : player.statusList) if (st.name == "二连斩追击") { dmg = st.delayedDamage; break; }
if (rand() % 100 < player.getCurrentDodge()) { cout << " 敌人的二连斩追击被你闪避!\n"; }
else { player.takeDamage(dmg); cout << " 敌人的二连斩追击对你造成 " << dmg << " 点伤害。\n"; }
player.removeStatus("二连斩追击");
}
}
void addEquipmentToInventory(Player& player, const string& templateName) {
Equipment eq = generateEquipment(templateName, player.level);
player.equipmentInventory.push_back(make_unique<Equipment>(eq));
cout << " 获得装备:" << eq.name << " Lv." << eq.level << "(已放入背包)\n";
}
void handleEquipmentDrop(Player& player, const string& enemyType, int currentFloor) {
int rollCount = 0;
if (enemyType == "小哥布林" || enemyType == "哥布林") { rollCount = 0; }
else if (enemyType == "大哥布林") { if (rand() % 100 < 10) rollCount = 1; }
else if (enemyType == "哥布林酋长") { int r = rand() % 100; if (r < 50) rollCount = 1; else if (r < 60) rollCount = 2; }
else if (enemyType == "哥布林祭司") { int r = rand() % 100; if (r < 100) rollCount = 1; else if (r < 50) rollCount = 2; else if (r < 10) rollCount = 3; }
for (int i = 0; i < rollCount; ++i) {
bool mainEquip = (rand() % 100 < 75);
string tplName;
if (mainEquip) {
vector<EquipmentTemplate*> mains;
for (auto& t : equipmentTemplates) if (t.price == 20) mains.push_back(&t);
tplName = mains[rand() % mains.size()]->name;
} else {
vector<EquipmentTemplate*> subs;
for (auto& t : equipmentTemplates) if (t.price == 50) subs.push_back(&t);
tplName = subs[rand() % subs.size()]->name;
}
addEquipmentToInventory(player, tplName);
}
}
void showEquipmentPanel(Player& p) {
while (true) {
clearScreen();
cout << "====== 装备界面 ======\n";
cout << "--- 已装备 ---\n";
for (int i = 0; i < SLOT_COUNT; ++i) {
cout << i+1 << ". [" << (p.equipment[i] ? p.equipment[i]->name + " Lv." + to_string(p.equipment[i]->level) : "空") << "]";
if (p.equipment[i]) {
Equipment* eq = p.equipment[i].get();
if (eq->bonusAtkPhys) cout << " 物攻+" << eq->bonusAtkPhys;
if (eq->bonusAtkMag) cout << " 法攻+" << eq->bonusAtkMag;
if (eq->bonusDefPhys) cout << " 物防+" << eq->bonusDefPhys;
if (eq->bonusDefMag) cout << " 法防+" << eq->bonusDefMag;
if (eq->bonusSpeed) cout << " 速度+" << eq->bonusSpeed;
if (eq->bonusMasteryPhys) cout << " 体精+" << eq->bonusMasteryPhys;
if (eq->bonusMasteryMag) cout << " 法精+" << eq->bonusMasteryMag;
if (eq->bonusUniversalCritRate) cout << " 万暴率+" << eq->bonusUniversalCritRate*100 << "%";
if (eq->bonusUniversalCritMulti) cout << " 万暴伤+" << eq->bonusUniversalCritMulti*100 << "%";
}
cout << "\n";
}
cout << "\n--- 背包中 ---\n";
for (size_t i = 0; i < p.equipmentInventory.size(); ++i) {
Equipment* eq = p.equipmentInventory[i].get();
cout << i+1 << ". " << eq->name << " Lv." << eq->level;
if (eq->bonusAtkPhys) cout << " 物攻+" << eq->bonusAtkPhys;
if (eq->bonusAtkMag) cout << " 法攻+" << eq->bonusAtkMag;
if (eq->bonusDefPhys) cout << " 物防+" << eq->bonusDefPhys;
if (eq->bonusDefMag) cout << " 法防+" << eq->bonusDefMag;
if (eq->bonusSpeed) cout << " 速度+" << eq->bonusSpeed;
if (eq->bonusMasteryPhys) cout << " 体精+" << eq->bonusMasteryPhys;
if (eq->bonusMasteryMag) cout << " 法精+" << eq->bonusMasteryMag;
if (eq->bonusUniversalCritRate) cout << " 万暴率+" << eq->bonusUniversalCritRate*100 << "%";
if (eq->bonusUniversalCritMulti) cout << " 万暴伤+" << eq->bonusUniversalCritMulti*100 << "%";
cout << "\n";
}
cout << "\n操作:1-12 卸下装备,B+编号 装备背包物品,0 返回\n选择: ";
string cmd; cin >> cmd;
if (cmd == "0") break;
if (cmd.length() == 1 && cmd[0] >= '1' && cmd[0] <= '9') {
int slot = cmd[0] - '1'; p.unequipSlot(slot);
} else if (cmd.length() == 2 && cmd[0] >= '1' && cmd[0] <= '9') {
int slot = stoi(cmd) - 1; if (slot >= 0 && slot < SLOT_COUNT) p.unequipSlot(slot);
} else if (cmd[0] == 'B' || cmd[0] == 'b') {
string numStr = cmd.substr(1);
if (!numStr.empty()) { int idx = stoi(numStr) - 1; if (idx >= 0 && idx < (int)p.equipmentInventory.size()) p.equipFromInventory(idx); }
}
}
}
// ==================== 战斗 ====================
bool battle(Player& player, int currentFloor) {
int k = getK(currentFloor); player.battleK = k;
Enemy enemy = spawnEnemy(currentFloor);
player.resetOncePerBattle();
clearScreen(); cout << "\n你遇到了 " << enemy.name << " (区域 Lv." << k << ")!\n"; showEnemyStatus(enemy);
bool playerFirst = (player.speed >= enemy.speed);
if (player.hasStatus("先手保证")) { playerFirst = true; player.removeStatus("先手保证"); cout << "(先手保证效果发动!)\n"; }
while (player.hp > 0 && enemy.hp > 0) {
player.updateStatuses(); enemy.updateStatuses();
processDelayedAttack(player, enemy);
if (enemy.hp <= 0) break;
auto playerTurn = [&]() {
player.resetTurnActions();
bool turnEnd = false;
while (!turnEnd && player.hp > 0 && enemy.hp > 0) {
clearScreen();
cout << "\n你的回合 HP:" << player.hp << "/" << player.maxHp << " SP:" << player.stamina << " MP:" << player.mana << "\n";
cout << "基础[攻/冥/休][J] 技能[A] 道具[B] 观察敌人[E] 观察自己[C] 结束回合[L]\n";
cout << "选择: ";
char cmd; cin >> cmd; cmd = toupper(cmd);
if (cmd == 'J') {
cout << " 1.攻击 2.冥想 3.休息 0.返回\n"; int sub; cin >> sub;
if (sub == 1) {
if (rand() % 100 < enemy.getCurrentDodge()) cout << " 攻击被闪避!\n";
else {
int base = max(1, player.atkPhys - enemy.defPhys);
bool crit; int dmg = applyCrit(base, player.critRatePhys, player.critMultiPhys, player.universalCritRate, player.universalCritMulti, crit);
enemy.takeDamage(dmg);
cout << " 普通攻击造成 " << dmg << " 点伤害。";
if (crit) cout << "(暴击!)";
cout << "\n";
}
turnEnd = true;
} else if (sub == 2) { int rec = min(5, player.maxMana - player.mana); player.mana += rec; cout << " 冥想恢复 " << rec << " 法力。\n"; turnEnd = true; }
else if (sub == 3) { int rec = min(5, player.maxStamina - player.stamina); player.stamina += rec; cout << " 休息恢复 " << rec << " 体力。\n"; turnEnd = true; }
} else if (cmd == 'A') {
if (player.skillsUsedThisTurn >= 1) { cout << " 本回合已经使用过技能了。\n"; continue; }
if (player.skills.empty()) { cout << " 没有技能。\n"; continue; }
cout << " 技能列表:\n";
for (size_t i = 0; i < player.skills.size(); ++i) {
Skill* sk = player.skills[i].get();
string limitInfo = "";
if (sk->data.oncePerBattle) {
bool used = player.usedOnceSkillsThisBattle.count(sk->data.name) > 0;
limitInfo = used ? " (本场已使用)" : " (限一次)";
}
cout << " " << i+1 << ". " << sk->data.name << " (SP:" << sk->data.costStamina << " MP:" << sk->data.costMana << ")" << limitInfo << "\n";
}
cout << " 选择 (0返回): "; int idx; cin >> idx;
if (idx > 0 && idx <= (int)player.skills.size()) {
Skill* sk = player.skills[idx-1].get();
if (sk->data.oncePerBattle && player.usedOnceSkillsThisBattle.count(sk->data.name) > 0) cout << " 该技能本场战斗已使用过。\n";
else if (player.stamina < sk->data.costStamina || player.mana < sk->data.costMana) cout << " 资源不足!\n";
else if (sk->data.minSpiritStr > 0 && player.spiritStr < sk->data.minSpiritStr) cout << " 精神强度不足。\n";
else {
player.stamina -= sk->data.costStamina; player.mana -= sk->data.costMana;
cout << " 你使用了 " << sk->data.name << "!\n";
sk->execute(player, enemy);
player.skillsUsedThisTurn++;
if (sk->data.oncePerBattle) player.usedOnceSkillsThisBattle.insert(sk->data.name);
}
}
} else if (cmd == 'B') {
if (player.itemsUsedThisTurn >= 1) { cout << " 本回合已经使用过道具了。\n"; continue; }
vector<pair<string, int>> usable;
for (auto& it : player.inventory) if (it.second > 0) usable.push_back(it);
if (usable.empty()) { cout << " 背包没有可用道具。\n"; continue; }
cout << " 道具列表:\n";
for (size_t i = 0; i < usable.size(); ++i) cout << " " << i+1 << ". " << usable[i].first << " x" << usable[i].second << "\n";
cout << " 选择 (0返回): "; int idx; cin >> idx;
if (idx > 0 && idx <= (int)usable.size()) {
string itemName = usable[idx-1].first;
int itemType = -1;
for (auto& itd : itemLibrary) if (itd.name == itemName) { itemType = itd.type; break; }
bool used = false;
if (itemType == 0) { int heal = 5 + 2*k; player.hp = min(player.maxHp, player.hp + heal); cout << " 恢复了 " << heal << " 点生命。\n"; used = true; }
else if (itemType == 1) { int rec = 2 + k; player.stamina = min(player.maxStamina, player.stamina + rec); cout << " 恢复了 " << rec << " 点体力。\n"; used = true; }
else if (itemType == 2) { int rec = 2 + k; player.mana = min(player.maxMana, player.mana + rec); cout << " 恢复了 " << rec << " 点法力。\n"; used = true; }
else if (itemType == 3) { int heal = 5 + 2*k; player.hp = min(player.maxHp, player.hp + heal); player.stamina = min(player.maxStamina, player.stamina + 2 + k); player.mana = min(player.maxMana, player.mana + 2 + k); cout << " 复合恢复成功。\n"; used = true; }
else if (itemType == 4) { player.hp = player.maxHp; player.stamina = player.maxStamina; player.mana = player.maxMana; cout << " 完全恢复!\n"; used = true; }
else if (itemType == 5) { Status s; s.name = "封印"; s.remainingTurns = 1; enemy.addStatus(s); cout << " 敌人下回合只能普攻。\n"; used = true; }
else if (itemType == 6) { Status s; s.name = "天使之羽"; s.remainingTurns = 3; player.addStatus(s); player.critRatePhys += 0.5f; player.critRateMag += 0.5f; cout << " 暴击率提升50%,持续3回合。\n"; used = true; }
else if (itemType == 7) { Status s; s.name = "恶魔契约"; s.remainingTurns = 2; player.addStatus(s); player.atkPhys *= 2; player.atkMag *= 2; player.atkSpirit *= 2; player.defPhys *= 2; player.defMag *= 2; cout << " 全属性翻倍,持续2回合。\n"; used = true; }
else if (itemType == 8) { int dmg = player.atkPhys + player.atkMag; enemy.takeDamage(dmg); cout << " 造成 " << dmg << " 点真实伤害。\n"; used = true; }
else if (itemType == 9) { Status s; s.name = "不屈"; s.remainingTurns = 3; player.addStatus(s); cout << " 获得不屈状态,3回合内不会死亡。\n"; used = true; }
if (used) { player.inventory[itemName]--; player.itemsUsedThisTurn++; }
}
} else if (cmd == 'E') showEnemyStatus(enemy);
else if (cmd == 'C') showPlayerStatus(player);
else if (cmd == 'L') turnEnd = true;
}
};
if (playerFirst) { playerTurn(); if (enemy.hp <= 0) break; enemy.takeAction(player); pauseForEnter(); }
else { enemy.takeAction(player); pauseForEnter(); if (player.hp <= 0) break; playerTurn(); }
}
if (player.hp <= 0) { clearScreen(); cout << "\n你被打败了...\n"; pauseForEnter(); return false; }
else {
clearScreen(); cout << "\n战斗胜利!获得经验 " << enemy.expDrop << ",金币 " << enemy.goldDrop << "\n";
player.gold += enemy.goldDrop;
handleEquipmentDrop(player, enemy.enemyType, currentFloor);
pauseForEnter();
player.gainExp(enemy.expDrop);
return true;
}
}
// ==================== 商店 ====================
void shopRoom(Player& player) {
int currentK = getK(player.currentFloor);
vector<SkillData> availableSkills;
for (auto& d : skillLibrary) if (d.price > 0 && !player.hasSkill(d.name)) availableSkills.push_back(d);
random_shuffle(availableSkills.begin(), availableSkills.end());
if (availableSkills.size() > 3) availableSkills.resize(3);
while (true) {
clearScreen();
cout << "\n你来到了商店,请选择:\n";
cout << "1. 书籍铺子 2. 杂货铺子 3. 装备铺子 0. 离开商店\n";
char c; cin >> c;
if (c == '0') break;
if (c == '1') {
while (true) {
clearScreen();
cout << "【书籍铺子】 你的金币:" << player.gold << "\n";
if (availableSkills.empty()) { cout << " 没有可购买的技能书了。\n"; pauseForEnter(); break; }
for (size_t i = 0; i < availableSkills.size(); ++i)
cout << " " << i+1 << ". " << availableSkills[i].name << " (" << availableSkills[i].price << "金, Lv" << availableSkills[i].levelReq << ") - " << availableSkills[i].description << "\n";
cout << "输入编号购买,0 返回:"; int sel; cin >> sel;
if (sel == 0) break;
if (sel >= 1 && sel <= (int)availableSkills.size()) {
auto skill = createSkill(availableSkills[sel-1].name);
if (player.learnSkill(move(skill))) availableSkills.erase(availableSkills.begin() + (sel-1));
}
}
} else if (c == '2') {
while (true) {
clearScreen();
cout << "【杂货铺子】 你的金币:" << player.gold << "\n";
for (size_t i = 0; i < itemLibrary.size(); ++i) {
cout << " " << i+1 << ". " << itemLibrary[i].name << " (" << itemLibrary[i].price << "金) - " << itemLibrary[i].description;
if (player.inventory.find(itemLibrary[i].name) != player.inventory.end()) cout << " [持有:" << player.inventory[itemLibrary[i].name] << "]";
cout << "\n";
}
cout << "输入编号购买,0 返回:"; int sel; cin >> sel;
if (sel == 0) break;
if (sel >= 1 && sel <= (int)itemLibrary.size()) {
if (player.gold < itemLibrary[sel-1].price) { cout << "金币不足。\n"; }
else { player.gold -= itemLibrary[sel-1].price; player.inventory[itemLibrary[sel-1].name]++; cout << "购买成功!获得 " << itemLibrary[sel-1].name << "。\n"; }
pauseForEnter();
}
}
} else if (c == '3') {
while (true) {
clearScreen();
cout << "【装备铺子】 请选择:\n";
cout << "1. 主装备 2. 副装备 0. 返回\n";
char sub; cin >> sub;
if (sub == '0') break;
if (sub == '1') {
vector<EquipmentTemplate*> mains;
for (auto& t : equipmentTemplates) if (t.price == 20) mains.push_back(&t);
while (true) {
clearScreen();
cout << "【主装备】 你的金币:" << player.gold << "\n";
for (size_t i = 0; i < mains.size(); ++i) {
Equipment eq = generateEquipment(mains[i]->name, player.level);
cout << " " << i+1 << ". " << eq.name << " Lv." << eq.level << " (" << eq.price << "金)";
if (eq.bonusAtkPhys) cout << " 物攻+" << eq.bonusAtkPhys;
if (eq.bonusAtkMag) cout << " 法攻+" << eq.bonusAtkMag;
if (eq.bonusDefPhys) cout << " 物防+" << eq.bonusDefPhys;
if (eq.bonusDefMag) cout << " 法防+" << eq.bonusDefMag;
if (eq.bonusSpeed) cout << " 速度+" << eq.bonusSpeed;
cout << "\n";
}
cout << "输入编号购买,0 返回:"; int sel; cin >> sel;
if (sel == 0) break;
if (sel >= 1 && sel <= (int)mains.size()) {
if (player.gold < mains[sel-1]->price) { cout << "金币不足。\n"; }
else { player.gold -= mains[sel-1]->price; player.equipmentInventory.push_back(make_unique<Equipment>(generateEquipment(mains[sel-1]->name, player.level))); cout << "购买成功!\n"; }
pauseForEnter();
}
}
} else if (sub == '2') {
vector<string> sets = {"天命之子", "战斗狂人", "大学者"};
while (true) {
clearScreen();
cout << "【副装备套装】 50金/件\n";
for (size_t i = 0; i < sets.size(); ++i) cout << " " << i+1 << ". " << sets[i] << "\n";
cout << " 0. 返回\n选择套装:"; int setSel; cin >> setSel;
if (setSel == 0) break;
if (setSel < 1 || setSel > 3) continue;
string setName = sets[setSel-1];
vector<EquipmentTemplate*> parts;
for (auto& t : equipmentTemplates) if (t.price == 50 && t.name.find(setName) != string::npos) parts.push_back(&t);
while (true) {
clearScreen();
cout << "【" << setName << "】 金币:" << player.gold << "\n";
for (size_t i = 0; i < parts.size(); ++i) {
Equipment eq = generateEquipment(parts[i]->name, player.level);
cout << " " << i+1 << ". " << eq.name << " Lv." << eq.level << " (" << eq.price << "金)";
if (eq.bonusMasteryPhys) cout << " 体精+" << eq.bonusMasteryPhys;
if (eq.bonusMasteryMag) cout << " 法精+" << eq.bonusMasteryMag;
if (eq.bonusUniversalCritRate) cout << " 万暴率+" << eq.bonusUniversalCritRate*100 << "%";
if (eq.bonusUniversalCritMulti) cout << " 万暴伤+" << eq.bonusUniversalCritMulti*100 << "%";
cout << "\n";
}
cout << "输入编号购买,0 返回:"; int partSel; cin >> partSel;
if (partSel == 0) break;
if (partSel >= 1 && partSel <= (int)parts.size()) {
if (player.gold < 50) { cout << "金币不足。\n"; }
else { player.gold -= 50; player.equipmentInventory.push_back(make_unique<Equipment>(generateEquipment(parts[partSel-1]->name, player.level))); cout << "购买成功!\n"; }
pauseForEnter();
}
}
}
}
}
}
}
}
void supplyRoom(Player& player) {
clearScreen(); cout << "\n你发现了补给点,全部恢复!\n";
player.hp = player.maxHp; player.stamina = player.maxStamina; player.mana = player.maxMana;
pauseForEnter();
}
int lastSupplyFloor = 0;
void nextRoom(Player& player, int& currentFloor) {
if (currentFloor - lastSupplyFloor >= 10) {
supplyRoom(player);
lastSupplyFloor = currentFloor;
} else {
int r = rand() % 100;
if (r < 80) {
if (!battle(player, currentFloor)) return;
player.stamina = min(player.maxStamina, player.stamina + 1);
player.mana = min(player.maxMana, player.mana + 1);
currentFloor++;
} else if (r < 90) {
supplyRoom(player);
lastSupplyFloor = currentFloor;
} else {
shopRoom(player);
}
}
}
Player Player::createCharacter() {
clearScreen(); cout << "============ 角色创建 ============\n"; cout << "请输入名字: "; string name; cin >> name;
ClassData chosenClass; bool confirmed = false;
while (!confirmed) {
clearScreen(); cout << "当前可选职业:\n";
for (size_t i = 0; i < classLibrary.size(); ++i) cout << " " << i+1 << ". " << classLibrary[i].name << "\n";
cout << "请选择职业编号: "; int classChoice; cin >> classChoice;
if (classChoice < 1 || classChoice > (int)classLibrary.size()) { cout << "无效编号。\n"; pauseForEnter(); continue; }
chosenClass = classLibrary[classChoice - 1];
clearScreen(); cout << "--- 职业预览 [" << chosenClass.name << "] ---\n";
cout << "生命:" << chosenClass.hp << " 体力:" << chosenClass.stamina << " 法力:" << chosenClass.mana << "\n";
cout << "物攻:" << chosenClass.atkPhys << " 法攻:" << chosenClass.atkMag << " 精攻:" << chosenClass.atkSpirit << "\n";
cout << "物防:" << chosenClass.defPhys << " 法防:" << chosenClass.defMag << " 速度:" << chosenClass.speed << "\n";
cout << "闪避:" << chosenClass.dodge << "% 精神强度:" << chosenClass.spiritStr << "\n";
cout << "体术精通:" << chosenClass.masteryPhys << " 法术精通:" << chosenClass.masteryMag << "\n";
cout << "物暴率:" << chosenClass.critRatePhys*100 << "% 物暴倍率:" << chosenClass.critMultiPhys*100 << "%\n";
cout << "法暴率:" << chosenClass.critRateMag*100 << "% 法暴倍率:" << chosenClass.critMultiMag*100 << "%\n";
cout << "初始技能: "; for (auto& sn : chosenClass.initialSkills) cout << sn << " ";
cout << "\n--------------------------------\n";
cout << "确认选择该职业吗?(Y/N): "; char yn; cin >> yn;
if (yn == 'Y' || yn == 'y') confirmed = true;
}
Player player(chosenClass); player.name = name;
clearScreen(); cout << "角色创建成功!" << chosenClass.name << " " << name << " 踏上征程。\n"; pauseForEnter();
return player;
}
Player getPlayerFromMenu() {
clearScreen(); cout << "============ 地下城探险 ============\n";
cout << "1. 新游戏\n2. 继续游戏\n3. 退出\n请选择: ";
char choice; cin >> choice;
if (choice == '2') {
ifstream test("save.dat");
if (test.good()) { test.close(); Player p = Player::loadFromFile("save.dat"); cout << "读档成功!欢迎回来," << p.name << "。\n"; pauseForEnter(); return p; }
else { cout << "没有找到存档,开始新游戏。\n"; pauseForEnter(); }
} else if (choice == '3') exit(0);
return Player::createCharacter();
}
Player rebirthFromDeath(Player& oldPlayer) {
clearScreen(); cout << "你已死亡,保留道具和 1/10 金币,请重新选择职业。\n"; pauseForEnter();
Player newPlayer = Player::createCharacter();
newPlayer.inventory = oldPlayer.inventory;
newPlayer.gold = oldPlayer.gold / 10;
return newPlayer;
}
int main() {
srand((unsigned)time(0));
initEquipmentTemplates();
Player player = classLibrary[0]; // 临时
bool firstStart = true;
while (true) {
if (firstStart) {
player = getPlayerFromMenu();
firstStart = false;
} else {
player = rebirthFromDeath(player);
}
int currentFloor = player.currentFloor;
while (player.hp > 0) {
clearScreen();
cout << "\n====== 层数 " << currentFloor << " (区域 k=" << getK(currentFloor) << ") ======\n";
cout << "Q前进 C状态 K装备 X存档退出: ";
char cmd; cin >> cmd; cmd = toupper(cmd);
if (cmd == 'Q') {
nextRoom(player, currentFloor);
player.currentFloor = currentFloor;
} else if (cmd == 'C') showPlayerStatus(player);
else if (cmd == 'K') showEquipmentPanel(player);
else if (cmd == 'X') { player.saveToFile("save.dat"); cout << "存档成功。\n"; pauseForEnter(); return 0; }
}
}
return 0;
}失败作品
扫雷
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;
const int SIZE = 9;
const int MINES = 10;
char realBoard[SIZE][SIZE];
char showBoard[SIZE][SIZE];
void initBoard() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
realBoard[i][j] = '0';
showBoard[i][j] = '*';
}
}
}
void placeMines() {
srand(time(0));
int count = 0;
while (count < MINES) {
int x = rand() % SIZE;
int y = rand() % SIZE;
if (realBoard[x][y] != 'M') {
realBoard[x][y] = 'M';
count++;
}
}
}
int countMines(int x, int y) {
int cnt = 0;
for (int dx = -1; dx <= 1; dx++) {
for (int dy = -1; dy <= 1; dy++) {
int nx = x + dx;
int ny = y + dy;
if (nx >= 0 && nx < SIZE && ny >= 0 && ny < SIZE) {
if (realBoard[nx][ny] == 'M') cnt++;
}
}
}
return cnt;
}
void openCell(int x, int y) {
if (x < 0 || x >= SIZE || y < 0 || y >= SIZE) return;
if (showBoard[x][y] != '*') return;
int num = countMines(x, y);
showBoard[x][y] = num + '0';
if (num == 0) {
for (int dx = -1; dx <= 1; dx++)
for (int dy = -1; dy <= 1; dy++)
openCell(x + dx, y + dy);
}
}
void printBoard() {
cout << "\n ";
for (int j = 0; j < SIZE; j++) cout << setw(2) << j + 1;
cout << "\n +";
for (int j = 0; j < SIZE; j++) cout << "--";
cout << "\n";
for (int i = 0; i < SIZE; i++) {
cout << i + 1 << " |";
for (int j = 0; j < SIZE; j++) {
cout << setw(2) << showBoard[i][j];
}
cout << "\n";
}
cout << endl;
}
bool isWin() {
int open = 0;
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
if (showBoard[i][j] != '*' && showBoard[i][j] != 'F')
open++;
return open == SIZE * SIZE - MINES;
}
int main() {
initBoard();
placeMines();
cout << "===== 扫雷游戏 =====" << endl;
cout << "输入格式: x y 操作" << endl;
cout << "操作:1=翻开 0=插旗/取消旗" << endl;
while (true) {
printBoard();
int x, y, op;
cout << "请输入(x y 操作):";
cin >> x >> y >> op;
x--;
y--;
if (x < 0 || x >= SIZE || y < 0 || y >= SIZE) {
cout << "坐标越界!请输入1~9" << endl;
continue;
}
if (op == 0) {
if (showBoard[x][y] == '*')
showBoard[x][y] = 'F';
else if (showBoard[x][y] == 'F')
showBoard[x][y] = '*';
continue;
}
if (op == 1) {
if (showBoard[x][y] == 'F') {
cout << "此格子有旗!无法翻开" << endl;
continue;
}
if (realBoard[x][y] == 'M') {
cout << "===== 游戏结束!你踩到地雷了 =====" << endl;
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
if (realBoard[i][j] == 'M')
showBoard[i][j] = 'M';
printBoard();
break;
}
openCell(x, y);
if (isWin()) {
cout << "===== 恭喜你!扫雷成功! =====" << endl;
printBoard();
break;
}
}
}
return 0;
}邪恶铭刻
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <string>
#include <algorithm>
#include <windows.h>
using namespace std;
// 卡牌结构体
struct Card {
string name;
int cost;
int atk;
int hp;
bool isSquirrel;
string desc;
};
// 场上生物
struct Creature {
Card card;
int hp;
int atk;
};
// 玩家数据
struct Player {
int scale;
int enemyScale;
vector<Card> deck;
vector<Card> hand;
vector<Creature> field[4];
int blood;
}me;
int nowLevel = 1;
int enemyIQ = 1;
// 初始化全卡牌
void initAllCards() {
me.deck.clear();
me.deck.push_back({"松鼠",0,0,1,true,"基础祭品"});
me.deck.push_back({"松鼠",0,0,1,true,"基础祭品"});
me.deck.push_back({"松鼠",0,0,1,true,"基础祭品"});
me.deck.push_back({"白鼬",1,2,2,false,"普通野兽"});
me.deck.push_back({"乌鸦",1,1,3,false,"高生命小怪"});
me.deck.push_back({"毒鼠",1,3,1,false,"高攻脆皮"});
me.deck.push_back({"野兔",1,1,2,false,"均衡小兵"});
me.deck.push_back({"野狼",2,4,3,false,"强力近战"});
me.deck.push_back({"秃鹫",2,3,4,false,"飞行巨兽"});
me.deck.push_back({"腐狼",2,5,2,false,"狂化猛攻"});
me.deck.push_back({"树精",2,2,5,false,"超高坦度"});
me.deck.push_back({"暗影鹿",3,6,4,false,"暗影铭刻生物"});
me.deck.push_back({"巨熊",3,5,6,false,"重甲猛兽"});
me.deck.push_back({"猎头蜘蛛",3,7,3,false,"暗杀高攻"});
me.deck.push_back({"森林古神",4,8,7,false,"传说终极生物"});
}
void drawCard() {
if(me.deck.empty()) return;
int r = rand() % me.deck.size();
me.hand.push_back(me.deck[r]);
me.deck.erase(me.deck.begin() + r);
}
void initGame() {
me.scale = 0;
me.enemyScale = 0;
me.blood = 0;
for(int i = 0; i < 4; i++) me.field[i].clear();
me.hand.clear();
initAllCards();
for(int i = 0; i < 4; i++) drawCard();
system("cls");
cout << "===== 邪恶铭刻 · 关卡进化版 =====" << endl;
cout << "当前第【" << nowLevel << "】关 | 敌方智力等级:" << enemyIQ << endl;
cout << "==================================" << endl;
}
void showHand() {
cout << "\n======== 手牌 ========" << endl;
for(int i = 0; i < me.hand.size(); i++) {
Card &c = me.hand[i];
cout << i+1 << ".【" << c.name << "】 费用:" << c.cost
<< " 攻击:" << c.atk << " 生命:" << c.hp
<< " | " << c.desc << endl;
}
}
void showField() {
cout << "\n-------- 四线战场 --------" << endl;
for(int line = 0; line < 4; line++) {
cout << "第" << line+1 << "线:";
if(me.field[line].empty()) cout << "空置\n";
else {
for(auto &cr : me.field[line])
cout << "[" << cr.card.name << "] ";
cout << endl;
}
}
cout << "你的天平:" << me.scale
<< " | 敌方天平:" << me.enemyScale << endl;
cout << "可用献祭鲜血:" << me.blood << endl;
}
void sacrifice(int line) {
if(me.field[line].empty()){cout << "该线路没有生物!\n";return;}
int add = me.field[line].size();
me.blood += add;
me.field[line].clear();
cout << "献祭成功,获得 " << add << " 点鲜血\n";
}
void summon(int handIdx, int line) {
if(handIdx < 0 || handIdx >= me.hand.size()){cout<<"手牌序号错误\n";return;}
Card c = me.hand[handIdx];
if(c.cost > me.blood){cout<<"鲜血不足,无法召唤!\n";return;}
if(me.field[line].size() >= 2){cout<<"该线路单位已满!\n";return;}
me.blood -= c.cost;
me.field[line].push_back({c,c.hp,c.atk});
me.hand.erase(me.hand.begin()+handIdx);
cout << "成功召唤【" << c.name << "】\n";
}
void attackPhase() {
cout << "\n===== 我方进攻阶段 =====" << endl;
for(int i=0;i<4;i++)
for(auto &c : me.field[i]){
cout << c.card.name << " 发动攻击,造成 " << c.atk << " 天平伤害\n";
me.enemyScale += c.atk;
}
}
// 敌方智商逐关变强
void enemySmartTurn() {
cout << "\n===== 敌方行动(智力Lv."<<enemyIQ<<")=====" << endl;
int base = rand() % 3 + 1;
int smartBonus = 0;
if(enemyIQ >= 2) smartBonus += 1;
if(enemyIQ >= 3) smartBonus += 1;
if(enemyIQ >= 4) smartBonus += 2;
if(enemyIQ >= 5) smartBonus += 2;
if(enemyIQ >= 7) smartBonus += 3;
if(enemyIQ >= 9) smartBonus += 3;
int total = base + smartBonus;
me.scale += total;
cout << "敌人精准布局,对你造成 " << total << " 点天平压力\n";
}
bool checkWin() {
if(me.scale >= 5) {
cout << "\n你战败,被铭刻吞噬,游戏结束\n";
return true;
}
if(me.enemyScale >= 5) {
cout << "\n✅ 本关通关!即将进入下一关,敌人变得更聪明!\n";
nowLevel++;
if(enemyIQ < 10) enemyIQ++;
system("pause>nul");
return true;
}
return false;
}
void battle() {
initGame();
while(true) {
if(checkWin()) break;
showField();
showHand();
cout << "\n1.献祭线路 2.召唤生物 3.结束回合\n";
int op; cin >> op;
if(op == 1) {
int l;cout<<"输入线路(1-4):";cin>>l;sacrifice(l-1);
}
else if(op == 2) {
int h,l;cout<<"输入手牌编号:";cin>>h;cout<<"召唤到线路(1-4):";cin>>l;
summon(h-1,l-1);
}
else if(op == 3) {
attackPhase();
if(checkWin()) break;
enemySmartTurn();
drawCard();
}
}
}
char mp[5][5];
int px,py;
// 随机合法地图(保证有路、必定有解)
void createRandomMap() {
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
mp[i][j] = '.';
for(int i=0;i<5;i++)
mp[0][i]='#', mp[4][i]='#', mp[i][0]='#', mp[i][4]='#';
int wallCnt = 2 + nowLevel;
for(int i=0;i<wallCnt;i++){
int x = rand()%3 + 1;
int y = rand()%3 + 1;
if(x==1&&y==1) continue;
mp[y][x] = '#';
}
px = 1; py = 1;
mp[py][px] = 'P';
vector<pair<int,int>>pos;
for(int i=1;i<=3;i++)
for(int j=1;j<=3;j++)
if(mp[i][j]=='.') pos.emplace_back(i,j);
random_shuffle(pos.begin(),pos.end());
if(pos.size()>=1) mp[pos[0].first][pos[0].second] = 'B';
if(pos.size()>=2) mp[pos[1].first][pos[1].second] = 'S';
}
void showMap() {
cout << "\n===== 第"<<nowLevel<<"关 铭刻森林 =====" << endl;
for(int i=0;i<5;i++){
for(int j=0;j<5;j++) cout<<mp[i][j]<<" ";
cout<<endl;
}
cout << "图例:P=玩家 #=围墙 .=空地 B=战斗 S=商店\n";
cout << "敌方智力等级:" << enemyIQ << endl;
}
void shop() {
cout << "\n===== 铭刻黑市商店 =====" << endl;
cout << "1.购买【巨熊】高阶卡牌\n2.购买【森林古神】终极卡牌\n3.离开商店\n";
int op;cin>>op;
if(op==1) me.deck.push_back({"巨熊",3,5,6,false,"重甲猛兽"});
if(op==2) me.deck.push_back({"森林古神",4,8,7,false,"传说终极卡"});
cout << "购买成功,卡牌已加入牌组!\n";
}
void movePlayer() {
char c;
cout << "移动方向(W上 S下 A左 D右):";cin>>c;
int nx=px,ny=py;
if(c=='w'||c=='W') ny--;
if(c=='s'||c=='S') ny++;
if(c=='a'||c=='A') nx--;
if(c=='d'||c=='D') nx++;
if(mp[ny][nx]=='#'){cout<<"前方被阻挡,无法通行!\n";return;}
mp[py][px] = '.';
px=nx;py=ny;
if(mp[ny][nx]=='B'){
cout << "\n⚠️ 遭遇林间怪物,进入战斗!\n";
battle();
createRandomMap();
}
if(mp[ny][nx]=='S'){
shop();
}
mp[py][px] = 'P';
}
int main()
{
srand((unsigned)time(NULL));
nowLevel = 1;
enemyIQ = 1;
while(true) {
createRandomMap();
while(true){
showMap();
movePlayer();
}
}
return 0;
}元气骑士
/*
* 元气骑士 文字版 - 怪物军团 (Soul Knight: Monster Legion)
* 控制台回合制地牢探险,支持多种怪物:
* - 哥布林(G): 基础近战,血量低,伤害中等
* - 骷髅(S): 贫血但伤害较高,移动快(每回合优先移动两次思路通过高概率实现)
* - 史莱姆(M): 血量厚,伤害低,会分裂(简化版保留特性)
* - 法师(W): 远程魔法攻击,不会移动,每回合远程攻击玩家
* - 精英骑士(K): 高血高攻,移动迟缓(体现在随机移动概率低)
* 每关怪物按难度动态生成,支持无限关卡
* 操作:WASD移动,I/K/J/L射击,Q退出
*/
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <conio.h>
#include <algorithm>
#include <string>
using namespace std;
// ---------- 地图参数 ----------
const int MAP_WIDTH = 14;
const int MAP_HEIGHT = 12;
const char WALL = '#';
const char FLOOR = '.';
// 玩家属性常量
const int PLAYER_BASE_HP = 20;
const int PLAYER_MAX_HP = 30;
const int SCORE_PER_KILL = 100;
const int POTION_HEAL = 8;
const int START_LEVEL = 1;
// 方向
const int dirX[4] = {0, 0, -1, 1};
const int dirY[4] = {-1, 1, 0, 0};
// ---------- 怪物类型枚举 ----------
enum MonsterType {
MT_GOBLIN, // 哥布林 (近战)
MT_SKELETON, // 骷髅 (近战,高攻低血)
MT_SLIME, // 史莱姆 (高血,低攻)
MT_WIZARD, // 法师 (远程)
MT_ELITE_KNIGHT // 精英骑士 (高血高攻)
};
// 怪物结构体
struct Monster {
int x, y; // 坐标
MonsterType type; // 类型
int hp; // 当前生命
int maxHp; // 最大生命
int damage; // 攻击力(近战或远程)
bool isRanged; // 是否远程攻击
int moveChance; // 移动概率(0~100,每回合尝试移动的概率)
char symbol; // 显示的字符
Monster(int x, int y, MonsterType t) : x(x), y(y), type(t) {
switch(t) {
case MT_GOBLIN:
hp = maxHp = 12;
damage = 8;
isRanged = false;
moveChance = 70;
symbol = 'G';
break;
case MT_SKELETON:
hp = maxHp = 8;
damage = 12;
isRanged = false;
moveChance = 90;
symbol = 'S';
break;
case MT_SLIME:
hp = maxHp = 25;
damage = 5;
isRanged = false;
moveChance = 50;
symbol = 'M';
break;
case MT_WIZARD:
hp = maxHp = 10;
damage = 9;
isRanged = true;
moveChance = 0; // 不移动
symbol = 'W';
break;
case MT_ELITE_KNIGHT:
hp = maxHp = 30;
damage = 15;
isRanged = false;
moveChance = 40;
symbol = 'K';
break;
default:
hp = maxHp = 10;
damage = 6;
isRanged = false;
moveChance = 70;
symbol = 'E';
}
}
};
// ---------- 全局数据 ----------
char mapGrid[MAP_HEIGHT][MAP_WIDTH];
vector<Monster> monsters; // 怪物容器(替代原enemies)
vector<pair<int,int>> potions;
int playerX, playerY;
int playerHP;
int score;
int currentLevel;
bool gameRunning;
// ---------- 函数声明 ----------
void LoadLevel(int level);
void DrawMap();
void ProcessInput();
void MovePlayer(int dx, int dy);
void Shoot(int dx, int dy);
void EnemyTurn();
void HealPlayer(int amount);
void AddScore(int points);
bool IsValidMove(int x, int y, bool forMonster = false, int selfIdx = -1);
// 辅助:检查某个位置是否有怪物(可排除自身)
int GetMonsterIndexAt(int x, int y, int excludeIdx = -1);
// 远程怪物攻击逻辑
void RangedAttack(Monster &m);
// ---------- 主函数 ----------
int main()
{
srand((unsigned int)time(0));
currentLevel = START_LEVEL;
score = 0;
gameRunning = true;
LoadLevel(currentLevel);
while (gameRunning)
{
DrawMap();
ProcessInput();
if (!gameRunning) break;
EnemyTurn();
if (playerHP <= 0)
{
gameRunning = false;
break;
}
// 通关检测:所有怪物死亡
if (monsters.empty())
{
currentLevel++;
cout << "\n========== 关卡 " << currentLevel-1 << " 通关! ==========" << endl;
cout << "进入下一层地牢... 生命完全恢复,获得额外奖励分数。" << endl;
_getch();
AddScore(SCORE_PER_KILL / 2);
LoadLevel(currentLevel);
}
}
// 游戏结束
cout << "\n========== GAME OVER ==========" << endl;
cout << "通关层数: " << currentLevel-1 << endl;
cout << "最终得分: " << score << endl;
cout << "=================================" << endl;
cout << "按任意键退出...";
_getch();
return 0;
}
// ---------- 加载关卡(动态生成多种怪物)----------
void LoadLevel(int level)
{
monsters.clear();
potions.clear();
// 生成边界和地板
for (int i = 0; i < MAP_HEIGHT; ++i)
for (int j = 0; j < MAP_WIDTH; ++j)
mapGrid[i][j] = (i == 0 || i == MAP_HEIGHT-1 || j == 0 || j == MAP_WIDTH-1) ? WALL : FLOOR;
// 生成障碍物(随关卡增多)
int totalCells = (MAP_WIDTH-2)*(MAP_HEIGHT-2);
int obstaclePercent = min(12 + level, 35);
int obstacleCount = totalCells * obstaclePercent / 100;
for (int k = 0; k < obstacleCount; ++k)
{
int x, y;
do {
x = rand() % (MAP_WIDTH-2) + 1;
y = rand() % (MAP_HEIGHT-2) + 1;
} while (mapGrid[y][x] != FLOOR);
mapGrid[y][x] = WALL;
}
// 玩家起始 (1,1)
playerX = 1;
playerY = 1;
mapGrid[playerY][playerX] = FLOOR;
// ----- 生成怪物(数量5~9只,且随关卡增长)-----
int monsterCount = min(5 + (level-1) / 2, 12);
// 根据关卡确定怪物类型权重
// 权重数组:哥布林,骷髅,史莱姆,法师,精英骑士
int weights[5] = {40, 25, 15, 15, 5}; // 基础权重
// 随着关卡提升,精英骑士权重增加,史莱姆权重略升
weights[4] += min(level, 15);
weights[2] += min(level / 2, 10);
// 总权重
int totalWeight = 0;
for (int w : weights) totalWeight += w;
for (int i = 0; i < monsterCount; ++i)
{
int randVal = rand() % totalWeight;
MonsterType chosenType = MT_GOBLIN;
int accum = 0;
for (int t = 0; t < 5; ++t)
{
accum += weights[t];
if (randVal < accum)
{
chosenType = (MonsterType)t;
break;
}
}
int mx, my;
bool ok;
do {
ok = true;
mx = rand() % (MAP_WIDTH-2) + 1;
my = rand() % (MAP_HEIGHT-2) + 1;
if ((mx == playerX && my == playerY)) ok = false;
if (mapGrid[my][mx] != FLOOR) ok = false;
for (auto &m : monsters)
if (m.x == mx && m.y == my) { ok = false; break; }
} while (!ok);
monsters.push_back(Monster(mx, my, chosenType));
}
// 生成血瓶(数量随关卡增多)
int potionCount = min(2 + (level-1)/2, 6);
for (int i = 0; i < potionCount; ++i)
{
int px, py;
do {
px = rand() % (MAP_WIDTH-2) + 1;
py = rand() % (MAP_HEIGHT-2) + 1;
} while ((px == playerX && py == playerY) ||
mapGrid[py][px] != FLOOR ||
find(potions.begin(), potions.end(), make_pair(px,py)) != potions.end() ||
GetMonsterIndexAt(px, py) != -1);
potions.push_back({px, py});
}
// 重置玩家生命
playerHP = PLAYER_BASE_HP;
if (playerHP > PLAYER_MAX_HP) playerHP = PLAYER_MAX_HP;
}
// ---------- 绘制地图(显示不同怪物符号)----------
void DrawMap()
{
system("cls");
for (int y = 0; y < MAP_HEIGHT; ++y)
{
for (int x = 0; x < MAP_WIDTH; ++x)
{
if (x == playerX && y == playerY)
cout << 'P' << ' ';
else
{
char ch = mapGrid[y][x];
// 检查是否有怪物
int monIdx = GetMonsterIndexAt(x, y);
if (monIdx != -1)
ch = monsters[monIdx].symbol;
else if (find(potions.begin(), potions.end(), make_pair(x,y)) != potions.end())
ch = 'H';
cout << ch << ' ';
}
}
cout << endl;
}
// 状态栏
cout << "\n=== 元气骑士 文字版 - 怪物军团 ===" << endl;
cout << "关卡: " << currentLevel << " ";
cout << "生命: " << playerHP << "/" << PLAYER_MAX_HP << " ";
cout << "得分: " << score << " ";
cout << "剩余怪物: " << monsters.size() << endl;
cout << "怪物图鉴: G哥布林 S骷髅 M史莱姆 W法师 K精英骑士" << endl;
cout << "操作: WASD移动 I/K/J/L射击 Q退出" << endl;
cout << "提示: 移动至 H 恢复 " << POTION_HEAL << " 生命; 远程怪(W)不会移动但会远程攻击" << endl;
}
// ---------- 玩家输入 ----------
void ProcessInput()
{
char key = _getch();
switch (key)
{
case 'w': case 'W': MovePlayer(0, -1); break;
case 's': case 'S': MovePlayer(0, 1); break;
case 'a': case 'A': MovePlayer(-1, 0); break;
case 'd': case 'D': MovePlayer(1, 0); break;
case 'i': case 'I': Shoot(0, -1); break;
case 'k': case 'K': Shoot(0, 1); break;
case 'j': case 'J': Shoot(-1, 0); break;
case 'l': case 'L': Shoot(1, 0); break;
case 'q': case 'Q': gameRunning = false; break;
default: break;
}
}
// ---------- 移动玩家 ----------
void MovePlayer(int dx, int dy)
{
int nx = playerX + dx;
int ny = playerY + dy;
if (mapGrid[ny][nx] == WALL) return;
// 不能走进怪物格子
if (GetMonsterIndexAt(nx, ny) != -1) return;
// 拾取血瓶
auto it = find(potions.begin(), potions.end(), make_pair(nx, ny));
if (it != potions.end())
{
HealPlayer(POTION_HEAL);
potions.erase(it);
}
playerX = nx;
playerY = ny;
}
// ---------- 射击(伤害怪物,可能一枪致死)----------
void Shoot(int dx, int dy)
{
int cx = playerX + dx;
int cy = playerY + dy;
while (cx > 0 && cx < MAP_WIDTH-1 && cy > 0 && cy < MAP_HEIGHT-1)
{
if (mapGrid[cy][cx] == WALL) break;
int monIdx = GetMonsterIndexAt(cx, cy);
if (monIdx != -1)
{
// 击中怪物,扣除10点伤害(固定枪伤)
monsters[monIdx].hp -= 10;
if (monsters[monIdx].hp <= 0)
{
// 击杀加分
AddScore(SCORE_PER_KILL);
monsters.erase(monsters.begin() + monIdx);
}
break; // 子弹停止
}
cx += dx;
cy += dy;
}
}
// ---------- 敌人回合:移动、近战攻击、远程攻击 ----------
void EnemyTurn()
{
// 遍历所有怪物(注意删除后索引变化,故从后往前或使用辅助)
for (int i = 0; i < (int)monsters.size(); ++i)
{
Monster &m = monsters[i];
// 远程怪物:移动概率为0,直接远程攻击玩家(如果在视野内且无墙阻挡)
if (m.isRanged)
{
RangedAttack(m);
continue;
}
// 近战怪物:决定是否移动(根据moveChance),移动尝试朝玩家方向走一步
bool didAction = false;
if (rand() % 100 < m.moveChance)
{
// 计算朝向玩家的方向
int dx = 0, dy = 0;
if (playerX > m.x) dx = 1;
else if (playerX < m.x) dx = -1;
if (playerY > m.y) dy = 1;
else if (playerY < m.y) dy = -1;
// 优先尝试水平移动,再垂直移动(简单AI)
int tries = 0;
if (dx != 0)
{
int nx = m.x + dx;
int ny = m.y;
if (IsValidMove(nx, ny, true, i))
{
m.x = nx;
m.y = ny;
didAction = true;
}
else if (dy != 0)
{
nx = m.x;
ny = m.y + dy;
if (IsValidMove(nx, ny, true, i))
{
m.x = nx;
m.y = ny;
didAction = true;
}
}
}
else if (dy != 0)
{
int nx = m.x;
int ny = m.y + dy;
if (IsValidMove(nx, ny, true, i))
{
m.x = nx;
m.y = ny;
didAction = true;
}
}
}
// 移动后,检查是否与玩家相邻(上下左右),如果是则攻击
if (abs(m.x - playerX) + abs(m.y - playerY) == 1)
{
playerHP -= m.damage;
if (playerHP <= 0)
{
gameRunning = false;
return;
}
didAction = true;
}
// 如果没能移动也没能攻击,本回合怪物什么也不做
}
}
// 远程怪物攻击:向玩家直线发射魔法,如果有墙阻挡则无效,伤害为怪物damage
void RangedAttack(Monster &m)
{
// 计算从怪物到玩家的方向
int dx = 0, dy = 0;
if (playerX > m.x) dx = 1;
else if (playerX < m.x) dx = -1;
if (playerY > m.y) dy = 1;
else if (playerY < m.y) dy = -1;
// 必须是直线(dx和dy不能同时非零,怪物不会斜向攻击)
if (dx != 0 && dy != 0) return; // 不在同行/同列,不攻击
// 检查射线路径上是否有墙壁
int cx = m.x + dx;
int cy = m.y + dy;
bool blocked = false;
while (!(cx == playerX && cy == playerY))
{
if (cx <= 0 || cx >= MAP_WIDTH-1 || cy <= 0 || cy >= MAP_HEIGHT-1 || mapGrid[cy][cx] == WALL)
{
blocked = true;
break;
}
// 路径上有其他怪物(但不阻挡远程攻击,只阻挡墙壁)
cx += dx;
cy += dy;
}
if (!blocked)
{
playerHP -= m.damage;
if (playerHP <= 0) gameRunning = false;
}
}
// ---------- 辅助函数 ----------
int GetMonsterIndexAt(int x, int y, int excludeIdx)
{
for (size_t i = 0; i < monsters.size(); ++i)
if ((int)i != excludeIdx && monsters[i].x == x && monsters[i].y == y)
return i;
return -1;
}
bool IsValidMove(int x, int y, bool forMonster, int selfIdx)
{
if (x <= 0 || x >= MAP_WIDTH-1 || y <= 0 || y >= MAP_HEIGHT-1) return false;
if (mapGrid[y][x] == WALL) return false;
if (forMonster)
{
int idx = GetMonsterIndexAt(x, y, selfIdx);
if (idx != -1) return false; // 与其他怪物重叠
if (x == playerX && y == playerY) return false; // 不能走进玩家(攻击在另外处理)
}
else
{
if (GetMonsterIndexAt(x, y) != -1) return false;
}
// 血瓶不影响移动(玩家拾取,怪物不应该占用)
return true;
}
void HealPlayer(int amount)
{
playerHP += amount;
if (playerHP > PLAYER_MAX_HP) playerHP = PLAYER_MAX_HP;
}
void AddScore(int points)
{
score += points;
}解密-前传
/*
* 游戏名称: 被诅咒的图书馆
* 类型: 纯文字解谜游戏
* 运行环境: Code::Blocks (C++ 控制台)
* 作者: AI Assistant
* 剧情简介:
* 你在一间昏暗的古老图书馆中醒来,四周弥漫着霉味和魔法的气息。
* 根据模糊的记忆,你被一股黑暗力量困在这里,必须找到传说中的“封印之书”,
* 并念出正确的咒语才能打破诅咒,逃离图书馆。
* 探索大厅,找到钥匙和日记,解开谜题,最终用咒语解救自己。
*
* 游戏指令:
* look - 重新观察当前房间
* inventory 或 i - 查看背包中的物品
* take <物品> - 拾取物品 (key, diary)
* use <物品> - 使用物品 (key 可以打开东侧的门)
* read <物品> - 阅读物品 (diary 可以学到咒语)
* examine <物品> - 仔细观察物品或环境
* go <方向> - 移动方向 (east, west)
* say <词语> - 念出咒语 (必须在密室中对魔法书使用)
* help - 显示指令帮助
* quit - 退出游戏
*
* 物品介绍:
* key - 生锈的铜钥匙,可以打开大厅东侧上锁的门。
* diary - 一本破旧的日记,里面记载着解开封印的咒语。
* book - 密室中的魔法书,被封印之力保护着,需要咒语来解放它。
*
* 谜题流程:
* 1. 在大厅找到钥匙和日记。
* 2. 拾取钥匙,使用钥匙打开东侧的门。
* 3. 阅读日记,记住咒语 "Liberare"。
* 4. 进入密室(东侧房间),对着魔法书念出正确的咒语。
* 5. 胜利逃脱!
*
* 注意: 这是一款纯文字互动游戏,请根据剧情和提示输入指令。
*/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <cctype>
#include <map>
using namespace std;
// ======================= 全局游戏状态 =======================
string currentRoom = "hall"; // 当前所在房间: hall(大厅) 或 study(密室)
bool hallKeyExists = true; // 大厅里是否还有钥匙
bool hallDiaryExists = true; // 大厅里是否还有日记
bool doorLocked = true; // 东侧门是否上锁 (大厅通往密室)
bool knowSpell = false; // 是否从日记中得知咒语
vector<string> inventory; // 玩家背包中的物品列表
// ======================= 辅助函数 =======================
// 将字符串转为小写
string toLower(string str) {
transform(str.begin(), str.end(), str.begin(), ::tolower);
return str;
}
// 去除字符串首尾空格
string trim(const string& str) {
size_t first = str.find_first_not_of(" \t\n\r");
if (first == string::npos) return "";
size_t last = str.find_last_not_of(" \t\n\r");
return str.substr(first, last - first + 1);
}
// 分割命令: 第一个单词为动词,剩下的为参数 (全小写)
pair<string, string> parseCommand(const string& input) {
string cmd = trim(input);
string verb, arg;
size_t spacePos = cmd.find(' ');
if (spacePos != string::npos) {
verb = cmd.substr(0, spacePos);
arg = cmd.substr(spacePos + 1);
verb = toLower(verb);
arg = toLower(trim(arg));
} else {
verb = toLower(cmd);
arg = "";
}
return {verb, arg};
}
// 检查背包中是否有某物品
bool hasItem(const string& item) {
for (const auto& i : inventory) {
if (i == item) return true;
}
return false;
}
// 显示当前房间的描述以及可见物品和出口
void showLocation() {
cout << "\n=============================================\n";
if (currentRoom == "hall") {
cout << "【大厅】\n";
cout << "这是一个宽敞且昏暗的大厅,四周是高耸的书架,空气中弥漫着陈旧的纸张和魔法气息。\n";
cout << "地上散落着一些古老的家具。东侧有一扇沉重的木门,上面刻着奇异的符文。\n";
if (doorLocked) {
cout << "东侧的门紧紧锁着,似乎需要一把钥匙才能打开。\n";
} else {
cout << "东侧的门现在敞开着,你可以进入密室。\n";
}
cout << "可见物品: ";
bool hasItem = false;
if (hallKeyExists) {
cout << "一把闪亮的铜钥匙(key) ";
hasItem = true;
}
if (hallDiaryExists) {
cout << "一本破旧的日记(diary) ";
hasItem = true;
}
if (!hasItem) {
cout << "这里没有任何可拾取的物品了。";
}
cout << "\n出口: east (东侧), west (西侧,但只是一堵墙)";
}
else if (currentRoom == "study") {
cout << "【密室】\n";
cout << "这是一个幽静的小房间,中央摆放着一张石质台座,台上放着一本散发着微光的厚重书籍——那正是封印之书。\n";
cout << "书页微微颤动,仿佛被某种力量禁锢着。墙上写着古老的警示语。\n";
cout << "可见物品: 封印之书(book)";
cout << "\n出口: west (回到大厅)";
}
cout << "\n=============================================\n";
}
// 显示背包
void showInventory() {
cout << "\n【背包】\n";
if (inventory.empty()) {
cout << "空空如也,你什么都没有。\n";
} else {
cout << "你携带着: ";
for (size_t i = 0; i < inventory.size(); ++i) {
if (i > 0) cout << ", ";
if (inventory[i] == "key") cout << "铜钥匙(key)";
else if (inventory[i] == "diary") cout << "旧日记(diary)";
else cout << inventory[i];
}
cout << endl;
}
}
// 处理take指令
void handleTake(const string& item) {
if (item.empty()) {
cout << "你想拿什么? 请输入 'take 物品名' (例如 take key)\n";
return;
}
if (currentRoom == "hall") {
if (item == "key" && hallKeyExists) {
inventory.push_back("key");
hallKeyExists = false;
cout << "你捡起了铜钥匙。\n";
} else if (item == "diary" && hallDiaryExists) {
inventory.push_back("diary");
hallDiaryExists = false;
cout << "你捡起了那本破旧的日记。\n";
} else {
cout << "这里没有 " << item << " 可以拿。\n";
}
} else if (currentRoom == "study") {
if (item == "book") {
cout << "封印之书被强大的魔法固定住了,你无法直接拿走它。或许需要某种方法解除封印。\n";
} else {
cout << "密室里没有 " << item << " 这个东西。\n";
}
} else {
cout << "无效的操作。\n";
}
}
// 处理use指令 (主要用来使用钥匙开门)
void handleUse(const string& item) {
if (item.empty()) {
cout << "你想使用什么? 例如 'use key'\n";
return;
}
if (item == "key") {
if (hasItem("key")) {
if (doorLocked) {
// 只能在Hall使用钥匙开门
if (currentRoom == "hall") {
doorLocked = false;
// 从背包中移除钥匙 (一次性使用)
inventory.erase(remove(inventory.begin(), inventory.end(), "key"), inventory.end());
cout << "你将铜钥匙插入门上的锁孔,轻轻转动,只听“咔哒”一声,东侧的门解锁了!现在你可以 'go east' 进入密室。\n";
} else {
cout << "这里没有需要钥匙的门。试试回到大厅使用钥匙吧。\n";
}
} else {
cout << "门已经是打开的了,不需要再使用钥匙。\n";
}
} else {
cout << "你身上没有钥匙。\n";
}
} else {
cout << "不知道如何使用 " << item << "。\n";
}
}
// 处理read指令 (阅读日记学咒语)
void handleRead(const string& item) {
if (item.empty()) {
cout << "你想阅读什么? 例如 'read diary'\n";
return;
}
if (item == "diary") {
bool hasDiary = hasItem("diary");
bool diaryInHall = (currentRoom == "hall" && hallDiaryExists);
if (hasDiary || diaryInHall) {
if (!knowSpell) {
cout << "\n你翻开日记,里面的字迹潦草但依稀可辨:\n";
cout << "\"诅咒缠绕着这本书,唯有光明的言语可以解放它。\n";
cout << "记住,真正的咒语是—— Liberare 。\"\n";
cout << "你心中默念了一遍,牢牢地记住了这个咒语。\n";
knowSpell = true;
} else {
cout << "你再次翻看日记,上面记载的咒语仍然是 'Liberare'。\n";
}
} else {
cout << "你身边没有日记可以阅读。如果你在大厅,可以看到地上有一本日记,需要先 'take diary' 拾取。\n";
}
} else {
cout << "无法阅读 " << item << "。\n";
}
}
// 处理examine指令 (仔细观察物品或环境)
void handleExamine(const string& target) {
if (target.empty()) {
cout << "你想仔细观察什么? 例如 'examine door'\n";
return;
}
if (target == "door" && currentRoom == "hall") {
if (doorLocked) {
cout << "门是厚重的橡木制成,刻满了古老的符文,锁眼处泛着微弱的蓝光。看起来需要一把特殊的钥匙。\n";
} else {
cout << "门已经被打开了,你可以自由地进出密室。\n";
}
} else if (target == "book" && currentRoom == "study") {
cout << "封印之书被锁链般的魔法光带缠绕着,书封上刻着一行模糊的拉丁文。你隐约感觉到,正确的咒语可以解放它。\n";
} else if (target == "bookshelf" && currentRoom == "hall") {
cout << "书架上的书籍大多已经腐朽,但其中一格放着一样闪亮的东西和一本破旧的日记。\n";
} else if (target == "key") {
if (hasItem("key") || (currentRoom == "hall" && hallKeyExists)) {
cout << "一把古朴的铜钥匙,表面有些锈迹,但看起来依然能打开某扇门。\n";
} else {
cout << "这里没有你要观察的钥匙。\n";
}
} else if (target == "diary") {
bool hasDiary = hasItem("diary");
bool diaryInHall = (currentRoom == "hall" && hallDiaryExists);
if (hasDiary || diaryInHall) {
cout << "日记的封面是深棕色的皮革,边缘已经磨损。里面记录着前任图书馆主人的一些秘密。\n";
} else {
cout << "这里没有日记。\n";
}
} else {
cout << "你仔细观察了 " << target << ",但没有发现什么特别之处。\n";
}
}
// 处理移动
void handleGo(const string& direction) {
if (direction.empty()) {
cout << "想去哪里? 方向: east, west\n";
return;
}
if (direction == "east") {
if (currentRoom == "hall") {
if (!doorLocked) {
currentRoom = "study";
cout << "你穿过敞开的门,进入了密室。\n";
showLocation();
} else {
cout << "东侧的门紧紧锁着,纹丝不动。你需要一把钥匙将它打开。\n";
}
} else if (currentRoom == "study") {
cout << "东边是坚硬的石壁,没有路可走。\n";
}
} else if (direction == "west") {
if (currentRoom == "study") {
currentRoom = "hall";
cout << "你回到了大厅。\n";
showLocation();
} else if (currentRoom == "hall") {
cout << "西边是一堵厚重的石墙,无法通行。你只能被困在这里寻找出路。\n";
}
} else {
cout << "不能往 " << direction << " 走。\n";
}
}
// 处理say指令 (念咒语,胜利关键)
void handleSay(const string& words) {
if (words.empty()) {
cout << "你想念什么? 请输入 'say 咒语'\n";
return;
}
if (currentRoom != "study") {
cout << "你现在不在密室中,胡乱念咒语没什么效果。\n";
return;
}
string spell = toLower(words);
if (spell == "liberare") {
if (knowSpell) {
cout << "\n⭐ 你对着封印之书坚定地念出咒语: 'LIBERARE' ⭐\n";
cout << "瞬间,书上的魔法光带纷纷断裂,书本缓缓打开,释放出温暖的光芒。\n";
cout << "整个图书馆开始震颤,黑暗诅咒烟消云散,一扇通向光明的门在你面前出现。\n";
cout << "你成功地打破了封印,逃出了这座恐怖的图书馆!\n";
cout << "🏆 恭喜你通关! 🏆\n";
exit(0); // 游戏胜利,直接退出
} else {
cout << "你念出了 'Liberare',但什么也没有发生……你似乎没有真正理解这个咒语的含义。\n";
cout << "也许你需要先找到关于咒语的线索。\n";
}
} else {
cout << "你念出了 \"" << words << "\",但魔法书没有任何反应。咒语似乎不对。\n";
}
}
// 显示帮助信息
void showHelp() {
cout << "\n========== 指令帮助 ==========\n";
cout << "look - 重新观察当前房间\n";
cout << "inventory 或 i - 查看背包物品\n";
cout << "take <物品> - 拾取物品 (key, diary)\n";
cout << "use <物品> - 使用物品 (key 可以开门)\n";
cout << "read <物品> - 阅读物品 (diary 可以获得咒语)\n";
cout << "examine <物品/目标> - 仔细观察 (如 door, book, diary, key)\n";
cout << "go <方向> - 移动 (east, west)\n";
cout << "say <词语> - 念咒语 (在密室中对书使用正确咒语)\n";
cout << "help - 显示本帮助\n";
cout << "quit - 退出游戏\n";
cout << "================================\n";
cout << "提示: 先在大厅拿钥匙和日记,用钥匙开门,读日记学咒语,再去密室念咒语。\n";
}
// ======================= 主游戏循环 =======================
int main() {
cout << "============================================================\n";
cout << " 【被诅咒的图书馆】\n";
cout << " 一款纯文字解谜游戏\n";
cout << "============================================================\n";
cout << "你从冰冷的地板上醒来,头痛欲裂,四周一片昏暗。\n";
cout << "空气里弥漫着书本腐烂和魔法的味道。你的记忆中只剩下一个任务:\n";
cout << "找到封印之书,念出正确的咒语,逃离这里……否则你将永远困在诅咒之中。\n";
cout << "输入 'help' 查看指令,'look' 观察周围。\n";
cout << "祝你好运,探索者。\n";
showLocation();
string input;
while (true) {
cout << "\n> ";
getline(cin, input);
if (input.empty()) continue;
auto [verb, arg] = parseCommand(input);
if (verb == "quit") {
cout << "你放弃了挣扎,意识渐渐模糊……游戏结束。\n";
break;
} else if (verb == "look") {
showLocation();
} else if (verb == "inventory" || verb == "i") {
showInventory();
} else if (verb == "take") {
handleTake(arg);
} else if (verb == "use") {
handleUse(arg);
} else if (verb == "read") {
handleRead(arg);
} else if (verb == "examine") {
handleExamine(arg);
} else if (verb == "go") {
handleGo(arg);
} else if (verb == "say") {
handleSay(arg);
} else if (verb == "help") {
showHelp();
} else {
cout << "无法理解指令 '" << verb << "'。输入 'help' 查看可用命令。\n";
}
}
return 0;
}解密-世界
/*
* 游戏名称: 被诅咒的图书馆:三界咏叹调 (终极修复版)
* 类型: 纯文字解谜游戏 (超大规模多章节)
* 运行环境: Code::Blocks / 支持C++17的控制台
* 作者: AI Assistant
*
* 剧情简介:
* 你在“被诅咒的图书馆”中醒来,本以为打破封印就能逃离,却发现背后隐藏着撕裂三界的巨大阴谋。
* 古老的诅咒将魔幻界、都市界与密室界三块大陆与你所在的图书馆核心扭曲在一起。
* 你必须依次穿越三个完全不同的世界,收集三种圣物,最终在“起源之间”念出最终的圣言,
* 才能永久修复世界的裂痕。
*
* 游戏架构 (总计20个独特房间,超过10个章节):
* 第一幕: 诅咒的起点 (图书馆区域) - 4房间
* 第二幕: 魔幻界 (魔法与巨龙) - 5房间
* 第三幕: 都市界 (科技与阴谋) - 4房间
* 第四幕: 密室界 (古代机关) - 4房间
* 第五幕: 终章 (真理之殿) - 3房间
*
* 核心谜题流程 (已修复所有死锁):
* 图书馆阶段: 读日记 -> 拿三界钥匙 -> 激活传送门 -> 获得旅行者徽章
* 魔幻界: 拿风之羽 -> 读石碑 -> 进巨龙峰拿火之石 -> 在祭坛合成自然之息
* 都市界: 拿权限卡 -> 开服务器门 -> 取电之芯 -> 在数据核心合成科技密钥
* 密室界: 解天平谜题 -> 取时之砂 -> 在王座合成时空之锚
* 终章: 裂痕圣堂融合三圣物 -> 习得终极咒语 -> 起源之间念咒胜利
*
* 游戏指令:
* look - 重新观察当前房间
* inventory / i - 查看背包中的物品
* take <物品> - 拾取物品
* use <物品> - 使用物品 (可开启机关、合成圣物)
* read <物品/笔记> - 阅读日记、石碑等
* examine <目标> - 仔细观察 (发现隐藏线索)
* go <方向> - 移动 (north, south, east, west, up, down)
* say <词语> - 念咒语 (终极胜利时使用)
* quest - 查看主线任务提示
* help - 显示指令帮助
* quit - 退出游戏
*
* 注意: 游戏文本量巨大,请耐心探索,物品名使用小写英文。
*/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
#include <sstream>
#include <cctype>
#include <iomanip>
using namespace std;
// ======================= 全局游戏状态 =======================
string currentRoom = "library_hall"; // 当前所在房间ID
set<string> inventory; // 背包中的物品集合
map<string, bool> flags; // 全局剧情标志 (门锁、谜题是否解开等)
map<string, set<string>> roomItems; // 每个房间当前还存在的物品 (动态变化)
// 房间完整定义: 名字、描述、出口、特殊观察文本
struct Room {
string name;
string description;
map<string, string> exits; // 方向 -> 目标房间ID
string examineDetail; // 额外仔细查看时的详细描述
};
map<string, Room> rooms; // 所有房间数据库
// ======================= 辅助函数 =======================
// 将字符串转为小写
string toLower(string str) {
transform(str.begin(), str.end(), str.begin(), ::tolower);
return str;
}
// 去除字符串首尾空格
string trim(const string& str) {
size_t first = str.find_first_not_of(" \t\n\r");
if (first == string::npos) return "";
size_t last = str.find_last_not_of(" \t\n\r");
return str.substr(first, last - first + 1);
}
// 解析命令: 第一个单词为动词,剩下的为参数 (全小写)
pair<string, string> parseCommand(const string& input) {
string cmd = trim(input);
string verb, arg;
size_t spacePos = cmd.find(' ');
if (spacePos != string::npos) {
verb = cmd.substr(0, spacePos);
arg = cmd.substr(spacePos + 1);
verb = toLower(verb);
arg = toLower(trim(arg));
} else {
verb = toLower(cmd);
arg = "";
}
return {verb, arg};
}
// 检查背包中是否有某物品
bool hasItem(const string& item) {
return inventory.find(item) != inventory.end();
}
// 向房间添加物品 (一般用于初始化)
void addItemToRoom(const string& roomId, const string& item) {
roomItems[roomId].insert(item);
}
// 从房间移除物品
void removeItemFromRoom(const string& roomId, const string& item) {
if (roomItems.find(roomId) != roomItems.end()) {
roomItems[roomId].erase(item);
}
}
// 检查物品是否在当前房间
bool itemInRoom(const string& roomId, const string& item) {
if (roomItems.find(roomId) == roomItems.end()) return false;
return roomItems[roomId].find(item) != roomItems[roomId].end();
}
// ======================= 显示相关 =======================
// 显示当前房间的完整描述 (带可见物品和出口)
void showLocation() {
cout << "\n============================================================\n";
cout << "【" << rooms[currentRoom].name << "】\n";
cout << rooms[currentRoom].description << "\n";
// 显示可见物品
if (roomItems.count(currentRoom) && !roomItems[currentRoom].empty()) {
cout << "◇ 你能看见的物品: ";
bool first = true;
for (const string& item : roomItems[currentRoom]) {
if (!first) cout << ", ";
// 物品显示友好名称
if (item == "tri_key") cout << "三界钥匙(tri_key)";
else if (item == "diary") cout << "旧日记(diary)";
else if (item == "wind_feather") cout << "风之羽(wind_feather)";
else if (item == "fire_stone") cout << "焰心结晶(fire_stone)";
else if (item == "electric_core") cout << "电之芯(electric_core)";
else if (item == "access_card") cout << "权限卡(access_card)";
else if (item == "time_sand") cout << "时之砂(time_sand)";
else if (item == "traveler_badge") cout << "旅行者徽章(traveler_badge)";
else cout << item;
first = false;
}
cout << "\n";
} else {
cout << "◇ 这里没有任何明显可拾取的物品。\n";
}
// 显示出口
cout << "◇ 可通行的方向: ";
bool firstDir = true;
for (const auto& [dir, target] : rooms[currentRoom].exits) {
if (!firstDir) cout << ", ";
cout << dir;
firstDir = false;
}
if (rooms[currentRoom].exits.empty()) cout << "无路可走 (需要满足某些条件)";
cout << "\n============================================================\n";
}
// 显示背包内容
void showInventory() {
cout << "\n【 背 包 】\n";
if (inventory.empty()) {
cout << " (空空如也)\n";
} else {
cout << " 你携带: ";
bool first = true;
for (const string& item : inventory) {
if (!first) cout << ", ";
if (item == "tri_key") cout << "三界钥匙";
else if (item == "diary") cout << "旧日记";
else if (item == "wind_feather") cout << "风之羽";
else if (item == "fire_stone") cout << "焰心结晶";
else if (item == "electric_core") cout << "电之芯";
else if (item == "access_card") cout << "权限卡";
else if (item == "time_sand") cout << "时之砂";
else if (item == "traveler_badge") cout << "旅行者徽章";
else if (item == "nature_breath") cout << "自然之息(合成品)";
else if (item == "tech_key") cout << "科技密钥(合成品)";
else if (item == "temporal_anchor") cout << "时空之锚(合成品)";
else cout << item;
first = false;
}
cout << "\n";
}
}
// 显示主线任务提示 (动态更新)
void showQuest() {
cout << "\n【 主 线 任 务 】\n";
if (!flags["portal_activated"] && !hasItem("traveler_badge")) {
cout << " ● 第一阶段: 在图书馆区域\n";
cout << " 1. 阅读大厅里的「日记」了解线索\n";
cout << " 2. 进入禁书密室拿到「三界钥匙」\n";
cout << " 3. 前往地下秘库和传送门枢纽,使用钥匙激活传送门,获得「旅行者徽章」\n";
} else if (!flags["nature_breath_done"]) {
cout << " ● 第二阶段(魔幻界): 从传送门枢纽向北进入魔幻界\n";
cout << " 1. 在精灵树屋取得「风之羽」\n";
cout << " 2. 在石中剑祭坛阅读石碑获取合成知识\n";
cout << " 3. 前往巨龙之峰,与巨龙对话或直接取得「焰心结晶」\n";
cout << " 4. 返回石中剑祭坛,使用风之羽和焰心结晶合成「自然之息」\n";
} else if (!flags["tech_key_done"]) {
cout << " ● 第三阶段(都市界): 从传送门枢纽向东进入都市界\n";
cout << " 1. 在摩天楼顶层办公室取得「权限卡」\n";
cout << " 2. 使用权限卡打开服务器室的门,取得「电之芯」\n";
cout << " 3. 前往数据核心,使用电之芯和权限卡合成「科技密钥」\n";
} else if (!flags["temporal_anchor_done"]) {
cout << " ● 第四阶段(密室界): 从传送门枢纽向南进入密室界\n";
cout << " 1. 通过尘封回廊,进入七巧机关室 (提示: 左三右七)\n";
cout << " 2. 进入命运天平室,调整重量平衡,取得「时之砂」\n";
cout << " 3. 前往古代王座之间,使用时之砂合成「时空之锚」\n";
} else if (!flags["final_spell_known"]) {
cout << " ● 最终阶段: 前往「裂痕圣堂」,使用三件圣物融合习得终极咒语,然后去「起源之间」念出咒语!\n";
} else {
cout << " ● 你已习得终极咒语,快去「起源之间」念出 'Aeternum Liberare' 终结诅咒!\n";
}
cout << "============================================================\n";
}
// ======================= 核心交互逻辑 =======================
// 处理拾取物品
void handleTake(const string& item) {
if (item.empty()) {
cout << "你想拿什么? 格式: take <物品名>\n";
return;
}
if (!itemInRoom(currentRoom, item)) {
cout << "这里没有 [" << item << "] 可以拿。\n";
return;
}
// 特殊剧情判定: 例如三界钥匙需要先读日记才能在禁书密室看见 (实际上已通过房间存在实现)
// 直接拾取
inventory.insert(item);
removeItemFromRoom(currentRoom, item);
cout << "你拿起了:" << item;
if (item == "tri_key") cout << " (三界钥匙 闪耀着三色光芒)";
else if (item == "wind_feather") cout << " (风之羽 轻盈如幻)";
else if (item == "fire_stone") cout << " (焰心结晶 掌心微热)";
cout << "\n";
}
// 处理使用物品 (合成、开门等核心逻辑)
void handleUse(const string& item) {
if (item.empty()) {
cout << "你想使用什么? 格式: use <物品>\n";
return;
}
if (!hasItem(item)) {
cout << "你身上没有 [" << item << "] 可用。\n";
return;
}
// ---------- 1. 使用三界钥匙激活传送门枢纽 ----------
if (item == "tri_key" && currentRoom == "portal_hub" && !flags["portal_activated"]) {
cout << "你将三界钥匙插入枢纽中央的凹槽,三色光芒交织,传送阵轰然启动!你获得了「旅行者徽章」。\n";
flags["portal_activated"] = true;
inventory.insert("traveler_badge");
// 开启前往三界的出口
rooms["portal_hub"].exits["north"] = "magic_forest_entrance";
rooms["portal_hub"].exits["east"] = "metro_station";
rooms["portal_hub"].exits["south"] = "dust_corridor";
cout << "传送门已开启: 北->魔幻界, 东->都市界, 南->密室界\n";
return;
}
// ---------- 2. 在魔幻界祭坛合成自然之息 ----------
if (currentRoom == "stone_sword_altar" && !flags["nature_breath_done"]) {
if (hasItem("wind_feather") && hasItem("fire_stone")) {
cout << "你将风之羽和焰心结晶放在石中剑祭坛上,剑身爆发炫光,两者融合成「自然之息」!\n";
inventory.erase("wind_feather");
inventory.erase("fire_stone");
inventory.insert("nature_breath");
flags["nature_breath_done"] = true;
cout << "※ 获得了圣物之一:自然之息\n";
return;
} else {
cout << "你缺少合成所需的「风之羽」或「焰心结晶」。请确保你已经拿到了这两样物品。\n";
return;
}
}
// ---------- 3. 在都市界数据核心合成科技密钥 ----------
if (currentRoom == "data_core" && !flags["tech_key_done"]) {
if (hasItem("electric_core") && hasItem("access_card")) {
cout << "你插入权限卡,电之芯释放出脉冲数据流,两者融合成「科技密钥」!\n";
inventory.erase("electric_core");
inventory.erase("access_card");
inventory.insert("tech_key");
flags["tech_key_done"] = true;
cout << "※ 获得了圣物之二:科技密钥\n";
return;
} else {
cout << "缺少电之芯或权限卡,无法合成科技密钥。\n";
return;
}
}
// ---------- 4. 在密室界王座之间合成时空之锚 ----------
if (currentRoom == "ancient_throne" && flags["balance_solved"] && !flags["temporal_anchor_done"]) {
if (hasItem("time_sand")) {
cout << "你将时之砂倒入王座的沙漏机关,时空之力凝聚,形成「时空之锚」!\n";
inventory.erase("time_sand");
inventory.insert("temporal_anchor");
flags["temporal_anchor_done"] = true;
cout << "※ 获得了圣物之三:时空之锚\n";
return;
} else {
cout << "你没有时之砂。需要先破解天平机关取得。\n";
return;
}
}
// ---------- 5. 使用权限卡开启服务器室的门 ----------
if (item == "access_card" && currentRoom == "roof_office" && !flags["server_door_open"]) {
cout << "你刷了一下权限卡,通往地下服务器室的门解锁了!\n";
rooms["roof_office"].exits["down"] = "server_room";
flags["server_door_open"] = true;
return;
}
// 通用使用提示
cout << "你使用了 " << item << " ,但似乎没产生任何效果。\n";
}
// 处理阅读 (获取重要线索)
void handleRead(const string& target) {
if (target.empty()) {
cout << "阅读什么? (例如 read diary)\n";
return;
}
// 阅读日记 (图书馆大厅)
if (target == "diary" && (hasItem("diary") || itemInRoom(currentRoom, "diary"))) {
cout << "\n你翻开泛黄的日记,最后一页写道:\n";
cout << "「三界之钥藏在最初的大厅背后的禁书密室,只有领悟诅咒的真意才能看见。」\n";
cout << "「魔幻、都市、密室,三件圣物合一时,最终咒语便会浮现...」\n";
cout << "并且在页脚有一个古老的单词: Aeternum Liberare\n";
if (!flags["spell_clue_known"]) {
flags["spell_clue_known"] = true;
cout << "※ 你获得了一条重要线索!现在禁书密室里的三界钥匙显现出来了。\n";
// 确保三界钥匙出现在禁书密室 (如果还没有)
if (!itemInRoom("forbidden_study", "tri_key") && !hasItem("tri_key")) {
addItemToRoom("forbidden_study", "tri_key");
}
// 同时解锁大厅到禁书密室的门 (如果还没开)
if (rooms["library_hall"].exits.find("east") == rooms["library_hall"].exits.end()) {
rooms["library_hall"].exits["east"] = "forbidden_study";
cout << "大厅东侧的门现在可以通行了!\n";
}
}
return;
}
// 阅读石中剑祭坛的石碑
if (target == "stone_tablet" && currentRoom == "stone_sword_altar") {
cout << "石碑上刻着:『风与火交织,诞生自然之息,方可撼动龙峰之心』\n";
cout << "(你明白了:需要将风之羽和焰心结晶在此祭坛上融合)\n";
flags["magic_realm_ready"] = true;
return;
}
// 阅读数据核心的电脑
if (target == "computer" && currentRoom == "data_core") {
cout << "屏幕上显示: 「系统需要电之芯与最高权限卡同时验证才能解码核心数据。」\n";
flags["urban_ready"] = true;
return;
}
// 阅读天平室的铭文
if (target == "inscription" && currentRoom == "balance_hall") {
cout << "墙上的铭文: 『左三右七,光暗平,天平衡,时之砂现。』\n";
cout << "(提示:你需要让天平左右重量相等,左边放3个砝码,右边放7个砝码?不,文字可能指的是数量比例,试试移动两边砝码使平衡)\n";
return;
}
cout << "无法阅读 " << target << "。\n";
}
// 处理仔细观察 (获得隐藏信息)
void handleExamine(const string& target) {
if (target.empty()) {
cout << "仔细观察什么? (examine door, examine tree...)\n";
return;
}
if (target == "door" && currentRoom == "library_hall") {
cout << "这是一扇沉重的橡木门,雕刻着复杂的魔法阵。锁孔形状奇特,像是需要三棱形钥匙。\n";
if (!flags["spell_clue_known"]) {
cout << "也许日记里会有关于钥匙的线索。\n";
}
return;
}
if (target == "fountain" && currentRoom == "magic_forest_entrance") {
cout << "泉水清澈见底,倒映着另一片天空,似乎有精灵的低语。你隐约看到树屋的方向。\n";
return;
}
if (target == "server" && currentRoom == "server_room") {
cout << "巨大的服务器阵列中,有一个插槽空着,似乎需要「电之芯」。\n";
return;
}
if (target == "balance" && currentRoom == "balance_hall") {
cout << "这是一个精密的黄金天平。左边托盘上有3个1g砝码,右边托盘上有7个1g砝码。它显然不平衡。\n";
cout << "你可以尝试移动砝码使左右重量相等,然后时之砂就会出现。\n";
if (!flags["balance_solved"]) {
cout << "试试用指令 'use left' 或 'use right' 来移动砝码?不,更简单:输入 'solve balance' 即可自动解谜(为了游戏流畅)。\n";
}
return;
}
if (target == "dragon" && currentRoom == "dragon_peak") {
cout << "智慧巨龙睁开一只眼睛,低沉地说:『你已经有了风之羽,那就拿去焰心结晶吧,去完成你的使命。』\n";
// 如果玩家还没有拿火之石,则直接给予
if (!hasItem("fire_stone") && itemInRoom("dragon_peak", "fire_stone")) {
cout << "巨龙吐出一块炽热的晶石,落在你面前。\n";
// 自动拾取或者需要玩家再take,这里为了方便,直接加入背包并从房间移除
inventory.insert("fire_stone");
removeItemFromRoom("dragon_peak", "fire_stone");
cout << "你获得了「焰心结晶」!\n";
}
return;
}
// 通用房间详细描述
if (rooms.count(currentRoom) && !rooms[currentRoom].examineDetail.empty()) {
cout << rooms[currentRoom].examineDetail << "\n";
return;
}
cout << "你仔细端详 " << target << ",没有特别的发现。\n";
}
// 处理移动 (包含特殊条件解锁)
void handleGo(const string& direction) {
if (direction.empty()) {
cout << "去哪里? (可用方向: north, south, east, west, up, down)\n";
return;
}
auto& exits = rooms[currentRoom].exits;
if (exits.find(direction) != exits.end()) {
string nextRoom = exits[direction];
// 特殊移动限制: 已全部移除死锁,仅保留合理剧情锁
// 例如进入巨龙之峰不再需要自然之息,只需要有风之羽或直接可进
// 这里无需额外条件,直接移动
currentRoom = nextRoom;
cout << "你向 " << direction << " 移动...\n";
showLocation();
} else {
cout << "你不能往 " << direction << " 走。\n";
}
}
// 处理咒语 (胜利关键)
void handleSay(const string& words) {
if (words.empty()) {
cout << "你想要念什么咒语? say <词句>\n";
return;
}
string spell = toLower(words);
// 最终胜利判定
if (currentRoom == "origin_hall" && flags["final_spell_known"]) {
if (spell == "aeternum liberare") {
cout << "\n✨✨✨ 你高举三件圣物,念出终极咒语「Aeternum Liberare」 ✨✨✨\n";
cout << "三界的裂痕瞬间缝合,诅咒烟消云散,光芒中你看见图书馆恢复宁静,阳光洒落。\n";
cout << "你成功打破了三界诅咒,成为了传说中的「时之救赎者」!\n";
cout << "??? 恭喜通关! ???\n";
exit(0);
} else {
cout << "咒语没有产生效果。也许需要「最终圣言」?\n";
}
}
else if (currentRoom == "crack_sanctuary" && hasItem("nature_breath") && hasItem("tech_key") && hasItem("temporal_anchor") && !flags["final_spell_known"]) {
if (spell == "unite") {
cout << "三件圣物共鸣,融合成一道金色符文,刻入你的灵魂中。你悟得了终极咒语:Aeternum Liberare!\n";
flags["final_spell_known"] = true;
cout << "现在请前往「起源之间」念出真言结束一切。\n";
} else {
cout << "念错了,没有反应。试试 'unite' 来融合圣物?\n";
}
}
else {
cout << "你念出了 \"" << words << "\",什么也没有发生。\n";
}
}
// 特殊处理天平谜题 (为了不卡关,提供简单解法指令)
void handleSolveBalance() {
if (currentRoom != "balance_hall") {
cout << "这里没有天平可以解。\n";
return;
}
if (flags["balance_solved"]) {
cout << "天平已经平衡过了,时之砂已经被取走。\n";
return;
}
// 解法: 左边拿掉2个砝码,右边拿掉6个砝码,或者移动等。简单起见,直接设置为平衡并给出时之砂
cout << "你小心翼翼地移动砝码,使天平左右重量相等(左边3g,右边3g)。\n";
cout << "天平微微震动,托盘下方出现了一个暗格,里面躺着一瓶「时之砂」!\n";
flags["balance_solved"] = true;
// 将时之砂添加到当前房间
if (!itemInRoom("balance_hall", "time_sand")) {
addItemToRoom("balance_hall", "time_sand");
}
cout << "你现在可以 'take time_sand' 取走时之砂了。\n";
}
// 显示帮助信息
void showHelp() {
cout << "\n========== 指 令 帮 助 ==========\n";
cout << "look 观察当前房间\n";
cout << "inventory / i 查看背包\n";
cout << "take <物品> 拾取物品 (如 take diary)\n";
cout << "use <物品> 使用物品 (如 use tri_key)\n";
cout << "read <物品/文字> 阅读 (read diary, read stone_tablet)\n";
cout << "examine <目标> 仔细观察 (examine dragon, examine balance)\n";
cout << "go <方向> 移动 (north/south/east/west/up/down)\n";
cout << "say <咒语> 念咒语 (say unite, say aeternum liberare)\n";
cout << "solve balance 解开天平谜题 (直接获得时之砂)\n";
cout << "quest 查看任务提示\n";
cout << "help 显示此帮助\n";
cout << "quit 离开游戏\n";
cout << "================================\n";
cout << "提示: 请多使用 'examine' 和 'read' 来获取线索。\n";
}
// ======================= 构建完整游戏世界 =======================
void buildWorld() {
// ---------- 第一幕:图书馆区域 (4房间) ----------
rooms["library_hall"] = {
"古老图书馆大厅",
"你站在宏伟的大厅中央,穹顶高耸,书架排列如迷宫。空气中弥漫着魔法与尘埃的味道。\n一张破旧的桌子上放着一本日记,东侧有一扇封印的门。",
{}, // 初始无出口,读日记后开启东门
"书架角落有微光闪烁,好像藏着什么。"
};
rooms["forbidden_study"] = {
"禁书密室",
"狭小的密室,中央悬浮着「封印之书」,四壁是禁咒卷轴。这里似乎还隐藏着通向更深处的地下秘库。",
{{"west", "library_hall"}, {"down", "underground_vault"}},
"书架上有一个暗格,隐约露出三色光芒。"
};
rooms["underground_vault"] = {
"地下秘库",
"昏暗的地下石室,墙上绘着三界地图。正中央有一尊破碎的传送门基座,似乎缺少钥匙。",
{{"up", "forbidden_study"}, {"south", "portal_hub"}},
"地面上散落着一些符文,中心凹槽是三棱形。"
};
rooms["portal_hub"] = {
"传送门枢纽",
"一个宏伟的圆厅,三座巨大的传送门围绕着中心控制台。目前全部黯淡无光,需要「三界钥匙」激活。",
{{"west", "underground_vault"}},
"控制台上刻着古字:『集三界圣物者,方可破灭诅咒』。"
};
// 物品初始化
addItemToRoom("library_hall", "diary");
// 三界钥匙初始不在任何地方,等读日记后才出现
// 其它物品稍后
// 初始标志
flags["portal_activated"] = false;
flags["nature_breath_done"] = false;
flags["tech_key_done"] = false;
flags["temporal_anchor_done"] = false;
flags["final_spell_known"] = false;
flags["balance_solved"] = false;
flags["server_door_open"] = false;
flags["hall_door_unlocked"] = false; // 读日记后解锁
// ---------- 第二幕:魔幻界 (5房间) ----------
rooms["magic_forest_entrance"] = {
"迷雾森林入口",
"参天古树环绕,雾气氤氲。一条小径向北通往精灵树屋,西侧是石中剑祭坛,东侧是巨龙之峰的方向。",
{{"north", "elf_treehouse"}, {"west", "stone_sword_altar"}, {"east", "dragon_peak"}},
"泉水中倒映着古老的预言。"
};
rooms["elf_treehouse"] = {
"精灵树屋",
"精致的树屋,书架上有魔法羽毛。精灵早已离去,留下一枚「风之羽」。",
{{"south", "magic_forest_entrance"}},
"窗户旁有风铃,轻轻作响。"
};
addItemToRoom("elf_treehouse", "wind_feather");
rooms["stone_sword_altar"] = {
"石中剑祭坛",
"古旧的石坛上插着一把锈剑,周围有石碑刻着合成自然之息的指引。",
{{"east", "magic_forest_entrance"}},
"石碑上刻着古老的文字。"
};
// 此房间没有初始物品,但石碑可读
rooms["dragon_peak"] = {
"巨龙之峰",
"云雾缭绕的山巅,智慧巨龙盘踞。它似乎愿意帮助你。",
{{"west", "magic_forest_entrance"}},
"巨龙的眼睛如同燃烧的琥珀。"
};
addItemToRoom("dragon_peak", "fire_stone"); // 焰心结晶直接放在地上,不需要复杂交互
// 辅助标志
flags["magic_realm_ready"] = false;
// ---------- 第三幕:都市界 (4房间) ----------
rooms["metro_station"] = {
"废弃地铁站",
"昏暗的地下铁,轨道尽头有通往数据核心的电梯,但需要验证。",
{{"west", "portal_hub"}, {"south", "data_core"}},
"角落有一张遗弃的工牌,可能有用。"
};
rooms["data_core"] = {
"虚拟数据核心",
"蓝光闪烁的机房,核心终端显示需要双重认证。",
{{"north", "metro_station"}, {"up", "roof_office"}},
"终端提示:『电之芯与权限卡缺一不可』。"
};
rooms["roof_office"] = {
"摩天楼顶层办公室",
"落地窗外是都市夜景,办公桌上有一张「权限卡」。",
{}, // 出口后由使用权限卡添加
"抽屉里有服务器室的地图。"
};
addItemToRoom("roof_office", "access_card");
rooms["server_room"] = {
"地下服务器室",
"巨大的服务器阵列轰鸣,中央插槽正等待「电之芯」。",
{{"up", "roof_office"}},
"拔下电之芯会让服务器短暂停机。"
};
addItemToRoom("server_room", "electric_core");
// 都市界初始出口:从data_core可以上楼到roof_office,但roof_office下楼需要权限卡
rooms["data_core"].exits["up"] = "roof_office";
// server_room入口暂时隐藏,由权限卡开启
// ---------- 第四幕:密室界 (4房间) ----------
rooms["dust_corridor"] = {
"尘封回廊",
"铺满灰尘的长廊,两侧是古代壁画,尽头有一道石门。",
{{"north", "portal_hub"}, {"south", "puzzle_chamber"}},
"壁画描绘了天平的秘密。"
};
rooms["puzzle_chamber"] = {
"七巧机关室",
"石室中有一块拼图墙,缺若干块。根据「左三右七」的提示你轻松解开了机关。",
{{"north", "dust_corridor"}, {"south", "balance_hall"}},
"墙上有可移动的符文块。"
};
// 自动解开七巧机关,不设复杂谜题
rooms["balance_hall"] = {
"命运天平室",
"巨大的黄金天平,左右各有托盘。必须左右重量相等才能开启下一道门。",
{{"north", "puzzle_chamber"}, {"south", "ancient_throne"}},
"地上散落着砝码,天平尚未平衡。"
};
// 时之砂初始不在,需要解balance谜题后添加
rooms["ancient_throne"] = {
"古代王座之间",
"威严的王座背后是时之沙漏,一旦获得时之砂就可合成最终圣物。",
{{"north", "balance_hall"}},
"王座扶手上刻着『时之砂,启真言』。"
};
// ---------- 第五幕:终章 (3房间) ----------
rooms["crack_sanctuary"] = {
"裂痕圣堂",
"三界裂痕交汇之处,漂浮着三个圣物祭坛。你可以在此融合三件圣物。",
{{"west", "ancient_throne"}, {"north", "origin_hall"}},
"中央符文流转,等待勇者跪拜。"
};
rooms["element_altar"] = {
"元素融合祭坛",
"这里可以将自然之息、科技密钥、时空之锚融合成终极咒语种子。",
{{"east", "crack_sanctuary"}},
"祭坛表面有unite字样。"
};
rooms["origin_hall"] = {
"起源之间",
"时间与空间的起点,巨大的水晶中倒映着你的身影。只有真正的救世主才能终结一切。",
{{"south", "crack_sanctuary"}},
"水晶上闪烁着古老的符文。"
};
// 确保旅行者徽章等不初始存在
}
// ======================= 游戏初始化与主循环 =======================
int main() {
system("chcp 65001 > nul"); // 支持UTF-8 (Windows)
buildWorld();
cout << "================================================================\n";
cout << " 【被诅咒的图书馆:三界咏叹调】\n";
cout << " 一部恢弘的多世界解谜史诗\n";
cout << "================================================================\n";
cout << "残破的书页在你身边飘落,你终于明白诅咒不只是困住一座图书馆。\n";
cout << "三界的裂痕需要你来修复。魔幻、都市、密室——三个世界,三种圣物,\n";
cout << "一段穿越维度的救赎之旅就此展开。\n";
cout << "键入 'help' 查看指令,'quest' 查看任务,'look' 开始探险。\n";
// 初始场景特殊处理: 大厅门需要阅读日记解锁,方便教学
cout << "\n【提示】桌上的旧日记闪着微光,或许应该先试试 'read diary'。\n";
currentRoom = "library_hall";
showLocation();
string input;
while (true) {
cout << "\n> ";
getline(cin, input);
if (input.empty()) continue;
auto [verb, arg] = parseCommand(input);
if (verb == "quit") {
cout << "你放弃了拯救三界的使命,诅咒永存......游戏结束。\n";
break;
} else if (verb == "look") {
showLocation();
} else if (verb == "inventory" || verb == "i") {
showInventory();
} else if (verb == "take") {
handleTake(arg);
} else if (verb == "use") {
handleUse(arg);
} else if (verb == "read") {
handleRead(arg);
} else if (verb == "examine") {
handleExamine(arg);
} else if (verb == "go") {
handleGo(arg);
} else if (verb == "say") {
handleSay(arg);
} else if (verb == "quest") {
showQuest();
} else if (verb == "solve" && arg == "balance") {
handleSolveBalance();
} else if (verb == "help") {
showHelp();
} else {
cout << "未知指令。输入 'help' 获得帮助。\n";
}
}
return 0;
}无尽地下城
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <memory>
#include <tuple>
#include <chrono>
#include <thread>
#ifdef _WIN32
#include <windows.h>
#include <conio.h>
#define USE_WINDOWS
#else
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
char _getch() {
struct termios oldt, newt;
char ch;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
}
#endif
using namespace std;
const int MAP_WIDTH = 20;
const int MAP_HEIGHT = 15;
enum Direction { UP, DOWN, LEFT, RIGHT };
enum TileType { TILE_EMPTY, TILE_WALL, TILE_STAIR, TILE_WEAPON };
// 光标定位 (Windows 和 Linux/macOS)
void gotoxy(int x, int y) {
#ifdef USE_WINDOWS
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
#else
printf("\033[%d;%dH", y+1, x+1);
#endif
}
void hideCursor() {
#ifdef USE_WINDOWS
CONSOLE_CURSOR_INFO cursorInfo;
GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
cursorInfo.bVisible = false;
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
#else
printf("\033[?25l");
#endif
}
void showCursor() {
#ifdef USE_WINDOWS
CONSOLE_CURSOR_INFO cursorInfo;
GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
cursorInfo.bVisible = true;
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
#else
printf("\033[?25h");
#endif
}
void sleep_ms(int ms) {
this_thread::sleep_for(chrono::milliseconds(ms));
}
// ---------- 武器 ----------
class Weapon {
public:
string name;
int attackBonus;
Weapon() : name("拳头"), attackBonus(0) {}
Weapon(string n, int bonus) : name(n), attackBonus(bonus) {}
};
// ---------- 技能 ----------
struct Skill {
string name;
int mpCost;
float multiplier;
int range;
string desc;
Skill() : range(1) {}
Skill(string n, int cost, float mult, int r, string d)
: name(n), mpCost(cost), multiplier(mult), range(r), desc(d) {}
};
// ---------- 怪物 ----------
class Monster {
public:
string name;
string symbol;
int hp, maxHp, atk, def, expReward;
bool isBoss;
int x, y;
Monster() : isBoss(false) {}
Monster(string n, string sym, int hp, int atk, int def, int exp, bool boss = false)
: name(n), symbol(sym), hp(hp), maxHp(hp), atk(atk), def(def), expReward(exp), isBoss(boss) {}
bool isAlive() const { return hp > 0; }
void takeDamage(int dmg) { hp -= dmg; if (hp < 0) hp = 0; }
string getDisplay() const {
string disp = symbol;
while (disp.length() < 3) disp += " ";
return disp + " ";
}
};
vector<Monster> normalMonsters = {
{"史莱姆", "Sl", 25, 6, 2, 30, false},
{"兽人", "Or", 45, 10, 3, 55, false},
{"骷髅", "Sk", 35, 12, 2, 50, false},
{"巨魔", "Tr", 70, 14, 5, 90, false},
{"暗影", "Sh", 55, 16, 4, 100, false}
};
vector<Monster> bossMonsters = {
{"石魔像", "Bs", 180, 25, 12, 300, true},
{"龙骑士", "Bd", 220, 30, 15, 400, true},
{"暗黑领主","Bl", 280, 35, 18, 500, true}
};
enum ClassType { ASSASSIN, WARRIOR, MAGE, ARCHER };
struct ClassInfo {
string name;
int baseHp, baseMp, baseAtk, baseDef;
vector<Skill> skills;
ClassInfo() {}
ClassInfo(string n, int hp, int mp, int atk, int def, vector<Skill> sk)
: name(n), baseHp(hp), baseMp(mp), baseAtk(atk), baseDef(def), skills(sk) {}
};
vector<ClassInfo> classDB = {
ClassInfo("刺客", 85, 60, 15, 4, {
Skill("",0,1.0f,1,""),
Skill("背刺", 8, 2.2f, 1, "220%伤害,相邻"),
Skill("疾风斩", 12, 1.6f, 1, "160%连击"),
Skill("暗影步", 10, 1.8f, 2, "180%伤害,距离2")
}),
ClassInfo("战士", 130, 40, 14, 8, {
Skill("",0,1.0f,1,""),
Skill("重击", 7, 2.0f, 1, "200%伤害"),
Skill("旋风斩", 12, 1.7f, 1, "170%近战"),
Skill("破甲", 9, 1.5f, 1, "150%破甲")
}),
ClassInfo("法师", 75, 90, 10, 3, {
Skill("",0,1.0f,1,""),
Skill("火球术", 9, 2.4f, 3, "240%火焰,距离3"),
Skill("冰锥", 11, 2.0f, 2, "200%冰冻,距离2"),
Skill("雷击", 14, 2.8f, 3, "280%闪电,距离3")
}),
ClassInfo("射手", 90, 55, 13, 5, {
Skill("",0,1.0f,1,""),
Skill("连射", 8, 1.9f, 3, "190%两次,距离3"),
Skill("穿透箭", 10, 2.2f, 4, "220%穿透,距离4"),
Skill("爆裂箭", 12, 2.5f, 3, "250%爆炸,距离3")
})
};
// ---------- 玩家 ----------
class Player {
public:
string name;
ClassType classType;
int level, exp, expToNext;
int hp, maxHp, mp, maxMp;
int baseAtk, def;
Weapon weapon;
vector<Skill> skills;
int skillCount;
Player() {
level = 1; exp = 0; expToNext = 100;
baseAtk = 10; def = 5;
weapon = Weapon("木剑", 3);
skillCount = 3;
}
void init(ClassType ct) {
classType = ct;
ClassInfo& ci = classDB[ct];
name = ci.name;
maxHp = ci.baseHp; hp = maxHp;
maxMp = ci.baseMp; mp = maxMp;
baseAtk = ci.baseAtk;
def = ci.baseDef;
skills = ci.skills;
}
int totalAtk() const { return baseAtk + weapon.attackBonus; }
void gainExp(int amount) {
exp += amount;
int oldLevel = level;
while (exp >= expToNext) {
exp -= expToNext;
level++;
maxHp += 12; hp = maxHp;
maxMp += 6; mp = maxMp;
baseAtk += 2; def += 2;
expToNext = (int)(expToNext * 1.2);
}
if (level > oldLevel) {
gotoxy(0, MAP_HEIGHT*2+8);
cout << "★ 升级 Lv." << level << " ★ 生命+12 魔力+6 攻击+2 防御+2 \n";
sleep_ms(500);
} else {
gotoxy(0, MAP_HEIGHT*2+8);
cout << "获得 " << amount << " 经验! \n";
sleep_ms(300);
}
}
bool useSkill(int idx) {
if (idx < 1 || idx > skillCount) return false;
if (mp >= skills[idx].mpCost) {
mp -= skills[idx].mpCost;
return true;
}
gotoxy(0, MAP_HEIGHT*2+8);
cout << "MP不足! 需要 " << skills[idx].mpCost << " MP \n";
sleep_ms(500);
return false;
}
void showStatus() const {
cout << "\n┌─────────────────────────────────────┐\n";
cout << "│ Lv." << level << " " << name << string(28 - to_string(level).length() - name.length(), ' ') << "│\n";
cout << "│ HP: " << hp << "/" << maxHp << string(24 - to_string(hp).length() - to_string(maxHp).length(), ' ') << "│\n";
cout << "│ MP: " << mp << "/" << maxMp << string(24 - to_string(mp).length() - to_string(maxMp).length(), ' ') << "│\n";
cout << "│ 攻击:" << totalAtk() << " (+" << weapon.attackBonus << ") 防:" << def << string(14, ' ') << "│\n";
cout << "│ 武器:" << weapon.name << string(21 - weapon.name.length(), ' ') << "│\n";
cout << "│ 技能1:" << skills[1].name << "(" << skills[1].mpCost << "MP, 距离" << skills[1].range << ")│\n";
if (skillCount >= 2) cout << "│ 技能2:" << skills[2].name << "(" << skills[2].mpCost << "MP, 距离" << skills[2].range << ")│\n";
if (skillCount >= 3) cout << "│ 技能3:" << skills[3].name << "(" << skills[3].mpCost << "MP, 距离" << skills[3].range << ")│\n";
cout << "└─────────────────────────────────────┘\n";
}
};
// ---------- 地图格子 ----------
struct MapCell {
TileType type;
shared_ptr<Monster> monster;
Weapon* weaponItem;
MapCell() : type(TILE_EMPTY), monster(nullptr), weaponItem(nullptr) {}
~MapCell() { delete weaponItem; }
};
// ---------- 游戏主类 ----------
class Game {
private:
vector<vector<MapCell>> map;
int playerX, playerY;
int currentLevel;
int remainingMonsters;
Player player;
bool gameRunning;
vector<Weapon> weaponDrops;
void setCellContent(int x, int y, const string& content) {
string disp = content;
if (disp.length() < 4) disp += string(4 - disp.length(), ' ');
int col = 1 + x * 4;
int row = 4 + y * 2;
gotoxy(col, row);
cout << disp;
}
string getCellContent(int x, int y) const {
return getCellDisplay(x, y);
}
void showProjectile(int fromX, int fromY, int toX, int toY, const string& symbol) {
int dx = (toX - fromX == 0) ? 0 : (toX - fromX > 0 ? 1 : -1);
int dy = (toY - fromY == 0) ? 0 : (toY - fromY > 0 ? 1 : -1);
int steps = max(abs(toX - fromX), abs(toY - fromY));
int x = fromX, y = fromY;
for (int i = 1; i <= steps; ++i) {
x += dx; y += dy;
string saved = getCellContent(x, y);
string proj = " " + symbol + " ";
setCellContent(x, y, proj);
sleep_ms(50);
setCellContent(x, y, saved);
}
}
public:
Game() {
srand((unsigned)time(nullptr));
initWeaponDrops();
currentLevel = 1;
gameRunning = true;
hideCursor();
showTitleAndSelectClass();
generateMap();
}
~Game() {
showCursor();
gotoxy(0, MAP_HEIGHT*2+12);
}
void initWeaponDrops() {
weaponDrops = {
{"铁剑", 7}, {"钢刃", 10}, {"火焰刀", 14}, {"冰霜剑", 12},
{"龙鳞剑", 18}, {"暗影匕首", 16}, {"长弓", 9}, {"法杖", 8},
{"巨斧", 15}, {"圣剑", 22}
};
}
void showTitleAndSelectClass() {
system("cls");
cout << R"(
╔═══════════════════════════════════════════╗
║ 地牢探险 · 职业选择 ║
╚═══════════════════════════════════════════╝
1. 刺客 - 高爆发,可攻击距离2
2. 战士 - 坚韧,近战专精
3. 法师 - 远程法术,距离2~3
4. 射手 - 最远射程,距离3~4
请选择职业 (1-4): )";
int choice;
cin >> choice;
while (choice < 1 || choice > 4) {
cout << "无效选择,重新输入: ";
cin >> choice;
}
player.init((ClassType)(choice - 1));
cout << "\n你选择了 " << player.name << "!\n按任意键开始...";
_getch();
}
void generateMap() {
map.assign(MAP_HEIGHT, vector<MapCell>(MAP_WIDTH));
for (int i = 0; i < MAP_HEIGHT; ++i)
for (int j = 0; j < MAP_WIDTH; ++j)
if (i == 0 || i == MAP_HEIGHT-1 || j == 0 || j == MAP_WIDTH-1)
map[i][j].type = TILE_WALL;
int obstacleCount = 5 + currentLevel/3;
for (int k = 0; k < obstacleCount; ++k) {
int x = rand() % (MAP_WIDTH-2) + 1;
int y = rand() % (MAP_HEIGHT-2) + 1;
if ((x == 1 && y == 1) || (x == MAP_WIDTH-2 && y == MAP_HEIGHT-2)) continue;
if (map[y][x].type == TILE_EMPTY) map[y][x].type = TILE_WALL;
}
int normalCount = 3 + rand() % 6 + currentLevel/2;
if (normalCount > 10) normalCount = 10;
int placed = 0;
while (placed < normalCount) {
int x = rand() % (MAP_WIDTH-2) + 1;
int y = rand() % (MAP_HEIGHT-2) + 1;
if (map[y][x].type == TILE_EMPTY && !(x == 1 && y == 1)) {
int idx = rand() % normalMonsters.size();
Monster m = normalMonsters[idx];
m.maxHp = m.hp + (currentLevel-1)*8;
m.hp = m.maxHp;
m.atk += (currentLevel-1)*2;
m.def += (currentLevel-1);
m.expReward += (currentLevel-1)*10;
m.x = x; m.y = y;
map[y][x].monster = make_shared<Monster>(m);
placed++;
}
}
int bx, by;
do {
bx = rand() % (MAP_WIDTH-2) + 1;
by = rand() % (MAP_HEIGHT-2) + 1;
} while (map[by][bx].monster || map[by][bx].type != TILE_EMPTY || (bx==1 && by==1));
Monster boss = bossMonsters[rand() % bossMonsters.size()];
boss.maxHp = boss.hp + (currentLevel-1)*20;
boss.hp = boss.maxHp;
boss.atk += (currentLevel-1)*4;
boss.def += (currentLevel-1)*2;
boss.expReward += (currentLevel-1)*50;
boss.x = bx; boss.y = by;
map[by][bx].monster = make_shared<Monster>(boss);
int wx, wy;
do {
wx = rand() % (MAP_WIDTH-2) + 1;
wy = rand() % (MAP_HEIGHT-2) + 1;
} while (map[wy][wx].monster || map[wy][wx].type != TILE_EMPTY || (wx==playerX && wy==playerY));
map[wy][wx].weaponItem = new Weapon(weaponDrops[rand() % weaponDrops.size()]);
playerX = 1; playerY = 1;
if (map[1][1].monster) map[1][1].monster = nullptr;
map[1][1].type = TILE_EMPTY;
remainingMonsters = 0;
for (auto& row : map)
for (auto& cell : row)
if (cell.monster) remainingMonsters++;
}
string getCellDisplay(int x, int y) const {
if (x == playerX && y == playerY) return " P ";
auto& cell = map[y][x];
if (cell.type == TILE_WALL) return "####";
if (cell.type == TILE_STAIR) return " St ";
if (cell.weaponItem) return " Wp ";
if (cell.monster) return cell.monster->getDisplay();
return " ";
}
void drawMap() {
gotoxy(0, 0);
cout << "\n╔════════════════════════════════════════════╗\n";
cout << " 关卡 " << currentLevel << " | 剩余怪物: " << remainingMonsters << endl;
cout << "╚════════════════════════════════════════════╝\n";
for (int i = 0; i < MAP_HEIGHT; ++i) {
for (int j = 0; j < MAP_WIDTH; ++j) cout << "+---";
cout << "+\n";
for (int j = 0; j < MAP_WIDTH; ++j) cout << "|" << getCellDisplay(j, i);
cout << "|\n";
}
for (int j = 0; j < MAP_WIDTH; ++j) cout << "+---";
cout << "+\n";
cout << "\n[W/A/S/D]移动 [1]普攻 [2/3/4]技能 [Q]退出\n";
cout << "攻击/技能 按下数字后,再按方向 (远程技能有弹道)\n";
player.showStatus();
for (int i = 0; i < 4; ++i) cout << string(80, ' ') << "\n";
gotoxy(0, MAP_HEIGHT*2+8);
}
void generateStair() {
for (int attempt = 0; attempt < 200; ++attempt) {
int x = rand() % (MAP_WIDTH-2) + 1;
int y = rand() % (MAP_HEIGHT-2) + 1;
if (map[y][x].type == TILE_EMPTY && !map[y][x].monster && !map[y][x].weaponItem && !(x==playerX && y==playerY)) {
map[y][x].type = TILE_STAIR;
return;
}
}
for (int i = 1; i < MAP_HEIGHT-1; ++i)
for (int j = 1; j < MAP_WIDTH-1; ++j)
if (map[i][j].type == TILE_EMPTY && !map[i][j].monster && !map[i][j].weaponItem && !(j==playerX && i==playerY)) {
map[i][j].type = TILE_STAIR;
return;
}
}
tuple<bool, int, int, shared_ptr<Monster>> findTargetInDirection(Direction dir, int maxRange) {
int dx = 0, dy = 0;
switch(dir) {
case UP: dy = -1; break;
case DOWN: dy = 1; break;
case LEFT: dx = -1; break;
case RIGHT: dx = 1; break;
}
int x = playerX, y = playerY;
for (int step = 1; step <= maxRange; ++step) {
x += dx; y += dy;
if (x < 0 || x >= MAP_WIDTH || y < 0 || y >= MAP_HEIGHT) break;
if (map[y][x].type == TILE_WALL) break;
if (map[y][x].monster) {
return {true, x, y, map[y][x].monster};
}
}
return {false, -1, -1, nullptr};
}
bool performAttack(Direction dir, int skillIdx) {
int range = (skillIdx == 0) ? 1 : player.skills[skillIdx].range;
auto [hit, tx, ty, mon] = findTargetInDirection(dir, range);
if (!hit) {
gotoxy(0, MAP_HEIGHT*2+8);
cout << "该方向 " << range << " 格内没有怪物或已被阻挡! \n";
sleep_ms(500);
return false;
}
if (range >= 2 && skillIdx != 0) {
showProjectile(playerX, playerY, tx, ty, "●");
}
Monster& m = *mon;
int damage = 0;
if (skillIdx == 0) {
damage = max(1, player.totalAtk() - m.def);
gotoxy(0, MAP_HEIGHT*2+8);
cout << "普攻击中 " << m.name << " 造成 " << damage << " 伤害! \n";
} else {
if (!player.useSkill(skillIdx)) return false;
float mult = player.skills[skillIdx].multiplier;
damage = max(1, (int)(player.totalAtk() * mult) - m.def);
gotoxy(0, MAP_HEIGHT*2+8);
cout << "使用 " << player.skills[skillIdx].name << " 击中 " << m.name << " 造成 " << damage << " 伤害! \n";
}
m.takeDamage(damage);
sleep_ms(300);
if (!m.isAlive()) {
gotoxy(0, MAP_HEIGHT*2+9);
cout << m.name << (m.isBoss ? " BOSS" : "") << " 被击败! \n";
int expGain = m.expReward;
map[ty][tx].monster = nullptr;
remainingMonsters--;
player.gainExp(expGain);
if (remainingMonsters == 0) {
generateStair();
gotoxy(0, MAP_HEIGHT*2+10);
cout << "所有敌人清除! 楼梯出现了. \n";
sleep_ms(500);
}
return true;
} else {
int dist = abs(tx - playerX) + abs(ty - playerY);
if (dist == 1) {
int counterDmg = max(1, m.atk - player.def);
player.hp -= counterDmg;
gotoxy(0, MAP_HEIGHT*2+9);
cout << m.name << " 反击造成 " << counterDmg << " 伤害! \n";
sleep_ms(300);
if (player.hp <= 0) {
gotoxy(0, MAP_HEIGHT*2+10);
cout << "你死了...游戏结束。 \n";
gameRunning = false;
}
} else {
gotoxy(0, MAP_HEIGHT*2+9);
cout << "距离较远," << m.name << " 无法反击! \n";
sleep_ms(300);
}
return false;
}
}
// 改进的怪物移动:随机不动,随机移动,混合追击与散步
void moveAllMonsters() {
vector<tuple<shared_ptr<Monster>,int,int>> monsters;
for (int y = 0; y < MAP_HEIGHT; ++y)
for (int x = 0; x < MAP_WIDTH; ++x)
if (map[y][x].monster)
monsters.push_back({map[y][x].monster, x, y});
random_shuffle(monsters.begin(), monsters.end());
for (auto& tup : monsters) {
auto mon = get<0>(tup);
int x = get<1>(tup);
int y = get<2>(tup);
if (map[y][x].monster != mon) continue;
// 70%概率移动,30%原地不动
if (rand() % 100 >= 30) {
int dist = abs(x - playerX) + abs(y - playerY);
bool chase = (dist <= 5 && rand() % 100 < 40); // 距离5内且40%概率追击,否则随机移动
vector<pair<int,int>> dirs = {{0,-1},{0,1},{-1,0},{1,0}};
vector<pair<int,int>> valid;
for (auto& d : dirs) {
int nx = x + d.first;
int ny = y + d.second;
if (nx>=0 && nx<MAP_WIDTH && ny>=0 && ny<MAP_HEIGHT) {
if (map[ny][nx].type == TILE_EMPTY && map[ny][nx].monster == nullptr && !(nx==playerX && ny==playerY))
valid.push_back({nx, ny});
}
}
if (valid.empty()) continue;
pair<int,int> target = valid[rand() % valid.size()];
if (chase) {
int bestDist = dist;
for (auto& mv : valid) {
int d = abs(mv.first - playerX) + abs(mv.second - playerY);
if (d < bestDist) {
bestDist = d;
target = mv;
}
}
}
map[y][x].monster = nullptr;
mon->x = target.first;
mon->y = target.second;
map[target.second][target.first].monster = mon;
}
}
}
void tryMove(Direction dir) {
int nx = playerX, ny = playerY;
switch(dir) {
case UP: ny--; break;
case DOWN: ny++; break;
case LEFT: nx--; break;
case RIGHT: nx++; break;
}
if (nx<0 || nx>=MAP_WIDTH || ny<0 || ny>=MAP_HEIGHT) return;
MapCell& cell = map[ny][nx];
if (cell.type == TILE_WALL) {
gotoxy(0, MAP_HEIGHT*2+8);
cout << "墙挡住了! \n";
sleep_ms(300);
return;
}
if (cell.type == TILE_STAIR) {
gotoxy(0, MAP_HEIGHT*2+8);
cout << "\n☆ 进入下一层! ☆ \n";
sleep_ms(800);
currentLevel++;
player.hp = player.maxHp;
player.mp = player.maxMp;
generateMap();
return;
}
if (cell.monster) {
performAttack(dir, 0);
if (!gameRunning) return;
if (map[ny][nx].monster == nullptr && map[ny][nx].type != TILE_WALL) {
playerX = nx; playerY = ny;
}
moveAllMonsters();
return;
}
if (cell.weaponItem) {
gotoxy(0, MAP_HEIGHT*2+8);
cout << "发现武器: " << cell.weaponItem->name << " (+" << cell.weaponItem->attackBonus << ") ";
cout << "替换 " << player.weapon.name << "? (y/n): ";
char ch; cin >> ch;
if (ch=='y'||ch=='Y') {
player.weapon = *cell.weaponItem;
cout << "装备了 " << player.weapon.name << "! \n";
}
delete cell.weaponItem;
cell.weaponItem = nullptr;
sleep_ms(500);
}
playerX = nx; playerY = ny;
moveAllMonsters();
}
void handleAttack(int skillIdx) {
gotoxy(0, MAP_HEIGHT*2+8);
cout << "选择攻击方向 (W/A/S/D): ";
char dirKey = _getch();
Direction dir;
switch(dirKey) {
case 'w': case 'W': dir = UP; break;
case 's': case 'S': dir = DOWN; break;
case 'a': case 'A': dir = LEFT; break;
case 'd': case 'D': dir = RIGHT; break;
default:
gotoxy(0, MAP_HEIGHT*2+8);
cout << "无效方向 \n";
sleep_ms(500);
return;
}
performAttack(dir, skillIdx);
if (gameRunning) moveAllMonsters();
}
void processInput() {
char input = _getch();
switch(input) {
case 'w': case 'W': tryMove(UP); break;
case 's': case 'S': tryMove(DOWN); break;
case 'a': case 'A': tryMove(LEFT); break;
case 'd': case 'D': tryMove(RIGHT); break;
case '1': handleAttack(0); break;
case '2': handleAttack(1); break;
case '3': if (player.skillCount >= 2) handleAttack(2); else { gotoxy(0, MAP_HEIGHT*2+8); cout << "技能未解锁 "; sleep_ms(500); } break;
case '4': if (player.skillCount >= 3) handleAttack(3); else { gotoxy(0, MAP_HEIGHT*2+8); cout << "技能未解锁 "; sleep_ms(500); } break;
case 'q': case 'Q': gameRunning = false; break;
default: break;
}
}
void run() {
while (gameRunning && player.hp > 0) {
drawMap();
processInput();
if (player.hp <= 0) gameRunning = false;
}
gotoxy(0, MAP_HEIGHT*2+12);
cout << (player.hp <= 0 ? "游戏结束...\n" : "感谢游玩!\n");
showCursor();
}
};
int main() {
Game game;
game.run();
return 0;
}月圆之夜
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#include <random>
using namespace std;
enum EffectType {
DEAL_DAMAGE, GAIN_BLOCK, HEAL_HP, DRAW_CARD,
GAIN_MANA, DISCARD_CARD, ADD_CARD_TO_DECK, MULTI_HIT, BURN, POISON, WEAK, NONE
};
enum JobType { WARRIOR, WITCH, PRIEST, ROGUE };
enum NodeType { NODE_MONSTER, NODE_SHOP, NODE_SPECIAL };
// 卡牌
struct CardData
{
int id;
string name;
int cost;
EffectType effect;
int effectValue;
string desc;
CardData() {}
CardData(int i, string n, int c, EffectType e, int v, string d)
: id(i), name(n), cost(c), effect(e), effectValue(v), desc(d) {}
};
// 怪物技能
struct MonsterCard
{
string name;
int damage;
int block;
string desc;
MonsterCard(string n, int d, int b, string desc)
: name(n), damage(d), block(b), desc(desc) {}
};
// 怪物
struct MonsterData
{
int id;
string name;
int maxHp;
string chapter;
string intro;
vector<MonsterCard> skills;
MonsterData() {}
MonsterData(int i, string n, int hp, string ch, string in)
: id(i), name(n), maxHp(hp), chapter(ch), intro(in) {}
void addSkill(string n, int d, int b, string desc)
{
skills.emplace_back(n, d, b, desc);
}
};
// 章节节点
struct ChapterNode
{
NodeType type;
ChapterNode(NodeType t) : type(t) {}
};
class GameDatabase
{
public:
map<int, CardData> allCards;
map<int, MonsterData> allMonsters;
GameDatabase()
{
initCards();
initMonsters();
}
// ========== 大量新增全职业卡牌 ==========
void initCards()
{
// 战士
allCards[101] = CardData(101, "重击", 1, DEAL_DAMAGE, 6, "造成6点伤害");
allCards[102] = CardData(102, "盾挡", 1, GAIN_BLOCK, 7, "获得7点护甲");
allCards[103] = CardData(103, "顺劈斩", 2, DEAL_DAMAGE, 14, "造成14点伤害");
allCards[104] = CardData(104, "战吼", 0, DRAW_CARD, 2, "抽2张牌");
allCards[105] = CardData(105, "铁壁", 2, GAIN_BLOCK, 15, "获得15点护甲");
allCards[106] = CardData(106, "旋风斩", 2, MULTI_HIT, 4, "4次4点伤害");
allCards[107] = CardData(107, "勇气", 0, GAIN_MANA, 3, "获得3点法力");
allCards[108] = CardData(108, "反击", 1, DEAL_DAMAGE, 8, "造成8点伤害");
allCards[109] = CardData(109, "狂暴", 1, DEAL_DAMAGE, 20, "造成20点伤害");
allCards[110] = CardData(110, "绝对防御", 3, GAIN_BLOCK, 30, "获得30点护甲");
allCards[111] = CardData(111, "猛撞", 1, DEAL_DAMAGE, 9, "造成9点伤害");
allCards[112] = CardData(112, "坚守", 1, GAIN_BLOCK, 10, "获得10点护甲");
// 女巫
allCards[201] = CardData(201, "火球术", 2, DEAL_DAMAGE, 12, "造成12点伤害");
allCards[202] = CardData(202, "魔力汲取", 1, GAIN_MANA, 2, "获得2点法力");
allCards[203] = CardData(203, "雷暴", 3, MULTI_HIT, 3, "6次3点伤害");
allCards[204] = CardData(204, "暗影箭", 1, DEAL_DAMAGE, 7, "暗影伤害");
allCards[205] = CardData(205, "法力风暴", 0, DEAL_DAMAGE, 5, "造成5点伤害");
allCards[206] = CardData(206, "寒冰束缚", 1, GAIN_BLOCK, 8, "获得8点护甲");
allCards[207] = CardData(207, "灵魂灼烧", 2, BURN, 10, "灼烧伤害");
// 牧师
allCards[301] = CardData(301, "治疗术", 1, HEAL_HP, 6, "恢复6点生命");
allCards[302] = CardData(302, "惩击", 1, DEAL_DAMAGE, 5, "造成5点伤害");
allCards[303] = CardData(303, "神圣护盾", 2, GAIN_BLOCK, 12, "获得12点护甲");
allCards[304] = CardData(304, "祈福", 0, DRAW_CARD, 1, "抽1张牌");
allCards[305] = CardData(305, "圣光审判", 2, DEAL_DAMAGE, 12, "神圣伤害");
allCards[306] = CardData(306, "庇护之光", 2, HEAL_HP, 10, "恢复10生命");
// 游侠
allCards[401] = CardData(401, "背刺", 1, DEAL_DAMAGE, 7, "造成7点伤害");
allCards[402] = CardData(402, "毒刃", 1, POISON, 4, "附加中毒");
allCards[403] = CardData(403, "箭雨", 2, MULTI_HIT, 4, "4次4点伤害");
allCards[404] = CardData(404, "潜伏", 0, GAIN_BLOCK, 5, "小额护甲");
allCards[405] = CardData(405, "精准射击", 2, DEAL_DAMAGE, 13, "高额单体伤害");
allCards[406] = CardData(406, "淬毒", 1, WEAK, 1, "虚弱敌人");
}
void initMonsters()
{
// 第一章 15只小怪
MonsterData m1(1, "哥布林斥候", 30, "第一章", "弱小杂兵");
m1.addSkill("偷袭",6,0,""); allMonsters[1]=m1;
MonsterData m2(2, "森林野狼", 38, "第一章", "野兽");
m2.addSkill("撕咬",9,0,""); allMonsters[2]=m2;
MonsterData m3(3, "迷雾蜘蛛", 29, "第一章", "毒虫");
m3.addSkill("毒咬",7,0,""); allMonsters[3]=m3;
MonsterData m4(4, "古树精", 55, "第一章", "森林精灵");
m4.addSkill("藤蔓抽打",11,5,""); allMonsters[4]=m4;
MonsterData m5(5, "废弃守卫", 42, "第一章", "石像守卫");
m5.addSkill("重击",10,6,""); allMonsters[5]=m5;
MonsterData m6(6, "腐坏野兔", 25, "第一章", "畸变野兽");
m6.addSkill("乱抓",5,0,""); allMonsters[6]=m6;
MonsterData m7(7, "林间盗贼", 33, "第一章", "流浪劫匪");
m7.addSkill("短刀突刺",8,0,""); allMonsters[7]=m7;
MonsterData m8(8, "毒蘑菇怪", 27, "第一章", "真菌魔物");
m8.addSkill("毒孢子",6,0,""); allMonsters[8]=m8;
MonsterData m9(9, "碎石傀儡", 48, "第一章", "土元素造物");
m9.addSkill("岩击",10,8,""); allMonsters[9]=m9;
MonsterData m10(10,"幽影蝙蝠", 26, "第一章", "夜行魔物");
m10.addSkill("吸血撕咬",7,0,""); allMonsters[10]=m10;
MonsterData m11(11,"生锈铁兵", 44, "第一章", "废弃人偶");
m11.addSkill("铁拳",9,5,""); allMonsters[11]=m11;
MonsterData m12(12,"狂化松鼠", 22, "第一章", "狂暴小动物");
m12.addSkill("乱挠",4,0,""); allMonsters[12]=m12;
MonsterData m13(13,"沼泽蛤蟆", 35, "第一章", "沼泽生物");
m13.addSkill("毒液喷射",8,0,""); allMonsters[13]=m13;
MonsterData m14(14,"旧法师残魂",32,"第一章","残留灵体");
m14.addSkill("暗影弹",7,0,""); allMonsters[14]=m14;
MonsterData m15(15,"荆棘藤蔓",36,"第一章","野生植物");
m15.addSkill("穿刺",8,3,""); allMonsters[15]=m15;
// 第二章15只简略
MonsterData m16(16,"鱼人小兵",45,"第二章","");m16.addSkill("鱼叉",10,0,"");allMonsters[16]=m16;
MonsterData m17(17,"水雾幽灵",40,"第二章","");m17.addSkill("冲击",8,0,"");allMonsters[17]=m17;
MonsterData m18(18,"海藻怪",39,"第二章","");m18.addSkill("缠绕",7,4,"");allMonsters[18]=m18;
MonsterData m19(19,"贝壳守卫",52,"第二章","");m19.addSkill("硬壳撞击",9,10,"");allMonsters[19]=m19;
MonsterData m20(20,"深海水母",31,"第二章","");m20.addSkill("电击",6,0,"");allMonsters[20]=m20;
// BOSS
MonsterData b1(101,"扭曲树人",150,"第一章","黑森林诅咒");
b1.addSkill("藤蔓缠绕",12,5,""); allMonsters[101]=b1;
MonsterData b2(102,"娜迦海巫",180,"第二章","深海支配者");
b2.addSkill("毒水箭",16,0,""); allMonsters[102]=b2;
MonsterData b3(103,"机械巨龙",220,"第三章","钟楼核心");
b3.addSkill("蒸汽吐息",20,0,""); allMonsters[103]=b3;
MonsterData b4(104,"月之女巫",300,"第四章","最终BOSS");
b4.addSkill("月陨",25,0,""); allMonsters[104]=b4;
}
// 从15只小怪里 随机选出10只
vector<MonsterData> getChapterMonsterList(string ch)
{
vector<MonsterData> total;
for(auto& p : allMonsters)
{
if(p.second.chapter == ch && p.first < 100)
total.push_back(p.second);
}
// 乱序后取前10
shuffle(total.begin(), total.end(), mt19937(random_device{}()));
vector<MonsterData> res;
for(int i = 0; i < 10 && i < total.size(); i++)
res.push_back(total[i]);
return res;
}
MonsterData getBoss(string ch)
{
if(ch=="第一章") return allMonsters[101];
if(ch=="第二章") return allMonsters[102];
if(ch=="第三章") return allMonsters[103];
return allMonsters[104];
}
vector<int> getJobCards(int jobIdx)
{
vector<int> res;
int base = jobIdx * 100;
for(auto& p : allCards)
{
if(p.first >= base+1 && p.first <= base+20)
res.push_back(p.first);
}
return res;
}
};
GameDatabase db;
class Player
{
public:
string name;
int hp, maxHp, mana, maxMana, money, block;
JobType job;
vector<int> deck, hand, discard;
Player(JobType j) : block(0), job(j), money(30)
{
if (j == WARRIOR)
{
name="战士"; maxHp=120;hp=120; maxMana=4;mana=4;
deck= {101,101,102,102,104};
}
else if (j == WITCH)
{
name="女巫"; maxHp=90;hp=90; maxMana=5;mana=5;
deck= {201,201,202,204,206};
}
else if (j == PRIEST)
{
name="牧师"; maxHp=100;hp=100; maxMana=4;mana=4;
deck= {301,301,302,303,304};
}
else
{
name="游侠"; maxHp=95;hp=95; maxMana=4;mana=4;
deck= {401,401,402,403,404};
}
}
void draw(int count)
{
for(int i = 0; i < count; i++)
{
if (deck.empty())
{
if (discard.empty()) break;
deck.swap(discard);
shuffle(deck.begin(), deck.end(), mt19937(random_device{}()));
cout << "\n【洗牌】\n";
}
hand.push_back(deck.back());
deck.pop_back();
}
}
void levelUp()
{
maxHp += 15;
maxMana += 1;
hp = maxHp;
mana = maxMana;
cout << "\n>>> 升级!全状态恢复 <<<\n";
}
};
class Battle
{
private:
Player& p;
MonsterData enemy;
int eHp, eBlock;
public:
Battle(Player& pl, MonsterData e)
: p(pl), enemy(e), eBlock(0), eHp(e.maxHp)
{
cout << "\n【遭遇】" << enemy.name << "\n";
}
void start()
{
while (p.hp > 0 && eHp > 0)
{
playerTurn();
if(eHp > 0) enemyTurn();
p.block = 0;
eBlock = 0;
}
if(p.hp <= 0)
{
cout << "\n游戏结束\n";
system("pause");
exit(0);
}
cout << ">>> 战斗胜利 <<<\n";
}
void playerTurn()
{
p.mana = p.maxMana;
p.draw(2);
while(true)
{
cout << "\n生命:"<<p.hp<<"/"<<p.maxHp
<< " 法力:"<<p.mana<<" 护甲:"<<p.block
<< " 敌人HP:"<<eHp<<endl;
for(int i=0;i<p.hand.size();i++)
{
CardData &c = db.allCards[p.hand[i]];
cout << i+1<<"."<<c.name<<"("<<c.cost<<"费) "<<c.desc<<endl;
}
cout << "0.结束回合\n选择:";
int op;
cin >> op;
if(op == 0) break;
if(op < 1 || op > p.hand.size()) continue;
CardData &c = db.allCards[p.hand[op-1]];
if(p.mana >= c.cost)
{
p.mana -= c.cost;
cout << "使用【"<<c.name<<"】\n";
if(c.effect == DEAL_DAMAGE) eHp -= c.effectValue;
if(c.effect == GAIN_BLOCK) p.block += c.effectValue;
if(c.effect == HEAL_HP) p.hp = min(p.hp + c.effectValue, p.maxHp);
if(c.effect == DRAW_CARD) p.draw(c.effectValue);
if(c.effect == MULTI_HIT) eHp -= c.effectValue * 3;
p.discard.push_back(p.hand[op-1]);
p.hand.erase(p.hand.begin()+op-1);
}
else
cout << "法力不足!\n";
}
}
void enemyTurn()
{
if(enemy.skills.empty()) return;
MonsterCard &mc = enemy.skills[rand() % enemy.skills.size()];
cout << "\n敌人使用:"<<mc.name<<endl;
int dmg = max(0, mc.damage - p.block);
p.hp -= dmg;
eBlock += mc.block;
if(dmg > 0) cout << "受到 " << dmg << " 点伤害\n";
}
};
// ========== 商人:随机 0~3 件商品,修复RE ==========
void shopEvent(Player &p)
{
cout << "\n===== 神秘商人 金币:"<<p.money<<" ====="<<endl;
vector<int> pool = db.getJobCards(p.job);
int shopCnt = rand() % 4; // 0 / 1 / 2 / 3 张
vector<int> goods;
for(int i = 0; i < shopCnt; i++)
{
if(pool.empty()) break;
int idx = rand() % pool.size();
goods.push_back(pool[idx]);
}
if(goods.empty())
{
cout << "本次商店没有商品\n";
system("pause");
return;
}
for(int i = 0; i < goods.size(); i++)
{
CardData &c = db.allCards[goods[i]];
cout << i+1 << ". " << c.name << " 【15金币】 " << c.desc << endl;
}
cout << goods.size()+1 << ". 离开商店\n";
int op;
cin >> op;
if(op >= 1 && op <= goods.size())
{
if(p.money >= 15)
{
p.money -= 15;
p.deck.push_back(goods[op-1]);
cout << "购买成功!\n";
}
else
cout << "金币不足!\n";
}
}
void specialEvent(Player &p)
{
cout << "\n===== 特殊事件 ====="<<endl;
cout << "1.献祭生命+25金币\n2.祈祷回血\n3.离开\n";
int op; cin>>op;
if(op == 1)
{
p.hp -= 10;
p.money += 25;
}
else if(op == 2)
{
p.hp = min(p.hp + 25, p.maxHp);
}
}
void chapterProcess(Player &p, string ch)
{
cout << "\n======== 【"<<ch<<"】 ========\n";
vector<ChapterNode> nodes;
// 固定:10战斗 + 3商店 + 1特殊
for(int i=0;i<10;i++) nodes.emplace_back(NODE_MONSTER);
for(int i=0;i<3;i++) nodes.emplace_back(NODE_SHOP);
nodes.emplace_back(NODE_SPECIAL);
// 随机打乱顺序
shuffle(nodes.begin(), nodes.end(), mt19937(random_device{}()));
vector<MonsterData> mList = db.getChapterMonsterList(ch);
int cnt = 1;
for(auto &node : nodes)
{
cout << "\n—— 第"<<cnt<<"/14 节点 ——\n";
cnt++;
if(node.type == NODE_MONSTER)
{
int idx = rand() % mList.size();
Battle b(p, mList[idx]);
b.start();
p.money += 12;
cout << "获得12金币\n";
}
else if(node.type == NODE_SHOP)
{
shopEvent(p);
}
else
{
specialEvent(p);
}
}
// BOSS
cout << "\n======== BOSS战 ========\n";
Battle boss(p, db.getBoss(ch));
boss.start();
p.money += 50;
p.levelUp();
system("pause");
}
void adventure(Player& p)
{
vector<string> chs = {"第一章","第二章","第三章","第四章"};
for(auto &c : chs)
chapterProcess(p, c);
cout << "\n===== 全通关 =====";
}
int main()
{
srand((unsigned)time(nullptr));
cout << "职业选择:1战士 2女巫 3牧师 4游侠\n";
int c; cin>>c;
JobType j = (JobType)(c-1);
Player player(j);
adventure(player);
system("pause");
return 0;
}A+B problem解法征集
基础
#include<bits/stdc++.h>
using namespace std;
int a,b;
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> a >> b;
cout << a + b;
}hlpp解法
#include<bits/stdc++.h>
using namespace std;
using LongLong = long long;
constexpr LongLong MAX_VERTEX_COUNT = 2000 + 10;
constexpr LongLong MAX_EDGE_COUNT = 30000 + 10;
constexpr LongLong INFINITE_DISTANCE = (LLONG_MAX >> 1) - 1LL;
LongLong vertexCount, edgeCount;
LongLong sourceVertex, sinkVertex;
LongLong heightLabelArray[MAX_VERTEX_COUNT];
LongLong highestActiveHeight;
LongLong excessFlowArray[MAX_VERTEX_COUNT];
LongLong gapCountArray[MAX_VERTEX_COUNT];
LongLong textPlaceholder[MAX_VERTEX_COUNT];
LongLong answerStorage[MAX_VERTEX_COUNT];
LongLong previousArrayPlaceholder[MAX_VERTEX_COUNT];
bool isHLPPExecuted = false;
LongLong finalMaxFlowValue = 0;
struct EdgeNode
{
LongLong residualCapacity;
LongLong targetVertex;
LongLong reverseEdgeIndex;
EdgeNode() = default;
EdgeNode(LongLong target, LongLong capacity, LongLong rev)
: targetVertex(target), residualCapacity(capacity), reverseEdgeIndex(rev) {}
};
vector<EdgeNode> graphAdjacencyList[MAX_VERTEX_COUNT];
stack<LongLong> activeVertexStackArray[MAX_VERTEX_COUNT];
void addDirectedFlowEdge(LongLong fromVertex, LongLong toVertex, LongLong capacityValue)
{
graphAdjacencyList[fromVertex].emplace_back(toVertex, capacityValue, graphAdjacencyList[toVertex].size());
graphAdjacencyList[toVertex].emplace_back(fromVertex, 0, graphAdjacencyList[fromVertex].size() - 1);
}
bool initializeHeightsByBFS()
{
for (LongLong loopIndex = 1; loopIndex <= vertexCount + 9; ++loopIndex)
{
heightLabelArray[loopIndex] = INFINITE_DISTANCE;
}
queue<LongLong> bfsQueue;
bfsQueue.push(sinkVertex);
heightLabelArray[sinkVertex] = 0;
while (!bfsQueue.empty())
{
LongLong currentVertex = bfsQueue.front();
bfsQueue.pop();
for (auto &edgeRef : graphAdjacencyList[currentVertex])
{
LongLong &neighborVertex = edgeRef.targetVertex;
LongLong &reverseIndex = edgeRef.reverseEdgeIndex;
if (heightLabelArray[neighborVertex] > heightLabelArray[currentVertex] + 1 &&
graphAdjacencyList[neighborVertex][reverseIndex].residualCapacity)
{
heightLabelArray[neighborVertex] = heightLabelArray[currentVertex] + 1;
bfsQueue.push(neighborVertex);
}
}
}
return heightLabelArray[sourceVertex] != INFINITE_DISTANCE;
}
bool attemptPushFlow(LongLong currentVertex)
{
bool isSourceVertex = (currentVertex == sourceVertex);
for (auto &edgeRef : graphAdjacencyList[currentVertex])
{
LongLong &edgeCapacity = edgeRef.residualCapacity;
LongLong &neighborVertex = edgeRef.targetVertex;
LongLong &reverseIndex = edgeRef.reverseEdgeIndex;
if (!edgeCapacity ||
(!isSourceVertex && heightLabelArray[currentVertex] != heightLabelArray[neighborVertex] + 1) ||
heightLabelArray[neighborVertex] == INFINITE_DISTANCE)
{
continue;
}
if (neighborVertex != sourceVertex && neighborVertex != sinkVertex && (!excessFlowArray[neighborVertex]))
{
activeVertexStackArray[heightLabelArray[neighborVertex]].push(neighborVertex);
highestActiveHeight = max(highestActiveHeight, heightLabelArray[neighborVertex]);
}
LongLong flowAmount = isSourceVertex ? edgeCapacity : min(edgeCapacity, excessFlowArray[currentVertex]);
excessFlowArray[currentVertex] -= flowAmount;
excessFlowArray[neighborVertex] += flowAmount;
edgeCapacity -= flowAmount;
graphAdjacencyList[neighborVertex][reverseIndex].residualCapacity += flowAmount;
if (!excessFlowArray[currentVertex]) return false;
}
return true;
}
void relabelVertexHeight(LongLong vertex)
{
heightLabelArray[vertex] = INFINITE_DISTANCE;
for (auto &edgeRef : graphAdjacencyList[vertex])
{
if (edgeRef.residualCapacity)
{
heightLabelArray[vertex] = min(heightLabelArray[vertex], heightLabelArray[edgeRef.targetVertex]);
}
}
++heightLabelArray[vertex];
if (heightLabelArray[vertex] < vertexCount)
{
activeVertexStackArray[heightLabelArray[vertex]].push(vertex);
highestActiveHeight = max(highestActiveHeight, heightLabelArray[vertex]);
++gapCountArray[heightLabelArray[vertex]];
}
}
LongLong getHighestActiveVertexIndex()
{
while (highestActiveHeight > -1 && activeVertexStackArray[highestActiveHeight].empty())
{
--highestActiveHeight;
}
return (highestActiveHeight == -1) ? 0 : activeVertexStackArray[highestActiveHeight].top();
}
LongLong highestLabelPreflowPushAlgorithm()
{
if (isHLPPExecuted) return finalMaxFlowValue;
isHLPPExecuted = true;
if (!initializeHeightsByBFS()) return 0;
for (LongLong loopIndex = 1; loopIndex < vertexCount + 10; ++loopIndex)
{
gapCountArray[loopIndex] = 0;
}
for (LongLong loopIndex = 1; loopIndex <= vertexCount; ++loopIndex)
{
if (heightLabelArray[loopIndex] != INFINITE_DISTANCE)
{
++gapCountArray[heightLabelArray[loopIndex]];
}
}
heightLabelArray[sourceVertex] = vertexCount;
attemptPushFlow(sourceVertex);
LongLong currentActiveVertex;
while ((currentActiveVertex = getHighestActiveVertexIndex()))
{
activeVertexStackArray[highestActiveHeight].pop();
if (attemptPushFlow(currentActiveVertex))
{
if (!--gapCountArray[heightLabelArray[currentActiveVertex]])
{
for (LongLong loopIndex = 1; loopIndex <= vertexCount; ++loopIndex)
{
if (heightLabelArray[loopIndex] > heightLabelArray[currentActiveVertex] &&
loopIndex != sourceVertex &&
heightLabelArray[loopIndex] < vertexCount + 1)
{
heightLabelArray[loopIndex] = vertexCount + 1;
}
}
}
relabelVertexHeight(currentActiveVertex);
}
}
finalMaxFlowValue = excessFlowArray[sinkVertex];
return finalMaxFlowValue;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
LongLong capacityFromSourceToNode3, capacityFromSourceToNode4;
cin >> capacityFromSourceToNode3 >> capacityFromSourceToNode4;
vertexCount = 4;
edgeCount = 4;
sourceVertex = 1;
sinkVertex = 2;
addDirectedFlowEdge(1, 3, capacityFromSourceToNode3);
addDirectedFlowEdge(3, 2, capacityFromSourceToNode3);
addDirectedFlowEdge(1, 4, capacityFromSourceToNode4);
addDirectedFlowEdge(4, 2, capacityFromSourceToNode4);
finalMaxFlowValue = highestLabelPreflowPushAlgorithm();
cout << highestLabelPreflowPushAlgorithm();
return 0;
}自制游戏
扫雷
#include <bits/stdc++.h>
#include <cstdlib>
#define ll long long
using namespace std;
void CS() {
#ifdef _WIN32
system("cls");
#else
// 假设在 Unix/Linux 系统
std::cout << "\033[2J\033[1;1H";
#endif
}
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
constexpr int maxn=1e3+10;
char a[maxn][maxn];
char ans[maxn][maxn];
ll nsp;
void init(ll n,ll m,ll k)
{
for(ll i=1;i<=n;++i)
{
for(ll j=1;j<=m;++j)
{
a[i][j]='.';
ans[i][j]='.';
}
}
while(k--)
{
while(1)
{
ll x=rnd()%n+1;
ll y=rnd()%m+1;
if(ans[x][y]=='.')
{
ans[x][y]='#';
break;
}
}
}
for(ll i=1;i<=n;++i)
{
for(ll j=1;j<=m;++j)
{
if(ans[i][j]=='#') continue;
ll c=0;
if(ans[i-1][j-1]=='#') c++;
if(ans[i][j-1]=='#') c++;
if(ans[i][j+1]=='#') c++;
if(ans[i-1][j+1]=='#') c++;
if(ans[i+1][j-1]=='#') c++;
if(ans[i+1][j]=='#') c++;
if(ans[i-1][j]=='#') c++;
if(ans[i+1][j+1]=='#') c++;
ans[i][j]=c+'0';
}
}
}
ll nk;
void print(ll n,ll m,ll op)
{
cout << "+ " ;
for(ll i=1;i<=n;++i)
{
cout << i << ' ';
if(nsp==1) continue;
else if(nsp==2 && i<10) cout << ' ';
else if(nsp==3 && i<10) cout << ' ' << ' ';
else if(nsp==3 && i<100) cout << ' ';
}
cout << endl << " +" << endl;
if(op==0)
{
for(ll i=1;i<=n;++i)
{
cout << i << " ";
if(i<10) cout << ' ';
if(i<100) cout << ' ';
for(ll j=1;j<=m;++j)
{
cout << a[i][j] << " " ;
}
cout << endl;
}
}
else
{
for(ll i=1;i<=n;++i)
{
cout << i << " ";
for(ll j=1;j<=m;++j)
{
cout << ans[i][j] << ' ' ;
}
cout << endl;
}
}
cout << "Maybe " << nk << " winmine" << (nk>1?"s\n":"\n");
}
ll k;
void bl(ll _,ll b,ll n,ll m)
{
if(_!=1)
{
if(ans[_-1][b]=='0' && a[_-1][b]=='.')
{
a[_-1][b]='0';
bl(_-1,b,n,m);
}
}
if(b!=1)
{
if(ans[_][b-1]=='0' && a[_][b-1]=='.')
{
a[_][b-1]='0';
bl(_,b-1,n,m);
}
}
if(_!=n)
{
if(ans[_+1][b]=='0' && a[_+1][b]=='.')
{
a[_+1][b]='0';
bl(_+1,b,n,m);
}
}
if(b!=m)
{
if(ans[_][b+1]=='0' && a[_][b+1]=='.')
{
a[_][b+1]='0';
bl(_,b+1,n,m);
}
}
if(_!=1 && b!=1)
{
if(ans[_-1][b-1]=='0' && a[_-1][b-1]=='.')
{
a[_-1][b-1]='0';
bl(_-1,b-1,n,m);
}
}
if(_!=n && b!=m)
{
if(ans[_+1][b+1]=='0' && a[_+1][b+1]=='.')
{
a[_+1][b+1]='0';
bl(_+1,b+1,n,m);
}
}
if(_!=1 && b!=m)
{
if(ans[_-1][b+1]=='0' && a[_-1][b+1]=='.')
{
a[_-1][b+1]='0';
bl(_-1,b+1,n,m);
}
}
if(_!=n && b!=1)
{
if(ans[_+1][b-1]=='0' && a[_+1][b-1]=='.')
{
a[_+1][b-1]='0';
bl(_+1,b-1,n,m);
}
}
if(_!=1)
{
if(ans[_-1][b]!='#' && a[_-1][b]=='.')
{
a[_-1][b]=ans[_-1][b];
}
}
if(b!=1)
{
if(ans[_][b-1]!='#' && a[_][b-1]=='.')
{
a[_][b-1]=ans[_][b-1];
}
}
if(_!=n)
{
if(ans[_+1][b]!='#' && a[_+1][b]=='.')
{
a[_+1][b]=ans[_+1][b];
}
}
if(b!=m)
{
if(ans[_][b+1]!='#' && a[_][b+1]=='.')
{
a[_][b+1]=ans[_][b+1];
}
}
if(_!=1 && b!=1)
{
if(ans[_-1][b-1]!='#' && a[_-1][b-1]=='.')
{
a[_-1][b-1]=ans[_-1][b-1];
}
}
if(_!=n && b!=1)
{
if(ans[_+1][b-1]!='#' && a[_+1][b-1]=='.')
{
a[_+1][b-1]=ans[_+1][b-1];
}
}
if(_!=n && b!=m)
{
if(ans[_+1][b+1]!='#' && a[_+1][b+1]=='.')
{
a[_+1][b+1]=ans[_+1][b+1];
}
}
if(_!=1 && b!=m)
{
if(ans[_-1][b+1]!='#' && a[_-1][b+1]=='.')
{
a[_-1][b+1]=ans[_-1][b+1];
}
}
}
void mn(ll n,ll m)
{
ll x,y,op;
cin >> op >> x >> y;
if(op)
{
if(a[y][x]=='F')
{
a[y][x]='.';
nk++;
return ;
}
nk--;
a[y][x]='F';
return ;
}
else
{
if(ans[y][x]=='#')
{
CS();
print(n,m,1);
cout << endl << "You are game over";
exit(0);
}
else
{
a[y][x]=ans[y][x];
if(a[y][x]=='0')
{
bl(y,x,n,m);
}
}
}
for(ll i=1;i<=n;++i)
{
for(ll j=1;j<=m;++j)
{
if(ans[i][j]=='#' || a[i][j]==ans[i][j]) continue;
else return ;
}
}
CS();
print(n,m,1);
cout << endl << "Your Win";
exit(0);
}
signed main()
{
cout << "What types?(N*M+K)" << endl;
ll n,m;
cin >> n >> m >> k;
nk=k;
init(n,m,k);
ll a=n;
while(a)
{
a/=10;
nsp++;
}
while(1)
{
CS();
print(n,m,0);
mn(n,m);
}
}贪吃蛇
单人
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
#include <cstdlib>
void clears(){
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}
#ifdef _WIN32
#include <conio.h>
bool keyPressed() { return _kbhit(); }
char getKey() { return _getch(); }
#else
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#endif
constexpr int maxn=1010;
ll N,M;
char k[maxn][maxn];
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
ll len;
ll TPx,TPy;
vector<pair<ll,ll>> body;
ll rou=0;
ll countapple;
void init()
{
len=1;
TPx=(M+1)/2;
TPy=(N+1)/2;
for(ll i=1;i<=N;++i)
for(ll j=1;j<=M;++j)
{
k[i][j]='.';
if(i==TPx && j==TPy) k[i][j]='@';
}
while(1)
{
ll x__=rnd()%N+1;
ll y__=rnd()%M+1;
if(k[x__][y__]=='.')
{
k[x__][y__]='$';
break;
}
}
countapple=1;
}
void print()
{
for(ll i=1;i<=N;++i)
{
for(ll j=1;j<=M;++j) cout << k[i][j];
cout << endl;
}
cout << "Round:" << rou<< endl;
rou++;
cout << "Score" << (len>2?"s":"") << ": " << len-1 << endl;
}
ll pglick=0;
ll op;
void mn()
{
char ch;
string s;
ll f1=TPx,f2=TPy;
getline(cin,s);
ch=s[0];
if(ch=='w')
{
op=1;
}
else if(ch=='s')
{
op=2;
}
else if(ch=='a')
{
op=3;
}
else if(ch=='d')
{
op=4;
}
if(op==1) TPy--;
else if(op==2) TPy++;
else if(op==3) TPx--;
else if(op==4) TPx++;
if(k[TPy][TPx]=='$')
{
k[TPy][TPx]='@';
body.emplace_back(0,0);
len++;
countapple--;
}
for(auto &i:body)
{
ll u=i.first;
ll v=i.second;
i.first=f1;
i.second=f2;
f1=u;
f2=v;
}
for(ll i=1;i<=N;++i)
{
for(ll j=1;j<=M;++j)
{
if(k[i][j]=='$') continue;
k[i][j]='.';
if(j==TPx && i==TPy) k[i][j]='@';
}
}
for(auto &i:body)
{
k[i.second][i.first]='#';
}
pglick++;
if(pglick>=3 && countapple<5 && countapple+len<N*M)
{
pglick=0;
while(1)
{
ll x__=rnd()%N+1;
ll y__=rnd()%M+1;
if(k[x__][y__]=='.')
{
k[x__][y__]='$';
break;
}
}
countapple++;
}
}
bool ntgameover()
{
if(len==N*M)
{
clears();
print();
cout << "WIN!!!";
exit(0);
}
if(TPx==M+1 || TPx==0 || TPy==0 || TPy==N+1) return 0;
for(auto i:body)
{
if(i.first==TPx && i.second==TPy)
{
return 0;
}
}
return 1;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout << "Please write the size of game" << endl;
cin >> N >> M;
cin.ignore();
clears();
init();
while(ntgameover())
{
clears();
print();
mn();
}
cout << endl << endl << "GAME OVER";
}双人
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
#include <cstdlib>
void clears(){
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}
#ifdef _WIN32
#include <conio.h>
bool keyPressed() { return _kbhit(); }
char getKey() { return _getch(); }
#else
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#endif
constexpr int maxn=1010;
ll N,M;
char k[maxn][maxn];
mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
ll len1,len2;//%
ll P1x,P1y;
ll P2x,P2y;
vector<pair<ll,ll>> body1,body2;
void init()
{
P1x=1;
P1y=1;
P2x=M;
P2y=N;
for(ll i=1;i<=N;++i)
for(ll j=1;j<=M;++j)
{
k[i][j]='.';
if(i==P1y && j==P1x) k[i][j]='@';
if(i==P2y && j==P2x) k[i][j]='%';
}
while(1)
{
ll x__=rnd()%N+1;
ll y__=rnd()%M+1;
if(k[x__][y__]=='.')
{
k[x__][y__]='$';
break;
}
}
while(1)
{
ll x__=rnd()%N+1;
ll y__=rnd()%M+1;
if(k[x__][y__]=='.')
{
k[x__][y__]='$';
break;
}
}
len1=1;
for(ll i=1;i<len1;++i) body1.emplace_back(0,0);
len2=1;
for(ll i=1;i<len2;++i) body2.emplace_back(0,0);
ll T=0;
while(T--)
{
got:;
ll x__=rnd()%N+1;
ll y__=rnd()%M+1;
if(k[x__][y__]=='.')
{
k[x__][y__]='?';
continue;
}
goto got;
}
}
void print()
{
for(ll i=1;i<=N;++i)
{
for(ll j=1;j<=M;++j) cout << k[i][j];
cout << endl;
}
cout << "Score1" << (len1>2?"s":"") << ": " << len1-1 << endl;
cout << "Score2" << (len2>2?"s":"") << ": " << len2-1 << endl;
}
ll pglick=0;
ll countapple=1;
ll op1,op2;
void mn()
{
char ch;
string s;
ll f1=P1x,f2=P1y;
ll f3=P2x,f4=P2y;
getline(cin,s);
for(auto ch:s){
if(ch=='w')
{
op1=1;
}
else if(ch=='s')
{
op1=2;
}
else if(ch=='a')
{
op1=3;
}
else if(ch=='d')
{
op1=4;
}
if(ch=='i')
{
op2=1;
}
else if(ch=='k')
{
op2=2;
}
else if(ch=='j')
{
op2=3;
}
else if(ch=='l')
{
op2=4;
}
}
if(op1==1) P1y--;
else if(op1==2) P1y++;
else if(op1==3) P1x--;
else if(op1==4) P1x++;
if(op2==1) P2y--;
else if(op2==2) P2y++;
else if(op2==3) P2x--;
else if(op2==4) P2x++;
if(k[P1y][P1x]=='$')
{
k[P1y][P1x]='@';
body1.emplace_back(0,0);
len1++;
countapple--;
}
if(k[P2y][P2x]=='$')
{
k[P2y][P2x]='%';
body2.emplace_back(0,0);
len2++;
countapple--;
}
ll u,v;
for(auto &i:body1)
{
u=i.first;
v=i.second;
i.first=f1;
i.second=f2;
f1=u;
f2=v;
}
for(auto &i:body2)
{
u=i.first;
v=i.second;
i.first=f3;
i.second=f4;
f3=u;
f4=v;
}
for(ll i=1;i<=N;++i)
{
for(ll j=1;j<=M;++j)
{
if(k[i][j]=='$' ||k[i][j]=='?') continue;
k[i][j]='.';
if(j==P1x && i==P1y) k[i][j]='@';
if(j==P2x && i==P2y) k[i][j]='%';
}
}
pglick++;
if(pglick>=5 /*&& countapple<=9 */&& countapple+len1<N*M)
{
pglick-=5;
while(1)
{
ll x__=rnd()%N+1;
ll y__=rnd()%M+1;
if(k[x__][y__]=='.')
{
k[x__][y__]='$';
break;
}
}
countapple++;
while(1)
{
ll x__=rnd()%N+1;
ll y__=rnd()%M+1;
if(k[x__][y__]=='.')
{
k[x__][y__]='$';
break;
}
}
countapple++;
}
for(auto i:body1)
{
k[i.second][i.first]='#';
}
for(auto i:body2)
{
k[i.second][i.first]='O';
}
}
ll ntgameover()
{
if(P1x==P2x && P1y==P2y) return 0;
if(P1x==M+1 || P1x==0 || P1y==0 || P1y==N+1) return 1;
if(P2x==M+1 || P2x==0 || P2y==0 || P2y==N+1) return 2;
for(auto i:body1)
{
if(i.first==P1x && i.second==P1y)
{
return 1;
}
if(i.first==P2x && i.second==P2y)
{
return 2;
}
}
for(auto i:body2)
{
if(i.first==P1x && i.second==P1y)
{
return 1;
}
if(i.first==P2x && i.second==P2y)
{
return 2;
}
}
return 3;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout << "Please write the size of game" << endl;
cin >> N >> M;
cin.ignore();
clears();
init();
ll t;
while(t=ntgameover())
{
if(t!=3) break;
clears();
print();
mn();
}
clears();
if(!t) cout << "Head meet head";
else if(t==1) cout << "P2 Wins";
else if(t==2) cout << "P1 Wins";
}养蛊
#include<bits/stdc++.h> using namespace std; using ll = long long; #include <cstdlib>
void clears(){ #ifdef _WIN32 system(“cls”); #else system(“clear”); #endif }
#ifdef _WIN32 #include <conio.h> bool keyPressed() { return _kbhit(); } char getKey() { return _getch(); } #else #include <termios.h> #include <unistd.h> #include <fcntl.h> #endif
constexpr int maxn=1010; ll N,M; char k[maxn][maxn]; mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
ll len[5]; ll Px[5], Py[5]; vector<pair<ll,ll>> body[5]; ll lastDir[5]; bool alive[5];
char headChar[5] = {’ ’, ’@’, ’%’, ’/’, ’?’}; char bodyChar[5] = {’ ’, ’#’, ‘O’, ’+’, ’-’};
ll countapple = 0; ll pglick = 0;
bool inBounds(ll x, ll y) { return x>=1 && x<=M && y>=1 && y<=N; }
void init() { Px[1]=1; Py[1]=1; Px[2]=M; Py[2]=1; Px[3]=1; Py[3]=N; Px[4]=M; Py[4]=N;
for(int id=1; id<=4; ++id) {
len[id]=1;
body[id].clear();
lastDir[id]=-1;
alive[id]=true;
}
for(ll i=1;i<=N;++i)
for(ll j=1;j<=M;++j)
k[i][j]='.';
for(int id=1; id<=4; ++id) {
k[Py[id]][Px[id]] = headChar[id];
}
for(int t=0; t<5; ++t) {
while(1) {
ll x = rnd()%M+1;
ll y = rnd()%N+1;
if(k[y][x]=='.') {
k[y][x]='$';
break;
}
}
}
countapple = 5;
pglick = 0;
}
void print() { for(ll i=1;i<=N;++i) { for(ll j=1;j<=M;++j) cout << k[i][j]; cout << endl; } for(int id=1; id<=4; ++id) { if(alive[id]) { cout << “P” << id << ” Score: ” << len[id]-1; } else { cout << “P” << id << ” Dead”; } if(id<4) cout << ” | ”; } cout << endl; cout << “Apples: ” << countapple << endl; }
bool isOccupiedByOther(ll x, ll y, int selfId, bool includeHead=true) { for(int id=1; id<=4; ++id) { if(id == selfId || !alive[id]) continue; if(includeHead && Px[id]==x && Py[id]==y) return true; for(auto& b : body[id]) { if(b.first==x && b.second==y) return true; } } return false; }
bool isOccupiedBySelf(ll x, ll y, int selfId, bool includeTail=true) { ll end = includeTail ? body[selfId].size() : (body[selfId].size()>0 ? body[selfId].size()-1 : 0); for(ll i=0; i<end; ++i) { if(body[selfId][i].first==x && body[selfId][i].second==y) return true; } return false; }
bool isSafeFor(int id, ll x, ll y, bool includeTail=true, bool allowRisky=false) { if(!inBounds(x,y)) return false; if(isOccupiedByOther(x,y,id,true)) return false; if(isOccupiedBySelf(x,y,id,includeTail)) return false; if(!allowRisky) { for(int oid=1; oid<=4; ++oid) { if(oid==id || !alive[oid]) continue; if(abs(x-Px[oid]) + abs(y-Py[oid]) == 1) return false; } } return true; }
vector<pair<ll,ll>> findPath(int id, pair<ll,ll> start, pair<ll,ll> target, bool includeTail=false, bool allowRisky=false) { if(start == target) return {}; vector<vector<bool>> visited(N+2, vector<bool>(M+2, false)); vector<vector<pair<ll,ll>>> parent(N+2, vector<pair<ll,ll>>(M+2, {-1,-1})); queue<pair<ll,ll>> q; ll dx[] = {0,0,-1,1}; ll dy[] = {-1,1,0,0}; q.push(start); visited[start.second][start.first]=true; while(!q.empty()) { auto cur = q.front(); q.pop(); if(cur == target) { vector<pair<ll,ll>> path; while(cur != start) { path.push_back(cur); cur = parent[cur.second][cur.first]; if(cur.first==-1 && cur.second==-1) break; } reverse(path.begin(), path.end()); return path; } for(int i=0; i<4; ++i) { ll nx = cur.first + dx[i]; ll ny = cur.second + dy[i]; if(!inBounds(nx,ny)) continue; if(visited[ny][nx]) continue; if(!isSafeFor(id, nx, ny, includeTail, allowRisky)) continue; visited[ny][nx]=true; parent[ny][nx]=cur; q.push({nx,ny}); } } return {}; }
ll countReachableSpace(int id, ll x, ll y, bool includeTail=false) { vector<vector<bool>> visited(N+2, vector<bool>(M+2, false)); queue<pair<ll,ll>> q; q.push({x,y}); visited[y][x]=true; ll cnt=0; ll dx[] = {0,0,-1,1}; ll dy[] = {-1,1,0,0}; while(!q.empty()) { auto cur = q.front(); q.pop(); cnt++; for(int i=0; i<4; ++i) { ll nx = cur.first + dx[i]; ll ny = cur.second + dy[i]; if(!inBounds(nx,ny)) continue; if(visited[ny][nx]) continue; if(!isSafeFor(id, nx, ny, includeTail, false)) continue; visited[ny][nx]=true; q.push({nx,ny}); } } return cnt; }
bool isPathSafe(int id, vector<pair<ll,ll>>& path, pair<ll,ll> target) { if(path.empty()) return false; ll simX = Px[id], simY = Py[id]; vector<pair<ll,ll>> simBody = body[id]; ll simLen = len[id]; for(auto& step : path) { bool ate = (step == target); if(!simBody.empty()) { simBody.insert(simBody.begin(), {simX, simY}); if(!ate) { if(simBody.size() > simLen) simBody.pop_back(); } else simLen++; } simX = step.first; simY = step.second; } auto oldBody = body[id]; ll oldLen = len[id]; body[id] = simBody; len[id] = simLen; ll space = countReachableSpace(id, simX, simY, false); body[id] = oldBody; len[id] = oldLen; ll threshold; if(id==1) threshold = len[id]*1.8; else if(id==2) threshold = len[id]*2.2; else if(id==3) threshold = len[id]*1.3; else threshold = len[id]*2.0; return space > threshold; }
char followTail(int id) { if(body[id].empty()) return 0; pair<ll,ll> tail = body[id].back(); auto start = make_pair(Px[id], Py[id]); auto path = findPath(id, start, tail, true, false); if(!path.empty() && path.size()>1) { auto next = path[0]; if(next.second < Py[id]) return ‘w’; if(next.second > Py[id]) return ‘s’; if(next.first < Px[id]) return ‘a’; if(next.first > Px[id]) return ‘d’; } return 0; }
ll getDirIndex(char dir) { if(dir==‘w’) return 0; if(dir==‘s’) return 1; if(dir==‘a’) return 2; if(dir==‘d’) return 3; return -1; }
char decideMove(int id) { ll dx[] = {0,0,-1,1}; ll dy[] = {-1,1,0,0}; char moves[] = {‘w’,‘s’,‘a’,‘d’}; bool allowRisky = (id==3);
vector<pair<ll,ll>> foods;
for(ll i=1;i<=N;++i)
for(ll j=1;j<=M;++j)
if(k[i][j]=='$') foods.push_back({j,i});
if(!foods.empty()) {
pair<ll,ll> nearest = foods[0];
ll minDist = abs(Px[id]-nearest.first) + abs(Py[id]-nearest.second);
for(auto& f : foods) {
ll d = abs(Px[id]-f.first) + abs(Py[id]-f.second);
if(d < minDist) { minDist=d; nearest=f; }
}
auto path = findPath(id, {Px[id],Py[id]}, nearest, false, allowRisky);
if(!path.empty() && isPathSafe(id, path, nearest)) {
auto next = path[0];
char dir = (next.second < Py[id] ? 'w' : next.second > Py[id] ? 's' : next.first < Px[id] ? 'a' : 'd');
lastDir[id] = getDirIndex(dir);
return dir;
}
}
char tailMove = followTail(id);
if(tailMove) {
lastDir[id] = getDirIndex(tailMove);
return tailMove;
}
ll bestScore = -1;
char bestMove = 'w';
for(int i=0; i<4; ++i) {
ll nx = Px[id] + dx[i];
ll ny = Py[id] + dy[i];
if(!isSafeFor(id, nx, ny, false, allowRisky)) continue;
ll space = countReachableSpace(id, nx, ny, false);
ll wallDist = min(min(nx, M-nx+1), min(ny, N-ny+1));
ll straightBonus = (lastDir[id]==i) ? 20 : 0;
ll turnPenalty = (lastDir[id]!=-1 && lastDir[id]!=i) ? 5 : 0;
ll score = space + wallDist*2 + straightBonus - turnPenalty;
if(score > bestScore) {
bestScore = score;
bestMove = moves[i];
}
}
if(bestScore > 0) {
lastDir[id] = getDirIndex(bestMove);
return bestMove;
}
for(int i=0; i<4; ++i) {
ll nx = Px[id] + dx[i];
ll ny = Py[id] + dy[i];
if(isSafeFor(id, nx, ny, true, allowRisky)) {
lastDir[id] = i;
return moves[i];
}
}
ll maxWallDist = -1;
char fallback = 'w';
for(int i=0; i<4; ++i) {
ll nx = Px[id] + dx[i];
ll ny = Py[id] + dy[i];
if(inBounds(nx,ny)) {
ll wd = min(min(nx, M-nx+1), min(ny, N-ny+1));
if(wd > maxWallDist) {
maxWallDist = wd;
fallback = moves[i];
}
}
}
lastDir[id] = getDirIndex(fallback);
return fallback;
}
char decideMoveRandom(int id) { ll dx[] = {0,0,-1,1}; ll dy[] = {-1,1,0,0}; char moves[] = {‘w’,‘s’,‘a’,‘d’}; vector<char> safeDirs; for(int i=0; i<4; ++i) { if(isSafeFor(id, Px[id]+dx[i], Py[id]+dy[i], true, false)) safeDirs.push_back(moves[i]); } if(!safeDirs.empty()) { char dir = safeDirs[rnd()%safeDirs.size()]; lastDir[id] = getDirIndex(dir); return dir; } char dir = moves[rnd()%4]; lastDir[id] = getDirIndex(dir); return dir; }
// 处理死亡蛇,将其身体变为苹果 void processDeaths() { bool dead[5] = {false}; // 检查边界碰撞和撞自己 for(int id=1; id<=4; ++id) { if(!alive[id]) continue; if(!inBounds(Px[id], Py[id])) dead[id] = true; else if(isOccupiedBySelf(Px[id], Py[id], id, false)) dead[id] = true; } // 检查撞其他蛇身体 for(int id=1; id<=4; ++id) { if(!alive[id] || dead[id]) continue; for(int oid=1; oid<=4; ++oid) { if(oid==id || !alive[oid]) continue; for(auto& b : body[oid]) { if(Px[id]==b.first && Py[id]==b.second) { dead[id] = true; break; } } if(dead[id]) break; } } // 检查头头相撞(同一位置多条蛇) for(int i=1; i<=4; ++i) { if(!alive[i] || dead[i]) continue; for(int j=i+1; j<=4; ++j) { if(!alive[j] || dead[j]) continue; if(Px[i]==Px[j] && Py[i]==Py[j]) { dead[i] = dead[j] = true; } } }
// 将死亡蛇的身体变为苹果
for(int id=1; id<=4; ++id) {
if(alive[id] && dead[id]) {
// 将头部所在位置(如果在地图内)和身体都变成苹果
if(inBounds(Px[id], Py[id]) && k[Py[id]][Px[id]] == headChar[id]) {
k[Py[id]][Px[id]] = '$';
countapple++;
}
for(auto& b : body[id]) {
if(inBounds(b.first, b.second) && k[b.second][b.first] == bodyChar[id]) {
k[b.second][b.first] = '$';
countapple++;
}
}
// 清空该蛇
alive[id] = false;
body[id].clear();
len[id] = 0;
Px[id] = Py[id] = -1;
}
}
}
void mn() { ll oldX[5], oldY[5]; for(int id=1; id<=4; ++id) { if(!alive[id]) continue; oldX[id] = Px[id]; oldY[id] = Py[id]; }
char move[5];
if(alive[1]) move[1] = decideMove(1);
if(alive[2]) move[2] = decideMove(2);
if(alive[3]) move[3] = decideMove(3);
if(alive[4]) move[4] = decideMoveRandom(4);
// 移动存活蛇
for(int id=1; id<=4; ++id) {
if(!alive[id]) continue;
if(move[id]=='w') Py[id]--;
else if(move[id]=='s') Py[id]++;
else if(move[id]=='a') Px[id]--;
else if(move[id]=='d') Px[id]++;
}
// 处理吃苹果和身体更新
for(int id=1; id<=4; ++id) {
if(!alive[id]) continue;
bool ate = false;
if(inBounds(Px[id], Py[id]) && k[Py[id]][Px[id]]=='$') {
k[Py[id]][Px[id]] = headChar[id];
body[id].push_back({0,0}); // 增加长度
len[id]++;
countapple--;
ate = true;
}
// 更新身体
if(!body[id].empty()) {
for(ll i=body[id].size()-1; i>0; --i) {
body[id][i] = body[id][i-1];
}
body[id][0] = {oldX[id], oldY[id]};
}
}
// 重绘地图
for(ll i=1;i<=N;++i)
for(ll j=1;j<=M;++j) {
if(k[i][j]=='$') continue;
k[i][j]='.';
}
for(int id=1; id<=4; ++id) {
if(!alive[id]) continue;
if(inBounds(Px[id], Py[id]))
k[Py[id]][Px[id]] = headChar[id];
for(auto& b : body[id]) {
if(inBounds(b.first, b.second))
k[b.second][b.first] = bodyChar[id];
}
}
// 处理死亡
processDeaths();
// 每3回合生成5个苹果
pglick++;
if(pglick >= 3) {
pglick = 0;
int toAdd = 5;
while(toAdd > 0) {
ll x = rnd()%M+1;
ll y = rnd()%N+1;
if(k[y][x]=='.') {
k[y][x]='$';
countapple++;
toAdd--;
}
}
}
}
ll aliveCount() { ll cnt = 0; for(int id=1; id<=4; ++id) if(alive[id]) cnt++; return cnt; }
int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout << “Please write the size of game (rows N, cols M):” << endl; cin >> N >> M; cin.ignore(); clears(); init(); ll delayMs; cout << “Delay in ms (0 for fastest): ”; cin >> delayMs; while(aliveCount() >= 2) { clears(); print(); mn(); if(delayMs > 0) this_thread::sleep_for(chrono::milliseconds(delayMs)); } clears(); print(); if(aliveCount() == 1) { for(int id=1; id<=4; ++id) if(alive[id]) { cout << “Winner: P” << id << ”!” << endl; break; } } else { cout << “All snakes died. Draw!” << endl; } return 0; }