天天看點

HDLBits刷題_Lemmings2

See also: Lemmings1.

In addition to walking left and right, Lemmings will fall (and presumably go "aaah!") if the ground disappears underneath them.

In addition to walking left and right and changing direction when bumped, when ground=0, the Lemming will fall and say "aaah!". When the ground reappears (ground=1), the Lemming will resume walking in the same direction as before the fall. Being bumped while falling does not affect the walking direction, and being bumped in the same cycle as ground disappears (but not yet falling), or when the ground reappears while still falling, also does not affect the walking direction.

Build a finite state machine that models this behaviour.

module top_module(
    input clk,
    input areset,    // Freshly brainwashed Lemmings walk left.
    input bump_left,
    input bump_right,
    input ground,
    output walk_left,
    output walk_right,
    output aaah ); 
    
    parameter g1right = 3, g1left = 2, g0right = 1, g0left = 0; //四個狀态,分别是右走、坐走、掉落向右、掉落向左
    reg [1:0] state, next;
    
    always @(*)begin
    case (state)
        g0left: next = (ground == 0) ? g0left : g1left;
        g0right: next = (ground == 0) ? g0right : g1right;
        
        g1left: begin
            if (ground == 0) next = g0left;
            else begin next = (bump_left == 1) ? g1right : g1left; end
        end
        
        g1right: begin
            if (ground == 0) next = g0right;
            else begin next = (bump_right == 1) ? g1left : g1right; end
        end
    endcase
    end
    
    always @(posedge clk or posedge areset) begin
        if (areset == 1) state = g1left;
        else state = next;
    end
    
    assign walk_left = (state == g1left);
    assign walk_right = (state == g1right);
    
    assign aaah = (state == g0left | state == g0right);       

endmodule
           

繼續閱讀