#include #include #include #include #include #define framerate 8.0 #define screen_width 640 #define screen_height 480 #define BLOCK_LEN 10 #define GRID_HEIGHT 40 #define GRID_WIDTH 50 #define GRID_BORDER_WIDTH 10 _bool is_snake(int x, int y, int* snake_x, int* snake_y,int snake_length){ for(int i=0; iclk = !tb->clk; tb->event al_wait_for_event(queue, &event); switch(event.type) { case ALLEGRO_EVENT_TIMER: // game logic goes here. redraw = true; break; case ALLEGRO_EVENT_KEY_DOWN: switch(event.keyboard.keycode){ case(ALLEGRO_KEY_DOWN): if(!changed_direction &&direction_y!=-1){ direction_x=0; direction_y=1; } changed_direction = 1; break; case(ALLEGRO_KEY_UP): if(!changed_direction &&direction_y!=1){ direction_x=0; direction_y=-1; } changed_direction = 1; break; case(ALLEGRO_KEY_RIGHT): if(!changed_direction &&direction_x!=-1){ direction_x=1; direction_y=0; } changed_direction = 1; break; case(ALLEGRO_KEY_LEFT): if(!changed_direction &&direction_x!=1){ direction_x=-1; direction_y=0; } changed_direction = 1; break; } break; case ALLEGRO_EVENT_DISPLAY_CLOSE: done = true; break; } if(done) break; if(redraw && al_is_event_queue_empty(queue)) { changed_direction=0; al_draw_rectangle(0,0,2*GRID_BORDER_WIDTH+BLOCK_LEN*GRID_WIDTH, 2*GRID_BORDER_WIDTH+BLOCK_LEN*GRID_HEIGHT, al_map_rgb(0,0,255),GRID_BORDER_WIDTH); int next_pos_x; int next_pos_y; next_pos_x=direction_x+pos_x[head_i]; next_pos_y=direction_y+pos_y[head_i]; if(is_snake(next_pos_x,next_pos_y,pos_x,pos_y,length)) return 0; if(next_pos_x>=GRID_WIDTH) next_pos_x=0; if(next_pos_x<0) next_pos_x=GRID_WIDTH-1; if(next_pos_y>=GRID_HEIGHT) next_pos_y=0; if(next_pos_y<0) next_pos_y=GRID_HEIGHT-1; if(next_pos_x==apple_x && next_pos_y==apple_y){ memmove(pos_x+head_i+2,pos_x+head_i+1,sizeof(int)*(length-head_i-1)); memmove(pos_y+head_i+2,pos_y+head_i+1,sizeof(int)*(length-head_i-1)); length++; create_apple(&apple_x,&apple_y,pos_x,pos_y,length); } head_i++; if(head_i>=length) head_i=0; draw_box(pos_x[head_i],pos_y[head_i],al_map_rgb(0,0,0)); pos_x[head_i]=next_pos_x; pos_y[head_i]=next_pos_y; draw_box(apple_x,apple_y,al_map_rgb(255,0,0)); //for(int i =0;i