给我写贪吃蛇C语言代码
时间: 2023-03-01 09:03:22 浏览: 127
好的,这是一份简单的贪吃蛇的C语言代码:
```
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#define UP 72
#define LEFT 75
#define RIGHT 77
#define DOWN 80
#define WIDTH 20
#define HEIGHT 20
void gotoxy(int x, int y) {
COORD pos = {x, y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void hidecursor() {
CONSOLE_CURSOR_INFO cursor_info = {1, 0};
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
void draw(int x, int y, char use) {
gotoxy(x, y); printf("%c", use);
}
int main() {
int x, y, fruitx, fruity, gameover, score, flag;
int tailx[100], taily[100];
int ntail;
char key;
hidecursor();
gameover = 0;
x = WIDTH / 2;
y = HEIGHT / 2;
fruitx = rand() % WIDTH;
fruity = rand() % HEIGHT;
score = 0;
while (!gameover) {
// 在图形界面边界画边框
for (int i = 0; i < WIDTH + 2; i++) {
draw(i, 0, '#');
draw(i, HEIGHT + 1, '#');
}
for (int i = 0; i < HEIGHT + 2; i++) {
draw(0, i, '#');
draw(WIDTH + 1, i, '#');
}
// 画出蛇头和蛇尾
draw(x, y, 'O');
for (int i = 0; i < ntail; i++) {
draw(tailx[i], taily[i], 'o');
}
// 画出水果
draw(fruitx, fruity, 'F');
// 移动蛇尾
for (int i = ntail - 1; i > 0; i--) {
tailx[i] = tailx[i - 1];
taily[i] = taily[i - 1];
}
tailx[0] = x;
taily[0] = y;
// 获取方向键
key = getch();
// 移动蛇头
if (key == RIGHT) x++;
else if (key == LEFT) x--;
else if (key == UP) y--;
else if (key == DOWN) y++;
// 游戏结
阅读全文