用c语言编写贪吃蛇代码是多少
时间: 2023-12-20 08:25:05 浏览: 73
超简单贪吃蛇c语言代码编写.pdf
以下是用C语言编写贪吃蛇游戏的基本代码,仅供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 30
#define HEIGHT 20
int map[HEIGHT][WIDTH];
typedef struct Snake
{
int x;
int y;
struct Snake *next;
} Snake;
typedef struct Food
{
int x;
int y;
} Food;
Snake *head, *tail;
Food food;
int dir = 1;
int score = 0;
void init()
{
int i, j;
for (i = 0; i < HEIGHT; i++)
for (j = 0; j < WIDTH; j++)
map[i][j] = 0;
head = (Snake*)malloc(sizeof(Snake));
tail = (Snake*)malloc(sizeof(Snake));
head->x = WIDTH / 2;
head->y = HEIGHT / 2;
head->next = tail;
tail->x = head->x - 1;
tail->y = head->y;
tail->next = NULL;
map[head->y][head->x] = 1;
map[tail->y][tail->x] = 1;
food.x = rand() % WIDTH;
food.y = rand() % HEIGHT;
}
void draw()
{
int i, j;
system("cls");
printf("Score: %d\n\n", score);
for (i = 0; i < HEIGHT; i++)
{
for (j = 0; j < WIDTH; j++)
{
if (map[i][j] == 0)
printf(".");
else if (map[i][j] == 1)
printf("*");
else if (map[i][j] == 2)
printf("#");
else if (map[i][j] == 3)
printf("O");
}
printf("\n");
}
}
void update()
{
int i, j;
Snake *p = (Snake*)malloc(sizeof(Snake));
p->x = head->x;
p->y = head->y;
p->next = head->next;
head->next = p;
head->x += dir % 2 * (2 - dir);
head->y += (dir + 1) % 2 * (dir - 1);
if (head->x < 0 || head->x >= WIDTH || head->y < 0 || head->y >= HEIGHT || map[head->y][head->x] == 1)
exit(0);
if (head->x == food.x && head->y == food.y)
{
score++;
food.x = rand() % WIDTH;
food.y = rand() % HEIGHT;
}
else
{
map[tail->y][tail->x] = 0;
tail = tail->next;
free(tail->next);
tail->next = NULL;
}
p = head;
while (p != NULL)
{
map[p->y][p->x] = 1;
p = p->next;
}
map[food.y][food.x] = 2;
map[head->y][head->x] = 3;
}
void control()
{
if (_kbhit())
{
switch (_getch())
{
case 'w':
dir = 0;
break;
case 'a':
dir = 3;
break;
case 's':
dir = 2;
break;
case 'd':
dir = 1;
break;
}
}
}
int main()
{
init();
while (1)
{
draw();
update();
control();
Sleep(100);
}
return 0;
}
```
这只是一个简单的贪吃蛇游戏,你可以根据自己的需要进行修改和扩展。
阅读全文