你可以给我一个贪吃蛇的c语言代码吗?
时间: 2023-03-26 21:01:55 浏览: 55
可以的,以下是一个简单的贪吃蛇的 C 语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 20
#define HEIGHT 20
int snake[100][2];
int food[2];
int score = ;
int length = 1;
int direction = ; // : up, 1: right, 2: down, 3: left
void init() {
snake[][] = HEIGHT / 2;
snake[][1] = WIDTH / 2;
food[] = rand() % HEIGHT;
food[1] = rand() % WIDTH;
}
void draw() {
system("cls");
for (int i = ; i < HEIGHT; i++) {
for (int j = ; j < WIDTH; j++) {
if (i == snake[][] && j == snake[][1]) {
printf("O");
} else if (i == food[] && j == food[1]) {
printf("*");
} else {
int is_body = ;
for (int k = 1; k < length; k++) {
if (i == snake[k][] && j == snake[k][1]) {
printf("o");
is_body = 1;
break;
}
}
if (!is_body) {
printf(" ");
}
}
}
printf("\n");
}
printf("Score: %d\n", score);
}
void update() {
int tail[2];
tail[] = snake[length - 1][];
tail[1] = snake[length - 1][1];
for (int i = length - 1; i > ; i--) {
snake[i][] = snake[i - 1][];
snake[i][1] = snake[i - 1][1];
}
if (direction == ) {
snake[][]--;
} else if (direction == 1) {
snake[][1]++;
} else if (direction == 2) {
snake[][]++;
} else if (direction == 3) {
snake[][1]--;
}
if (snake[][] == food[] && snake[][1] == food[1]) {
score++;
length++;
food[] = rand() % HEIGHT;
food[1] = rand() % WIDTH;
}
if (snake[][] < || snake[][] >= HEIGHT || snake[][1] < || snake[][1] >= WIDTH) {
printf("Game Over!\n");
exit();
}
for (int i = 1; i < length; i++) {
if (snake[][] == snake[i][] && snake[][1] == snake[i][1]) {
printf("Game Over!\n");
exit();
}
}
}
void input() {
if (_kbhit()) {
int key = _getch();
if (key == 'w' || key == 'W') {
if (direction != 2) {
direction = ;
}
} else if (key == 'd' || key == 'D') {
if (direction != 3) {
direction = 1;
}
} else if (key == 's' || key == 'S') {
if (direction != ) {
direction = 2;
}
} else if (key == 'a' || key == 'A') {
if (direction != 1) {
direction = 3;
}
}
}
}
int main() {
init();
while (1) {
draw();
update();
input();
Sleep(100);
}
return ;
}
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)