用C语言写一个贪吃蛇的游戏
时间: 2023-03-19 16:22:03 浏览: 57
好的,下面是一个简单的用C语言实现的贪吃蛇游戏的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include <windows.h>
#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77
void gotoxy(int x, int y) {
COORD coord = {x, y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void hidecursor() {
CONSOLE_CURSOR_INFO cursor_info = {1, 0};
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
void draw_wall(int width, int height) {
int i, j;
for (i = 0; i < width; i++) {
gotoxy(i, 0);
putchar('*');
gotoxy(i, height - 1);
putchar('*');
}
for (j = 0; j < height; j++) {
gotoxy(0, j);
putchar('*');
gotoxy(width - 1, j);
putchar('*');
}
}
void draw_snake(int x[], int y[], int length) {
int i;
for (i = 0; i < length; i++) {
gotoxy(x[i], y[i]);
if (i == 0) {
putchar('@');
} else {
putchar('#');
}
}
}
void move_snake(int x[], int y[], int length, int dir) {
int i;
for (i = length - 1; i > 0; i--) {
x[i] = x[i - 1];
y[i] = y[i - 1];
}
switch (dir) {
case UP:
y[0]--;
break;
case DOWN:
y[0]++;
break;
case LEFT:
x[0]--;
break;
case RIGHT:
x[0]++;
break;
}
}
int check_collision(int x[], int y[], int length, int width, int height) {
int i;
if (x[0] == 0 || x[0] == width - 1 || y[0] == 0 || y[0] == height - 1) {
return 1;
}
for (i = 1; i < length; i++) {
if (x[0] == x[i] && y[0] == y[i]) {
return 1;
}
}
return 0;
}
void generate_food(int *food_x, int *food_y, int width, int height, int x[], int y[], int length) {
int i;
do {
*food_x = rand() % (width - 2) + 1;
*food_y = rand() % (height - 2) + 1;
for (i = 0; i < length; i++) {
if (*food_x == x[i] && *food_y == y[i]) {
break;
}
}
} while (i < length);
gotoxy(*food_x, *food_y);
putchar('$');
}
int main() {
int width = 40;
int height = 20;
int x[100], y[100];
int length = 3;
int dir = RIGHT;
int food_x, food_y;
int score = 0;
hidecursor();
srand((unsigned)time
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)