自制C++ 贪吃蛇

C++入门——实现贪吃蛇游戏 参考 《C和C++游戏趣味编程》 贪吃蛇游戏 键盘控制小蛇上、下、左、右移动,迟到食物后长度加1;蛇头碰到自身或窗口边缘,游戏失败 程序框架 #include <graphics.h> #include <conio.h> #include <stdio.h> // 全局变量定义 void startup() // 初始化函数 { } void show() // 绘 阅读详情



VS2013,把代码复制过去应该可以直接编译运行




#include<windows.h>
#include<conio.h>
#include<time.h>
#include<string>
using namespace std;

/*=============== all the structures ===============*/

typedef struct Frame
{
    COORD position[2];//位置
    int flag;
}Frame;//帧


/*=============== all the functions ===============*/

void SetPos(COORD a)// set cursor 设置光标
{
    HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(out, a);
}

/* set cursor设置光标*/void SetPos(int i, int j)
{
    COORD pos = { i, j };
    SetPos(pos);
}

void HideCursor()
{
    CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };
    SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}

//把第y行,[x1, x2) 之间的坐标填充为 ch
void drawRow(int y, int x1, int x2, char ch)
{
    SetPos(x1, y);
    for (int i = 0; i <= (x2 - x1); i++)
        cout << ch;
}

//在a, b 纵坐标相同的前提下,把坐标 [a, b] 之间填充为 ch
void drawRow(COORD a, COORD b, char ch)
{
    if (a.Y == b.Y)
        drawRow(a.Y, a.X, b.X, ch);
    else
    {
        SetPos(0, 25);
        cout << "error code 01:无法填充行,因为两个坐标的纵坐标(x)不相等";
        system("pause");
    }
}

//把第x列,[y1, y2] 之间的坐标填充为 ch
void drawCol(int x, int y1, int y2, char ch)
{
    int y = y1;
    while (y != y2 + 1)
    {
        SetPos(x, y);
        cout << ch;
        y++;
    }
}

//在a, b 横坐标相同的前提下,把坐标 [a, b] 之间填充为 ch
void drawCol(COORD a, COORD b, char ch)
{
    if (a.X == b.X)
        drawCol(a.X, a.Y, b.Y, ch);
    else
    {
        SetPos(0, 25);
        cout << "error code 02:无法填充列,因为两个坐标的横坐标(y)不相等";
        system("pause");
    }
}

//左上角坐标、右下角坐标、用row填充行、用col填充列
void drawFrame(COORD a, COORD  b, char row, char col)
{
    drawRow(a.Y, a.X + 1, b.X - 1, row);
    drawRow(b.Y, a.X + 1, b.X - 1, row);
    drawCol(a.X, a.Y + 1, b.Y - 1, col);
    drawCol(b.X, a.Y + 1, b.Y - 1, col);
}
//点覆盖
void drawFrame(COORD a, char r)
{
    SetPos(a.X, a.Y);
    cout << r;
}

void drawFrame(int x1, int y1, int x2, int y2, char row, char col)
{
    COORD a = { x1, y1 };
    COORD b = { x2, y2 };
    drawFrame(a, b, row, col);
}

void drawFrame(Frame frame, char row, char col)
{
    COORD a = frame.position[0];
    COORD b = frame.position[1];
    drawFrame(a, b, row, col);
}

void drawPlaying()
{
    drawFrame(0, 0, 48, 24, '=', '|');//    draw map frame;
    drawFrame(49, 0, 77, 24, '-', '|');//        draw output frame
    SetPos(52, 6);
    cout << "玩家1长度:";
    SetPos(52, 8);
    cout << "玩家2长度:";
    SetPos(52, 14);
    cout << "操作方式:";
    SetPos(52, 16);
    cout << " 玩家1 上下左右";
    SetPos(52, 17);
    cout << " 玩家2 a,s,d,w";
    SetPos(52, 19);
    cout << "  p 暂停游戏。";
    SetPos(52, 20);
    cout << "  esc 退出游戏。";
}

//在[a, b)之间产生一个随机整数
int random(int a, int b)
{
    int c = (rand() % (a - b)) + a;
    return c;
}

//在两个坐标包括的矩形框内随机产生一个坐标
COORD random(COORD a, COORD b)
{
    int x = random(a.X, b.X);
    int y = random(a.Y, b.Y);
    COORD c = { x, y };
    return c;
}

//判断是否撞到蛇身或者墙壁 点对点
bool  judgeCoordSnake(COORD spot1, COORD spot2)
{
    if (spot1.X == spot2.X)
        if (spot1.Y == spot2.Y)
            return true;
    if (spot1.X == 0 || spot1.X == 48 || spot1.Y == 0 || spot1.Y == 24)
        return true;
    return false;
}

//判断是否撞到蛇身或者墙壁 头对身子
bool  judgeCoordSnake(COORD spot1, COORD *snake1, COORD *snake2)
{
    for (int i = 1; i < 250; i++)
    {
        if (spot1.X == snake1[i].X)
            if (spot1.Y == snake1[i].Y)
                return false;
        if (spot1.X == snake2[i].X)
            if (spot1.Y == snake2[i].Y)
                return false;
        if (spot1.X == 0 || spot1.X == 48 || spot1.Y == 0 || spot1.Y == 24)
            return false;
    }
    return true;
}
bool  judgeCoordSnakeFood(COORD spot1, COORD spot2, COORD spot3,int& a)
{
    if (spot1.X == spot2.X)
        if (spot1.Y == spot2.Y)
        {
            a = 0;
            return true;
        }
    if (spot1.X == spot3.X)
        if (spot1.Y == spot3.Y)
        {
            a = 1;
            return true;
        }

    return false;
}
//因为在判断时头部的问题所以单列出来



void printCoord(COORD a)
{
    cout << "( " << a.X << " , " << a.Y << " )";
}

int drawMenu()
{
    SetPos(30, 1);
    cout << "贪吃的大蟒蛇";
    drawRow(3, 0, 79, '-');
    drawRow(5, 0, 79, '-');
    SetPos(28, 4);
    cout << "w 和 s 选择, k 确定";
    SetPos(15, 11);
    cout << "开始游戏";
    SetPos(15, 13);
    cout << "结束游戏";
    drawRow(20, 0, 79, '-');
    drawRow(22, 0, 79, '-');
    SetPos(47, 11);
    cout << "本游戏为双人游戏:";
    SetPos(51, 13);
    cout << "wasd和ijkl控制";
    SetPos(24, 21);
    cout << "制作: 威微游戏制造厂厂长  唐宇威";
    int j = 11;
    SetPos(12, j);
    cout <<"->";
    while (1)
    {
        if (_kbhit())
        {
            char x = _getch();
            switch (x)
            {
            case 'w':
            {
                if (j == 13)
                {
                    SetPos(12, j);
                    cout << " ";
                    j = 11;
                    SetPos(12, j);
                    cout << "->";
                    SetPos(51, 13);
                    cout << "            ";
                    SetPos(47, 11);
                    cout << "准备好了吗?";
                    SetPos(51, 13);
                    cout << "wasd和ijkl控制";
                }
                break;
            }
            case 's':
            {
                if (j == 11)
                {
                    SetPos(12, j);
                    cout << " ";
                    j = 13;
                    SetPos(12, j);
                    cout << "->";
                    SetPos(51, 13);
                    cout << "              ";
                    SetPos(47, 11);
                    cout << "结束游戏:";
                    SetPos(51, 13);
                    cout << "要走了吗?";
                }
                break;
            }
            case 'k':
            {
                if (j == 11)    
                    return 1;
                else exit(0);
            }
            }
        }
    }
}

/*
DWORD WINAPI MusicFun(LPVOID lpParamte)
{
//DWORD OBJ;
sndPlaySound(TEXT("bgm.wav"), SND_FILENAME|SND_ASYNC);
return 0;
}
*/


/*================== the Game Class ==================*/

class Game
{
public:
    COORD snake1[250];
    COORD snake2[250];
    COORD food[2];
    int length1;
    int length2;
    int direction1;//蛇1的头 1上2下3左4右
    int direction2;//蛇2的头 1上2下3左4右
    string title;
    //初始化所有
    void initFood();
    COORD randomFood();
    //初始化其中一个
    //void initThisBullet( COORD );
    //void initThisEnemy( Frame );
    void Playing();
    void Pause();
    void judgeSnake();
    void GameOver();
    void snake1ChangeDirection(char x);
    void snake2ChangeDirection(char x);
    void drawSnake1(int direction);
    void drawSnake2(int direction);
    void drawSnake1ToNull();
    void drawSnake2ToNull();
    void drawFood();
    void drawFoodToNull();
    Game()
    {
        direction1 = 1,direction2 = 1;
        snake1[0] = { 8, 15 }, snake1[1] = { 8, 16 }, snake1[2] = { 8, 17 };
        snake2[0] = { 40, 15 }, snake2[1] = { 40, 16 }, snake2[2] = { 40, 17 };
        length1 = 3, length2 = 3;
        for (int i = 3; i < 249; i++)
        {
            snake1[i] = { 0, 0 };
            snake2[i] = { 0, 0 };
        }
    }

};

//画第一条蛇
void Game::drawSnake1(int direction)
{
    for (int i = 0; i<240; i++)
    {
        SetPos(snake1[i]);
        if (i != 0)
            cout << "O";
        else if (i == 0)
        {
            if (direction==1)
            {
                cout << "^";
            }
            else if(direction == 2)
            {
                cout << "v";
            }
            else if (direction == 3)
            {
                cout << "<";
            }
            else if (direction == 4)
            {
                cout << ">";
            }

        }

    }
}
void Game::drawSnake2(int direction)
{
    for (int i = 0; i<240; i++)
    {
        SetPos(snake2[i]);
        if (i != 0)
            cout << "X";
        else if (i == 0)
        {
            if (direction == 1)
            {
                cout << "^";
            }
            else if (direction == 2)
            {
                cout << "v";
            }
            else if (direction == 3)
            {
                cout << "<";
            }
            else if (direction == 4)
            {
                cout << ">";
            }

        }

    }
}
//把第一条蛇消失,行动时使用,只让蛇头蛇尾消失,这样不会一闪一闪
void Game::drawSnake1ToNull()
{
    SetPos(snake1[0]);
    cout << " ";
    SetPos(snake1[length1]);
    cout << " ";    
}
void Game::drawSnake2ToNull()
{
    /*for (int i = length2; i<240; i++)
    {
        SetPos(snake2[i]);
        cout << " ";
    }*/
    SetPos(snake2[0]);
    cout << " ";
    SetPos(snake2[length2]);
    cout << " ";
}
//初始食物
void Game::initFood()
{
    COORD a = { 2, 2  };
    COORD b = { 24,12 };
    COORD c = { 25, 2 };
    COORD d = { 47,14 };
    food[0] = random(a, b);
    food[1] = random(c, d);
}
//随机食物,如果有墙需要修改。
COORD Game::randomFood()
{
    COORD food;
    COORD a = { 2, 2 };
    COORD b = { 47, 23 };
    while (1)
    {
        food = random(a, b);
        if (judgeCoordSnake(food, snake1, snake2))
            return food;
    }
}
//画出食物
void Game::drawFood()
{
    for (int i = 0; i<2; i++)
        drawFrame(food[i], '@');
}
//判断蛇是否吃到东西

/*不用这个也行,蛇吃过了就没了*/void Game::drawFoodToNull()
{
    for (int i = 0; i<2; i++)
    {
        drawFrame(food[i], ' ');
    }
}
//暂停游戏
void Game::Pause()
{
    SetPos(61, 2);
    cout << "               ";
    SetPos(61, 2);
    cout << "暂停中...";
    char c = _getch();
    while (c != 'p')
        c = _getch();
    SetPos(61, 2);
    cout << "         ";
}

void Game::snake1ChangeDirection(char x)
{

        if (x == 'w')//是上箭头;
        {
            if (direction1!=2)
            direction1 = 1;
        }
        else if (x == 's') //是 下箭头;
        {
            if (direction1 != 1)
            direction1 = 2;
        }
        else if (x == 'a')  //是 左箭头;
        {
            if (direction1 != 4)
            direction1 = 3;
        }
        else if (x == 'd') // 是 右箭头;
        {
            if (direction1 != 3)
            direction1 = 4;
        }

}
void Game::snake2ChangeDirection(char x)
{

    if (x == 'i')//是上箭头;
    {
        if (direction2 != 2)
            direction2 = 1;
    }
    else if (x == 'k') //是 下箭头;
    {
        if (direction2 != 1)
            direction2 = 2;
    }
    else if (x == 'j')  //是 左箭头;
    {
        if (direction2 != 4)
            direction2 = 3;
    }
    else if (x == 'l') // 是 右箭头;
    {
        if (direction2 != 3)
            direction2 = 4;
    }

}

void Game::judgeSnake()
{
    for (int i = 0; i < 250; i++)
    {
        if (judgeCoordSnake(snake1[0], snake1, snake2) == false )
        {
            for (int i = 1; i < 500; i++)
            {
                Sleep(2);
                SetPos(random(1,79), random(1,24));
                cout << "玩家一输了";
            }
            Sleep(1000);
            GameOver();
            break;
        }
        if (judgeCoordSnake(snake2[0], snake1, snake2) == false)
        {
            for (int i = 1; i < 500; i++)
            {
                Sleep(2);
                SetPos(random(1, 79), random(1, 24));
                cout << "玩家二输了";
            }
            Sleep(1000);
            GameOver();
            break;
        }
    }



}


void Game::Playing()
{
    //HANDLE MFUN;
    //MFUN= CreateThread(NULL, 0, MusicFun, NULL, 0, NULL); 

    drawSnake1(direction1);
    drawSnake2(direction2);
    initFood();
    drawFood();
    int numfood;

    while (1)
    {
        Sleep(10);
        SetPos(52, 7);
        cout << length1;
        SetPos(52, 9);
        cout << length2;
        drawSnake1ToNull();
        drawSnake2ToNull();
        if (_kbhit())
        {
            char x = _getch();
            if ('a' == x || 's' == x || 'd' == x || 'w' == x)
            {
                snake1ChangeDirection(x);    
            }
            else if ('p' == x)
                Pause();
            else if ('j' == x || 'k' == x || 'l' == x || 'i' == x)
            {
                snake2ChangeDirection(x);
            }
            else if (27 == x)
            {
                //CloseHandle(MFUN);
                GameOver();
                break;
            }
        }
        if(judgeCoordSnakeFood(snake1[0], food[0], food[1],numfood)==true)
        {

            if (direction1 == 1)
            {
                for (int i = length1; i > 0; i--)
                    snake1[i+1] = snake1[i];
                snake1[0].Y--;
                length1++;
            }
            if (direction1 == 2)
            {
                for (int i = length1; i >= 0; i--)
                    snake1[i+1] = snake1[i];
                snake1[0].Y++;
                length1++;
            }
            if (direction1 == 3)
            {
                for (int i = length1; i >= 0; i--)
                    snake1[i+1] = snake1[i];
                snake1[0].X--;
                length1++;
            }
            if (direction1 == 4)
            {
                for (int i = length1; i >= 0; i--)
                    snake1[i+1] = snake1[i];
                snake1[0].X++;
                length1++;
            }
            food[numfood] = randomFood();
            drawFood();
        }
        else
        {
            if (direction1 == 1)
            {
                for (int i = length1; i > 0; i--)
                    snake1[i] = snake1[i - 1];
                snake1[0].Y--;
            }
            if (direction1 == 2)
            {
                for (int i = length1; i > 0; i--)
                    snake1[i] = snake1[i - 1];
                snake1[0].Y++;
            }
            if (direction1 == 3)
            {
                for (int i = length1; i > 0; i--)
                    snake1[i] = snake1[i - 1];
                snake1[0].X--;
            }
            if (direction1 == 4)
            {
                for (int i = length1; i > 0; i--)
                    snake1[i] = snake1[i - 1];
                snake1[0].X++;
            }
            judgeSnake();
        }
        if (judgeCoordSnakeFood(snake2[0], food[0], food[1], numfood) == true)
        {

            if (direction2 == 1)
            {
                for (int i = length2; i > 0; i--)
                    snake2[i + 1] = snake2[i];
                snake2[0].Y--;
                length2++;
            }
            if (direction2 == 2)
            {
                for (int i = length2; i >= 0; i--)
                    snake2[i + 1] = snake2[i];
                snake2[0].Y++;
                length2++;
            }
            if (direction2 == 3)
            {
                for (int i = length2; i >= 0; i--)
                    snake2[i + 1] = snake2[i];
                snake2[0].X--;
                length2++;
            }
            if (direction2 == 4)
            {
                for (int i = length2; i >= 0; i--)
                    snake2[i + 1] = snake2[i];
                snake2[0].X++;
                length2++;
            }
            food[numfood] = randomFood();
            drawFood();
        }
        else
        {
            if (direction2 == 1)
            {
                for (int i = length2; i > 0; i--)
                    snake2[i] = snake2[i - 1];
                snake2[0].Y--;
            }
            if (direction2 == 2)
            {
                for (int i = length2; i > 0; i--)
                    snake2[i] = snake2[i - 1];
                snake2[0].Y++;
            }
            if (direction2 == 3)
            {
                for (int i = length2; i > 0; i--)
                    snake2[i] = snake2[i - 1];
                snake2[0].X--;
            }
            if (direction2 == 4)
            {
                for (int i = length2; i > 0; i--)
                    snake2[i] = snake2[i - 1];
                snake2[0].X++;
            }
            judgeSnake();
        }
        drawSnake1(direction1);
        drawSnake2(direction2);

    }
}

void Game::GameOver()
{
    system("cls");
    COORD p1 = { 28, 9 };
    COORD p2 = { 53, 15 };
    drawFrame(p1, p2, '=', '|');
    SetPos(36, 12);
    string str = "Game Over!";
    for (int i = 0; i<str.size(); i++)
    {
        Sleep(80);
        cout << str[i];
    }
    Sleep(1000);
    system("cls");
    drawFrame(p1, p2, '=', '|');
    SetPos(31, 11);
    cout << "玩家一长度:" ;
    SetPos(31, 12);
    cout << length1;
    SetPos(31, 13);
    cout << "玩家二长度:";
    SetPos(31, 14);
    cout << length2;
    SetPos(30, 16);
    Sleep(1000);
    cout << "继续? 是(y)| 否(n)";
as:
    char x = _getch();
    if (x == 'n')
        exit(0);
    else if (x == 'y')
    {
        system("cls");
        Game game;
        int a = drawMenu();    
        system("cls");
        drawPlaying();
        game.Playing();
    }
    else goto as;
}

/*================== the main function ==================*/
int main()
{
    //游戏准备
    srand((int)time(0));    //随机种子
    HideCursor();    //隐藏光标

    Game game;
    int a = drawMenu();
    system("cls");
    drawPlaying();
    game.Playing();
}
学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入学习交流群
639368839,我们一起学C/C++!


C/C++游戏项目详细教程:《贪吃蛇》 还记我们童年时的贪吃蛇吗,用“砖头”诺基亚玩的更是经典中的经典,贪食蛇操作简单,可玩性比较高。这个游戏难度最大的不是蛇长得很长的时候,而是开始。那个时候蛇身很短,看上去难度不大,却最容易死掉,因为把玩一条小短蛇让人容易走神,失去耐心。由于难度小,你会不知不觉加快调整方向的速度,在游走自如的时候蛇身逐渐加长了,而玩家却没有意识到危险,在最得意洋洋的一刻突然死亡。 1976年,Gremlin平台推出了一款经典街机游戏Blockade。游戏中,两名玩家分别控制一个角色在屏幕上移动,所经之... 阅读详情

相关推荐

写了一个DEV-c++的小游戏:贪吃蛇

【代码】写了一个DEV-c++的小游戏:贪吃蛇。

Yj110923的博客 1137

用C++实现经典的贪吃蛇游戏

六一儿童节到了,无论是大朋友还是小朋友,相信大家心里都藏有一颗向往浪漫的童真的心。贪吃蛇是一款经典的单机小游戏,大家在小时候应该都接触过。今天,我将用C++来复刻这款游戏,并祝福所有大朋友小朋友六一儿童节快乐,永远童心未泯。我们需要定义游戏整个场景的大小,蛇的朝向所代表的数值,蛇的速度,蛇的每一个结点大小,食物的大小。//定义场景大小//定义食物以及蛇的大小//定义蛇的朝向//蛇的速度(用在睡眠函数里面)如果您觉得本篇文章不错的话,不如将它分享出去吧!让更多的人感受这份童真快乐。

记录了个人在学习生活中的所思所想,在反思自己的同时希望也能够帮到你 1万+

贪吃蛇(一)--用C++编写一个简单的贪吃蛇

#include<iostream> #include<windows.h> #include<conio.h> #include<time.h> using namespace std; #define random(a,b) (rand()%(b-a+1)+a) const int N=1e3+100;//蛇的最大长度 int X[N],Y[N];//记录蛇的每个节点的坐标 int Snake_length;//蛇的当前长度 int X1=1,Y1=1;

weixin_43918046的博客 1万+

贪吃蛇小游戏(C++)

贪吃蛇小游戏(C++)

好好学习,天天向上 6749

C++贪吃蛇

C++贪吃蛇基本概念前言采用的平台贪吃蛇移动食物的产生判断游戏结束吃到食物代码实现效果后记 基本概念 前言 最近疫情比较严重没有带书回家,所以就突发奇想来实现之前一直想做的一个游戏,或许这个游戏比较粗糙但是也是自己进步的一小步。希望能够对大家有帮助。 采用的平台 windows+visual studio+C++ 贪吃蛇移动 贪吃蛇使用链表实现, 每一次移动,蛇尾摘下来,接到蛇头方向。 rear...

或许没有的博客 2789

利用C++写一个简单的贪吃蛇小游戏

首先,非常感谢白家名大佬参考提供的思路与方法,非常感谢!     首先写一个给光标定位的函数 void gotoxy(int x, int y) //光标定位 { COORD pos = { x,y }; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos); } 这个函数需要用win...

qq_40694605的博客 6792

C/C++实现贪吃蛇游戏

文章目录前言一、游戏效果展示二、具体项目实现1.游戏欢迎界面 welcome( )2.游戏背景 initGameScreen( )3.方块表示 int block[ ][ ][ ]总结 前言 俄罗斯方块(Tetris, 俄文:Тетрис)是一款电视游戏机和掌上游戏机游戏,它由俄罗斯人阿列克谢·帕基特诺夫发明,故得此名。俄罗斯方块的基本规则是移动、旋转和摆放游戏自动输出的各种方块,使之排列成完整的一行或多行并且消除得分。由于上手简单、老少皆宜,从而家喻户晓,风靡世界。 一、游戏效果展示 二、具体项目实现

Brenda_Bestow的博客 2万+

c++贪吃蛇游戏 DEV

c++贪吃蛇 DEV DEV-C++ #include <iostream> #include <list> #include <cstdio> #include <string> #include <vector> #include <ctime> #include <algorithm> #include &l...

ivan_lai2020的博客 1553

c++实现贪吃蛇

1.绘制地图

qq_17769213的博客 2万+

SSE消息推送避坑指南:从Chrome兼容性到Spring超时配置

本文深入探讨了在Java Spring Boot项目中实现SSE消息推送时,从浏览器兼容性到后端配置的完整避坑指南。针对Chrome并发连接限制、Safari自动断开、Nginx代理缓冲以及Spring SseEmitter内存泄漏与超时管理等生产环境常见问题,提供了具体的解决方案和最佳实践配置,帮助开发者构建稳定可靠的实时推送系统。

work3的博客 452

从零到一:TI AWR1843 Boost EVM与DCA1000 EVM的ADC数据采集实战指南

本文详细介绍了TI AWR1843 Boost EVM与DCA1000 EVM的ADC数据采集实战指南,涵盖硬件连接、软件配置、固件烧录、雷达参数设置及数据处理等关键步骤。通过MATLAB等工具,开发者可高效实现毫米波雷达数据采集,适用于自动驾驶、工业检测等领域。

weixin_29001327的博客 975

自制C++控制台小游戏—贪吃蛇

个人练习程序,使用Windows.h库简单制作了一个传统的贪吃蛇游戏。直接复制到Dev-C++中,就可以运行了。

jundage7788的博客 518

Mac用户必看:Parallels Desktop 18.1.1最新破解版安装与优化全攻略(附资源)

本文为Mac用户提供Parallels Desktop 18.1.1的详细安装与优化指南,涵盖虚拟化技术选型、专业级配置流程及性能调优技巧。重点解析Parallels Desktop在图形加速、系统资源调度方面的核心优势,并分享生产力增强技巧与典型应用场景实战方案,帮助用户最大化利用这一高效虚拟化工具。

weixin_29240343的博客 852

经典游戏---贪吃蛇从C++代码实现

小时候都玩过贪吃蛇这个经典的小游戏,在我们的普通手机里似乎都是必备的。它伴随着我们的童年,经历了好多好多时光。它带给我们了许多的乐趣。 学习了c++这门编程语言后,我就想着能不能把它做出来,在我查看了相关知识后,明白了其中的道理,就尝试着自己写出这个小游戏来,而且加入了许多可玩性的东西,包括等级选择,暂停/继续和分数制。整个程序采用了类和数组的相关知识实现。 //=====================================

Shawn Hou 18万+

补洞与fairing算法

对网格进行补洞,remesh, 平滑,fairing, 最小二乘优化平滑

闪电彬彬的博客 1055

2023东华大学OJ机试题22-70

东华大学计算机考研复试机试22 约瑟夫环223、整除的尾数24、回文质数25、汽水瓶26、阶乘最后的非0位27、算菜价28、 水果价格29、求奇数的乘积30、求最晚和最早日期31、素数32、计算e33 数字之和34 繁殖问题35 奇妙的数字36 整除的尾数37 黑色星期五38 树39 约瑟夫环40 最大与最小41 环42 求数列项43 最高频率44 三艘船45 回文数46 特殊四位数47 最大值48 数列149 修理牛棚50 按要求输出序列51 部落人乘法52 序列53 双重回文数54 等差数列55 人见人

m0_49263811的博客 2602

Coder.@的奇幻冒险(贪吃蛇—_—)

上一周博主痴迷于贪吃蛇游戏的制作。 虽说这是一项软导作业,而且只让简单写出操作思想就好 但博主死性不改非要做到最好。 简单地从网上大神的作品中学习到了轮廓,然后自己动手打了一遍码,学到了不少代码黑科技,可惜用C/C++要想实现kbhit()函数(无等待键盘输入)只找到了windows的解决方案,并没有找到mac OS X系统下的类似函数。 传统贪吃蛇的原理是通过系统刷屏system(”c

weixin_40346642的博客 537

别再乱点U盘里的.exe了!手把手教你清除‘Usb Disk.exe’病毒并恢复隐藏文件

本文详细介绍了如何识别和清除U盘病毒(如Usb Disk.exe),并提供从终止病毒进程到恢复隐藏文件的完整步骤。通过禁用自动播放、清理注册表和使用命令行工具,帮助用户彻底清除病毒并预防未来感染,确保数据安全。

weixin_42530732的博客 620

贪吃蛇,自己编

贪吃蛇,自己编 待改进:while()存在盲等、没有图形界面。 #include #include #include #include //Console Input/Output 头文件,不是标准C++文件 #include using namespace std; const int border_size=21; char game_map[22][22];

yichudu 1286

【unity游戏开发入门到精通——通用篇】Post Processing 后处理插件Post-process Volume 和 Volume最全基础使用说明

之前我已经实现了不少后处理功能,本文其实就是将他们归类整理,以便更好的查找和理解。在Unity中,后处理(Post-Processing)是在相机所捕捉的图像上应用一些特殊效果的过程,后处理会让图像视觉效果更好(前提是做的好)。这些效果的范围有非常细微的颜色调整,也包括整体的美术风格的大修,可以让场景看起来更加真实或风格化,或者只是变得更好看。就像我们都会用手机拍照,但很多时候我们拍的原始的相片都打不到我们想要的效果。比如照片可能亮度不够,颜色不饱和或者对比度不好等。

向宇的博客,专注php/web全栈 unity游戏开发,欢迎大家评论纠错 7911

9篇2章2节:GBD 数据库的数据申请详解

无论您是初入公共卫生领域的学生、资深的科研工作者,还是政策决策者,GBD数据库都将成为您数据分析与决策支持中不可或缺的重要工具。

MD Code 2625

贪吃蛇(c++)

好久没发博客了 今天来发一个吧 (是个以前的) 我家在徐州睢宁在家憋疯了 好了,这是一个贪吃蛇的 可以选择难度的 好了,不说废话了 可以上代码了: #include <bits/stdc++.h> #include <windows.h> #include <stdlib.h> #include <conio.h> #include <time.h> #include <cstring> #include <c

kangweichen的博客 474

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

C++小游戏综合(GCC环境,转载)

本篇是一些C++小游戏,在GCC环境下的哦。

jinboxin_的博客 688

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

用C++语言实现贪吃蛇游戏

写在前面 用C++语言写游戏再适合不过了,当然不是因为用它写起来简单,(相反那并不简单),但是其性能绝对是其他语言没法比的。所以这里我会用C++实现一个贪吃蛇的游戏。当然我可能有意隐瞒了你,因为我们不仅仅是用C++纯语言来干这件事,那会很别扭,因为我们需要图像渲染、声音、甚至是碰撞检测(我最喜欢的一个版块)!所以仅仅用语言是不够的。 (注:在文章最后我会给出两个版本的贪吃蛇源码及涉及到的一些资源

razorEdge的博客 1万+

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

基于c++的贪吃蛇

这是利用c++编写的贪吃蛇小游戏,期中涉及了蛇的移动、食物的生成以及碰撞检测等功能。通过对键盘输入的处理,蛇的移动方向可以被改变,而生成食物时需要避免与蛇身重叠。同时,通过检测蛇头与食物或蛇身的碰撞,游戏可以判断是否吃到食物或者游戏是否结束。这些功能共同构成了贪吃蛇游戏的基本逻辑,展示了如何利用简单的数据结构和流程控制来实现一个小型游戏。

2401_85260543的博客 949
上一篇: C语言学习基本字符集
下一篇: Python爬虫天气预报(小白入门)
敲代码的猴
博客等级 码龄10年 126粉丝 61原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址