vs2022 C语言
#include <graphics.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define num 8
#define houdu1 20
#define houdu2 40
int ballx, bally;
int ballvx, ballvy;
int r = 40;
int barleft = 200;
int brick[num]; // 1为有0为无
int i = 0;
int m = 1;
// 显示游戏画面
void show() {
setfillcolor(GREEN); // 画板
fillrectangle(barleft, 460, barleft + 80, 480);
setfillcolor(YELLOW); // 画球
fillcircle(ballx, bally, r);
setfillcolor(RED); // 画砖块
for (int t = 0; t < num; t++) {
if (brick[t]) {
fillrectangle(t * 80, 0, (t + 1) * 80, 40);
}
}
}
// 主逻辑部分,更新球的位置和处理碰撞
void zhuyaobufen() {
ballx += ballvx;
bally += ballvy;
// 左右边界检测
if (ballx <= r || ballx >= 640 - r) {
ballvx = -ballvx;
}
// 上边界检测
if (bally <= r) {
ballvy = -ballvy;
}
// 下边界检测,若球超出下边界游戏结束
if (bally >= 480 - r) {
m = 0;
}
// 砖块碰撞检测
for (int t = 0; t < num; t++) {
if (brick[t]) {
if (bally - r <= 40 && ballx >= t * 80 && ballx <= (t + 1) * 80) {
brick[t] = 0;
ballvy = -ballvy;
i++;
}
}
}
// 挡板碰撞检测
if (bally + r >= 460 && ballx >= barleft && ballx <= barleft + 80) {
ballvy = -ballvy;
}
}
// 游戏结束处理
void gameover() {
EndBatchDraw();
Sleep(2000);
closegraph();
}
// 处理用户输入和更新挡板位置
void inputupdate() {
char input;
if (_kbhit()) {
input = _getch();
if (input == 'a' && barleft > 0) {
barleft -= 20;
}
if (input == 'd' && barleft < 400) {
barleft += 20;
}
}
}
int main() {
initgraph(640, 480);
BeginBatchDraw(); // 开启批量绘图
ballx = 320;
bally = 420;
ballvx = 20;
ballvy = -20;
// 初始化砖块
for (int t = 0; t < num; t++) {
brick[t] = 1;
}
while (m) {
cleardevice(); // 清屏
zhuyaobufen();
inputupdate();
show();
FlushBatchDraw(); // 刷新批量绘图
Sleep(100);
}
gameover();
return 0;
}