13 / 13 / 10
Регистрация: 23.08.2015
Сообщений: 131
1

Реализовать интерактивное размещение шахмат на доске и подсветить возможные ходы

30.10.2016, 23:29. Показов 643. Ответов 3
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Дано поле 8х8 в виде 2хмерного массива. Все свободные поля обозначаются запятой [ , ]. Пользователь должен расставлять фигуры П(пешка), Т(тура), С(слон) в любую часть поля координатами по типа a5, g7 (Доска 1-8, a-h). После каждой веденной фигуры, она должна отображаться на поле соответствующей буквой. Также необходимо указать звёздочкой [ * ] возможные ходы последней введённой фигуры.
Необходимо также предусмотреть, если пользователь ввёл существующую координату, выдать ошибку и предложить ввести вновь.
Использовать только команды ввода-вывода, if-else, циклы и строки.
Я справился почти со всем, кроме обозначения возможного хода для Туры и Слона и нуждаюсь в вашей помощи. + код вышел слишком длинный. У других одногрупников код в этом задании ~150 строк, у меня уже больше 200. (У каждого разное задание, но всё же). Может у вас будут идеи как оптимизировать его?

Вот код:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <string.h>
#include <tchar.h>
#include <Windows.h>
 
using namespace std;
 
int main()
{
    SetConsoleCP(1251);// установка кодовой страницы win-cp 1251 в поток ввода
    SetConsoleOutputCP(1251); // установка кодовой страницы win-cp 1251 в поток вывода
    char arr[8][8];
 
    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j < 8; j++)
        {
            arr[i][j] = ',';
        }
    }
 
    char po[3];
    char pos[3];
    
    for(;;) {
        char name1;
        char name;
        
        cout << "Введите Т(тура), С(слон) или П(пешка). Что бы выйти введите \'x\': ";
        cin >> name;
        name1 = name;
 
        cin.get();
        if (name == 'х')
        {
            break;
        } // for
        cout << "Введите расположение фигуры (латиницей): ";
        cin.getline(po, 3);
        for (;;) {
            if (po[0] == pos[0] && po[1] == pos[1])
            {
                cout << "Вы ввели уже существующее расположение фигуры. Введите заново: ";
                cin.getline(po, 3);
            }
            else break;
        }
        strcpy(pos, po);
        cout << endl;
        
        //1st line
        if      (pos[1] == '1' && pos[0] == 'a')    arr[0][0] = name;
        else if (pos[1] == '1' && pos[0] == 'b')    arr[0][1] = name;
        else if (pos[1] == '1' && pos[0] == 'c')    arr[0][2] = name;
        else if (pos[1] == '1' && pos[0] == 'd')    arr[0][3] = name;
        else if (pos[1] == '1' && pos[0] == 'e')    arr[0][4] = name;
        else if (pos[1] == '1' && pos[0] == 'f')    arr[0][5] = name;
        else if (pos[1] == '1' && pos[0] == 'g')    arr[0][6] = name;
        else if (pos[1] == '1' && pos[0] == 'h')    arr[0][7] = name;
        // 2nd line
        else if (pos[1] == '2' && pos[0] == 'a')    arr[1][0] = name;
        else if (pos[1] == '2' && pos[0] == 'b')    arr[1][1] = name;
        else if (pos[1] == '2' && pos[0] == 'c')    arr[1][2] = name;
        else if (pos[1] == '2' && pos[0] == 'd')    arr[1][3] = name;
        else if (pos[1] == '2' && pos[0] == 'e')    arr[1][4] = name;
        else if (pos[1] == '2' && pos[0] == 'f')    arr[1][5] = name;
        else if (pos[1] == '2' && pos[0] == 'g')    arr[1][6] = name;
        else if (pos[1] == '2' && pos[0] == 'h')    arr[1][7] = name;
        //3rd line
        else if (pos[1] == '3' && pos[0] == 'a')    arr[2][0] = name;
        else if (pos[1] == '3' && pos[0] == 'b')    arr[2][1] = name;
        else if (pos[1] == '3' && pos[0] == 'c')    arr[2][2] = name;
        else if (pos[1] == '3' && pos[0] == 'd')    arr[2][3] = name;
        else if (pos[1] == '3' && pos[0] == 'e')    arr[2][4] = name;
        else if (pos[1] == '3' && pos[0] == 'f')    arr[2][5] = name;
        else if (pos[1] == '3' && pos[0] == 'g')    arr[2][6] = name;
        else if (pos[1] == '3' && pos[0] == 'h')    arr[2][7] = name;
        //4rt line
        else if (pos[1] == '4' && pos[0] == 'a')    arr[3][0] = name;
        else if (pos[1] == '4' && pos[0] == 'b')    arr[3][1] = name;
        else if (pos[1] == '4' && pos[0] == 'c')    arr[3][2] = name;
        else if (pos[1] == '4' && pos[0] == 'd')    arr[3][3] = name;
        else if (pos[1] == '4' && pos[0] == 'e')    arr[3][4] = name;
        else if (pos[1] == '4' && pos[0] == 'f')    arr[3][5] = name;
        else if (pos[1] == '4' && pos[0] == 'g')    arr[3][6] = name;
        else if (pos[1] == '4' && pos[0] == 'h')    arr[3][7] = name;
        //5th line
        else if (pos[1] == '5' && pos[0] == 'a')    arr[4][0] = name;
        else if (pos[1] == '5' && pos[0] == 'b')    arr[4][1] = name;
        else if (pos[1] == '5' && pos[0] == 'c')    arr[4][2] = name;
        else if (pos[1] == '5' && pos[0] == 'd')    arr[4][3] = name;
        else if (pos[1] == '5' && pos[0] == 'e')    arr[4][4] = name;
        else if (pos[1] == '5' && pos[0] == 'f')    arr[4][5] = name;
        else if (pos[1] == '5' && pos[0] == 'g')    arr[4][6] = name;
        else if (pos[1] == '5' && pos[0] == 'h')    arr[4][7] = name;
        //6th line
        else if (pos[1] == '6' && pos[0] == 'a')    arr[5][0] = name;
        else if (pos[1] == '6' && pos[0] == 'b')    arr[5][1] = name;
        else if (pos[1] == '6' && pos[0] == 'c')    arr[5][2] = name;
        else if (pos[1] == '6' && pos[0] == 'd')    arr[5][3] = name;
        else if (pos[1] == '6' && pos[0] == 'e')    arr[5][4] = name;
        else if (pos[1] == '6' && pos[0] == 'f')    arr[5][5] = name;
        else if (pos[1] == '6' && pos[0] == 'g')    arr[5][6] = name;
        else if (pos[1] == '6' && pos[0] == 'h')    arr[5][7] = name;
        //7th line
        else if (pos[1] == '7' && pos[0] == 'a')    arr[6][0] = name;
        else if (pos[1] == '7' && pos[0] == 'b')    arr[6][1] = name;
        else if (pos[1] == '7' && pos[0] == 'c')    arr[6][2] = name;
        else if (pos[1] == '7' && pos[0] == 'd')    arr[6][3] = name;
        else if (pos[1] == '7' && pos[0] == 'e')    arr[6][4] = name;
        else if (pos[1] == '7' && pos[0] == 'f')    arr[6][5] = name;
        else if (pos[1] == '7' && pos[0] == 'g')    arr[6][6] = name;
        else if (pos[1] == '7' && pos[0] == 'h')    arr[6][7] = name;
        //8th line
        else if (pos[1] == '8' && pos[0] == 'a')    arr[7][0] = name;
        else if (pos[1] == '8' && pos[0] == 'b')    arr[7][1] = name;
        else if (pos[1] == '8' && pos[0] == 'c')    arr[7][2] = name;
        else if (pos[1] == '8' && pos[0] == 'd')    arr[7][3] = name;
        else if (pos[1] == '8' && pos[0] == 'e')    arr[7][4] = name;
        else if (pos[1] == '8' && pos[0] == 'f')    arr[7][5] = name;
        else if (pos[1] == '8' && pos[0] == 'g')    arr[7][6] = name;
        else if (pos[1] == '8' && pos[0] == 'h')    arr[7][7] = name;
 
        char xname = '*';
 
        if (name1 == 'П')
        {
            // 2nd line
            if (pos[1] == '2' && pos[0] == 'a' && arr[0][0] == ',') arr[0][0] = xname;
            else if (pos[1] == '2' && pos[0] == 'b' && arr[0][1] == ',')    arr[0][1] = xname;
            else if (pos[1] == '2' && pos[0] == 'c' && arr[0][2] == ',')    arr[0][2] = xname;
            else if (pos[1] == '2' && pos[0] == 'd' && arr[0][3] == ',')    arr[0][3] = xname;
            else if (pos[1] == '2' && pos[0] == 'e' && arr[0][4] == ',')    arr[0][4] = xname;
            else if (pos[1] == '2' && pos[0] == 'f' && arr[0][5] == ',')    arr[0][5] = xname;
            else if (pos[1] == '2' && pos[0] == 'g' && arr[0][6] == ',')    arr[0][6] = xname;
            else if (pos[1] == '2' && pos[0] == 'h' && arr[0][7] == ',')    arr[0][7] = xname;
            //3rd line
            else if (pos[1] == '3' && pos[0] == 'a' && arr[1][0] == ',')    arr[1][0] = xname;
            else if (pos[1] == '3' && pos[0] == 'b' && arr[1][1] == ',')    arr[1][1] = xname;
            else if (pos[1] == '3' && pos[0] == 'c' && arr[1][2] == ',')    arr[1][2] = xname;
            else if (pos[1] == '3' && pos[0] == 'd' && arr[1][3] == ',')    arr[1][3] = xname;
            else if (pos[1] == '3' && pos[0] == 'e' && arr[1][4] == ',')    arr[1][4] = xname;
            else if (pos[1] == '3' && pos[0] == 'f' && arr[1][5] == ',')    arr[1][5] = xname;
            else if (pos[1] == '3' && pos[0] == 'g' && arr[1][6] == ',')    arr[1][6] = xname;
            else if (pos[1] == '3' && pos[0] == 'h' && arr[1][7] == ',')    arr[1][7] = xname;
            //4rt linxe
            else if (pos[1] == '4' && pos[0] == 'a' && arr[2][0] == ',')    arr[2][0] = xname;
            else if (pos[1] == '4' && pos[0] == 'b' && arr[2][1] == ',')    arr[2][1] = xname;
            else if (pos[1] == '4' && pos[0] == 'c' && arr[2][2] == ',')    arr[2][2] = xname;
            else if (pos[1] == '4' && pos[0] == 'd' && arr[2][3] == ',')    arr[2][3] = xname;
            else if (pos[1] == '4' && pos[0] == 'e' && arr[2][4] == ',')    arr[2][4] = xname;
            else if (pos[1] == '4' && pos[0] == 'f' && arr[2][5] == ',')    arr[2][5] = xname;
            else if (pos[1] == '4' && pos[0] == 'g' && arr[2][6] == ',')    arr[2][6] = xname;
            else if (pos[1] == '4' && pos[0] == 'h' && arr[2][7] == ',')    arr[2][7] = xname;
            //5th line
            else if (pos[1] == '5' && pos[0] == 'a' && arr[3][0] == ',')    arr[3][0] = xname;
            else if (pos[1] == '5' && pos[0] == 'b' && arr[3][1] == ',')    arr[3][1] = xname;
            else if (pos[1] == '5' && pos[0] == 'c' && arr[3][2] == ',')    arr[3][2] = xname;
            else if (pos[1] == '5' && pos[0] == 'd' && arr[3][3] == ',')    arr[3][3] = xname;
            else if (pos[1] == '5' && pos[0] == 'e' && arr[3][4] == ',')    arr[3][4] = xname;
            else if (pos[1] == '5' && pos[0] == 'f' && arr[3][5] == ',')    arr[3][5] = xname;
            else if (pos[1] == '5' && pos[0] == 'g' && arr[3][6] == ',')    arr[3][6] = xname;
            else if (pos[1] == '5' && pos[0] == 'h' && arr[3][7] == ',')    arr[3][7] = xname;
            //6th line
            else if (pos[1] == '6' && pos[0] == 'a' && arr[4][0] == ',')    arr[4][0] = xname;
            else if (pos[1] == '6' && pos[0] == 'b' && arr[4][1] == ',')    arr[4][1] = xname;
            else if (pos[1] == '6' && pos[0] == 'c' && arr[4][2] == ',')    arr[4][2] = xname;
            else if (pos[1] == '6' && pos[0] == 'd' && arr[4][3] == ',')    arr[4][3] = xname;
            else if (pos[1] == '6' && pos[0] == 'e' && arr[4][4] == ',')    arr[4][4] = xname;
            else if (pos[1] == '6' && pos[0] == 'f' && arr[4][5] == ',')    arr[4][5] = xname;
            else if (pos[1] == '6' && pos[0] == 'g' && arr[4][6] == ',')    arr[4][6] = xname;
            else if (pos[1] == '6' && pos[0] == 'h' && arr[4][7] == ',')    arr[4][7] = xname;
            //7th linxe
            else if (pos[1] == '7' && pos[0] == 'a' && arr[5][0] == ',')    arr[5][0] = xname;
            else if (pos[1] == '7' && pos[0] == 'b' && arr[5][1] == ',')    arr[5][1] = xname;
            else if (pos[1] == '7' && pos[0] == 'c' && arr[5][2] == ',')    arr[5][2] = xname;
            else if (pos[1] == '7' && pos[0] == 'd' && arr[5][3] == ',')    arr[5][3] = xname;
            else if (pos[1] == '7' && pos[0] == 'e' && arr[5][4] == ',')    arr[5][4] = xname;
            else if (pos[1] == '7' && pos[0] == 'f' && arr[5][5] == ',')    arr[5][5] = xname;
            else if (pos[1] == '7' && pos[0] == 'g' && arr[5][6] == ',')    arr[5][6] = xname;
            else if (pos[1] == '7' && pos[0] == 'h' && arr[5][7] == ',')    arr[5][7] = xname;
            //8th line
            else if (pos[1] == '8' && pos[0] == 'a' && arr[6][0] == ',')    arr[6][0] = xname;
            else if (pos[1] == '8' && pos[0] == 'b' && arr[6][1] == ',')    arr[6][1] = xname;
            else if (pos[1] == '8' && pos[0] == 'c' && arr[6][2] == ',')    arr[6][2] = xname;
            else if (pos[1] == '8' && pos[0] == 'd' && arr[6][3] == ',')    arr[6][3] = xname;
            else if (pos[1] == '8' && pos[0] == 'e' && arr[6][4] == ',')    arr[6][4] = xname;
            else if (pos[1] == '8' && pos[0] == 'f' && arr[6][5] == ',')    arr[6][5] = xname;
            else if (pos[1] == '8' && pos[0] == 'g' && arr[6][6] == ',')    arr[6][6] = xname;
            else if (pos[1] == '8' && pos[0] == 'h' && arr[6][7] == ',')    arr[6][7] = xname;
 
            for (int i = 0; i < 8; i++) {
                for (int j = 0; j < 8; j++)
                {
                    cout << setw(3) << "[" << arr[i][j] << "]";
                }
                cout << endl;
            }
        }// if
        else if (name1 == 'Т')
        {
 
            for (int i = 0; i < 8; i++) {
                for (int j = 0; j < 8; j++)
                {
                    cout << setw(3) << "[" << arr[i][j] << "]";
                }
                cout << endl;
            }
        }//else if
        else if (name1 == 'С')
        {
 
            for (int i = 0; i < 8; i++) {
                for (int j = 0; j < 8; j++)
                {
                    cout << setw(3) << "[" << arr[i][j] << "]";
                }
                cout << endl;
            }
        }//else if
        
    }//for(;;)
 
    system("pause");
    return 0;
}
Заранее спасибо)
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
30.10.2016, 23:29
Ответы с готовыми решениями:

Расположение на доске шахмат
Напишите пожалуйста программу (с комментариями), по заданию :) : &quot;Поле шахматной доски...

Возможные ходы пешки
Всем добры день, Помогите пожалуйста написать функцию которая будет возвращать True если королю...

Вывести все возможные ходы коня
Ребят есть задача,а именно ввести в интуп значение в формате &quot;d4&quot; а на выходе при нажатии на баттон...

Вычислить все возможные ходы коня
в шахматах задать начальные координаты клетки(х,у) и вычислить все возможные ходы коня из этой...

3
1391 / 1020 / 324
Регистрация: 28.07.2012
Сообщений: 2,809
31.10.2016, 00:09 2
neketsh, строки 54-124 замени на одну строчку:
C++
1
arr[pos[1] - '1'][pos[0] - 'a'] = name;
А строки 131-192 на:
C++
1
2
if (pos[1] > '1' && arr[pos[1] - '1' - 1][pos[0] - 'a'] == ',')
    arr[pos[1] - '1' - 1][pos[0] - 'a'] = xname;
2
13 / 13 / 10
Регистрация: 23.08.2015
Сообщений: 131
31.10.2016, 13:50  [ТС] 3
nonedark2008, А по какому принципу это высчитывается, не понимаю. Почему это:
C++
1
arr[pos[1] - '1'][pos[0] - 'a'] = name;
может задать любые кординаты на поле? Мы вычитаем из pos[1] значение '1' и получаем нужную координату? Как?
0
1391 / 1020 / 324
Регистрация: 28.07.2012
Сообщений: 2,809
31.10.2016, 14:00 4
neketsh, из символов от '1' до '8' (или букв от 'a' до 'h') нужно получить числа от 0 до 7.
Известно, что в кодировке ASCII цифры, как и буквы латинского алфавита, идут по порядку один за другим.
Каждый символ в кодировке задается некоторым кодом, например код символа '0' - это 48, '1' - 49 и т.д.
Что бы получить из любого элемента последовательности 49, 50,... его порядковый номер 0, 1, ..., 7 и нужно pos[1] - '1'.
То же самое и с буквами.
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
31.10.2016, 14:00
Помогаю со студенческими работами здесь

Вычислить все возможные ходы ферзём
вычислить все возможные ходы ферзём

Ход возможные ходы шахматного коня, таблица
Заполняю простую таблицу, 8 на 8 клеток, первая цифра номер строки, вторая номер колонки, по...

Определить все возможные ходы для следующих фигур
Даны исходная координата клетки (например, B6), где стоит фигура. Определить все возможные ходы...

Определить все возможные ходы ферзя, с поворотом доски на 180 градусов
Здравствуйте! Задача состоит в следующем: дано поле 8*8, нужно определить все возможные ходы ферзя,...

На доске стоит белая шашка. Определить, может ли она попасть в заданную клетку, делая ходы по правилам
Задача №1 На доске стоит белая шашка.Требуется определить, может ли она попасть в заданную клетку,...

Вывести все возможные ходы шахматного коня из данной позиции, для трехмерной шахматной доски 8*8*8
Sub asd() Dim x As Integer, y As Integer, xx As Integer, yy As Integer, s As String Do x =...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru