贪吃蛇:参考程序,实现吃食物长身体。
(通过↑↓←→控制小蛇)
#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;
}