Исправить вращение для 2D головоломки Рубика

Я работаю над этой программой, которая является симулятором головоломки Grid. Сетка - это двухмерная версия кубика Рубика. Вот критерии для этой загадки:

  • Сетка 6 х 6
  • 2 лица
  • пользователь может вращать столбцы и строки
  • повороты на 180 градусов
  • состоят из двух цветов

Примечание. Я использовал символ "*" для обозначения черного и "o" для обозначения белого.

Пользователь вводит сторону (сверху, снизу, слева или справа) и количество столбцов или строк, которые он хочет повернуть, и симуляция будет имитировать движение. Пожалуйста, посмотрите на сетку:

Когда пользователь вращается, цвет меняется на противоположный цвет и ИЗМЕНИТ ПОЛОЖЕНИЕ в соответствии с вращением.

У меня в основном все сделано, кроме вращения. Когда пользователь вводит номер стороны и строки / столбца, меняется только цвет, размещение цвета не является правильным.

Вот пример поворота:

Можете ли вы помочь мне, чтобы вращения работали правильно. Заранее большое спасибо.

Вот мой код класса.

// Library Files
using namespace std;
# include <iostream>    // input and output

#ifndef G_R_I_D
#define G_R_I_D

class grid
{
public:
    int input();                                        // side and num
    int flipTop();
    int flipBottom();
    int flipRight();
    int flipLeft();
    void initBoard();                                   // Create blank board
    void printBoard();                                  // print board

private:
    char board [6][6];                                  // board
    int num;                                            // number of rows/ columns from side
};

/******************
*Member Definition*
******************/
int grid::input()
{
    cout << "# of Rows /Columns: ";                     // Indicates num of rows or columns
    cin >> num;
}

int grid::flipRight()
{
    num = 6 - num;                                     // Match input to correct array ex. if right 2, actual array is 4
    for(num; num < 6; num++)                           // Because bottom contains the y axis arrays 3, 4, 5, count up in sequence
    {
        for(int i = 0; i < 6; i++)
        {
            if (board[i][num] == 'o')
            {
                board[i][num] = '*';
            }


            else if (board[i][num] == '*')
            {
                board[i][num] = 'o';
            }
        }
    }
}

int grid::flipLeft()
{
    num = num - 1;                                      // If between arrays 0-2, subtract one from input because first array is 1
    for(num; num >= 0; num--)                           // Because bottom contains the y axis arrays 0, 1, 2, count down in sequence
    {
        for(int i = 0; i < 6; i++)
        {
            if (board[i][num] == 'o')
                board[i][num] = '*';

            else if (board[i][num] == '*')
                board[i][num] = 'o';
        }
    }
}

int grid::flipTop()
{
    num = num - 1;                                      // If between arrays 0-2, subtract one from input because first array is 1
    for(num; num >= 0; num--)                           // Because bottom contains the y axis arrays 0, 1, 2, count down in sequence
    {
        for(int i = 0; i < 6; i++)
            if (board[num][i] == 'o')
                board[num][i] = '*';

            else if (board[num][i] == '*')
                board[num][i] = 'o';
    }
}

int grid::flipBottom()
{
    num = 6 - num;                                       // Match input to correct array ex. if right 2, actual array is 4
    for(num; num < 6; num++)                             // Because bottom contains the y axis arrays 3, 4, 5, count up in sequence
    {
        for(int i = 0; i < 6; i++)
            if (board[num][i] == 'o')
                board[num][i] = '*';

            else if (board[num][i] == '*')
                board[num][i] = 'o';
    }
}

void grid::initBoard()                                // Goes through each 36 array starting with 0,0
{
    for(int y = 0; y < 6; y++)                          // columns
    {
        for (int x = 0; x < 6; x++)                     // rows
        {
            board[y][x] = 'o';                          // assign each array to the char 'o'
        }
    }
}

void grid::printBoard()
{
    for (int y = 0; y < 6; y++)                         // Defining y axis (wait until x axis arrays have printed to continue to next column)
    {
        for (int x = 0; x < 6; x++)                     // Defining x axis (once row is finished, proceed to next column)
        {
            cout << ' ' << board[y][x] << ' ';          // Place space between each character
        }
        cout << endl << endl;                           // New line, next row
    }
}

#endif // G_R_I_D


/*
+---+---+---+---+---+---+
|0,0|0,1|0,2|0,3|0,4|0,5|
+---+---+---+---+---+---+
|1,0|1,1|1,2|1,3|1,4|1,5|
+---+---+---+---+---+---+
|2,0|2,1|2,2|2,3|2,4|2,5|
+---+---+---+---+---+---+
|3,0|3,1|3,2|3,3|3,4|3,5|
+---+---+---+---+---+---+
|4,0|4,1|4,2|4,3|4,4|4,5|
+---+---+---+---+---+---+
|5,0|5,1|5,2|5,3|5,4|5,5|
+---+---+---+---+---+---+
*/

А вот мой файл C++, который запускает класс.

// Library Files
using namespace std;
# include <iostream>
# include "grid.h"

// Start of main function
int main()
{

    // Variables
    char side;
    grid gridBoard;
    // Introduction
    cout << "Grid\n Instructions: This program is a simulation of the puzzle Grid. The Grid grid has four sides and each \n"
         << "side has three rows or columns. To twist a side, enter the side you want to turn and the number of rows or columns. \n"
         << "Sides:\n- (T)op \n- (B)ottom \n- (R)ight \n- (L)eft\n- (E)xit \nColumns/Rows: 1-3\n\n";

    // Initialize
    gridBoard.initBoard();

    //Rotations
    do
    {
        gridBoard.printBoard();
        cout << "Side: ";
        cin >> side;
        gridBoard.input();
        switch (toupper(side))
        {
        case 'T':
            gridBoard.flipTop();
            break;
        case 'B':
            gridBoard.flipBottom();
            break;
        case 'R':
            waffleBoard.flipRight();
            break;
        case 'L':
            gridBoard.flipLeft();
            break;
        case 'E':
            cout << "Simulation will exit.";
            break;
        default:
            cout << "Invalid input, please try again.\n\n";
            break;
        }
    }
    while (side != 'E');

    return 0;
}

1 ответ

Самый простой способ - понять, что поворот массива на 180 градусов - это то же самое, что перевернуть массив один раз в направлении строки и один раз в направлении столбца. Так что сделайте следующие шаги:

  1. Получить подмассив, выбранный пользователем из массива доски
  2. Сделайте свою операцию инвертирования
  3. Переверните вложенный массив в направлении строки
  4. Переверните вложенный массив в направлении столбца
  5. Скопируйте вложенный массив обратно в массив платы

Для операции переворота вы можете использовать временные массивы. Кстати, я называю это массивами здесь, но вы можете заглянуть в std::array для более легкой обработки данных. Там вы можете использовать итераторы и функции подкачки.

Другие вопросы по тегам