devc++贪吃蛇代码
时间: 2023-09-24 21:10:12 浏览: 129
以下是一个使用DevC++编写的简单贪吃蛇代码的例子:
```C++
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <list>
using namespace std;
HANDLE hand;
COORD dir = {0, 1};
COORD food;
int score = 0;
int level = 1;
int length = 5;
list<COORD> snake;
void init() {
hand = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cci;
cci.bVisible = 0;
cci.dwSize = sizeof(cci);
SetConsoleCursorInfo(hand, &cci);
srand((unsigned)time(NULL));
food.X = rand() % 30 + 1;
food.Y = rand() % 20 + 1;
}
void gotoxy(int x, int y) {
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(hand, pos);
}
void drawFood() {
gotoxy(food.X, food.Y);
SetConsoleTextAttribute(hand, FOREGROUND_BLUE | FOREGROUND_INTENSITY);
cout << "F";
}
void drawSnake() {
for (auto it = snake.begin(); it != snake.end(); ++it) {
gotoxy((*it).X, (*it).Y);
SetConsoleTextAttribute(hand, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
cout << "O";
}
}
void eraseSnake() {
for (auto it = snake.begin(); it != snake.end(); ++it) {
gotoxy((*it).X, (*it).Y);
cout << " ";
}
}
void updateSnake() {
COORD head = snake.front();
COORD next = {head.X + dir.X, head.Y + dir.Y};
snake.push_front(next);
if (next.X == food.X && next.Y == food.Y) {
score += 10;
length++;
food.X = rand() % 30 + 1;
food.Y = rand() % 20 + 1;
} else if (snake.size() > length) {
snake.pop_back();
}
if (next.X < 0 || next.X > 31 || next.Y < 0 || next.Y > 21) {
gameover();
}
for (auto it = snake.begin(); it != snake.end(); ++it) {
if (it != snake.begin() && (*it).X == head.X && (*it).Y == head.Y) {
gameover();
}
}
}
void input() {
if (_kbhit()) {
char ch = _getch();
switch (ch) {
case 'w':
if (dir.Y != 1) {
dir.X = 0;
dir.Y = -1;
}
break;
case 'a':
if (dir.X != 1) {
dir.X = -1;
dir.Y = 0;
}
break;
case 's':
if (dir.Y != -1) {
dir.X = 0;
dir.Y = 1;
}
break;
case 'd':
if (dir.X != -1) {
dir.X = 1;
dir.Y = 0;
}
break;
}
}
}
void gameover() {
system("cls");
gotoxy(15, 10);
cout << "Game Over!" << endl;
gotoxy(15, 11);
cout << "Score: " << score << endl;
while (_getch() != 13) {}
exit(0);
}
int main() {
init();
while (1) {
eraseSnake();
drawFood();
drawSnake();
input();
updateSnake();
Sleep(200);
}
return 0;
}
```
这段代码使用了Windows API函数和标准库函数来实现贪吃蛇的基本功能。其中使用了`list`容器来存储蛇的身体坐标,通过不断更新蛇的位置来控制蛇的移动。当蛇的头与食物的位置重合时,会增加分数和长度,并生成新的食物。如果蛇撞到墙壁或者撞到自己的身体,游戏结束并显示得分。
阅读全文