module vga(clk ,p1_pos,p2_pos,p1_size,p2_size,ball_posx,ball_posy ,VGA_r,VGA_g,VGA_b,hs,vs);
input clk;
input [9:0]p1_pos,p2_pos;
input [7:0]p1_size,p2_size;
input [10:0]ball_posx;//640
input [9:0]ball_posy;//480
output [3:0]VGA_r,VGA_g,VGA_b;
output hs,vs;
reg [19:0]vt;
reg [10:0]ht;

///////

reg [11:0] hc,hcount,r,g,b;  // VGA horizontal counter
reg [10:0] vc,vcount;  // VGA vertical counter

wire hcount_ov,vcount_ov,video_active;
// VGA mode parameters
parameter
    hsync_end   = 12'd119,
    hdat_begin  = 12'd242,
    hdat_end    = 12'd1266,
    hpixel_end  = 12'd1345,
    vsync_end   = 11'd5,
    vdat_begin  = 11'd32,
    vdat_end    = 11'd632,
    vline_end   = 11'd665;
always@(posedge clk) hcount<=(hcount_ov)? 12'd0:(hcount+12'd1);
always@(posedge clk) vcount<=(hcount_ov)? (vcount_ov)? 11'd0:(vcount+11'd1):vcount;
assign hcount_ov=hcount == hpixel_end;
assign vcount_ov=vcount == vline_end;
assign video_active=hdat_begin<=hcount&&hcount<hdat_end&&
                    vdat_begin<=vcount&&vcount<vdat_end;
assign hs=hcount>hsync_end;
assign vs=vcount>vsync_end;

assign VGA_r=(video_active)? r[3:0]:0;
assign VGA_g=(video_active)? g[3:0]:0;
assign VGA_b=(video_active)? b[3:0]:0;

// generate "image",p.s.:you can only use clk there,or it will too late to
// show image
always@(posedge clk)
begin
    vc<=vcount-vdat_begin;
    hc<=hcount-hdat_begin;
    //show ball
    if( (hc>=ball_posx)&&(hc<(ball_posx+`Ball_size))&&
        (vc>=ball_posy)&&(vc<(ball_posy+`Ball_size)))
    begin
        r<=12;
        g<=6;
        b<=0;
    end
    else
    begin
        r<=15;
        g<=15;
        b<=15;
    end
    //show player1
    if( hc>10'd30&&hc<=10'd62&&
        vc>=p1_pos&&vc<(p1_pos+p1_size))
    begin
        r<=r-((hc-30)>>1);
        g<=g-((hc-30)>>1);
    end
    else
    begin
        //show player2
        if( hc>10'd962&&hc<=10'd994&&
            vc>=p2_pos&&vc<(p2_pos+p2_size))
        begin
            g<=g-((962-hc)>>1);
            b<=b-((962-hc)>>1);
        end
    end
end
endmodule