#include#include #include #include #include #include #include #define WIDE 60 #define HIGH 20 #define _CRT_SECURE_NO_WARNINGS int score = 0; int qx = 0; int qy = 0; int lX = 0; int lY = 0; int sleepSecond = 400; struct BODY { int x; int y; }; struct FOOD { int x; int y; }food; struct SNAKE { struct BODY body[WIDE*HIGH]; int size; }snake; void initWall(void) { int i=0; int j=0; for (i = 0; i <= HIGH; i++) { for (j = 0; j <= WIDE; j++) { if (j == WIDE) { printf("|"); } else if (i == HIGH) { printf("_"); } else { printf(" "); } } printf("n"); } } void pos(int x,int y) { COORD coord; HANDLE houtput; coord.X=x; coord.Y=y; houtput=GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(houtput, coord); } void initSnake(void) { snake.size = 2; snake.body[0].x = WIDE / 2; snake.body[0].y = HIGH / 2; snake.body[1].x = WIDE / 2 - 1; snake.body[1].y = HIGH / 2; return; } void initFood(void) { srand(time(NULL)); food.x = rand() % WIDE; food.y = rand() % HIGH; return; } void initUI(void) { COORD coord = {0}; int i=0; for ( i = 0; i < snake.size; i++) { pos(snake.body[i].x,snake.body[i].y); if (i == 0) putchar('@'); else putchar('*'); } pos(lX,lY); putchar(' '); pos( food.x, food.y); putchar('#'); } void playGame(void) { char key = 'd'; int i=0; while (snake.body[0].x >= 0 && snake.body[0].x < WIDE && snake.body[0].y >= 0 && snake.body[0].y < HIGH) { initUI(); if (_kbhit()) { key = _getch(); } switch (key) { case 'w': qx = 0; qy = -1; break; case 's': qx = 0; qy = +1; break; case 'd': qx = +1; qy = 0; break; case 'a': qx = -1; qy = 0; break; default: break; } for (i = 1; i < snake.size; i++) { if (snake.body[0].x == snake.body[i].x && snake.body[0].y == snake.body[i].y) { return; } } if (snake.body[0].x == food.x && snake.body[0].y == food.y) { initFood(); snake.size++; score += 10; sleepSecond -= 5; } lX = snake.body[snake.size - 1].x; lY = snake.body[snake.size - 1].y; for (i = snake.size - 1; i > 0; i--) { snake.body[i].x = snake.body[i - 1].x; snake.body[i].y = snake.body[i - 1].y; } snake.body[0].x += qx; snake.body[0].y += qy; Sleep(sleepSecond); //system("cls"); } return; } void showScore(void) { COORD coord; coord.X = 0; coord.Y = HIGH + 2; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); printf("Game Over!!!n"); printf("成绩为:%dn", score); } int main() { CONSOLE_CURSOR_INFO cci; cci.dwSize = sizeof(cci); cci.bVisible = FALSE; SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci); srand(time(NULL)); initSnake(); initFood(); initWall(); initUI(); playGame(); showScore(); return 0; }
代码有许多不足,请大家多多指正
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)