- Шаг 1. Создание проекта и добавление таблицы в форму Step 1: Create a project and add a table to your form
- Создание проекта и добавление таблицы в форму To create a project and add a table to your form
- Задание свойств формы To set properties for a form
- Продолжить или повторить пройденный материал To continue or review
Шаг 1. Создание проекта и добавление таблицы в форму Step 1: Create a project and add a table to your form
Первым шагом создания игры «Подбери пару!» является создание проекта и добавление таблицы в форму. The first step in creating a matching game is to create the project and add a table to your form. Таблица помогает равномерно распределить значки по сетке 4×4. The table helps align the icons into an orderly 4×4 grid. Можно также задать несколько свойств, чтобы улучшить внешний вид игрового поля. You also set several properties to enhance the appearance of the game board.
Создание проекта и добавление таблицы в форму To create a project and add a table to your form
В строке меню щелкните Файл > Создать > Проект. On the menu bar, choose File > New > Project.
Выберите Visual C# или Visual Basic в левой области диалогового окна Новый проект, а затем — Классическое приложение Windows. Choose either Visual C# or Visual Basic on the left side of the New Project dialog box, and then choose Windows Desktop.
В списке шаблонов выберите шаблон Приложение Windows Forms (.NET Framework), назовите его MatchingGame, а затем нажмите кнопку ОК. In the list of templates, choose the Windows Forms App (.NET Framework) template, name it MatchingGame, and then choose the OK button.
Появится форма с именем Form1.cs или Form1.vb, в зависимости от выбранного языка программирования. A form that’s named Form1.cs or Form1.vb appears, depending on the programming language that you chose.
Если вы не видите шаблон Приложение Windows Forms (.NET Framework), используйте Visual Studio Installer, чтобы установить рабочую нагрузку Разработка классических приложений .NET. If you don’t see the Windows Forms App (.NET Framework) template, use the Visual Studio Installer to install the .NET desktop development workload.
Дополнительные сведения см. в разделе Установка Visual Studio. For more information, see the Install Visual Studio page.
На начальном экране выберите Создать проект. On the start window, choose Create a new project.
В поле поиска окна Создание проекта введите Windows Forms. On the Create a new project window, enter or type Windows Forms in the search box. Затем в списке Тип проекта выберите Рабочий стол. Next, choose Desktop from the Project type list.
Применив фильтр Тип проекта, выберите шаблон Приложение Windows Forms (.NET Framework) для C# или Visual Basic и нажмите кнопку Далее. After you apply the Project type filter, choose the Windows Forms App (.NET Framework) template for either C# or Visual Basic, and then choose Next.
Если шаблон Приложение Windows Forms (.NET Framework) отсутствует, его можно установить из окна Создание проекта. If you do not see the Windows Forms App (.NET Framework) template, you can install it from the Create a new project window. В сообщении Не нашли то, что искали? выберите ссылку Установка других средств и компонентов. In the Not finding what you’re looking for? message, choose the Install more tools and features link.
После этого в Visual Studio Installer выберите рабочую нагрузку Разработка классических приложений .NET. Next, in the Visual Studio Installer, choose the Choose the .NET desktop development workload.
Затем нажмите кнопку Изменить в Visual Studio Installer. After that, choose the Modify button in the Visual Studio Installer. Вам может быть предложено сохранить результаты работы; в таком случае сделайте это. You might be prompted to save your work; if so, do so. Выберите Продолжить, чтобы установить рабочую нагрузку. Next, choose Continue to install the workload.
В окне Настроить новый проект введите MatchingGame в поле Имя проекта. In the Configure your new project window, type or enter MatchingGame in the Project name box. Затем нажмите Создать. Then, choose Create.
Задание свойств формы To set properties for a form
В окне Свойства задайте следующие значения свойств формы. In the Properties window, set the following form properties.
Измените свойство формы Text с Form1 на Matching Game. Change the form’s Text property from Form1 to Matching Game. Этот текст отображается в верхней части окна игры. This text appears at the top of the game window.
Установите размер формы на 550 пикселей в ширину и 550 пикселей в высоту. Set the size of the form to 550 pixels wide by 550 tall. Для этого установите для свойства Size значение 550, 550 или перетащите угол формы, чтобы требуемый размер отобразился в правом нижнем углу интегрированной среды разработки (IDE). You can do this either by setting the Size property to 550, 550, or by dragging the corner of the form until you see the correct size in the lower-right corner of the integrated development environment (IDE).
Откройте панель элементов, выбрав вкладку Панель элементов в левой части интегрированной среды разработки. Display the toolbox by choosing the Toolbox tab on the left side of the IDE.
Перетащите элемент управления TableLayoutPanel из категории Контейнеры панели элементов, а затем установите для него следующие свойства. Drag a TableLayoutPanel control from the Containers category in the toolbox, and then set the following properties for it.
Задайте для свойства BackColor значение CornflowerBlue. Set the BackColor property to CornflowerBlue. Для этого откройте диалоговое окно BackColor, щелкнув стрелку раскрывающегося списка рядом со свойством BackColor в окне Свойства. To do this, open the BackColor dialog box by choosing the drop-down arrow next to the BackColor property in the Properties window. Затем перейдите на вкладку Веб в диалоговом окне BackColor, чтобы просмотреть список доступных имен цветов. Then, choose the Web tab in the BackColor dialog box to view a list of available color names.
Цвета упорядочены не по алфавиту, и цвет CornflowerBlue находится в нижней части списка. The colors are not in alphabetical order, and CornflowerBlue is near the bottom of the list.
Задайте для свойства Dock значение Fill, нажав кнопку раскрывающегося списка рядом со свойством и щелкнув большую среднюю кнопку. Set the Dock property to Fill by choosing the drop-down button next to the property and choosing the large middle button. Таблица будет растянута по всей форме. This spreads the table out so that it covers the entire form.
Для свойства CellBorderStyle установите значение Inset. Set the CellBorderStyle property to Inset. Между ячейками поля появятся видимые границы. This provides visual borders between each cell on the board.
Нажмите треугольную кнопку в правом верхнем углу элемента управления TableLayoutPanel для отображения меню задач этой панели. Choose the triangle button in the upper-right corner of the TableLayoutPanel to display its task menu.
В меню задач дважды щелкните Добавить строку для добавления двух дополнительных строк, а затем дважды щелкните Добавить столбец для добавления двух дополнительных столбцов. On the task menu, choose Add Row twice to add two more rows, and then choose Add Column twice to add two more columns.
В меню задач выберите команду Изменить строки и столбцы, чтобы открыть окно Стили столбцов и строк. On the task menu, choose Edit Rows and Columns to open the Column and Row Styles window. Выберите каждый из столбцов, нажмите кнопку Процент и установите ширину каждого столбца равной 25 процентам от общей ширины. Choose each of the columns, choose the Percent option button, and then set each column’s width to 25 percent of the total width. Затем в раскрывающемся списке в верхней части окна выберите Строки и задайте высоту каждой строки равной 25 процентам. Then select Rows from the drop-down box at the top of the window, and set each row’s height to 25 percent. По завершении нажмите кнопку ОК. When you’re done, choose the OK button.
Теперь на панели макета таблицы должна быть видна сетка размером 4х4, состоящая из шестнадцати одинаковых по размеру квадратных ячеек. Your TableLayoutPanel should now be a 4×4 grid, with sixteen equally sized square cells. Эти строки и столбцы задают места, в которых позже появятся изображения значков. These rows and columns are where the icon images will appear later.
Убедитесь, что TableLayoutPanel выбран в редакторе формы. Be certain that the TableLayoutPanel is selected in the form editor. На это будет указывать надпись tableLayoutPanel1 в верхней части окна Свойства. To verify this, you should see tableLayoutPanel1 at the top of the Properties window. Если этот элемент управления не выбран, выберите элемент управления TableLayoutPanel в форме или в раскрывающемся списке в верхней части окна Свойства. If it is not selected, choose the TableLayoutPanel on the form, or choose it in the dropdown control at the top of the Properties window.
При выбранном элементе управления TableLayoutPanel откройте панель элементов и добавьте элемент управления Label (находится в категории Стандартные элементы управления) в левую верхнюю ячейку TableLayoutPanel. While the TableLayoutPanel is selected, open the toolbox and add a Label control (located in the Common Controls category) to the upper-left cell of the TableLayoutPanel. Теперь элемент управления Label должен быть выбран в интегрированной среде разработки. The label control should now be selected in the IDE. Задайте для него следующие свойства. Set the following properties for it.
Убедитесь, что свойство BackColor имеет значение CornflowerBlue. Be sure that the label’s BackColor property is set to CornflowerBlue.
Задайте свойству AutoSize значение False. Set the AutoSize property to False.
Задайте для свойства Dock значение Fill. Set the Dock property to Fill.
Задайте для свойства TextAlign значение MiddleCenter, нажав кнопку раскрывающегося списка рядом со свойством, а затем щелкнув среднюю кнопку. Set the TextAlign property to MiddleCenter by choosing the drop-down button next to the property, and then choosing the middle button. Это необходимо, чтобы значок отображался в середине ячейки. This ensures the icon appears in the middle of the cell.
Выберите свойство Font. Choose the Font property. Должна появиться кнопка с многоточием (…). An ellipsis (. ) button should appear.
Нажмите кнопку с многоточием и установите для параметра Font значение Webdings, для параметра Font Style — значение Bold, а для параметра Size — значение 48. Choose the ellipsis button, and set the Font value to Webdings, the Font Style to Bold, and the Size to 48.
Установите свойство Text равным букве с. Set the Text property of the label to the letter c.
Теперь в левой верхней ячейке TableLayoutPanel должен располагаться черный квадрат на синем фоне, который выравнивается по центру. The upper-left cell in the TableLayoutPanel should now contain a black box centered on a blue background.
Шрифт Webdings является шрифтом значков, который поставляется с операционной системой Windows. The Webdings font is a font of icons that ships with the Windows operating system. В вашей игре «Подбери пару!» игроку необходимо найти пары одинаковых значков, поэтому используйте этот шрифт для отображения значков. In your matching game, the player needs to match pairs of icons, so you use this font to display the icons to match. Вместо ввода буквы с в свойство Text попробуйте вводить разные буквы, чтобы увидеть, какие значки отображаются. Instead of putting c in the Text property, try entering different letters to see what icons are displayed. Восклицательный знак соответствует пауку, прописная буква N — глазу, а запятая — перцу чили. An exclamation point is a spider, an uppercase N is an eye, and a comma is a chili pepper.
Выберите элемент управления Label и скопируйте его в следующую ячейку TableLayoutPanel. Choose your Label control and copy it to the next cell in the TableLayoutPanel. (Нажмите сочетание клавиш CTRL+C или в строке меню выберите Правка > Копировать.) Затем вставьте его. (Choose the Ctrl+C keys, or on the menu bar, choose Edit > Copy.) Then paste it. (Нажмите сочетание клавиш CTRL+V или в строке меню выберите Правка > Вставить.) Во второй ячейке элемента управления TableLayoutPanel появится копия первого элемента управления Label. (Choose the Ctrl+V keys, or on the menu bar, choose Edit > Paste.) A copy of the first Label appears in the second cell of the TableLayoutPanel. Вставьте его снова, и в третьей ячейке появится еще один элемент управления Label. Paste it again, and another Label appears in the third cell. Продолжайте вставлять элементы управления Label, пока все ячейки не будут заполнены. Keep pasting Label controls until all of the cells are filled.
Если выполнить команду вставки слишком много раз, интегрированная среда разработки добавит новую строку в TableLayoutPanel, чтобы появилось место для добавления нового элемента управления Label. If you paste too many times, the IDE adds a new row to the TableLayoutPanel so that it has a place to add your new Label control. Можно выполнить откат. You can undo it. Чтобы удалить новую ячейку, нажмите сочетание клавиш CTRL+Z или в меню выберите Правка > Отменить. To remove the new cell, choose the Ctrl+Z keys, or on the menu bar, choose Edit > Undo.
Теперь ваша форма готова. Она будет выглядеть примерно так, как показано на рисунке ниже. Now your form is laid out. It should look similar to the following picture.
Исходная форма игры «Подбери пару!» Initial matching game form
Продолжить или повторить пройденный материал To continue or review
Предыдущая статья с общими сведениями: Руководство 3. Создание игры «Подбери пару!». To return to the overview topic, see Tutorial 3: Create a matching game.