Linux下C编程设计贪吃蛇游戏的具体代码,需要使用ncurse库
时间: 2024-04-21 11:22:38 浏览: 18
下面是一个使用 ncurses 库在 Linux 下用 C 语言编写的简单贪吃蛇游戏的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <ncurses.h>
#define DELAY 100000
int main()
{
int x, y, maxX, maxY;
int direction = KEY_RIGHT;
int snakeLength = 5;
int gameOver = 0;
int score = 0;
/* 初始化 ncurses */
initscr();
noecho();
curs_set(0);
keypad(stdscr, TRUE);
timeout(0);
/* 获取窗口大小 */
getmaxyx(stdscr, maxY, maxX);
/* 初始化蛇的位置 */
x = maxX / 2;
y = maxY / 2;
/* 初始化随机数种子 */
srand(time(NULL));
/* 初始化食物的位置 */
int foodX = (rand() % (maxX - 2)) + 1;
int foodY = (rand() % (maxY - 2)) + 1;
/* 游戏循环 */
while (!gameOver) {
clear();
/* 绘制蛇头 */
mvprintw(y, x, "O");
/* 绘制蛇身 */
for (int i = 1; i < snakeLength; i++) {
mvprintw(y, x - i, "o");
}
/* 绘制食物 */
mvprintw(foodY, foodX, "*");
/* 显示得分 */
mvprintw(0, 0, "Score: %d", score);
refresh();
usleep(DELAY);
/* 处理用户输入 */
int input = getch();
switch (input) {
case KEY_UP:
direction = KEY_UP;
break;
case KEY_DOWN:
direction = KEY_DOWN;
break;
case KEY_LEFT:
direction = KEY_LEFT;
break;
case KEY_RIGHT:
direction = KEY_RIGHT;
break;
default:
break;
}
/* 更新蛇的位置 */
switch (direction) {
case KEY_UP:
y--;
break;
case KEY_DOWN:
y++;
break;
case KEY_LEFT:
x--;
break;
case KEY_RIGHT:
x++;
break;
default:
break;
}
/* 检查是否吃到食物 */
if (x == foodX && y == foodY) {
score++;
snakeLength++;
foodX = (rand() % (maxX - 2)) + 1;
foodY = (rand() % (maxY - 2)) + 1;
}
/* 检查游戏是否结束 */
if (x <= 0 || x >= maxX - 1 || y <= 0 || y >= maxY - 1) {
gameOver = 1;
}
for (int i = 1; i < snakeLength; i++) {
if (x - i == x && y == y) {
gameOver = 1;
}
}
}
/* 清理资源 */
endwin();
printf("Game Over! Your score: %d\n", score);
return 0;
}
```
这段代码使用了 ncurses 库来在终端上进行图形界面的显示,实现了贪吃蛇游戏的基本功能。你可以将代码保存为一个名为 "snake.c" 的文件,然后使用 GCC 编译器进行编译:gcc -o snake snake.c -lncurses。编译成功后,运行生成的可执行文件 "./snake" 即可开始游戏。