能运行多条贪吃蛇的代码
时间: 2023-11-30 19:04:43 浏览: 86
以下是一个可以运行多条贪吃蛇的 C++ 代码示例:
```c++
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <vector>
using namespace std;
const int MAP_WIDTH = 50;
const int MAP_HEIGHT = 20;
const int MAX_SNAKE_LEN = 100;
const int MAX_SNAKE_NUM = 5;
struct Snake {
int x, y, len;
int dir; // 0-up, 1-right, 2-down, 3-left
int tailX[MAX_SNAKE_LEN], tailY[MAX_SNAKE_LEN];
};
struct Fruit {
int x, y;
};
int score[MAX_SNAKE_NUM];
int aliveSnakeNum = MAX_SNAKE_NUM;
Snake snakes[MAX_SNAKE_NUM];
Fruit fruits[MAX_SNAKE_NUM];
void gotoxy(int x, int y) {
COORD pos = { x, y };
HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(output, pos);
}
void DrawSnake(const Snake& snake, char c) {
gotoxy(snake.x, snake.y);
printf("%c", c);
for (int i = 0; i < snake.len; i++) {
gotoxy(snake.tailX[i], snake.tailY[i]);
printf("%c", c);
}
}
void DrawFruit(const Fruit& fruit) {
gotoxy(fruit.x, fruit.y);
printf("*");
}
void Setup() {
for (int i = 0; i < MAX_SNAKE_NUM; i++) {
snakes[i].x = rand() % MAP_WIDTH;
snakes[i].y = rand() % MAP_HEIGHT;
snakes[i].len = 1;
snakes[i].dir = rand() % 4;
score[i] = 0;
for (int j = 0; j < MAX_SNAKE_LEN; j++) {
snakes[i].tailX[j] = -1;
snakes[i].tailY[j] = -1;
}
fruits[i].x = rand() % MAP_WIDTH;
fruits[i].y = rand() % MAP_HEIGHT;
}
}
void Input(Snake& snake) {
if (_kbhit()) {
switch (_getch()) {
case 'w':
if (snake.dir != 2)
snake.dir = 0;
break;
case 'd':
if (snake.dir != 3)
snake.dir = 1;
break;
case 's':
if (snake.dir != 0)
snake.dir = 2;
break;
case 'a':
if (snake.dir != 1)
snake.dir = 3;
break;
}
}
}
void Logic(Snake& snake, Fruit& fruit) {
int prevX = snake.x;
int prevY = snake.y;
int prev2X, prev2Y;
snake.tailX[0] = prevX;
snake.tailY[0] = prevY;
for (int i = 1; i < snake.len; i++) {
prev2X = snake.tailX[i];
prev2Y = snake.tailY[i];
snake.tailX[i] = prevX;
snake.tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (snake.dir) {
case 0:
snake.y--;
break;
case 1:
snake.x++;
break;
case 2:
snake.y++;
break;
case 3:
snake.x--;
break;
}
if (snake.x < 0 || snake.x >= MAP_WIDTH || snake.y < 0 || snake.y >= MAP_HEIGHT) {
aliveSnakeNum--;
snake.len = 0;
return;
}
for (int i = 0; i < snake.len; i++) {
if (snake.tailX[i] == snake.x && snake.tailY[i] == snake.y) {
aliveSnakeNum--;
snake.len = 0;
return;
}
}
if (snake.x == fruit.x && snake.y == fruit.y) {
score[&snake - &snakes[0]] += 10;
snake.len++;
fruit.x = rand() % MAP_WIDTH;
fruit.y = rand() % MAP_HEIGHT;
}
}
int main() {
srand(time(0));
Setup();
while (aliveSnakeNum > 0) {
for (int i = 0; i < MAX_SNAKE_NUM; i++) {
if (snakes[i].len > 0) {
DrawSnake(snakes[i], 'o' + i);
DrawFruit(fruits[i]);
Input(snakes[i]);
Logic(snakes[i], fruits[i]);
}
}
Sleep(100);
}
system("cls");
for (int i = 0; i < MAX_SNAKE_NUM; i++) {
printf("Snake %d: Score = %d\n", i, score[i]);
}
return 0;
}
```
这个代码使用了 C++ 语言和 Windows API 来实现多条贪吃蛇游戏。它使用了结构体来存储每条蛇和每个食物的位置和状态,并使用了向量来存储所有的蛇和分数。它还使用了 Windows API 的函数 `gotoxy()` 来实现控制台的光标移动和字符输出。
阅读全文