easyx实现小球移动

easyx是一个针对VC++编译器的图形化插件。使用它,可以使得在C++中编写图形程序。

 

小球移动代码:

#include"stdafx.h"
#include<graphics.h>      
#include<conio.h>
#include<stdlib.h>
#include<time.h>

int main(){
    initgraph(640, 480);
    char ch;

    int now_x=200,now_y=200;

    for(;;){
        circle(now_x,now_y,15);
        ch=_getch();
        if(ch=='A')now_x-=10;
        else if(ch=='S')now_y+=10;
        else if(ch=='W')now_y-=10;
        else if(ch=='D')now_x+=10;
        cleardevice();

    }
    
    closegraph();
    return 0;
}

 

注:

1.stdafx.h是VC++新建工程时默认加入的头文件

2.initgraph用于创建窗口

3.根据getch()的结果进行移动小球

4.每次得到按键之后清屏(即cleardevice()函数),然后使用circle画新的圆

 

效果演示:

 

 

简单小游戏:

小球移动,掉落到地面上就GAME OVER,如果球碰到右上角的球就胜利。(球在没有控制的情况下会不断向下掉落)

使用WASD控制

 

#include"stdafx.h"
#include<graphics.h>      
#include<conio.h>
#include<stdlib.h>
#include<time.h>

int main(){
    initgraph(640, 480);
    char ch;

    int now_x=200,now_y=200;

    int t=clock();

    circle(30,400,15);
    for(;;){
        circle(now_x,now_y,15);
        if(_kbhit()){
            ch=_getch();
            if(ch=='A')now_x-=10;
            else if(ch=='S')now_y+=10;
            else if(ch=='W')now_y-=10;
            else if(ch=='D')now_x+=10;
        }
        else if(clock()-t>100){
            t=clock();
            now_y+=10;
            if(now_y>480)now_y=480;
        }
        cleardevice();
        circle(400,30,15);
        
        if(now_x==400 && now_y==30)goto win;
        if(now_y>=480)goto lose;
    }
    
win:
    cleardevice();
    TCHAR s[]=_T("YOU WIN");
    outtextxy(200,200,s);
    for(;;);
    closegraph();
    return 0;
lose:
    cleardevice();
    TCHAR st[]=_T("GAME OVER");
    outtextxy(200,200,st);
    for(;;);
    closegraph();
    return 0;
}

 

 

 

posted @ 2021-08-25 09:00  计算机知识杂谈  阅读(601)  评论(0编辑  收藏  举报