-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
419 lines (365 loc) · 11.1 KB
/
main.cpp
File metadata and controls
419 lines (365 loc) · 11.1 KB
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
#include <windows.h>
#include <math.h>
#include <vector>
#include <string>
#include <stdlib.h>
#include <time.h>
#define BLOCK_NUM 18
#define ROWS 4
#define COLS 8 //row랑 col은 나중에 사용사로부터 난이도 정할 때 바꾸자.
using namespace std;
typedef struct {
int life;
int x;
int y;
}LIFE;
typedef enum _GAME_STATE { INIT, RUNNING, RESULT } GAME_STATE;
class DemoApp
{
public:
DemoApp() {};
~DemoApp() { DiscardDeviceResource(); DiscardAppResource(); };
bool Initialize(HINSTANCE hInstance);
bool Update(float timeDelta);
void Render();
WCHAR strbuf[180]; // 문자열 버퍼
wstring str; // 출력할 문자열
private:
static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
void OnResize();
bool CreateAppResource();
void DiscardAppResource();
bool CreateDeviceResource();
void DiscardDeviceResource();
void InitBlocks();
void randomSpeed();
void Screen();
void collision();
HDC hdcMem = NULL; // GDI 더블 버퍼링 구현
HBITMAP hBitmapMem = NULL; // 메모리 만듬
vector<float> v{}; // 공 스피드,방향 결정.
vector<float> ballpos{350, 350}; // 공의 위치 벡터
vector<float> paddle{200, 400}; // 패들의 위치 벡터
vector<vector<LIFE>> Blocks;
int mouse; // mouse의 x좌표
int r = 5; // 공의 반지름
int w = 35, h = 9; // 패드의 좌우 너비 결정
int blank = 50; // block과 창 사이의 간격
int width, height = 30; // block의 너비, 높이
int block_count; // 남은 블록의 개수 판별
float timeDuration; // stage n 창의 지속 시간
GAME_STATE g_GameState = INIT; // 게임현재진행상태
private:
HWND hWnd = NULL;
};
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
DemoApp demoApp;
if (!demoApp.Initialize(hInstance)) return 1;
// Time 선언
LARGE_INTEGER nPrevTime;
LARGE_INTEGER nFrequency;
// Time 초기화
QueryPerformanceFrequency(&nFrequency);
QueryPerformanceCounter(&nPrevTime);
MSG msg = {};
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
// Time 갱신
LARGE_INTEGER nCurrentTime;
QueryPerformanceCounter(&nCurrentTime);
float timeDelta = (float)((double)(nCurrentTime.QuadPart - nPrevTime.QuadPart) / (double)(nFrequency.QuadPart));
nPrevTime = nCurrentTime;
// 갱신 함수를 호출한다. false가 리턴되면 종료한다.
if (!demoApp.Update(timeDelta)) break;
demoApp.Render();
}
}
return 0;
}
bool DemoApp::Initialize(HINSTANCE hInstance)
{
// 윈도우 클래스를 등록함.
WNDCLASS wc = {};
wc.lpfnWndProc = DemoApp::WndProc;
wc.cbWndExtra = sizeof(LONG_PTR);
wc.hInstance = hInstance;
wc.lpszClassName = L"DemoApp";
RegisterClass(&wc);
hWnd = CreateWindow(L"DemoApp", L"DemoApp", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInstance, this);
if (!hWnd) return false;
ShowWindow(hWnd, SW_SHOWNORMAL);
UpdateWindow(hWnd);
if (!CreateAppResource()) return false;
return true;
}
LRESULT CALLBACK DemoApp::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_CREATE)
{
CREATESTRUCT* pCreate = (CREATESTRUCT*)lParam;
DemoApp* pDemoApp = (DemoApp*)pCreate->lpCreateParams;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)pDemoApp);
return 1;
}
DemoApp* pDemoApp = (DemoApp*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (!pDemoApp)
{
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
switch (uMsg)
{
case WM_SIZE:
{
pDemoApp->OnResize();
return 0;
}
case WM_KEYDOWN:
{
if (wParam == VK_ESCAPE) // ESC 키 누르면 종료
{
DestroyWindow(hWnd);
return 0;
} else if (pDemoApp->g_GameState==INIT and wParam == VK_SPACE) { // 게임상태 INIT, SPACE 키 누르면 game 시작
pDemoApp->g_GameState = RUNNING;
}
else if (pDemoApp->g_GameState == RESULT and wParam == VK_LEFT) { // 게임상태 RESULT, 왼쪽 방향키 누르면 리셋
pDemoApp->g_GameState = INIT;
//다 초기화 시켜줘야 함.
}
else if (pDemoApp->g_GameState == RESULT and wParam == VK_RETURN) { // 게임상태 RESULT, ENTER 키 누르면 종료
int ret = MessageBox(0, L"정말 게임을 나가시겠습니까?", L"에러", MB_ICONQUESTION | MB_YESNO);
if (ret == IDYES) {
int subret = MessageBox(0, L"게임을 종료합니다", L"접수", MB_ICONINFORMATION | MB_OK);
DestroyWindow(hWnd);
}
else if (ret == IDNO) {
MessageBox(0, L"처음으로 돌아갑니다", L"접수", MB_ICONINFORMATION | MB_OK);
pDemoApp->g_GameState = INIT;
}
else MessageBox(0, L"무엇인가 잘못되었습니다.", L"접수", MB_ICONERROR | MB_OK);
return 0;
}
return 0;
}
case WM_MOUSEMOVE:
{
pDemoApp->mouse = LOWORD(lParam);
return 1;
}
case WM_DESTROY:
{
PostQuitMessage(0);
return 1;
}
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
void DemoApp::OnResize()
{
}
bool DemoApp::CreateAppResource()
{
RECT rc;
GetClientRect(hWnd, &rc);
timeDuration = 3.5f; //3초만에 지나가게 하겠다
// GDI 더블 버퍼링 구현. hdcMem, hBitmapMem 준비.
HDC hdc = GetDC(hWnd);
hdcMem = CreateCompatibleDC(hdc);
hBitmapMem = CreateCompatibleBitmap(hdc, rc.right, rc.bottom);
ReleaseDC(hWnd, hdc);
// 비트맵 객체를 선택함. 바뀌지 않으므로 한번만 수행함.
SelectObject(hdcMem, hBitmapMem);
return true;
}
void DemoApp::DiscardAppResource()
{
DeleteObject(hBitmapMem);
DeleteDC(hdcMem);
}
bool DemoApp::CreateDeviceResource()
{
return true;
}
void DemoApp::DiscardDeviceResource()
{
}
void DemoApp::InitBlocks() { //블럭 초기화(x,y)는 블럭 왼쪽 위 꼭짓점 좌표.
RECT rc;
GetClientRect(hWnd, &rc);
Blocks = vector<vector<LIFE>>(ROWS, vector<LIFE>(COLS));
width = ((rc.right - blank) - (rc.left + blank)) / COLS;
int randomR, randomC;
int count = 0;
while (count <= BLOCK_NUM) {
randomR = rand() % ROWS;
randomC = rand() % COLS;
if (Blocks[randomR][randomC].life == 1) continue;
Blocks[randomR][randomC].x = rc.left + blank + randomC * width + 5;
Blocks[randomR][randomC].y = rc.top + blank + randomR * height + 5;
Blocks[randomR][randomC].life = 1;
count++;
}
}
void DemoApp::randomSpeed() {
float speedX = (rand() / (float)RAND_MAX) * (-1) * (0.55);
float speedY = (rand() / (float)RAND_MAX) * (-1) * (0.55);
if (speedY > -0.12) speedY = -0.12;
else if (speedY < -0.15) speedY = -0.15;
if (speedX > -0.12) speedX = -0.12;
else if (speedX < -0.15) speedX = -0.15;
v = { speedX, speedY };
}
void DemoApp::Screen() {
if (g_GameState == INIT) {
wsprintf(strbuf, L" ----------------------------------------------------------- ");
str += strbuf;
str += L"\n";
wsprintf(strbuf, L" 블럭깨기 게임 ");
str += strbuf;
str += L"\n";
wsprintf(strbuf, L" ----------------------------------------------------------- ");
str += strbuf;
str += L"\n";
wsprintf(strbuf, L"시작하려면 SPACE BAR를 누르세요");
str += strbuf;
str += L"\n";
}
else if (g_GameState == RESULT) {
wsprintf(strbuf, L" ----------------------------------------------------------- ");
str += strbuf;
str += L"\n";
wsprintf(strbuf, L" 게임이 끝났습니다 ");
str += strbuf;
str += L"\n";
wsprintf(strbuf, L" ----------------------------------------------------------- ");
str += strbuf;
str += L"\n";
wsprintf(strbuf, L" 다시 시작하려면 왼쪽 방향키를, ");
str += strbuf;
str += L"\n";
wsprintf(strbuf, L" 종료하려면 enter를 눌러주세요 ");
str += strbuf;
str += L"\n";
}
}
void DemoApp::collision() {
RECT rc;
GetClientRect(hWnd, &rc);
float x = ballpos[0], y = ballpos[1];
/*창 벽면에 부딪혔을 때*/
if (x >= rc.right || x <= rc.left) v[0] *= -1; // 왼,오
if (y <= rc.top) v[1] *= -1; // 천장
if (y >= rc.bottom) g_GameState = RESULT; // 바닥 -> 게임 끝
/*패들에 부딪혔을 때*/
if (x >= paddle[0] - w and x<=paddle[0] + w and y>= paddle[1] - h and y <= paddle[1]+h) {
if (x - r < paddle[0] - w and x + r > paddle[0] - w) v[0] *= -1; // 왼
else if (x - r < paddle[0] + w and x + r > paddle[0] + w) v[0] *= -1; // 오
else if (y - r < paddle[1] - h and y + r > paddle[1] - h) v[1] *= -1; // 위
}
/*블록에 부딪혔을 때*/
static int wall= 0; //block
for (int c = 0; c < COLS; c++) {
for (int r = 0; r < ROWS; r++) {
LIFE b = Blocks[r][c];
// 어느 벽면에 부딪혔는지 체크
if (x-r < b.x and x +r > b.x) wall = 1; // 왼
else if (x -r < b.x + width and x + r > b.x + width) wall = 2; // 오
else if (y - r < b.y and y + r > b.y) wall = 3; // 위
else if (y - r < b.y+height and y + r > b.y+height) wall = 4; // 아래
if (x > b.x and x<b.x + width and y>b.y and y < b.y + height and b.life==1) {
switch (wall)
{
case 1:
case 2: v[0] *= -1;
break;
case 3:
case 4: v[1] *= -1;
break;
}
Blocks[r][c].life = 0;
block_count--;
if (block_count == -1) g_GameState = RESULT;
}
}
}
}
bool DemoApp::Update(float timeDelta) //업데이트 작성 방법. 상태 갱신에만 집중
{
str.clear();
RECT rc; // 창
GetClientRect(hWnd, &rc);
switch (g_GameState)
{
case INIT: {
Screen();
ballpos[0] = rand() % (rc.right- rc.left-2*r) + rc.left + r;
ballpos[1] = 350;
block_count = BLOCK_NUM;
randomSpeed();
InitBlocks();
break;
}
case RUNNING: {
paddle[0] = mouse;
ballpos[0] += v[0];
ballpos[1] += v[1];
/*블록*/
collision();
break;
}
case RESULT: {
Screen();
break;
}
}
// 응용 프로그램을 종료하는 경우에 false를 리턴하고 그 외에는 항상 true를 리턴함.
return true;
}
void DemoApp::Render()
{
if (!CreateDeviceResource()) return;
// 그리기 코드 시작 - 기존의 hdc 대신 hdcMem에 그리면 됨.
RECT rc; //윈도우 창 배경
GetClientRect(hWnd, &rc); //그리기 영역의 크기를 얻음. 위치 정보 주는.
FillRect(hdcMem, &rc, GetSysColorBrush(COLOR_BACKGROUND));
// 문자열 출력해준다
RECT rcText; // 텍스트 출력 영역을 나타내는 사각형 구조체
float x = 180; // 출력 위치 x 좌표
float y = 150; // 출력 위치 y 좌표
// 출력 영역의 좌표 설정
SetRect(&rcText, x, y, rc.right, rc.bottom);
DrawText(hdcMem, str.c_str(), -1, &rcText, DT_LEFT);
if (g_GameState == RUNNING) {
//공
Ellipse(hdcMem, ballpos[0] - r, ballpos[1] - r, ballpos[0] + r, ballpos[1] + r);
//바닥
RECT rcp;
Rectangle(hdcMem, paddle[0] - w, paddle[1] - r, paddle[0] + w, paddle[1] + r); //마우스에 따른 움직임. l, top, r, bottom
FillRect(hdcMem, &rcp, GetSysColorBrush(COLOR_HIGHLIGHT));
//벽돌
RECT rcb;
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
if(Blocks[r][c].life==1)
Rectangle(hdcMem, Blocks[r][c].x, Blocks[r][c].y, Blocks[r][c].x + width, Blocks[r][c].y + height); //마우스에 따른 움직임. l, top, r, bottom
}
}
//FillRect(hdcMem, &rcb, GetSysColorBrush(RGB(128,128,128)));
//
// 그리기 코드 끝
}
// 버퍼 스와핑.
HDC hdc = GetDC(hWnd);
BitBlt(hdc, 0, 0, rc.right, rc.bottom, hdcMem, 0, 0, SRCCOPY); //그려진 비트맵을 복사해라.
ReleaseDC(hWnd, hdc);
bool DeviceLost = false;
if (DeviceLost) DiscardDeviceResource();
}