让蛇动起来
放置奖励的食物
在蛇吃到食物时延长蛇的身体
设置游戏结束的机制
让蛇动起来
先设置一下相应的字符表示:
char BLANK_CHAR = ’ ‘;
char WALL_CHAR = ‘*’;
char SNAKE_HEAD_CHAR = ‘H’;
char SNAKE_BODY_CHAR = ‘X’;
char FOOD_CHAR = ‘
′;在这里,我们用∗来围成墙体,用
来表示食物,用 H 来表示蛇头,用 X 来表示蛇的身体。
绘出一个方形区域,这是蛇身活动的范围。
char map[12][13] = {
“**”,
“* *”,
“* *”,
“* *”,
“* *”,
“* *”,
“* *”,
“* *”,
“* *”,
“* *”,
“* *”,
“**”,
};
初始化变量:
int myMin(int array[4]) {
int i;
int Min = array[0];
for (i = 1; i < 4; i++) {
if (array[i] < Min) Min = array[i];
}
for (i = 0; i < 4; i++) {
if (array[i] == Min) break;
}
return i;
}
char whereToGo(int Hx, int Hy, int Fx, int Fy) {
char direction[4] = { ‘W’, ‘A’, ‘S’, ‘D’ };
int distance[4] = { 0, 0, 0, 0 };
int result[4][2] = { { Hx, Hy - 1 },{ Hx - 1, Hy },{ Hx, Hy + 1 },{ Hx + 1, Hy } };
int i;
for (i = 0; i < 4; i++) {
if (map[result[i][1]][result[i][0]] != ‘*’ && map[result[i][1]][result[i][0]] != ‘X’) {
distance[i] = abs(result[i][0] - Fx) + abs(result[i][1] - Fy);
}
else distance[i] = 9999;
}
int index_Min = myMin(distance);
return direction[index_Min];
}
oid set_path(char path[]){
int count = 0;
int originalX = snakeX[0];
int originalY = snakeY[0];
while(snakeX[0] != foodX || snakeY[0] != foodY){
path[count] = whereToGo(snakeX[0], snakeY[0], foodX, foodY);
map[snakeY[0]][snakeX[0]] == ‘X’;
int x = path[count];
switch (x) {
case ‘A’:
snakeX[0] = snakeX[0] - 1;
break;
case ‘W’:
snakeY[0] = snakeY[0] - 1;
break;
case ‘D’:
snakeX[0] = snakeX[0] + 1;
break;
case ‘S’:
snakeY[0] = snakeY[0] + 1;
break;
}
if(map[snakeY[0]][snakeX[0]] == '*' || map[snakeY[0]][snakeX[0]] == 'X'){
p = 0;
return;
}
printf("%c\n",path[count]);
prediction_X[count] = snakeX[0];
prediction_Y[count] = snakeY[0];
count++;
if(count < snake_length) map[snakeY[snake_length-count]][snakeX[snake_length-count]] = ' ';
}
snakeX[0] = originalX;
snakeY[0] = originalY;
map[snakeY[0]][snakeX[0]] = 'H';
reset(map, count);
on_my_way = 1;
//printf("in\n");
}
void reset(char map[12][12], int n){
int i,j;
for(j = 1; j < n-1; j++){
map[prediction_Y[j]][prediction_X[j]] = ' ';
}
for(i = 1; i < snake_length; i++){
map[snakeY[i]][snakeX[i]] = 'X';
}