BITMAP *tiles;
//virtual background buffer
BITMAP *scroll;
//position variables
int x=0, y=0, n;
int tilex, tiley;
void drawframe(BITMAP *source, BITMAP *dest,
int x, int y, int width, int height,
int startx, int starty, int columns, int frame)
{
//calculate frame position
int framex = startx + (frame % columns) * width;
int framey = starty + (frame / columns) * height;
//draw frame to destination bitmap
masked blit(source,dest,framex,framey,x,y,width,height);
}
//main function
int main(void)
{
//initialize allegro
allegro init();
install keyboard();
install timer();
srand(time(NULL));
set color depth(16);
set gfx mode(MODE, WIDTH, HEIGHT, 0, 0);
//create the virtual background
scroll = create bitmap(1600, 1200);
Introduction to Tile-Based Backgrounds 443
//load the tile bitmap
tiles = load bitmap("tiles.bmp", NULL);
//now draw tiles randomly on virtual background
for (tiley=0; tiley < scroll->h; tiley+=TILEH)
{
for (tilex=0; tilex < scroll->w; tilex+=TILEW)
{
//pick a random tile
n = rand() % TILES;
//draw the tile
drawframe(tiles, scroll, tilex, tiley, TILEW+1, TILEH+1,
0, 0, COLS, n);
}
}
//main loop
while (!key[KEY ESC])
{
//check right arrow
if (key[KEY RIGHT])
{
x += STEP;
if (x > scroll->w - WIDTH)
x = scroll->w - WIDTH;
}
//check left arrow
if (key[KEY LEFT])
{
x -= STEP;
if (x < 0)
x = 0;
}
//check down arrow
if (key[KEY DOWN])
{
y += STEP;
if (y > scroll->h - HEIGHT)
y = scroll->h - HEIGHT;
}
//check up arrow
if (key[KEY UP])
{
y -= STEP;
if (y < 0)
y = 0;
}
//draw the scroll window portion of the virtual buffer
blit(scroll, screen, x, y, 0, 0, WIDTH-1, HEIGHT-1);
//slow it down
rest(20);
}
destroy bitmap(scroll);
destroy bitmap(tiles);
return 0;
}
END OF MAIN()
8.5 Creating a Tile Map
int map[MAPW*MAPH] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,
0,2,2,2,2,2,2,2,2,2,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2,2,2,2,2,2,2,2,2,2,2,2,0,
0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
};
Figure 8.5
A legend of the tiles and their reference numbers used to create a map in the GameWorld program.
Figure 8.5
The GameWorld program scrolls a map that was defined in the map array.
#define MAP ACROSS 25
#define MAP DOWN 25
#define MAPW MAP ACROSS * TILEW
#define MAPH MAP DOWN * TILEH
//now draw tiles randomly on virtual background
for (tiley=0; tiley < scroll->h; tiley+=TILEH)
{
for (tilex=0; tilex < scroll->w; tilex+=TILEW)
{
//draw the tile
drawframe(tiles, scroll, tilex, tiley, TILEW+1, TILEH+1,
0, 0, COLS, map[n++]);
}
}
- Yêu cầu SV chuẩn bị:
Đọc chương 12,13,14,15,16 tài liệu [1]
Đọc các phần tương ứng trong tài liệu [5].
Chú ý nghe giảng.
Tích cực tham gia phát biểu ý kiến
Chia sẻ với bạn bè của bạn: |