|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 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[20][20],snake[200][2];
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[0][0]=1;
snake[0][1]=1;
snake[1][0]=2;
snake[1][1]=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[i][j]==1)cout<<'#';
else if(game[i][j]==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[snakelong-1][0];
taily=snake[snakelong-1][1];
for(int i=snakelong-1;i>=1;--i)
{
snake[i][0]=snake[i-1][0];
snake[i][1]=snake[i-1][1];
}
switch(ch)
{
case 'a':snake[0][0]--;break;
case 'd':snake[0][0]++;break;
case 'w':snake[0][1]--;break;
case 'x':snake[0][1]++;break;
}
if(snake[0][0]==m&&snake[0][1]==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[snakelong-1][0]=tailx;
snake[snakelong-1][1]=taily;
}
if(snake[0][0]==0||snake[0][0]==19||snake[0][1]==0||snake[0][1]==19)
{
system("cls");
cout<<"GAME OVER"<<endl;
cout<<"long of your snake:"<<snakelong<<endl;
cout<<"your score:"<<score<<endl;
while(1)
{
}
}
else game[taily][tailx]=0;
for(int i=0;i<=19;++i)
{
for(int j=0;j<=19;++j)
{
if(i==0||i==19)game[i][j]=1;
if(j==0||j==19)game[i][j]=1;
if(j==m&&i==n)game[i][j]=3;
for(int n=0;n<=snakelong-1;++n)
{
if(snake[n][0]==j&&snake[n][1]==i)game[i][j]=2;
}
}
}
Sleep(speed);
}
}
|
|