用c语言写个贪吃蛇
时间: 2023-12-17 15:03:53 浏览: 41
好的,下面是一个简单的贪吃蛇游戏:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define WIDTH 30
#define HEIGHT 20
int snake[WIDTH * HEIGHT][2]; // 蛇身位置
int food[2]; // 食物位置
int length = 3; // 蛇身长度
int direction = 0; // 蛇头方向:0-右,1-下,2-左,3-上
int score = 0; // 得分
void init();
void draw();
void generate_food();
int is_eat_food();
int is_hit_wall();
int is_hit_self();
void move();
int main() {
init();
while (1) {
draw();
if (is_eat_food()) {
generate_food();
length++;
score++;
}
if (is_hit_wall() || is_hit_self()) {
printf("\n\nGame over! Your score is %d.\n", score);
system("pause");
return 0;
}
move();
Sleep(100);
}
return 0;
}
void init() {
srand((unsigned)time(NULL)); // 随机数种子
// 初始化蛇头和蛇身
snake[0][0] = rand() % (WIDTH - 4) + 2;
snake[0][1] = rand() % (HEIGHT - 4) + 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];
// 初始化食物
generate_food();
}
void draw() {
system("cls");
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (i == 0 || i == HEIGHT - 1 || j == 0 || j == WIDTH - 1) {
printf("#");
}
else if (i == food[1] && j == food[0]) {
printf("*");
}
else {
int flag = 0;
for (int k = 0; k < length; k++) {
if (j == snake[k][0] && i == snake[k][1]) {
printf("O");
flag = 1;
break;
}
}
if (!flag) {
printf(" ");
}
}
}
printf("\n");
}
printf("Score: %d\n", score);
}
void generate_food() {
int x, y;
do {
x = rand() % (WIDTH - 2) + 1;
y = rand() % (HEIGHT - 2) + 1;
} while (x == food[0] && y == food[1]);
food[0] = x;
food[1] = y;
}
int is_eat_food() {
if (snake[0][0] == food[0] && snake[0][1] == food[1]) {
return 1;
}
return 0;
}
int is_hit_wall() {
if (snake[0][0] == 0 || snake[0][0] == WIDTH - 1 || snake[0][1] == 0 || snake[0][1] == HEIGHT - 1) {
return 1;
}
return 0;
}
int is_hit_self() {
for (int i = 1; i < length; i++) {
if (snake[0][0] == snake[i][0] && snake[0][1] == snake[i][1]) {
return 1;
}
}
return 0;
}
void move() {
// 蛇身跟随蛇头移动
for (int i = length - 1; i > 0; i--) {
snake[i][0] = snake[i - 1][0];
snake[i][1] = snake[i - 1][1];
}
// 根据方向移动蛇头
switch (direction) {
case 0: // 右
snake[0][0]++;
break;
case 1: // 下
snake[0][1]++;
break;
case 2: // 左
snake[0][0]--;
break;
case 3: // 上
snake[0][1]--;
break;
}
// 检查是否撞到墙或自己
if (is_hit_wall() || is_hit_self()) {
return;
}
// 检查是否吃到食物
if (is_eat_food()) {
generate_food();
length++;
score++;
}
// 检查是否改变方向
if (_kbhit()) {
char ch = _getch();
switch (ch) {
case 'a':
if (direction != 0) {
direction = 2;
}
break;
case 's':
if (direction != 3) {
direction = 1;
}
break;
case 'd':
if (direction != 2) {
direction = 0;
}
break;
case 'w':
if (direction != 1) {
direction = 3;
}
break;
}
}
}
```
注意:该程序只能在 Windows 操作系统下运行,因为使用了 `conio.h` 头文件中的 `_kbhit()` 和 `_getch()` 函数。如果在其他操作系统下运行,需要使用相应的函数替代。