洛谷

文字游戏-A梦

#include <iostream>
#include <windows.h>
#include <conio.h>

using namespace std;

void gotoXY(int x, int y) {
    COORD coord;
    coord.X = x;
    coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void hideCursor() {
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_CURSOR_INFO cursorInfo;
    GetConsoleCursorInfo(hConsole, &cursorInfo);
    cursorInfo.bVisible = false;
    SetConsoleCursorInfo(hConsole, &cursorInfo);
}

int main() {
    // 设置控制台窗口大小
    system("mode con cols=45 lines=25");
    hideCursor();

    // 游戏区域尺寸 - 减少宽度适应控制台
    const int WIDTH = 40;    // 宽度
    const int HEIGHT = 20;   // 高度

    int x = 10, y = 10;  // 初始位置

    // 初始化界面(只绘制一次)
    system("cls");

    // 绘制固定边界
    for (int i = 0; i < HEIGHT; i++) {
        gotoXY(0, i);
        for (int j = 0; j < WIDTH; j++) {
            if (i == 0 || i == HEIGHT - 1 || j == 0 || j == WIDTH - 1) {
                cout << "#";  // 英文字符边界
            } else {
                cout << " ";
            }
        }
    }

    // 初始绘制玩家
    gotoXY(x, y);
    cout << "@";  // 英文字符玩家

    // 显示游戏信息
    gotoXY(0, HEIGHT);
    cout << "Position: (" << x << ", " << y << ")  WASD move, Q quit";

    // 游戏循环
    while (true) {
        if (_kbhit()) {
            char ch = _getch();
            int oldX = x, oldY = y;

            switch (ch) {
                case 'w': case 'W': 
                    if (y > 1) y--;
                    break;
                case 's': case 'S': 
                    if (y < HEIGHT - 2) y++;
                    break;
                case 'a': case 'A': 
                    if (x > 1) x--;
                    break;
                case 'd': case 'D': 
                    if (x < WIDTH - 2) x++;
                    break;
                case 'q': case 'Q': 
                    gotoXY(0, HEIGHT + 1);
                    cout << "Game Over!" << endl;
                    return 0;
            }

            // 更新玩家位置
            if (oldX != x || oldY != y) {
                gotoXY(oldX, oldY);
                cout << " ";

                gotoXY(x, y);
                cout << "@";

                // 更新位置信息
                gotoXY(10, HEIGHT);  // "Position: "占10个字符
                cout << "(" << x << ", " << y << ")      ";
            }
        }

        Sleep(50);
    }

    return 0;
}