用c语言写个贪吃蛇代码
时间: 2023-06-19 12:09:04 浏览: 111
以下是一个基本的贪吃蛇游戏的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include <windows.h>
#define width 20
#define height 20
int snake[100][2];
int length = 3;
int food[2];
int score = 0;
int direction = 1; // 1: up, 2: down, 3: left, 4: right
void init() {
srand((unsigned)time(NULL)); // 随机数种子
snake[0][0] = height / 2;
snake[0][1] = width / 2;
for (int i = 1; i < length; i++) {
snake[i][0] = snake[0][0] + i;
snake[i][1] = snake[0][1];
}
food[0] = rand() % height;
food[1] = rand() % width;
score = 0;
direction = 1;
}
void draw() {
system("cls"); // 清屏
for (int i = 0; i < width + 2; i++) {
printf("#");
}
printf("\n");
for (int i = 0; i < height; i++) {
printf("#");
for (int j = 0; j < width; j++) {
if (i == snake[0][0] && j == snake[0][1]) {
printf("O");
} else if (i == food[0] && j == food[1]) {
printf("$");
} else {
int flag = 0;
for (int k = 1; k < length; k++) {
if (i == snake[k][0] && j == snake[k][1]) {
printf("o");
flag = 1;
break;
}
}
if (!flag) {
printf(" ");
}
}
}
printf("#\n");
}
for (int i = 0; i < width + 2; i++) {
printf("#");
}
printf("\n");
printf("Score: %d\n", score);
}
void update() {
int tail[2] = {snake[length - 1][0], snake[length - 1][1]};
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 1:
snake[0][0]--;
break;
case 2:
snake[0][0]++;
break;
case 3:
snake[0][1]--;
break;
case 4:
snake[0][1]++;
break;
}
if (snake[0][0] == food[0] && snake[0][1] == food[1]) {
length++;
score += 10;
food[0] = rand() % height;
food[1] = rand() % width;
}
if (snake[0][0] < 0 || snake[0][0] >= height || snake[0][1] < 0 || snake[0][1] >= width) {
init();
}
for (int i = 1; i < length; i++) {
if (snake[0][0] == snake[i][0] && snake[0][1] == snake[i][1]) {
init();
}
}
}
void input() {
if (kbhit()) { // 检测是否有按键输入
char c = getch(); // 获取按键
if (c == 'w' && direction != 2) {
direction = 1;
} else if (c == 's' && direction != 1) {
direction = 2;
} else if (c == 'a' && direction != 4) {
direction = 3;
} else if (c == 'd' && direction != 3) {
direction = 4;
}
}
}
int main() {
init();
while (1) {
draw();
update();
input();
Sleep(100); // 休眠 100 毫秒
}
return 0;
}
```
请注意,此代码使用了 Windows 系统下的 `conio.h` 头文件,可能不适用于其他操作系统。
阅读全文