**小时候玩过的贪吃蛇是这样的:
或者是这样的:
而我现在能打出来的却是:
只能说是:理想很丰满,现实很骨感。
这两周的作业都是“贪吃蛇”,这对一个小白来说简直是痛不欲生,因为不会做!所以网上查了很多资料以及看了很多dalao的文章,最后才勉勉强强打出走了很多弯路的贪吃蛇,见笑了。
首先是移动
const int dx[] = { 0, 0, -1, 1 };
const int dy[] = { -1, 1, 0, 0 };
void move(int dir) {
int nx = snakeX[0] + dx[dir];
int ny = snakeY[0] + dy[dir];
if (!isFoodCell(nx, ny)) {
if (mp[nx][ny] == SNAKE_BODY || isOutOfBound(nx, ny)) {
gameOver = 1;
return;
}
--snakeLength;
updateMap(snakeX[snakeLength], snakeY[snakeLength], EMPTY_CELL);
}
else {
if (!generateFood()) {
win = 1;
return;
}
}
if (snakeLength > 0)
updateMap(snakeX[0], snakeY[0], SNAKE_BODY);
updateMap(nx, ny, SNAKE_HEAD);
for (int i = snakeLength; i; --i) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
++snakeLength;
snakeX[0] = nx;
snakeY[0] = ny;
}
这里面融合了是否吃到食物的判断以及对应的“增长”“不变”;
而食物的产生肯定也要一个函数
int generateFood() {
do {
if (snakeLength >= n * m - 1) {
return 0;
}
foodX = random(n);
foodY = random(m);
} while (mp[foodX][foodY] != EMPTY_CELL);
updateMap(foodX, foodY, FOOD_CELL);
return 1;
}
关于地图的初始化以及每次“操作”之后的更新
void outputMap() {
for (int i = 0; i <= n + 1; ++i) {
for (int j = 0; j <= m + 1; ++j)
putchar(mp[i][j]);
putchar('\n');
}
}
int isFoodCell(int x, int y) {
return x == foodX && y == foodY;
}
int random(int n) {
return (int)(rand() * 1.0 / RAND_MAX * n + 1);
}
int isOutOfBound(int x, int y) {
return x < 1 || x > n || y < 1 || y > m;
}
void updateMap(int x, int y, char newChar) {
mp[x][y] = newChar;
setCursor(y, x);
putchar(newChar);
}
最后就是主函数
int main() {
int d;
char ch;
srand(time(0));
do {
printf("Please enter the size of map, height first, width second: ");
scanf("%d%d", &n, &m);
if (n < 2 || m < 2 || n > 254 || m > 254) {
printf("Your input is not valid, 5 <= n <= 254, 5 <= m <= 254\n");
}
else {
break;
}
} while (1);
initMap();
initSnake();
clearScreen();
outputMap();
while (!gameOver) {
ch = _getch();
if (ch >= 'a' && ch <= 'z') {
ch = ch - 'a' + 'A';
}
switch (ch) {
case 'A': d = 0; break;
case 'D': d = 1; break;
case 'W': d = 2; break;
case 'S': d = 3; break;
case ESCAPE: return 0; break;
default: continue;
}
move(d);
setCursor(0, n + 2);
if (gameOver) {
printf("Game Over! Your final score is %d.\n", snakeLength - 1);
break;
}
if (win) {
printf("Congraulations!\n");
break;
}
}
return 0;
}
此处受到dalao指点:对于方向的操控,只需要用一个case,分别让w、a、s、d对应0、1、2、3;从而“激活”函数move 中的dx dy;从而达到移动的目的,最后就可以简化程序。
至于其他的代码,都是抄网上的,我也不知道原理是什么,在此就不一一打出来解释了,反正…就是做了很久,模仿dalao以及网上的帖子也是很痛苦…
然后经过多次试验,使用“单身已久”的手速(好吧其实是快进),就可以达到这样的效果
**
That’s all. Thanks for reading.