C/C++ 编程代写
当前位置:以往案例 > >C++ Allegro案例 | 游戏案例 | Lightning Game
2020-02-26

C++ Allegro案例 booltype
A kind of data type in lots of programminglanguages
Like c++, java and so
It can only be assigned by twovalues:

Final Project
What is Allegro?

Allegro = Allegro Low-Level GameRoutines
Created in
Written in C and supporting several platform, like windows, macos, linux-like platform and so on.

C++ Allegro案例C++ Allegro案例
booltype
A kind of data type in lots of programminglanguages
Like c++, java and so
It can only be assigned by twovalues:
0 – means
1 – means
You can just assign true or false to a bool variable. (e.g. bool a =true;)
Allegro implements a bool data type in


In this section, we will learn how to program our firstallegro program.


For each allegro with display, we need to initial allegro, initial display, set and show the display, and finally, destroy allthings have been initialized or
C++ Allegro案例
Let’s doit!!


Initialallegro
Step 1:#include

Step 2:
It’s necessary to call the initialization function before doing anythingelse with the
After you callingal_init():
Great!!! The allegro is initialized. Now you can use any function youwant in .


Initialdisplay
Step 1: Declare a pointer fordisplay:
ALLEGRO_DISPLAY*display=NULL;

Step 2: Construct thedisplay:
ALLEGRO_DISPLAY*al_create_display(intwidth,intheight);

g.:
ALLEGRO_DISPLAY* display = NULL; //declare a displaypointer
display =al_create_display(30, 50); // construct the display
Step 3: Set and show thedisplay
To getcolor:
ALLEGRO_COLORal_map_rgb(unsignedcharr,unsignedcharg,unsignedcharb);
r, g, b are the integers belonging to [0,255]
To set the whole window into thecolor:
voidal_clear_to_color(ALLEGRO_COLORcolor);
To showit:
voidal_flip_display(void);

Step 4:Destroy
Using function below to destroy yourdisplay:
voidal_destroy_display(ALLEGRO_DISPLAY*display)
Please destroy all things we have initialized or created beforethe program


In this task, we will program our first allegro project — helloworld!!


Please accomplish the task_1.c


There’s lots of hint, hoping it might help


Feel free to ask us if there’s any


In this section, we will learn how to show some words, graphicsor even images in our






draw text on thewindow:
Step 1: include the following headfiles:
#include#include
Step 2: call the following function toinitial:
al_init_font_addon(); // initialize the fontaddon
al_init_ttf_addon(); // initialize the ttf (True Type Font) addon







draw text on thewindow:
Step3:
voidal_draw_text(constALLEGRO_FONT*font, ALLEGRO_COLORcolor,floatx,floaty,intflags, charconst*text)

ALLEGRO_FONT*font:the font of text will be
Using this toconstruct:
ALLEGRO_FONT*al_load_ttf_font(charconst*filename,intsize,intflags)
filename = the address of your own .ttffile
size = the size of
Notice: You have to construct 2 kinds of font if you want use the same .ttf file but in different
flags = 0 is






draw text on thewindow:
voidal_draw_text(constALLEGRO_FONT*font, ALLEGRO_COLORcolor,floatx,floaty,intflags, charconst*text)


ALLEGRO_COLOR color: The same as we mentioned
ALLEGRO_COLORal_map_rgb(unsignedcharr,unsignedcharg,unsignedcharb)
r, g, b are the integers belonging to [0,255]






draw text on thewindow:
voidal_draw_text(constALLEGRO_FONT*font, ALLEGRO_COLORcolor,floatx,floaty,intflags, charconst*text)


Float x and y: the coordiate of our
Flags: The flags parameter can be 0 or one of the followingflags:
ALLEGRO_ALIGN_LEFT – Draw the text left-aligned (same as0).
ALLEGRO_ALIGN_CENTRE – Draw the text centered around the given
ALLEGRO_ALIGN_RIGHT – Draw the text right-aligned to the given
Text: The words you want to draw on the


draw graphic onwindow:
Step 1:#include
Step 2: call the following function to initialize thelibrary:
boolal_init_primitives_addon(void)
Step 3: call the function corresponding to the graphic you want todraw
Using rectangle as anexample:
voidal_draw_rectangle(floatx1,floaty1,floatx2,floaty2,ALLEGRO_COLORcolor, floatthickness)
x1, y1, x2, y2 – Upper left and lower right points of therectangle
color – Color of therectangle
thickness – Thickness of the lines, pass <= 0 to draw hairlinelines
There’s bunch of functions drawing different graphics filled or
Using Google to explore if you needthem!






draw aimage
Step 1: including the following headfile:
#include

Step 2: call the following function to initialize thelibrary:
al_init_image_addon();

Step 3: declare a variable in ALLEGRO_BITMAP* type to containour image:
ALLEGRO_BITMAP*img=NULL;


draw aimage
Step 4: loading the image into our variable (e.g.img):
ALLEGRO_BITMAP*al_load_bitmap(constchar*filename)
Filename: the address of your image
g:
ALLEGRO_BITMAP * img =NULL;
img =al_load_bitmap(“image.jpg”);
We can judge whether the variable img is NULL to determine whether the loadingis success.


draw aimage
Step 5: display theimage
voidal_draw_bitmap(ALLEGRO_BITMAP*bitmap,floatdx,floatdy,intflags)
bitmap: the variable containing theimage
dx dy: the location of theimage
flags canbe:
ALLEGRO_FLIP_HORIZONTAL – flip the bitmap about they-axis
ALLEGRO_FLIP_VERTICAL – flip the bitmap about thex-axis
0 – donothing


Step 6: don’t forget to destroy all things you create andload
voidal_destroy_bitmap(ALLEGRO_BITMAP*bitmap)


In this task, you are asked to draw something, including at least some words, one graphic and one
A sample font and image has already provided for
We also provided a sample code for you, filled with hint. You can either use it to design your own program, or coding from
Feel free to ask us if there’s anyquestion!!!!
You should show something likethis:


In this section, we will learn how to set up a basic interactive mechanism and deal with some interaction which is calledevent in the


For reach our goal, we need to initial event queue to record the event, and then process the event caught from event


Now we share the method for you step by


Queue


Queue
The one that enters the queue first will also exit first (becausehe/she gets serviced first)


Queue vsArray


Event
Event is something happened during the gamerunning
Like keyboard input, click mouse, close display and so


Event_queue
Event_queue is a queue containing all event, and is the only sourcewe catch any
Therefore, to let the code know what has happened, we must createa event queue first:
ALLEGRO_EVENT_QUEUE*event_queue=NULL;
event_queue=al_create_event_queue();



Event_queue –cont.
To set the type of event (keyboard, mouse, display, etc)recorded:
voidal_register_event_source(ALLEGRO_EVENT_QUEUE*queue,ALLEGRO_EVENT_SOURCE*source)
g.al_register_event_source(event_queue,al_get_display_event_source(display));

Then we can get event from
More specific, the event we get from it must belongs to one of the source wehave already
If you can not get the event you expect (e.g. keyboard input), please checkwhether you register your keyboard as one of your event source before smashing your keyboard or your






Getevent.
To know whether there is any event inevent_queue:
boolal_is_event_queue_empty(ALLEGRO_EVENT_QUEUE*)
It will return a boolvalue:
1 (true) means the queue isempty;
0 (false) means there’s some event in the
To get the event out of thequeue:
ALLEGRO_EVENTevent;(declare a variable to record theevent)
voidal_wait_for_event(ALLEGRO_EVENT_QUEUE*queue,ALLEGRO_EVENT*event); The program will be blocked here until the data of the earliest event have been duplicated into the allegro event we






Eventtype
How can we know what the event is (keyboard pressed, mouse.)
Usetype
g.event.type==ALLEGRO_EVENT_DISPLAY_CLOSE
The function is used to find whether the display is closed just






Have you ever noticed that in the 2 tasks before, the window can not be closed in normal way (click the cross symbol at thecorner)?
In this task, we will make it possible!!!






In this section, we will learn how to use keyboard and mouseas input source to interact with our






Step 1: declare and create the event_queue and event as


Step 2: call boolal_init_primitives_addon(void)first then
boolal_install_keyboard(void)to initial the keyboard





Step 3: register keyboard as event source to the eventqueue
Using ALLEGRO_EVENT_SOURCE*al_get_keyboard_event_source(void)toget the event source of keyboard
Using voidal_register_event_source(ALLEGRO_EVENT_QUEUE*queue,ALLEGRO_EVENT_SOURCE*source)to register the source to event






Step 4: To find if there’s some key being pressed or bouncingup:
Compare the event.type with keyboard
There are 2 event types for thekeyboard:
ALLEGRO_EVENT_KEY_DOWN – indicating some keys being
ALLEGRO_EVENT_KEY_UP – indicating some keys bouncing up just
Using event.type to judge the type of
Step 4: get the specifickey:
keycode to each button of keyboard:https://allegro.cc/manual/5/keyboard.html (e.g. A = ALLEGRO_KEY_A)
keyboard.keycodecapsules                   the   keycode   of   the   key   causing   the event.
Comparing it with the keycode you design to get the






Using up, down, left, right button to control the box move inthe same


The box should move to the direction whenever the corresponding button is pressed, and stop whenever the corresponding button is


Press ESC to terminate theprogram






In this section, we will learn how to use mouse as input sourceto interact with our






Register the source of mouse to theevent_queue
Using ALLEGRO_EVENT_SOURCE*al_get_mouse_event_source()toget               the source of mouse.
Callboolal_init_primitives_addon(void)first then bool al_install_mouse(void)to initial the
To find whether the mouse is clicked justnow
Compare the event.type withALLEGRO_EVENT_MOUSE_BUTTON_DOWN
mouse.button capsules the information of the pressedbutton
1 for left button. 2 for right one, and so on soforth
To find whether the mouse ismoving:
Compare the event.type withALLEGRO_EVENT_MOUSE_AXES
Using event.mouse.x and event.mouse.y to get the position of






Using mouse to determinate the location of the


The box should be the same place as the cursor wheneverthe cursor is in the


Press left button to make the box disappear and press it again to make it


Press right button to terminate theprogram


1.语言及环境:用C语言的Allegro 5套件写一个类似雷电的2D射击小游戏(大一课设水平),

须使用提供的template(后面有关于template的说明

2.内容:

(1)游戏主选单:

Start

About

Exit

(2)游戏主体:

外观:战机,血条(蓝条),子弹…

游戏性:射击子弹,移动,击中扣血等…

(3)游戏结束画面:

Win

Game Over

Restart

End

4.以下几样选5样做就行:

(1)开头+人物动画(可截取多张图片连续display

(2)厉害的AI(比如子弹追踪等…

(3)道具

(4)商店系统

(5)存档,读档

(6)背景音乐

-and so on



对于Template中所提供code中各func的解释:

game_init():初始化所有控制器

game_begin():初始游戏介面

game_run():游戏主体(while循环内,会持续刷新接收queue指令)

game_destroy():对queue,display等的摧毁,防占用内存

process_event():控制各式event(键盘 鼠标)

show_err_msg(int msg):方便debug

范例:

#include
#include
#include
#include
#include
#include
#include
#include

#define GAME_TERMINATE -1

// ALLEGRO Variables
ALLEGRO_DISPLAY* display = NULL;
ALLEGRO_EVENT_QUEUE *event_queue = NULL;
ALLEGRO_BITMAP *image = NULL;
ALLEGRO_BITMAP *image2 = NULL;
ALLEGRO_BITMAP *image3 = NULL;
ALLEGRO_BITMAP *background = NULL;
ALLEGRO_KEYBOARD_STATE keyState ;
ALLEGRO_TIMER *timer = NULL;
ALLEGRO_TIMER *timer2 = NULL;
ALLEGRO_TIMER *timer3 = NULL;
ALLEGRO_SAMPLE *song=NULL;
ALLEGRO_FONT *font = NULL;

//Custom Definition
const char *title = "Final Project 10xxxxxxx";
const float FPS = 60;
const int WIDTH = 400;
const int HEIGHT = 600;
typedef struct character
{
int x;
int y;
ALLEGRO_BITMAP *image_path;

}Character;

Character character1;
Character character2;
Character character3;

int imageWidth = 0;
int imageHeight = 0;
int draw = 0;
int done = 0;
int window = 1;
bool judge_next_window = false;
bool ture = true; //true: appear, false: disappear
bool next = false; //true: trigger
bool dir = true; //true: left, false: right

void show_err_msg(int msg);
void game_init();
void game_begin();
int process_event();
int game_run();
void game_destroy();

int main(int argc, char *argv[]) {
int msg = 0;

game_init();
game_begin();

while (msg != GAME_TERMINATE) {
msg = game_run();
if (msg == GAME_TERMINATE)
printf("Game Over\n");
}

game_destroy();
return 0;
}

void show_err_msg(int msg) {
fprintf(stderr, "unexpected msg: %d\n", msg);
game_destroy();
exit(9);
}

void game_init() {
if (!al_init()) {
show_err_msg(-1);
}
if(!al_install_audio()){
fprintf(stderr, "failed to initialize audio!\n");
show_err_msg(-2);
}
if(!al_init_acodec_addon()){
fprintf(stderr, "failed to initialize audio codecs!\n");
show_err_msg(-3);
}
if (!al_reserve_samples(1)){
fprintf(stderr, "failed to reserve samples!\n");
show_err_msg(-4);
}
// Create display
display = al_create_display(WIDTH, HEIGHT);
event_queue = al_create_event_queue();
if (display == NULL || event_queue == NULL) {
show_err_msg(-5);
}
// Initialize Allegro settings
al_set_window_position(display, 0, 0);
al_set_window_title(display, title);
al_init_primitives_addon();
al_install_keyboard();
al_install_audio();
al_init_image_addon();
al_init_acodec_addon();
al_init_font_addon();
al_init_ttf_addon();

// Register event
al_register_event_source(event_queue, al_get_display_event_source(display));
al_register_event_source(event_queue, al_get_keyboard_event_source());
}

void game_begin() {
// Load sound
song = al_load_sample( "hello.wav" );
if (!song){
printf( "Audio clip sample not loaded!\n" );
show_err_msg(-6);
}
// Loop the song until the display closes
al_play_sample(song, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_LOOP,NULL);
al_clear_to_color(al_map_rgb(100,100,100));
// Load and draw text
font = al_load_ttf_font("pirulen.ttf",12,0);
al_draw_text(font, al_map_rgb(255,255,255), WIDTH/2, HEIGHT/2+220 , ALLEGRO_ALIGN_CENTRE, "Press 'Enter' to start");
al_draw_rectangle(WIDTH/2-150, 510, WIDTH/2+150, 550, al_map_rgb(255, 255, 255), 0);
al_flip_display();
}

int process_event(){
// Request the event
ALLEGRO_EVENT event;
al_wait_for_event(event_queue, &event);

// Our setting for controlling animation
if(event.timer.source == timer){
if(character2.x < -150) dir = false; else if(character2.x > WIDTH+50) dir = true;

if(dir) character2.x -= 10;
else character2.x += 10;
}
if(event.timer.source == timer2){
ture = false;
next = true;
}
if(event.timer.source == timer3){
if(next) next = false;
else ture = true;
}

// Keyboard
if(event.type == ALLEGRO_EVENT_KEY_UP)
{
switch(event.keyboard.keycode)
{
// Control
case ALLEGRO_KEY_W:
character1.y -= 30;
break;
case ALLEGRO_KEY_S:
character1.y += 30;
break;
case ALLEGRO_KEY_A:
character1.x -= 30;
break;
case ALLEGRO_KEY_D:
character1.x += 30;
break;

// For Start Menu
case ALLEGRO_KEY_ENTER:
judge_next_window = true;
break;
}
}

// Shutdown our program
else if(event.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
return GAME_TERMINATE;

return 0;
}

int game_run() {
int error = 0;
// First window(Menu)
if(window == 1){
if (!al_is_event_queue_empty(event_queue)) {
error = process_event();
if(judge_next_window) {
window = 2;
// Setting Character
character1.x = WIDTH / 2;
character1.y = HEIGHT / 2 + 150;
character2.x = WIDTH + 100;
character2.y = HEIGHT / 2 - 280;
character1.image_path = al_load_bitmap("tower.png");
character2.image_path = al_load_bitmap("teemo_left.png");
character3.image_path = al_load_bitmap("teemo_right.png");
background = al_load_bitmap("stage.jpg");

//Initialize Timer
timer = al_create_timer(1.0/15.0);
timer2 = al_create_timer(1.0);
timer3 = al_create_timer(1.0/10.0);
al_register_event_source(event_queue, al_get_timer_event_source(timer)) ;
al_register_event_source(event_queue, al_get_timer_event_source(timer2)) ;
al_register_event_source(event_queue, al_get_timer_event_source(timer3)) ;
al_start_timer(timer);
al_start_timer(timer2);
al_start_timer(timer3);
}
}
}
// Second window(Main Game)
else if(window == 2){
// Change Image for animation
al_draw_bitmap(background, 0,0, 0);
if(ture) al_draw_bitmap(character1.image_path, character1.x, character1.y, 0);

if(dir) al_draw_bitmap(character2.image_path, character2.x, character2.y, 0);
else al_draw_bitmap(character3.image_path, character2.x, character2.y, 0);

al_flip_display();
al_clear_to_color(al_map_rgb(0,0,0));

// Listening for new event
if (!al_is_event_queue_empty(event_queue)) {
error = process_event();
}
}
return error;
}

void game_destroy() {
// Make sure you destroy all things
al_destroy_event_queue(event_queue);
al_destroy_display(display);
al_destroy_timer(timer);
al_destroy_timer(timer2);
al_destroy_bitmap(image);
al_destroy_sample(song);
}


在线提交订单