Verilog刷题HDLBits——Lemmings4

Verilog刷题HDLBits——Lemmings4

  • 题目描述
  • 代码
  • 结果

题目描述

See also: Lemmings1, Lemmings2, and Lemmings3.

Although Lemmings can walk, fall, and dig, Lemmings aren’t invulnerable. If a Lemming falls for too long then hits the ground, it can splatter. In particular, if a Lemming falls for more than 20 clock cycles then hits the ground, it will splatter and cease walking, falling, or digging (all 4 outputs become 0), forever (Or until the FSM gets reset). There is no upper limit on how far a Lemming can fall before hitting the ground. Lemmings only splatter when hitting the ground; they do not splatter in mid-air.

Extend your finite state machine to model this behaviour.

Falling for 20 cycles is survivable:
Verilog刷题HDLBits——Lemmings4_第1张图片
Verilog刷题HDLBits——Lemmings4_第2张图片

代码

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,SPLAT=6;
    reg[3:0] state,next_state;
    integer clock;
    
    always@(*)
        case(state)
            LEFT:next_state=ground?(dig?DIG_L:(bump_left?RIGHT:LEFT)):FALL_L;
            RIGHT:next_state=ground?(dig?DIG_R:(bump_right?LEFT:RIGHT)):FALL_R;
            FALL_L:next_state=ground?((clock>19)?SPLAT:LEFT):FALL_L;
            FALL_R:next_state=ground?((clock>19)?SPLAT:RIGHT):FALL_R;
            DIG_L:next_state=ground?DIG_L:FALL_L;
            DIG_R:next_state=ground?DIG_R:FALL_R;
            SPLAT:next_state=SPLAT;
        endcase
    
    always@(posedge clk or posedge areset)
        if(areset)
            state<=LEFT;
    	else
            state<=next_state;
    
    always@(posedge clk or posedge areset)
        if(areset)
            clock<=0;
    	else if(state==FALL_L||state==FALL_R)
            clock<=clock+1;
    	else
            clock<=0;
    
    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——Lemmings4_第3张图片

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