目录
背景
Lemmings1
前言
原题复现
我的设计
Lemmings2
Lemmings3
背景
这是一个Lemmings的简单游戏,我们通过状态机可以设计这个游戏,从简单到复杂,一步一步实现这个游戏。
Lemmings1
前言
Lemmings1想要往左走,可是遇到左侧的障碍后,便向右转向;在向右走的过程中,如果遇到右侧的障碍,同理左转向。头脑简单的Lemmings要么左走,要么右走,两种状态。
原题复现
原题点此传送:
The game Lemmings involves critters with fairly simple brains. So simple that we are going to model it using a finite state machine.
In the Lemmings' 2D world, Lemmings can be in one of two states: walking left or walking right. It will switch directions if it hits an obstacle. In particular, if a Lemming is bumped on the left, it will walk right. If it's bumped on the right, it will walk left. If it's bumped on both sides at the same time, it will still switch directions.
Implement a Moore state machine with two states, two inputs, and one output that models this behaviour.
module top_module(input clk,input areset, // Freshly brainwashed Lemmings walk left.input bump_left,input bump_right,output walk_left,output walk_right);
我的设计
设计我的Lemmings:
module top_module(input clk,input areset, // Freshly brainwashed Lemmings walk left.input bump_left,input bump_right,output walk_left,output walk_right); // parameter LEFT=0, RIGHT=1;reg state, next_state;always @(*) begin// State transition logiccase(state)LEFT: beginif(bump_left) next_state = RIGHT;else next_state = LEFT;endRIGHT: beginif(bump_right) next_state = LEFT;else next_state = RIGHT;enddefault: beginnext_state = LEFT; endendcaseendalways @(posedge clk, posedge areset) begin// State flip-flops with asynchronous resetif(areset) beginstate <= LEFT;endelse beginstate <= next_state; endendalways@(*) begincase(state)LEFT: beginwalk_left = 1; walk_right = 0;endRIGHT: beginwalk_right = 1;walk_left = 0;enddefault: begin // almost impossiblewalk_left = 0;walk_right = 0;endendcaseend// Output logic// assign walk_left = (state == ...);// assign walk_right = (state == ...);endmodule
我设计的Lemmings,就是两个状态,处于LEFT状态,则向左走,处于RIGHT状态,也就向右走,复位则向左走。
输出仅仅和当前处于那个状态有关,而状态的切换,也是看当前状态下有没有当前方向的阻碍,例如在LEFT状态下,存在bump_left,则下一个时钟状态切换到RIGHT,固然,Lemmings也就向右走。
测试成功。
Lemmings2
Lemmings3