马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在网上找了一份贪吃蛇的代码,复制完代码后编译运行一直报这个错误,在网上搜了半天也没明白得怎么整#include "ncurses.h"
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#define MAX_LEN 100 // 贪吃蛇最大长度
#define INIT_LEN 5 // 贪吃蛇初始长度
#define ROWS 20 // 地图行数
#define COLS 40 // 地图列数
#define SNAKE_CHAR 'O' // 贪吃蛇字符
#define FRUIT_CHAR 'x' // 食物字符
struct snake {
int len; // 贪吃蛇长度
int row[MAX_LEN], col[MAX_LEN]; // 贪吃蛇各节点的位置
int direction; // 贪吃蛇当前行进方向
};
struct fruit {
int row, col;
};
void draw_map();
void draw_snake(struct snake *s);
void draw_fruit(struct fruit *f);
void move_snake(struct snake *s, struct fruit *f);
void generate_fruit(struct snake *s, struct fruit *f);
void initialize_snake(struct snake *s);
int main() {
struct snake s;
struct fruit f;
srand(time(NULL)); // 初始化随机数生成器
initscr(); // 初始化 ncurses
noecho(); // 输入字符不回显
cbreak(); // 输入字符无需回车键
timeout(100); // 100ms 后超时 getch()
keypad(stdscr, TRUE); // 开启键盘支持
draw_map(); // 绘制地图
initialize_snake(&s); // 初始化贪吃蛇
generate_fruit(&s, &f); // 随机生成食物
while (1) {
draw_snake(&s); // 绘制贪吃蛇
draw_fruit(&f); // 绘制食物
move_snake(&s, &f); // 移动贪吃蛇
refresh(); // 刷新屏幕
}
endwin(); // 关闭 ncurses
return 0;
}
// 绘制地图
void draw_map() {
int i, j;
clear();
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if(i == 0 || j == 0 || i == ROWS-1 || j == COLS-1) {
mvprintw(i, j, "#");
}
}
}
}
// 初始化贪吃蛇
void initialize_snake(struct snake *s) {
int i;
s->len = INIT_LEN;
for (i = 0; i < s->len; i++) {
s->row[i] = ROWS/2;
s->col[i] = COLS/2 - i;
}
s->direction = KEY_RIGHT;
}
// 绘制贪吃蛇
void draw_snake(struct snake *s) {
int i;
for (i = 0; i < s->len; i++) {
mvprintw(s->row[i], s->col[i], "%c", SNAKE_CHAR);
}
}
// 绘制食物
void draw_fruit(struct fruit *f) {
mvprintw(f->row, f->col, "%c", FRUIT_CHAR);
}
// 移动贪吃蛇
void move_snake(struct snake *s, struct fruit *f) {
int i;
int ch = getch();
switch (ch) {
case KEY_UP:
case KEY_DOWN:
case KEY_LEFT:
case KEY_RIGHT:
s->direction = ch;
break;
}
for (i = s->len - 1; i > 0; i--) {
s->row[i] = s->row[i-1];
s->col[i] = s->col[i-1];
}
switch (s->direction) {
case KEY_UP:
s->row[0] --;
break;
case KEY_DOWN:
s->row[0] ++;
break;
case KEY_LEFT:
s->col[0] --;
break;
case KEY_RIGHT:
s->col[0] ++;
break;
}
if (s->row[0] == 0 || s->row[0] == ROWS-1
|| s->col[0] == 0 || s->col[0] == COLS-1) {
clear();
mvprintw(ROWS/2, COLS/2-5, "Game Over");
refresh();
sleep(2);
endwin();
exit(0);
}
if (s->row[0] == f->row && s->col[0] == f->col) {
s->len ++;
generate_fruit(s, f);
}
}
// 生成随机食物
void generate_fruit(struct snake *s, struct fruit *f) {
int i, j;
do {
f->row = rand() % (ROWS-2) + 1;
f->col = rand() % (COLS-2) + 1;
} while (mvinch(f->row, f->col) == SNAKE_CHAR);
for (i = 0; i < s->len; i++) {
if (f->row == s->row[i] && f->col == s->col[i]) {
generate_fruit(s, f);
break;
|