bool Application::Init()
{
    // logfile
    if (ENABLE_LOGFILE)
    {
        logFile = fopen(LOGFILE,"w");
    }

    log("starting game\n");

    srand(time(NULL));

    // allegro
    log("initializing Allegro\n");

    if (allegro_init() != 0)
        return false;

    //
    // graphics
    //

    log("initializing graphics\n");

    set_color_depth(COLOR_DEPTH);

    int card;
    if (FULL_SCREEN)
        card = GFX_AUTODETECT_FULLSCREEN;
    else
        card = GFX_AUTODETECT_WINDOWED;

    if (set_gfx_mode(card,SCREEN_WIDTH,SCREEN_HEIGHT,0,0) != 0)
        return false;

    canvas = create_bitmap_ex(COLOR_DEPTH,screen->w,screen->h);
    if (canvas == NULL)
        return false;

    loadingImg = load_bitmap("data/loading.bmp",NULL);
    if (loadingImg == NULL)
        return false;
    blit(loadingImg,screen,0,0,0,0,screen->w,screen->h);

    //
    // font system
    //

    log("initializing font system\n");
    if (alfont_init() != ALFONT_OK)
        return false;

    font = alfont_load_font(FONT_FILE);
    if (font == NULL)
        return false;

    //
    // keyboard
    //

    log("initializing keyboard\n");

    if (install_keyboard() != 0)
        return false;

    memset(prevKeyState,0,256);

    //
    // mouse
    //

    log("initializing mouse\n");

    numMouseButtons = install_mouse();
    if (numMouseButtons < 0)
        return false;
    mouseButtons = new bool[numMouseButtons+1];
    prevMouseButtons = new bool[numMouseButtons+1];
    mousePressedLocs = new MousePos[numMouseButtons+1];

    for (int button = 0; button < numMouseButtons+1; button++)
    {
        mouseButtons[button] = false;
        prevMouseButtons[button] = false;
        mousePressedLocs[button].x = -1;
        mousePressedLocs[button].y = -1;
    }

    // timer
    log("initializing timer\n");

    if (install_timer() != 0)
        return false;

    //
    // sound
    //

    log("initializing base sound\n");

    if (install_sound(DIGI_AUTODETECT,MIDI_AUTODETECT,NULL) != 0)
        return false;

    set_volume(ALLEGRO_SOUND_VOLUME,ALLEGRO_SOUND_VOLUME);

    // initialized successfully!
    log("initialization completed successfully\n");
    KeepRunning = true;
    return true;
}
int main() {

    BITMAP *mysha = NULL, *buffer = NULL;
    PARTICLE *particle[NUM_PARTICLES];
    int old_time = 0, old_time2 = 0;
    int i;
    int count = 0;
    int use_alleg = FALSE;
    int depth = 16;

    allegro_init();

    install_keyboard();
    install_timer();

    set_config_file("examples.cfg");
    depth = get_config_int("examples", "depth", 16);

    set_color_depth(depth);
    if (set_gfx_mode(GFX_AUTODETECT, 640, 480, 0, 0)) {
        set_color_depth(16);
        if (set_gfx_mode(GFX_AUTODETECT, 640, 480, 0, 0)) {
            set_color_depth(15);
            if (set_gfx_mode(GFX_AUTODETECT, 640, 480, 0, 0)) {
                set_color_depth(32);
                if (set_gfx_mode(GFX_AUTODETECT, 640, 480, 0, 0)) {
                    allegro_message("Unable to set 640x480 screen mode!\n");
                    return -1;
                }
            }
        }
    }

    mysha = load_bitmap("mysha.pcx", NULL);

    if (!mysha) {
        set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
        allegro_message("Unable to load mysha.pcx. Copy it from the allegro examples directory.\n");
        return -2;
    }

    TRACE("Got here!\n");

    for (i = 0; i < NUM_PARTICLES; i++)
        particle[i] = NULL;

    TRACE("Still here!\n");

    for (i = 0; i < NUM_PARTICLES; i++) {
        int j;
        int r, g, b;

        TRACE("Going for particle: %i\n", i);

        particle[i] = malloc(sizeof(PARTICLE));
        if (!particle[i]) {
            TRACE("Out of memory while creating particle!\n");
            goto Error;
        }

        TRACE("Clearing particle\n");

        memset(particle[i], 0, sizeof(PARTICLE));

        TRACE("Creating bitmap\n");

        particle[i]->bmp = create_bitmap(PARTICLE_SIZE, PARTICLE_SIZE);
        if (!particle[i]->bmp) {
            TRACE("Out of memory while creating particle bitmap!\n");
            goto Error;
        }

        TRACE("Clearing bitmap\n");

        clear(particle[i]->bmp);

        TRACE("Setting up coordinates\n");

        particle[i]->x = rand() % SCREEN_W;
        particle[i]->y = rand() % SCREEN_H;
        particle[i]->vx = rand() % 10 - 5;
        particle[i]->vy = rand() % 10 - 5;
        particle[i]->a = rand() & 255;
        particle[i]->a_dir = 1;

        TRACE("Setting up colors\n");
        hsv_to_rgb(rand() % 360, 1, 1, &r, &g, &b);

        TRACE("Drawing circles\n");

        for (j = 1; j < PARTICLE_SIZE/2-1; j++) {
            circle(particle[i]->bmp, PARTICLE_SIZE/2-1, PARTICLE_SIZE/2, j, makecol(r*2/(j+1), g*2/(j+1), b*2/(j+1)));
            circle(particle[i]->bmp, PARTICLE_SIZE/2, PARTICLE_SIZE/2, j, makecol(r*2/(j+1), g*2/(j+1), b*2/(j+1)));
        }
    }

    LOCK_FUNCTION(the_timer);
    LOCK_VARIABLE(chrono);

    buffer = create_bitmap(SCREEN_W, SCREEN_H);

    if (!buffer) {
        TRACE("Out of memory while creating back buffer!\n");
        goto Error;
    }

    clear(buffer);

    TRACE("Starting...\n");

    install_int(the_timer, 1);
    old_time = chrono;

    text_mode(0);

    do {
        int chrono2;

        /* Tile mysha over the screen */
#ifndef COMPARE_WITH_ALLEGRO
        blit(mysha, buffer, 0, 0, 0, 0, mysha->w, mysha->h);
        blit(mysha, buffer, 0, 0, 320, 0, mysha->w, mysha->h);
        blit(mysha, buffer, 0, 0, 0, 200, mysha->w, mysha->h);
        blit(mysha, buffer, 0, 0, 320, 200, mysha->w, mysha->h);
        blit(mysha, buffer, 0, 0, 0, 400, mysha->w, mysha->h);
        blit(mysha, buffer, 0, 0, 320, 400, mysha->w, mysha->h);
#endif

        if (use_alleg) {
            for (i = 0; i < NUM_PARTICLES; i++) {
                set_add_blender(0, 0, 0, particle[i]->a);
                draw_trans_sprite(buffer, particle[i]->bmp, particle[i]->x - particle[i]->bmp->w/2, particle[i]->y - particle[i]->bmp->h/2);
            }
        }
        else {
            for (i = 0; i < NUM_PARTICLES; i++)
                fblend_add(particle[i]->bmp, buffer, particle[i]->x - particle[i]->bmp->w/2, particle[i]->y - particle[i]->bmp->h/2, particle[i]->a);
        }

        if (key[KEY_SPACE]) {
            use_alleg = !use_alleg;
            key[KEY_SPACE] = 0;
            chrono = 0;
            count = 0;
            old_time = 0;
            old_time2 = 0;
        }
        count++;

#ifdef COMPARE_WITH_ALLEGRO
        textprintf(screen, font, 0, 0, makecol(255, 255, 255), "%s  %.2f fps (%.3f avg)", use_alleg ? "Using Allegro" : "Using new", (chrono - old_time2) == 0 ? 1000.0 : 1000 / ((double)chrono - old_time2), count * 1000.0 / chrono);
#else
        textprintf(buffer, font, 0, 0, makecol(255, 255, 255), "%s  %.2f fps (%.3f avg)", use_alleg ? "Using Allegro" : "Using new", (chrono - old_time2) == 0 ? 1000.0 : 1000 / ((double)chrono - old_time2), count * 1000.0 / chrono);
#endif

        old_time2 = chrono;


#ifndef COMPARE_WITH_ALLEGRO

        /* Draw the buffer */
        blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H);

#endif

        chrono2 = chrono / 40;
        for (i = old_time/40; i < chrono2; i++) {
            int j;
            for (j = 0; j < NUM_PARTICLES; j++) {
                particle[j]->x += particle[j]->vx;
                particle[j]->y += particle[j]->vy;

                if (particle[j]->x <= 0 || particle[j]->x >= SCREEN_W)
                    particle[j]->vx = -particle[j]->vx;
                if (particle[j]->y <= 0 || particle[j]->y >= SCREEN_H)
                    particle[j]->vy = -particle[j]->vy;

                if (particle[j]->a <= 0 || particle[j]->a >= 256)
                    particle[j]->a_dir = -particle[j]->a_dir;

                particle[j]->a += particle[j]->a_dir;
            }
        }
        old_time = chrono;

    } while (!key[KEY_ESC]);

Error:

    TRACE("Shutting down.\n");

    if (mysha)
        destroy_bitmap(mysha);
    if (buffer)
        destroy_bitmap(buffer);

    for (i = 0; i < NUM_PARTICLES; i++) {
        if (particle[i]) {
            if (particle[i]->bmp)
                destroy_bitmap(particle[i]->bmp);
            free(particle[i]);
        }
    }

    set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);

    return 0;

}
Beispiel #3
0
int main(void) {

    int f,i,j,k,c,x,y,ix,iy,displayloop;
    int usingmap,makingmap,mmx,mmy,tmpmap,maploop;
    float rx,ry,nrx,nry,px,py;
    RGB rgb;
    FILE *fp;

    img=(uchar **)calloc(scrhei,sizeof(uchar *));
    for (y=0; y<scrhei; y++) {
        img[y]=(uchar *)calloc(scrwid,sizeof(uchar));
        for (x=0; x<scrwid; x++) {
            img[y][x]=myrnd()*255;
        }
    }
    img2=(uchar **)calloc(scrhei,sizeof(uchar *));
    for (y=0; y<scrhei; y++) {
        img2[y]=(uchar *)calloc(scrwid,sizeof(uchar));
        for (x=0; x<scrwid; x++) {
            img2[y][x]=myrnd()*255;
        }
    }

    srand((int)time(NULL));

    usingmap=0;
    makingmap=1;
    mmx=0;
    mmy=0;

    /* Originals from QB
    op[0] = 1; damp[0] = .999; force[0] = .005;
    op[1] = 1.02; damp[1] = .999; force[1] = .002;
    op[2] = 0; damp[2] = .999; force[2] = .002;
    op[3] = 1; damp[3] = .999; force[3] = .005;
    op[4] = 1; damp[4] = .999; force[4] = .005;
    op[5] = 0; damp[5] = .999; force[5] = .002;
    */

// 0 Accelerate
    op[0] = 1;
    damp[0] = .999;
    force[0] = .005;
// 1 Velocity
    op[1] = 1.02;
    damp[1] = .999;
    force[1] = .01;
// 2 Rotation
    op[2] = 0;
    damp[2] = .999;
    force[2] = .05;
// 3 Drip
    op[3] = 1;
    damp[3] = .999;
    force[3] = .03;
// 4 Dribble
    op[4] = 1;
    damp[4] = .999;
    force[4] = .01;
// 5 Slide
    op[5] = 0;
    damp[5] = .999;
    force[5] = .01;

    for (f=0; f<fs; f++) {
        var[f] = op[f];
        fon[f]=1;
    }

    allegro_init ();
    install_keyboard ();
    install_timer ();
    set_gfx_mode (GFX_AUTODETECT, scrwid, scrhei, 0, 0);
    set_pallete (desktop_palette);
    _farsetsel(screen->seg);
    for (c=0; c<=255; c++) {
        rgb.r=saw(0,c);
        rgb.g=saw(256/3,c);
        rgb.b=saw(2*256/3,c);
        set_color(c,&rgb);
    }

    while(!key[KEY_ESC]) {

        // Generate some more of the map
        for (maploop=1; maploop<scrwid*scrhei/15; maploop++) {
            rx=(float)mmx/scrwid*2-1;
            ry=(float)(mmy-scrhei/2)/scrwid*2;
            if (fon[1]) {
                rx = rx / var[1];
                ry = ry / var[1];
            }
            if (fon[0]) {
                rx = mysgn(rx)/var[1]*mypow(myabs(rx),1/var[6]);
                ry = mysgn(ry)/var[1]*mypow(myabs(ry),1/var[6]);
            }
            if (fon[2]) {
                nrx = rx * cos(var[2]) + ry * sin(var[2]);
                nry = -rx * sin(var[2]) + ry * cos(var[2]);
                rx = nrx;
                ry=nry;
            }
            if (fon[3]) {
                ry = ry / var[3];
            }
            if (fon[4]) {
                ry = ((myabs(ry) - 1) / var[4] + 1) * mysgn(ry);
            }
            if (fon[5]) {
                rx = rx + var[5] * mysgn(rx);
            }
            px=(rx+1)/2*scrwid;
            py=scrhei/2+(ry)/2*scrwid;
            ix=(int)px;
            iy=(int)py;
            amount[mmx][mmy][0][0][makingmap]=((float)ix+1-(float)px)*((float)(iy+1)-(float)py);
            amount[mmx][mmy][1][0][makingmap]=((float)px-(float)ix)*((float)(iy+1)-(float)py);
            amount[mmx][mmy][0][1][makingmap]=((float)ix+1-(float)px)*((float)py-(float)iy);
            amount[mmx][mmy][1][1][makingmap]=((float)px-(float)ix)*((float)py-(float)iy);
            pix[mmx][mmy][makingmap]=ix;
            piy[mmx][mmy][makingmap]=iy;
            if (ix<0 || ix>=scrwid-1 || iy<0 || iy>=scrhei-1) {
                pix[mmx][mmy][makingmap]=scrwid/2;
                piy[mmx][mmy][makingmap]=scrhei/2;
                for (i=0; i<=1; i++) {
                    for (j=0; j<=1; j++) {
                        amount[mmx][mmy][i][j][makingmap]=0;
                    }
                }
            }
            mmx++;
            if (mmx>=scrwid) {
                mmx=0;
                mmy++;
                if (mmy>=scrhei) {
                    mmy=0;
                    tmpmap=usingmap;
                    usingmap=makingmap;
                    makingmap=tmpmap;
                    for (f=0; f<fs; f++) {
                        perturb(f);
                    }
                    for (i=0; i<4; i++) {
                        f = myrnd() * fs;
                        if (myrnd()<.8) {
                            if (myrnd()<.5)
                                fon[f] = 1;
                            else
                                fon[f]=0;
                        }
                    }
                }
            }
        }

        // Animate
        for (x=0; x<scrwid; x++) {
            for (y=0; y<scrhei; y++) {
                c=0;
                for (i=0; i<=1; i++) {
                    for (j=0; j<=1; j++) {
                        c=c+amount[x][y][i][j][usingmap]*img[piy[x][y][usingmap]+j][pix[x][y][usingmap]+i];
                    }
                }
                c--;
                img2[y][x]=c;
            }
        }
        /*        for (y=0;y<scrhei;y++) {
                for (x=0;x<scrwid;x++) {
                  _farpokeb(screen->seg, (unsigned long)screen->line[y]+x, img2[y][x]);
                }
                }*/
        for (y=0; y<scrhei; y++) {
            movedata(_my_ds(), img2[y], screen->seg, bmp_write_line(screen,y), scrwid);
        }
        for (f=0; f<fs; f++) {
            if (fon[f]) {
                hline(screen, scrwid/2, f*2, scrwid/2+(var[f] - op[f]) * scrwid * 4, 0);
            }
        }
        imgtmp=img;
        img=img2;
        img2=imgtmp;
        for (i=1; i<=5; i++) {
            mycircle(myrnd()*scrwid,myrnd()*scrhei,2+myrnd()*8,myrnd()*255);
        }
    }

}
Beispiel #4
0
int main(int argc, char *argv[])
{
        int frames = 0;
        int c, d;
        allegro_init();
        allegro_video_init();
        install_timer();
        install_int_ex(timer_rout, BPS_TO_TIMER(100));
	install_int_ex(onesec, BPS_TO_TIMER(1));
	midi_init();
        
        initpc(argc, argv);

        d = romset;
        for (c = 0; c < ROM_MAX; c++)
        {
                romset = c;
                romspresent[c] = loadbios();
                pclog("romset %i - %i\n", c, romspresent[c]);
        }
        
        for (c = 0; c < ROM_MAX; c++)
        {
                if (romspresent[c])
                   break;
        }
        if (c == ROM_MAX)
        {
                printf("No ROMs present!\nYou must have at least one romset to use PCem.");
                return 0;
        }

        romset=d;
        c=loadbios();

        if (!c)
        {
                if (romset != -1)
			printf("Configured romset not available.\nDefaulting to available romset.");
                for (c = 0; c < ROM_MAX; c++)
                {
                        if (romspresent[c])
                        {
                                romset = c;
                                model = model_getmodel(romset);
                                saveconfig();
                                resetpchard();
                                break;
                        }
                }
        }

        for (c = 0; c < GFX_MAX; c++)
                gfx_present[c] = video_card_available(video_old_to_new(c));

        if (!video_card_available(video_old_to_new(gfxcard)))
        {
                if (gfxcard) printf("Configured video BIOS not available.\nDefaulting to available romset.");
                for (c = GFX_MAX-1; c >= 0; c--)
                {
                        if (gfx_present[c])
                        {
                                gfxcard = c;
                                saveconfig();
                                resetpchard();
                                break;
                        }
                }
        }

	resetpchard();

        ticks = 0;
        while (!quited)
        {
                if (ticks)
                {
                        ticks--;
                        runpc();
                        frames++;
                        if (frames >= 200 && nvr_dosave)
                        {
                                frames = 0;
                                nvr_dosave = 0;
                                savenvr();
                        }
                }
                else
                        rest(1);

		if (ticks > 10)
			ticks = 0;
                
		if ((mouse_b & 1) && !mousecapture)
			mousecapture = 1;

		if (((key[KEY_LCONTROL] || key[KEY_RCONTROL]) && key[KEY_END]) || (mouse_b & 4))
			mousecapture = 0;

                if ((key[KEY_LCONTROL] || key[KEY_RCONTROL]) && key[KEY_ALT] && key[KEY_PGDN])
                {
			int old_winsizex = winsizex, old_winsizey = winsizey;
			if (winsizex < 512 || winsizey < 350)
				updatewindowsize(512, 350);
                        gui_enter();
			if (old_winsizex < 512 || old_winsizey < 350)
				updatewindowsize(old_winsizex, old_winsizey);
                        ticks = 0;
                }
        }
        
        closepc();

	midi_close();

        return 0;
}
Beispiel #5
0
int main(int argc, char *argv[])
{
   MIDI *the_music;
   int length, pos;
   int beats, beat;
   int x, y, tw, th;
   int background_color;
   int text_color;
   int paused = 0;
   int done = 0;

   if (allegro_init() != 0)
      return 1;

   if (argc != 2) {
      allegro_message("Usage: 'exmidi filename.mid'\n");
      return 1;
   }

   install_keyboard(); 
   install_timer();

   /* install a MIDI sound driver */
   if (install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL) != 0) {
      allegro_message("Error initialising sound system\n%s\n", allegro_error);
      return 1;
   }

   /* read in the MIDI file */
   the_music = load_midi(argv[1]);
   if (!the_music) {
      allegro_message("Error reading MIDI file '%s'\n", argv[1]);
      return 1;
   }
   length = get_midi_length(the_music);
   beats = -midi_pos; /* get_midi_length updates midi_pos to the negative
                         number of beats (quarter notes) in the midi. */

   if (set_gfx_mode(GFX_AUTODETECT, 320, 200, 0, 0) != 0) {
      if (set_gfx_mode(GFX_SAFE, 320, 200, 0, 0) != 0) {
	 set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
	 allegro_message("Unable to set any graphic mode\n%s\n", allegro_error);
	 return 1;
      }
   }
   
   /* try to continue in the background */
   if (set_display_switch_mode(SWITCH_BACKGROUND))
      set_display_switch_mode(SWITCH_BACKAMNESIA);

   set_palette(desktop_palette);
   background_color = makecol(255, 255, 255);
   text_color = makecol(0, 0, 0);
   clear_to_color(screen, background_color);
   th = text_height(font);
   x = SCREEN_W / 2;

   textprintf_centre_ex(screen, font, x, SCREEN_H / 3, text_color, -1,
			"Driver: %s", midi_driver->name);
   textprintf_centre_ex(screen, font, x, SCREEN_H / 2, text_color, -1,
			"Playing %s", get_filename(argv[1]));

   /* start up the MIDI file */
   play_midi(the_music, TRUE);

   y = 2 * SCREEN_H / 3;
   tw = text_length(font, "0000:00 / 0000:00");
   /* wait for a key press */
   while (!done) {
       /* P key pauses/resumes, any other key exits. */
      while (keypressed()) {
	 int k = readkey() & 255;
	 if (k == 'p') {
	    paused = !paused;
	    if (paused) {
	       midi_pause();
	       textprintf_centre_ex(screen, font, x, y + th * 3,
		  text_color, -1, "P A U S E D");
	    }
	    else {
	       midi_resume();
	       rectfill(screen, x - tw / 2, y + th * 3, x + tw / 2,
		  y + th * 4, background_color);
	    }
	 }
	 else
	    done = 1;
      }
      pos = midi_time;
      beat = midi_pos;
      rectfill(screen, x - tw / 2, y, x + tw / 2, y + th * 2, background_color);
      textprintf_centre_ex(screen, font, x, y, text_color, -1,
	 "%d:%02d / %d:%02d", pos / 60, pos % 60, length / 60, length % 60);
      textprintf_centre_ex(screen, font, x, y + th, text_color, -1,
	 "beat %d / %d", beat, beats);
      /* We have nothing else to do. */
      rest(100);
   }

   /* destroy the MIDI file */
   destroy_midi(the_music);

   return 0;
}
/////////////////////////////////////
//// MAIN ///////////////////////////
/////////////////////////////////////
int main(int argc, char *argv[])
{
 
/////////////////////////////////////
// START GUI SPECIFIC CODE //////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////
	int bpp; // color depth 
	int ret; // for processing return values
	
	//initialise allegro stuff
	allegro_init(); 
	install_keyboard(); 
	install_timer();

	bpp = desktop_color_depth();
	set_color_depth(bpp);
	
	/* Lets play the color depth game!  tries 32, 24, then 16 bit color modes */
	// set resolution to play intro movie
	ret = set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0);
	/* did the video mode set properly? */
	if (ret != 0) {
		set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
		allegro_message("Error setting %d bit graphics mode\n%s\nLets try another color depth!", bpp, allegro_error);
		
		bpp = 32;
		set_color_depth(bpp);
		
		// set resolution
		ret = set_gfx_mode(GFX_AUTODETECT, 640, 480, 0, 0);
		/* did the video mode set properly? */
		if (ret != 0) {
			set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
			allegro_message("Error setting %d bit graphics mode\n%s\nLets try another color depth!", bpp, allegro_error);

			bpp = 16;
			set_color_depth(bpp);

			// set resolution
			ret = set_gfx_mode(GFX_AUTODETECT, 640, 480, 0, 0);
			/* did the video mode set properly? */
			if (ret != 0) {
				set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
				allegro_message("Error setting %d bit graphics mode\n%s\nIm all out of options. Exiting", bpp, allegro_error);
				return 1;
			}
		}
	}
	
///////////////////////////
// END OF GUI SPECIFIC //////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////

//////////////////////////
///// VARIABLES //////////
//////////////////////////

	CEdge edgelist; //the edges
	int besttour = MAX_DISTANCE*NUM_TOWNS; //best result ever
	int currtour = MAX_DISTANCE*NUM_TOWNS; //best result from last tour
	int bestant = -1; //stores ant that did really well and adds more phero to its trail
	CAnt colony[NUM_ANTS]; //the ants

	int i,j; //universal for loop counters
	
	int cycles=0;
	
	srand(time(NULL));		 //seed random number
	int limit;				//universal random number limit.. (rand()%limit will give a number between 0 and limit-1)

	// Start Cycling
	while (!key[KEY_ESC] && cycles < MAX_CYCLES) {
		
		textprintf(screen,font,5,5,makecol(255,0,0),"Press Esc to hault processing [Cycle %d]",cycles);
		
		//initialise the ants before they all do a tour	
		//sets each ants first town to somewhere random
		
		limit = NUM_TOWNS;
		for (i=0;i<NUM_ANTS;i++) {			
			//colony[i].SetTown(0,i); //set each ants first tour element to a town 
			colony[i].SetTown(0,rand()%limit); //random version
		}	
		
		
		//each time though loop add another node to each ants tour list 
		//starting at the 2nd node (the 1st node is already set)
		limit = NUM_TOWNS+1;				
		double distance;
		double pheromone;	
		double probability;
		double total;
		double p[NUM_TOWNS];

		for (int tourcount=1;tourcount<NUM_TOWNS;tourcount++) {
			
			for (i=0;i<NUM_ANTS;i++) { //for each ant.. add 1 more tour
				
				//reset probabilities
				probability=0;
				total=0;
				
				//calculate best probability from all possible new paths
				
				//loop through all remaining possible tours left on the current ant
				//each time through the loop calc probability and keep track of best
				int k;
				for (j=tourcount,k=0;j<NUM_TOWNS;j++,k++) {
					
					//get variables used to calc probability
					distance = edgelist.GetDistance(colony[i].GetTown(tourcount-1), colony[i].GetTown(j));
					pheromone = edgelist.GetPhero(colony[i].GetTown(tourcount-1), colony[i].GetTown(j));
					
					probability = pow(pheromone, ALPHA);
					probability = probability * pow(distance, -BETA);
					
					p[k] = probability;
					total += probability;
					
				}
				
				//choose new town based on probability
				int best = 0;
				for (j=0;j<k;j++) {
					
					if ((p[best]/total)  > (p[j]/total)) {
						//new best
						best = j; 
					}
					
				}
				
				//move current ant to new town
				colony[i].SetTown(tourcount, colony[i].GetTown(tourcount+best));
				
			}//for ant
		}
		

		//////////////////////////////////////
		//ants now have full tour lists
		//compute length of each ants list
		//////////////////////////////////////
		for (i=0;i<NUM_ANTS;i++) { //for each ant
			
			int distance = 0;
			
			//reset currtour
			currtour = MAX_DISTANCE*NUM_TOWNS;
			
			printf("\nant %d [%d",i,colony[i].GetTown(0));//display ants tour in console window
			
			for (int j=1;j<NUM_TOWNS;j++) { //for each edge in the ants tour
				
				printf(",%d",colony[i].GetTown(j));//display ants tour in console window
				distance += edgelist.GetDistance(colony[i].GetTown(j-1), colony[i].GetTown(j));
				
			}
			
			printf("]");//display ants tour in console window
			
			//add on loopback distance
			distance += edgelist.GetDistance(colony[i].GetTown(NUM_TOWNS-1), colony[i].GetTown(0));
			
			printf("=%d",distance);//display ants tour distance in console window

			//keep record of best tours
			if (distance < besttour) {
				besttour = distance;
				bestant = i; //we only add extra phero to a tour when a best tour "record" is broken
			}
			if (distance < currtour)
				currtour = distance;

			//store distance on ant
			colony[i].SetDistance(distance);
		}

		
		/////////////////////////
		//evaporate pheromones
		/////////////////////////
		edgelist.Evaporate(EVAP);


		//////////////////////////////////////////////////
		//lay new pheromones based on colony[i].distance
		//////////////////////////////////////////////////
		for (i=0;i<NUM_ANTS;i++) {
			
			double phero;
			
			for (int j=1;j<NUM_TOWNS;j++) { //for each edge in the ants tour
				
				phero = edgelist.GetPhero(colony[i].GetTown(j-1), colony[i].GetTown(j)); //get old phero
				phero = phero + QUE / colony[i].GetDistance(); //calc new phero
				
				//reinforce best path
				if (bestant != -1 && i == bestant) {
					phero += ADD_PHERO;
				}

				edgelist.SetPhero(colony[i].GetTown(j-1), colony[i].GetTown(j), phero);
			}
			
			//loop back 
			phero = edgelist.GetPhero(colony[i].GetTown(NUM_TOWNS-1), colony[i].GetTown(0)); //get old phero
			phero = phero + QUE / colony[i].GetDistance(); //calc new phero
			
			//reinforce best path
			if (bestant != -1 && i == bestant) {
				phero += ADD_PHERO;
				bestant = -1;
			}

			edgelist.SetPhero(colony[i].GetTown(NUM_TOWNS-1), colony[i].GetTown(0), phero); //set phero
		}

		
		/////////////////////////////
		//reset ants and do it again
		/////////////////////////////
		for (i=0;i<NUM_ANTS;i++) {
			
			colony[i].ResetAnt();
			
		}
				
		//cycle done
		
		cycles ++;
		Draw(cycles, currtour, besttour);

	}

	clear_keybuf();
	textprintf_centre(screen,font,SCREEN_W/2,SCREEN_H/2-60,makecol(255,0,0),"Best Tour = %d",besttour);
	textout_centre(screen,font,"Press a key to exit",SCREEN_W/2,SCREEN_H/2-40,makecol(255,0,0));
	readkey();

	return 0;
}
Beispiel #7
0
int main (void) {
    allegro_init();
    install_keyboard();
    install_timer();

    set_color_depth(32);
    set_gfx_mode(GFX_AUTODETECT_WINDOWED, SCREENX*SCALE, SCREENY*SCALE, 0, 0);
    set_window_title("Ultra Tank Destruction Battle Game");
    BITMAP * buffer = create_bitmap(SCREEN_W, SCREEN_H);

    install_int_ex(ticker, BPS_TO_TIMER(30));


    int tankx = 0, tanky = 0;
    int speed = 1;
    int tanksizex = 16, tanksizey = 16;
    int tankframe = 0, tankdir = 0;
    int walking = 0, shooting = 0;

    int xoffset = 0, yoffset = 0;

    int bullet = 0, bulletspeed = 3;
    int bulleton[BULLETS], bulletx[BULLETS], bullety[BULLETS], bulletspeedx[BULLETS], bulletspeedy[BULLETS];
    int shot = 0;

    int level[LEVELSIZEX*LEVELSIZEY] =
        {   2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,
            2,2,2,2,2,3,2,2,2,2,2,2,5,2,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,
            3,3,3,3,3,3,3,3,3,3,3,2,4,2,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,
            2,2,2,2,2,5,2,2,2,2,3,2,2,2,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,

            2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,
            2,2,2,2,2,3,2,2,2,2,2,2,5,2,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,
            3,3,3,3,3,3,3,3,3,3,3,2,4,2,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,
            2,2,2,2,2,5,2,2,2,2,3,2,2,2,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,

            2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,
            2,2,2,2,2,3,2,2,2,2,2,2,5,2,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,
            3,3,3,3,3,3,3,3,3,3,3,2,4,2,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,
            2,2,2,2,2,5,2,2,2,2,3,2,2,2,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,

            2,2,2,2,5,4,2,2,2,2,3,2,2,5,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,
            5,2,2,2,4,2,2,2,2,2,3,2,2,4,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,
            4,2,2,2,2,2,2,2,5,2,3,3,3,3,3,3,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,
            2,2,2,2,2,2,2,2,4,2,3,2,2,2,2,2,    2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2,     };

    for (int i = 0; i < BULLETS; i++) {
        bulleton[i] = 0;
        bulletx[i] = 0;
        bullety[i] = 0;
        bulletspeedx[i] = 0;
        bulletspeedy[i] = 0;
    }


    BITMAP * tank = load_bitmap("mechtest/extremetankn.bmp", NULL);
    BITMAP * bulletimg = load_bitmap("mechtest/bullet.bmp", NULL);
    BITMAP * tilemap = load_bitmap("mechtest/tilemap.bmp", NULL);


    int running = 1;
    while (running) {

        rectfill(buffer, 0, 0, SCREEN_W-1, SCREEN_H-1, WHITE);

        poll_keyboard();
        if (key[KEY_ESC]) running = 0;

// ---------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------
        walking = 0;
        if (key[KEY_LEFT])  {tankdir = 0;   tankx-=speed;   walking=1;}
        if (key[KEY_RIGHT]) {tankdir = 1;   tankx+=speed;   walking=1;}
        if (key[KEY_UP])    {tankdir = 2;   tanky-=speed;   walking=1;}
        if (key[KEY_DOWN])  {tankdir = 3;   tanky+=speed;   walking=1;}

        if (key[KEY_S]) {
            if (!shot) {
                shot = 1;
                shooting = 1;
                bulleton[bullet] = 1;

                bulletspeedx[bullet] = 0;
                bulletspeedy[bullet] = 0;


                if (tankdir == 0) {
                    bulletx[bullet] = tankx - bulletimg->w;
                    bullety[bullet] = tanky + tanksizey/2 - bulletimg->h/2;
                    bulletspeedx[bullet] -= bulletspeed;

                }
                if (tankdir == 1) {
                    bulletx[bullet] = tankx + tanksizex;
                    bullety[bullet] = tanky + tanksizey/2 - bulletimg->h/2;
                    bulletspeedx[bullet] += bulletspeed;
                }
                if (tankdir == 2) {
                    bulletx[bullet] = tankx + tanksizex/2 - bulletimg->w/2;
                    bullety[bullet] = tanky - bulletimg->w/2;
                    bulletspeedy[bullet] -= bulletspeed;
                }
                if (tankdir == 3) {
                    bulletx[bullet] = tankx + tanksizex/2 - bulletimg->w/2;
                    bullety[bullet] = tanky + tanksizey;
                    bulletspeedy[bullet] += bulletspeed;
                }

                bullet++;
                if (bullet >= BULLETS) bullet = 0;
            }
        } else {
            shot = 0;
            shooting = 0;
        }


        xoffset = tankx - SCREENX/2 + tanksizex/2;
        yoffset = tanky - SCREENY/2 + tanksizey/2;

        if (xoffset > LEVELSIZEX*TILESIZE - SCREENX - 1) xoffset = LEVELSIZEX*TILESIZE - SCREENX - 1;
        if (yoffset > LEVELSIZEY*TILESIZE - SCREENY - 1) yoffset = LEVELSIZEY*TILESIZE - SCREENY - 1;

        if (xoffset < 0) xoffset = 0;
        if (yoffset < 0) yoffset = 0;




        int tilenum = 0;
        int destx1 = (xoffset)/TILESIZE, destx2 = (xoffset + SCREENX)/TILESIZE + 1;
        int desty1 = (yoffset)/TILESIZE, desty2 = (yoffset + SCREENY)/TILESIZE + 1;

        if (destx1 < 0) destx1 = 0;
        if (desty1 < 0) desty1 = 0;
        if (destx2 > LEVELSIZEX) destx2 = LEVELSIZEX;
        if (desty2 > LEVELSIZEY) desty2 = LEVELSIZEY;


        for (int y = desty1; y < desty2; y++) {
            for (int x = destx1; x < destx2; x++) {

                tilenum = level[y*LEVELSIZEX + x];
                stretch_blit(tilemap, buffer, (tilenum%MAPSIZEX)*TILESIZE, (tilenum/MAPSIZEX)*TILESIZE, TILESIZE, TILESIZE, (x*TILESIZE-xoffset)*SCALE, (y*TILESIZE-yoffset)*SCALE, TILESIZE*SCALE, TILESIZE*SCALE);


            }
        }



        if (walking) {
            if (tankframe == 1) {
                tankframe = 0;
            } else {
                tankframe = 1;
            }
        }
        masked_stretch_blit(tank, buffer, tankframe*tanksizex, tankdir*tanksizey, tanksizex, tanksizey, (tankx-xoffset)*SCALE, (tanky-yoffset)*SCALE, tanksizex*SCALE, tanksizey*SCALE);


        for (int i = 0; i < BULLETS; i++) {
            if (bulleton[i]) {
                bulletx[i] += bulletspeedx[i];
                bullety[i] += bulletspeedy[i];

                masked_stretch_blit(bulletimg, buffer, 0, 0, bulletimg->w, bulletimg->h, (bulletx[i]-xoffset)*SCALE, (bullety[i]-yoffset)*SCALE, bulletimg->w*SCALE, bulletimg->h*SCALE);
            }
        }




        //vsync();
        blit(buffer, screen, 0, 0, 0, 0, buffer->w, buffer->h);

        while (ticks<1) {
            yield_timeslice();
            rest(10);
        }
        ticks=0;
    }

// ---------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------
    destroy_bitmap(tank);
    destroy_bitmap(bulletimg);
    destroy_bitmap(tilemap);

    destroy_bitmap(buffer);
    allegro_exit();
    return 0;
}
int main (int argc, char *argv[]) {
	allegro_init(); // Initialize Allegro
	install_keyboard(); // Initialize keyboard routines
	install_timer(); // Initialize the timer routines

<<<<<<< HEAD
/**
 * Main function.
 */
int main(int argc, const char *argv[]) {
	int i, done;
	
	testMainScreenWidth = 320;
	testMainScreenHeight = 200;
	initializeAllegroStuff();
	zoneAllocatorInitialize();
	systemGraphicsInitialize();
	initializeWadFile(WAD_FILE_PATH);
	initializeStaticGraphicsData();
	initializeStaticGameData();
	systemGraphicsSetPalette((unsigned char *)getWadFileLumpContentsByName("PLAYPAL"));
	
	loadMap(1);
	prepareAutomap();
	
	install_timer();
	install_int(&timerCallback, 10);
	
	done = 0;
	while (!done) {
		
		/** wait for timer tick **/
		while (!timerTick);
		timerTick = 0;
		
		/** update key states **/
		sampleKeyboard();

		/** handle control keys **/
		if (key[KEY_ESC]) {
			done = 1;
		}
		if (key[KEY_ENTER]) {
			showFirstPersonView();
		}
		
		/** handle map change keys **/
		for (i=0; i<9; i++) {
			if (key[mapChangeKeys[i]]) {
				loadMap(i + 1);
				prepareAutomap();
			}
		}
		
		/** handle movement keys **/
		if (!getAutomapMovementKeysCaptured()) {
			int multiplier = key[KEY_LSHIFT] ? 5 : 1;
			Angle angle = key[KEY_LEFT] ? 1 : key[KEY_RIGHT] ? -1 : 0;
			int movement = key[KEY_UP] ? 1 : key[KEY_DOWN] ? -1 : 0;
			int floating = key[KEY_Q] ? 1 : key[KEY_A] ? -1 : 0;
			
			playerAngle += angle << 25;
			playerX += cosForAngle(playerAngle) * movement * multiplier * 5;
			playerY += sinForAngle(playerAngle) * movement * multiplier * 5;
			playerZ += FIXED_POINT_NUMBER_ONE * floating * multiplier * 3;
			
			if (floating != 0 || key[KEY_U]) {
				clear(screen);
				drawFirstPersonView();
				while (!timerTick);
				timerTick = 0;
				while (!timerTick);
				timerTick = 0;
			}
		}
		
		/** regular work **/
		drawAutomap();
		runAutomapTicker();
		
	}
	
	return 0;
}
Beispiel #10
0
/** Parse one event from itrm_in.queue and append to itrm_out.queue.
 * @pre On entry, @a *itrm must not be blocked.
 * @returns the number of bytes removed from itrm->in.queue; at least 0.
 * @post If this function leaves the queue not full, it also reenables
 * reading from itrm->in.std.  (Because it does not add to the queue,
 * it never need disable reading.)  */
static int
process_queue(struct itrm *itrm)
{
	struct interlink_event ev;
	int el = 0;

	if (!itrm->in.queue.len) goto return_without_event;
	assert(!itrm->blocked);
	if_assert_failed return 0; /* unlike goto, don't enable reading */

	set_kbd_interlink_event(&ev, KBD_UNDEF, KBD_MOD_NONE);

#ifdef DEBUG_ITRM_QUEUE
	{
		int i;

		/* Dump current queue in a readable form to stderr. */
		for (i = 0; i < itrm->in.queue.len; i++)
			if (itrm->in.queue.data[i] == ASCII_ESC)
				fprintf(stderr, "ESC ");
			else if (isprint(itrm->in.queue.data[i]) && !isspace(itrm->in.queue.data[i]))
				fprintf(stderr, "%c ", itrm->in.queue.data[i]);
			else
				fprintf(stderr, "0x%02x ", itrm->in.queue.data[i]);

		fprintf(stderr, "\n");
		fflush(stderr);
	}
#endif /* DEBUG_ITRM_QUEUE */

	/* el == -1 means itrm->in.queue appears to be the beginning of an
	 *          escape sequence but it is not yet complete.  Set a timer;
	 *          if it times out, then assume it wasn't an escape sequence
	 *          after all.
	 * el == 0 means this function has not yet figured out what the data
	 *         in itrm->in.queue is, but some possibilities remain.
	 *         One of them will be chosen before returning.
	 * el > 0 means some bytes were successfully parsed from the beginning
	 *        of itrm->in.queue and should now be removed from there.
	 *        However, this does not always imply an event will be queued.
	 */

	/* ELinks should also recognize U+009B CONTROL SEQUENCE INTRODUCER
	 * as meaning the same as ESC 0x5B, and U+008F SINGLE SHIFT THREE as
	 * meaning the same as ESC 0x4F, but those cannot yet be implemented
	 * because of bug 777: the UTF-8 decoder is run too late.  */
	if (itrm->in.queue.data[0] == ASCII_ESC) {
		if (itrm->in.queue.len < 2) {
			el = -1;
		} else if (itrm->in.queue.data[1] == 0x5B /* CSI */) {
			el = decode_terminal_escape_sequence(itrm, &ev);
		} else if (itrm->in.queue.data[1] == 0x4F /* SS3 */) {
			el = decode_terminal_application_key(itrm, &ev);
		} else if (itrm->in.queue.data[1] == ASCII_ESC) {
			/* ESC ESC can be either Alt-Esc or the
			 * beginning of e.g. ESC ESC 0x5B 0x41,
			 * which we should parse as Esc Up.  */
			if (itrm->in.queue.len < 3) {
				/* Need more data to figure it out.  */
				el = -1;
			} else if (itrm->in.queue.data[2] == 0x5B
				   || itrm->in.queue.data[2] == 0x4F) {
				/* The first ESC appears to be followed
				 * by an escape sequence.  Treat it as
				 * a standalone Esc.  */
				el = 1;
				set_kbd_event(itrm, &ev,
					      itrm->in.queue.data[0],
					      KBD_MOD_NONE);
			} else {
				/* The second ESC of ESC ESC is not the
				 * beginning of any known escape sequence.
				 * This must be Alt-Esc, then.  */
				el = 2;
				set_kbd_event(itrm, &ev,
					      itrm->in.queue.data[1],
					      KBD_MOD_ALT);
			}
		}
		if (el == 0) {	/* Begins with ESC, but none of the above */
			el = 2;
			set_kbd_event(itrm, &ev, itrm->in.queue.data[1],
				      KBD_MOD_ALT);
		}

	} else if (itrm->in.queue.data[0] == 0) {
		static const struct term_event_keyboard os2xtd[256] = {
#include "terminal/key.inc"
		};

		if (itrm->in.queue.len < 2)
			el = -1;
		else {
			el = 2;
			set_kbd_interlink_event(&ev,
						os2xtd[itrm->in.queue.data[1]].key,
						os2xtd[itrm->in.queue.data[1]].modifier);
		}
	}

	if (el == 0) {
		el = 1;
		set_kbd_event(itrm, &ev, itrm->in.queue.data[0],
			      itrm->bracketed_pasting ? KBD_MOD_PASTE : KBD_MOD_NONE);
	}

	/* The call to decode_terminal_escape_sequence() might have changed the
	 * keyboard event to a mouse event. */
	if (ev.ev == EVENT_MOUSE || ev.info.keyboard.key != KBD_UNDEF) {
		itrm_queue_event(itrm, (char *) &ev, sizeof(ev));
		itrm->bracketed_pasting = 
			(ev.ev == EVENT_KBD
			 && (ev.info.keyboard.modifier & KBD_MOD_PASTE));
	}

return_without_event:
	if (el == -1) {
		install_timer(&itrm->timer, ESC_TIMEOUT, (void (*)(void *)) kbd_timeout,
			      itrm);
		return 0;
	} else {
		assertm(itrm->in.queue.len >= el, "event queue underflow");
		if_assert_failed { itrm->in.queue.len = el; }

		itrm->in.queue.len -= el;
		if (itrm->in.queue.len)
			memmove(itrm->in.queue.data, itrm->in.queue.data + el, itrm->in.queue.len);

		if (itrm->in.queue.len < ITRM_IN_QUEUE_SIZE)
			handle_itrm_stdin(itrm);

		return el;
	}
}
Beispiel #11
0
int main(void)
{
 BITMAP *scrbuffer;
 DATAFILE *main_data;
 int vmode_error;

 RGB black = { 0,  0,  0 };

 // initialise allegro
 allegro_init();
 install_keyboard();
 install_timer();
 //install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL);

 // load main data file into memory
 main_data = load_datafile("dogfight.dat");

 // use the palette stored in the datafile and
 // set the "clear" colour from a working hot pink to an invisible black
 memcpy(&pal, main_data[MAINPAL].dat, sizeof(pal));

 // enter graphics mode -- don't debug from here --
 vmode_error = set_gfx_mode(GFX_AUTODETECT, SET_W, SET_H, 0, 0);
 if (vmode_error) {
   printf("Error setting graphics mode...\n%s\n\n", allegro_error);
   allegro_exit();
   exit(1);
 }

 set_palette(pal);
 set_color(0, &black);

 // build a colour lookup table for translucent drawing
 // NB: 128 translucency = 50%
 textout_centre_ex(screen, main_data[FONTSMALL].dat, "Dogfight by Gregory McIntyre", SCREEN_W/2, SCREEN_H/2-58, GREY+15, -1);
 textout_centre_ex(screen, font, "Loading. Please wait...", SCREEN_W/2, SCREEN_H/2-20, GREY+15, -1);
 callback_count = 0;
 create_trans_table(&trans_table, main_data[MAINPAL].dat, CLOUD_TRANSPARENCY, CLOUD_TRANSPARENCY, CLOUD_TRANSPARENCY, callback_func);

 // allocate memory for screen buffer
 scrbuffer = create_bitmap(SCREEN_W, SCREEN_H); clear(scrbuffer);

 // when everything is ready fade out and go to the title screen
 fade_out(10);
 title_page(scrbuffer, main_data);

 // free allocated memory and exit allegro
 destroy_bitmap(scrbuffer);

 unload_datafile(main_data);
 allegro_exit();

 // print a message that will be displayed at the DOS prompt on leaving
 printf("Thankyou for playing Dogfight.\n");
 printf("Dogfight was created using the Allegro game library.\n");
 printf("It's free so enjoy and distribute at your leasure.\n\n");

 printf("-------------------------------\n");
 printf("The author can be contacted at:\n\n");
 printf("[email protected]*\n\n");
 printf("-------------------------------\n\n");
 printf("Have a nice day!\n");
 printf("\n");
 printf("* Email no longer valid.\n");
 return 0;
}
Beispiel #12
0
void alleg_init() {
	allegro_init();
	install_timer();
	install_keyboard();
}
Beispiel #13
0
/********************* Main*/
int omain(int argc, char *argv[]){
	int i, cnt, cntt, cnttt, way;
	static char file[MAXC], attr[MAXC], val[MAXC], *p, *binver;
	#if defined(ALLEGRO_WINDOWS)
	binver = "Windows binary";
	#elif defined(ALLEGRO_DOS)
	binver = "DOS binary";
	#elif defined(ALLEGRO_LINUX)
	binver = "Linux binary";
	#elif defined(ALLEGRO_BEOS)
	binver = "BEOS binary";
	#elif defined(ALLEGRO_QNX)
	binver = "QNX binary";
	#elif defined(ALLEGRO_UNIX)
	binver = "UNIX binary";
	#elif defined(ALLEGRO_MPW)
	binver = "MacOS binary";
	#else
	binver = "Unknown binary";
	#endif
	printf("%s %s\n","\nO2EM v" O2EM_VERSION " " RELEASE_DATE "  - ", binver);
	printf("Free Odyssey2 / Videopac+ Emulator - http://o2em.sourceforge.net\n");
	printf("Created by Daniel Boris (c)1996/1998\n");
    printf("Developed by:\n");
	printf("     Andre de la Rocha since version 0.80\n");
	printf("     Arlindo M. de Oliveira since version 1.16\n");
    printf("\n");

    app_data.debug = 0;
	app_data.stick[0] = app_data.stick[1] = 1;
	app_data.sticknumber[0] = app_data.sticknumber[1] = 0;
	set_defjoykeys(0,0);
	set_defjoykeys(1,1);
	set_defsystemkeys();
	app_data.bank = 0;
	app_data.limit = 1;
	app_data.sound_en = 1;
	app_data.speed = 100;
	app_data.wsize = 2;
	#ifdef ALLEGRO_DOS
	app_data.fullscreen = 1;
	#else
	app_data.fullscreen = 0;
	#endif
	app_data.scanlines = 0;
	app_data.voice = 1;
	app_data.window_title = "O2EM v" O2EM_VERSION;
	app_data.svolume = 100;
	app_data.vvolume = 100;
	app_data.filter = 0;
	app_data.exrom = 0;
	app_data.three_k = 0;
	app_data.crc = 0;
	app_data.scshot = scshot;
	app_data.statefile = statefile;
	app_data.euro = 0;
	app_data.openb = 0;
	app_data.vpp = 0;
	app_data.bios = 0;
	app_data.scoretype = 0;
	app_data.scoreaddress = 0;
	app_data.default_highscore = 0;
	app_data.breakpoint = 65535;
	app_data.megaxrom = 0;
	strcpy(file,"");
	strcpy(file_l,"");
	strcpy(bios_l,"");
    strcpy(bios,"");
	strcpy(scshot,"");
	strcpy(statefile,"");
    strcpy(xrom,"");
	strcpy(scorefile,"highscore.txt");
	read_default_config();
	if (argc >= 2){
    for(i=1; i<argc; i++) {
		if (argv[i][0] != '-') 	{
			strncat(file,argv[i],MAXC-1);
	        file[MAXC-1]=0;
	        strcpy(file_v,file);
		} else {
			p=strtok(argv[i],"=");
	        if (p){
				strncpy(attr,p+1,MAXC-1);
				attr[MAXC-1]=0;
			   } else
				strcpy(attr,"");
			    p=strtok(NULL,"=");
			if (p){
				strncpy(val,p,MAXC-1);
				val[MAXC-1]=0;
			    if (!strcmp(attr,"romdir")||!strcmp(attr,"ROMDIR"))
                   {
                    strcpy(romdir,val);
                    strcat(romdir,file);
                    strcpy(file,romdir);
                    strcpy(romdir,val);
                   }
                if (!strcmp(attr,"biosdir")||!strcmp(attr,"BIOSDIR"))
                   {
                    strcpy(biosdir,val);
                   }                                       
            } else
			strcpy(val,"");
			strlwr(attr);
			if (!parse_option(attr, val)) exit(EXIT_FAILURE);
		}
    }
    if (helpflag) helpus();
    if (strlen(file)==0) {
		fprintf(stderr,"Error: file name missing\n");
		exit(EXIT_FAILURE);
	}

#ifdef __LIBRETRO__
sprintf(statefile,"%s.state\0",file);
#endif
	printf("Starting emulation ...\n");
#ifndef __LIBRETRO__
	allegro_init();
	install_timer();
#endif
	init_audio();

#ifndef __LIBRETRO__
	printf("Using Allegro %s\n",allegro_id);
#endif 


/********************** ROMs if Launcher running... */
    k = strchr(romdir, '/'); 

    launcher_flag_r = strchr(file, '\\');

    if (k != 0) {
                 strcpy (xrom,romdir);
                }
                else if (!launcher_flag_r)
                        {

                        strcpy(xrom,"roms/");
                        strcpy(romdir,file);
#ifndef __LIBRETRO__
                        strcpy(file,xrom);
                        strcat(file,romdir);
#endif
                        strcpy(romdir,xrom);

                        }
                        else
                        {    
         
                        cnt = 0;
                        cntt = 0;
                        cnttt = 0;
                        way = 0;
                        for (cnt=0; file[cnt] != '\0'; cnt=cnt+1) 
                        { 
                        if ( file[cnt] == '\\' ) 
                           {
                           cnttt = cnt;
                           }
                        } 
                        for (cnt=0; cnt<=cnttt; cnt++)
                        { 
                        file_l[cnt] = file[cnt];
                        } 

                        strcpy (romdir,file_l);
                        strcpy (xrom,romdir);
                        }

#ifdef __LIBRETRO__
#ifdef AND
	sprintf(xrom,"%s\0","/mnt/sdcard/O2EM/roms/");
	strcpy(romdir,xrom);
#else
	sprintf(xrom,"%s\0","./roms/");
	strcpy(romdir,xrom);
#endif
#endif


    file_name(xrom);

    if (contax < 3)
                 {
                 printf("\nROMs directory empty!\n");
                 exit(EXIT_FAILURE);
                 }

    app_data.crc = crc32_file(file);

    crcx = app_data.crc;
    suck_roms(); 

/********************** BIOSs if Launcher running... */     
launcher_flag_b = strchr(bios, '\\');

if (!launcher_flag_b){
    k = strchr(biosdir, '/');

    if (k != 0) {    
                 strcpy (xbios,biosdir);
                }
                else           
                        {
                        strcpy (xbios,"bios/");
                        strcpy (biosdir,xbios);
                        }
#ifdef __LIBRETRO__
#ifdef AND
	sprintf(xbios,"%s\0","/mnt/sdcard/O2EM/bios/");
	strcpy (biosdir,xbios);
#else	
	sprintf(xbios,"%s\0","./bios/");
	strcpy (biosdir,xbios);
#endif
#endif

    file_name(xbios);

    if (contax < 3)
                 {
                 printf("\nBIOS directory empty!\n");
                 exit(EXIT_FAILURE);                 
                 }

    suck_bios();

    c_j = strcmp(bios,"jopac");
    if ((rom_f!=1) && (c_j!=0)) strcpy(bios,g7400);
    if ((!o2flag) && (!jopflag) && (!c52flag) && (!g74flag))
                                              {
                                             printf("\ndir '%s' without BIOS !",biosdir);
                                             exit(EXIT_FAILURE);
                                              }
    printf("BIOS found:\n");
    if (!strcmp(bios,"g7400")){
                               strcpy(bios,g7400);
                               if (g74flag != 1) {
                                             printf("\nG7400 BIOS not found !");
                                             exit(EXIT_FAILURE);
                                             } 
                               }
    if (g74flag) printf("  G7400 VP+\n");
    if (!strcmp(bios,"c52")){ 
                             strcpy(bios,c52);
                             if (c52flag != 1) {
                                             printf("\nC52 BIOS not found !");
                                             exit(EXIT_FAILURE);
                                             } 
                                 }
    if (c52flag) printf("  C52\n");
    if (!strcmp(bios,"jopac")){
                               strcpy(bios,jopac);
                               if (jopflag != 1) {
                                          printf("\nJOPAC BIOS not found !");
                                          exit(EXIT_FAILURE);
                                             } 
                               }
    if (jopflag) printf("  JOPAC VP+\n");
    if ((!strcmp(bios,"")) || (!strcmp(bios,"o2rom")))
                            {
                            strcpy(bios,odyssey2);
                            if ((!o2flag)&&(!c52flag)&&(rom_f)){
                                             printf("Odyssey2 BIOS not found !\n");
                                             exit(EXIT_FAILURE);
                                             } 
                            if ((!o2flag)&&(c52flag)&&(rom_f)){
                                             printf("\nOdyssey2 BIOS not found !\n");
                                             printf("Loading C52 BIOS ... ");
                                             strcpy(bios,c52);
                                             }
                            }
    if (o2flag) printf("  Odyssey 2\n");
    }                                           
    if (launcher_flag_b)
       {
       identify_bios(bios);
                if (rom_f!=1)
                   {
                   if (!((g74flag)||(jopflag)))
                      {
                      fprintf(stderr,"\nError: ROM only VP+ BIOS");
                      exit(EXIT_FAILURE);
                      }
                   }
       }      


      if (!launcher_flag_b)
                  {  
                  if (rom_f!=1)
                     {  
                     if (!((g74flag)||(jopflag)))
                         {
                         printf("\nROM only VP+ BIOS\n");
                         exit(EXIT_FAILURE);
                         }
                     if (!(g74flag))
                         {
                         printf("\nVP+ G7400 BIOS not found !");
                         printf("\nLoading VP+ Jopac BIOS ...");
                         strcpy(bios,jopac);
                         }
                     }
                  }
    load_bios(bios);

	load_cart(file);
	if (app_data.voice) load_voice_samples(path);

	init_display();

	init_cpu();

	init_system();

	set_score(app_data.scoretype, app_data.scoreaddress, app_data.default_highscore);
	int stateError;
	if ((stateError=loadstate(app_data.statefile))==0)
	{
		printf("Savefile loaded.");
	}
	else if (stateError>=199)
	{
		if (stateError==199) fprintf(stderr,"Wrong ROM-File for Savefile.");
		else if (stateError==200+ROM_O2) fprintf(stderr,"Wrong BIOS for Savefile: O2ROM needed.");
		else if (stateError==200+ROM_G7400) fprintf(stderr,"Wrong BIOS for Savefile: G7400 ROM needed.");
		else if (stateError==200+ROM_C52) fprintf(stderr,"Wrong BIOS for Savefile: C52 ROM needed.");
		else if (stateError==200+ROM_JOPAC) fprintf(stderr,"Wrong BIOS for Savefile: JOPAC ROM needed.");
		else fprintf(stderr,"Wrong BIOS for Savefile: UNKNOWN ROM needed.");
		return(0);
	}
	if (app_data.debug) key_debug=1;
	#ifndef _DEBUG
	#ifdef ALLEGRO_WINDOWS
	FreeConsole();
	#endif
	#endif

#ifdef __LIBRETRO__
return 1;
#endif
	run();

    if (app_data.scoretype!=0) save_highscore(get_score(app_data.scoretype, app_data.scoreaddress), scorefile);
	exit(EXIT_SUCCESS);
 }
if (!strcmp(attr,"help")||!strcmp(attr,"HELP")) helpus();
printf("type o2em -help");
exit(EXIT_SUCCESS);
}
Beispiel #14
0
static struct graphics_device *
directfb_init_device (void)
{
  struct graphics_device *gd;
  DFBDeviceData          *data;
  IDirectFBWindow        *window;
  DFBWindowDescription    desc;

  if (!dfb || !layer)
    return NULL;

  desc.flags  = DWDESC_WIDTH | DWDESC_HEIGHT | DWDESC_POSX | DWDESC_POSY;
  /*desc.width  = directfb_driver.x;
  desc.height = directfb_driver.y;
  desc.posx   = 0;
  desc.posy   = 0;*/
  desc.width  = (int)w;
  desc.height = (int)h;
  desc.posx   = (int)x;
  desc.posy   = (int)y;

  if (layer->CreateWindow (layer, &desc, &window) != DFB_OK)
    return NULL;

  gd = mem_alloc (sizeof (struct graphics_device));

  gd->size.x1 = 0;
  gd->size.y1 = 0;
  window->GetSize (window, &gd->size.x2, &gd->size.y2);

  gd->clip = gd->size;

  data = mem_alloc (sizeof (DFBDeviceData));

  data->window       = window;
  data->mapped       = 0;
  data->flip_pending = 0;
  data->flipWindow   = 0;
  data->ghostWindow  = 0;

  if (arrow)
    window->SetCursorShape (window, arrow, arrow_hot_x, arrow_hot_y);

  window->GetSurface (window, &data->surface);
  window->GetID (window, &data->id);

  gd->drv = &directfb_driver;
  gd->driver_data = data;
  gd->user_data   = NULL;

  directfb_add_to_table (gd);

  if (!events)
    {
      window->CreateEventBuffer (window, &events);
      event_timer = install_timer (20, directfb_check_events, events);
    }
  else
    {
      window->AttachEventBuffer (window, events);
    }

  return gd;
}
int install()
{
    int screen_mode;

    if(IsInstalled)
        return 0;
    if(allegro_init())
        return 1;
    if(install_allegro_gl())
        return 1;
    set_window_title("Sharp Fighters");

    Resolutions=get_gfx_mode_list(GFX_OPENGL_FULLSCREEN);

    LoadSettings();

   LoadCollisionData();

    if(install_keyboard())
        return 1;
    if(install_timer())
        return 1;
    if(install_sound(DIGI_AUTODETECT, MIDI_NONE, NULL))
        return 1;

    JoyStickEnabled=(install_joystick(JOY_TYPE_AUTODETECT)==0);
    JoyStickEnabled=JoyStickEnabled && num_joysticks;
    LoadInput();

    if(install_fonts())
        printf("One or more font files were not loaded.\n");

    allegro_gl_set(AGL_COLOR_DEPTH, depth);
    allegro_gl_set(AGL_RENDERMETHOD, 1);
    allegro_gl_set(AGL_DOUBLEBUFFER, 1);
    allegro_gl_set(AGL_SUGGEST, AGL_COLOR_DEPTH | AGL_DOUBLEBUFFER | AGL_RENDERMETHOD);

    if(Fullscreen)
        screen_mode=GFX_OPENGL_FULLSCREEN;
    else
        screen_mode=GFX_OPENGL_WINDOWED;

    if (set_gfx_mode(screen_mode, Width,Height, 0, 0))
    {
        set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
        allegro_message("Unable to set graphic mode\n%s\n", allegro_error);
        return 1;
    }
    set_close_button_callback(close_button_handler);
    SetOpenGL2D();
    screenimage=(IMAGE*)malloc(sizeof(IMAGE));
    screenimage->ID=0;
    AspectRatio=(float)SCREEN_W/(float)SCREEN_H;

    if(install_int(Ticks,1))
        return 1;
    if(install_int(ProcessKeys,25))
        return 1;

    IsInstalled=1;
    return 0;
}
Beispiel #16
0
void main_init(int argc, char *argv[])
{
        char t[512], *p;
        int c;
        int tapenext = 0, discnext = 0;

        startblit();

        log_open();
        log_info("main: starting %s", VERSION_STR);

        vid_fskipmax = 1;

        al_init_main(argc, argv);

        append_filename(t, exedir, "roms/tube/ReCo6502ROM_816", 511);
        if (!file_exists(t,FA_ALL,NULL) && selecttube == 4) selecttube = -1;

        curtube = selecttube;
        model_check();

        for (c = 1; c < argc; c++)
        {
//                log_debug("%i : %s",c,argv[c]);
/*                if (!strcasecmp(argv[c],"-1770"))
                {
                        I8271=0;
                        WD1770=1;
                }
                else*/
//#ifndef WIN32
                if (!strcasecmp(argv[c], "--help"))
                {
                        printf("%s command line options :\n\n", VERSION_STR);
                        printf("-mx             - start as model x (see readme.txt for models)\n");
                        printf("-tx             - start with tube x (see readme.txt for tubes)\n");
                        printf("-disc disc.ssd  - load disc.ssd into drives :0/:2\n");
                        printf("-disc1 disc.ssd - load disc.ssd into drives :1/:3\n");
                        printf("-autoboot       - boot disc in drive :0\n");
                        printf("-tape tape.uef  - load tape.uef\n");
                        printf("-fasttape       - set tape speed to fast\n");
                        printf("-s              - scanlines display mode\n");
                        printf("-i              - interlace display mode\n");
                        printf("-debug          - start debugger\n");
                        printf("-allegro        - use Allegro for video rendering\n");
                        exit(-1);
                }
                else
//#endif
                if (!strcasecmp(argv[c], "-tape"))
                {
                        tapenext = 2;
                }
                else if (!strcasecmp(argv[c], "-disc") || !strcasecmp(argv[c], "-disk"))
                {
                        discnext = 1;
                }
                else if (!strcasecmp(argv[c], "-disc1"))
                {
                        discnext = 2;
                }
                else if (argv[c][0] == '-' && (argv[c][1] == 'm' || argv[c][1] == 'M'))
                {
                        sscanf(&argv[c][2], "%i", &curmodel);
                }
                else if (argv[c][0] == '-' && (argv[c][1] == 't' || argv[c][1] == 'T'))
                {
                        sscanf(&argv[c][2], "%i", &curtube);
                }
                else if (!strcasecmp(argv[c], "-fasttape"))
                {
                        fasttape = 1;
                }
                else if (!strcasecmp(argv[c], "-autoboot"))
                {
                        autoboot = 150;
                }
                else if (argv[c][0] == '-' && (argv[c][1] == 'f' || argv[c][1]=='F'))
                {
                        sscanf(&argv[c][2], "%i", &vid_fskipmax);
            if (vid_fskipmax < 1) vid_fskipmax = 1;
            if (vid_fskipmax > 9) vid_fskipmax = 9;
                }
                else if (argv[c][0] == '-' && (argv[c][1] == 's' || argv[c][1] == 'S'))
                {
                        vid_scanlines = 1;
                }
                else if (!strcasecmp(argv[c], "-debug"))
                {
                        debug_core = 1;
                }
                else if (!strcasecmp(argv[c], "-debugtube"))
                {
                        debug_tube = 1;
                }
                else if (argv[c][0] == '-' && (argv[c][1] == 'i' || argv[c][1] == 'I'))
                {
                        vid_interlace = 1;
            vid_linedbl = vid_scanlines = 0;
                }
                else if (tapenext)
                   strcpy(tape_fn, argv[c]);
                else if (discnext)
                {
                        strcpy(discfns[discnext-1], argv[c]);
                        discnext = 0;
                }
                else
                {
                    if ((p = strrchr(argv[c], '.')) && (!strcasecmp(p, ".uef") || !strcasecmp(p, ".csw"))) {
                        strncpy(tape_fn, argv[c], sizeof tape_fn);
                        tapenext = 0;
                    }
                    else {
                        strncpy(discfns[0], argv[c], sizeof discfns[0]);
                        discnext = 0;
                        autoboot = 150;
                    }
                }
                if (tapenext) tapenext--;
        }

        video_init();
        mode7_makechars();

#ifndef WIN32
        install_keyboard();
#endif
        install_timer();

        mem_init();
        ddnoise_init();
        tapenoise_init();

        sound_init();
        al_init();
        sid_init();
        sid_settype(sidmethod, cursid);
        music5000_init();

    adc_init();
#ifdef WIN32
        pal_init();
#endif
        disc_init();
        fdi_init();

        scsi_init();
        ide_init();
        vdfs_init();

        model_init();

        midi_init();
        main_reset();

        install_int_ex(secint, MSEC_TO_TIMER(1000));
        install_int_ex(int50,  MSEC_TO_TIMER(20));

        set_display_switch_mode(SWITCH_BACKGROUND);
#ifdef WIN32
                timeBeginPeriod(1);
#endif
        oldmodel = curmodel;

        if (curtube == 3 || mouse_amx) install_mouse();

        disc_load(0, discfns[0]);
        disc_load(1, discfns[1]);
        tape_load(tape_fn);
        if (defaultwriteprot) writeprot[0] = writeprot[1] = 1;

        endblit();

        debug_start();
}
Beispiel #17
0
int main(int argc, char **argv)
{
   SPRITE sprites[SPRITE_COUNT];
   BITMAP *buffer;
   BITMAP *pic;
   BITMAP *tmp;
   char buf[1024];
   char *filename;
   int mode = 0;
   int hold_space = 0;
   char *msg;
   int i;

   /* standard init */
   if (allegro_init() != 0)
      return 1;
   install_timer();
   install_keyboard();

   /* setting graphics mode */
   set_color_depth(16);
   if (set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0) != 0) {
      if (set_gfx_mode(GFX_SAFE, 640, 480, 0, 0) != 0) {
         set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
         allegro_message("Unable to set any graphic mode\n%s\n",
                 allegro_error);
         return 1;
      }
   }

   /* set initial position, direction and drawing for all sprites */
   for (i = 0; i < SPRITE_COUNT; i++)
      setup_sprite(&sprites[i], i);

   /* sort the sprites by drawing level */
   qsort(sprites, SPRITE_COUNT, sizeof(SPRITE), sprite_compare);

   /* locate the bitmap we will use */
   replace_filename(buf, argv[0], "allegro.pcx", sizeof(buf));
   filename = buf;

   /* load the bitmap and stretch it */
   tmp = load_bitmap(filename, NULL);
   pic = create_bitmap(64, 64);
   stretch_blit(tmp, pic, 0, 0, tmp->w, tmp->h, 0, 0, pic->w, pic->h);
   destroy_bitmap(tmp);

   /* we are using double buffer mode, so create the back buffer */
   buffer = create_bitmap(screen->w, screen->h);

   set_trans_blender(128, 0, 64, 128);

   /* exit on Esc key */
   while (!key[KEY_ESC]) {
      /* move every sprite and draw it on the back buffer */
      for (i = 0; i < SPRITE_COUNT; i++) {
         SPRITE *s = &sprites[i];
         move_sprite(s);
         draw_sprite_ex(buffer, pic, s->x, s->y, s->draw_type, mode);
      }

      /* handle the space key */
      if (key[KEY_SPACE] && !hold_space) {
         hold_space = 1;
         /* switch to next flipping mode */
         switch (mode) {
            case DRAW_SPRITE_H_FLIP:
               mode = DRAW_SPRITE_V_FLIP;
               break;
            case DRAW_SPRITE_V_FLIP:
               mode = DRAW_SPRITE_VH_FLIP;
               break;
            case DRAW_SPRITE_VH_FLIP:
               mode = DRAW_SPRITE_NO_FLIP;
               break;
            case DRAW_SPRITE_NO_FLIP:
               mode = DRAW_SPRITE_H_FLIP;
               break;
         }
      }
      if (!key[KEY_SPACE]) {
         hold_space = 0;
      }

      /* set the title according to the flipping mode used */
      if (mode == DRAW_SPRITE_VH_FLIP) {
         msg = "horizontal and vertical flip";
      } else if (mode == DRAW_SPRITE_H_FLIP) {
         msg = "horizontal flip";
      } else if (mode == DRAW_SPRITE_V_FLIP) {
         msg = "vertical flip";
      } else {
         msg = "no flipping";
      }
      textprintf_ex(buffer, font, 1, 1, makecol(255, 255, 255), -1, msg);

      /* finally blit the back buffer on the screen */
      blit(buffer, screen, 0, 0, 0, 0, buffer->w, buffer->h);
      clear_bitmap(buffer);

      /* reduce CPU usage */
      rest(20);
   }

   /* clean up */
   destroy_bitmap(pic);
   destroy_bitmap(buffer);

   return 0;
}
Beispiel #18
0
void main(void) {
    
    int xy,i,j,c,x,y,front,back,n,minc,maxc;
    int ix,iy,k,address,jx,jy,kx,ky;
    float dzdx,dzdy,a,b,dot,norm;
    float rx,ry,sx,sy,px,py;
    long p,q;
    RGB rgb;

    for (x=0;x<scrwid;x++) {
    for (y=0;y<scrhei;y++) {
        kx=x-scrwid/2;
        ky=y-scrhei/2;
        jx=kx*cos(ang)+ky*sin(ang);
        jy=-kx*sin(ang)+ky*cos(ang);
        ix=scrwid/2+(1-0.2*jx/scrwid)*jx;
        iy=scrhei/2+(1-0.2*jy/scrwid)*jy;
        dx[x][y]=ix;
        dy[x][y]=iy;
    }
    }

//    srand(456789);
        srand((int)time(NULL));
        //printf("%d\n",(int)time(NULL));


  allegro_init ();
  install_keyboard ();
  install_timer ();
  set_gfx_mode (GFX_AUTODETECT, scrwid, scrhei, 0, 0);
  set_pallete (desktop_palette);
  buffer = create_bitmap (scrwid, scrhei);
      clear (buffer);

//      textout_centre (buffer, font, "Press SPACE!", 60, 220, 4);


    // Set up grayscale colours
    for (c=0;c<=255;c++) {
        i=0;
        rgb.r=c*63/255;
        rgb.g=0;
        rgb.b=0;
        set_color(c,&rgb);
//        colors[c]=GrAllocColor(c,i,i);
    }
    
        for (x=0; x<scrwid; x++) {
        for (y=0; y<scrhei; y++) {
            putpixel(buffer,x,y,128);
        }
        }

      blit (buffer, screen, 0, 0, 0, 0, scrwid, scrhei);

   _farsetsel(screen->seg);

    while(!key[KEY_ESC]) {
        for (y=0; y<scrhei; y++) {
     movedata(screen->seg, bmp_read_line(screen,y), _my_ds(), tmp[y], scrwid);
     }
        for (x=0; x<scrwid; x++) {
        for (y=0; y<scrhei; y++) {
        c=tmp[dy[x][y]][dx[x][y]];
        c--;
        tmp2[y][x]=c;
        }
        }
        for (y=0; y<scrhei; y++) {
     movedata(_my_ds(), tmp2[y], screen->seg, bmp_write_line(screen,y), scrwid);
     }
for (i=1;i<=10;i++)
        circlefill(screen,myrnd()*scrwid,myrnd()*scrhei,8,myrnd()*255);
//        putpixel(buffer,scrwid/2,scrhei/2,255);

//      blit (buffer, screen, 0, 0, 0, 0, scrwid, scrhei);
    }

destroy_bitmap(buffer);
exit(0);
    getch();

//    GrSetMode(GR_default_text);
    printf("max col %d\n",maxc);
    printf("min col %d\n",minc);
  
}
Beispiel #19
0
int main(int argc, char *argv[])
{
   static char config_override[] = "[system]\nkeyboard = \n";
   RGB black_rgb = {0, 0, 0, 0};
   DATAFILE *font_data;
   int c;

   if (allegro_init() != 0)
      exit(EXIT_FAILURE);

   if (argc > 1) {
      if (strcmp(argv[1], "--split-altgr") == 0) {
         split_altgr = TRUE;
      }
      else {
         allegro_message("Error: unrecognized option\n");
         exit(EXIT_FAILURE);
      }
   }

   install_mouse();
   install_timer();

   push_config_state();
   override_config_data(config_override, sizeof(config_override));
   install_keyboard();
   pop_config_state();

   memcpy(orig_key_ascii_table, _key_ascii_table, sizeof(orig_key_ascii_table));
   memcpy(orig_key_capslock_table, _key_capslock_table, sizeof(orig_key_capslock_table));
   memcpy(orig_key_shift_table, _key_shift_table, sizeof(orig_key_shift_table));
   memcpy(orig_key_control_table, _key_control_table, sizeof(orig_key_control_table));
   memcpy(orig_key_altgr_lower_table, _key_altgr_lower_table, sizeof(orig_key_altgr_lower_table));
   memcpy(orig_key_altgr_upper_table, _key_altgr_upper_table, sizeof(orig_key_altgr_upper_table));
   memcpy(orig_key_accent1_lower_table, _key_accent1_lower_table, sizeof(orig_key_accent1_lower_table));
   memcpy(orig_key_accent1_upper_table, _key_accent1_upper_table, sizeof(orig_key_accent1_upper_table));
   memcpy(orig_key_accent2_lower_table, _key_accent2_lower_table, sizeof(orig_key_accent2_lower_table));
   memcpy(orig_key_accent2_upper_table, _key_accent2_upper_table, sizeof(orig_key_accent2_upper_table));
   memcpy(orig_key_accent3_lower_table, _key_accent3_lower_table, sizeof(orig_key_accent3_lower_table));
   memcpy(orig_key_accent3_upper_table, _key_accent3_upper_table, sizeof(orig_key_accent3_upper_table));
   memcpy(orig_key_accent4_lower_table, _key_accent4_lower_table, sizeof(orig_key_accent4_lower_table));
   memcpy(orig_key_accent4_upper_table, _key_accent4_upper_table, sizeof(orig_key_accent4_upper_table));

   memcpy(my_key_ascii_table, _key_ascii_table, sizeof(my_key_ascii_table));
   memcpy(my_key_capslock_table, _key_capslock_table, sizeof(my_key_capslock_table));
   memcpy(my_key_shift_table, _key_shift_table, sizeof(my_key_shift_table));
   memcpy(my_key_control_table, _key_control_table, sizeof(my_key_control_table));
   memcpy(my_key_altgr_lower_table, _key_altgr_lower_table, sizeof(my_key_altgr_lower_table));
   memcpy(my_key_altgr_upper_table, _key_altgr_upper_table, sizeof(my_key_altgr_upper_table));
   memcpy(my_key_accent1_lower_table, _key_accent1_lower_table, sizeof(my_key_accent1_lower_table));
   memcpy(my_key_accent1_upper_table, _key_accent1_upper_table, sizeof(my_key_accent1_upper_table));
   memcpy(my_key_accent2_lower_table, _key_accent2_lower_table, sizeof(my_key_accent2_lower_table));
   memcpy(my_key_accent2_upper_table, _key_accent2_upper_table, sizeof(my_key_accent2_upper_table));
   memcpy(my_key_accent3_lower_table, _key_accent3_lower_table, sizeof(my_key_accent3_lower_table));
   memcpy(my_key_accent3_upper_table, _key_accent3_upper_table, sizeof(my_key_accent3_upper_table));
   memcpy(my_key_accent4_lower_table, _key_accent4_lower_table, sizeof(my_key_accent4_lower_table));
   memcpy(my_key_accent4_upper_table, _key_accent4_upper_table, sizeof(my_key_accent4_upper_table));

   _key_ascii_table = my_key_ascii_table;
   _key_capslock_table = my_key_capslock_table;
   _key_shift_table = my_key_shift_table;
   _key_control_table = my_key_control_table;
   _key_altgr_lower_table = my_key_altgr_lower_table;
   _key_altgr_upper_table = my_key_altgr_upper_table;
   _key_accent1_lower_table = my_key_accent1_lower_table;
   _key_accent1_upper_table = my_key_accent1_upper_table;
   _key_accent2_lower_table = my_key_accent2_lower_table;
   _key_accent2_upper_table = my_key_accent2_upper_table;
   _key_accent3_lower_table = my_key_accent3_lower_table;
   _key_accent3_upper_table = my_key_accent3_upper_table;
   _key_accent4_lower_table = my_key_accent4_lower_table;
   _key_accent4_upper_table = my_key_accent4_upper_table;

   edit_menu[0].dp = _key_ascii_table;
   edit_menu[1].dp = _key_capslock_table;
   edit_menu[2].dp = _key_shift_table;
   edit_menu[3].dp = _key_control_table;
   edit_menu[4].dp = _key_altgr_lower_table;
   edit_menu[5].dp = _key_altgr_upper_table;
   edit_menu[6].dp = _key_accent1_lower_table;
   edit_menu[7].dp = _key_accent1_upper_table;
   edit_menu[8].dp = _key_accent2_lower_table;
   edit_menu[9].dp = _key_accent2_upper_table;
   edit_menu[10].dp = _key_accent3_lower_table;
   edit_menu[11].dp = _key_accent3_upper_table;
   edit_menu[12].dp = _key_accent4_lower_table;
   edit_menu[13].dp = _key_accent4_upper_table;

   if (!split_altgr)
      edit_menu[5].flags = D_DISABLED;

   if (set_gfx_mode(GFX_AUTODETECT, 640, 480, 0, 0) != 0) {
      if (set_gfx_mode(GFX_SAFE, 640, 480, 0, 0) != 0) {
	 set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
	 allegro_message("Unable to set any graphic mode\n%s\n", allegro_error);
	 return 1;
      }
   }

   set_palette(desktop_palette);
   set_color(0, &black_rgb);
   gui_fg_color = palette_color[255];
   gui_bg_color = palette_color[16];

   /* We set up colors to match screen color depth (in case it changed) */
   for (c = 0; main_dlg[c].proc; c++) {
      main_dlg[c].fg = palette_color[main_dlg[c].fg];
      main_dlg[c].bg = palette_color[main_dlg[c].bg];
   }
   for (c = 0; ascii_dlg[c].proc; c++) {
      ascii_dlg[c].fg = palette_color[ascii_dlg[c].fg];
      ascii_dlg[c].bg = palette_color[ascii_dlg[c].bg];
   }
   for (c = 0; editor_dlg[c].proc; c++) {
      editor_dlg[c].fg = palette_color[editor_dlg[c].fg];
      editor_dlg[c].bg = palette_color[editor_dlg[c].bg];
   }
   for (c = 0; accent_dlg[c].proc; c++) {
      accent_dlg[c].fg = palette_color[accent_dlg[c].fg];
      accent_dlg[c].bg = palette_color[accent_dlg[c].bg];
   }

   _key_standard_kb = FALSE;

   font_data = load_datafile_object ("keyconf.dat", "BASE_FONT");

   if (font_data)
      font = font_data->dat;

   do_dialog(main_dlg, -1);

   if (font_data)
      unload_datafile_object(font_data);

   return 0;
}
void TextureUtil::initGrx() {
  Config * config = Config::getInstance();

#if EM_USE_SDL
  cerr << "Initing SDL" << endl << endl;
  if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) {
    cerr << "Couldn't initialize SDL video" << SDL_GetError() << endl;
    exit(1);
  }

  if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0) {
    cerr << "Couldn't initialize SDL joystick: " <<  SDL_GetError() << endl << endl;
  } else {
    int njoystick = SDL_NumJoysticks();
    cerr << njoystick << " joysticks were found." << endl;
    if (njoystick != 0) {
      cerr << "The names of the joysticks are:" << endl;
      for(int a=0; a<njoystick; a++ ) {
        cerr << "  " << SDL_JoystickName(a) << endl;
      }
      cerr << "Using " << SDL_JoystickName(0) << endl << endl;
      SDL_JoystickOpen(0);
      SDL_JoystickEventState(SDL_ENABLE);
    }
  }

  // See if we should detect the display depth
  if ( SDL_GetVideoInfo()->vfmt->BitsPerPixel <= 8 ) {
    SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 2 );
    SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 3 );
    SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 3 );
  } else        if ( SDL_GetVideoInfo()->vfmt->BitsPerPixel <= 16 ) {
    SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
  }     else {
    SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );
    SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 );
    SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );
  }

  SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
  SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

  /* Initialize the display */
  SDL_Surface* screen =
    SDL_SetVideoMode(config->getWidth(), config->getHeight(), config->getBpp(),
                     SDL_OPENGL
                     | (config->useFullScreen() ? SDL_FULLSCREEN : 0));

  //    if (config->useFullScreen()) {
  SDL_ShowCursor(SDL_DISABLE);
  //    }
  SDL_WM_SetCaption("Emilia Pinball", NULL);

  if (screen == NULL) {
    cerr << "Couldn't set video mode: " << SDL_GetError() << endl;
    exit(1);
  }

  cerr << "Vendor     : " << glGetString( GL_VENDOR ) << endl;
  cerr << "Renderer   : " << glGetString( GL_RENDERER ) << endl;
  cerr << "Version    : " << glGetString( GL_VERSION ) << endl;
  cerr << "Extensions : " << glGetString( GL_EXTENSIONS ) << endl << endl;
  //TODO: that would be usefull to report CPU/RAM specs also //!rzr

  int value;
  SDL_GL_GetAttribute( SDL_GL_RED_SIZE, &value );
  cerr << "SDL_GL_RED_SIZE: " << value << endl;
  SDL_GL_GetAttribute( SDL_GL_GREEN_SIZE, &value );
  cerr << "SDL_GL_GREEN_SIZE: " << value << endl;
  SDL_GL_GetAttribute( SDL_GL_BLUE_SIZE, &value );
  cerr << "SDL_GL_BLUE_SIZE: " << value << endl;
  SDL_GL_GetAttribute( SDL_GL_DEPTH_SIZE, &value );
  cerr << "SDL_GL_DEPTH_SIZE: " << value << endl;
  SDL_GL_GetAttribute( SDL_GL_DOUBLEBUFFER, &value );
  cerr << "SDL_GL_DOUBLEBUFFER: " << value << endl << endl;

  this->resizeView(config->getWidth(), config->getHeight());
#endif // EM_USE_SDL

#if EM_USE_ALLEGRO
  //config->setSize(320, 240);

  allegro_init();
  install_keyboard();
  install_timer();
  install_mouse();

  COLOR_MAP colorMap;
  RGB_MAP rgbMap;
  COLOR_MAP transMap;

  RGB* paPalette = (RGB*) calloc(256, sizeof(RGB));
  generate_332_palette(paPalette);
  // create rgb table
  create_rgb_table(&rgbMap, paPalette, NULL);
  rgb_map = &rgbMap;
  // create light table and setup the truecolor blending functions.
  create_light_table(&colorMap, paPalette, 0, 0, 0, NULL);
  color_map = &colorMap;
  // texture and flat polygons are 50% transparent
  create_trans_table(&transMap, paPalette, 128, 128, 128, NULL);
  set_trans_blender(0, 0, 0, 128);
  // set the graphics mode
  int tc = GFX_AUTODETECT_WINDOWED, tw = config->getWidth();
  int th = config->getHeight(), tbpp = 16;
  /*
    set_gfx_mode(GFX_SAFE, 320, 200, 0, 0);
    set_palette(desktop_palette);

    if (!gfx_mode_select_ex(&tc, &tw, &th, &tbpp)) {
    allegro_exit();
    cerr << "Error setting safe graphics mode" << endl;
    }
  */
  set_color_depth(tbpp);
  if (set_gfx_mode(tc, tw, th, 0, 0) != 0) {
    allegro_exit();
    cerr << "Error setting graphics mode " << endl << allegro_error << endl;
  }
  set_palette(paPalette);
  config->setSize(tw, th);
  set_projection_viewport(0, 0, tw, th);
  // Create back buffer.
  backbuffer = create_bitmap(tw, th);
  clear(backbuffer);
  zbuffer = create_zbuffer(backbuffer);
  set_zbuffer(zbuffer);
  clear_zbuffer(zbuffer, 0);
#endif // EM_USE_ALLEGRO
}
Beispiel #21
0
//Main function
int main(){
  allegro_init();
  alpng_init();
  install_timer();
  install_keyboard();
  install_mouse();
  install_joystick(JOY_TYPE_AUTODETECT);
  install_sound(DIGI_AUTODETECT,MIDI_AUTODETECT,".");
  set_color_depth(32);

  // Setup basic functionality
  setup();

  //Set the current state ID
  stateID = STATE_INIT;

  //Set the current game state object
  currentState = new Init();


  while(!game_closed_esc && !close_button_pressed && stateID != STATE_EXIT){
    while(ticks == 0){
      rest(1);
    }
    while(ticks > 0){
      //Esc key handler
     if(key[KEY_ESC]){
           if(alert(NULL, "Are you sure you want to exit the game?",NULL,"&Resume Game", "&Exit", 'r','e' )==2)
           game_closed_esc=true;

      }


      int old_ticks = ticks;

      //Do state logic
      currentState -> update();

      //Change state if needed
      change_state();

      // Counter for FPS
      frames_done++;

      ticks--;
      if(old_ticks <= ticks){
        break;
      }
    }
    if(game_time - old_time >= 10){
      fps = frames_done;
      frames_done = 0;
      old_time = game_time;
    }
    //Do state rendering
    currentState -> draw( true);
  }

  //Clean up
  clean_up();

  return 0;
}
Beispiel #22
0
void initialize()
{
    char buf[1024];
    int i;

    // Do the libxml binary compatibility check
    initXML();

    // Initialise Allegro
    allegro_init();
    install_keyboard();
    install_mouse();
    install_timer();

    set_config_file("rpgedit.cfg");
    int grph_drv = (get_config_int("video", "fullscreen", 1)) ?
        GFX_AUTODETECT_FULLSCREEN : GFX_AUTODETECT_WINDOWED;
    int screen_w = get_config_int("video", "width", 800);
    int screen_h = get_config_int("video", "height", 600);

    if (get_config_int("tile_zoom", "grid", 1)) {
        showTileGrid = true;
    }

    set_color_conversion(
            (COLORCONV_TOTAL &
             ~(
                 COLORCONV_32A_TO_8  |
                 COLORCONV_32A_TO_15 |
                 COLORCONV_32A_TO_16 |
                 COLORCONV_32A_TO_24
              ))
            );

    int colordepth = 0;
    if (grph_drv == GFX_AUTODETECT_WINDOWED) {
        colordepth = desktop_color_depth();
    }
    if (colordepth == 0) {
        colordepth = 16;
    }
    set_color_depth(colordepth);

    if (set_gfx_mode(grph_drv, screen_w, screen_h, 0, 0) != 0) {
        set_color_depth(15);
        if (set_gfx_mode(grph_drv, screen_w, screen_h, 0, 0) != 0) {
            set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
            allegro_message("Unable to set graphic mode\n%s\n", allegro_error);
            exit(1);
        }
    }

    buffer = create_bitmap(SCREEN_W, SCREEN_H);


    // Initialize GUI look and feel stuff
    agup_init(aphoton_theme);
    gui_fg_color = agup_fg_color;
    gui_bg_color = agup_bg_color;
    gui_shadow_box_proc = d_agup_shadow_box_proc;
    gui_button_proc = d_agup_button_proc;
    gui_edit_proc = d_agup_edit_proc;
    gui_text_list_proc = d_agup_text_list_proc;

    engine_data = load_datafile("gui.dat");

    DATAFILE* font_data = find_datafile_object(engine_data, "SmallFont");
    if (font_data) font = (FONT*)font_data->dat;

    engine_font = font;

    DATAFILE* mouse_pointer = find_datafile_object(engine_data, "_MS_STD_BMP");
    if (mouse_pointer) set_mouse_sprite((BITMAP*)mouse_pointer->dat);

    DATAFILE* logo = find_datafile_object(engine_data, "MoonlightLogo");
    if (logo) about_dlg[1].dp = (BITMAP*)logo->dat;
    else console.log(CON_QUIT, CON_ALWAYS, "Error loading MoonlightLogo");

    console.log(CON_LOG, CON_ALWAYS, "Loading module \"data\"...");
    module = new Module("data");

    // Lua initialisation
    console.log(CON_LOG, CON_ALWAYS, "Initialising scripting environment...");
    initScripting();

    D_AUTOTEXT_STATUS.dp2 = status_message;
    D_AUTOTEXT_MAPINFO.dp2 = status_mapinfo;

    set_dialog_color(main_dlg, agup_fg_color, agup_bg_color);
    set_dialog_color(newmap_dlg, agup_fg_color, agup_bg_color);
    set_dialog_color(import_tileset_dlg, agup_fg_color, agup_bg_color);
    set_dialog_color(export_tileset_dlg, agup_fg_color, agup_bg_color);
    set_dialog_color(resizemap_dlg, agup_fg_color, agup_bg_color);
    set_dialog_color(about_dlg, agup_fg_color, agup_bg_color);


    // Position the dialogs on the screen
    int margin = 6;
    int zoom_w = get_config_int("tile_zoom", "zoom_width", 120) - 1;
    int zoom_h = get_config_int("tile_zoom", "zoom_height", 120) - 1;
    int x, y, w, h;

    // Main (back + menu)
    set_dialog_size(&main_dlg[0],          -2,                -2,              SCREEN_W + 4,          SCREEN_H + 4);
    set_dialog_size(&main_dlg[1],          0,                 0,               SCREEN_W,              15);

    // Status bars
    set_dialog_size(&main_dlg[6],          0,                 SCREEN_H - 17,   SCREEN_W - 256,        17);
    set_dialog_size(&main_dlg[7],          SCREEN_W - 256,    SCREEN_H - 17,   256,                   17);
    set_dialog_size(&main_dlg[8],          3,                 SCREEN_H - 14,   SCREEN_W - 262,        11);
    set_dialog_size(&main_dlg[9],          SCREEN_W - 253,    SCREEN_H - 14,   250,                   11);

    // Edit tile area
    w = zoom_w + 4;
    h = zoom_h + 4;
    x = margin;
    y = main_dlg[6].y - margin - h;
    set_dialog_size(&edit_tile_layer[0],   x,                 y,               w,                     h);
    set_dialog_size(&edit_tile_layer[1],   x + 2,             y + 2,           w - 4,                 h - 4);
    set_dialog_size(&edit_tile_layer[2],   x + margin + w,    y + h - 14,      50,                    14);

    // Color sliders
    x += w + margin;
    w = 128;
    set_dialog_size(&edit_tile_layer[8],   x,                 y,               16,                    8);
    set_dialog_size(&edit_tile_layer[9],   x,                 y + 16,          16,                    8);
    set_dialog_size(&edit_tile_layer[10],  x,                 y + 32,          16,                    8);
    set_dialog_size(&edit_tile_layer[11],  x,                 y + 48 + 8,      16,                    8);
    set_dialog_size(&edit_tile_layer[12],  x,                 y + 64 + 8,      16,                    8);
    set_dialog_size(&edit_tile_layer[3],   x + 16,            y,               w,                     8);
    set_dialog_size(&edit_tile_layer[4],   x + 16,            y + 16,          w,                     8);
    set_dialog_size(&edit_tile_layer[5],   x + 16,            y + 32,          w,                     8);
    set_dialog_size(&edit_tile_layer[6],   x + 16,            y + 48 + 8,      w,                     8);
    set_dialog_size(&edit_tile_layer[7],   x + 16,            y + 64 + 8,      w,                     8);
    set_dialog_size(&edit_tile_layer[13],  x + 16 + w + 4,    y - 1,           11,                    10);
    set_dialog_size(&edit_tile_layer[14],  x + 16 + w + 4,    y + 16 - 1,      11,                    10);
    set_dialog_size(&edit_tile_layer[15],  x + 16 + w + 4,    y + 32 - 1,      11,                    10);
    set_dialog_size(&edit_tile_layer[20],  x + 16 + w + 18,   y + 4,           18,                    32);

    // Select tile area
    x = edit_tile_layer[20].x + edit_tile_layer[20].w + margin;
    w = SCREEN_W - x - margin;
    set_dialog_size(&edit_tile_layer[16],  x,                 y,               104,                   h);
    set_dialog_size(&edit_tile_layer[17],  x + 104,           y,               w - 104,               h);
    set_dialog_size(&edit_tile_layer[18],  x + 104 + 2,       y + 2,           w - 104 - 4 - 11,      h - 4);
    set_dialog_size(&edit_tile_layer[19],  x + w - 14,        y,               14,                    h);

    // Obstacle edit stuff
    w = 24;
    h = 24;
    x = margin;
    y = main_dlg[6].y - margin - h;
    for (i = 0; i < 5; i++) {
        set_dialog_size(&edit_obstacle_layer[i],   x + i*(w+margin),     y,     w,     h);
        set_dialog_size(&edit_obstacle_layer[i+5], x + i*(w+margin) + 2, y + 2, w - 4, h - 4);
    }

    // Edit map area
    x = margin;
    y = 16 + margin;
    w = SCREEN_W - 2 * margin;
    h = edit_obstacle_layer[0].y - margin - y;
    set_dialog_size(&main_dlg[2],          x,                 y,               w,                     h);
    set_dialog_size(&main_dlg[3],          x + 2,             y + 2,           w - 15,                h - 15);
    set_dialog_size(&main_dlg[4],          x + w - 14,        y,               14,                    h - 11);
    set_dialog_size(&main_dlg[5],          x,                 y + h - 14,      w - 11,                14);
    set_dialog_size(&main_dlg[10],         x + w - 12,        y + h - 12,      10,                    10);

    // Edit objects area
    w = 160;
    h = 120;
    x = margin;
    y = main_dlg[6].y - margin - h;
    set_dialog_size(&edit_objects_layer[0], x,                y,               w,                     h);
    set_dialog_size(&edit_objects_layer[1], w + margin * 2, main_dlg[6].y - margin - 14,  97,                    14);


    // Initialize map and tile stuff
    tileRepository = new TileRepository();

    // Import tilesets specified in rpgedit.cfg
    i = 1;
    while (i > 0) 
    {
        uszprintf(buf, sizeof buf, "tileset%d", i);

        const char* filename = get_config_string(buf, "filename", NULL);
        int tile_w = get_config_int(buf, "tile_w", 16);
        int tile_h = get_config_int(buf, "tile_h", 16);
        int tile_spacing = get_config_int(buf, "tile_spacing", 0);

        if (filename) {
            if (tile_w > 0 && tile_h > 0 && tile_spacing >= 0) {
                import_tile_bitmap(filename, tile_w, tile_h, tile_spacing);
            } else {
                allegro_message("Error, incorrect parameters for automatic tile import (%s)!", filename);
                // Print warning in log file
            }
            i++;
        } else  {
            i = -1;
        }
    }

    currentMap = new SquareMap(TILES_W, TILES_H);
    ustrcpy(map_filename, "untitled.tmx");

    // Load map specified in rpgedit.cfg
    const char* filename = get_config_string("startup", "load_map", NULL);
    if (filename) {
        if (!currentMap->loadMap(filename)) {
            ustrcpy(map_filename, filename);
            object_message(&D_MAP, MSG_NEW_MAP, 0);
            set_map_changed(false);
        } else {
            console.log(CON_LOG, CON_ALWAYS,
                    "Error while loading default map (%s)!\n", filename);
        }
    }

    update_window_title();

    map_edit_mode = EM_TILE;
    menu_item_edit_objects();
    //activate_mode(edit_objects_layer);
}
Beispiel #23
0
int main()
{
    /* Setup Allegro/AllegroGL */

	if (allegro_init())
		return 1;

	if (install_allegro_gl())
		return 1;

    if (install_keyboard() < 0)
    {
        allegro_message("Unable to install keyboard\n");
        return 1;
    }

    if (install_mouse() == -1)
    {
        allegro_message("Unable to install mouse\n");
        return 1;
    }

    if (install_timer() < 0)
    {
        allegro_message("Unable to install timers\n");
        return 1;
    }

    /* lock timer */
    LOCK_VARIABLE(rotation_counter);
    LOCK_FUNCTION(rotation_counter_handler);


    /* set desktop resolution */
    DESKTOP_W = GetSystemMetrics(SM_CXVIRTUALSCREEN);
    DESKTOP_H = GetSystemMetrics(SM_CYVIRTUALSCREEN);

    /* get monitor resolution/count */
    int monitor_count;
    MONITOR *monitors = get_monitors(&monitor_count);


    /* generate point data */
    PLACE places[POINT_COUNT];
    int c;
    for (c = 1; c < POINT_COUNT - 1; c++)
    {
        places[c].x = sin((M_PI * (GLfloat)c) / 10.0f) * 200.0f;
        places[c].y = cos((M_PI * (GLfloat)c) / 10.0f) * 200.0f;
    }
    places[0].x = 0.01;
    places[0].y = 200.0f;
    places[POINT_COUNT - 1].x = 0.01;
    places[POINT_COUNT - 1].y = -200.0f;


    /* setup display */
    allegro_gl_set(AGL_Z_DEPTH, 8);
	allegro_gl_set(AGL_COLOR_DEPTH, 16);
	allegro_gl_set(AGL_SUGGEST, AGL_Z_DEPTH | AGL_COLOR_DEPTH);
    glDepthFunc(GL_LEQUAL);

	if (set_gfx_mode(GFX_OPENGL_WINDOWED_BORDERLESS, DESKTOP_W, DESKTOP_H, 0, 0)) {
		set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
		allegro_message("Unable to set graphic mode\n%s\n", allegro_error);
		return 1;
	}

    /* move window so it covers the desktop */
    position_window(0, 0);


    /* fake information to use if only 1 monitor */
    MONITOR fake = {0, 512, 512, 512};

    /* setup lighting model */
    glShadeModel(GL_FLAT);
    glEnable(GL_LIGHT0);
    glEnable(GL_COLOR_MATERIAL);
    GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
    glLightfv(GL_LIGHT0, GL_POSITION, light_position);
    GLfloat ambient[] = { 0.1f, 0.1f, 0.1f };
    glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);


    int selected = -1; /* the point currently being moved */
    GLfloat rotation[3] = {0, 0, 0}; /* the rotation of the mesh */

    install_int(rotation_counter_handler, 20); /* install the rotation handler */

    /* enter main program loop */
    while(!key[KEY_ESC])
    {
        while (rotation_counter > 0)
        {
            /* rotate the mesh */
            rotation[0] += M_PI / 24.0f;
            rotation[1] += M_PI / 16.0f;
            rotation[2] += M_PI /  8.0f;
            rotation_counter--;
        }


        /* clear the buffers */
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        /* process monitor 0 */
        MONITOR *m = &monitors[0];

        /* adjust mouse so its relative to the monitor */
        int mx = (mouse_x - m->x) - (m->w / 2);
        int my = (mouse_y - m->y) - (m->h / 2);

        /* if the left mouse is pushed, find a close point */
        if (mouse_b & 1)
        {
            if (selected == -1)
            {
                GLfloat distance = 10;
                for (c = 0; c < POINT_COUNT; c++)
                {
                    GLfloat dx = mx - places[c].x;
                    GLfloat dy = my - places[c].y;
                    GLfloat d = sqrt(dx * dx + dy * dy);
                    if (d < distance)
                    {
                        distance = d;
                        selected = c;
                    }
                }
            }
        }
        else
            selected = -1;

        /* move selected point */
        if (selected >= 0)
        {
            places[selected].x = mx;
            places[selected].y = my;
        }

        /* center the viewport on monitor */
        glViewport(m->x, DESKTOP_H - m->h - m->y, m->w, m->h);

        /* setup viewport projection */
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluOrtho2D(-m->w / 2, m->w / 2, m->h / 2, -m->h / 2);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        /* draw points */
        glColor3ub(0, 255, 0);
        glBegin(GL_LINE_STRIP);
        for (c = 0; c < POINT_COUNT; c++)
        {
            glVertex2f(places[c].x, places[c].y);
        }
        glEnd();

        glColor3ub(255, 255, 255);
        for (c = 0; c < POINT_COUNT; c++)
        {
            draw_square(places[c].x, places[c].y, 10);
        }

        /* draw vertical line */
        glBegin(GL_LINE_STRIP);
        glVertex2f(0.0f, -m->h);
        glVertex2f(0.0f, m->h);
        glEnd();


        /* draw the mouse */
        glColor3ub(255, 255, 255);
        draw_square(mx, my, 20);



        /* process viewport 1 */

        /* select second monitor */
        if (monitor_count > 1)
        {
            /* if 2nd monitor exists use it */
            m = &monitors[1];
        }
        else
        {
            /* use fake monitor */
            m = &fake;
        }

        /* adjust mouse so its relative to the monitor*/
        mx = (mouse_x - m->x) - (m->w / 2);
        my = (mouse_y - m->y) - (m->h / 2);

        /* center the viewport on the monitor*/
        glViewport(m->x, DESKTOP_H - m->h - m->y, m->w, m->h);

        /* setup viewport projection */
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluPerspective(45.0f, (float)m->w / (float)m->h, 0.1f, 2000.0f);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        /* turn on lighting and depth testing */
        glEnable(GL_LIGHTING);
        glEnable(GL_DEPTH_TEST);

        /* move mesh so its visible */
        glTranslatef(0.0f, 0.0f, -1000.0f);
        /* rotate mesh */
        glRotatef(rotation[0], 1.0f, 0.0f, 0.0f);
        glRotatef(rotation[1], 0.0f, 1.0f, 0.0f);
        glRotatef(rotation[2], 0.0f, 0.0f, 1.0f);

        GLfloat p1[3] = {0, 0, 0};
        GLfloat p2[3] = {0, 0, 0};
        GLfloat p3[3] = {0, 0, 0};
        GLfloat p4[3] = {0, 0, 0};
        GLfloat vec1[3];
        GLfloat vec2[3];
        GLfloat normal[3];


        /* draw mesh to screen */
        glColor3ub(0, 255, 0);
        for (c = 0; c < (POINT_COUNT - 1); c++)
        {

            GLfloat a1 = 0;
            GLfloat a2 = M_PI / 16.0f;
            GLfloat d1 = places[c].x;
            GLfloat d2 = places[c + 1].x;

            p1[0] = sin(a1) * d1;  p1[1] = places[c].y;     p1[2] = cos(a1) * d1;
            p2[0] = sin(a2) * d1;  p2[1] = places[c].y;     p2[2] = cos(a2) * d1;
            p3[0] = sin(a2) * d2;  p3[1] = places[c + 1].y; p3[2] = cos(a2) * d2;
            p4[0] = sin(a1) * d2;  p4[1] = places[c + 1].y; p4[2] = cos(a1) * d2;

            buildVector(vec1, p1, p2);
            buildVector(vec2, p1, p4);
            cross_product_f(vec2[0], vec2[1], vec2[2], vec1[0], vec1[1], vec1[2], &normal[0], &normal[1], &normal[2]);
            normalize_vector_f(&normal[0], &normal[1], &normal[2]);


            glBegin(GL_QUAD_STRIP);
            glNormal3fv(normal);
            glVertex3fv(p1);
            glVertex3fv(p4);

            int s = 0;
            for (s = 1; s < 32; s++)
            {
                a2 = (M_PI * (GLfloat)(s + 1)) / 16.0f;
                d1 = places[c].x;
                d2 = places[c + 1].x;

                copyPoint(p1, p2);
                copyPoint(p4, p3);
                p2[0] = sin(a2) * d1;  p2[1] = places[c].y;     p2[2] = cos(a2) * d1;
                p3[0] = sin(a2) * d2;  p3[1] = places[c + 1].y; p3[2] = cos(a2) * d2;

                buildVector(vec1, p1, p2);
                buildVector(vec2, p1, p4);
                cross_product_f(vec2[0], vec2[1], vec2[2], vec1[0], vec1[1], vec1[2], &normal[0], &normal[1], &normal[2]);
                normalize_vector_f(&normal[0], &normal[1], &normal[2]);

                glNormal3fv(normal);
                glVertex3fv(p2);
                glVertex3fv(p3);
            }
            glEnd();
        }

        /* turn off lighting and depth testing */
        glDisable(GL_DEPTH_TEST);
        glDisable(GL_LIGHTING);

        /* if not using the fake monitor */
        if (m != &fake)
        {

            /* setup viewport projection */
            glMatrixMode(GL_PROJECTION);
            glLoadIdentity();
            gluOrtho2D(-m->w / 2, m->w / 2, m->h / 2, -m->h / 2);
            glMatrixMode(GL_MODELVIEW);
            glLoadIdentity();

            /* draw the mouse */
            glColor3ub(255, 255, 255);
            draw_square(mx, my, 20);
        }

        /* flip the contents to the screen */
        allegro_gl_flip();
    }


    free(monitors);

    return 0;
}
Beispiel #24
0
void main(void) {
    
    int xy,i,j,c,x,y,front,back,n,minc,maxc;
    int ix,iy,k,address,jx,jy,kx,ky;
    float dzdx,dzdy,a,b,dot,norm,tmp;
    float rx,ry,sx,sy,px,py;
    long p,q;
    RGB rgb;

    for (x=0;x<scrwid;x++) {
    for (y=0;y<scrhei;y++) {
        rx=(float)x/scrwid*2-1;
        ry=(float)y/scrhei*2-1;
        sx=rx*.8;
        sy=ry*.8;
        px=(sx+1)/2*scrwid;
        py=(sy+1)/2*scrhei;
        ix=(int)px;
        iy=(int)py;
        amount[x][y][0][0]=((float)ix+1-(float)px)*((float)(iy+1)-(float)py);
        amount[x][y][1][0]=((float)px-(float)ix)*((float)(iy+1)-(float)py);
        amount[x][y][0][1]=((float)ix+1-(float)px)*((float)py-(float)iy);
        amount[x][y][1][1]=((float)px-(float)ix)*((float)py-(float)iy);
        pix[x][y]=ix;
        piy[x][y]=iy;
//        printf("%f",amount[x][y][0][0]+amount[x][y][1][0]+amount[x][y][0][1]+amount[x][y][1][1]);
        if (mysquare(amount[x][y][0][0]+amount[x][y][1][0]+amount[x][y][0][1]+amount[x][y][1][1]-1)>0.00001) {
            printf("%d %d %f %f ",ix,iy,px,py);
            printf("%f+%f(%f*%f)+%f+%f=%f? \n",amount[x][y][0][0],amount[x][y][1][0],(float)px-(float)ix,(float)(iy+1)-(float)py,amount[x][y][0][1],amount[x][y][1][1],amount[x][y][0][0]+amount[x][y][1][0]+amount[x][y][0][1]+amount[x][y][1][1]);
        }
    }
    }

//    srand(456789);
        srand((int)time(NULL));
        //printf("%d\n",(int)time(NULL));


  allegro_init ();
  install_keyboard ();
  install_timer ();
  set_gfx_mode (GFX_AUTODETECT, scrwid, scrhei, 0, 0);
  set_pallete (desktop_palette);
  buffer = create_bitmap (scrwid, scrhei);
      clear (buffer);

//      textout_centre (buffer, font, "Press SPACE!", 60, 220, 4);


    // Set up grayscale colours
    for (c=0;c<=255;c++) {
        i=0;
        rgb.r=c*63/255;
        rgb.g=0;
        rgb.b=0;
        set_color(c,&rgb);
//        colors[c]=GrAllocColor(c,i,i);
    }
    
        for (x=0; x<scrwid; x++) {
        for (y=0; y<scrhei; y++) {
            putpixel(buffer,x,y,128);
        }
        }

      blit (buffer, screen, 0, 0, 0, 0, scrwid, scrhei);

   _farsetsel(screen->seg);

    while(!key[KEY_ESC]) {
     movedata(screen->seg, bmp_read_line(screen,0), _my_ds(), (unsigned)tmp, scrwid*scrhei);
        for (x=0; x<scrwid; x++) {
        for (y=0; y<scrhei; y++) {
        c=0;
        kx=x-scrwid/2;
        ky=y-scrhei/2;
        jx=kx*cos(ang)+ky*sin(ang);
        jy=-kx*sin(ang)+ky*cos(ang);
        ix=scrwid/2+0.9*jx;
        iy=scrhei/2+0.9*jy;
        k=0;
        i=0;j=0;
//        for (i=-1;i<=1;i++) {
//        for (j=-1;j<=1;j++) {
//            c=c+getpixel(screen, ix+i, iy+j);
     address = bmp_read_line(screen, iy)+ix;
            c=c+tmp[y*scrwid+x];
            k++;
//        }
//        }
        c=c/k;
        c--;
//     address = bmp_write_line(buffer, y)+x;
//        _farnspokeb(address, c);
        putpixel(buffer, x, y, c);
        }
        }
for (i=1;i<=10;i++)
        circlefill(buffer,myrnd()*scrwid,myrnd()*scrhei,8,myrnd()*255);
//        putpixel(buffer,scrwid/2,scrhei/2,255);
      blit (buffer, screen, 0, 0, 0, 0, scrwid, scrhei);
    }

destroy_bitmap(buffer);
exit(0);
    getch();

//    GrSetMode(GR_default_text);
    printf("max col %d\n",maxc);
    printf("min col %d\n",minc);
  
}
Beispiel #25
0
int main(int argc, char* argv[])
{
	// init allegro and add keyboard and optional mouse support
	allegro_init();
	install_timer();
	install_keyboard();
	if (ENABLE_MOUSE_SUPPORT)
	{
		install_mouse();
	}

	// set the video mode
	set_color_depth(WINDOW_COLOR_DEPTH);
	set_gfx_mode(
		(WINDOW_USE_FULLSCREEN) ?
			GFX_AUTODETECT_FULLSCREEN :
			GFX_AUTODETECT_WINDOWED,
		WINDOW_WIDTH, WINDOW_HEIGHT, 0, 0);
	// set the window caption text
	set_window_title(WINDOW_CAPTION);

	// create the back buffer bitmap
	backbuffer = create_bitmap(SCREEN_W, SCREEN_H);

	// seed the random number generator
	srand(time(0));

	// lock the static functions and variables we need for handling timing and closing the window via the [X] button
	LOCK_FUNCTION(my_allegro_close_button_handler);
	LOCK_FUNCTION(my_allegro_timer_speed_controller);
	LOCK_VARIABLE(allegrotimerspeedcounter);

	// set the callback function for the close-button to our global handler function
	set_close_button_callback(my_allegro_close_button_handler);

	// set our FPS lock timing global function
	install_int_ex(my_allegro_timer_speed_controller, BPS_TO_TIMER(FRAME_LOCK_RATE));

	// setup the game
	if (!setup_game())
	{
		fprintf(stderr, "The game initialization has failed. Cannot continue!\n");
		exit(1);
	}

	// main loop
	bool gameover = false;
	while(!gameover)
	{
		// if our global is ever false
		if (!mainthreadisrunning)
		{
			gameover = true;
		}

		// we only draw when the FPS should be locked
		if (allegrotimerspeedcounter > 0)
		{
			// we only update during our FPS lock time
			while (allegrotimerspeedcounter > 0)
			{
				// ensure the keyboard data is current
				if (keyboard_needs_poll())
				{
					poll_keyboard();
				}

				// ensure the mosue data is current
				if (ENABLE_MOUSE_SUPPORT)
				{
					if (mouse_needs_poll())
					{
						poll_mouse();
					}
				}

				// update
				update_game();

				// decrement the global timing var so that we can leave the update loop!
				allegrotimerspeedcounter--;
			}

			// start rendering the scene
			render_game();

			if (ENABLE_MOUSE_SUPPORT)
			{
				show_mouse(backbuffer);
			}

			// make it all visible
			blit(backbuffer, screen, 0, 0, 0, 0, backbuffer->w, backbuffer->h);
		}
		else
		{
			// a little rest to keep CPU usage down ^-^
			rest(1);
		}
	}

	// shutdown the game
	shutdown_game();

	// clean up the back buffer
	if (backbuffer)
	{
		if (ENABLE_MOUSE_SUPPORT)
		{
			show_mouse(0);
		}
		destroy_bitmap(backbuffer);
	}

	return 0;
}
	bool GameSingleton::Initialize(int argc, char* argv[])
	{
		gameSettings_ = new UTILITY::CONFIGURATION::Settings();

		if (gameSettings_)
		{
			// default settings
			gameSettings_->Set("screen_width", "800");
			gameSettings_->Set("screen_width", "600");
			gameSettings_->Set("screen_bpp", "24");
			gameSettings_->Set("use_fullscreen", "false");
			gameSettings_->Set("lock_fps_to", "60");

			// the micro display
			gameSettings_->Set("micro_screen_width", "200");
			gameSettings_->Set("micro_screen_height", "150");

			/*
				data file paths

				ROOT OF ALL DATA FILES
				data_path - relative to executable

				.WORLD FILES DIRECTORY
				world_path - relative to data_path

				MAPS DIRECTORY
				map_path - relative to data_path

				GRAPHICS DIRECTORY
				graphics_path - relative to data_path

				.DIALOGUE FILES DIRECTORY
				dialogue_path - relative to data_path

				.BATTLE FILES DIRECTORY
				battle_path - relative to data_path


				TILESET DIRECTORY
				tiles_path - relative to graphics_path

				GAME SPRITES DIRECTORY
				game_sprite_path - relative to graphics_path

				BATTLE SPRITES DIRECTORY
				battle_sprite_path - relative to graphics_path

				BATTLE SCENE IMAGERY DIRECTORY
				battle_scene_path - relative to graphics_path

				FONT DIRECTORY
				font_path - relative to graphics_path

				GAME OVERLAY IMAGES DIRECTORY
				game_overlay_path - relative to graphics_path

				BATTLE OVERLAY IMAGES DIRECTORY
				battle_overlay_path - relative to graphcis_path

				CHARACTER PORTRAIT IMAGES DIRECTORY
				portrait_path - relative to graphics_path



			*/

			gameSettings_->Set("data_path", "data/");
			gameSettings_->Set("world_path", "worlds/");
			gameSettings_->Set("map_path", "maps/");
			gameSettings_->Set("graphics_path", "graphics/");
			gameSettings_->Set("dialogue_path", "dialogue/");
			gameSettings_->Set("battle_path", "battles/");
			gameSettings_->Set("tiles_path", "game/tiles/");
			gameSettings_->Set("game_sprite_path", "game/sprites/");
			gameSettings_->Set("battle_sprite_path", "battle/sprites/");
			gameSettings_->Set("battle_scene_path", "battle/scenes/");
			gameSettings_->Set("font_path", "fonts/");
			gameSettings_->Set("game_overlay_path", "game/overlays/");
			gameSettings_->Set("battle_overlay_path", "battle/overlays/");
			gameSettings_->Set("portrait_path", "portraits/");



			// fonts
			gameSettings_->Set("small_font", "font5x5white.png");
			gameSettings_->Set("small_font_w", "5");
			gameSettings_->Set("small_font_h", "5");
			gameSettings_->Set("large_font", "font8x8white.png");
			gameSettings_->Set("large_font_w", "8");
			gameSettings_->Set("large_font_h", "8");





			gameSettings_->Set("start_world", "game.world");

			gameSettings_->Set("camera_anchor_x", "1");
			gameSettings_->Set("camera_anchor_y", "1");
			gameSettings_->Set("camera_w", "17");
			gameSettings_->Set("camera_h", "11");
			gameSettings_->Set("tile_w", "8");
			gameSettings_->Set("tile_h", "8");

			gameSettings_->Set("enable_collision_debugging", "false");
			gameSettings_->Set("enable_general_debugging", "false");
			gameSettings_->Set("enable_game_editors", "false");
			gameSettings_->Set("enable_verbose_startup", "false");

			gameSettings_->Set("enable_screen_overlays", "true");

			gameSettings_->Set("window_caption", "48h Contest LO-Fi Mini-RPG Game Project");

			// cheats haha
			gameSettings_->Set("enable_cheats", "false");
			gameSettings_->Set("enable_cheat_infinite_gold", "false");
			gameSettings_->Set("enable_cheat_infinite_health", "false");
			gameSettings_->Set("enable_cheat_infinite_magic", "false");
			gameSettings_->Set("enable_cheat_max_attack", "false");
			gameSettings_->Set("enable_cheat_max_defense", "false");
			gameSettings_->Set("enable_cheat_max_strength", "false");
			gameSettings_->Set("enable_cheat_no_battles", "false");


			// load the settings file if it exists
			if (UTILITY::FILESYSTEM::FileExists::Execute("game.cfg"))
			{
				gameSettings_->Load("game.cfg", false /* we do not want to clear the settings before loading the file! */);
			}
		}




		// initialize Allegro
		if (0 != allegro_init())
		{
			LogFatal("Could not initialize Allegro!");
		}

		// install the Allegro timer driver
		if (0 != install_timer())
		{
			LogFatal("Could not install Allegro Timer driver!");
		}

		// setup the 60fps allegro speed controller
		LOCK_VARIABLE(allegroTimerSpeedCounter);
		LOCK_FUNCTION(allegroTimerSpeedController);
		LOCK_FUNCTION(allegroTimer_RenderController);

		install_int_ex(allegroTimerSpeedController, BPS_TO_TIMER(static_cast<int>(atoi(gameSettings_->Get("lock_fps_to").c_str()))));

		int sw  = static_cast<int>(atoi(gameSettings_->Get("screen_width").c_str()));
		int sh  = static_cast<int>(atoi(gameSettings_->Get("screen_height").c_str()));
		int bpp = static_cast<int>(atoi(gameSettings_->Get("screen_bpp").c_str()));

		// setup the graphics device
		// we do not allow under 800 x 600 @ 24 bpp res
		GraphicsDevice->SetDisplay(
			(sw < 800) ? 800 : sw,
			(sh < 600) ? 600 : sh,
			(bpp == 32) ? GraphicsDevice_32bit :
			(bpp == 24) ? GraphicsDevice_24bit :
			(bpp < 24) ? GraphicsDevice_24bit : GraphicsDevice_24bit,
			("true" == gameSettings_->Get("use_fullscreen")) ? GraphicsDevice_Fullscreen : GraphicsDevice_Windowed);

		// setup the input device
		InputDevice->Initialize(INIT_KEYBOARD | INIT_MOUSE);

		// init the timing class
		GameTimer;

		// set the window title
		set_window_title(gameSettings_->Get("window_caption").c_str());

		// load fonts
		smallFont_ = new BitmapFont();
		if (!smallFont_->Load(
			static_cast<std::string>(
				gameSettings_->Get("data_path") +
					gameSettings_->Get("graphics_path") +
						gameSettings_->Get("font_path") +
							gameSettings_->Get("small_font")).c_str(),
				static_cast<int>(atoi(gameSettings_->Get("small_font_w").c_str())),
				static_cast<int>(atoi(gameSettings_->Get("small_font_h").c_str())),
				1))
		{
			return false;
		}

		largeFont_ = new BitmapFont();
		if (!largeFont_->Load(
			static_cast<std::string>(
				gameSettings_->Get("data_path") +
					gameSettings_->Get("graphics_path") +
						gameSettings_->Get("font_path") +
							gameSettings_->Get("large_font")).c_str(),
				static_cast<int>(atoi(gameSettings_->Get("large_font_w").c_str())),
				static_cast<int>(atoi(gameSettings_->Get("large_font_h").c_str())),
				1))
		{
			return false;
		}

		// load the over lays
		//windowOverlay_ 	= new ImageResource("data/graphics/game/overlays/mainscreen.png");
		// playerPortrait_ = new ImageResource("data/graphics/portraits/player.png");

		windowOverlay_ = new ImageResource();
		if (!windowOverlay_->Load(
			static_cast<std::string>(
				gameSettings_->Get("data_path") +
					gameSettings_->Get("graphics_path") +
						gameSettings_->Get("game_overlay_path") +
							"mainscreen.png").c_str()
			))
		{
			return false;
		}

		playerPortrait_ = new ImageResource();
		if (!playerPortrait_->Load(
			static_cast<std::string>(
				gameSettings_->Get("data_path") +
					gameSettings_->Get("graphics_path") +
						gameSettings_->Get("portrait_path") +
							"player.png").c_str()
			))
		{
			return false;
		}

		// all of this will be removed after the 48 hour jam entry
#if defined(FORTYEIGHTHOUR_JAM_ENTRY_VERSION)

		// lofiOverlay_ 	= new ImageResource("data/graphics/game/overlays/lofi.png");
		lofiOverlay_ = new ImageResource();
		if (!lofiOverlay_->Load(
			static_cast<std::string>(
				gameSettings_->Get("data_path") +
					gameSettings_->Get("graphics_path") +
						gameSettings_->Get("game_overlay_path") +
							"lofi.png").c_str()
			))
		{
			return false;
		}
#endif


		// create the dialogue message
		dialogueMessage_ = new GameDialogueMessage();

		// create the display surface we draw on for implementing the cool 400% scale
		int msw  = static_cast<int>(atoi(gameSettings_->Get("micro_screen_width").c_str()));
		int msh  = static_cast<int>(atoi(gameSettings_->Get("micro_screen_height").c_str()));
		microDisplay_ = new ImageResource(
			(msw > 0) ? (msw < sw) ? msw : 200 : 200,
			(msh > 0) ? (msh < sh) ? msh : 150 : 150);

		playerSpriteIndex_ = 0;

		//LoadWorldFile("data/worlds/game.world");
		LoadWorldFile(
			static_cast<std::string>(
				gameSettings_->Get("data_path") +
					gameSettings_->Get("world_path") +
						gameSettings_->Get("start_world")).c_str());


		// create the camera

		int camAX = static_cast<int>(atoi(gameSettings_->Get("camera_anchor_x").c_str()));
		int camAY = static_cast<int>(atoi(gameSettings_->Get("camera_anchor_y").c_str()));

		int camW = static_cast<int>(atoi(gameSettings_->Get("camera_w").c_str()));
		int camH = static_cast<int>(atoi(gameSettings_->Get("camera_h").c_str()));
		int tileW = static_cast<int>(atoi(gameSettings_->Get("tile_w").c_str()));
		int tileH = static_cast<int>(atoi(gameSettings_->Get("tile_h").c_str()));

		// keep the camera size in check
		camW = (camW < 1) ? 17 : (camW > (200 / tileW)) ? 17 : camW;
		camH = (camH < 1) ? 11 : (camH > (150 / tileH)) ? 11 : camH;

		camera_ = new GameCamera(
			camAX, camAY, 	// rendering anchor x, y
			0, 0, 			// world x, y
			camW * tileW, 	// width in pixels
			camH * tileH, 	// height in pixels
			1, 				// camera pan speed
			currentMap_->GetGameMapLayer(0)->GetWidth(),
			currentMap_->GetGameMapLayer(0)->GetHeight()
			);


		// center the camera on the player
		camera_->CenterOnSprite(gameSprites_->Get(playerSpriteIndex_));

		stepsTaken_ 		= 0;
		stepsUntilAmbush_ 	= 160;

		gameStateManager_ = new GAMESTATE::GameStateManager();

		// we will start with the map editor if the argv[] is -edit
		if (argc > 1)
		{
			std::string argvStr = argv[1];
			if ("-edit" == argvStr)
			{
				if ("true" == gameSettings_->Get("enable_game_editors"))
				{
					SetState(GAMESTATE::MapEditor);
					MapEditors->SetState(MAPEDITORS::EditingCollisionLayer);
				}
				else
				{
					LogSimpleMessage("Not allowed!");
				}
			}
		}

		gameMenu_ = new GameMenuManager();

		if ("true" == gameSettings_->Get("enable_verbose_startup"))
		{
			gameNPCs_->List(stderr);
		}

		return true;
	}
Beispiel #27
0
int main(int argc, char *argv[])
{
  {
    int i;

    if((argc - 1) % 2)
      goto help;

    for(i = 1; i < argc - 1; i += 2)
      if(!editing && (!strcmp(argv[i], "-e") || !strcmp(argv[i], "--edit")))
	editing = argv[i+1];
      else if(!layout_title[0] && (!strcmp(argv[i], "-t") || !strcmp(argv[i], "--title")))
      {
	bzero(layout_title, 55);
	strncpy(layout_title, argv[i+1], 54);
      }
      else
      {
help:
	printf("usage: mahjong [--edit <layout> [--title <layout title>]]\n");
	return 0;
      }
  }

  srand(time(NULL));
  allegro_init();

  {
    int x, y, z;
    for(x = 16; x--;)
    for(y =  9; y--;)
    for(z =  3; z--;)
      pieceInit(board[x][y][z], x, y, z);
  }

  set_color_depth(SCREEN_DEPTH);

  if(set_gfx_mode(GFX_AUTODETECT_WINDOWED,
      SCREEN_WIDTH,   SCREEN_HEIGHT,
      SCREEN_WIDTH*2, SCREEN_HEIGHT) < 0)
  {
    fprintf(stderr, "fatal: %s\n", allegro_error);
    exit(1);
  }

#ifdef ALLEGRO_WINDOWS
  set_display_switch_callback(SWITCH_IN, update);
#endif

  left_view =
    create_sub_bitmap(screen, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
  right_view =
    create_sub_bitmap(screen, SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT);

  // init colors
    BACKGROUND_COLOR = makecol32(0x2F, 0x5F, 0x2F); // soft green
      SELECTED_COLOR = makecol32(0x00, 0xDF, 0x00); // green
  OLD_SELECTED_COLOR = makecol32(0x00, 0xBF, 0xBF); // cyan

  // load data
  {
    DATAFILE *data = load_datafile("#");
    new_game   = data[NEW_GAME_BMP].dat;
    undo       = data[UNDO_BMP].dat;
    help       = data[HELP_BMP].dat;
    quit       = data[QUIT_BMP].dat;
    tile       = data[TILE_BMP].dat;
    number[ 0] = data[BLACK1_BMP].dat;
    number[ 2] = data[BLACK2_BMP].dat;
    number[ 4] = data[BLACK3_BMP].dat;
    number[ 6] = data[BLACK4_BMP].dat;
    number[ 8] = data[BLACK5_BMP].dat;
    number[10] = data[BLACK6_BMP].dat;
    number[12] = data[BLACK7_BMP].dat;
    number[14] = data[BLACK8_BMP].dat;
    number[16] = data[BLACK9_BMP].dat;
    number[ 1] = data[RED1_BMP].dat;
    number[ 3] = data[RED2_BMP].dat;
    number[ 5] = data[RED3_BMP].dat;
    number[ 7] = data[RED4_BMP].dat;
    number[ 9] = data[RED5_BMP].dat;
    number[11] = data[RED6_BMP].dat;
    number[13] = data[RED7_BMP].dat;
    number[15] = data[RED8_BMP].dat;
    number[17] = data[RED9_BMP].dat;
    suit[0]    = data[SPADE_BMP].dat;
    suit[1]    = data[CLUB_BMP].dat;
    suit[2]    = data[DIAMOND_BMP].dat;
    suit[3]    = data[HEART_BMP].dat;
    layouts[0] = data[BLOCK_LYT].dat;
    layouts[1] = data[FLAT_LYT].dat;
    layouts[2] = data[FROGGER_LYT].dat;
    layouts[3] = data[PRECIOUS_LYT].dat;
    layouts[4] = data[PTRAD_LYT].dat;
    layouts[5] = data[PYRAMID_LYT].dat;
    layouts[6] = data[STEPS_LYT].dat;
    layouts[7] = data[THETA_LYT].dat;
  }

  scroll_screen(SCREEN_WIDTH, 0);
  current_view = right_view;

  install_timer();
  install_mouse();
  install_keyboard();
  show_mouse(current_view);

  text_mode(BACKGROUND_COLOR);

  if(!editing)
  {
    defaultLayout();

    if(alert("Our Own Version of Mahjong Solitaire, v0.1.4", NULL,
	     "Copyright (c) 2001 Eric Mulvaney, Michelle Bondy",
	     "Play", "Edit", 0, 0) == 2
	&& file_select_ex("Please select layout file to edit:", path, "lyt",
	    PATH_LENGTH-1, OLD_FILESEL_WIDTH, OLD_FILESEL_HEIGHT))
    {
      int x, y, z;

      editing = path;

      for(x = 16; x--;)
      for(y =  9; y--;)
      for(z =  3; z--;)
	board[x][y][z].value = EMPTY;
    }
  }

  mouse_callback = editing ? mouse_handler_for_editing : mouse_handler;

  if(editing)
  {
    Layout data;
    FILE *file = fopen(editing, "r");

    if(file)
    {
      if(fread(&data, sizeof(Layout), 1, file))
      {
	int x, y, z;

	if(!layout_title[0])
	  memcpy(layout_title, data.title, 55);

	for(x = 16; x--;)
	for(y =  9; y--;)
	for(z = (data.board[x][y] > 3) ? 3 : data.board[x][y]; z--;)
	{
	  board[x][y][z].value = BLANK;
	  if(!--n_pieces_left)
	    goto skip;
	}
      }
skip:
      fclose(file);
    }

    update();
  }

  click_ready = 0;
  while(1) // game loop
  {
    if(click_ready)
    {
      int x = click_x - (BOARD_XOFF - 2 * EDGE_WIDTH );
      int y = click_y - (BOARD_YOFF - 2 * EDGE_HEIGHT);
      int z;

      for(z = 3; x > 0 && y > 0 && z--; x -= EDGE_WIDTH, y -= EDGE_HEIGHT)
      {
	int i = x / FACE_WIDTH;
	int j = y / FACE_HEIGHT;

	if(i >= 16 || j >= 9)
	  continue;

	if(editing)
	{
	  if(click_ready == 1 && board[i][j][z].value == EMPTY)
	  {
	    if((z == 0 || board[i][j][z-1].value != EMPTY) && n_pieces_left)
	    {
	      n_pieces_left--;
	      board[i][j][z].value = BLANK;
	      updatePiece(&board[i][j][z]);
	      goto event_handled;
	    }
	  }
	  else if(click_ready == 2 && board[i][j][z].value != EMPTY)
	  {
	    if(z == 2 || board[i][j][z+1].value == EMPTY)
	    {
	      board[i][j][z].value = EMPTY;
	      n_pieces_left++;
	      updatePiece(&board[i][j][z]);
	      goto event_handled;
	    }
	  }
	}
	else if(selectPiece(&board[i][j][z]))
	{
	  if(!n_pairs_remaining)
	  {
	    if(current_view != left_view)
	      update();

	    if(alert("Congratulations!	You won!",
		     "Play another?",
		     NULL, "Yes", "No", 0, 0) == 1)
	      newGame();
	    else
	      return 0;
	  }

	  goto event_handled;
	}
      }

      if(click_y < BUTTON_YOFF + BUTTON_HEIGHT && click_y > BUTTON_YOFF)
      {
	if(editing)
	{
	  if(click_x > NEW_GAME_BUTTON_X1 && click_x < NEW_GAME_BUTTON_X2)
	  {
	    if(n_pieces_left == 144)
	      goto event_handled;

	    if(current_view != left_view)
	      update();

	    if(alert("Are you sure you want to clear the current Layout?",
		     NULL, NULL, "Yes", "No", 0, 0) == 1)
	    {
	      int x, y, z;
	      for(x = 16; x--;)
	      for(y =  9; y--;)
	      for(z =  3; z--;)
		board[x][y][z].value = EMPTY;
	      n_pieces_left = 144;
	      update();
	    }
	  }
	  else if(click_x > QUIT_BUTTON_X1 && click_x < QUIT_BUTTON_X2)
	  {
	    int ync;

	    if(current_view != left_view)
	      update();

	    if(n_pieces_left)
	      ync = alert3("WARNING: Layout is incomplete.",
			   NULL,
			   "Do you wish to save before exiting?",
			   "Yes", "No", "Cancel", 0, 0, 0);
	    else
	      ync = alert3("Do you wish to save before exiting?",
		    NULL, NULL, "Yes", "No", "Cancel", 0, 0, 0);

	    if(ync == 2)
	      return 0;
	    else if(ync == 1)
	    {
	      Layout data;
	      FILE *file;

	      memcpy(data.title, layout_title, 55);

	      data.complete = (n_pieces_left) ? 0 : 1;

	      if((file = fopen(editing, "w")))
	      {
		for(x = 16; x--;)
		for(y =  9; y--;)
		{
		  if	 (board[x][y][2].value == BLANK) data.board[x][y] = 3;
		  else if(board[x][y][1].value == BLANK) data.board[x][y] = 2;
		  else if(board[x][y][0].value == BLANK) data.board[x][y] = 1;
		  else					 data.board[x][y] = 0;
		}

		if(fwrite(&data, sizeof(Layout), 1, file))
		{
		  fclose(file);
		  return 0;
		}
		else
		  fclose(file);
	      }

	      if(alert("WARNING: Save failed!",
		       NULL,
		       "Do you still wish to exit?",
		       "Yes", "No", 0, 0) == 1)
		return 0;
	    }
	  }
	}
	else if(click_x > NEW_GAME_BUTTON_X1 && click_x < NEW_GAME_BUTTON_X2)
	  newGame();
	else if(click_x > UNDO_BUTTON_X1 && click_x < UNDO_BUTTON_X2)
	  undoMove();
	else if(click_x > HELP_BUTTON_X1 && click_x < HELP_BUTTON_X2)
	  giveHelp(1);
	else if(click_x > QUIT_BUTTON_X1 && click_x < QUIT_BUTTON_X2)
	{
	  if(current_view != left_view)
	    update();

	  if(alert("Are you sure you want to quit?",
	      NULL, NULL, "Yes", "No", 0, 0) == 1)
	    return 0;
	}
      }

event_handled:

      click_ready = 0;
    }
    else
      rest(100);
  }

  return 0;
}
Beispiel #28
0
int main (void)
{
// Golobal Integers
    extern int level;
    extern int lifes;
    extern int score;
    extern int health;
// Local Integers
   register int mapxoff, mapyoff;
   extern int oldpy, oldpx;
   extern int facing;
   extern int jump;
   int n, m;
  // DATAFILE *data;
//initilization    
	allegro_init();	
	install_timer();
	install_keyboard();
    set_color_depth(32);
	set_gfx_mode(MODE, WIDTH, HEIGHT, 0, 0);

//load data
data = load_datafile("test.dat");
    temp = (BITMAP *)data[NEWGUY_BMP].dat;
    for (n=0; n<4; n++)
    player_image[n] = grabframe(temp,43,77,0,0,4,n);
    destroy_bitmap(temp);
    temp2 = (BITMAP *)data[BAT1_BMP].dat;
    for (m=0; m<2; m++)
    bat_img[m] = grabframe(temp2,87,72,0,0,2,m);
    destroy_bitmap(temp2);

    test_img = load_bitmap("test.bmp", NULL);
gameover:
Start();
first:
//initilize Player
    player = malloc(sizeof(SPRITE));
    player->x = 80;
    player->y = 200;
    player->curframe=0;
    player->framecount=0;
    player->framedelay=11;
    player->maxframe=3;
    player->width=player_image[0]->w;
    player->height=player_image[0]->h;
//initilize Bat
    bat = malloc(sizeof(SPRITE));
    bat->x = 170;
    bat->y = 100;
    bat->curframe=0;
    bat->framecount=0;
    bat->framedelay=11;
    bat->maxframe=1;
    bat->width=bat_img[0]->w;
    bat->height=bat_img[0]->h;
    bat->dir = 0;
    bat->xspeed = 0;
//ini test
test = malloc(sizeof(SPRITE));
    test->x = 270;
    test->y = 400;
    test->curframe=0;
    test->framecount=0;
    test->framedelay=11;
    test->maxframe=1;
    test->width=bat_img[0]->w;
    test->height=bat_img[0]->h;
    test->dir = 0;
    test->xspeed = 0;

loadlevel();

    //main loop
	while (!key[KEY_ESC])
	{
      oldpy = player->y; 
      oldpx = player->x;

if (player->x > 3000)
        {level = 2;
		goto first;}

if (lifes == 0)
{lifes = 3;
          goto gameover;}

if (health < 1)
{lifes -=1;
  health =100;
  goto first;}

  updateEnemy(150, 300, test);
  updateEnemy(150, 300, bat);       
  enemycoll(player->x, player->y, bat);       
  keyinput();
//collition control
	if (!facing) 
        { 
            if (collided(player->x, player->y + player->height)) 
                player->x = oldpx; 
                if (collidedobj(player->x, player->y + player->height))
                   {ClearCell(player->x, player->y + player->height); 
                   AddScore();}
                      if (collidedkill(player->x+9, player->y + player->height))
                         {health -= 25;}        
        }
		else 
        { 
            if (collided(player->x + player->width, player->y + player->height)) 
                player->x = oldpx; 
                if (collidedobj(player->x + player->width, player->y + player->height))
                   {ClearCell(player->x + player->width, player->y + player->height);
                   AddScore();}
                      if (collidedkill(player->x + player->width-15, player->y + player->height))
                         {health -= 25;}        
        }
		
        //update the map scroll position
		mapxoff = player->x + player->width/2 - WIDTH/2 + 10;
		mapyoff = player->y + player->height/2 - HEIGHT/2 + 10;
        //avoid moving beyond the map edge
		if (mapxoff < 0) mapxoff = 0;
		if (mapxoff > (mapwidth * mapblockwidth - WIDTH))
            mapxoff = mapwidth * mapblockwidth - WIDTH;
		if (mapyoff < 0) 
            mapyoff = 0;
		if (mapyoff > (mapheight * mapblockheight - HEIGHT)) 
            mapyoff = mapheight * mapblockheight - HEIGHT;

        //draw the background tiles
		MapDrawBG(buffer, mapxoff, mapyoff, 0, 0, WIDTH-1, HEIGHT-1);
        //draw foreground tiles
		MapDrawFG(buffer, mapxoff, mapyoff, 0, 0, WIDTH-1, HEIGHT-1, 0);
        //draw the player's sprite
		if (facing) 
            draw_sprite(buffer, player_image[player->curframe], 
                (player->x-mapxoff), (player->y-mapyoff+1));
		else 
            draw_sprite_h_flip(buffer, player_image[player->curframe], 
                (player->x-mapxoff), (player->y-mapyoff));

        //blit the double buffer 
		vsync();
        acquire_screen();
		if (bat->dir == 1)
           draw_sprite(buffer, bat_img[bat->curframe],(bat->x-mapxoff),(bat->y-mapyoff));
        else
           draw_sprite_h_flip(buffer, bat_img[bat->curframe],(bat->x-mapxoff),(bat->y-mapyoff)); 
        
        draw_sprite(buffer, test_img,(test->x-mapxoff),(test->y-mapyoff));
        textprintf(buffer,font,0,0,9999999,"lifes = %d  Score = %d  Health = %d",lifes,score,health);
        blit(buffer, screen, 0, 0, 0, 0, WIDTH-1, HEIGHT-1);
       	release_screen();

	} //End of game loop




    for (n=0; n<4; n++)
        destroy_bitmap(player_image[n]);
    for (m=0; m<2; m++)
        destroy_bitmap(bat_img[m]);

destroy_bitmap(test_img);

    free(player);
	free(bat);
    free(test);
    destroy_bitmap(buffer);
	MapFreeMem ();
	MapFreeMem ();
    unload_datafile(data);
    allegro_exit();
	return 0;
}
Beispiel #29
0
int main(int argc, char *argv[])
{
   char buf[256];
   int i;

   /* initialise everything */
   if (allegro_init() != 0)
      return 1;
   install_keyboard(); 
   install_mouse();
   install_timer();

   if (set_gfx_mode(GFX_AUTODETECT, 640, 480, 0, 0) != 0) {
      if (set_gfx_mode(GFX_SAFE, 640, 480, 0, 0) != 0) {
	 set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
	 allegro_message("Unable to set any graphic mode\n%s\n", allegro_error);
	 return 1;
      }
   }

   /* load the datafile */
   replace_filename(buf, argv[0], "example.dat", sizeof(buf));

   datafile = load_datafile(buf);
   if (!datafile) {
      set_gfx_mode(GFX_TEXT, 0, 0, 0, 0);
      allegro_message("Error loading %s!\n", buf);
      return 1;
   }

   set_palette(datafile[THE_PALETTE].dat);

   /* set up colors */
   gui_fg_color = makecol(0, 0, 0);
   gui_mg_color = makecol(128, 128, 128);
   gui_bg_color = makecol(200, 240, 200);
   set_dialog_color(the_dialog, gui_fg_color, gui_bg_color);

   /* white color for d_clear_proc and the d_?text_procs */
   the_dialog[0].bg = makecol(255, 255, 255);
   for (i = 4; the_dialog[i].proc; i++) {
      if (the_dialog[i].proc == d_text_proc ||
          the_dialog[i].proc == d_ctext_proc ||
          the_dialog[i].proc == d_rtext_proc)
      {
         the_dialog[i].bg = the_dialog[0].bg;
      }
   }
   
   /* fill in bitmap pointers */
   the_dialog[BITMAP_OBJECT].dp = datafile[SILLY_BITMAP].dat;
   the_dialog[ICON_OBJECT].dp = datafile[SILLY_BITMAP].dat;
   
   /* shift the dialog 2 pixels away from the border */
   position_dialog(the_dialog, 2, 2);
   
   /* do the dialog */
   do_dialog(the_dialog, -1);

   unload_datafile(datafile);
   
   return 0;
}