SDL入门教程(五):7、鼠标事件演示,代码重用

本文提供了一个简单的鼠标事件演示程序源代码,该程序通过跟踪鼠标位置来移动屏幕上的图像。使用了SDL库创建窗口并处理鼠标事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作者:龙飞

7.1:演示程序源代码

        今天因为一个网上的朋友的请求,做个一个关于鼠标事件的演示程序。实际上,可以完全用到前面我们构造的类和类方法,这里送上主程序,供大家参考。其他两个文件和图片文件均不需要任何改变。
#include "SurfaceClass.h"

int game(int argc, char* argv[]);
int main(int argc ,char* argv[])
{
    
int mainRtn = 0;
    
try {
        mainRtn 
= game(argc, argv);
    }
    
catch ( const ErrorInfo& info ) {
        info.show();
        
return -1;
    }
    
    
return mainRtn;
}

int game(int argc ,char* argv[])
{
    
//Create a SDL screen.
    const int SCREEN_WIDTH = 640;
    
const int SCREEN_HEIGHT = 480;
    ScreenSurface screen(SCREEN_WIDTH, SCREEN_HEIGHT);

    
//Create 2 SDL surface for the screen that just created.
    DisplaySurface backGround("bg.bmp", screen);
    DisplaySurface frontImage(
"image.bmp", screen);

    
//Blit backGround surface to screen and flip the screen.
    backGround.blit();
    screen.flip();

    
//moving image's coordinate.
    int xpos = 0;
    
int ypos = 0;
    
//mouse's coordinate.
    int px = 0;
    
int py = 0;
    
//moving image's size.
    const int IMG_WIDTH = 128;
    
const int IMG_HEIGHT = 128;
    
//main loop.
    bool gameOver = false;
    
while( gameOver == false ){
        
//press ESC or click X to quit.
        SDL_Event gameEvent;
        
while ( SDL_PollEvent(&gameEvent) != 0 ){
            
if ( gameEvent.type == SDL_QUIT ){
                gameOver 
= true;
            }
            
if ( gameEvent.type == SDL_KEYUP ){
                
if ( gameEvent.key.keysym.sym == SDLK_ESCAPE ){
                    gameOver 
= true;
                }
            }
            
//mouse event
            if ( gameEvent.type == SDL_MOUSEMOTION ) {
                px 
= gameEvent.motion.x;
                py 
= gameEvent.motion.y;
            }
        }

        
if ( xpos < px )
            xpos
++;
        
if ( xpos > px )
            xpos
--;
        
if ( ypos < py )
            ypos
++;
        
if ( ypos > py )
            ypos
--;

        backGround.blit(xpos, ypos, xpos, ypos, IMG_WIDTH, IMG_HEIGHT);
        frontImage.blit(xpos, ypos);
        screen.flip();
    }

    
return 0;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值