// increment global block counter, so we know when to start another level up
blocks_hit++;
// bounce the ball
ball_dy = -ball_dy;
// add a little english
ball_dx += (-1 + rand() % 3);
// make a little noise
MessageBeep(MB_OK);
// add some points
score += 5 * (level + (abs)(ball_dx));
return;
}
}
// advance column position
x1 += BLOCK_X_GAP;
}
// advance row position
y1 += BLOCK_Y_GAP;
}
}
4.时间控制
[cpp]
/* CLOCK FUNCTIONS ************************************************************************/
DWORD Get_Clock(void)
{
// this function returns the current tick count
// return time
return GetTickCount();
}
DWORD Start_Clock(void)
{
// this function starts the block, that is, saves the current count,
// use in conjunction with Wait_Clock()
return (start_clock_count = Get_Clock());
}
DWORD Wait_Clock(DWORD count)
{
// this function is used to wait for a specific number of clicks since
// the call to Start_Clock
while (Get_Clock() - start_clock_count < count)
;
return Get_Clock();
}
5. 发现的问题
1)颜色太暗:
原因可能是int 到RGB转换的问题,解决办法是传参数时直接用RGB构造。
2)挡板和分数都看不到
原因是原程序没有标题栏,是全屏显示的,现在有了标题栏,占了一定的空间,导致位置计算的不对,解决办法是设置窗口大小时增加边框和标题栏。
3)界面闪烁及耗费CPU
原因是每次都先绘制黑色屏幕清除全屏,然后重新绘制,较为浪费,且一直在循环,耗费CPU。
解决办法是减少重绘区域,每次只绘制需要绘制的地方,而不是重绘全屏。
但此次只是为了学习这个框架,所以暂时只是每次循环取消息后睡眠10ms,这只能缓解闪烁和耗费CUP,并不能消除。
完整代码:
[cpp]
/*
* FreakOut.cpp (改编自《Windows 游戏编程大师技巧》第一章示例程序)
* 2012-11-29
*/
/* INCLUDES *******************************************************************************/
#include
#include
#include
#include
/* DEFINES ********************************************************************************/
// defines for windows
#define WINDOW_CLASS_NAME TEXT("WIN32CLASS")
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
// states for game loop
#define GAME_STATE_INIT 0
#define GAME_STATE_START_LEVEL 1
#define GAME_STATE_RUN 2
#define GAME_STATE_SHUTDOWN 3
#define GAME_STATE_EXIT 4
// block defines
#define NUM_BLOCK_ROWS 6
#define NUM_BLOCK_COLUMNS 8
#define BLOCK_WIDTH 64
#define BLOCK_HEIGHT 16
#define BLOCK_ORIGIN_X 8
#define BLOCK_ORIGIN_Y 8
#define BLOCK_X_GAP 80
#define BLOCK_Y_GAP 32
#define BLOCK_COLOR RGB(125, 125, 0)
#define BALL_COLOR RGB(222, 222, 222)
// paddle defines
#define PADDLE_START_X (WINDOW_WIDTH/2 - 16)
#define PADDLE_START_Y (WINDOW_HEIGHT - 32);
#define PADDLE_WIDTH 32
#define PADDLE_HEIGHT 8
#define PADDLE_COLOR RGB(0, 0, 255)
// ball defines
#define BALL_START_Y (WINDOW_HEIGHT/2)
#define BALL_SIZE 4
// these read the keyboard asynchronously
#define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) 1 : 0)
#define KEY_UP(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) 0 : 1)
/* basic unsigned types ***************