写一段贪吃蛇的C++代码
时间: 2023-06-19 15:04:29 浏览: 104
以下是一个简单的贪吃蛇C++代码,使用了ncurses库来实现界面绘制:
```cpp
#include <iostream>
#include <vector>
#include <ncurses.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
const int WIDTH = 30;
const int HEIGHT = 20;
const int SNAKE_SIZE = 5;
struct Point {
int x;
int y;
Point(int x, int y) : x(x), y(y) {}
};
class Snake {
public:
Snake(int x, int y) {
head = new Point(x, y);
body.push_back(head);
for (int i = 1; i < SNAKE_SIZE; i++) {
body.push_back(new Point(x-i, y));
}
direction = KEY_RIGHT;
}
void move() {
Point* next = new Point(head->x, head->y);
switch (direction) {
case KEY_UP:
next->y--;
break;
case KEY_DOWN:
next->y++;
break;
case KEY_LEFT:
next->x--;
break;
case KEY_RIGHT:
next->x++;
break;
}
body.insert(body.begin(), next);
if (next->x == food->x && next->y == food->y) {
generate_food();
} else {
body.pop_back();
}
head = next;
}
bool check_collision() {
if (head->x < 0 || head->x >= WIDTH || head->y < 0 || head->y >= HEIGHT) {
return true;
}
for (int i = 1; i < body.size(); i++) {
if (head->x == body[i]->x && head->y == body[i]->y) {
return true;
}
}
return false;
}
void set_direction(int dir) {
if ((direction == KEY_UP && dir == KEY_DOWN) ||
(direction == KEY_DOWN && dir == KEY_UP) ||
(direction == KEY_LEFT && dir == KEY_RIGHT) ||
(direction == KEY_RIGHT && dir == KEY_LEFT)) {
return;
}
direction = dir;
}
void generate_food() {
int x = rand() % WIDTH;
int y = rand() % HEIGHT;
food = new Point(x, y);
}
Point* head;
vector<Point*> body;
Point* food;
int direction;
};
int main() {
srand(time(NULL));
initscr();
noecho();
cbreak();
keypad(stdscr, TRUE);
nodelay(stdscr, TRUE);
curs_set(0);
Snake* snake = new Snake(WIDTH/2, HEIGHT/2);
snake->generate_food();
while (true) {
clear();
mvprintw(snake->food->y, snake->food->x, "*");
for (int i = 0; i < snake->body.size(); i++) {
mvprintw(snake->body[i]->y, snake->body[i]->x, "O");
}
refresh();
int ch = getch();
if (ch == KEY_UP || ch == KEY_DOWN || ch == KEY_LEFT || ch == KEY_RIGHT) {
snake->set_direction(ch);
}
snake->move();
if (snake->check_collision()) {
break;
}
usleep(100000);
}
mvprintw(HEIGHT/2, WIDTH/2-5, "Game Over!");
refresh();
getch();
endwin();
return 0;
}
```
这段代码使用了ncurses库来实现控制台界面,使用了vector来存储贪吃蛇的身体,使用了Point结构体来表示坐标。在Snake类中实现了贪吃蛇的移动、碰撞检测、食物生成等功能。在主函数中使用循环来不断刷新界面,读取用户输入,并调用Snake类的方法来更新状态。
阅读全文