贪吃蛇(无苹果)C++

贪吃蛇:参考程序,实现吃食物长身体。

(通过↑↓←→控制小蛇)

#include <bits/stdc++.h>
#include "util.h"
using namespace std;

struct XY {
    int x;
    int y;
};

int main() {
    clear();
    const auto WIDTH = 50;
    const auto HEIGHT = 20;
    const auto LONG = 10;
    deque<XY> snake;
    for (auto i=0; i<LONG; i++) {
        snake.push_front(XY{i, 0});
    }

    auto direction = KEY_RIGHT;
    while (true) {
        pause(50);
        recursor();
        for (auto y=0; y<HEIGHT; y++) {
            for (auto x=0; x<WIDTH; x++) {
                bool p = false;
                for (auto xy:snake) {
                    if (xy.x==x && xy.y==y) {
                        p = true;
                        break;
                    }
                }
                if (p) cout << 'o';
                else cout << ' ';
            }
            cout << '\n';
        }

        switch (getkey(false)) {
        case KEY_UP: {
            if (direction!=KEY_DOWN) direction = KEY_UP;
            break;
        }
        case KEY_LEFT: {
            if (direction!=KEY_RIGHT) direction = KEY_LEFT;
            break;
        }
        case KEY_RIGHT: {
            if (direction!=KEY_LEFT) direction = KEY_RIGHT;
            break;
        }
        case KEY_DOWN: {
            if (direction!=KEY_UP) direction = KEY_DOWN;
            break;
        }
        }

        switch (direction) {
        case KEY_UP: {
            auto xy = snake.front();
            xy.y--;
            if (xy.y<0) xy.y = HEIGHT-1;
            snake.push_front(xy);
            snake.pop_back();
            break;
        }
        case KEY_DOWN: {
            auto xy = snake.front();
            xy.y++;
            if (xy.y>=HEIGHT) xy.y = 0;
            snake.push_front(xy);
            snake.pop_back();
            break;
        }
        case KEY_LEFT: {
            auto xy = snake.front();
            xy.x--;
            if (xy.x<0) xy.x = WIDTH-1;
            snake.push_front(xy);
            snake.pop_back();
            break;
        }
        case KEY_RIGHT: {
            auto xy = snake.front();
            xy.x++;
            if (xy.x>=WIDTH) xy.x = 0;
            snake.push_front(xy);
            snake.pop_back();
            break;
        }
        }
    }
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值