#include<bits/stdc++.h>
// 蛇的结构
struct Snake {
std::vector<coord body;
char direction;
};
// 初始化蛇和食物
void init(Snake &snake, COORD &food) {
srand(time(0));
snake.body = {{10, 10}, {9, 10}, {8, 10}};
snake.direction = 'w';
food.x = rand() % 20 + 2;
food.y = rand() % 20 + 2;
}
// 绘制蛇和食物
void draw(Snake &snake, COORD &food) {
initscr();
noecho();
curs_set(0);
keypad(stdscr, TRUE);
while (1) {
// 绘制食物
mvaddch(food.y, food.x, '@');
// 绘制蛇
for (auto &segment : snake.body) {
mvaddch(segment.y, segment.x, '#');
}
// 移动蛇
switch (snake.direction) {
case 'w': --snake.body[0].y; break;
case 's': ++snake.body[0].y; break;
case 'a': --snake.body[0].x; break;
case 'd': ++snake.body[0].x; break;
}
// 检测是否吃到食物
if (snake.body[0].x == food.x && snake.body[0].y == food.y) {
snake.body.push_back(snake.body.back());
food.x = rand() % 20 + 2;
food.y = rand() % 20 + 2;
}
// 刷新屏幕
refresh();
// 检测是否死亡
if (snake.body[0].x < 2 || snake.body[0].x > 20 || snake.body[0].y < 2 || snake.body[0].y > 20) {
endwin();
return;
}
// 获取用户输入
int ch = getch();
if (ch == KEY_UP && snake.direction != 's') snake.direction = 'w';
if (ch == KEY_DOWN && snake.direction != 'w') snake.direction = 's';
if (ch == KEY_LEFT && snake.direction != 'd') snake.direction = 'a';
if (ch == KEY_RIGHT && snake.direction != 'a') snake.direction = 'd';
usleep(100000); // 0.1秒
}
}
int main() {
Snake snake;
COORD food;
init(snake, food);
draw(snake, food);
return 0;
}
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include <cstring>
#include <cstdio>
#include <iostream>
#define N 22
using namespace std;
int gameover;
int x1, y1; // 随机出米
int x,y;
long start;
//=======================================
//类的实现与应用initialize
//=======================================
//下面定义贪吃蛇的坐标类
class snake_position
{
public:
int x,y; //x表示行,y表示列
snake_position(){};
void initialize(int &);//坐标初始化
};
snake_position position[(N-2)*(N-2)+1]; //定义贪吃蛇坐标类数组,有(N-2)*(N-2)个坐标
void snake_position::initialize(int &j)
{
x = 1;
y = j;
}
//下面定义贪吃蛇的棋盘图
class snake_map
{
private:
char s[N][N];//定义贪吃蛇棋盘,包括墙壁。
int grade, length;
int gamespeed; //前进时间间隔
char direction; // 初始情况下,向右运动
int head,tail;
int score;
bool gameauto;
public:
snake_map(int h=4,int t=1,int l=4,char d=77,int s=0):length(l),direction(d),head(h),tail(t),score(s){}
void initialize(); //初始化函数
void show_game();
int updata_game();
void setpoint();
void getgrade();
void display();
};
//定义初始化函数,将贪吃蛇的棋盘图进行初始化
void snake_map::initialize()
{
int i,j;
for(i=1;i<=3;i++)
s[1][i] = '*';
s[1][4] = '#';
for(i=1;i<=N-2;i++)
for(j=1;j<=N-2;j++)
s[i][j]=' '; // 初始化贪吃蛇棋盘中间空白部分
for(i=0;i<=N-1;i++)
s[0][i] = s[N-1][i] = '-'; //初始化贪吃蛇棋盘上下墙壁
for(i=1;i<=N-2;i++)
s[i][0] = s[i][N-1] = '|'; //初始化贪吃蛇棋盘左右墙壁
}
//============================================
//输出贪吃蛇棋盘信息
void snake_map::show_game()
{
system("cls"); // 清屏
int i,j;
cout << endl;
for(i=0;i<N;i++)
{
cout << '\t';
for(j=0;j<N;j++)
cout<<s[i][j]<<' '; // 输出贪吃蛇棋盘
if(i==2) cout << "\t等级:" << grade;
if(i==6) cout << "\t速度:" << gamespeed;
if(i==10) cout << "\t得分:" << score << "分" ;
if(i==14) cout << "\t暂停:按一下空格键" ;
if(i==18) cout << "\t继续:按两下空格键" ;
cout<<endl;
}
}
//输入选择等级
void snake_map::getgrade()
{
cin>>grade;
while( grade>7 || grade<1 )
{
cout << "请输入数字1-7选择等级,输入其他数字无效" << endl;
cin >> grade;
}
switch(grade)
{
case 1: gamespeed = 1000;gameauto = 0;break;
case 2: gamespeed = 800;gameauto = 0;break;
case 3: gamespeed = 600;gameauto = 0;break;
case 4: gamespeed = 400;gameauto = 0;break;
case 5: gamespeed = 200;gameauto = 0;break;
case 6: gamespeed = 100;gameauto = 0;break;
case 7: grade = 1;gamespeed = 1000;gameauto = 1;break;
}
}
//输出等级,得分情况以及称号
void snake_map::display()
{
cout << "\n\t\t\t\t等级:" << grade;
cout << "\n\n\n\t\t\t\t速度:" << gamespeed;
cout << "\n\n\n\t\t\t\t得分:" << score << "分" ;
}
//随机产生米
void snake_map::setpoint()
{
srand(time(0));
do
{
x1 = rand() % (N-2) + 1;
y1 = rand() % (N-2) + 1;
}while(s[x1][y1]!=' ');
s[x1][y1]='*';
}
char key;
int snake_map::updata_game()
{
gameover = 1;
key = direction;
start = clock();
while((gameover=(clock()-start<=gamespeed))&&!kbhit());
//如果有键按下或时间超过自动前进时间间隔则终止循环
if(gameover)
{
getch();
key = getch();
}
if(key == ' ')
{
while(getch()!=' '){};//这里实现的是按空格键暂停,按空格键继续的功能,但不知为何原因,需要按两下空格才能继续。这是个bug。
}
else
direction = key;
switch(direction)
{
case 72: x= position[head].x-1; y= position[head].y;break; // 向上
case 80: x= position[head].x+1; y= position[head].y;break; // 向下
case 75: x= position[head].x; y= position[head].y-1;break; // 向左
case 77: x= position[head].x; y= position[head].y+1; // 向右
}
if(!(direction==72||direction==80||direction==75 ||direction==77)) // 按键非方向键
gameover = 0;
else if(x==0 || x==N-1 ||y==0 || y==N-1) // 碰到墙壁
gameover = 0;
else if(s[x][y]!=' '&&!(x==x1&&y==y1)) // 蛇头碰到蛇身
gameover = 0;
else if(x==x1 && y==y1)
{ // 吃米,长度加1
length ++;
if(length>=8 && gameauto)
{
length -= 8;
grade ++;
if(gamespeed>=200)
gamespeed -= 200; // 改变贪吃蛇前进速度
else
gamespeed = 100;
}
s[x][y]= '#'; //更新蛇头
s[position[head].x][position[head].y] = '*'; //吃米后将原先蛇头变为蛇身
head = (head+1) % ( (N-2)*(N-2) ); //取蛇头坐标
position[head].x = x;
position[head].y = y;
show_game();
gameover = 1;
score += grade*20; //加分
setpoint(); //产生米
}
else
{ // 不吃米
s[position[tail].x][position[tail].y]=' ';//将蛇尾置空
tail= (tail+1) % ( (N-2) * (N-2) );//更新蛇尾坐标
s[position[head].x][position[head].y]='*'; //将蛇头更为蛇身
head= (head+1) % ( (N-2) * (N-2) );
position[head].x = x;
position[head].y = y;
s[position[head].x][position[head].y]='#'; //更新蛇头
gameover = 1;
}
return gameover;
}
//====================================
//主函数部分
//====================================
int main()
{
char ctn = 'y';
int nodead;
cout<<"\n\n\n\n\n\t\t\t 欢迎进入贪吃蛇游戏!"<<endl;//欢迎界面;
cout<<"\n\n\n\t\t\t 按任意键马上开始。。。"<<endl;//准备开始;;
getch();
while( ctn=='y' )
{
system("cls"); // 清屏
snake_map snake;
snake.initialize();
cout << "\n\n请输入数字选择游戏等级:" << endl;
cout << "\n\n\n\t\t\t1.等级一:速度 1000 \n\n\t\t\t2.等级二:速度 800 \n\n\t\t\t3.等级三:速度 600 ";
cout << "\n\n\t\t\t4.等级四:速度 400 \n\n\t\t\t5.等级五:速度 200 \n\n\t\t\t6.等级六:速度 100 \n\n\t\t\t7.自动升级模式" << endl;
snake.getgrade();//获取等级
for(int i=1;i<=4;i++)
{
position[i].initialize(i);//初始化坐标
}
snake.setpoint(); // 产生第一个米
do
{
snake.show_game();
nodead = snake.updata_game();
}while(nodead);
system("cls"); //清屏
cout << "\n\n\n\t\t\t\tGameover!\n\n"<<endl;
snake.display();//输出等级/得分情况
cout << "\n\n\n\t\t 是否选择继续游戏?输入 y 继续,n 退出" << endl;
cin >> ctn;
}
return 0;
}
试试这个(转)
using namespace std;
using namespace std可以不用,std::一样
这道题的解题思路是:
这段代码是一个简单的贪吃蛇游戏的实现,使用C++和ncurses库。不过,代码中存在一些错误和不规范的地方,以下是一些修改建议:
#include<bits/stdc++.h>这个头文件不是标准的C++库,它是一个非标准的、在竞赛编程中常用的头文件,包含了几乎所有标准库的头文件。在实际开发中,建议只包含需要的头文件。struct Snake中的std::vector<coord应该是std::vector<std::pair<int, int>>,这里需要定义坐标对。COORD应该是std::pair<int, int>。init函数中的srand(time(0));应该放在main函数中,以确保整个程序只调用一次。init函数中的snake.body初始化列表应该使用std::make_pair。draw函数中的initscr(),noecho(),curs_set(0),keypad(stdscr, TRUE),mvaddch,refresh(),endwin()和getch()都需要包含<ncurses.h>。draw函数中的while (1)应该有一个退出条件,否则会无限循环。usleep(100000);应该在ncurses的环境下使用napms函数。main函数中的draw(snake, food);调用应该在init(snake, food);之后。
修改代码是:
#include <ncurses.h>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
struct Snake {
vector<pair<int, int>> body;
char direction;
};
pair<int, int> food;
void init(Snake &snake) {
srand(time(0));
snake.body = {{10, 10}, {9, 10}, {8, 10}};
snake.direction = 'w';
}
void draw(Snake &snake, pair<int, int> &food) {
initscr();
noecho();
curs_set(0);
keypad(stdscr, TRUE);
while (true) {
// 绘制食物
mvaddch(food.second, food.first, '@');
// 绘制蛇
for (auto &segment : snake.body) {
mvaddch(segment.second, segment.first, '#');
}
// 刷新屏幕
refresh();
// 获取用户输入
int ch = getch();
switch (ch) {
case KEY_UP:
if (snake.direction != 's') snake.direction = 'w';
break;
case KEY_DOWN:
if (snake.direction != 'w') snake.direction = 's';
break;
case KEY_LEFT:
if (snake.direction != 'd') snake.direction = 'a';
break;
case KEY_RIGHT:
if (snake.direction != 'a') snake.direction = 'd';
break;
}
// 移动蛇
switch (snake.direction) {
case 'w': --snake.body[0].second; break;
case 's': ++snake.body[0].second; break;
case 'a': --snake.body[0].first; break;
case 'd': ++snake.body[0].first; break;
}
// 检测是否吃到食物
if (snake.body[0].first == food.first && snake.body[0].second == food.second) {
snake.body.push_back(snake.body.back());
int x = rand() % 20 + 2;
int y = rand() % 20 + 2;
food = make_pair(x, y);
}
// 检测是否死亡
if (snake.body[0].first < 2 || snake.body[0].first > 20 || snake.body[0].second < 2 || snake.body[0].second > 20) {
endwin();
exit(1);
}
napms(100); // 0.1秒
}
}
int main() {
Snake snake;
init(snake);
draw(snake, food);
return 0;
}
\color{green}稍微改了一下
#include <ncurses.h>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <utility>
using namespace std;
struct Snake {
vector<pair<int, int>> body;
char direction;
};
void init(Snake &snake) {
srand(time(0));
snake.body = {{10, 10}, {9, 10}, {8, 10}};
snake.direction = 'w';
}
void draw(Snake &snake) {
initscr();
noecho();
curs_set(0);
keypad(stdscr, TRUE);
pair<int, int> food;
food.first = rand() % 20 + 2;
food.second = rand() % 20 + 2;
while (true) {
// 清除屏幕
clear();
// 绘制食物
mvaddch(food.second, food.first, '@');
// 绘制蛇
for (auto &segment : snake.body) {
mvaddch(segment.second, segment.first, '#');
}
// 刷新屏幕
refresh();
// 获取用户输入
int ch = getch();
switch (ch) {
case KEY_UP:
if (snake.direction != 's') snake.direction = 'w';
break;
case KEY_DOWN:
if (snake.direction != 'w') snake.direction = 's';
break;
case KEY_LEFT:
if (snake.direction != 'd') snake.direction = 'a';
break;
case KEY_RIGHT:
if (snake.direction != 'a') snake.direction = 'd';
break;
}
// 移动蛇
switch (snake.direction) {
case 'w': --snake.body[0].second; break;
case 's': ++snake.body[0].second; break;
case 'a': --snake.body[0].first; break;
case 'd': ++snake.body[0].first; break;
}
// 检查是否吃到食物
if (snake.body[0].first == food.first && snake.body[0].second == food.second) {
snake.body.push_back(snake.body.back());
food.first = rand() % 20 + 2;
food.second = rand() % 20 + 2;
}
// 检测是否死亡
if (snake.body[0].first < 2 || snake.body[0].first > 20 || snake.body[0].second < 2 || snake.body[0].second > 20) {
endwin();
exit(1);
}
napms(100); // 0.1秒
}
}
int main() {
Snake snake;
init(snake);
draw(snake);
return 0;
}
//这个代码是建窗口打印彩色线条贪吃蛇的,需要graphics.h库,打开EasyX可下载
#include <bits/stdc++.h>
#include <graphics.h>
#include <stdio.h>
#include <conio.h>
#include<string.h>
#define NODE_WIDTH 100
struct node{
int x, y;
};
int score = 0;
node snakeMove(node* snake, int length, int d){
node tail = snake[length - 1];
for (int i = length - 1; i > 0; i–)
snake[i] = snake[i - 1];
node newHead;
newHead = snake[0];
if (d == 0)
newHead.y–;
else if (d == 1)
newHead.y++;
else if (d == 2)
newHead.x–;
else
newHead.x++;
if (newHead.x < 0 || newHead.x >= 15 || newHead.y < 0 || newHead.y >= 8) {
setfont(200, 0, “宋体”);
outtextxy(500, 100, “GAME”);
Sleep(1000);
setfont(250, 0, “宋体”);
outtextxy(450, 400, “OVER”);
Sleep(1000);
exit(0);
}
snake[0] = newHead;
return tail;
}
node createFood(node* snake, int length){
node food;
while (1){
food.x = rand() % (800 / NODE_WIDTH);
food.y = rand() % (600 / NODE_WIDTH);
int i;
for (i = 0; i < length; i++)
if (snake[i].x == food.x && snake[i].y == food.y)
break;
if (i < length)
continue;
else
break;
}
return food;
}
int main(){
srand(time(0));
initgraph(1500, 800);
setbkcolor(RGB(rand()%1000+1,rand()%1000+1,rand()%1000+1));
cleardevice();
getchar();
node snake[100] = { {5, 7}, {4, 7}, {3, 7}, {2, 7}, {1, 7} };
int length = 5;
int d = 3;
node food = createFood(snake, length);
while (1){
cleardevice();
for (int y = 0; y < 800; y += NODE_WIDTH)
line(0, y, 1500, y);
for (int x = 0; x < 1500; x += NODE_WIDTH)
line(x, 0, x, 800);
setfont(30, 0, “宋体”);
outtextxy(1, 1, "积分: ");
char C[105];
sprintf_s(C, “%d”, score);
outtextxy(80, 1, C);
int left, top, right, bottom;
for (int i = 0; i < length; i++) {
left = snake[i].x * NODE_WIDTH;
top = snake[i].y * NODE_WIDTH;
right = (snake[i].x + 1) * NODE_WIDTH;
bottom = (snake[i].y + 1) * NODE_WIDTH;
solidrectangle(left, top, right, bottom);
}
left = food.x * NODE_WIDTH;
top = food.y * NODE_WIDTH;
right = (food.x + 1) * NODE_WIDTH;
bottom = (food.y + 1) * NODE_WIDTH;
setfillcolor(YELLOW);
solidrectangle(left, top, right, bottom);
setfillcolor(WHITE);
Sleep(200);
if (_kbhit()) {
int c = _getch();
switch (c)
{
case ‘w’:
if (d != 1)
d = 0;
break;
case ‘s’:
if (d != 0)
d = 1;
break;
case ‘a’:
if (d != 3)
d = 2;
break;
case ‘d’:
if (d != 2)
d = 3;
break;
case 72:
if (d != 1)
d = 0;
break;
case 80:
if (d != 0)
d = 1;
break;
case 75:
if (d != 3)
d = 2;
break;
case 77:
if (d != 2)
d = 3;
break;
case 32:
setbkcolor(RGB(rand() % 1000 + 1, rand() % 1000 + 1, rand() % 1000 + 1));
cleardevice();
}
}
node tail = snakeMove(snake, length, d);
if (snake[0].x == food.x && snake[0].y == food.y) {
if (length < 100) {
snake[length] = tail;
length++;
score += 10;
}
food = createFood(snake, length);
}
bool flag = false;
for (int i = 1; i < length; i++) {
if (snake[i].x == snake[0].x && snake[i].y == snake[0].y) {
flag = true;
break;
}
}
if (flag) {
setfont(200, 0, "宋体");
outtextxy(500, 100, "GAME");
Sleep(1000);
setfont(250, 0, "宋体");
outtextxy(450, 400, "OVER");
Sleep(1000);
exit(0);
}
}
getchar();
closegraph();
return 0;
}
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <vector>
#include <ctime>
using namespace std;
const int WIDTH = 20; // 地图宽度
const int HEIGHT = 20; // 地图高度
const int WIN_SCORE = 30; // 胜利分数设定为10分
struct Position {
int x, y;
};
// 全局变量
Position snakeHead1, snakeHead2;
vector<Position> snakeBody1, snakeBody2;
Position food;
int score1 = 0, score2 = 0;
bool gameOver = false;
char direction1 = 'D'; // 玩家1初始方向:右
char direction2 = 'D'; // 玩家2初始方向:右
bool hasMoved1 = false; // 玩家1是否开始移动
bool hasMoved2 = false; // 玩家2是否开始移动
bool isSinglePlayer = false; // 是否为单人模式
// 控制台颜色设置
void setColor(int color) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
// 隐藏光标
void hideCursor() {
HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO info;
info.bVisible = FALSE;
info.dwSize = 100;
SetConsoleCursorInfo(consoleHandle, &info);
}
// 随机生成食物
void generateFood() {
srand(time(0));
while (true) {
food.x = rand() % (WIDTH - 2) + 1; // 避开外围墙
food.y = rand() % (HEIGHT - 2) + 1;
// 检查食物不生成在蛇身上
bool onSnake = false;
if (food.x == snakeHead1.x && food.y == snakeHead1.y) {
onSnake = true;
}
for (auto segment : snakeBody1) {
if (segment.x == food.x && segment.y == food.y) {
onSnake = true;
break;
}
}
if (!onSnake) break;
}
}
// 初始化游戏
void initializeGame() {
snakeHead1 = {WIDTH / 4, HEIGHT / 2};
snakeHead2 = {WIDTH / 2, HEIGHT / 2};
snakeBody1.clear();
snakeBody2.clear();
direction1 = 'D';
direction2 = 'D';
score1 = 0;
score2 = 0;
gameOver = false;
hasMoved1 = false;
hasMoved2 = false;
// 给蛇1和蛇2添加初始身体段
snakeBody1.push_back({snakeHead1.x - 1, snakeHead1.y});
if (!isSinglePlayer) snakeBody2.push_back({snakeHead2.x - 1, snakeHead2.y});
generateFood();
}
// 绘制游戏地图
void drawGame() {
system("cls"); // 清屏
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
if (y == 0 || y == HEIGHT - 1 || x == 0 || x == WIDTH - 1) {
setColor(7); // 白色墙壁
cout << "■"; // 墙壁
} else if (x == snakeHead1.x && y == snakeHead1.y) {
setColor(12); // 红色玩家1蛇头
cout << "●"; // 玩家1蛇头
} else if (x == snakeHead2.x && y == snakeHead2.y && !isSinglePlayer) {
setColor(9); // 蓝色玩家2蛇头
cout << "●"; // 玩家2蛇头(仅在双人模式下显示)
} else if (x == food.x && y == food.y) {
setColor(14); // 黄色食物
cout << "★"; // 食物
} else {
bool isBody1 = false, isBody2 = false;
for (auto segment : snakeBody1) {
if (segment.x == x && segment.y == y) {
isBody1 = true;
setColor(12); // 红色玩家1蛇身
cout << "◆"; // 玩家1蛇身
break;
}
}
if (!isBody1) {
for (auto segment : snakeBody2) {
if (segment.x == x && segment.y == y) {
isBody2 = true;
setColor(9); // 蓝色玩家2蛇身(仅在双人模式下显示)
cout << "◆"; // 玩家2蛇身
break;
}
}
}
if (!isBody1 && !isBody2) {
setColor(7); // 白色空白区域
cout << " "; // 空白区域
}
}
}
cout << endl;
}
setColor(7); // 恢复白色
cout << "玩家1得分: " << score1;
if (!isSinglePlayer) cout << " 玩家2得分: " << score2;
}
// 处理玩家输入
void processInput() {
if (_kbhit()) {
char key = _getch();
// 玩家1控制(WASD)
if ((key == 'W' || key == 'w') && direction1 != 'S') {
direction1 = 'W';
hasMoved1 = true;
}
if ((key == 'A' || key == 'a') && direction1 != 'D') {
direction1 = 'A';
hasMoved1 = true;
}
if ((key == 'S' || key == 's') && direction1 != 'W') {
direction1 = 'S';
hasMoved1 = true;
}
if ((key == 'D' || key == 'd') && direction1 != 'A') {
direction1 = 'D';
hasMoved1 = true;
}
// 玩家2控制(方向键)
if (!isSinglePlayer) {
if ((key == 72) && direction2 != 'S') { // Up Arrow
direction2 = 'W';
hasMoved2 = true;
}
if ((key == 75) && direction2 != 'D') { // Left Arrow
direction2 = 'A';
hasMoved2 = true;
}
if ((key == 80) && direction2 != 'W') { // Down Arrow
direction2 = 'S';
hasMoved2 = true;
}
if ((key == 77) && direction2 != 'A') { // Right Arrow
direction2 = 'D';
hasMoved2 = true;
}
}
}
}
// 更新蛇的位置
void updateSnake(Position& head, vector<Position>& body, char direction, int& score, bool& hasMoved) {
if (!hasMoved) return;
// 更新蛇身
if (!body.empty()) {
for (int i = body.size() - 1; i > 0; i--) {
body[i] = body[i - 1];
}
body[0] = head;
}
// 更新蛇头
switch (direction) {
case 'W': head.y--; break;
case 'A': head.x--; break;
case 'S': head.y++; break;
case 'D': head.x++; break;
}
// 判断吃到食物
if (head.x == food.x && head.y == food.y) {
body.push_back({-1, -1}); // 增加蛇身
score++;
generateFood();
}
}
// 碰撞检测
void checkCollision() {
// 撞墙检测
if (snakeHead1.x == 0 || snakeHead1.x == WIDTH - 1 ||
snakeHead1.y == 0 || snakeHead1.y == HEIGHT - 1) {
gameOver = true;
}
/*
// 自撞检测
for (auto segment : snakeBody1) {
if (snakeHead1.x == segment.x && snakeHead1.y == segment.y) {
gameOver = true;
}
}
*/
// 撞蛇尾检测
for (auto segment : snakeBody2) {
if (snakeHead1.x == segment.x && snakeHead1.y == segment.y) {
gameOver = true; // 玩家1撞到玩家2的蛇尾
}
}
// 如果是双人模式,还需要检测玩家2的碰撞
if (!isSinglePlayer) {
if (snakeHead2.x == 0 || snakeHead2.x == WIDTH - 1 ||
snakeHead2.y == 0 || snakeHead2.y == HEIGHT - 1) {
gameOver = true;
}
/*
for (auto segment : snakeBody2) {
if (snakeHead2.x == segment.x && snakeHead2.y == segment.y) {
gameOver = true;
}
}
*/
// 撞蛇尾检测
for (auto segment : snakeBody1) {
if (snakeHead2.x == segment.x && snakeHead2.y == segment.y) {
gameOver = true; // 玩家2撞到玩家1的蛇尾
}
}
// 蛇头相撞判断
if (snakeHead1.x == snakeHead2.x && snakeHead1.y == snakeHead2.y) {
// 比较分数,分高者胜
if (score1 > score2) {
gameOver = true;
cout << "\n玩家1获胜!" << endl;
} else if (score2 > score1) {
gameOver = true;
cout << "\n玩家2获胜!" << endl;
} else {
gameOver = true;
cout << "\n平局!" << endl;
}
}
}
}
// 游戏循环
void gameLoop(int flag) {
while (!gameOver) {
drawGame();
processInput();
updateSnake(snakeHead1, snakeBody1, direction1, score1, hasMoved1);
if (!isSinglePlayer) {
updateSnake(snakeHead2, snakeBody2, direction2, score2, hasMoved2);
}
checkCollision();
if (score1 >= WIN_SCORE) {
gameOver = true;
cout << "玩家1获胜!" << endl;
}
if (score2 >= WIN_SCORE) {
gameOver = true;
cout << "玩家2获胜!" << endl;
}
if (flag == 1) _sleep(200);
if (flag == 2) _sleep(100);
if (flag == 3) _sleep(50);
}
}
// 选择游戏模式
void chooseMode() {
cout << "选择游戏模式(1:单人, 2:双人): ";
char choice;
cin >> choice;
if (choice == '1') {
isSinglePlayer = true;
} else if (choice == '2') {
isSinglePlayer = false;
}
}
int main() {
cout << "请选择游戏难度(1.简单 2.中等 3.困难 其他.疯狂): ";
int n;
cin >> n;
cout << "游戏难度选择成功, 按任意键开始游戏" << endl;
_getch();
system("cls");
hideCursor();
chooseMode();
initializeGame();
gameLoop(n);
return 0;
}
你们这个用的是什么编程软件?为什么我用c++一直显示错误?
有第三方库,需要安装
有的时候可能是 C++版本的问题,例如 11,13,17,98.。。
我之前也浅浅的做了一下:
#include<bits/stdc++.h>
#include<windows.h>
#include<conio.h>
using namespace std;
void setCursorPosition(int x=0,int y=0){
COORD coord;
coord.X=x,coord.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
void color_print(int char_color=7,int background_color=0){
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),char_color+(background_color<<4));
}
void hidden(bool pd=true){
CONSOLE_CURSOR_INFO cci;
GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cci);
cci.bVisible=pd;
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cci);
}
char game_getch(){
unsigned char t=getch();
if((t==0||t==224)&&(t=getch())){
switch(t){
case 72:return'w';
case 80:return's';
case 75:return'a';
case 77:return'd';
}
return'\0';
}
return(t>='A'&&t<='Z')*' '+t;
}
long long random(long long a,long long b){
return double(rand())/(RAND_MAX+1)*(max(a,b)-min(a,b)+1)+min(a,b);
}
unsigned long long timems(){
SYSTEMTIME c;
volatile unsigned long long t=time(0);
GetSystemTime(&c);
return(t/60*60+c.wSecond+(t%60>c.wSecond)*60)*1000+c.wMilliseconds;
}
void srs(){
srand(timems());
}
struct axis{
int x,y;
};
const int length=10;
const int width=10;
int map_value[width][length];
string block="■";
int block_length=block.size();
//string block="██";
//int block_length=2;
int snake_x=0,snake_y=0;
int snake_len=1;
char snake_direction='d',key;
axis foodmap[length*width-1>0?length*width-1:1];
int foodmap_len=0;
int foodmap_random_idx;
int foodvalue=1;
int main(){
srs();
hidden(false);
map_value[snake_y][snake_x]=snake_len;
for(int i=-1;i<=width;i++){
for(int j=-1;j<=length;j++){
if(i==-1||i==width||j==-1||j==length)color_print(9);
else if(map_value[i][j]==0){
foodmap[foodmap_len++]={j,i};
color_print(0);
}
else color_print(4);
cout<<block;
}
cout<<"\n";
}
if(foodmap_len==0)return 0;
foodmap_random_idx=random(0,foodmap_len-1);
map_value[foodmap[foodmap_random_idx].y][foodmap[foodmap_random_idx].x]=-1;
setCursorPosition((foodmap[foodmap_random_idx].x+1)*block_length,foodmap[foodmap_random_idx].y+1);
color_print(10);
cout<<block;
while(1){
double t=(snake_len-1.0)/10;//slen-1的1是初始蛇身长度,10是达到最大速度的长度
Sleep(250-100*(t>1?1:t));//限制,让t在0~1之间,250是最慢的等待时间,100是最大减少的等待时间
if(kbhit()&&(key=game_getch())&&((snake_direction=='a'||snake_direction=='d')&&(key=='w'||key=='s')||(snake_direction=='w'||snake_direction=='s')&&(key=='a'||key=='d')||snake_len==1))snake_direction=key;
int temp_snake_x=snake_x,temp_snake_y=snake_y;
snake_x+=(snake_direction=='d')-(snake_direction=='a');
snake_y+=(snake_direction=='s')-(snake_direction=='w');
if(snake_x<0||snake_x>=length||snake_y<0||snake_y>=width||map_value[snake_y][snake_x]>1)break;
setCursorPosition((temp_snake_x+1)*block_length,temp_snake_y+1);
color_print(12);
cout<<block;
setCursorPosition((snake_x+1)*block_length,snake_y+1);
color_print(4);
cout<<block;
bool foodmet_decide=map_value[snake_y][snake_x]==-1;
snake_len+=foodmet_decide*foodvalue;
foodmap_len=0;
map_value[snake_y][snake_x]=snake_len;
for(int i=0;i<width;i++){
for(int j=0;j<length;j++){
if(i!=snake_y||j!=snake_x){
if(foodmet_decide){
if(map_value[i][j]==0)foodmap[foodmap_len++]={j,i};
}
else if(map_value[i][j]==1){
setCursorPosition((j+1)*block_length,i+1);
color_print(0);
cout<<block;
}
map_value[i][j]+=(map_value[i][j]>0)*((foodmet_decide*foodvalue)-1);
}
}
}
if(foodmet_decide){
if(foodmap_len==0)break;
foodmap_random_idx=random(0,foodmap_len-1);
map_value[foodmap[foodmap_random_idx].y][foodmap[foodmap_random_idx].x]=-1;
setCursorPosition((foodmap[foodmap_random_idx].x+1)*block_length,foodmap[foodmap_random_idx].y+1);
color_print(10);
cout<<block;
}
}
setCursorPosition(0,width+1);
return 0;
}