贪吃蛇代码分享
本帖最后由 hankmaths 于 2020-8-25 18:35 编辑前几天用C++写了一个贪吃蛇,代码量也不多,给大家分享一下:
按WXAD分别控制上下左右,*是蛇,o是食物,#是墙
#include<iostream>
#include<stdio.h>
#include<conio.h>
#include<windows.h>
#include<time.h>
#include<bits/stdc++.h>
using namespace std;
int game,snake;
char ch,dic,c;
int snakelong=2,score,tailx,taily,step;
int m,n,f;
double speed=500;
int main()
{
srand((unsigned)time(NULL));
snake=1;
snake=1;
snake=2;
snake=1;
dic='d';
m=rand()%18+1;
n=rand()%18+1;
cout<<"Welcom to use Snake!"<<endl;
cout<<"Press any key to start the game."<<endl;
c=getch();
system("cls");
while(1)
{
system("cls");
for(int i=0;i<=19;++i)
{
for(int j=0;j<=19;++j)
{
if(game==1)cout<<'#';
else if(game==2)cout<<'*';
else if(i==n&&j==m)cout<<'o';
else cout<< ' ';
}
cout<<endl;
}
cout<<"long of your snake:"<<snakelong<<endl;
cout<<"your score:"<<score<<endl;
cout<<"speed:"<<speed/1000<<'s';
for(int i=1;i<=60;++i)ch=kbhit();
if(_kbhit())
{
ch=_getch();
dic=ch;
}
else ch=dic;
speed--;
tailx=snake;
taily=snake;
for(int i=snakelong-1;i>=1;--i)
{
snake=snake;
snake=snake;
}
switch(ch)
{
case 'a':snake--;break;
case 'd':snake++;break;
case 'w':snake--;break;
case 'x':snake++;break;
}
if(snake==m&&snake==n)
{
Beep(659,150);
Beep(523,150);
speed-=20;
score+=snakelong+1;
snakelong++;
srand((unsigned)time(NULL));
m=rand()%18+1;
srand((unsigned)time(NULL));
n=rand()%18+1;
snake=tailx;
snake=taily;
}
if(snake==0||snake==19||snake==0||snake==19)
{
system("cls");
cout<<"GAME OVER"<<endl;
cout<<"long of your snake:"<<snakelong<<endl;
cout<<"your score:"<<score<<endl;
while(1)
{
}
}
else game=0;
for(int i=0;i<=19;++i)
{
for(int j=0;j<=19;++j)
{
if(i==0||i==19)game=1;
if(j==0||j==19)game=1;
if(j==m&&i==n)game=3;
for(int n=0;n<=snakelong-1;++n)
{
if(snake==j&&snake==i)game=2;
}
}
}
Sleep(speed);
}
}
页:
[1]