1. 程式人生 > >貪吃蛇C++

貪吃蛇C++

貪吃蛇(codeblocks)C++

#include
#include <windows.h>
#include <time.h>
#include <conio.h>
using namespace std;
//int N = 22;
inline void Refresh( char q[][22],int grade,int gamespeed)
{
system(“cls”);
cout << endl;
for( int i = 0 ; i < 22; ++i)
{
cout << “\t”;
for( int j = 0; j < 22; ++j)
cout << q[i][j] << “”;
if( i == 0 ) cout << “\t等級為:” << grade;
if( i == 4 ) cout <<"\t自動前進時間";
if( i == 6 ) cout << “\t間隔為:” <<gamespeed << “ms” << endl;
}
}
int main()
{
char tcsQipan[22][22];
int i , j ;
for( i = 1; i <= 20 ; ++i)
for( j = 1; j <= 20; ++j)
tcsQipan[i][j] = ’ ';//初始化貪吃蛇棋盤中間部分
for( i = 0; i <=21; ++i)
tcsQipan[0][i] = tcsQipan[21][i] = ‘-’;
for( j = 0; j <=20; ++j)
tcsQipan[i][0] = tcsQipan[i][21] = ‘-’;
int tcsZB[2][100];
for( i = 0; i < 4; ++i)
{
tcsZB[0][i] = 1;
tcsZB[1][i] = i+1;
}
int head = 3,tail = 0;
for( int i = 1; i <= 3; ++i )
tcsQipan[1][i] = ‘’;//蛇身
tcsQipan[1][4] = ‘#’;//蛇頭
int x1,y1;
srand(time(0));
do
{
x1 = rand()% 20+1;
y1 = rand()% 20 +1;
}while( tcsQipan[x1][y1] != ’ ');
tcsQipan[x1][y1] = '

’;
cout << “\n\n\t\t貪吃蛇遊戲即將開始!”<<endl;
long start;
int grade = 1,length = 4;
int gamespeed = 500;
for( int i = 3; i >= 0 ; --i)
{
start = clock();
while( clock() - start <= 1000 );
system(“cls”);
if(i > 0)
cout << “\n\n\t\t進入倒計時:” << i << endl;
else
Refresh(tcsQipan,grade,gamespeed);
}
int timeover;
char direction = 77;
int x,y;
while(1)
{
timeover = 1;
start = clock();
while((timeover = (clock()-start <= gamespeed)) && !kbhit());//如果按鍵按下或時間超過前進時間間隔則終止迴圈
if(timeover)
{
getch();direction = getch();
}
switch(direction)
{
case 72: x = tcsZB[0][head] -1 ; y = tcsZB[1][head]; break;//向上
case 80: x = tcsZB[0][head] + 1 ; y = tcsZB[1][head]; break;//向下
case 75: x = tcsZB[0][head] + 1 ; y = tcsZB[1][head] - 1; break;//向左
case 77: x = tcsZB[0][head] ; y = tcsZB[1][head] + 1; break;//向右
}
if ( !(direction == 72)|| direction == 80 || direction == 75 || direction == 77)//按鍵非方向鍵
{
cout << “\tgame over!” << endl;
system(“pause”);return 0;
}
if( x0 || x
21 || y== 0 || y== 21)//碰壁
{
cout << “\tgame over!” << endl;
system(“pause”);return 0;
}
if(tcsQipan[x][y]!= ’ ’ && !( x == x1 && y == y1))
{
cout << “\tgame over!” << endl;
system(“pause”);return 0;
}
if(x == x1 && y == y1)//吃米
{
length++;
if(length >= 8)
{
length -= 8;
grade ++;
if (gamespeed >= 200)
gamespeed = 550 - grade * 50;
}
tcsQipan[x][y] = ‘#’;
tcsQipan[tcsZB[0][head]][tcsZB[1][head]] = ‘’;
head = (head + 1)%100;
tcsZB[0][head] = x;
tcsZB[1][head] = y;
do
{
x1 = rand()% 20+1;
y1 = rand() % 20 +1;
}while( tcsQipan[x1][y1] != ’ ');
tcsQipan[x1][y1] = '
’;
Refresh(tcsQipan,grade,gamespeed);
}
else
{
tcsQipan[tcsZB[0][tail]][tcsZB[1][tail]] = ’ ';
tail = ( tail + 1)%100;
tcsQipan[tcsZB[0][head]][tcsZB[1][head]] = ‘*’;
head = ( head + 1)% 100;
tcsZB[0][head] = x;
tcsZB[1][head] = y;
tcsQipan[tcsZB[0][head]][tcsZB[1][head]]= ‘#’;
Refresh(tcsQipan,grade,gamespeed);
}
}
return 0;
}