天天看點

Verilog刷題HDLBits——Lemmings3題目描述代碼結果

Verilog刷題HDLBits——Lemmings3

  • 題目描述
  • 代碼
  • 結果

題目描述

See also: Lemmings1 and Lemmings2.

In addition to walking and falling, Lemmings can sometimes be told to do useful things, like dig (it starts digging when dig=1). A Lemming can dig if it is currently walking on ground (ground=1 and not falling), and will continue digging until it reaches the other side (ground=0). At that point, since there is no ground, it will fall (aaah!), then continue walking in its original direction once it hits ground again. As with falling, being bumped while digging has no effect, and being told to dig when falling or when there is no ground is ignored.

(In other words, a walking Lemming can fall, dig, or switch directions. If more than one of these conditions are satisfied, fall has higher precedence than dig, which has higher precedence than switching directions.)

Extend your finite state machine to model this behaviour.

Verilog刷題HDLBits——Lemmings3題目描述代碼結果
Verilog刷題HDLBits——Lemmings3題目描述代碼結果

代碼

module top_module(
    input clk,
    input areset,    // Freshly brainwashed Lemmings walk left.
    input bump_left,
    input bump_right,
    input ground,
    input dig,
    output walk_left,
    output walk_right,
    output aaah,
    output digging ); 
    
    parameter LEFT=0,RIGHT=1,FALL_L=2,FALL_R=3,DIG_L=4,DIG_R=5;
    reg[2:0] state,next_state;
    
    always@(*)
        case(state)
            LEFT:if(~ground)
                	next_state=FALL_L;
                else if(dig)
                    next_state=DIG_L;
            	else if(bump_left)
                    next_state=RIGHT;
            	else
                    next_state=LEFT;
            RIGHT:if(~ground)
                	next_state=FALL_R;
                else if(dig)
                    next_state=DIG_R;
            	else if(bump_right)
                    next_state=LEFT;
            	else
                    next_state=RIGHT;
            FALL_L:next_state=ground?LEFT:FALL_L;
            FALL_R:next_state=ground?RIGHT:FALL_R;
            DIG_L:next_state=ground?DIG_L:FALL_L;
            DIG_R:next_state=ground?DIG_R:FALL_R;
        endcase
    
    always@(posedge clk or posedge areset)
        if(areset)
            state<=LEFT;
    	else
            state<=next_state;
    
    assign walk_left = (state==LEFT);
    assign walk_right = (state==RIGHT);
    assign aaah = (state==FALL_L)|(state==FALL_R);
    assign digging = (state==DIG_L)|(state==DIG_R);

endmodule
           

結果

Verilog刷題HDLBits——Lemmings3題目描述代碼結果

繼續閱讀