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.

题目地址:Lemmings2 - HDLBits (01xz.net)

由于增加了坠落(fall)状态,所以可以通过增加两个状态 即 L2G 和R2G 分别表示向左走时进入坠落状态,向右走时进入坠落状态 。

注意,areset为异步的,所以应该为always @(posedge clk or posedge areset)begin

end

代码如下:

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 ); 
    //增加两个状态L2G 和R2G 分别表示左下坠、右下坠。
    reg [1:0] state,nextstate;
    wire [2:0]dirt = {ground,bump_left,bump_right};
    parameter left = 0,
              l2g = 1,
              right = 2,
              r2g = 3;
    always @(posedge clk or posedge areset) begin
        if(areset)
            state <= left;
        else
            state <= nextstate;
    end

    // logic translation
    always @(*)begin 
    //    nextstate <= left;
        case(state)
            left:if(~ground)
                    nextstate <= l2g;
                 else if(dirt==3'b111 || dirt==3'b110)
                    nextstate <= right;
                 else
                    nextstate <= left;
            right:if(~ground)
                    nextstate <=r2g;
                 else if(dirt==3'b111 || dirt==3'b101)
                    nextstate <= left;
                 else
                    nextstate <= right;
            l2g:if(ground)
                    nextstate <= left;
                else
                    nextstate <= l2g;
            r2g:if(ground)
                    nextstate <= right;
                else
                    nextstate <= r2g;
            default:
                    nextstate <= left;
        endcase
    end
    assign walk_left = (state==left);
    assign walk_right = (state==right);
    assign aaah = (state==l2g || state==r2g);
endmodule

你可能感兴趣的:(fpga开发)