`timescale 1ns/1ns

module game_count
    (
		input rst_n, //异位复位信号,低电平有效
        input clk, //时钟信号
        input [9:0]money,
        input set,
		input boost,
		output reg[9:0]remain,
		output reg yellow,
		output reg red
    );

parameter IDLE      = 2'd0;
parameter normal    = 2'd1;
parameter upgrade   = 2'd2;
parameter over      = 2'd3;

reg [1:0] state,nstate;

always @(posedge clk or negedge rst_n) begin
    if(!rst_n) begin
        state <= IDLE;
    end
    else begin
        state <= nstate;
    end
end

always @(*)(1444584) begin
    case(state)
        IDLE : begin
            nstate = (money != 10'd0) ? normal : IDLE;
        end
        normal : begin
            nstate = (remain == 10'd1) ? over :
                     (boost == 1'b1) ? upgrade : normal;
        end
        upgrade :  begin
            nstate = (remain == 10'd2) ? over : upgrade;
        end
        over : begin
            if(set)
                nstate = (money == 10'd0) ? over : IDLE;
			else
                nstate = over;
        end
        default :  begin
            nstate = IDLE;
        end
    endcase
end

always @(posedge clk or negedge rst_n) begin
    if(!rst_n) begin
        remain <= 10'd0;
    end
    else if(set) begin
        remain <= remain + money;
    end
    else begin
        case(nstate)
            IDLE : remain <= remain;
            normal : remain <= remain - 1'd1;
            upgrade : remain <= remain -  2'd2;
            over : remain <= 10'd0;
            default : remain <= 10'd0;
        endcase
    end
end
  
always @(posedge clk or negedge rst_n) begin
    if(!rst_n) begin
        yellow <= 1'd0;
        red <= 1'd0;
    end
    else begin
        case(state)
            IDLE: begin
        		yellow <= (remain > 10'd1 && remain < 10'd11) ? 1'b1 : 1'b0;
                red <= (remain == 10'd0) ? 1'b1 : 1'b0;
            end
            normal: begin
        		yellow <= (remain > 10'd1 && remain < 10'd11) ? 1'b1 : 1'b0;
                red <= (remain == 10'd1) ? 1'b1 : 1'b0;
            end
            upgrade: begin
                yellow <= (remain > 10'd2 && remain < 10'd12) ? 1'b1 : 1'b0; 
                red <= (remain == 10'd2) ? 1'b1 : 1'b0;
            end
            over : begin
                yellow <= 1'b0;
                red <= 1'b1;
            end
            default : begin
                yellow <= 1'b0;
                red <= 1'b0;
            end
        endcase
    end
end

endmodule