一、来源
这个项目是来自开源代码NWATCH。
github链接:https://github.com/Soysauce007/WatchX-Nwatch-stm32/
我移植项目使用的开发板是b站江协科技的stm32面包板。
二、项目介绍
1.打砖块游戏整体思路介绍
打砖块游戏主要由两个子任务组成,分别是挡球板任务以及小球任务。
2.硬件平台介绍
1.硬件模块
CPU:stm32f103c8t6
屏幕显示:0.96寸OLED I2C通信
传感器模块:红外遥控、旋转编码器和六轴姿态传感器
3.代码介绍
挡球板任务程序流程图
挡球板任务,不断从消息队列中获取控制信息。
//循环读取按键值 如果是左右 则改变木板移动方向 否则 进入下一次循环
while (1)
{
xStatus = xQueueReceive( gdirqueue, &mydata, portMAX_DELAY);
if(pdPASS == xStatus)
{
dir = mydata.value;
}else
{
dir = UPT_MOVE_NONE;
}
//隐藏滑动板
DrawBitMap(gameboard.x, gameboard.y, clearImg, 12, 8);
DrawFlushArea(gameboard.x, gameboard.y, 12, 8);
if(UPT_MOVE_LEFT == dir)
{
gameboard.x -= 3;
}
else if(UPT_MOVE_RIGHT == dir)
{
gameboard.x += 3;
}else
{
gameboard.x = gameboard.x;
}
//滑动板越界判断
if(gameboard.x>240)
gameboard.x = 0;
if(gameboard.x>(128- BOARD_WIDTH))
gameboard.x = SCREEN_WIDTH - BOARD_WIDTH;
//显示滑动板
DrawBitMap(gameboard.x, gameboard.y, platform, 12, 8);
DrawFlushArea(gameboard.x, gameboard.y, 12, 8);
}
移动小球的程序流程图
移动小球任务,游戏没有结束就改变小球的位置,然后做碰撞判断。
//游戏没有结束 球运动
if(!gameover)
{
gameball.x += gameball.velx;
gameball.y += gameball.vely;
//运动后判断 球是否碰撞砖块
unsigned char index = 0;
for(unsigned char x = 0 ;x<BLOCK_COLS;x++)
{
for(unsigned char y = 0 ;y<BLOCK_ROWS;y++)
{
//如果该砖块没有 被碰撞 并且小球的起始位于该砖块的位置之中 则发生碰撞
if(!blocks[index] && gameball.x >= x * 4 && gameball.x < (x * 4) + 4 && gameball.y >= (y * 4) + 8 && gameball.y < (y * 4) + 8 + 4 )
{
blocks[index] = true;
//隐藏该砖块
DrawBitMap(x * 4, (y * 4) + 8, clearImg, 3, 4);
DrawFlushArea(x * 4, (y * 4) + 8, 3, 8);
score++;
//改变球体的垂直加速度
gameball.vely = gameball.vely*(-1);
}
index++;
}
}
//运动后判断 球是否碰撞左右墙壁
if(gameball.x < 0)
{
gameball.x = 0;
gameball.velx = gameball.velx*(-1);
}
if((gameball.x+2) > SCREEN_WIDTH)
{
gameball.x = SCREEN_WIDTH - 2;
gameball.velx = gameball.velx*(-1);
}
//运动后判断 球是否碰撞挡板
if(gameball.x >= gameboard.x && gameball.x <= gameboard.x + BOARD_WIDTH && gameball.y+2 >= SCREEN_HEIGHT - BOARD_HEIGHT)
{
gameball.y = SCREEN_HEIGHT - BOARD_HEIGHT - 2;
//改变球体的垂直加速度
if(gameball.vely > 0)
gameball.vely = gameball.vely*(-1);
gameball.velx = ((float)rand() / (RAND_MAX / 2)) - 1; // -1.0 to 1.0
}
//运动后判断 球是否碰撞上下墙壁
if(gameball.y < 0)
{
gameball.y = 0;
gameball.vely = gameball.vely*(-1);
}
if((gameball.y+2) > SCREEN_HEIGHT)
{
gameball.y = SCREEN_HEIGHT - 2;
gameball.vely = gameball.vely*(-1);
lives--;
}
//显示球
DrawBitMap(gameball.x, gameball.y, ballImg, 2, 2);
DrawFlushArea(gameball.x, gameball.y, 2, 8);
// Draw score
sprintf(buff, "%u", score);
DrawString(0, 0 , buff);
// Draw lives
if(lives != 255)
{
for(unsigned char i = 0;i<3;i++)
{
if (i < lives)
DrawBitMap((SCREEN_WIDTH - (3*8)) + (8*i), 0, livesImg, 7, 8);
else
DrawBitMap((SCREEN_WIDTH - (3*8)) + (8*i), 0, clearImg, 7, 8);
DrawFlushArea((SCREEN_WIDTH - (3*8)) + (8*i), 0, 7, 8);
}
}
}
三、效果展示
打砖块游戏
源代码github地址:https://github.com/geyoupeng/game.git。