来源《C和C++游戏趣味编程》——童晶
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include <graphics.h>
#define RAND_MAX 50
int main()
{
float width, height, gravity;
float ball_x, ball_y, ball_vy, radius;
float rect_left_x, rect_top_y, rect_width, rect_height,rect_vx;
int score = 0;
int flag = 1;
int isBallFloor = 1;
width = 600;
height = 400;
gravity = 0.6;
initgraph(width, height);
radius = 20;
ball_x = width / 4;
ball_y = height - radius;
ball_vy = 0;
rect_height = 100;
rect_width = 20;
rect_left_x = width * 3 / 4;
rect_top_y = height - rect_height;
rect_vx = -3;
while (flag)
{
if (_kbhit())
{
char input = _getch();
if (input == ' '&&isBallFloor)
{
ball_vy = -16;
isBallFloor = 0;
}
}
ball_vy += gravity;
ball_y += ball_vy;
if (ball_y >= height - radius)
{
ball_vy = 0;
ball_y = height - radius;
isBallFloor = 1;
}
rect_left_x += rect_vx;
if (rect_left_x <= 0)
{
rect_left_x = width;
score++;
srand(time(NULL));
rect_height = rand() % 100 ;
}
if ((rect_left_x <= ball_x + radius) &&
(rect_left_x + rect_width >= ball_x - radius) &&
(height - rect_height <= ball_y + radius))
{
Sleep(50);
printf("GAME OVER");
break;
}
cleardevice();
fillcircle(ball_x, ball_y, radius);
fillrectangle(rect_left_x, height - rect_height, rect_left_x + rect_width, height);
TCHAR s1[] = _T("Your score is ");
outtextxy(10, 20, s1);
TCHAR s[1000];
_stprintf_s(s, _T("%d"), score);
outtextxy(10, 40, s);
Sleep(5);
}
closegraph();
return 0;
}
|