C++课程设计贪吃蛇小游戏(内附完整源码与附件) 下载本文

// 初始化蛇尾 tailX = tailY =

N/2-1; N/ 2;

map[tailY][tailX] =

TAIL ;

directionMap[tailY][tailX] =

RIGHT; // 记录蛇尾的移动方向

// 初始化食物

srand( unsigned (time( NULL))); do {

foodX = rand() % (

/ / 随机播种

N - 1) + 1; N - 1) + 1;

// 产生随机数 1~(N-1)

foodY = rand() % (

} while ( EMPTY!= map[foodY][foodX]); map[foodY][foodX] =

FOOD;

// 首次显示游戏界面

for (i = 0; i <

for (j = 0; j <

{

N; i++) {

N; j++)

switch (map[i][j])

case WALL:cout << \■\; break ; case HEAR:cout << \○\; break ; case BODY: case TAIL :cout default :

cout <<\break ;

}

<< \●\; break ;

break ;

case FOOD:cout << \★\

;

cout

<< endl;

}

}

void

RetroSnaker ::gotoXY(

COORDcoord; coord.X = 2* coord.Y =

y ;

x ;

int x, int y)

{

SetConsoleCursorPosition(GetStdHandle(

STD_OUTPUT_HANDLE), coord);

}

void RetroSnaker ::againFood() {

srand( unsigned (time( NULL)));

/ / 随机播种

do {

foodX = rand() % (

N - 1) + 1; N - 1) + 1;

// 产生随机数 1~(N-1)

foodY = rand() % (

map[foodY][foodX] = gotoXY(foodX, foodY); cout << \★\

}

} while ( EMPTY!= map[foodY][foodX]);

FOOD;

void RetroSnaker ::erasingTheTail() {

gotoXY(tailX, tailY); cout << \ \ ; map[tailY][tailX] =

// 擦除尾巴

EMPTY;

if ( UP == directionMap[tailY][tailX]) {

directionMap[tailY][tailX] = tailY--;

EMPTY;

}

else if

( DOWN== directionMap[tailY][tailX]) {

EMPTY;

directionMap[tailY][tailX] = tailY++;

}

else if

( LEFT == directionMap[tailY][tailX]) {

EMPTY;

directionMap[tailY][tailX] = tailX--;

}

else {

directionMap[tailY][tailX] = tailX++;

EMPTY;

}

map[tailY][tailX] =

}

TAIL ;

void RetroSnaker ::erasingTheHear( {

char ch )

int x= hearX, y = hearY;

if ( UP == ch )

--hearY; ++hearY;

else if ( DOWN== ch )

else if ( LEFT == ch )

hearX--;

else

hearX++;

map[y][x] =

BODY;

// 擦除蛇头,绘制蛇身

gotoXY(x, y); cout << \●\

directionMap[hearY][hearX] = directionMap[y][x];

// 绘制蛇头

map[hearY][hearX] = HEAR; gotoXY(hearX, hearY);

cout << \○\;

}

int main( void ) {

char ch; bool sign =

false ;

DWORDkeyTime=0; RetroSnaker r; while ( true ) {

if (r.gameOver) {

// 游戏结束

_getch(); break ;

}

if (_kbhit()) {

//

检测是否按下键盘

ch = _getch(); // 获取该按键,并不回显在屏幕上

sign =

true ;

}

if (GetTickCount()- keyTime >

GMAE_TIME&&sign) {

GMAE_TIME 毫秒则移动蛇

r.move(ch); // 移动蛇

keyTime = GetTickCount();

sign = false ;

} else {

// 没按下键盘,则默认处理

if (GetTickCount() - keyTime >

GMAE_TIME) {

GMAE_TIME 毫秒则移动蛇

r.move();

//

默认移动

keyTime = GetTickCount();

}

//

两次按键的间隔时间大于

//

两次按键的间隔时间大于

main.cpp

件贪吃蛇VC6.0++项目 .zip

}

}

return 0;

}