You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++实现俄罗斯方块:T型方块顶部放置算法求解

解决T型方块放置到俄罗斯方块地图顶部的问题

你已经完成了带边框的游戏地图初始化,现在需要将指定T型方块放置到地图顶部中间位置,以下是具体实现思路和代码修正方案:

现有代码的问题修正

  1. 变量拼写错误:定义的heigth与使用的height不一致,需统一变量名
  2. 地图初始化逻辑错误:每次向board添加deneme后未清空,导致每行空格重复累加,需在循环内清空deneme
  3. 边框赋值逻辑错误:循环顺序颠倒(行/列索引对应错误),需先遍历行再遍历列

方块放置核心逻辑

要将T型方块放到顶部中间,需:

  • 确定起始放置坐标:
    • 垂直方向:从顶部边框下一行开始(行索引1,第0行为边框x)
    • 水平方向:计算地图宽度中点,减去方块有效宽度的一半,保证居中。此处方块有效宽度为3,起始列 = (地图宽度 - 3) / 2
  • 遍历方块每个单元格,仅当单元格为T时,将地图对应位置设为T

完整实现代码

#include <vector>
#include <iostream>
using namespace std;

int main() {
    int i, j;
    int height = 6;
    int width = 14;
    vector<vector<char>> board;
    vector<vector<char>> shape;
    vector<char> deneme;

    // 初始化T型方块
    shape = {
        {' ', ' ', ' ', ' '},
        {' ', ' ', ' ', ' '},
        {'T', 'T', 'T', ' '},
        {' ', 'T', ' ', ' '}
    };

    // 正确初始化地图
    for (i = 0; i < height; i++) {
        deneme.clear();
        for (j = 0; j < width; j++) {
            deneme.push_back(' ');
        }
        board.push_back(deneme);
    }

    // 绘制地图边框
    for (i = 0; i < height; i++) {
        for (j = 0; j < width; j++) {
            if (i == 0 || i == height - 1) {
                board[i][j] = 'x';
            }
            if (j == 0 || j == width - 1) {
                board[i][j] = 'x';
            }
        }
    }

    // 核心:放置T型方块到顶部中间
    int start_row = 1;
    int shape_width = 3;
    int start_col = (width - shape_width) / 2;

    for (i = 0; i < shape.size(); i++) {
        for (j = 0; j < shape[i].size(); j++) {
            if (shape[i][j] == 'T' && (start_row + i) < height && (start_col + j) > 0 && (start_col + j) < width) {
                board[start_row + i][start_col + j] = shape[i][j];
            }
        }
    }

    // 打印验证地图
    for (auto &row : board) {
        for (char c : row) {
            cout << c;
        }
        cout << endl;
    }

    return 0;
}

代码说明

  • 地图初始化时每次循环清空deneme,确保每行空格数量正确
  • 边框绘制修正循环顺序,保证行/列索引对应无误
  • 方块放置增加边界判断,避免超出地图有效区域
  • 通过计算居中起始列,确保方块在水平方向居中显示

内容的提问来源于stack exchange,提问作者nwer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 09:40:29