C和C++游戏趣味编程(二)Easyx图形库入门与贪吃蛇

一、用二维数组记录地图蛇身位置为1~n,其他位置为0。

二、初始化蛇身和地图,显示随机的食物。

三、循环显示地图,更新蛇位置、长度和食物位置。

四、效果展示在这里插入图片描述

五、遇到的问题。outtextxy()输出字符串需要Unicode编码的字符串。

TCHAR len[5];
swprintf_s(len, _T("%d"), snakeSize);//visual stdio 2019 提示用这个函数,不能用stprintf()
outtextxy(x, y, len);

六、用到Easyx库的函数

1、创建与关闭
initgraph()
closegraph()
cleardevice()
2、设置颜色画方框
setlinecolor()
setfillcolor()
fillrectangle()
3、输出字体
settextcolor()
settextstyle()
outtextxy()
4、批量绘制
BeginBatchDraw()
FlushBatchDraw()

#include <graphics.h>
#include <conio.h>
#include <iostream>
const int HEIGH = 30, WIDTH = 40, BLOCK_SIZE = 20;
int Blocks[HEIGH][WIDTH];//数组用来记录地图信息
char moveDirection = 'a';//移动方向
int food_i = rand() % HEIGH, food_j = rand() % WIDTH;//食物位置
int isFailure = 0;//是否失败
int snakeSize = 5;//蛇身长度

void startup() {//初始化
    srand(time(NULL));
    initgraph(WIDTH * BLOCK_SIZE+10*BLOCK_SIZE, HEIGH * BLOCK_SIZE);
    for (int i = 1; i <= snakeSize; i++) Blocks[15][19 + i] = i;
    setlinecolor(RGB(200, 200, 200));
    BeginBatchDraw();//执行后,任何绘图操作都将暂时不输出到屏幕上,直到执行 FlushBatchDraw 或 EndBatchDraw 才将之前的绘图输出。
}
void show() {//显示地图
    cleardevice();
    for (int j = 0; j < WIDTH; j++) for (int i = 0; i < HEIGH; i++) {//画游戏表格和蛇身
        if (Blocks[i][j]) setfillcolor(HSVtoRGB(Blocks[i][j] * 10, 0.9, 1));
        else setfillcolor(RGB(150, 150, 150));
        fillrectangle(j * BLOCK_SIZE, i * BLOCK_SIZE, (j + 1) * BLOCK_SIZE, (i + 1) * BLOCK_SIZE);
    }
    //画食物
    setfillcolor(RGB(0, 255, 0));
    fillrectangle(food_j * BLOCK_SIZE, food_i * BLOCK_SIZE, (food_j + 1) * BLOCK_SIZE, (food_i + 1) * BLOCK_SIZE);
    //右方显示蛇身长度
    setfillcolor(RGB(150, 150, 150));
    fillrectangle((WIDTH + 1) * BLOCK_SIZE, BLOCK_SIZE, (WIDTH + 9) * BLOCK_SIZE, (HEIGH - 1) * BLOCK_SIZE);
    settextcolor(RGB(0, 255, 0));
    settextstyle(30, 0, _T("宋体"));
    outtextxy((WIDTH + 2) * BLOCK_SIZE, 220, _T("蛇身长度:"));
    TCHAR len[5];//转换格式
    swprintf_s(len, _T("%d"), snakeSize);
    outtextxy((WIDTH + 2) * BLOCK_SIZE, 250, len);//右方显示
    if(isFailure){//判断游戏失败
        setbkcolor(TRANSPARENT);
        settextcolor(RGB(255, 0, 0));
        settextstyle(80, 0, _T("宋体"));
        outtextxy(240, 220, _T("游戏失败!"));
    }
    FlushBatchDraw();
}
void moveSnake() {//移动蛇身
    int oldHead_i, oldHead_j, oldRear_i = 0, oldRear_j = 0;
    for (int i = 0; i < HEIGH; i++) {
        for (int j = 0; j < WIDTH; j++) {
            if (Blocks[i][j]) Blocks[i][j]++;
            if (Blocks[i][j] == 2) { oldHead_i = i; oldHead_j = j; }
            if (Blocks[i][j] > Blocks[oldRear_i][oldRear_j]) { oldRear_i = i; oldRear_j = j; }
        }
    }
    int newHead_i = oldHead_i, newHead_j = oldHead_j;
    if (moveDirection == 'w') newHead_i--;
    else if (moveDirection == 's') newHead_i++;
    else if (moveDirection == 'a') newHead_j--;
    else if (moveDirection == 'd') newHead_j++;
    if (newHead_i < 0 || newHead_i >= HEIGH || newHead_j < 0 || newHead_j >= WIDTH || Blocks[newHead_i][newHead_j]) {
        isFailure = 1;
    }
    else Blocks[newHead_i][newHead_j] = 1;
    if(newHead_i!=food_i || newHead_j!=food_j){
        Blocks[oldRear_i][oldRear_j] = 0;
    }
    else {
        snakeSize++;
        food_i = rand() % HEIGH;
        food_j = rand() % WIDTH;
    }
}
void updateWithoutInput() {//没有输入更新
    if (isFailure) return;
    static int waitIndex = 1;
    waitIndex++;
    if (waitIndex == 30) {
        moveSnake();
        waitIndex = 1;
    }
}
void updateWithInput() {//有输入更新
    if (!isFailure && _kbhit()) {
        char input = _getch();
        if (input == 'a' || input == 'w' || input == 's' || input == 'd') {
            moveDirection = input;
            moveSnake();
        }
    }
}

int main()
{   
    startup();
    while (1) {
        show();
        updateWithoutInput();
        updateWithInput();
    }
    closegraph();
    return 0;
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是一个使用 EasyX 图形库实现的贪吃蛇游戏的示例代码: ```c++ #include <graphics.h> #include <conio.h> #include <time.h> const int WIDTH = 600; // 游戏窗口宽度 const int HEIGHT = 600; // 游戏窗口高度 const int CELL_SIZE = 20; // 每个蛇身格子的大小 const int ROWS = HEIGHT / CELL_SIZE - 1; // 游戏窗口中行数 const int COLS = WIDTH / CELL_SIZE - 1; // 游戏窗口中列数 struct Snake { int x, y; struct Snake *next; }; enum Direction { UP, DOWN, LEFT, RIGHT }; Direction direction = RIGHT; // 蛇的初始方向 Snake *head = NULL; // 蛇头指针 int score = 0; // 得分 void initSnake() { head = new Snake; head->x = 5; head->y = 5; head->next = NULL; } void drawSnake() { setfillcolor(YELLOW); for (Snake *p = head; p; p = p->next) { solidrectangle(p->x * CELL_SIZE, p->y * CELL_SIZE, (p->x + 1) * CELL_SIZE, (p->y + 1) * CELL_SIZE); } } void moveSnake() { int x = head->x, y = head->y; switch (direction) { case UP: y--; break; case DOWN: y++; break; case LEFT: x--; break; case RIGHT: x++; break; } Snake *p = new Snake; p->x = x; p->y = y; p->next = head; head = p; if (x < 0 || x > COLS || y < 0 || y > ROWS) { // 撞墙 closegraph(); printf("Game Over!\n"); exit(0); } for (Snake *p = head->next; p; p = p->next) { // 撞自己 if (p->x == head->x && p->y == head->y) { closegraph(); printf("Game Over!\n"); exit(0); } } if (x == food_x && y == food_y) { // 吃到食物 score += 10; food_x = rand() % COLS; food_y = rand() % ROWS; } else { Snake *p = head; while (p->next->next) { p = p->next; } delete p->next; p->next = NULL; } } void drawFood() { setfillcolor(RED); solidcircle(food_x * CELL_SIZE + CELL_SIZE / 2, food_y * CELL_SIZE + CELL_SIZE / 2, CELL_SIZE / 2); } void updateScore() { setbkmode(TRANSPARENT); settextcolor(WHITE); char buf[32]; sprintf(buf, "Score: %d", score); outtextxy(10, 10, buf); } int food_x, food_y; int main() { initgraph(WIDTH, HEIGHT); setbkcolor(DARKGRAY); initSnake(); food_x = rand() % COLS; food_y = rand() % ROWS; while (true) { cleardevice(); drawSnake(); drawFood(); updateScore(); moveSnake(); Sleep(100); if (_kbhit()) { switch (_getch()) { case 'W': case 'w': if (direction != DOWN) direction = UP; break; case 'S': case 's': if (direction != UP) direction = DOWN; break; case 'A': case 'a': if (direction != RIGHT) direction = LEFT; break; case 'D': case 'd': if (direction != LEFT) direction = RIGHT; break; } } } return 0; } ``` 在这个示例代码中,我们使用了 EasyX 图形库来实现游戏窗口和绘制图形。我们使用 Snake 结构体来表示蛇身,其中的 next 指针指向下一个蛇身。当蛇移动时,我们将一个新的 Snake 节点插入到蛇头位置,然后删除蛇尾节点,从而实现蛇的移动。当蛇头碰到墙壁或者自己的身体时,游戏结束。当蛇头碰到食物时,得分加 10 分,并在随机位置生成一个新的食物。 在游戏循环中,我们使用 cleardevice() 函数清空屏幕,然后分别绘制蛇身、食物和得分。我们使用 Sleep(100) 函数控制游戏的帧率,从而实现动画效果。我们使用 _kbhit() 和 _getch() 函数来读取键盘输入,从而控制蛇的方向。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木灬U6770

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值