今天(周六)加班。。。给别的公司做技术支持,于是乎必须呆着,但是没事的时候自己安排。
于是学学SDL,我用它写了一个可视化的C随机函数发生器的小程序。
刚开始所有点都位于同一点,然后随机的向周围移动。模拟分子的运动情况。
很有意思,这里分享一下代码,用的两个线程(一个线程刷新屏幕,一个线程用于计算)——这也是一个游戏采用的结构。
代码,貌似TAB缩进出了点问题。。
#pragma comment(lib,"SDL/SDL.lib") #pragma comment(lib,"SDL/SDLmain.lib") #include"include/SDL.h" #include <stdlib.h> #include <stdio.h> #include <time.h> #include<iostream> using namespace std; SDL_Surface *screen; SDL_Surface *image1; SDL_Surface *image2; SDL_Surface *image3; int const MAX = 30; int const fps = 75; int const datarefresh = 1; SDL_Rect offsect[MAX]; SDL_Thread *thread = NULL; void work(); void cls(); void drawscreen(); void init(); void quit(); int my_thread( void *data ); int main(int argc, char **argv) { init(); while(1) { cls(); SDL_Delay( 1000 / fps ); drawscreen(); } quit(); return 0; } void init() { SDL_Init(SDL_INIT_VIDEO); screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE); srand( time( 0 ) ); image1 = SDL_LoadBMP("res/test3.bmp"); image2 = SDL_LoadBMP("res/test2.bmp"); image3 = SDL_LoadBMP("res/back.bmp"); Uint32 colorkey = SDL_MapRGB( image1->format, 0xFF, 0xFF, 0xFF ); SDL_SetColorKey( image1, SDL_SRCCOLORKEY, colorkey ); SDL_SetColorKey( image2, SDL_SRCCOLORKEY, colorkey ); SDL_SetColorKey( image3, SDL_SRCCOLORKEY, colorkey ); for( int i=0; i < MAX; i++ ) { offsect[i].x = 300; offsect[i].y = 200; offsect[i].w = image1->w; offsect[i].h = image1->h; } thread = SDL_CreateThread( my_thread, NULL ); } void cls() { SDL_Rect tmp; tmp.x = 0; tmp.y = 0; tmp.w = 640; tmp.h = 480; SDL_BlitSurface( image3, 0, screen, &tmp ); } void drawscreen() { SDL_UpdateRect(screen, 0, 0, 640, 480); } void work() { static bool turn = false; SDL_Rect offsectnew; for( int i=0; i < MAX; i++ ) { offsectnew = offsect[i]; int x_delta,y_delta; do { x_delta = ( (rand()%3) -1 )*1; y_delta = ( (rand()%3) -1 )*1; } while( (offsectnew.x+x_delta)<0 && (offsectnew.x+x_delta)>640 && (offsectnew.y+y_delta)<0 && (offsectnew.y+y_delta)>480 ); offsectnew.x += x_delta ; offsectnew.y += y_delta ; turn = !turn; SDL_Surface *image; if(turn) image = image1; else image = image2; SDL_BlitSurface(image, 0, screen, &offsectnew); offsect[i] = offsectnew; } } int my_thread( void *data ) { while( 1 ) { work(); SDL_Delay( datarefresh ); } return 0; } void quit() { SDL_FreeSurface(image1); SDL_FreeSurface(image2); SDL_FreeSurface(image3); SDL_KillThread( thread ); SDL_Quit(); }