#include<stdio.h>
#include<graphics.h>//包含easyx图形库头文件
#include<Windows.h>
#define WIDTH 640
#define HEIGHT 480
#define MAX 2
struct Berry//草莓结构
{
int x;
int y;
int r;
int flag;
}berry[MAX];
struct Box//盒子结构
{
int x;
int y;
int score;
}box;
IMAGE img;//图片定义变量
void Gameinit()//初始化
{
for (int i = 0; i < MAX; i++)
{
//初始化草莓
berry[i].x = rand() % WIDTH;
berry[i].y = -rand() % 700;//有一定的高度
//berry[i].y = 200;
berry[i].r = 20;
berry[i].flag = 1;//是否掉到窗口外,窗口中
}
//初始化盒子
box.x = WIDTH / 2 - 50;
box.y = HEIGHT - 20;
box.score = 0;
loadimage(&img, "./2.jpg", 40, 40);//加载图片
}
void GameDraw()
{
cleardevice();//清屏
//setfillcolor(RED);//画圆
//fillcircle(berry.x, berry.y, berry.r);
for (int i = 0; i < MAX; i++)//画草莓
{
//putimage(berry[i].x, berry[i].y, &img, SRCAND);//输出图片 SRCAND背景去掉
putimage(berry[i].x, berry[i].y, &img);//输出图片 SRCAND背景去掉
}
setfillcolor(BLUE);//画盒子
fillrectangle(box.x, box.y, box.x + 100, box.y + 20);
setbkmode(TRANSPARENT);//将分数背景去掉
char arr[20] = "";//分数定义
sprintf_s(arr, "分数:%d", box.score);//注意使用多字符集
outtextxy(box.x+10,box.y,arr);//画分数位置
}
void Gamemove()
{
if (GetAsyncKeyState(VK_LEFT))//盒子左移
{
if (box.x >= 0)
{
box.x -= 40;
}
}
if (GetAsyncKeyState(VK_RIGHT))//盒子左移
{
if (box.x+100 <= WIDTH)
{
box.x += 40;
}
}
//让草莓左右摇摆
for (int i = 0; i < MAX; i++)
{
if (rand() % 2 == 0)
{
berry[i].x += 10;
}
else
{
berry[i].x -= 10;
}
berry[i].y += 10;
}
}
void Gamejude()//判断草莓与盒子是否接触,计分
{
for (int i = 0; i < MAX; i++)
{
if (berry[i].x > box.x && berry[i].x<box.x + 100 && berry[i].y + berry[i].r>box.y)
{
box.score += 10;
berry[i].y = 0;
berry[i].x = rand() % WIDTH;
}
else if (berry[i].y > HEIGHT)
{
box.score -= 10;
berry[i].y = 0;
berry[i].x = rand() % WIDTH;
}
}
}
int main()
{
initgraph(WIDTH, HEIGHT);//初始化窗口
setbkcolor(GREEN);//背景颜色 或(RGB(179,192,204))
cleardevice();//清屏
srand(GetTickCount());//种子函数
Gameinit();
while (1)
{
Gamemove();
GameDraw();
Sleep(100);
Gamejude();
}
return 0;
}