0
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <windows.h>
#include <conio.h>
using namespace std;
const int W = 40;
const int H = 20;
const int GROUND = 14;
const char AIR = ' ';
const char GRASS = '#';
const char DIRT = '.';
const char STONE = 'O';
const char WOOD = 'T';
const char LEAF = '*';
struct Game {
vector<string> map;
int px = 5, py = GROUND - 1;
int facing = 1; // 1右 -1左
int score = 0;
bool running = true;
void gen() {
map.resize(H);
for (int y = 0; y < H; ++y) {
map[y].resize(W, AIR);
for (int x = 0; x < W; ++x) {
if (y > GROUND) map[y][x] = STONE;
else if (y == GROUND) map[y][x] = GRASS;
else if (y >= GROUND - 3) map[y][x] = DIRT;
}
}
// 种树
int tx = 20;
for (int y = GROUND - 5; y <= GROUND - 1; ++y) map[y][tx] = WOOD;
for (int y = GROUND - 7; y <= GROUND - 4; ++y)
for (int dx = -2; dx <= 2; ++dx)
if (tx + dx >= 0 && tx + dx < W) map[y][tx + dx] = LEAF;
}
void setColor(int c) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
void draw() {
system("cls");
for (int y = 0; y < H; ++y) {
for (int x = 0; x < W; ++x) {
if (x == px && y == py) {
setColor(14); cout << '@'; continue;
}
char c = map[y][x];
if (c == GRASS) { setColor(10); cout << '#'; }
else if (c == DIRT) { setColor(6); cout << '.'; }
else if (c == STONE) { setColor(8); cout << 'O'; }
else if (c == WOOD) { setColor(4); cout << 'T'; }
else if (c == LEAF) { setColor(2); cout << '*'; }
else { setColor(7); cout << ' '; }
}
cout << '\n';
}
setColor(7);
cout << "WASD移动 空格跳 Z挖 X放方块 Q退出 | 收集: " << score << endl;
}
bool solid(int x, int y) {
if (x < 0 || x >= W || y < 0 || y >= H) return false;
return map[y][x] != AIR;
}
void update(char k) {
int nx = px, ny = py;
if (k == 'a') { nx--; facing = -1; }
if (k == 'd') { nx++; facing = 1; }
if (k == 'w' && !solid(px, py - 1)) ny--;
if (k == 's') ny++;
// 重力
while (!solid(nx, ny + 1) && ny + 1 < H) ny++;
if (!solid(nx, ny)) { px = nx; py = ny; }
// 挖
if (k == 'z') {
int fx = px + facing;
if (solid(fx, py)) { map[py][fx] = AIR; score++; }
}
// 放
if (k == 'x') {
int fx = px + facing;
if (!solid(fx, py)) map[py][fx] = GRASS;
}
if (k == 'q') running = false;
}
};
int main() {
Game g;
g.gen();
while (g.running) {
g.draw();
if (_kbhit()) {
char k = _getch();
g.update(k);
}
Sleep(30);
}
system("cls");
cout << "游戏结束!你收集了 " << g.score << " 个方块!\n";
return 0;
}
