贪吃蛇代码实现
WightyIflia · · 个人记录
考场上采用了的刷屏和随机数为。
int t=66603;
ll get()
{
return (t=(t*8866)+(t>>(1<<4)))&((1<<4)-1);
}
void screenclear()
{
for(ll i=1;i<=100;++i)
{
cout << endl;
}
}
#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";
}