帮我写份贪吃蛇C加加代码
时间: 2024-12-11 10:05:01 浏览: 16
贪吃蛇是一个经典的电子游戏,通常用C++编写。这里给出一个简单的控制台版贪吃蛇的基本框架,使用了C++11的特性。请注意,完整的游戏还包括窗口绘制、键盘输入处理等部分,这里仅提供核心的部分代码:
```cpp
#include <iostream>
#include <conio.h> // for getch() function in Windows
using namespace std;
struct Snake {
int x[4], y[4]; // array to store snake segments
};
Snake snake; // initialize the snake with one segment at origin
int foodX = rand() % 20 + 1, foodY = rand() % 20 + 1;
bool gameRunning = true;
void moveSnake(int dx, int dy) {
for (int i = 3; i > 0; i--) {
snake.x[i] = snake.x[i - 1];
snake.y[i] = snake.y[i - 1];
}
snake.x[0] += dx;
snake.y[0] += dy;
}
// Draw the snake on console
void drawSnake() {
for (int i = 0; i < 4; i++) {
cout << "o ";
}
cout << endl;
}
int main() {
while (gameRunning) {
// Check if snake ate food
if (snake.x[0] == foodX && snake.y[0] == foodY) {
foodX = rand() % 20 + 1;
foodY = rand() % 20 + 1;
snake.x[3] = snake.x[0];
snake.y[3] = snake.y[0];
} else {
snake.x[0] = snake.x[3]; // remove tail of the snake
snake.y[0] = snake.y[3];
}
// Move the snake based on user input or a random direction
char dir = _getch(); // Get user input from keyboard
switch (dir) {
case 'a': moveSnake(-1, 0); break;
case 'd': moveSnake(1, 0); break;
case 'w': moveSnake(0, -1); break;
case 's': moveSnake(0, 1); break;
default: continue; // ignore other keys
}
// Check boundaries and collision with self
if (snake.x[0] < 1 || snake.x[0] > 20 || snake.y[0] < 1 || snake.y[0] > 20) {
gameRunning = false;
} else {
for (int i = 1; i < 4; i++) {
if (snake.x[0] == snake.x[i] && snake.y[0] == snake.y[i]) {
gameRunning = false;
}
}
}
drawSnake();
}
return 0;
}
```
阅读全文