问题标题: 酷町堂:求c++贪吃蛇代码

0
0

0
已采纳
颜咏春
颜咏春
中级光能
中级光能

 

#include <iostream>



 

#include <list>



 

#include <cstdio>



 

#include <string>



 

#include <vector>



 

#include <ctime>



 

#include <algorithm>



 

#include <conio.h>



 

#include <windows.h>



 

using namespace std;







 

class Node {



 

public:



 

int x, y;



 

Node(int x1, int y1);



 

};







 

class UserData {



 

public:



 

string name;



 

long long score;



 

int gt;



 

int gr;



 

UserData(string s, long long sc,int gametime,int grade);



 

friend bool operator < (UserData a, UserData b);



 

};







 

#define RIGHT 0x4d



 

#define LEFT 0x4b



 

#define UP 0x48



 

#define DOWN 0x50



 

#define YELLOW FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY



 

#define CYAN FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY



 

#define ORANGE FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY



 

#define PURPLE FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY



 

#define RED FOREGROUND_RED | FOREGROUND_INTENSITY



 

const int STARTX = 8;



 

const int STARTY = 4;



 

const int RANGEX = 60;



 

const int RANGEY = 20;



 

int point=10;



 

const int ENDX = STARTX + RANGEX;



 

const int ENDY = STARTY + RANGEY;



 

bool isSnake[RANGEY + 10 ][RANGEX + 10];



 

int speed;



 

int sysj;



 

int gametime;



 

list<Node> snake;



 

int curDiraction; //蛇的当前前进方向, 1上, 2下, 3左, 4右



 

int score; //当前分数



 

int grade;



 

int snakeLen; //蛇的长度



 

int foodx, foody; //食物坐标



 

int gox, goy; //蛇头坐标



 

int mj;



 

void GoTo(short x, short y); //定位光标



 

void DrawBoard(); //绘制边框



 

void ShowInformation(); //展示游戏信息



 

void Init(); //初始化游戏



 

void RunSnake(int x, int y); //绘制蛇身



 

void Try(int& x, int& y); //试走



 

bool IsGoodCoord(int x, int y); //前进坐标是否合法



 

void AddFood(); //增加食物



 

void EartFood(); //吃食物



 

void InitSnake(); //初始化蛇身



 

bool EndGame(); //结束游戏



 

bool StartGame(); //启动游戏



 

bool GameMenu(); //游戏菜单



 

void ShowRanking(); //排行榜



 

void ShowAbout(); //相关信息



 

void InputData(); //输入玩家名字







 

int main() {



 

system("title 贪吃蛇小游戏 by 蒋智航");



 

while (true) {



 

if (!GameMenu()) return 0;



 

}



 

return 0;



 

}







 

Node::Node(int x1, int y1) { //构造Node对象



 

x = x1; y = y1;



 

}







 

bool operator < (UserData a, UserData b) { //重载运算符,按分数由大到小排列



 

if(a.score != b.score)



 

return a.score > b.score;



 

if(a.gt !=b.gt)



 

return a.gt > b.gt;



 

else



 

return a.gr > b.gr;



 

}



 

UserData::UserData(string s, long long sc,int gametime_,int _grade) { //构造UserData对象



 

name = s; score = sc; gt=gametime_; gr=_grade;



 

}







 

void color(WORD A)



 

{



 

SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), A);



 

}







 

void Color(int score_)



 

{



 

if(score_%4==1)



 

{



 

color(PURPLE);



 

}



 

else if(score_%4==2)



 

{



 

color(RED);



 

}



 

else if(score_%4==3)



 

{



 

color(YELLOW);



 

}



 

else if(score_%4==0)



 

{



 

color(CYAN);



 

}



 

}







 

void GoTo(short x, short y) { //定位光标



 

COORD coord = { x, y };



 

SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);



 

}







 

void ShowInformation() { //输出游戏信息



 

color(YELLOW);



 

GoTo(78, 5);



 

printf("贪吃蛇游戏");



 

GoTo(78,18);



 

gametime=(clock()-mj)/1000;



 

grade=snakeLen-3;



 

printf("生存时间:%3d 秒",(clock()-mj)/1000);



 

GoTo(78, 8);



 

printf("游戏规则:");



 

GoTo(78, 10);



 

printf("请按 ↑ ↓ ← → 来控制您的蛇吃东西");



 

GoTo(78, 12);



 

printf("吃的越多,蛇就越长,您的等级也将越高");



 

GoTo(78, 14);



 

printf("当蛇吃到自己或撞上墙时,游戏结束。");



 

GoTo(78,16);



 

printf("自动前进时间:%3dms",speed);



 

GoTo(78, 20);



 

printf("当前等级: %8d", snakeLen-3);



 

GoTo(78, 23);



 

printf("您的分数: %d", score);



 

color(CYAN);



 

printf("+%d=%d",score/3,score*3/2);



 

color(YELLOW);



 

GoTo(78,25);



 

printf("剩余时间:%d秒",10+(snakeLen-3)*4-gametime);



 

sysj=10+(snakeLen-3)*4-gametime;



 

}







 

void DrawBoard() { //绘制墙体







 

HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); //获得输出句柄







 

CONSOLE_CURSOR_INFO cursor_info = { 1, 0 }; //光标信息



 

SetConsoleCursorInfo(hOut, &cursor_info); //隐藏光标







 

COORD size = { 120, 30 };



 

SetConsoleScreenBufferSize(hOut, size); //重设缓冲区大小







 

SMALL_RECT rc = { 0 , 0, 120, 30 };



 

SetConsoleWindowInfo(hOut, true, &rc); //重设窗口大小







 

SetConsoleTextAttribute(hOut, CYAN);







 

for (int i = STARTX - 2; i <= ENDX + 2; i += 2) { //横向墙体



 

GoTo(i, STARTY - 1);



 

printf("■");



 

GoTo(i, ENDY + 1);



 

printf("■");



 

}



 

for (int i = STARTY - 1; i <= ENDY + 1; ++i) { //竖向墙体



 

GoTo(STARTX - 2, i);



 

printf("■");



 

GoTo(ENDX + 2, i);



 

printf("■");



 

}



 

}



 

void draw()



 

{



 

char m=snakeLen+62;



 

Color(score);



 

cout<<"■";



 

}



 

void Init() { //初始化游戏



 

system("cls");



 

memset(isSnake, 0, sizeof(isSnake));



 

speed = 200;



 

curDiraction = 4;



 

score = 0;



 

DrawBoard();



 

InitSnake();



 

ShowInformation();



 

AddFood();



 

mj=clock();



 

point=10;



 

sysj=10;



 

}







 

void RunSnake(int x, int y) { //绘制蛇身



 

SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);



 

score += snakeLen + 1;



 

if (x == foodx && y == foody) {



 

EartFood();



 

AddFood();



 

return;



 

}



 

snake.push_front(Node(x, y));



 

isSnake[y][x] = true;



 

GoTo(x, y);



 

draw();



 

Node back = snake.back();



 

snake.pop_back();



 

isSnake[back.y][back.x] = false;



 

GoTo(back.x, back.y);



 

printf(" ");



 

}







 

void Try(int& x, int& y) { //试走



 

int key, cnt = 100;



 

while (cnt--) { //多次检测键盘状态



 

if (_kbhit()) {



 

key = getch();



 

switch (key) {



 

case UP:



 

if (curDiraction == 1 || curDiraction == 2) break;



 

--y; curDiraction = 1; return;



 

case DOWN:



 

if (curDiraction == 1 || curDiraction == 2) break;



 

++y; curDiraction = 2; return;



 

case LEFT:



 

if (curDiraction == 3 || curDiraction == 4) break;



 

x -= 2; curDiraction = 3; return;



 

case RIGHT:



 

if (curDiraction == 3 || curDiraction == 4) break;



 

x += 2; curDiraction = 4; return;



 

}



 

}



 

}



 

if (curDiraction == 1) --y; //用户没有输入时



 

else if (curDiraction == 2) ++y;



 

else if (curDiraction == 3) x -= 2;



 

else x += 2;



 

}







 

bool IsGoodCoord(int x, int y) { //判断光标是否合法



 

if (x <= ENDX && y <= ENDY && x >= STARTX && y >= STARTY)



 

return true;



 

else



 

return false;



 

}







 

void AddFood() { //增加食物



 

SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), PURPLE);



 

srand((unsigned)time(NULL));



 

while (true) {



 

foodx = (rand()%ENDX) + 1;



 

foody = (rand()%ENDY) + 1;



 

if (foodx&1) foodx++;



 

if (!isSnake[foody][foodx] && IsGoodCoord(foodx, foody)) break;



 

}



 

GoTo(foodx, foody);



 

int a=rand()%5;



 

if(a>=4)



 

printf("★");



 

else if(a<=1)



 

printf("○");



 

else



 

printf("▲");



 

}

1
金棕乐
金棕乐
资深守护
资深守护


    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;  
  
    }  
  
 

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;  

0
鲁天一
鲁天一
初级光能
初级光能

这是除头文件外的代码:

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.等级一:速度 0 \n\n\t\t\t2.等级二:速度 1 \n\n\t\t\t3.等级三:速度 2 ";  

        cout << "\n\n\t\t\t4.等级四:速度 3 \n\n\t\t\t5.等级五:速度 4 \n\n\t\t\t6.等级六:速度 5 \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;  
} 

------------------------------------------------------------------------------------------------------------------------

这是头文件的代码

#include <windows.h>  
#include <stdlib.h>  
#include <conio.h>  
#include <time.h>  
#include <cstring>  
#include <cstdio>  
#include <iostream>  
#define  N 22  

 

0
蒋智航
蒋智航
高级天翼
高级天翼
#include <iostream>

#include <list>

#include <cstdio>

#include <string>

#include <vector>

#include <ctime>

#include <algorithm>

#include <conio.h>

#include <windows.h>

using namespace std;



class Node { 

public:

    int x, y;

    Node(int x1, int y1); 

};



class UserData { 

public:

    string name;

    long long score;

    int gt;

    int gr; 

    UserData(string s, long long sc,int gametime,int grade); 

    friend bool operator < (UserData a, UserData b); 

};



#define RIGHT 0x4d

#define LEFT 0x4b  

#define UP 0x48  

#define DOWN 0x50 

#define YELLOW FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY

#define CYAN FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY

#define ORANGE FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY

#define PURPLE FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY

#define RED  FOREGROUND_RED | FOREGROUND_INTENSITY

const int STARTX = 8; 

const int STARTY = 4; 

const int RANGEX = 60; 

const int RANGEY = 20;

int point=10; 

const int ENDX = STARTX + RANGEX; 

const int ENDY = STARTY + RANGEY; 

bool isSnake[RANGEY + 10 ][RANGEX + 10];

int speed; 

int sysj;

int gametime;

list<Node> snake;

int curDiraction; //蛇的当前前进方向, 1上, 2下, 3左, 4右

int score; //当前分数

int grade;

int snakeLen; //蛇的长度

int foodx, foody; //食物坐标

int gox, goy; //蛇头坐标

int mj;

void GoTo(short x, short y); //定位光标

void DrawBoard(); //绘制边框

void ShowInformation(); //展示游戏信息

void Init(); //初始化游戏

void RunSnake(int x, int y); //绘制蛇身

void Try(int& x, int& y); //试走

bool IsGoodCoord(int x, int y); //前进坐标是否合法

void AddFood(); //增加食物

void EartFood(); //吃食物

void InitSnake(); //初始化蛇身

bool EndGame(); //结束游戏

bool StartGame(); //启动游戏

bool GameMenu(); //游戏菜单

void ShowRanking(); //排行榜

void ShowAbout(); //相关信息

void InputData(); //输入玩家名字



int main() {

    system("title 贪吃蛇小游戏 by 蒋智航");

    while (true) {

        if (!GameMenu()) return 0;

    }

    return 0;

}



Node::Node(int x1, int y1) { //构造Node对象

    x = x1; y = y1; 

}



bool operator < (UserData a, UserData b) { //重载运算符,按分数由大到小排列

    if(a.score != b.score)

    return a.score > b.score;

    if(a.gt !=b.gt)

    return a.gt > b.gt;

    else

    return a.gr > b.gr;

}

UserData::UserData(string s, long long sc,int gametime_,int _grade) { //构造UserData对象

    name = s; score = sc; gt=gametime_; gr=_grade;

}



void color(WORD A)

{

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), A);

} 



void Color(int score_)

{

    if(score_%4==1)

    {

        color(PURPLE);

    }

    else if(score_%4==2)

    {

        color(RED);

    }

    else if(score_%4==3)

    {

        color(YELLOW);

    }

    else if(score_%4==0) 

    {

        color(CYAN);

    }

}



void GoTo(short x, short y) { //定位光标

    COORD coord = { x, y };

    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);

}



void ShowInformation() { //输出游戏信息

    color(YELLOW);

    GoTo(78, 5);

    printf("贪吃蛇游戏");

    GoTo(78,18);

    gametime=(clock()-mj)/1000;

    grade=snakeLen-3; 

    printf("生存时间:%3d 秒",(clock()-mj)/1000);

    GoTo(78, 8);

    printf("游戏规则:");

    GoTo(78, 10);

    printf("请按 ↑ ↓ ← →  来控制您的蛇吃东西");

    GoTo(78, 12);

    printf("吃的越多,蛇就越长,您的等级也将越高");

    GoTo(78, 14);

    printf("当蛇吃到自己或撞上墙时,游戏结束。");

    GoTo(78,16);

    printf("自动前进时间:%3dms",speed);

    GoTo(78, 20);

    printf("当前等级: %8d", snakeLen-3);

    GoTo(78, 23);

    printf("您的分数: %d", score);

    color(CYAN);

    printf("+%d=%d",score/3,score*3/2);

    color(YELLOW);

    GoTo(78,25);

    printf("剩余时间:%d秒",10+(snakeLen-3)*4-gametime);

    sysj=10+(snakeLen-3)*4-gametime; 

}



void DrawBoard() { //绘制墙体



    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); //获得输出句柄



    CONSOLE_CURSOR_INFO cursor_info = { 1, 0 }; //光标信息

    SetConsoleCursorInfo(hOut, &cursor_info); //隐藏光标



    COORD size = { 120, 30 };

    SetConsoleScreenBufferSize(hOut, size); //重设缓冲区大小



    SMALL_RECT rc = { 0 , 0, 120, 30 };

    SetConsoleWindowInfo(hOut, true, &rc); //重设窗口大小



    SetConsoleTextAttribute(hOut, CYAN);



    for (int i = STARTX - 2; i <= ENDX + 2; i += 2) { //横向墙体

        GoTo(i, STARTY - 1);

        printf("■");

        GoTo(i, ENDY + 1);

        printf("■");

    }

    for (int i = STARTY - 1; i <= ENDY + 1; ++i) { //竖向墙体

        GoTo(STARTX - 2, i);

        printf("■");

        GoTo(ENDX + 2, i);

        printf("■");

    }

}

void draw()

{

    char m=snakeLen+62;

    Color(score);

    cout<<"■";

 } 

void Init() { //初始化游戏

    system("cls");

    memset(isSnake, 0, sizeof(isSnake));

    speed = 200;

    curDiraction = 4;

    score = 0;

    DrawBoard();

    InitSnake();

    ShowInformation();

    AddFood();

    mj=clock();

    point=10;

    sysj=10;

}



void RunSnake(int x, int y) { //绘制蛇身

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);

    score += snakeLen + 1;

    if (x == foodx && y == foody) {

        EartFood();

        AddFood();

        return;

    }

    snake.push_front(Node(x, y));

    isSnake[y][x] = true;

    GoTo(x, y);

    draw();

    Node back = snake.back();

    snake.pop_back();

    isSnake[back.y][back.x] = false;

    GoTo(back.x, back.y);

    printf(" ");

}



void Try(int& x, int& y) { //试走

    int key, cnt = 100;

    while (cnt--) { //多次检测键盘状态

        if (_kbhit()) {

            key = getch();

            switch (key) {

            case UP: 

                if (curDiraction == 1 || curDiraction == 2) break;

                --y; curDiraction = 1; return;

            case DOWN: 

                if (curDiraction == 1 || curDiraction == 2) break;

                ++y; curDiraction = 2; return;

            case LEFT: 

                if (curDiraction == 3 || curDiraction == 4) break;

                x -= 2; curDiraction = 3; return;

            case RIGHT: 

                if (curDiraction == 3 || curDiraction == 4) break;

                x += 2; curDiraction = 4; return;

            }

        }

    }

    if (curDiraction == 1) --y; //用户没有输入时

    else if (curDiraction == 2) ++y;

    else if (curDiraction == 3) x -= 2;

    else x += 2;

}



bool IsGoodCoord(int x, int y) { //判断光标是否合法

    if (x <= ENDX && y <= ENDY && x >= STARTX && y >= STARTY)

        return true;

    else

        return false;

}



void AddFood() { //增加食物

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), PURPLE);

    srand((unsigned)time(NULL));

    while (true) {

        foodx = (rand()%ENDX) + 1;

        foody = (rand()%ENDY) + 1;

        if (foodx&1) foodx++;

        if (!isSnake[foody][foodx] && IsGoodCoord(foodx, foody)) break;

    }

    GoTo(foodx, foody);

    int a=rand()%5;

    if(a>=4) 

    printf("★");

    else if(a<=1) 

    printf("○");

    else

    printf("▲");

}



void EartFood() { //吃东西

    point+=4;

    int sb=gametime=(clock()-mj)/1000;

    sysj=point-sb;

    score+=score/2;

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);

    snake.push_front(Node(foodx, foody));

    isSnake[foody][foodx] = true;

    ++snakeLen;

    if (speed >= 55) speed -= 5;



    GoTo(foodx, foody);

    draw();

    AddFood(); 

}



void InitSnake() { //初始化蛇身

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);

    snakeLen = 3, gox = 18, goy = 14;

    snake.clear();

    snake.push_front(Node(12, 14));

    snake.push_front(Node(14, 14));

    snake.push_front(Node(16, 14));

    for (int i = 12; i <= 16; i += 2) {

        GoTo(i, 14);

        draw();

        isSnake[14][i] = true;

    }

}

bool EndGame() { //结束游戏

    system("cls");

    DrawBoard();

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);

    GoTo(28, 10);

    printf("您的本局游戏得分: %d分", score);

    GoTo(32, 18);

    printf("....你挂了....");

    GoTo(27, 20);

    printf("是否继续游戏: 是(1), 否(0)");

    GoTo(27, 22);

    char key = getch();

    while (true) {

        if (key == '1') return false;

        else if (key == '0') 

        {GoTo(ENDX+1,ENDY+2);

        exit(0);return true;

        }

        else key = getch();

    }

}



bool StartGame() { //启动游戏



    Init();



    while (IsGoodCoord(gox, goy) && !isSnake[goy][gox]&&sysj>0) { //当试走合法时

        RunSnake(gox, goy);

        ShowInformation();

        Try(gox, goy);

        Sleep(speed);

    }

    InputData(); 

    return true;

}



bool GameMenu() { //游戏菜单

    system("cls");

    DrawBoard();

    GoTo(STARTX + 22, STARTY + 4);

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);

    printf("欢迎进入贪吃蛇游戏!");

    GoTo(STARTX + 24, STARTY + 10);

    printf("1: 新游戏");

    GoTo(STARTX + 24, STARTY + 12);

    printf("2: 排行榜");

    GoTo(STARTX + 24, STARTY + 14);

    printf("3: 关于游戏");

    GoTo(STARTX + 24, STARTY + 16);

    printf("4: 退出游戏");



    while (true) {

        if (_kbhit()) {

            char key = getch();

            switch (key) {

            case '1':

                if (!StartGame()) return false; 

                else return true;

            case '2':

                ShowRanking(); return true;

            case '3':

                ShowAbout(); return true;

            case '4':

                GoTo(1,ENDY+2);

                return false;

            default:

                return true;

            }

        }

    }

}



void ShowRanking() { //展示排行榜

    vector<UserData> vu;

    FILE *fp = fopen("GameData.txt", "r");

    if (fp == NULL) fp = fopen("GameData.txt", "w+");

    char name[20];

    int len = 0;

    while (fscanf(fp, "%s", name) != EOF) {

        ++len;

        int score,g=grade;

        fscanf(fp, "%d%d%d%*c", &score,&gametime,&g);

        vu.push_back(UserData(string(name), score,gametime,grade));

    }

    fclose(fp);

    sort(vu.begin(), vu.end()); //对得分进行排名

    system("cls");

    DrawBoard();

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), CYAN);

    GoTo(STARTX + 8, STARTY + 2);

    printf("用户");

    GoTo(STARTX + 20, STARTY + 2);

    printf("分数");

    GoTo(STARTX + 32, STARTY + 2);

    printf("生存时间");

    GoTo(STARTX + 44, STARTY + 2);

    printf("排行");

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);



    for (int i = 0; i < len && i < 14; ++i) { //打印前14名用户数据

        char const *p = vu[i].name.c_str();

        Color(vu[i].score);

        GoTo(STARTX + 8, STARTY + 4 + i);

        printf("%s", p);

        GoTo(STARTX + 20, STARTY + 4 + i);

        printf("%d分", vu[i].score);

        GoTo(STARTX + 32, STARTY + 4 + i);

        printf("%d秒", vu[i].gt);

        GoTo(STARTX + 44, STARTY + 4 + i);

        printf(" %d", i + 1);

    }



    GoTo(STARTX + 4, ENDY - 2);

    printf("-----------------  按'1'返回游戏菜单  ---------------");

    while (true) {

        if (_kbhit()) {

            char key = getch();

            if (key == '1') break;

        }

    }

}



void ShowAbout() { //展示游戏相关

    system("cls");

    DrawBoard();

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);



    GoTo(STARTX + 4, STARTY + 2);

    printf("-------------------  贪吃蛇游戏  -------------------");

    GoTo(STARTX + 10, STARTY + 4);

    printf("制作人: ");

    GoTo(STARTX + 10, STARTY + 6);

    printf("蒋智航");

    GoTo(STARTX + 10,STARTY + 8);

    printf("贪吃蛇游戏");

    GoTo(STARTX + 10,STARTY + 10);

    printf("游戏规则:");

    GoTo(STARTX + 10,STARTY + 12);

    printf("请按 ↑ ↓ ← →  来控制您的蛇吃东西");

    GoTo(STARTX + 10,STARTY + 14);

    printf("吃的越多,蛇就越长,您的等级也将越高");

    GoTo(STARTX + 10,STARTY + 16);

    printf("当蛇吃到自己或撞上墙时,游戏结束。");



    GoTo(STARTX + 4, ENDY - 2);

    printf("-----------------  按'1'返回游戏菜单  ---------------");

    while (true) {

        if (_kbhit()) {

            char key = getch();

            if (key == '1') break;

        }

    }

}



void InputData() { //用户输入名字

    char name[20];

    if(score>=1000)

    {

    GoTo(STARTX + 10, STARTY + 10);

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), RED);

    printf("请输入你的名字: ");

    COORD coord = { STARTX + 10, STARTY + 12 };

    SetConsoleCursorPosition(GetStdHandle(STD_INPUT_HANDLE), coord);

    while (true) { //忽略非法字符

        scanf("%s", name);

        if (name[0] != 0 && name[0] != ' ') break; 

    }FILE *fp = fopen("Gamedata.txt", "a");

    if (fp == NULL) fp = fopen("GameData.txt", "w+");

    fprintf(fp, "%s %d %d \n", name, score,gametime);

    fclose(fp);

    }

    else 

    {

        GoTo(STARTX + 20, STARTY + 10);

        cout<<"很遗憾,您未能上榜!"<<endl; 

        Sleep(1000);

     }  

    EndGame(); 



}

 

0
陈喆鹏
陈喆鹏
资深光能
资深光能

#include<iostream>
#include<windows.h>
#include<time.h>
#include<conio.h>
using namespace std;
// 刷新当前屏幕
inline void Refresh(char q[][22], int grade, int gamespeed){
    system("cls");     //  清屏
 int i,j;
 cout << endl;
 for(i=0;i<22;i++){
     cout << "\t";
  for(j=0;j<22;j++)
   cout<<q[i][j]<<' ';    //  输出贪吃蛇棋盘
        if(i==0) cout << "\t等级为:" << grade;
        if(i==4) cout << "\t自动前进时间";
        if(i==6) cout << "\t间隔为:" << gamespeed << "ms";
  cout<<endl;
 }
}
int main(){
    char tcsQipan[22][22];     //  贪吃蛇棋盘是一个二维数组(如22*22,包括墙壁)
    int i,j;
    for(i=1;i<=20;i++)
        for(j=1;j<=20;j++)
            tcsQipan[i][j]=' ';     //     初始化贪吃蛇棋盘中间空白部分
    for(i=0;i<=21;i++)
        tcsQipan[0][i] = tcsQipan[21][i] = '-';      //初始化贪吃蛇棋盘上下墙壁
    for(i=1;i<=20;i++)
        tcsQipan[i][0] = tcsQipan[i][21] = '|';      //初始化贪吃蛇棋盘左右墙壁
    int tcsZuobiao[2][100];     //蛇的坐标数组
    for(i=0; i<4; i++){
        tcsZuobiao[0][i] = 1;
        tcsZuobiao[1][i] = i + 1;
    }
    int head = 3,tail = 0;
    for(i=1;i<=3;i++)
        tcsQipan[1][i]='*';    //蛇身
    tcsQipan[1][4]='#';       //蛇头
    int x1, y1;           // 随机出米
    srand(time(0));
    do{
  x1=rand()%20+1;
  y1=rand()%20+1;
 }while(tcsQipan[x1][y1]!=' ');
 tcsQipan[x1][y1]='*';
 cout<<"\n\n\t\t贪吃蛇游戏即将开始 !"<<endl;//准备开始;;
 long start;
    int grade = 1, length = 4;
    int gamespeed = 500;  //前进时间间隔
 for(i=3;i>=0;i--){
  start=clock();
  while(clock()-start<=1000);
  system("cls");
  if(i>0)
   cout << "\n\n\t\t进入倒计时:" << i << endl;
  else
   Refresh(tcsQipan,grade,gamespeed);
 }
    int timeover;
    char direction = 77;  // 初始情况下,向右运动
    int x,y;
    while(1){
        timeover = 1;
        start = clock();
        while((timeover=(clock()-start<=gamespeed))&&!kbhit());
             //如果有键按下或时间超过自动前进时间间隔则终止循环
        if(timeover){
            getch();direction = getch();
        }
        switch(direction){
        case 72: x= tcsZuobiao[0][head]-1; y= tcsZuobiao[1][head];break;     // 向上
        case 80: x= tcsZuobiao[0][head]+1; y= tcsZuobiao[1][head];break;      // 向下
        case 75: x= tcsZuobiao[0][head]; y= tcsZuobiao[1][head]-1;break;      // 向左
        case 77: x= tcsZuobiao[0][head]; y= tcsZuobiao[1][head]+1;           // 向右
        }
        if(!(direction==72||direction==80||direction==75 ||direction==77)){   //  按键非方向键
            cout << "\tGame over!" << endl;return 0;
        }
        if(x==0 || x==21 ||y==0 || y==21){   // 碰到墙壁
            cout << "\tGame over!" << endl;return 0;
        }
        if(tcsQipan[x][y]!=' '&&!(x==x1&&y==y1)){ //   蛇头碰到蛇身
            cout << "\tGame over!" << endl;return 0;
        }
        if(x==x1 && y==y1){      //  吃米,长度加1
            length ++;
            if(length>=8){
                length -= 8;
                grade ++;
                if(gamespeed>=200)
                    gamespeed = 550 - grade * 50; // 改变自动前进时间间隔
            }
            tcsQipan[x][y]= '#';
            tcsQipan[tcsZuobiao[0][head]][tcsZuobiao[1][head]] = '*';
            head = (head+1)%100;
            tcsZuobiao[0][head] = x;
            tcsZuobiao[1][head] = y;
            do
            {
                x1=rand()%20+1;
                y1=rand()%20+1;
            }while(tcsQipan[x1][y1]!=' ');
            tcsQipan[x1][y1]='*';
            Refresh(tcsQipan,grade,gamespeed);
        }
 
        else{       //  不吃米
            tcsQipan [tcsZuobiao[0][tail]][tcsZuobiao[1][tail]]=' ';
            tail=(tail+1)%100;
            tcsQipan [tcsZuobiao[0][head]][tcsZuobiao[1][head]]='*';
            head=(head+1)%100;
            tcsZuobiao[0][head]=x;
            tcsZuobiao[1][head]=y;
            tcsQipan[tcsZuobiao[0][head]][tcsZuobiao[1][head]]='#';
            Refresh(tcsQipan,grade,gamespeed);
        }
    }
    return 0;
}

0
张梓沫
张梓沫
资深守护
资深守护

#include <iostream>

 

#include <list>

 

#include <cstdio>

 

#include <string>

 

#include <vector>

 

#include <ctime>

 

#include <algorithm>

 

#include <conio.h>

 

#include <windows.h>

 

using namespace std;

 

 

 

class Node {

 

public:

 

    int x, y;

 

    Node(int x1, int y1);

 

};

 

 

 

class UserData {

 

public:

 

    string name;

 

    long long score;

 

    int gt;

 

    int gr;

 

    UserData(string s, long long sc,int gametime,int grade);

 

    friend bool operator < (UserData a, UserData b);

 

};

 

 

 

#define RIGHT 0x4d

 

#define LEFT 0x4b  

 

#define UP 0x48  

 

#define DOWN 0x50

 

#define YELLOW FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY

 

#define CYAN FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY

 

#define ORANGE FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY

 

#define PURPLE FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY

 

#define RED  FOREGROUND_RED | FOREGROUND_INTENSITY

 

const int STARTX = 8;

 

const int STARTY = 4;

 

const int RANGEX = 60;

 

const int RANGEY = 20;

 

int point=10;

 

const int ENDX = STARTX + RANGEX;

 

const int ENDY = STARTY + RANGEY;

 

bool isSnake[RANGEY + 10 ][RANGEX + 10];

 

int speed;

 

int sysj;

 

int gametime;

 

list<Node> snake;

 

int curDiraction; //蛇的当前前进方向, 1上, 2下, 3左, 4右

 

int score; //当前分数

 

int grade;

 

int snakeLen; //蛇的长度

 

int foodx, foody; //食物坐标

 

int gox, goy; //蛇头坐标

 

int mj;

 

void GoTo(short x, short y); //定位光标

 

void DrawBoard(); //绘制边框

 

void ShowInformation(); //展示游戏信息

 

void Init(); //初始化游戏

 

void RunSnake(int x, int y); //绘制蛇身

 

void Try(int& x, int& y); //试走

 

bool IsGoodCoord(int x, int y); //前进坐标是否合法

 

void AddFood(); //增加食物

 

void EartFood(); //吃食物

 

void InitSnake(); //初始化蛇身

 

bool EndGame(); //结束游戏

 

bool StartGame(); //启动游戏

 

bool GameMenu(); //游戏菜单

 

void ShowRanking(); //排行榜

 

void ShowAbout(); //相关信息

 

void InputData(); //输入玩家名字

 

 

 

int main() {

 

    system("title 贪吃蛇小游戏 by 张梓沫");

 

    while (true) {

 

        if (!GameMenu()) return 0;

 

    }

 

    return 0;

 

}

 

 

 

Node::Node(int x1, int y1) { //构造Node对象

 

    x = x1; y = y1;

 

}

 

 

 

bool operator < (UserData a, UserData b) { //重载运算符,按分数由大到小排列

 

    if(a.score != b.score)

 

    return a.score > b.score;

 

    if(a.gt !=b.gt)

 

    return a.gt > b.gt;

 

    else

 

    return a.gr > b.gr;

 

}

 

UserData::UserData(string s, long long sc,int gametime_,int _grade) { //构造UserData对象

 

    name = s; score = sc; gt=gametime_; gr=_grade;

 

}

 

 

 

void color(WORD A)

 

{

 

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), A);

 

}

 

 

 

void Color(int score_)

 

{

 

    if(score_%4==1)

 

    {

 

        color(PURPLE);

 

    }

 

    else if(score_%4==2)

 

    {

 

        color(RED);

 

    }

 

    else if(score_%4==3)

 

    {

 

        color(YELLOW);

 

    }

 

    else if(score_%4==0)

 

    {

 

        color(CYAN);

 

    }

 

}

 

 

 

void GoTo(short x, short y) { //定位光标

 

    COORD coord = { x, y };

 

    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);

 

}

 

 

 

void ShowInformation() { //输出游戏信息

 

    color(YELLOW);

 

    GoTo(78, 5);

 

    printf("贪吃蛇游戏");

 

    GoTo(78,18);

 

    gametime=(clock()-mj)/1000;

 

    grade=snakeLen-3;

 

    printf("生存时间:%3d 秒",(clock()-mj)/1000);

 

    GoTo(78, 8);

 

    printf("游戏规则:");

 

    GoTo(78, 10);

 

    printf("请按 ↑ ↓ ← →  来控制您的蛇吃东西");

 

    GoTo(78, 12);

 

    printf("吃的越多,蛇就越长,您的等级也将越高");

 

    GoTo(78, 14);

 

    printf("当蛇吃到自己或撞上墙时,游戏结束。");

 

    GoTo(78,16);

 

    printf("自动前进时间:%3dms",speed);

 

    GoTo(78, 20);

 

    printf("当前等级: %8d", snakeLen-3);

 

    GoTo(78, 23);

 

    printf("您的分数: %d", score);

 

    color(CYAN);

 

    printf("+%d=%d",score/3,score*3/2);

 

    color(YELLOW);

 

    GoTo(78,25);

 

    printf("剩余时间:%d秒",10+(snakeLen-3)*4-gametime);

 

    sysj=10+(snakeLen-3)*4-gametime;

 

}

 

 

 

void DrawBoard() { //绘制墙体

 

 

 

    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); //获得输出句柄

 

 

 

    CONSOLE_CURSOR_INFO cursor_info = { 1, 0 }; //光标信息

 

    SetConsoleCursorInfo(hOut, &cursor_info); //隐藏光标

 

 

 

    COORD size = { 120, 30 };

 

    SetConsoleScreenBufferSize(hOut, size); //重设缓冲区大小

 

 

 

    SMALL_RECT rc = { 0 , 0, 120, 30 };

 

    SetConsoleWindowInfo(hOut, true, &rc); //重设窗口大小

 

 

 

    SetConsoleTextAttribute(hOut, CYAN);

 

 

 

    for (int i = STARTX - 2; i <= ENDX + 2; i += 2) { //横向墙体

 

        GoTo(i, STARTY - 1);

 

        printf("■");

 

        GoTo(i, ENDY + 1);

 

        printf("■");

 

    }

 

    for (int i = STARTY - 1; i <= ENDY + 1; ++i) { //竖向墙体

 

        GoTo(STARTX - 2, i);

 

        printf("■");

 

        GoTo(ENDX + 2, i);

 

        printf("■");

 

    }

 

}

 

void draw()

 

{

 

    char m=snakeLen+62;

 

    Color(score);

 

    cout<<"■";

 

 }

 

void Init() { //初始化游戏

 

    system("cls");

 

    memset(isSnake, 0, sizeof(isSnake));

 

    speed = 200;

 

    curDiraction = 4;

 

    score = 0;

 

    DrawBoard();

 

    InitSnake();

 

    ShowInformation();

 

    AddFood();

 

    mj=clock();

 

    point=10;

 

    sysj=10;

 

}

 

 

 

void RunSnake(int x, int y) { //绘制蛇身

 

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);

 

    score += snakeLen + 1;

 

    if (x == foodx && y == foody) {

 

        EartFood();

 

        AddFood();

 

        return;

 

    }

 

    snake.push_front(Node(x, y));

 

    isSnake[y][x] = true;

 

    GoTo(x, y);

 

    draw();

 

    Node back = snake.back();

 

    snake.pop_back();

 

    isSnake[back.y][back.x] = false;

 

    GoTo(back.x, back.y);

 

    printf(" ");

 

}

 

 

 

void Try(int& x, int& y) { //试走

 

    int key, cnt = 100;

 

    while (cnt--) { //多次检测键盘状态

 

        if (_kbhit()) {

 

            key = getch();

 

            switch (key) {

 

            case UP:

 

                if (curDiraction == 1 || curDiraction == 2) break;

 

                --y; curDiraction = 1; return;

 

            case DOWN:

 

                if (curDiraction == 1 || curDiraction == 2) break;

 

                ++y; curDiraction = 2; return;

 

            case LEFT:

 

                if (curDiraction == 3 || curDiraction == 4) break;

 

                x -= 2; curDiraction = 3; return;

 

            case RIGHT:

 

                if (curDiraction == 3 || curDiraction == 4) break;

 

                x += 2; curDiraction = 4; return;

 

            }

 

        }

 

    }

 

    if (curDiraction == 1) --y; //用户没有输入时

 

    else if (curDiraction == 2) ++y;

 

    else if (curDiraction == 3) x -= 2;

 

    else x += 2;

 

}

 

 

 

bool IsGoodCoord(int x, int y) { //判断光标是否合法

 

    if (x <= ENDX && y <= ENDY && x >= STARTX && y >= STARTY)

 

        return true;

 

    else

 

        return false;

 

}

 

 

 

void AddFood() { //增加食物

 

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), PURPLE);

 

    srand((unsigned)time(NULL));

 

    while (true) {

 

        foodx = (rand()%ENDX) + 1;

 

        foody = (rand()%ENDY) + 1;

 

        if (foodx&1) foodx++;

 

        if (!isSnake[foody][foodx] && IsGoodCoord(foodx, foody)) break;

 

    }

 

    GoTo(foodx, foody);

 

    int a=rand()%5;

 

    if(a>=4)

 

    printf("★");

 

    else if(a<=1)

 

    printf("○");

 

    else

 

    printf("▲");

 

}

 

 

 

void EartFood() { //吃东西

 

    point+=4;

 

    int sb=gametime=(clock()-mj)/1000;

 

    sysj=point-sb;

 

    score+=score/2;

 

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);

 

    snake.push_front(Node(foodx, foody));

 

    isSnake[foody][foodx] = true;

 

    ++snakeLen;

 

    if (speed >= 55) speed -= 5;

 

 

 

    GoTo(foodx, foody);

 

    draw();

 

    AddFood();

 

}

 

 

 

void InitSnake() { //初始化蛇身

 

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);

 

    snakeLen = 3, gox = 18, goy = 14;

 

    snake.clear();

 

    snake.push_front(Node(12, 14));

 

    snake.push_front(Node(14, 14));

 

    snake.push_front(Node(16, 14));

 

    for (int i = 12; i <= 16; i += 2) {

 

        GoTo(i, 14);

 

        draw();

 

        isSnake[14][i] = true;

 

    }

 

}

 

bool EndGame() { //结束游戏

 

    system("cls");

 

    DrawBoard();

 

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);

 

    GoTo(28, 10);

 

    printf("您的本局游戏得分: %d分", score);

 

    GoTo(32, 18);

 

    printf("....你挂了....");

 

    GoTo(27, 20);

 

    printf("是否继续游戏: 是(1), 否(0)");

 

    GoTo(27, 22);

 

    char key = getch();

 

    while (true) {

 

        if (key == '1') return false;

 

        else if (key == '0')

 

        {GoTo(ENDX+1,ENDY+2);

 

        exit(0);return true;

 

        }

 

        else key = getch();

 

    }

 

}

 

 

 

bool StartGame() { //启动游戏

 

 

 

    Init();

 

 

 

    while (IsGoodCoord(gox, goy) && !isSnake[goy][gox]&&sysj>0) { //当试走合法时

 

        RunSnake(gox, goy);

 

        ShowInformation();

 

        Try(gox, goy);

 

        Sleep(speed);

 

    }

 

    InputData();

 

    return true;

 

}

 

 

 

bool GameMenu() { //游戏菜单

 

    system("cls");

 

    DrawBoard();

 

    GoTo(STARTX + 22, STARTY + 4);

 

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);

 

    printf("欢迎进入贪吃蛇游戏!");

 

    GoTo(STARTX + 24, STARTY + 10);

 

    printf("1: 新游戏");

 

    GoTo(STARTX + 24, STARTY + 12);

 

    printf("2: 排行榜");

 

    GoTo(STARTX + 24, STARTY + 14);

 

    printf("3: 关于游戏");

 

    GoTo(STARTX + 24, STARTY + 16);

 

    printf("4: 退出游戏");

 

 

 

    while (true) {

 

        if (_kbhit()) {

 

            char key = getch();

 

            switch (key) {

 

            case '1':

 

                if (!StartGame()) return false;

 

                else return true;

 

            case '2':

 

                ShowRanking(); return true;

 

            case '3':

 

                ShowAbout(); return true;

 

            case '4':

 

                GoTo(1,ENDY+2);

 

                return false;

 

            default:

 

                return true;

 

            }

 

        }

 

    }

 

}

 

 

 

void ShowRanking() { //展示排行榜

 

    vector<UserData> vu;

 

    FILE *fp = fopen("GameData.txt", "r");

 

    if (fp == NULL) fp = fopen("GameData.txt", "w+");

 

    char name[20];

 

    int len = 0;

 

    while (fscanf(fp, "%s", name) != EOF) {

 

        ++len;

 

        int score,g=grade;

 

        fscanf(fp, "%d%d%d%*c", &score,&gametime,&g);

 

        vu.push_back(UserData(string(name), score,gametime,grade));

 

    }

 

    fclose(fp);

 

    sort(vu.begin(), vu.end()); //对得分进行排名

 

    system("cls");

 

    DrawBoard();

 

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), CYAN);

 

    GoTo(STARTX + 8, STARTY + 2);

 

    printf("用户");

 

    GoTo(STARTX + 20, STARTY + 2);

 

    printf("分数");

 

    GoTo(STARTX + 32, STARTY + 2);

 

    printf("生存时间");

 

    GoTo(STARTX + 44, STARTY + 2);

 

    printf("排行");

 

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);

 

 

 

    for (int i = 0; i < len && i < 10; ++i) { //打印前十名用户数据

 

        char const *p = vu[i].name.c_str();

 

        Color(vu[i].score);

 

        GoTo(STARTX + 8, STARTY + 4 + i);

 

        printf("%s", p);

 

        GoTo(STARTX + 20, STARTY + 4 + i);

 

        printf("%d分", vu[i].score);

 

        GoTo(STARTX + 32, STARTY + 4 + i);

 

        printf("%d秒", vu[i].gt);

 

        GoTo(STARTX + 44, STARTY + 4 + i);

 

        printf(" %d", i + 1);

 

    }

 

 

 

    GoTo(STARTX + 4, ENDY - 2);

 

    printf("-----------------  按'1'返回游戏菜单  ---------------");

 

    while (true) {

 

        if (_kbhit()) {

 

            char key = getch();

 

            if (key == '1') break;

 

        }

 

    }

 

}

 

 

 

void ShowAbout() { //展示游戏相关

 

    system("cls");

 

    DrawBoard();

 

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);

 

 

 

    GoTo(STARTX + 4, STARTY + 2);

 

    printf("-------------------  贪吃蛇游戏  -------------------");

 

    GoTo(STARTX + 10, STARTY + 4);

 

    printf("制作人: ");

 

    GoTo(STARTX + 10, STARTY + 6);

 

    printf("张梓沫");

 

    GoTo(STARTX + 10,STARTY + 8);

 

    printf("贪吃蛇游戏");

 

    GoTo(STARTX + 10,STARTY + 10);

 

    printf("游戏规则:");

 

    GoTo(STARTX + 10,STARTY + 12);

 

    printf("请按 ↑ ↓ ← →  来控制您的蛇吃东西");

 

    GoTo(STARTX + 10,STARTY + 14);

 

    printf("吃的越多,蛇就越长,您的等级也将越高");

 

    GoTo(STARTX + 10,STARTY + 16);

 

    printf("当蛇吃到自己或撞上墙时,游戏结束。");

 

 

 

    GoTo(STARTX + 4, ENDY - 2);

 

    printf("-----------------  按'1'返回游戏菜单  ---------------");

 

    while (true) {

 

        if (_kbhit()) {

 

            char key = getch();

 

            if (key == '1') break;

 

        }

 

    }

 

}

 

 

 

void InputData() { //用户输入名字

 

    char name[20];

 

    if(score>=1000)

 

    {

 

    GoTo(STARTX + 10, STARTY + 10);

 

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), RED);

 

    printf("请输入你的名字: ");

 

    COORD coord = { STARTX + 10, STARTY + 12 };

 

    SetConsoleCursorPosition(GetStdHandle(STD_INPUT_HANDLE), coord);

 

    while (true) { //忽略非法字符

 

        scanf("%s", name);

 

        if (name[0] != 0 && name[0] != ' ') break;

 

    }FILE *fp = fopen("Gamedata.txt", "a");

 

    if (fp == NULL) fp = fopen("GameData.txt", "w+");

 

    fprintf(fp, "%s %d %d \n", name, score,gametime);

 

    fclose(fp);

 

    }

 

    else

 

    {

 

        GoTo(STARTX + 20, STARTY + 10);

 

        cout<<"哟!这分数也能上榜??"<<endl;

 

        Sleep(1000);

 

     }  

 

    EndGame();

 

 

 

}

 

 

 

这是我收集贪吃蛇代码四个中的第一个

0
张梓沫
张梓沫
资深守护
资深守护

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <windows.h>
#include <conio.h>
using namespace std;
int block00[4][4] = { { 10,0,0,0 },{ 1,1,1,1 },{ 0,0,0,0 },{ 0,0,0,0 } };
int block01[4][4] = { { 11,0,1,0 },{ 0,0,1,0 },{ 0,0,1,0 },{ 0,0,1,0 } };
int block02[4][4] = { { 12,0,0,0 },{ 0,0,0,0 },{ 1,1,1,0 },{ 0,1,0,0 } };
int block03[4][4] = { { 13,0,0,0 },{ 0,1,0,0 },{ 1,1,0,0 },{ 0,1,0,0 } };
int block04[4][4] = { { 14,0,0,0 },{ 0,0,0,0 },{ 0,1,0,0 },{ 1,1,1,0 } };
int block05[4][4] = { { 15,0,0,0 },{ 0,1,0,0 },{ 0,1,1,0 },{ 0,1,0,0 } };
int block06[4][4] = { { 16,0,0,0 },{ 0,0,0,0 },{ 1,1,1,0 },{ 1,0,0,0 } };
int block07[4][4] = { { 17,0,0,0 },{ 1,1,0,0 },{ 0,1,0,0 },{ 0,1,0,0 } };
int block08[4][4] = { { 18,0,0,0 },{ 0,0,0,0 },{ 0,0,1,0 },{ 1,1,1,0 } };
int block09[4][4] = { { 19,0,0,0 },{ 0,1,0,0 },{ 0,1,0,0 },{ 0,1,1,0 } };
int block10[4][4] = { { 20,0,0,0 },{ 0,0,0,0 },{ 1,1,1,0 },{ 0,0,1,0 } };
int block11[4][4] = { { 21,0,0,0 },{ 0,1,0,0 },{ 0,1,0,0 },{ 1,1,0,0 } };
int block12[4][4] = { { 22,0,0,0 },{ 0,0,0,0 },{ 1,0,0,0 },{ 1,1,1,0 } };
int block13[4][4] = { { 23,0,0,0 },{ 0,1,1,0 },{ 0,1,0,0 },{ 0,1,0,0 } };
int block14[4][4] = { { 24,0,0,0 },{ 0,0,0,0 },{ 0,1,1,0 },{ 1,1,0,0 } };
int block15[4][4] = { { 25,0,0,0 },{ 1,0,0,0 },{ 1,1,0,0 },{ 0,1,0,0 } };
int block16[4][4] = { { 26,0,0,0 },{ 0,0,0,0 },{ 1,1,0,0 },{ 0,1,1,0 } };
int block17[4][4] = { { 27,0,0,0 },{ 0,0,1,0 },{ 0,1,1,0 },{ 0,1,0,0 } };
int block18[4][4] = { { 28,0,0,0 },{ 0,0,0,0 },{ 1,1,0,0 },{ 1,1,0,0 } };
 
void initialWindow(HANDLE hOut);//初始化窗口
void initialPrint(HANDLE hOut);//初始化界面
void gotoXY(HANDLE hOut, int x, int y);//移动光标
void roundBlock(HANDLE hOut, int block[4][4]);//随机生成方块并打印到下一个方块位置
bool collisionDetection(int block[4][4], int map[21][12], int x, int y);//检测碰撞
void printBlock(HANDLE hOut, int block[4][4], int x, int y);//打印方块
void clearBlock(HANDLE hOut, int block[4][4], int x, int y);//消除方块
void myLeft(HANDLE hOut, int block[4][4], int map[21][12], int x, int &y);//左移
void myRight(HANDLE hOut, int block[4][4], int map[21][12], int x, int &y);//右移
void myUp(HANDLE hOut, int block[4][4], int map[21][12], int x, int &y);//顺时针旋转90度
int myDown(HANDLE hOut, int block[4][4], int map[21][12], int &x, int y);//加速下落
void myStop(HANDLE hOut, int block[4][4]);//游戏暂停
void gameOver(HANDLE hOut, int block[4][4], int map[21][12]);//游戏结束
void eliminateRow(HANDLE hOut, int map[21][12], int &val, int &fraction, int &checkpoint);//判断是否能消行并更新分值
int main()
{
    int map[21][12];
    int blockA[4][4];//候选区的方块
    int blockB[4][4];//下落中的方块
    int positionX, positionY;//方块左上角的坐标
    bool check;//检查方块还能不能下落
    char key;//用来存储按键
    int val;//用来控制下落速度
    int fraction;//用来存储得分
    int checkpoint;//用来存储关卡
    int times;
    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);//获取标准输出设备句柄
    initialWindow(hOut);
initial:
    gotoXY(hOut, 0, 0);
    initialPrint(hOut);
    check = true;
    val = 50;
    fraction = 0;
    checkpoint = 1;
    times = val;
    for (int i = 0; i < 20; ++i)
    {
        for (int j = 1; j < 11; ++j)
        {
            map[i][j] = 0;
        }
    }
    for (int i = 0; i < 20; ++i)
    {
        map[i][0] = map[i][11] = 1;
    }
    for (int i = 0; i < 12; ++i)
    {
        map[20][i] = 1;
    }
 
    srand((unsigned)time(NULL));
    roundBlock(hOut, blockA);
    while (true)
    {
        if (check)
        {
            eliminateRow(hOut, map, val, fraction, checkpoint);
            check = false;
            positionX = -3;
            positionY = 4;
            if (collisionDetection(blockA, map, positionX, positionY))
            {
                for (int i = 0; i < 4; ++i)
                {
                    for (int j = 0; j < 4; ++j)
                    {
                        blockB[i][j] = blockA[i][j];
                    }
                }
                roundBlock(hOut, blockA);
            }
            else
            {
                gameOver(hOut, blockA, map);
                goto initial;
            }
        }
        printBlock(hOut, blockB, positionX, positionY);
        if (_kbhit())
        {
            key = _getch();
            switch (key)
            {
            case 72:
                myUp(hOut, blockB, map, positionX, positionY);
                break;
            case 75:
                myLeft(hOut, blockB, map, positionX, positionY);
                break;
            case 77:
                myRight(hOut, blockB, map, positionX, positionY);
                break;
            case 80:
                switch (myDown(hOut, blockB, map, positionX, positionY))
                {
                case 0:
                    check = false;
                    break;
                case 1:
                    check = true;
                    break;
                case 2:
                    gameOver(hOut, blockB, map);
                    goto initial;
                default:
                    break;
                }
                break;
            case 32:
                myStop(hOut, blockA);
                break;
            case 27:
                exit(0);
            default:
                break;
            }
        }
        Sleep(20);
        if (0 == --times)
        {
            switch (myDown(hOut, blockB, map, positionX, positionY))
            {
            case 0:
                check = false;
                break;
            case 1:
                check = true;
                break;
            case 2:
                gameOver(hOut, blockB, map);
                goto initial;
            default:
                break;
            }
            times = val;
        }
    }
    cin.get();
    return 0;
}
 
void initialWindow(HANDLE hOut)
{
    SetConsoleTitle("俄罗斯方块");
    COORD size = { 80, 25 };
    SetConsoleScreenBufferSize(hOut, size);
    SMALL_RECT rc = { 0, 0, 79, 24 };
    SetConsoleWindowInfo(hOut, true, &rc);
    CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };
    SetConsoleCursorInfo(hOut, &cursor_info);
}
 
void initialPrint(HANDLE hOut)
{
    SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
    for (int i = 0; i < 20; ++i)
    {
        cout << "■                    ■☆                      ☆" << endl;
    }
    gotoXY(hOut, 26, 0);
    cout << "☆☆☆☆☆☆☆☆☆☆☆";
    gotoXY(hOut, 0, 20);
    cout << "■■■■■■■■■■■■☆☆☆☆☆☆☆☆☆☆☆☆☆";
    gotoXY(hOut, 26, 1);
    cout << "分    数:      ";
    gotoXY(hOut, 26, 2);
    cout << "关    卡:      ";
    gotoXY(hOut, 26, 4);
    cout << "下一方块:";
    gotoXY(hOut, 26, 9);
    cout << "操作方法:";
    gotoXY(hOut, 30, 11);
    cout << "↑:旋转 ↓:速降";
    gotoXY(hOut, 30, 12);
    cout << "→:右移 ←:左移";
    gotoXY(hOut, 30, 13);
    cout << "空格键:开始/暂停";
    gotoXY(hOut, 30, 14);
    cout << "Esc 键:退出";
    gotoXY(hOut, 26, 16);
    cout << "关    于:";
    gotoXY(hOut, 30, 18);
    cout << "俄罗斯方块V1.0";
    gotoXY(hOut, 35, 19);
    cout << "作者:张梓沫";
}
 
void gotoXY(HANDLE hOut, int x, int y)
{
    COORD pos;
    pos.X = x;
    pos.Y = y;
    SetConsoleCursorPosition(hOut, pos);
}
 
void roundBlock(HANDLE hOut, int block[4][4])
{
    clearBlock(hOut, block, 5, 15);
    switch (rand() % 19)
    {
    case 0:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block00[i][j];
            }
        }
        break;
    case 1:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block01[i][j];
            }
        }
        break;
    case 2:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block02[i][j];
            }
        }
        break;
    case 3:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block03[i][j];
            }
        }
        break;
    case 4:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block04[i][j];
            }
        }
        break;
    case 5:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block05[i][j];
            }
        }
        break;
    case 6:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block06[i][j];
            }
        }
        break;
    case 7:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block07[i][j];
            }
        }
        break;
    case 8:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block08[i][j];
            }
        }
        break;
    case 9:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block09[i][j];
            }
        }
        break;
    case 10:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block10[i][j];
            }
        }
        break;
    case 11:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block11[i][j];
            }
        }
        break;
    case 12:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block12[i][j];
            }
        }
        break;
    case 13:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block13[i][j];
            }
        }
        break;
    case 14:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block14[i][j];
            }
        }
        break;
    case 15:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block15[i][j];
            }
        }
        break;
    case 16:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block16[i][j];
            }
        }
        break;
    case 17:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block17[i][j];
            }
        }
        break;
    case 18:
        for (int i = 0; i < 4; ++i)
        {
            for (int j = 0; j < 4; ++j)
            {
                block[i][j] = block18[i][j];
            }
        }
        break;
    default:
        break;
    }
    printBlock(hOut, block, 5, 15);
}
 
bool collisionDetection(int block[4][4], int map[21][12], int x, int y)
{
    for (int i = 0; i < 4; ++i)
    {
        for (int j = 0; j < 4; ++j)
        {
            if (x + i >= 0 && y + j >= 0 && map[x + i][y + j] == 1 && block[i][j] == 1)
            {
                return false;
            }
        }
    }
    return true;
}
 
void printBlock(HANDLE hOut, int block[4][4], int x, int y)
{
    switch (block[0][0])
    {
    case 10:
    case 11:
        SetConsoleTextAttribute(hOut, FOREGROUND_GREEN);
        break;
    case 12:
    case 13:
    case 14:
    case 15:
        SetConsoleTextAttribute(hOut, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
        break;
    case 16:
    case 17:
    case 18:
    case 19:
        SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
        break;
    case 20:
    case 21:
    case 22:
    case 23:
        SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
        break;
    case 24:
    case 25:
        SetConsoleTextAttribute(hOut, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
        break;
    case 26:
    case 27:
        SetConsoleTextAttribute(hOut, FOREGROUND_BLUE | FOREGROUND_INTENSITY);
        break;
    case 28:
        SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_INTENSITY);
        break;
    default:
        break;
    }
    for (int i = 0; i < 4; ++i)
    {
        if (i + x >= 0)
        {
            for (int j = 0; j < 4; ++j)
            {
                if (block[i][j] == 1)
                {
 
                    gotoXY(hOut, 2 * (y + j), x + i);
                    cout << "■";
                }
            }
        }
    }
}
 
void clearBlock(HANDLE hOut, int block[4][4], int x, int y)
{
    for (int i = 0; i < 4; ++i)
    {
        if (i + x >= 0)
        {
            for (int j = 0; j < 4; ++j)
            {
                if (block[i][j] == 1)
                {
                    gotoXY(hOut, 2 * (y + j), x + i);
                    cout << "  ";
                }
            }
        }
    }
}
 
void gameOver(HANDLE hOut, int block[4][4], int map[21][12])
{
    SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_INTENSITY);
    gotoXY(hOut, 9, 8);
    cout << "GAME OVER";
    gotoXY(hOut, 8, 9);
    cout << "空格键:重来";
    gotoXY(hOut, 8, 10);
    cout << "ESC键:退出";
    char key;
    while (true)
    {
        key = _getch();
        if (key == 32)
        {
            return;
        }
        if (key == 27)
        {
            exit(0);
        }
    }
}
 
int myDown(HANDLE hOut, int block[4][4], int map[21][12], int &x, int y)
{
    if (collisionDetection(block, map, x + 1, y))
    {
        clearBlock(hOut, block, x, y);
        ++x;
        return 0;
    }
    if (x < 0)
    {
        return 2;
    }
    for (int i = 0; i < 4; ++i)
    {
        for (int j = 0; j < 4; ++j)
        {
            if (block[i][j] == 1)
            {
                map[x + i][y + j] = 1;
                SetConsoleTextAttribute(hOut, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
                gotoXY(hOut, 2 * (y + j), x + i);
                cout << "■";
            }
        }
    }
    return 1;
}
 
void myLeft(HANDLE hOut, int block[4][4], int map[21][12], int x, int &y)
{
    if (collisionDetection(block, map, x, y - 1))
    {
        clearBlock(hOut, block, x, y);
        --y;
    }
}
 
void myRight(HANDLE hOut, int block[4][4], int map[21][12], int x, int &y)
{
    if (collisionDetection(block, map, x, y + 1))
    {
        clearBlock(hOut, block, x, y);
        ++y;
    }
}
 
void myUp(HANDLE hOut, int block[4][4], int map[21][12], int x, int &y)
{
    switch (block[0][0])
    {
    case 10:
        if (collisionDetection(block01, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block01[i][j];
                }
            }
        }
        break;
    case 11:
        if (collisionDetection(block00, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block00[i][j];
                }
            }
        }
        else if (collisionDetection(block00, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block00[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block00, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block00[i][j];
                }
            }
            ++y;
        }
        else if (collisionDetection(block00, map, x, y - 2))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block00[i][j];
                }
            }
            y = y - 2;
        }
        else if (collisionDetection(block00, map, x, y + 2))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block00[i][j];
                }
            }
            y = y + 2;
        }
        break;
    case 12:
        if (collisionDetection(block03, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block03[i][j];
                }
            }
        }
        else if (collisionDetection(block03, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block03[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block03, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block03[i][j];
                }
            }
            ++y;
        }
        break;
    case 13:
        if (collisionDetection(block04, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block04[i][j];
                }
            }
        }
        else if (collisionDetection(block04, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block04[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block04, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block04[i][j];
                }
            }
            ++y;
        }
        break;
    case 14:
        if (collisionDetection(block05, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block05[i][j];
                }
            }
        }
        else if (collisionDetection(block05, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block05[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block05, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block05[i][j];
                }
            }
            ++y;
        }
        break;
    case 15:
        if (collisionDetection(block02, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block02[i][j];
                }
            }
        }
        else if (collisionDetection(block02, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block02[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block02, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block02[i][j];
                }
            }
            ++y;
        }
        break;
 
    case 16:
        if (collisionDetection(block07, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block07[i][j];
                }
            }
        }
        else if (collisionDetection(block07, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block07[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block07, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block07[i][j];
                }
            }
            ++y;
        }
        break;
    case 17:
        if (collisionDetection(block08, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block08[i][j];
                }
            }
        }
        else if (collisionDetection(block08, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block08[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block08, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block08[i][j];
                }
            }
            ++y;
        }
        break;
    case 18:
        if (collisionDetection(block09, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block09[i][j];
                }
            }
        }
        else if (collisionDetection(block09, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block09[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block09, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block09[i][j];
                }
            }
            ++y;
        }
        break;
    case 19:
        if (collisionDetection(block06, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block06[i][j];
                }
            }
        }
        else if (collisionDetection(block06, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block06[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block06, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block06[i][j];
                }
            }
            ++y;
        }
        break;
    case 20:
        if (collisionDetection(block11, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block11[i][j];
                }
            }
        }
        else if (collisionDetection(block11, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block11[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block11, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block11[i][j];
                }
            }
            ++y;
        }
        break;
    case 21:
        if (collisionDetection(block12, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block12[i][j];
                }
            }
        }
        else if (collisionDetection(block12, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block12[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block12, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block12[i][j];
                }
            }
            ++y;
        }
        break;
    case 22:
        if (collisionDetection(block13, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block13[i][j];
                }
            }
        }
        else if (collisionDetection(block13, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block13[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block13, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block13[i][j];
                }
            }
            ++y;
        }
        break;
    case 23:
        if (collisionDetection(block10, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block10[i][j];
                }
            }
        }
        else if (collisionDetection(block10, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block10[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block10, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block10[i][j];
                }
            }
            ++y;
        }
        break;
    case 24:
        if (collisionDetection(block15, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block15[i][j];
                }
            }
        }
        else if (collisionDetection(block15, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block15[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block15, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block15[i][j];
                }
            }
            ++y;
        }
        break;
    case 25:
        if (collisionDetection(block14, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block14[i][j];
                }
            }
        }
        else if (collisionDetection(block14, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block14[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block14, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block14[i][j];
                }
            }
            ++y;
        }
        break;
    case 26:
        if (collisionDetection(block17, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block17[i][j];
                }
            }
        }
        else if (collisionDetection(block17, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block17[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block17, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block17[i][j];
                }
            }
            ++y;
        }
        break;
    case 27:
        if (collisionDetection(block16, map, x, y))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block16[i][j];
                }
            }
        }
        else if (collisionDetection(block16, map, x, y - 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block16[i][j];
                }
            }
            --y;
        }
        else if (collisionDetection(block16, map, x, y + 1))
        {
            clearBlock(hOut, block, x, y);
            for (int i = 0; i < 4; ++i)
            {
                for (int j = 0; j < 4; ++j)
                {
                    block[i][j] = block16[i][j];
                }
            }
            ++y;
        }
        break;
    default:
        break;
    }
}
 
void myStop(HANDLE hOut, int block[4][4])
{
    clearBlock(hOut, block, 5, 15);
    SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_INTENSITY);
    gotoXY(hOut, 30, 7);
    cout << "游戏暂停";
    char key;
    while (true)
    {
        key = _getch();
        if (key == 32)
        {
            gotoXY(hOut, 30, 7);
            cout << "        ";
            printBlock(hOut, block, 5, 15);
            return;
        }
        if (key == 27)
        {
            exit(0);
        }
    }
}
 
void eliminateRow(HANDLE hOut, int map[21][12], int &val, int &fraction, int &checkpoint)
{
    SetConsoleTextAttribute(hOut, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
    for (int i = 19; i >= 0; --i)
    {
        int x = 0;
        for (int j = 1; j < 11; ++j)
        {
            x += map[i][j];
        }
        if (x == 10)
        {
            fraction += 100;
            if (val > 1 && fraction / 1000 + 1 != checkpoint)
            {
                checkpoint = fraction / 1000 + 1;
                val -= 5;
            }
            for (int m = i; m > 0; --m)
            {
                for (int n = 1; n < 11; ++n)
                {
                    map[m][n] = map[m - 1][n];
                    gotoXY(hOut, 2 * n, m);
                    if (map[m][n] == 1)
                    {
                        cout << "■";
                    }
                    else
                    {
                        cout << "  ";
                    }
                }
            }
            ++i;
        }
    }
    gotoXY(hOut, 36, 1);
    cout << fraction;
    gotoXY(hOut, 36, 2);
    cout << checkpoint;
}

 

 

再送你一个俄罗斯方块

0
张梓沫
张梓沫
资深守护
资深守护

还需要吗?我可以给你剩下的三个

#include<stdio.h>
#include<process.h>
#include<windows.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>
#define WIDTH 40
#define HEIGH 12
enum direction{//方向
LEFT,
RIGHT,
UP,
DOWN
};
struct Food{//食物
int x;
int y;
};
struct Node{//画蛇身
int x;
int y;
struct Node *next;
};
struct Snake{//蛇属性
int lenth;//长度
enum direction dir;//方向
};
struct Food *food; //食物
struct Snake *snake;//蛇属性
struct Node *snode,*tail;//蛇身
int SPEECH=200;
int score=0;//分数
int smark=0;//吃食物标记
int times=0;
int STOP=0;
void Initfood();//产生食物
void Initsnake();//构造snake
void Eatfood();//头部前进
void Addnode(int x, int y);//增加蛇身
void display(struct Node *shead);//显示蛇身坐标
void move();//蛇移动
void draw();//画蛇
void Homepage();//主页
void keybordhit();//监控键盘按键
void Addtail();//吃到食物
void gotoxy(int x, int y)//定位光标
{
    COORD pos;
    pos.X = x - 1;
    pos.Y = y - 1;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
}
void Initsnake()//构造snake
{
int i;
snake=(struct Snake*)malloc(sizeof(struct Snake));
tail=(struct Node*)malloc(sizeof(struct Node));
food = (struct Food*)malloc(sizeof(struct Food));
snake->lenth=5;//初始长度 5
snake->dir=RIGHT;//初始蛇头方向 右
for(i=2;i<=snake->lenth+2;i++)//增加 5 个结点
{
Addnode(i,2);
}
}
void Initfood()//产生食物
{
struct Node *p=snode;
int mark=1;
srand((unsigned)time(NULL));//以时间为种子产生随机数
while(1)
{
food->x=rand()%(WIDTH-2)+2;//食物X坐标
food->y=rand()%(HEIGH-2)+2;//食物Y坐标
while(p!=NULL)
{
if((food->x==p->x)&&(food->y==p->y))//如果食物产生在蛇身上
{//则重新生成食物
mark=0;//食物生成无效
break;
}
p=p->next;
}
if(mark==1)//如果食物不在蛇身上,生成食物,否则重新生成食物
{
gotoxy(food->x,food->y);
printf("%c",3);
break;
}
mark=1;
p=snode;
}
}
void move()//移动
{
struct Node *q, *p=snode;
if(snake->dir==RIGHT)
{
Addnode(p->x+1,p->y);
if(smark==0)
{
while(p->next!=NULL)
{
q=p;
p=p->next;
}
q->next=NULL;
free(p);
}
}
if(snake->dir==LEFT)
{
Addnode(p->x-1,p->y);
if(smark==0)
{
while(p->next!=NULL)
{
q=p;
p=p->next;
}
q->next=NULL;
free(p);
}
}
if(snake->dir==UP)
{
Addnode(p->x,p->y-1);
if(smark==0)
{
while(p->next!=NULL)
{
q=p;
p=p->next;
}
q->next=NULL;
free(p);
}
}
if(snake->dir==DOWN)
{
Addnode(p->x,p->y+1);
if(smark==0)
{
while(p->next!=NULL)
{
q=p;
p=p->next;
}
q->next=NULL;
free(p);
}
}
}
void Addnode(int x, int y)//增加蛇身
{
struct Node *newnode=(struct Node *)malloc(sizeof(struct Node));
struct Node *p=snode;
newnode->next=snode;
newnode->x=x;
newnode->y=y;
snode=newnode;//结点加到蛇头
if(x<2||x>=WIDTH||y<2||y>=HEIGH)//碰到边界
{
STOP=1;
gotoxy(10,19);
printf("撞墙,游戏结束,任意键退出!\n");//失败
_getch();
free(snode);//释放内存
free(snake);
exit(0);
}
while(p!=NULL)//碰到自身
{
if(p->next!=NULL)
if((p->x==x)&&(p->y==y))
{
STOP=1;
gotoxy(10,19);
printf("撞到自身,游戏结束,任意键退出!\n");//失败
_getch();
free(snode);//释放内存
free(snake);
exit(0);
}
p=p->next;
}
}
void Eatfood()//吃到食物
{
Addtail();
score++;
}
void Addtail()//增加蛇尾
{
struct Node *newnode=(struct Node *)malloc(sizeof(struct Node));
struct Node *p=snode;
tail->next=newnode;
newnode->x=50;
newnode->y=20;
newnode->next=NULL;//结点加到蛇头
tail=newnode;//新的蛇尾
}
void draw()//画蛇
{
struct Node *p=snode;
int i,j;
while(p!=NULL)
{
gotoxy(p->x,p->y);
printf("%c",2);
tail=p;
p=p->next;
}
if(snode->x==food->x&&snode->y==food->y)//蛇头坐标等于食物坐标
{
smark=1;
Eatfood();//增加结点
Initfood();//产生食物
}
if(smark==0)
{
gotoxy(tail->x,tail->y);//没吃到食物清除之前的尾结点
printf("%c",' ');//如果吃到食物,不清楚尾结点
}
else
{
times=1;
}
if((smark==1)&&(times==1))
{
gotoxy(tail->x,tail->y);//没吃到食物清除之前的尾结点
printf("%c",' ');//如果吃到食物,不清楚尾结点
smark=0;
}
gotoxy(50,12);
printf("食物: %d,%d",food->x,food->y);
gotoxy(50,5);
printf("分数: %d",score);
gotoxy(50,7);
printf("速度: %d",SPEECH);
gotoxy(15,14);
printf("按o键加速");
gotoxy(15,15);
printf("按p键减速");
gotoxy(15,16);
printf("按空格键暂停");
}
void HideCursor()//隐藏光标
{
 CONSOLE_CURSOR_INFO cursor_info = {1, 0};
 SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
void Homepage()//绘主页
{
int x,y;
HideCursor();//隐藏光标
printf("----------------------------------------\n");
printf("|\t\t\t\t       |\n");
printf("|\t\t\t\t       |\n");
printf("|\t\t\t\t       |\n");
printf("|\t\t\t\t       |\n");
printf("|\t\t\t\t       |\n");
printf("|\t\t\t\t       |\n");
printf("|\t\t\t\t       |\n");
printf("|\t\t\t\t       |\n");
printf("|\t\t\t\t       |\n");
printf("|\t\t\t\t       |\n");
printf("----------------------------------------\n");
gotoxy(5,13);
printf("任意键开始游戏!按W.A.S.D控制方向");
_getch();
Initsnake();
Initfood();
gotoxy(5,13);
printf("                                ");
}
void keybordhit()//监控键盘
{
char ch;
if(_kbhit())
{
ch=getch();
switch(ch)
{
case 'W':
case 'w':if(snake->dir==DOWN)//如果本来方向是下,而按相反方向无效
{
 break;
}
else
snake->dir=UP;break;
case 'A':
case 'a':if(snake->dir==RIGHT)//如果本来方向是右,而按相反方向无效
{
 break;
}
else
snake->dir=LEFT;break;
case 'S':
case 's':if(snake->dir==UP)//如果本来方向是上,而按相反方向无效
{
 break;
}
else
snake->dir=DOWN;break;
case 'D':
case 'd':if(snake->dir==LEFT)//如果本来方向是左,而按相反方向无效
{
 break;
}
else
snake->dir=RIGHT;break;
case 'O':
case 'o':
if(SPEECH>=150)//速度加快
{
SPEECH=SPEECH-50;
}
break;
case 'P':
case 'p':
if(SPEECH<=400)//速度减慢
{
SPEECH=SPEECH+50;
}
break;
case ' '://暂停
gotoxy(15,18);
printf("游戏已暂停,按任意键恢复游戏");
system("pause>nul");
gotoxy(15,18);
printf("                           ");
break;
default:break;
}
}
}
int main(void)//程序入口
{
Homepage();
while(!STOP)
{
keybordhit();//监控键盘按键
move();//蛇的坐标变化
draw();//蛇的重绘
Sleep(SPEECH);//暂时挂起线程
}
return 0;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

#include<iostream>
#include<windows.h>
#include<time.h>
#include<conio.h>
using namespace std;
// 刷新当前屏幕
inline void Refresh(char q[][22], int grade, int gamespeed){
    system("cls");     //  清屏
 int i,j;
 cout << endl;
 for(i=0;i<22;i++){
     cout << "\t";
  for(j=0;j<22;j++)
   cout<<q[i][j]<<' ';    //  输出贪吃蛇棋盘
        if(i==0) cout << "\t等级为:" << grade;
        if(i==4) cout << "\t自动前进时间";
        if(i==6) cout << "\t间隔为:" << gamespeed << "ms";
  cout<<endl;
 }
}
int main(){
    char tcsQipan[22][22];     //  贪吃蛇棋盘是一个二维数组(如22*22,包括墙壁)
    int i,j;
    for(i=1;i<=20;i++)
        for(j=1;j<=20;j++)
            tcsQipan[i][j]=' ';     //     初始化贪吃蛇棋盘中间空白部分
    for(i=0;i<=21;i++)
        tcsQipan[0][i] = tcsQipan[21][i] = '-';      //初始化贪吃蛇棋盘上下墙壁
    for(i=1;i<=20;i++)
        tcsQipan[i][0] = tcsQipan[i][21] = '|';      //初始化贪吃蛇棋盘左右墙壁
    int tcsZuobiao[2][100];     //蛇的坐标数组
    for(i=0; i<4; i++){
        tcsZuobiao[0][i] = 1;
        tcsZuobiao[1][i] = i + 1;
    }
    int head = 3,tail = 0;
    for(i=1;i<=3;i++)
        tcsQipan[1][i]='*';    //蛇身
    tcsQipan[1][4]='#';       //蛇头
    int x1, y1;           // 随机出米
    srand(time(0));
    do{
  x1=rand()%20+1;
  y1=rand()%20+1;
 }while(tcsQipan[x1][y1]!=' ');
 tcsQipan[x1][y1]='*';
 cout<<"\n\n\t\t贪吃蛇游戏即将开始 !"<<endl;//准备开始;;
 long start;
    int grade = 1, length = 4;
    int gamespeed = 500;  //前进时间间隔
 for(i=3;i>=0;i--){
  start=clock();
  while(clock()-start<=1000);
  system("cls");
  if(i>0)
   cout << "\n\n\t\t进入倒计时:" << i << endl;
  else
   Refresh(tcsQipan,grade,gamespeed);
 }
    int timeover;
    char direction = 77;  // 初始情况下,向右运动
    int x,y;
    while(1){
        timeover = 1;
        start = clock();
        while((timeover=(clock()-start<=gamespeed))&&!kbhit());
             //如果有键按下或时间超过自动前进时间间隔则终止循环
        if(timeover){
            getch();direction = getch();
        }
        switch(direction){
        case 72: x= tcsZuobiao[0][head]-1; y= tcsZuobiao[1][head];break;     // 向上
        case 80: x= tcsZuobiao[0][head]+1; y= tcsZuobiao[1][head];break;      // 向下
        case 75: x= tcsZuobiao[0][head]; y= tcsZuobiao[1][head]-1;break;      // 向左
        case 77: x= tcsZuobiao[0][head]; y= tcsZuobiao[1][head]+1;           // 向右
        }
        if(!(direction==72||direction==80||direction==75 ||direction==77)){   //  按键非方向键
            cout << "\tGame over!" << endl;return 0;
        }
        if(x==0 || x==21 ||y==0 || y==21){   // 碰到墙壁
            cout << "\tGame over!" << endl;return 0;
        }
        if(tcsQipan[x][y]!=' '&&!(x==x1&&y==y1)){ //   蛇头碰到蛇身
            cout << "\tGame over!" << endl;return 0;
        }
        if(x==x1 && y==y1){      //  吃米,长度加1
            length ++;
            if(length>=8){
                length -= 8;
                grade ++;
                if(gamespeed>=200)
                    gamespeed = 550 - grade * 50; // 改变自动前进时间间隔
            }
            tcsQipan[x][y]= '#';
            tcsQipan[tcsZuobiao[0][head]][tcsZuobiao[1][head]] = '*';
            head = (head+1)%100;
            tcsZuobiao[0][head] = x;
            tcsZuobiao[1][head] = y;
            do
            {
                x1=rand()%20+1;
                y1=rand()%20+1;
            }while(tcsQipan[x1][y1]!=' ');
            tcsQipan[x1][y1]='*';
            Refresh(tcsQipan,grade,gamespeed);
        }
 
        else{       //  不吃米
            tcsQipan [tcsZuobiao[0][tail]][tcsZuobiao[1][tail]]=' ';
            tail=(tail+1)%100;
            tcsQipan [tcsZuobiao[0][head]][tcsZuobiao[1][head]]='*';
            head=(head+1)%100;
            tcsZuobiao[0][head]=x;
            tcsZuobiao[1][head]=y;
            tcsQipan[tcsZuobiao[0][head]][tcsZuobiao[1][head]]='#';
            Refresh(tcsQipan,grade,gamespeed);
        }
    }
    return 0;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

#include<iostream>
#include<windows.h>
#include<time.h>
#include<stdlib.h>
#include<conio.h>
#define N 21
void gotoxy(int x,int y)//位置函数
{
COORD pos;
pos.X=2*x;
pos.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);
}
void color(int a)//颜色函数
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);
}
void init(int apple[2])//初始化函数(初始化围墙、显示信息、苹果)
{
int i,j;//初始化围墙
int wall[N+2][N+2]={{0}};
for(i=1;i<=N;i++)
{
for(j=1;j<=N;j++)
wall[i][j]=1;
}
color(11);
for(i=0;i<N+2;i++)
{
for(j=0;j<N+2;j++)
{
if(wall[i][j])
cout<<"■";
else cout<<"□" ;
}
cout<<endl;
}
gotoxy(N+3,1);//显示信息
color(20);
cout<<"按 W S A D 移动方向"<<endl;
gotoxy(N+3,2);
color(20);
cout<<"按任意键暂停"<<endl;
gotoxy(N+3,3);
color(20);
cout<<"得分:"<<endl;
apple[0]=rand()%N+1;//苹果
apple[1]=rand()%N+1;
gotoxy(apple[0],apple[1]);
color(12);
cout<<"●"<<endl;
}
int main()
{
int i,j;
int** snake=NULL;
int apple[2];
int score=0;
int tail[2];
int len=3;
char ch='p';
srand((unsigned)time(NULL));
init(apple);
snake=(int**)realloc(snake,sizeof(int*)*len);
for(i=0;i<len;i++)
snake[i]=(int*)malloc(sizeof(int)*2);
for(i=0;i<len;i++)
{
snake[i][0]=N/2;
snake[i][1]=N/2+i;
gotoxy(snake[i][0],snake[i][1]);
color(14);
cout<<"★"<<endl;
}
while(1)//进入消息循环
{
tail[0]=snake[len-1][0];
tail[1]=snake[len-1][1];
gotoxy(tail[0],tail[1]);
color(11);
cout<<"■"<<endl;
for(i=len-1;i>0;i--)
{
snake[i][0]=snake[i-1][0];
snake[i][1]=snake[i-1][1];
gotoxy(snake[i][0],snake[i][1]);
color(14);
cout<<"★"<<endl;
}
if(kbhit())
{
gotoxy(0,N+2);
ch=getche();
}
switch(ch)
{
case 'w':snake[0][1]--;break;
case 's':snake[0][1]++;break;
case 'a':snake[0][0]--;break;
case 'd':snake[0][0]++;break;
default: break;
}
gotoxy(snake[0][0],snake[0][1]);
color(14);
cout<<"★"<<endl;
Sleep(abs(200-0.5*score));
if(snake[0][0]==apple[0]&&snake[0][1]==apple[1])//吃掉苹果后蛇分数加1,蛇长加1
{
score++;
len++;
snake=(int**)realloc(snake,sizeof(int*)*len);
snake[len-1]=(int*)malloc(sizeof(int)*2);
apple[0]=rand()%N+1;
apple[1]=rand()%N+1;
gotoxy(apple[0],apple[1]);
color(12);
cout<<"●"<<endl;
gotoxy(N+5,3);
color(20);
cout<<score<<endl;
}
if(snake[0][1]==0||snake[0][1]==N||snake[0][0]==0||snake[0][0]==N)//撞到围墙后失败
{
gotoxy(N/2,N/2);
color(30);
cout<<"失败!!!"<<endl;
for(i=0;i<len;i++)
free(snake[i]);
Sleep(INFINITE);
exit(0);
}
}
return 0;
}

 

 

 

 

 

 

给你了那么多,采纳一下吧

 

 

0
傅文彬
傅文彬
新手天翼
新手天翼

#include<iostream>
#include<windows.h>
#include<time.h>
#include<conio.h>
using namespace std;
inline void Refresh(char q[][22], int grade, int gamespeed){
    system("cls");     
 int i,j;
 cout << endl;
 for(i=0;i<22;i++){
     cout << "\t";
  for(j=0;j<22;j++)
   cout<<q[i][j]<<' ';    //  输出贪吃蛇棋盘
        if(i==0) cout << "\t等级为:" << grade;
        if(i==4) cout << "\t自动前进时间";
        if(i==6) cout << "\t间隔为:" << gamespeed << "ms";
  cout<<endl;
 }
}
int main(){
    char tcsQipan[22][22];     //  贪吃蛇棋盘是一个二维数组(如22*22,包括墙壁)
    int i,j;
    for(i=1;i<=20;i++)
        for(j=1;j<=20;j++)
            tcsQipan[i][j]=' ';     //     初始化贪吃蛇棋盘中间空白部分
    for(i=0;i<=21;i++)
        tcsQipan[0][i] = tcsQipan[21][i] = '-';      //初始化贪吃蛇棋盘上下墙壁
    for(i=1;i<=20;i++)
        tcsQipan[i][0] = tcsQipan[i][21] = '|';      //初始化贪吃蛇棋盘左右墙壁
    int tcsZuobiao[2][100];     //蛇的坐标数组
    for(i=0; i<4; i++){
        tcsZuobiao[0][i] = 1;
        tcsZuobiao[1][i] = i + 1;
    }
    int head = 3,tail = 0;
    for(i=1;i<=3;i++)
        tcsQipan[1][i]='*';    //蛇身
    tcsQipan[1][4]='#';       //蛇头
    int x1, y1;           // 随机出米
    srand(time(0));
    do{
  x1=rand()%20+1;
  y1=rand()%20+1;
 }while(tcsQipan[x1][y1]!=' ');
 tcsQipan[x1][y1]='*';
 cout<<"\n\n\t\t贪吃蛇游戏即将开始 !"<<endl;//准备开始;;
 long start;
    int grade = 1, length = 4;
    int gamespeed = 500;  //前进时间间隔
 for(i=3;i>=0;i--){
  start=clock();
  while(clock()-start<=1000);
  system("cls");
  if(i>0)
   cout << "\n\n\t\t进入倒计时:" << i << endl;
  else
   Refresh(tcsQipan,grade,gamespeed);
 }
    int timeover;
    char direction = 77;  // 初始情况下,向右运动
    int x,y;
    while(1){
        timeover = 1;
        start = clock();
        while((timeover=(clock()-start<=gamespeed))&&!kbhit());
             //如果有键按下或时间超过自动前进时间间隔则终止循环
        if(timeover){
            getch();direction = getch();
        }
        switch(direction){
        case 72: x= tcsZuobiao[0][head]-1; y= tcsZuobiao[1][head];break;     // 向上
        case 80: x= tcsZuobiao[0][head]+1; y= tcsZuobiao[1][head];break;      // 向下
        case 75: x= tcsZuobiao[0][head]; y= tcsZuobiao[1][head]-1;break;      // 向左
        case 77: x= tcsZuobiao[0][head]; y= tcsZuobiao[1][head]+1;           // 向右
        }
        if(!(direction==72||direction==80||direction==75 ||direction==77)){   //  按键非方向键
            cout << "\tGame over!" << endl;return 0;
        }
        if(x==0 || x==21 ||y==0 || y==21){   // 碰到墙壁
            cout << "\tGame over!" << endl;return 0;
        }
        if(tcsQipan[x][y]!=' '&&!(x==x1&&y==y1)){ //   蛇头碰到蛇身
            cout << "\tGame over!" << endl;return 0;
        }
        if(x==x1 && y==y1){      //  吃米,长度加1
            length ++;
            if(length>=8){
                length -= 8;
                grade ++;
                if(gamespeed>=200)
                    gamespeed = 550 - grade * 50; // 改变自动前进时间间隔
            }
            tcsQipan[x][y]= '#';
            tcsQipan[tcsZuobiao[0][head]][tcsZuobiao[1][head]] = '*';
            head = (head+1)%100;
            tcsZuobiao[0][head] = x;
            tcsZuobiao[1][head] = y;
            do
            {
                x1=rand()%20+1;
                y1=rand()%20+1;
            }while(tcsQipan[x1][y1]!=' ');
            tcsQipan[x1][y1]='*';
            Refresh(tcsQipan,grade,gamespeed);
        }
 
        else{       //  不吃米
            tcsQipan [tcsZuobiao[0][tail]][tcsZuobiao[1][tail]]=' ';
            tail=(tail+1)%100;
            tcsQipan [tcsZuobiao[0][head]][tcsZuobiao[1][head]]='*';
            head=(head+1)%100;
            tcsZuobiao[0][head]=x;
            tcsZuobiao[1][head]=y;
            tcsQipan[tcsZuobiao[0][head]][tcsZuobiao[1][head]]='#';
            Refresh(tcsQipan,grade,gamespeed);
        }
    }
    return 0;
}

0
李素妍
李素妍
新手天翼
新手天翼

                           

我要回答