帮我实现一个简易贪吃蛇代码,要求cy语言
时间: 2024-03-18 16:41:22 浏览: 30
好的,以下是一个简单的贪吃蛇代码,使用C语言编写:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define ROW 20
#define COL 40
int snake[ROW*COL][2]; // 蛇身数组
int food[2]; // 食物位置
int score = 0; // 得分
int head, tail; // 蛇头和蛇尾位置
char direction = 'D'; // 初始方向
void init() {
// 初始化蛇身数组
head = tail = 0;
snake[head][0] = ROW / 2;
snake[head][1] = COL / 2;
tail++;
snake[tail][0] = ROW / 2;
snake[tail][1] = COL / 2 - 1;
tail++;
// 初始化食物位置
srand(time(NULL));
food[0] = rand() % ROW;
food[1] = rand() % COL;
}
void draw() {
system("cls"); // 清屏
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
if (i == snake[head][0] && j == snake[head][1]) { // 蛇头
printf("O ");
} else if (i == food[0] && j == food[1]) { // 食物
printf("* ");
} else {
int flag = 0;
for (int k = tail; k < head; k++) { // 蛇身
if (i == snake[k][0] && j == snake[k][1]) {
printf("o ");
flag = 1;
break;
}
}
if (!flag) {
printf(" ");
}
}
}
printf("\n");
}
printf("Score: %d\n", score);
}
void move() {
int next_row = snake[head][0], next_col = snake[head][1];
switch (direction) {
case 'W':
next_row--;
break;
case 'A':
next_col--;
break;
case 'S':
next_row++;
break;
case 'D':
next_col++;
break;
}
if (next_row < 0 || next_row >= ROW || next_col < 0 || next_col >= COL) { // 撞墙
printf("Game over!\n");
exit(0);
}
if (next_row == food[0] && next_col == food[1]) { // 吃到食物
score++;
food[0] = rand() % ROW;
food[1] = rand() % COL;
} else { // 移动
tail++;
}
head++;
snake[head][0] = next_row;
snake[head][1] = next_col;
}
int main() {
init();
while (1) {
draw();
if (kbhit()) { // 按键检测
char ch = getch();
if ((ch == 'W' && direction != 'S') || (ch == 'A' && direction != 'D') ||
(ch == 'S' && direction != 'W') || (ch == 'D' && direction != 'A')) {
direction = ch;
}
}
move();
for (int i = tail; i < head; i++) { // 撞到自己
if (snake[i][0] == snake[head][0] && snake[i][1] == snake[head][1]) {
printf("Game over!\n");
exit(0);
}
}
Sleep(100); // 控制速度
}
return 0;
}
```
以上代码是使用Windows API的Sleep函数控制速度,因此需要在Windows下编译运行。如果要在Linux下运行,需要使用头文件`<unistd.h>`中的`usleep()`函数来控制速度。