把它转换成代码格式按照以下思路写出贪吃蛇代码int max, grade; //全局变量 int main() { #pragma warning (disable:4996) //消除警告 max = 0, grade = 0; //初始化变量 system(“title 贪吃蛇”); //设置cmd窗口的
时间: 2023-12-06 13:04:55 浏览: 77
标题
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include <windows.h>
#define MAX_X 40
#define MAX_Y 20
#define SNAKE_MAX_LENGTH 100
int map[MAX_Y][MAX_X]; //游戏地图
int snake[SNAKE_MAX_LENGTH][2]; //蛇身
int snake_length; //蛇的长度
int direction; //蛇的方向
int food_x, food_y; //食物的坐标
int score, max_score; //分数和最高分
void init_map() { //初始化地图
int i, j;
for (i = 0; i < MAX_Y; i++) {
for (j = 0; j < MAX_X; j++) {
if (i == 0 || i == MAX_Y - 1 || j == 0 || j == MAX_X - 1) {
map[i][j] = -1; //边界
} else {
map[i][j] = 0; //空地
}
}
}
}
void draw_map() { //绘制地图
int i, j;
system("cls"); //清屏
for (i = 0; i < MAX_Y; i++) {
for (j = 0; j < MAX_X; j++) {
switch (map[i][j]) {
case -1: printf("#"); break; //边界
case 0: printf(" "); break; //空地
case 1: printf("*"); break; //蛇身
case 2: printf("$"); break; //食物
}
}
printf("\n");
}
printf("得分:%d 最高分:%d\n", score, max_score);
}
void init_snake() { //初始化蛇
snake_length = 3;
snake[0][0] = MAX_X / 2; snake[0][1] = MAX_Y / 2; //蛇头
snake[1][0] = snake[0][0] - 1; snake[1][1] = snake[0][1]; //蛇身
snake[2][0] = snake[1][0] - 1; snake[2][1] = snake[1][1]; //蛇尾
direction = 'd'; //初始方向向右
}
void create_food() { //生成食物
int x, y;
do {
x = rand() % (MAX_X - 2) + 1; //随机生成x坐标,不能在边界上
y = rand() % (MAX_Y - 2) + 1; //随机生成y坐标,不能在边界上
} while (map[y][x] != 0); //如果生成的位置不是空地,则重新生成
food_x = x;
food_y = y;
}
void move_snake() { //移动蛇
int i;
int new_head_x = snake[0][0], new_head_y = snake[0][1];
switch (direction) {
case 'w': new_head_y--; break; //向上
case 's': new_head_y++; break; //向下
case 'a': new_head_x--; break; //向左
case 'd': new_head_x++; break; //向右
}
if (map[new_head_y][new_head_x] == -1 || map[new_head_y][new_head_x] == 1) { //撞墙或咬到自己
if (score > max_score) {
max_score = score;
}
score = 0;
init_map();
init_snake();
create_food();
return;
}
if (new_head_x == food_x && new_head_y == food_y) { //吃到食物
snake_length++;
score += 10;
create_food();
} else { //移动蛇身
map[snake[snake_length - 1][1]][snake[snake_length - 1][0]] = 0; //清除蛇尾
for (i = snake_length - 1; i > 0; i--) { //蛇身向前移动
snake[i][0] = snake[i - 1][0];
snake[i][1] = snake[i - 1][1];
map[snake[i][1]][snake[i][0]] = 1; //更新地图
}
}
snake[0][0] = new_head_x;
snake[0][1] = new_head_y;
map[new_head_y][new_head_x] = 1; //更新地图
}
void game_loop() { //游戏循环
int ch;
while (1) {
draw_map();
move_snake();
if (_kbhit()) { //检测按键
ch = _getch();
switch (ch) {
case 'w': case 's': case 'a': case 'd': direction = ch; break; //改变方向
case 'q': return; //退出游戏
}
}
Sleep(100); //延时
}
}
int main() {
srand((unsigned)time(NULL)); //随机数种子
init_map();
init_snake();
create_food();
game_loop();
return 0;
}
```
阅读全文