3. Интерфейс программы
При запуске исполняемого файла Variant15[SeaBattle].exe на экране появляется окно программы (Рис.1).
Рисунок 1 – Стартовое окно программы
Как мы видим, были созданы 2 игровых поля (слева для игрока, справа для Ai). Корабли можно расставить двумя способами – вручную и случайным образом. В первом случае нам вручную приходиться вписывать количество палуб (от 1 до 4), а также координаты верхней (в случае вертикального расположения корабля) палубы или левой (в случае горизонтального расположения корабля) палубы. После размещения всех кораблей и нажатии кнопки «Начать Бой!», собственно говоря, начинается игра (рис.2):
Рисунок 2 – Начало «боевых» действий
Список литературы
Архангельский А.Я. - Полная версия справок по C++Builder и Turbo C++
Павловская Т. C C++ Программирование на языке высокого уровня.
Седжвик Р. Фундаментальные алгоритмы на C++. DiaSoft.
Кубенский. Структуры и алгоритмы обработки данных, объектно-ориентированный подход и реализация на С++.
Пол А. Объектно-ориентированное программирование на С++.
Кениг Э., Му Б. Эффективное программирование на С++.Вильямс.
Приложение А. UML-диаграмма классов
GameBoard |
Cells:GameCell* |
+ Draw(System::Windows::Forms::Panel^ panel):void
+ RemoveBoat(int x, int y, int size, bool vertical):void
+ Draw(System::Windows::Forms::GroupBox^):void
+ RandFill():void
+ Reset():void
+ Fire(int x, int y, bool key):bool
+ Finish():void
|
GameCell |
State:GameCellState |
+ setState(GameCellState state):void
|
Player |
Score:int Combo:int |
+ Fire(int x, int y, bool key): bool
|
Приложение Б. Описания классов
В программном средстве реализовано 3 класса Player, GameCell, GameBoard:
GameCell – отвечает за состояние ячейки игрового поля.
class GameCell {
GameCellState State;
public:
bool Checked; // было попадание в клетку или нет
GameCell();
GameCellState getState();
void setState(GameCellState state);
};
GameBoard – отвечает за расстановку и удаление кораблей, состояние и отображение игрового поля.
class GameBoard {
GameCell** Cells;
public:
static int type1BoatCount; // счетчик кол-ва однопалубных кораблей
static int type2BoatCount; // счетчик кол-ва двухпалубных кораблей
static int type3BoatCount; // счетчик кол-ва трехпалубных кораблей
static int type4BoatCount; // счетчик кол-ва четырехпалубных кораблей
// конструктор с параметром (если hidden, то скрытая карта)
// используется для создания карты врага
GameBoard(bool hidden);
// конструктор копирования
GameBoard(GameBoard& board);
// отобразить игровое поле
void Draw(System::Windows::Forms::Panel^ panel);
// добавление корабля на игровое поле
// возвращает true, если корабль успешно добавлен
bool AddBoat(int x, int y, int size, bool vertical);
// удаление корабля с игрового поля
void RemoveBoat(int x, int y, int size, bool vertical);
// заполнение игрового поля кораблями случайным образом
void RandFill();
// очистить игровое поле
void Reset();
// просмотреть выбранную ячейку
bool Fire(int x, int y, bool key);
// возвращает состояние ячейки
GameCellState GetCellState(int x, int y);
// возвращает состояние ячейки
bool IsCellChecked(int x, int y);
// пусто ли игровое поле
// возвращает true, если пусто, и false в противном случае
bool IsEmpty();
// закончить расстановку кораблей
void Finish();
// деструктор
~GameBoard();
};
Player – отвечает за ведение огня (как для Ai так и для игрока), а также за очки и комбо.
class Player
{
int Score;
int Combo;
public:
GameBoard* enemyBoard; //вражеское поле
bool Turns; //true - ход игрока
int getScore();
int getCombo();
Player(GameBoard* b);
bool Fire(int x, int y, bool key); // огонь по выбранной клетке
};
Приложение В. Фрагменты кода
Form1.h
#pragma once
#include "GameCell.h"
#include "GameBoard.h"
#include "Player.h"
#include "stdlib.h"
#include <time.h>
#include <string.h>
#include <vcclr.h>
#include <windows.h>
#include "Form2.h"
// функция для перевода строки типа System::String в строку char*
char* StringToPChar (System::String^ istr) {
pin_ptr<const wchar_t> wch = PtrToStringChars(istr);
size_t isize = wcslen(wch) + 1;
size_t i = 0;
char* ostr = new char[isize];
wcstombs_s(&i, ostr, isize, wch, _TRUNCATE);
return ostr;
}
namespace Variant15SeaBattle {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
// переменные для расстановки кораблей
GameBoard* gameBoard1 = new GameBoard(false); // открытая карта для игрока
GameBoard* gameBoard2 = new GameBoard(true); // скрытая карта для компьютера
Player* player; // игрок
Player* AI; // бот
// параметры последнего добавленного корабля (для возможности отменить последнее действие)
// эти же переменные используются в бою для
int lastX; // координата x
int lastY; // координата y
int lastSize; // кол-во палуб
bool lastDir; // направление
char* message1 = "Combo: x";
char* message2 = "Score: ";
/// <summary>
/// Сводка для Form1
/// </summary>
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: добавьте код конструктора
//
}
protected:
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::GroupBox^ groupBox1;
private: System::Windows::Forms::GroupBox^ groupBox2;
private: System::Windows::Forms::Panel^ panel1;
private: System::Windows::Forms::Panel^ panel2;
private: System::Windows::Forms::TabControl^ tabControl1;
public: System::Windows::Forms::TabPage^ tabPage1;
private:
private: System::Windows::Forms::TabPage^ tabPage2;
private: System::Windows::Forms::Button^ button2;
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::TextBox^ textBox1;
private: System::Windows::Forms::TextBox^ textBox2;
private: System::Windows::Forms::Button^ button4;
private: System::Windows::Forms::TextBox^ textBox3;
private: System::Windows::Forms::Label^ label3;
private: System::Windows::Forms::Button^ button6;
private: System::Windows::Forms::Button^ button5;
private: System::Windows::Forms::Label^ label4;
private: System::Windows::Forms::Timer^ timer1;
private: System::Windows::Forms::ComboBox^ comboBox1;
private: System::Windows::Forms::Label^ label8;
private: System::Windows::Forms::Label^ label7;
private: System::Windows::Forms::Button^ button7;
private: System::Windows::Forms::TextBox^ textBox4;
private: System::Windows::Forms::Label^ label5;
private: System::Windows::Forms::Label^ label6;
private: System::Windows::Forms::TextBox^ textBox5;
private: System::Windows::Forms::Timer^ timer2;
private: System::Windows::Forms::Button^ button8;
private: System::Windows::Forms::MenuStrip^ menuStrip1;
private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem1;
private: System::ComponentModel::IContainer^ components;
void AITurn() {
int rnd = rand()%3; // в каком из 4х направлений будет стрелять ИИ в случае попадания
// повторяем действия до первого промаха
while (AI->Turns) {
if (AI->getCombo() == 1) {
Sleep(rand()%500+500);
// генерируем координаты случайными образом
lastX = rand()%10;
lastY = rand()%10;
// цикл генерации таких координат, чтобы не было попадания в одну клетку дважды
while ((!AI->enemyBoard->IsCellChecked(lastX, lastY)) ||
(AI->enemyBoard->GetCellState(lastX, lastY) == Damaged)) {
lastX = rand()%10;
lastY = rand()%10;
}
// если ИИ попал по кораблю, то в увеличиваем координату на 1 в случайном направлении
if (AI->Fire(lastX, lastY, false)) {
switch(rnd) {
case 0:
if (lastX == 9) AITurn();
else {
lastX++;
if ((!AI->enemyBoard->IsCellChecked(lastX, lastY)) ||
(AI->enemyBoard->GetCellState(lastX, lastY) == Damaged)) AITurn();
}
break;
case 1:
if (lastX == 0) AITurn();
else {
lastX--;
if ((!AI->enemyBoard->IsCellChecked(lastX, lastY)) ||
(AI->enemyBoard->GetCellState(lastX, lastY) == Damaged)) AITurn();
}
break;
case 2:
if (lastY == 9) AITurn();
else {
lastY++;
if ((!AI->enemyBoard->IsCellChecked(lastX, lastY)) ||
(AI->enemyBoard->GetCellState(lastX, lastY) == Damaged)) AITurn();
}
break;
case 3:
if (lastY == 0) AITurn();
else {
lastY--;
if ((!AI->enemyBoard->IsCellChecked(lastX, lastY)) ||
(AI->enemyBoard->GetCellState(lastX, lastY) == Damaged)) AITurn();
}
break;
}
}
else {
Sleep(rand()%500+500);
player->Turns = true;
AI->Turns = false;
}
}
else {
Sleep(rand()%500+500);
if (AI->Fire(lastX, lastY, false)) {
switch(rnd) {
case 0:
if (lastX == 9) AITurn();
else {
lastX++;
if ((!AI->enemyBoard->IsCellChecked(lastX, lastY)) ||
(AI->enemyBoard->GetCellState(lastX, lastY) == Damaged)) AITurn();
}
break;
case 1:
if (lastX == 0) AITurn();
else {
lastX--;
if ((!AI->enemyBoard->IsCellChecked(lastX, lastY)) ||
(AI->enemyBoard->GetCellState(lastX, lastY) == Damaged)) AITurn();
}
break;
case 2:
if (lastY == 9) AITurn();
else {
lastY++;
if ((!AI->enemyBoard->IsCellChecked(lastX, lastY)) ||
(AI->enemyBoard->GetCellState(lastX, lastY) == Damaged)) AITurn();
}
break;
case 3:
if (lastY == 0) AITurn();
else {
lastY--;
if ((!AI->enemyBoard->IsCellChecked(lastX, lastY)) ||
(AI->enemyBoard->GetCellState(lastX, lastY) == Damaged)) AITurn();
}
break;
}
}
else {
Sleep(rand()%500+500);
player->Turns = true;
AI->Turns = false;
}
}
gameBoard1->Draw(panel1);
}
}
private:
/// <summary>
/// Требуется переменная конструктора.
/// </summary>
#pragma region Windows Form Designer generated code
/// <summary>
/// Обязательный метод для поддержки конструктора - не изменяйте
/// содержимое данного метода при помощи редактора кода.
/// </summary>
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
this->groupBox1 = (gcnew System::Windows::Forms::GroupBox());
this->panel1 = (gcnew System::Windows::Forms::Panel());
this->groupBox2 = (gcnew System::Windows::Forms::GroupBox());
this->panel2 = (gcnew System::Windows::Forms::Panel());
this->tabControl1 = (gcnew System::Windows::Forms::TabControl());
this->tabPage1 = (gcnew System::Windows::Forms::TabPage());
this->comboBox1 = (gcnew System::Windows::Forms::ComboBox());
this->button6 = (gcnew System::Windows::Forms::Button());
this->button5 = (gcnew System::Windows::Forms::Button());
this->label4 = (gcnew System::Windows::Forms::Label());
this->button4 = (gcnew System::Windows::Forms::Button());
this->textBox3 = (gcnew System::Windows::Forms::TextBox());
this->label3 = (gcnew System::Windows::Forms::Label());
this->textBox2 = (gcnew System::Windows::Forms::TextBox());
this->label2 = (gcnew System::Windows::Forms::Label());
this->label1 = (gcnew System::Windows::Forms::Label());
this->textBox1 = (gcnew System::Windows::Forms::TextBox());
this->button2 = (gcnew System::Windows::Forms::Button());
this->button1 = (gcnew System::Windows::Forms::Button());
this->tabPage2 = (gcnew System::Windows::Forms::TabPage());
this->button8 = (gcnew System::Windows::Forms::Button());
this->label8 = (gcnew System::Windows::Forms::Label());
this->label7 = (gcnew System::Windows::Forms::Label());
this->button7 = (gcnew System::Windows::Forms::Button());
this->textBox4 = (gcnew System::Windows::Forms::TextBox());
this->label5 = (gcnew System::Windows::Forms::Label());
this->label6 = (gcnew System::Windows::Forms::Label());
this->textBox5 = (gcnew System::Windows::Forms::TextBox());
this->timer1 = (gcnew System::Windows::Forms::Timer(this->components));
this->timer2 = (gcnew System::Windows::Forms::Timer(this->components));
this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip());
this->toolStripMenuItem1 = (gcnew System::Windows::Forms::ToolStripMenuItem());
this->groupBox1->SuspendLayout();
this->groupBox2->SuspendLayout();
this->tabControl1->SuspendLayout();
this->tabPage1->SuspendLayout();
this->tabPage2->SuspendLayout();
this->menuStrip1->SuspendLayout();
this->SuspendLayout();
//
// groupBox1
//
this->groupBox1->Controls->Add(this->panel1);
this->groupBox1->Location = System::Drawing::Point(12, 27);
this->groupBox1->Name = L"groupBox1";
this->groupBox1->Size = System::Drawing::Size(361, 383);
this->groupBox1->TabIndex = 3;
this->groupBox1->TabStop = false;
this->groupBox1->Text = L" Игрок ";
//
// panel1
//
this->panel1->Location = System::Drawing::Point(6, 19);
this->panel1->Name = L"panel1";
this->panel1->Size = System::Drawing::Size(350, 350);
this->panel1->TabIndex = 0;
this->panel1->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &Form1::panel1_Paint);
//
// groupBox2
//
this->groupBox2->Controls->Add(this->panel2);
this->groupBox2->Location = System::Drawing::Point(405, 27);
this->groupBox2->Name = L"groupBox2";
this->groupBox2->Size = System::Drawing::Size(363, 383);
this->groupBox2->TabIndex = 4;
this->groupBox2->TabStop = false;
this->groupBox2->Text = L" Оппонент (AI) ";
//
// panel2
//
this->panel2->Location = System::Drawing::Point(6, 19);
this->panel2->Name = L"panel2";
this->panel2->Size = System::Drawing::Size(350, 350);
this->panel2->TabIndex = 1;
this->panel2->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &Form1::panel2_Paint);
//
// tabControl1
//
this->tabControl1->Controls->Add(this->tabPage1);
this->tabControl1->Controls->Add(this->tabPage2);
this->tabControl1->Location = System::Drawing::Point(12, 416);
this->tabControl1->Name = L"tabControl1";
this->tabControl1->SelectedIndex = 0;
this->tabControl1->Size = System::Drawing::Size(757, 130);
this->tabControl1->TabIndex = 6;
//
// tabPage1
//
this->tabPage1->Controls->Add(this->comboBox1);
this->tabPage1->Controls->Add(this->button6);
this->tabPage1->Controls->Add(this->button5);
this->tabPage1->Controls->Add(this->label4);
this->tabPage1->Controls->Add(this->button4);
this->tabPage1->Controls->Add(this->textBox3);
this->tabPage1->Controls->Add(this->label3);
this->tabPage1->Controls->Add(this->textBox2);
this->tabPage1->Controls->Add(this->label2);
this->tabPage1->Controls->Add(this->label1);
this->tabPage1->Controls->Add(this->textBox1);
this->tabPage1->Controls->Add(this->button2);
this->tabPage1->Controls->Add(this->button1);
this->tabPage1->Location = System::Drawing::Point(4, 22);
this->tabPage1->Name = L"tabPage1";
this->tabPage1->Padding = System::Windows::Forms::Padding(3);
this->tabPage1->Size = System::Drawing::Size(749, 104);
this->tabPage1->TabIndex = 0;
this->tabPage1->Text = L"Расстановка кораблей";
this->tabPage1->UseVisualStyleBackColor = true;
//
// comboBox1
//
this->comboBox1->FormattingEnabled = true;
this->comboBox1->Items->AddRange(gcnew cli::array< System::Object^ >(2) {L"по вертикали", L"по горизонтали"});
this->comboBox1->Location = System::Drawing::Point(91, 64);
this->comboBox1->Name = L"comboBox1";
this->comboBox1->Size = System::Drawing::Size(109, 21);
this->comboBox1->TabIndex = 15;
this->comboBox1->Text = L"по горизонтали";
//
// button6
//
this->button6->Location = System::Drawing::Point(338, 58);
this->button6->Name = L"button6";
this->button6->Size = System::Drawing::Size(141, 34);
this->button6->TabIndex = 14;
this->button6->Text = L"Очистить поле";
this->button6->UseVisualStyleBackColor = true;
this->button6->Click += gcnew System::EventHandler(this, &Form1::button6_Click);
//
// button5
//
this->button5->Location = System::Drawing::Point(215, 58);
this->button5->Name = L"button5";
this->button5->Size = System::Drawing::Size(117, 34);
this->button5->TabIndex = 13;
this->button5->Text = L"Отменить действие";
this->button5->UseVisualStyleBackColor = true;
this->button5->Click += gcnew System::EventHandler(this, &Form1::button5_Click);
//
// label4
//
this->label4->AutoSize = true;
this->label4->Location = System::Drawing::Point(6, 67);
this->label4->Name = L"label4";
this->label4->Size = System::Drawing::Size(78, 13);
this->label4->TabIndex = 12;
this->label4->Text = L"Направление:";
//
// button4
//
this->button4->Location = System::Drawing::Point(215, 17);
this->button4->Name = L"button4";
this->button4->Size = System::Drawing::Size(117, 35);
this->button4->TabIndex = 11;
this->button4->Text = L"Добавить корабль";
this->button4->UseVisualStyleBackColor = true;
this->button4->Click += gcnew System::EventHandler(this, &Form1::button4_Click);
//
// textBox3
//
this->textBox3->Location = System::Drawing::Point(91, 35);
this->textBox3->MaxLength = 1;
this->textBox3->Name = L"textBox3";
this->textBox3->Size = System::Drawing::Size(42, 20);
this->textBox3->TabIndex = 8;
//
// label3
//
this->label3->AutoSize = true;
this->label3->Location = System::Drawing::Point(6, 39);
this->label3->Name = L"label3";
this->label3->Size = System::Drawing::Size(76, 13);
this->label3->TabIndex = 7;
this->label3->Text = L"Кол-во палуб:";
//
// textBox2
//
this->textBox2->Location = System::Drawing::Point(91, 7);
this->textBox2->MaxLength = 1;
this->textBox2->Name = L"textBox2";
this->textBox2->Size = System::Drawing::Size(42, 20);
this->textBox2->TabIndex = 6;
//
// label2
//
this->label2->AutoSize = true;
this->label2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label2->Location = System::Drawing::Point(139, 10);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(13, 20);
this->label2->TabIndex = 5;
this->label2->Text = L",";
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(6, 10);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(72, 13);
this->label1->TabIndex = 4;
this->label1->Text = L"Координаты:";
//
// textBox1
//
this->textBox1->Location = System::Drawing::Point(158, 6);
this->textBox1->MaxLength = 1;
this->textBox1->Name = L"textBox1";
this->textBox1->Size = System::Drawing::Size(42, 20);
this->textBox1->TabIndex = 2;
//
// button2
//
this->button2->Location = System::Drawing::Point(338, 17);
this->button2->Name = L"button2";
this->button2->Size = System::Drawing::Size(141, 35);
this->button2->TabIndex = 1;
this->button2->Text = L"Расставить корабли случайным образом";
this->button2->UseVisualStyleBackColor = true;
this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
//
// button1
//
this->button1->Location = System::Drawing::Point(571, 35);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(104, 41);
this->button1->TabIndex = 0;
this->button1->Text = L"Начать бой!";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
//
// tabPage2
//
this->tabPage2->Controls->Add(this->button8);
this->tabPage2->Controls->Add(this->label8);
this->tabPage2->Controls->Add(this->label7);
this->tabPage2->Controls->Add(this->button7);
this->tabPage2->Controls->Add(this->textBox4);
this->tabPage2->Controls->Add(this->label5);
this->tabPage2->Controls->Add(this->label6);
this->tabPage2->Controls->Add(this->textBox5);
this->tabPage2->Location = System::Drawing::Point(4, 22);
this->tabPage2->Name = L"tabPage2";
this->tabPage2->Padding = System::Windows::Forms::Padding(3);
this->tabPage2->Size = System::Drawing::Size(749, 104);
this->tabPage2->TabIndex = 1;
this->tabPage2->Text = L"Боевые действия";
this->tabPage2->UseVisualStyleBackColor = true;
//
// button8
//
this->button8->Location = System::Drawing::Point(118, 49);
this->button8->Name = L"button8";
this->button8->Size = System::Drawing::Size(117, 41);
this->button8->TabIndex = 14;
this->button8->Text = L"Огонь по случайному сектору";
this->button8->UseVisualStyleBackColor = true;
this->button8->Click += gcnew System::EventHandler(this, &Form1::button8_Click);
//
// label8
//
this->label8->AutoSize = true;
this->label8->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label8->ForeColor = System::Drawing::Color::Red;
this->label8->Location = System::Drawing::Point(647, 3);
this->label8->Name = L"label8";
this->label8->Size = System::Drawing::Size(56, 20);
this->label8->TabIndex = 13;
this->label8->Text = L"Очки:";
//
// label7
//
this->label7->AutoSize = true;
this->label7->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label7->ForeColor = System::Drawing::Color::Red;
this->label7->Location = System::Drawing::Point(548, 3);
this->label7->Name = L"label7";
this->label7->Size = System::Drawing::Size(83, 20);
this->label7->TabIndex = 12;
this->label7->Text = L"Combo: x";
//
// button7
//
this->button7->Location = System::Drawing::Point(18, 49);
this->button7->Name = L"button7";
this->button7->Size = System::Drawing::Size(94, 41);
this->button7->TabIndex = 11;
this->button7->Text = L"Огонь";
this->button7->UseVisualStyleBackColor = true;
this->button7->Click += gcnew System::EventHandler(this, &Form1::button7_Click);
//
// textBox4
//
this->textBox4->Location = System::Drawing::Point(187, 18);
this->textBox4->MaxLength = 1;
this->textBox4->Name = L"textBox4";
this->textBox4->Size = System::Drawing::Size(42, 20);
this->textBox4->TabIndex = 10;
//
// label5
//
this->label5->AutoSize = true;
this->label5->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(204)));
this->label5->Location = System::Drawing::Point(168, 16);
this->label5->Name = L"label5";
this->label5->Size = System::Drawing::Size(13, 20);
this->label5->TabIndex = 9;
this->label5->Text = L",";
//
// label6
//
this->label6->AutoSize = true;
this->label6->Location = System::Drawing::Point(15, 21);
this->label6->Name = L"label6";
this->label6->Size = System::Drawing::Size(99, 13);
this->label6->TabIndex = 8;
this->label6->Text = L"Огонь по сектору:";
//
// textBox5
//
this->textBox5->Location = System::Drawing::Point(120, 18);
this->textBox5->MaxLength = 1;
this->textBox5->Name = L"textBox5";
this->textBox5->Size = System::Drawing::Size(42, 20);
this->textBox5->TabIndex = 7;
//
// timer1
//
this->timer1->Enabled = true;
this->timer1->Interval = 10;
this->timer1->Tick += gcnew System::EventHandler(this, &Form1::timer1_Tick);
//
// timer2
//
this->timer2->Interval = 1;
this->timer2->Tick += gcnew System::EventHandler(this, &Form1::timer2_Tick);
//
// menuStrip1
//
this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(1) {this->toolStripMenuItem1});
this->menuStrip1->Location = System::Drawing::Point(0, 0);
this->menuStrip1->Name = L"menuStrip1";
this->menuStrip1->Size = System::Drawing::Size(781, 24);
this->menuStrip1->TabIndex = 7;
this->menuStrip1->Text = L"menuStrip1";
//
// toolStripMenuItem1
//
this->toolStripMenuItem1->Name = L"toolStripMenuItem1";
this->toolStripMenuItem1->ShortcutKeys = System::Windows::Forms::Keys::F1;
this->toolStripMenuItem1->Size = System::Drawing::Size(62, 20);
this->toolStripMenuItem1->Text = L"Справка";
this->toolStripMenuItem1->Click += gcnew System::EventHandler(this, &Form1::toolStripMenuItem1_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(781, 556);
this->Controls->Add(this->tabControl1);
this->Controls->Add(this->groupBox2);
this->Controls->Add(this->groupBox1);
this->Controls->Add(this->menuStrip1);
this->MainMenuStrip = this->menuStrip1;
this->Name = L"Form1";
this->Text = L"Морской бой";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->groupBox1->ResumeLayout(false);
this->groupBox2->ResumeLayout(false);
this->tabControl1->ResumeLayout(false);
this->tabPage1->ResumeLayout(false);
this->tabPage1->PerformLayout();
this->tabPage2->ResumeLayout(false);
this->tabPage2->PerformLayout();
this->menuStrip1->ResumeLayout(false);
this->menuStrip1->PerformLayout();
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private: System::Void panel1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) {
gameBoard1->Draw(panel1);
}
private: System::Void panel2_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) {
gameBoard2->Draw(panel2);
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
srand((unsigned int)time(NULL));
gameBoard2->RandFill();
GameBoard::type1BoatCount = 0;
GameBoard::type2BoatCount = 0;
GameBoard::type3BoatCount = 0;
GameBoard::type4BoatCount = 0;
button1->Enabled = false;
tabPage2->Enabled = false;
button5->Enabled = false;
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
gameBoard1->RandFill();
GameBoard::type1BoatCount = 4;
GameBoard::type2BoatCount = 3;
GameBoard::type3BoatCount = 2;
GameBoard::type4BoatCount = 1;
lastX = -1;
lastY = -1;
lastSize = -1;
lastDir = false;
button5->Enabled = false;
gameBoard1->Draw(panel1);
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
tabPage1->Enabled = false;
tabPage2->Enabled = true;
gameBoard1->Finish();
gameBoard2->Finish();
gameBoard1->Draw(panel1);
timer1->Enabled = false;
timer2->Enabled = true;
// создаем экземпляры класса "игрок"
player = new Player(gameBoard2);
AI = new Player(gameBoard1);
// выставляем ключи - игрок ходит, компьютер не ходит
// можно поменять, чтобы ИИ ходил первым
player->Turns = true;
AI->Turns = false;
// выводим значения combo и score на label'ы
char* message = new char[50];
char* buf = new char[4];
strcpy(message, message1);
strcat(message, itoa(player->getCombo(), buf, 10));
label7->Text = gcnew String(message);
delete message;
delete buf;
message = new char[50];
buf = new char[10];
strcpy(message, message2);
strcat(message, itoa(player->getScore(), buf, 10));
label8->Text = gcnew String(message);
delete message;
delete buf;
}
private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) {
char* xvalue = new char;
char* yvalue = new char;
char* sizevalue = new char;
xvalue = StringToPChar(textBox1->Text);
yvalue = StringToPChar(textBox2->Text);
sizevalue = StringToPChar(textBox3->Text);
switch (atoi(sizevalue)) {
case 1:
if (GameBoard::type1BoatCount == 4) {
MessageBox::Show("Невозможно добавить более 4 однопалубных кораблей!",
"Ошибка");
break;
}
else {
if (comboBox1->Text == "по горизонтали")
if(!gameBoard1->AddBoat(atoi(yvalue), atoi(xvalue), atoi(sizevalue), false))
MessageBox::Show("Невозможно разместить корабль на поле! Проверьте правильность введенных данных",
"Ошибка");
else {
GameBoard::type1BoatCount++;
lastX = atoi(xvalue);
lastY = atoi(yvalue);
lastSize = atoi(sizevalue);
lastDir = false;
button5->Enabled = true;
}
else
if(!gameBoard1->AddBoat(atoi(yvalue), atoi(xvalue), atoi(sizevalue), true))
MessageBox::Show("Невозможно разместить корабль на поле! Проверьте правильность введенных данных",
"Ошибка");
else {
GameBoard::type1BoatCount++;
lastX = atoi(xvalue);
lastY = atoi(yvalue);
lastSize = atoi(sizevalue);
lastDir = true;
button5->Enabled = true;
}
gameBoard1->Draw(panel1);
break;
}
case 2:
if (GameBoard::type2BoatCount == 3) {
MessageBox::Show("Невозможно добавить более 3 двухпалубных кораблей!",
"Ошибка");
break;
}
else {
if (comboBox1->Text == "по горизонтали")
if(!gameBoard1->AddBoat(atoi(yvalue), atoi(xvalue), atoi(sizevalue), false))
MessageBox::Show("Невозможно разместить корабль на поле! Проверьте правильность введенных данных",
"Ошибка");
else {
GameBoard::type2BoatCount++;
lastX = atoi(xvalue);
lastY = atoi(yvalue);
lastSize = atoi(sizevalue);
lastDir = false;
button5->Enabled = true;
}
else
if(!gameBoard1->AddBoat(atoi(yvalue), atoi(xvalue), atoi(sizevalue), true))
MessageBox::Show("Невозможно разместить корабль на поле! Проверьте правильность введенных данных",
"Ошибка");
else {
GameBoard::type2BoatCount++;
lastX = atoi(xvalue);
lastY = atoi(yvalue);
lastSize = atoi(sizevalue);
lastDir = true;
button5->Enabled = true;
}
gameBoard1->Draw(panel1);
break;
}
case 3:
if (GameBoard::type3BoatCount == 2) {
MessageBox::Show("Невозможно добавить более 2 трехпалубных кораблей!",
"Ошибка");
break;
}
else {
if (comboBox1->Text == "по горизонтали")
if(!gameBoard1->AddBoat(atoi(yvalue), atoi(xvalue), atoi(sizevalue), false))
MessageBox::Show("Невозможно разместить корабль на поле! Проверьте правильность введенных данных",
"Ошибка");
else {
GameBoard::type3BoatCount++;
lastX = atoi(xvalue);
lastY = atoi(yvalue);
lastSize = atoi(sizevalue);
lastDir = false;
button5->Enabled = true;
}
else
if(!gameBoard1->AddBoat(atoi(yvalue), atoi(xvalue), atoi(sizevalue), true))
MessageBox::Show("Невозможно разместить корабль на поле! Проверьте правильность введенных данных",
"Ошибка");
else {
GameBoard::type3BoatCount++;
lastX = atoi(xvalue);
lastY = atoi(yvalue);
lastSize = atoi(sizevalue);
lastDir = true;
button5->Enabled = true;
}
gameBoard1->Draw(panel1);
break;
}
case 4:
if (GameBoard::type4BoatCount == 1) {
MessageBox::Show("Невозможно добавить более 1 четырехпалубного корабля!",
"Ошибка");
break;
}
else {
if (comboBox1->Text == "по горизонтали")
if(!gameBoard1->AddBoat(atoi(yvalue), atoi(xvalue), atoi(sizevalue), false))
MessageBox::Show("Невозможно разместить корабль на поле! Проверьте правильность введенных данных",
"Ошибка");
else {
GameBoard::type4BoatCount++;
lastX = atoi(xvalue);
lastY = atoi(yvalue);
lastSize = atoi(sizevalue);
lastDir = false;
button5->Enabled = true;
}
else
if(!gameBoard1->AddBoat(atoi(yvalue), atoi(xvalue), atoi(sizevalue), true))
MessageBox::Show("Невозможно разместить корабль на поле! Проверьте правильность введенных данных",
"Ошибка");
else {
GameBoard::type4BoatCount++;
lastX = atoi(xvalue);
lastY = atoi(yvalue);
lastSize = atoi(sizevalue);
lastDir = true;
button5->Enabled = true;
}
gameBoard1->Draw(panel1);
break;
}
}
}
private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e) {
if ((textBox1->Text == "") || (textBox2->Text == "")
|| (textBox3->Text == "") || (comboBox1->Text == "")
|| ((GameBoard::type1BoatCount == 4) && (GameBoard::type2BoatCount == 3)
&& (GameBoard::type3BoatCount == 2) && (GameBoard::type4BoatCount == 1))) button4->Enabled = false;
else button4->Enabled = true;
if ((GameBoard::type1BoatCount == 4) && (GameBoard::type2BoatCount == 3)
&& (GameBoard::type3BoatCount == 2) && (GameBoard::type4BoatCount == 1)) button1->Enabled = true;
else button1->Enabled = false;
if (gameBoard1->IsEmpty()) button6->Enabled = false;
else button6->Enabled = true;
}
private: System::Void button6_Click(System::Object^ sender, System::EventArgs^ e) {
gameBoard1->Reset();
GameBoard::type1BoatCount = 0;
GameBoard::type2BoatCount = 0;
GameBoard::type3BoatCount = 0;
GameBoard::type4BoatCount = 0;
gameBoard1->Draw(panel1);
}
private: System::Void button5_Click(System::Object^ sender, System::EventArgs^ e) {
gameBoard1->RemoveBoat(lastY, lastX, lastSize, lastDir);
switch(lastSize) {
case 1:
GameBoard::type1BoatCount--;
break;
case 2:
GameBoard::type2BoatCount--;
break;
case 3:
GameBoard::type3BoatCount--;
break;
case 4:
GameBoard::type4BoatCount--;
break;
}
lastX = -1;
lastY = -1;
lastSize = -1;
lastDir = false;
button5->Enabled = false;
gameBoard1->Draw(panel1);
}
private: System::Void button7_Click(System::Object^ sender, System::EventArgs^ e) {
if (player->Turns) {
// считываем значения из textBox'ов
char* xvalue = new char;
char* yvalue = new char;
xvalue = StringToPChar(textBox4->Text);
yvalue = StringToPChar(textBox5->Text);
// делаем выстрел по полю ИИ
if (player->Fire(atoi(yvalue), atoi(xvalue), true)) {
// в случае попадания перерисовываем поле ИИ
gameBoard2->Draw(panel2);
}
else { // в случае попадания перерисовываем поле ИИ меняем ключи
gameBoard2->Draw(panel2);
player->Turns = false;
AI->Turns = true;
// ход ИИ
AITurn();
}
}
// деактивируем кнопки выстрела, пока длится ход ИИ
button7->Enabled = false;
button8->Enabled = false;
// выводим значения combo и score на label'ы
char* message = new char[255];
char* buf = new char[2];
strcpy(message, message1);
strcat(message, itoa(player->getCombo(), buf, 10));
label7->Text = gcnew String(message);
delete message;
delete buf;
message = new char[50];
buf = new char[10];
strcpy(message, message2);
strcat(message, itoa(player->getScore(), buf, 10));
label8->Text = gcnew String(message);
delete message;
delete buf;
// делаем проверку, все ли корабли уничтожены на поле игрока
if (AI->enemyBoard->IsEmpty()) {
MessageBox::Show("Компьютер победил", "Поражение :(");
this->Close();
}
// делаем проверку, все ли корабли уничтожены на поле ИИ
if (player->enemyBoard->IsEmpty()) {
MessageBox::Show("Игрок победил", "Победа! :)");
this->Close();
}
}
private: System::Void timer2_Tick(System::Object^ sender, System::EventArgs^ e) {
if (player->Turns) {
button7->Enabled = true;
button8->Enabled = true;
}
if ((textBox5->Text == "") || (textBox4->Text == "")) button7->Enabled = false;
else button7->Enabled = true;
}
private: System::Void button8_Click(System::Object^ sender, System::EventArgs^ e) {
if (player->Turns) {
// генерируем координаты случайными образом
int x = rand()%10;
int y = rand()%10;
// если в такую клетку уже было попадание, то генерируем координаты до тех пор
// пока не сгенерируются координаты еще не пробитой клетки
while ((player->enemyBoard->IsCellChecked(y, x)) ||
(player->enemyBoard->GetCellState(y, x) == Damaged)) {
x = rand()%10;
y = rand()%10;
}
// в случае попадания перерисовываем игровое поле
if (player->Fire(y, x, true)) {
gameBoard2->Draw(panel2);
}
else { // в случае промаха перерисовываем игровое поле и меняем ключи
gameBoard2->Draw(panel2);
player->Turns = false;
AI->Turns = true;
// ход ИИ
AITurn();
}
}
// деактивируем кнопки выстрела, пока длится ход ИИ
button7->Enabled = false;
button8->Enabled = false;
// выводим значения combo и score на label'ы
char* message = new char[50];
char* buf = new char[4];
strcpy(message, message1);
strcat(message, itoa(player->getCombo(), buf, 10));
label7->Text = gcnew String(message);
delete message;
delete buf;
message = new char[50];
buf = new char[10];
strcpy(message, message2);
strcat(message, itoa(player->getScore(), buf, 10));
label8->Text = gcnew String(message);
delete message;
delete buf;
// делаем проверку, все ли корабли уничтожены на поле игрока
if (AI->enemyBoard->IsEmpty()) {
MessageBox::Show("Компьютер победил", "Поражение :(");
this->Close();
}
// делаем проверку, все ли корабли уничтожены на поле ИИ
if (player->enemyBoard->IsEmpty()) {
MessageBox::Show("Игрок победил", "Победа! :)");
this->Close();
}
}
private: System::Void toolStripMenuItem1_Click(System::Object^ sender, System::EventArgs^ e) {
Form2^ helpform = gcnew Form2();
helpform->Show();
}
};
}