Форум программистов, компьютерный форум, киберфорум
C++/CLI Windows Forms
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
Другие темы раздела
C++/CLI WinForms Как передать из события TextBox на обработчик имена других TextBox и Label? https://www.cyberforum.ru/ cpp-cli-winforms/ thread1212605.html
Задачка такая: есть несколько рядов TextBox, содержимое их их надо, например, сложить и поместить в соответствующую метку. Делаться это должно не после заполнения всех TextBox (не через кнопку), а в процессе. Содержимое TextBox-ов складывается и помещается в нужную метку в обработчике. Для этого надо из события TextBox TextChanged пересылать на обработчик не только имя текущего TextBox, но и...
Как организовать построчный перенос текста из RichTextBox в TextBox? C++/CLI WinForms
Сабж, есть текстовой файл с многострочной информацией вида 123456|1|2|345| я его загружаю в richtextbox затем из richtextbox нужно перенести каждое значение между разделителей "|" в отдельные textbox'ы, есть какая либо литература по этому вопросу, или какие-либо подсказки от комьюнити?
C++/CLI WinForms Не могу сменить значение приватного поля DoubleBuffered На форме есть компонент Panel, в нем отрисовываю всякое. Хотел убрать мерцание с помощью включения двойной буферизации, но в дизайнере я не нашел этого параметра, у него модификатор "protected", по этому при попытке изменения его в коде я получаю ошибку: error C3767: 'System::Windows::Forms::Control::DoubleBuffered::set': candidate function(s) not accessible. Последнее, что я мог попробовать -... https://www.cyberforum.ru/ cpp-cli-winforms/ thread1211850.html C++/CLI WinForms Работа с BMP файлом считывание с файла в масивpublic: int *loadBMP( const char *fname, int &mx, int &my ) { int *v; mx = my = -1; FILE *f = fopen( fname, "rb" ); if( !f ) return NULL; BMPheader bh; // File header sizeof(BMPheader) = 56 size_t res; // читаем заголовок res = fread( &bh, 1, sizeof(BMPheader), f ); https://www.cyberforum.ru/ cpp-cli-winforms/ thread1211090.html
Работа с точкой: ввод с цифровой клавиатуры C++/CLI WinForms
При вводе в текст боксы числа запятой, он компилятор требует именно запятую. Но мне удобнее вводить числа с правой стороны клавы ( привычка от калькуляторов). Но кнопка " delete " ставит там именно точку, и жутко неудобно, особенно когда вводишь какие-нить большие числа..как сделать так, чтобы прога не вылетала, а нормально работала с точкой вместо запятой?
C++/CLI WinForms Реализация взаимодействия между двумя формами Всем доброго времени суток! Помогите пожалуйста решить следующею проблему. Имеется класс Messenger который работает с COM портом (ссылка на порт передается в конструктор). Также имеется приложение с двумя формами: одна главная, вторая дочерняя которая служит для настройки порта. Я делал следующее: Первое: С начала хотел объявлять класс родительской формы(главной) в дочерней так:... https://www.cyberforum.ru/ cpp-cli-winforms/ thread1210578.html
C++/CLI WinForms Нарисовать гарфик экспоненциальной функции C++/CLI Помогите найти ошибку, пожалуйста! Нужно нарисовать график функции y=exp(-xk). int x0, y0, x, y, xc; double kx, ky, Xmax, Ymax, Ymin, k; Ymax = 1; Ymin = 0.9; k=0.0003; Xmax = -Math::Log(Ymax)/k; kx=pictureBox1->Size.Width/Xmax; ky=pictureBox1->Size.Height/(Ymax-Ymin); ... https://www.cyberforum.ru/ cpp-cli-winforms/ thread1209682.html Подписаться на событие KeyPress для TextBox C++/CLI WinForms
есть несколько текстбоксов, в них можно вводить цифры, разделитеть и бэкспейс. Сам обработчик уменя есть (функция обработчик_KeyPress), но не могу подписать на него события KeyPress из TextBox-ов. И откуда создавать, из Form1_Load или textBox_KeyPress? Вот код: ... ... ... this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion String^ ТчкИлиЗпт;
C++/CLI WinForms Переделать консольную программу под формы Здравствуйте, имеется консольная программа, осуществляющая сжатие данных методом LZW кодирования. Нужно переписать ее, чтобы она работала через форму. Как это можно сделать? Вот код программы: #include <stdio.h> #include <string.h> #include <stdlib.h> #define STR_FILE_IN_NAME "input.txt" #define STR_FILE_OUT_NAME "output.txt" #define BITS_IN_CODE 12 #define TABLE_SIZE 4095 https://www.cyberforum.ru/ cpp-cli-winforms/ thread1207630.html C++/CLI WinForms Проверка ввода в Textbox https://www.cyberforum.ru/ cpp-cli-winforms/ thread1207263.html
Итак, есть код, который позволяет вводить в TextBox только цифры и буквы от A до F. Но мне нужно: 1. Изначально переключить программно язык с русского на английский. 2. Чтобы при ручном вводе после каждого ПЯТОГО символа АВТОМАТИЧЕСКИ ставился пробел. private:bool nonNumberEntered; private: System::Void textBox1_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) ...
C++/CLI WinForms Как открыть диалоговое окно по клику в PictureBox?
Добрый вечер! Есть PictureBox с картинкой. Нужно чтобы при клике на него открывало или в новом диалоговом окне, или в другой форме определенную картинку с определенной папки. Как это реализовать на Visual C++? Раб
13 / 13 / 6
Регистрация: 07.02.2013
Сообщений: 214
0

Покритикуйте код "Змейки" - C++/CLI WinForms - Ответ 6349139

22.06.2014, 00:00. Показов 2309. Ответов 4
Метки (Все метки)

Author24 — интернет-сервис помощи студентам
Создал примитивную игру "Змейка". Есть управление мышкой для тех, кто не любит честно играть.
Код:

mf.h
Кликните здесь для просмотра всего текста

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
230
231
232
233
234
235
236
237
238
239
240
241
242
#pragma once
 
namespace snake {
 
    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Collections::Generic;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;
 
    /// <summary>
    /// Summary for mf
    /// </summary>
    public ref class mf : public System::Windows::Forms::Form
    {
    public:
        mf(void)
        {
            InitializeComponent();
        }
 
    protected:
        /// <summary>
        /// Clean up all resources being used.
        /// </summary>
        ~mf()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::Timer^  timer1;
    private: System::Windows::Forms::StatusStrip^  statusStrip1;
    private: System::Windows::Forms::ToolStripStatusLabel^  toolStripStatusLabel1;
    private: System::Windows::Forms::ToolStripStatusLabel^  cwidth;
    private: System::Windows::Forms::ToolStripStatusLabel^  toolStripStatusLabel3;
    private: System::Windows::Forms::ToolStripStatusLabel^  cheight;
    private: System::Windows::Forms::ToolStripStatusLabel^  toolStripStatusLabel5;
    private: System::Windows::Forms::ToolStripStatusLabel^  score;
    private: System::Windows::Forms::ToolStripStatusLabel^  toolStripStatusLabel7;
    private: System::Windows::Forms::ToolStripStatusLabel^  speed;
    private: System::Windows::Forms::ToolStripStatusLabel^  toolStripStatusLabel2;
    private: System::Windows::Forms::ToolStripStatusLabel^  lmouse;
    private: System::Windows::Forms::ToolStripStatusLabel^  toolStripStatusLabel4;
    private: System::Windows::Forms::ToolStripStatusLabel^  ldir;
 
    private: System::ComponentModel::IContainer^  components;
 
    private:
        /// <summary>
        /// Required designed variable.
        /// </summary>
 
 
#pragma region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            this->components = (gcnew System::ComponentModel::Container());
            this->timer1 = (gcnew System::Windows::Forms::Timer(this->components));
            this->statusStrip1 = (gcnew System::Windows::Forms::StatusStrip());
            this->toolStripStatusLabel1 = (gcnew System::Windows::Forms::ToolStripStatusLabel());
            this->cwidth = (gcnew System::Windows::Forms::ToolStripStatusLabel());
            this->toolStripStatusLabel3 = (gcnew System::Windows::Forms::ToolStripStatusLabel());
            this->cheight = (gcnew System::Windows::Forms::ToolStripStatusLabel());
            this->toolStripStatusLabel5 = (gcnew System::Windows::Forms::ToolStripStatusLabel());
            this->score = (gcnew System::Windows::Forms::ToolStripStatusLabel());
            this->toolStripStatusLabel7 = (gcnew System::Windows::Forms::ToolStripStatusLabel());
            this->speed = (gcnew System::Windows::Forms::ToolStripStatusLabel());
            this->toolStripStatusLabel2 = (gcnew System::Windows::Forms::ToolStripStatusLabel());
            this->lmouse = (gcnew System::Windows::Forms::ToolStripStatusLabel());
            this->toolStripStatusLabel4 = (gcnew System::Windows::Forms::ToolStripStatusLabel());
            this->ldir = (gcnew System::Windows::Forms::ToolStripStatusLabel());
            this->statusStrip1->SuspendLayout();
            this->SuspendLayout();
            // 
            // timer1
            // 
            this->timer1->Enabled = true;
            // 
            // statusStrip1
            // 
            this->statusStrip1->BackColor = System::Drawing::Color::White;
            this->statusStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^  >(12) {
                this->toolStripStatusLabel1,
                    this->cwidth, this->toolStripStatusLabel3, this->cheight, this->toolStripStatusLabel5, this->score, this->toolStripStatusLabel7,
                    this->speed, this->toolStripStatusLabel2, this->lmouse, this->toolStripStatusLabel4, this->ldir
            });
            this->statusStrip1->Location = System::Drawing::Point(0, 371);
            this->statusStrip1->Name = L"statusStrip1";
            this->statusStrip1->Size = System::Drawing::Size(620, 22);
            this->statusStrip1->TabIndex = 0;
            this->statusStrip1->Text = L"statusStrip1";
            // 
            // toolStripStatusLabel1
            // 
            this->toolStripStatusLabel1->BackColor = System::Drawing::SystemColors::Control;
            this->toolStripStatusLabel1->Font = (gcnew System::Drawing::Font(L"Segoe UI", 9, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(204)));
            this->toolStripStatusLabel1->Name = L"toolStripStatusLabel1";
            this->toolStripStatusLabel1->Size = System::Drawing::Size(42, 17);
            this->toolStripStatusLabel1->Text = L"Width:";
            // 
            // cwidth
            // 
            this->cwidth->BackColor = System::Drawing::SystemColors::Control;
            this->cwidth->Name = L"cwidth";
            this->cwidth->Size = System::Drawing::Size(13, 17);
            this->cwidth->Text = L"1";
            // 
            // toolStripStatusLabel3
            // 
            this->toolStripStatusLabel3->BackColor = System::Drawing::SystemColors::Control;
            this->toolStripStatusLabel3->Name = L"toolStripStatusLabel3";
            this->toolStripStatusLabel3->Size = System::Drawing::Size(46, 17);
            this->toolStripStatusLabel3->Text = L"Height:";
            // 
            // cheight
            // 
            this->cheight->BackColor = System::Drawing::SystemColors::Control;
            this->cheight->Name = L"cheight";
            this->cheight->Size = System::Drawing::Size(13, 17);
            this->cheight->Text = L"1";
            // 
            // toolStripStatusLabel5
            // 
            this->toolStripStatusLabel5->BackColor = System::Drawing::SystemColors::Control;
            this->toolStripStatusLabel5->Name = L"toolStripStatusLabel5";
            this->toolStripStatusLabel5->Size = System::Drawing::Size(39, 17);
            this->toolStripStatusLabel5->Text = L"Score:";
            // 
            // score
            // 
            this->score->BackColor = System::Drawing::SystemColors::Control;
            this->score->Name = L"score";
            this->score->Size = System::Drawing::Size(13, 17);
            this->score->Text = L"0";
            // 
            // toolStripStatusLabel7
            // 
            this->toolStripStatusLabel7->BackColor = System::Drawing::SystemColors::Control;
            this->toolStripStatusLabel7->Name = L"toolStripStatusLabel7";
            this->toolStripStatusLabel7->Size = System::Drawing::Size(42, 17);
            this->toolStripStatusLabel7->Text = L"Speed:";
            // 
            // speed
            // 
            this->speed->BackColor = System::Drawing::SystemColors::Control;
            this->speed->Name = L"speed";
            this->speed->Size = System::Drawing::Size(13, 17);
            this->speed->Text = L"1";
            // 
            // toolStripStatusLabel2
            // 
            this->toolStripStatusLabel2->Name = L"toolStripStatusLabel2";
            this->toolStripStatusLabel2->Size = System::Drawing::Size(46, 17);
            this->toolStripStatusLabel2->Text = L"Mouse:";
            // 
            // lmouse
            // 
            this->lmouse->Name = L"lmouse";
            this->lmouse->Size = System::Drawing::Size(33, 17);
            this->lmouse->Text = L"False";
            // 
            // toolStripStatusLabel4
            // 
            this->toolStripStatusLabel4->Name = L"toolStripStatusLabel4";
            this->toolStripStatusLabel4->Size = System::Drawing::Size(58, 17);
            this->toolStripStatusLabel4->Text = L"Direction:";
            // 
            // ldir
            // 
            this->ldir->Name = L"ldir";
            this->ldir->Size = System::Drawing::Size(0, 17);
            // 
            // mf
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->BackColor = System::Drawing::Color::White;
            this->ClientSize = System::Drawing::Size(620, 393);
            this->Controls->Add(this->statusStrip1);
            this->DoubleBuffered = true;
            this->KeyPreview = true;
            this->MaximizeBox = false;
            this->Name = L"mf";
            this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen;
            this->Text = L"Snake";
            this->Load += gcnew System::EventHandler(this, &mf::mf_Load);
            this->statusStrip1->ResumeLayout(false);
            this->statusStrip1->PerformLayout();
            this->ResumeLayout(false);
            this->PerformLayout();
 
        }
#pragma endregion
 
    private: void mf_Load(System::Object^  sender, System::EventArgs^  e);
    private: void addHandlers();
    private: void paint(Object^ sender, PaintEventArgs^ e);
    private: void tick(Object^ sender, EventArgs^ e);
    private: void key_press(Object^ sender, KeyEventArgs^ e);
    private: void resize(Object^ sender, EventArgs^ e);
    private: void resize_ref(Object^ sender, EventArgs^ e);
    private: void mouse_move(Object^ sender, MouseEventArgs^ e);
 
    private: int SmartRandom(int min, int max, int multiplier);
    private: void checkCollision();
    private: void placeApple();
    private: void newGame();
    private: void gameOver();
    private: void findPath(int x, int y);
 
    private: Byte dir; //0 - left, 1 - up, 2 - right, 3 - down
    private: List<Point>^ snake = gcnew List<Point>();
    private: List<int>^ moves = gcnew List<int>(3);
    private: int distance = 2;
    private: int step = 10;
    private: int stp = step + distance;
    private: Pen^ pen = gcnew Pen(Color::Blue);
    private: Pen^ iPen = gcnew Pen(Color::LimeGreen);
    private: Random^ rnd = gcnew Random();
    private: Point apple;
    private: int vscore = 0;
    private: int vspeed = 1;
    private: bool game_over = false;
    private: bool mouse = false;
    private: bool filled = false;
    private: List<Point>^ path = gcnew List<Point>();
 
    };
 
    public enum class Directions {
        Left, Up, Right, Down
    };
}


mf.cpp
Кликните здесь для просмотра всего текста

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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
#include "mf.h"
 
using namespace snake;
 
int main(array<String^>^ arg) {
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);
    mf form;
    Application::Run(%form);
 
    return 0;
}
 
void mf::mf_Load(Object^ sender, EventArgs^ e) {
    resize(this, gcnew EventArgs());
    placeApple();
    dir = rnd->Next(3);
 
    for (int a = 0; a < 3; a++)
        snake->Add(Point(Math::Round(this->ClientRectangle.Width / (2*stp))*stp, Math::Round(this->ClientRectangle.Height / (2*stp))*stp));
    
    ldir->Text = ((Directions)dir).ToString();
    addHandlers();
    Refresh();
}
 
void mf::addHandlers() {
    this->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &snake::mf::paint);
    timer1->Tick += gcnew System::EventHandler(this, &snake::mf::tick);
    this->KeyUp += gcnew System::Windows::Forms::KeyEventHandler(this, &snake::mf::key_press);
    this->ResizeEnd += gcnew EventHandler(this, &snake::mf::resize);
    this->Resize += gcnew EventHandler(this, &snake::mf::resize_ref);
    this->MouseMove += gcnew System::Windows::Forms::MouseEventHandler(this, &snake::mf::mouse_move);
}
 
void mf::paint(Object^ sender, PaintEventArgs^ e) {
    //rendering snake, apple and wall
    Graphics^ g = e->Graphics;
    g->DrawRectangle(gcnew Pen(Color::Black, 12), stp/2, stp/2, this->ClientRectangle.Width - stp, this->ClientRectangle.Height - 3*stp);
 
    if (game_over) return;
    Color clr = Color::Red;
 
    for (int a = 0; a < snake->Count; a++) {
        int x = snake[a].X;
        int y = snake[a].Y;
 
        if (a == 0) clr = Color::Red;
            else clr = Color::Blue;
 
        pen->Color = clr;
 
        if (filled) {
            g->FillRectangle(pen->Brush, x, y, step, step);
            g->FillRectangle(iPen->Brush, apple.X, apple.Y, step, step);
        }
        else {
            g->DrawRectangle(pen, x, y, step, step);
            g->DrawRectangle(iPen, apple.X, apple.Y, step, step);
        }
    }
}
 
void mf::tick(Object^ sender, EventArgs^ e) {
    //mouse mode
    if (mouse) {
        if (path->Count > 0) {
            for (int a = snake->Count - 1; a > 0; a--) {
                snake[a] = snake[a - 1];
            }
 
            snake[0] = path[0];
            path->RemoveAt(0);
        }
        checkCollision();
        Refresh();
        return;
    }
 
    //keyboard mode
    if (moves->Count == 0) moves->Add(dir);
 
    for (int a = snake->Count - 1; a > 0; a--) {
        snake[a] = snake[a - 1];
    }
 
    Point temp = snake[0];
 
    switch (moves[0]) {
        case 0: temp.X -= stp;
            break;
        case 1: temp.Y -= stp;
            break;
        case 2: temp.X += stp;
            break;
        case 3: temp.Y += stp;
            break;
    }
    moves->RemoveAt(0);
 
    snake[0] = temp;
    checkCollision();
    Refresh();
}
 
void mf::key_press(Object^ sender, KeyEventArgs^ e) {
    //pause or resume game
    if (e->KeyCode == Keys::P) timer1->Enabled = !timer1->Enabled;
 
    //new game
    if (e->KeyCode == Keys::N) {
        newGame();
    }
 
    //switch mouse control
    if (e->KeyCode == Keys::M) {
        mouse = !mouse;
        lmouse->Text = mouse.ToString();
    }
 
    if (e->KeyCode == Keys::F) {
        filled = !filled;
        Refresh();
    }
 
    //exit function if mouse control is switched ob
    if (mouse) return;
 
    //changing direction
    int val = e->KeyValue;
    if (val >= 37 && val <= 40)
        if (Math::Abs(dir - val + 37) != 2)
            if (moves->Count < 3) {
                moves->Add(val - 37);
                dir = val - 37;
            }
            else {
                moves->RemoveAt(0);
                moves->Add(val - 37);
                dir = val - 37;
            }
 
    ldir->Text = ((Directions)dir).ToString();
}
 
int mf::SmartRandom(int min, int max, int multiplier) {
    //get random number, which is a multiple of 'multiplier'
    int lowBound = (int)Math::Ceiling(min / (double)multiplier);
    int highBound = (int)Math::Floor(max / (double)multiplier);
 
    return (rnd->Next(highBound - lowBound + 1) + lowBound) * multiplier;
}
 
void mf::checkCollision() {
    //checking collision with an apple or a wall or a snake
    Point head = snake[0];
    if (apple == head) {
        placeApple();
        vscore += 10;
        if (vspeed < 100)
        vspeed += 5;
        timer1->Interval = 102 - vspeed;
 
        score->Text = vscore.ToString();
        speed->Text = vspeed.ToString();
 
        snake->Add(snake[snake->Count - 1]);
    }
 
    if (snake->LastIndexOf(head) != 0 && !mouse) {
        gameOver();
    }
 
    if (head.X >= this->ClientRectangle.Width - stp || head.X < stp || head.Y >= this->ClientRectangle.Height - 3 * stp || head.Y < stp) {
        gameOver();
    }
}
 
void mf::newGame() {
    moves->Clear();
    dir = rnd->Next(3);
    snake->Clear();
    int px = Math::Round(this->ClientRectangle.Width / 24) * stp;
    int py = Math::Round(this->ClientRectangle.Height / (2 * stp)) * stp;
    for (int a = 0; a < 3; a++)
        snake->Add(Point(px, py));
 
    vscore = 0;
    vspeed = 1;
    timer1->Interval = 102 - vspeed;
    score->Text = "0";
    speed->Text = vspeed.ToString();
    game_over = false;
    placeApple();
    findPath(px, py);
    timer1->Enabled = true;
}
 
void mf::gameOver() {
    //you lose
    timer1->Enabled = false;
    game_over = true;
    MessageBox::Show("Game over", "Snake", MessageBoxButtons::OK, MessageBoxIcon::Exclamation);
}
 
void mf::placeApple() {
    //place apple to random point
    int w = this->ClientRectangle.Width - 2*stp;
    int h = this->ClientRectangle.Height - 4*stp;
    apple = Point(SmartRandom(stp, w, stp), SmartRandom(stp, h, stp));
}
 
void mf::resize(Object^ sender, EventArgs^ e) {
    //adjustment size of window after resizing
    Rectangle rect = this->ClientRectangle;
    int cw = Math::Round(rect.Width / stp) * stp;
    int ch = (Math::Round(22 + rect.Height / stp) - 22) * stp;
 
    cwidth->Text = cw.ToString();
    cheight->Text = ch.ToString();
 
    this->ClientSize = Drawing::Size(cw, ch);
}
 
void mf::resize_ref(Object^ sender, EventArgs^ e) {
    //redraw all elemnts during window resizing
    Refresh();
}
 
void mf::mouse_move(Object^ sender, MouseEventArgs^ e) {
    findPath(e->Location.X, e->Location.Y);
}
 
void mf::findPath(int x, int y) {
    //algorithm of finding path from snake's head to mouse point
    if (!mouse) return;
 
    path->Clear();
    Point final_destination = Point(Math::Round(x / 12) * 12, Math::Round(y / 12) * 12);
    Point start = snake[0];
 
    if (final_destination == start) return;
 
    int w = Math::Abs(final_destination.X - start.X);
    int h = Math::Abs(final_destination.Y - start.Y);
 
    int signx = 0;
    int signy = 0;
 
    if (final_destination.X - start.X > 0) signx = 1;
    else signx = -1;
    if (final_destination.Y - start.Y > 0) signy = -1;
    else signy = 1;
 
    Point p;
    if (w > h)
        p = Point(start.X + 12 * signx, start.Y);
    else
        p = Point(start.X, start.Y - 12 * signy);
 
    path->Add(p);
 
    while (p != final_destination) {
        if (w == h) {
            //##########
            int w1 = Math::Abs(final_destination.X - p.X);
            int h1 = Math::Abs(final_destination.Y - p.Y);
 
            if (w1 == h1) {
                p.Y -= 12 * signy;
                path->Add(p);
            }
            else {
                p.X += 12 * signx;
                path->Add(p);
            }
            //##########
        }
        else {
            //##########
            if (p.X == final_destination.X) {
                p.Y -= 12 * signy;
                path->Add(p);
            }
            else if (p.Y == final_destination.Y) {
                p.X += 12 * signx;
                path->Add(p);
            }
            else if (Math::Abs(p.X - final_destination.X) == Math::Abs(p.Y - final_destination.Y)) {
                if (w > h)
                    p.Y -= 12 * signy;
                else
                    p.X += 12 * signx;
 
                path->Add(p);
            }
            else {
                if (w > h)
                    p.X += 12 * signx;
                else
                    p.Y -= 12 * signy;
 
                path->Add(p);
            }
            //##########
        }
    }
}


Вернуться к обсуждению:
Покритикуйте код "Змейки" C++/CLI WinForms
Вложения
Тип файла: rar snake.rar (9.21 Мб, 75 просмотров)
1
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
22.06.2014, 00:00
Готовые ответы и решения:

Движение змейки - разобрать код
Доброе время суток. Есть задание написать змейку, которая ползает по экрану. Искал подобные темы,...

Код Змейки на Паскаль ABC.NET
Срочно нужен код змейки. Т.е. что нужно,что бы было в ней:(примерно:файлы,списки,графика в коде...

Покритикуйте код
Есть класс Студенты (реализован через односвязный список), хотел бы услышать критику по поводу его...

Покритикуйте код
class AutoLotDal { private const string _connectionStr =...

Покритикуйте код
Здравствуйте. Начинаю изучать jquery. Пожалуйста просмотрите код для сайта...

4
22.06.2014, 00:00
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
22.06.2014, 00:00
Помогаю со студенческими работами здесь

Покритикуйте код
Добрый день. Пытался устроиться на работу (C# junior программист, зп 15-20к). По результатам...

Покритикуйте код
https://github.com/wwall/wtf/tree/master/src Критику желательно конструктивную. Проект только в...

Покритикуйте код
Код использует Direct2D и WIC, и преобразует изображение (поворот, масштабирование, зеркальное...

Покритикуйте код
Всем привет. У меня есть обычный POJO-класс с полями и класс для работы с данной коллекцией...

Покритикуйте код
Покритикуйте код, я точно знаю, что он нубовский но все же. Это моя первая программа на с++ которая...

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

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