- rand - give a variable the ability to be randomized
- constraint block - constrain that randomization
- randomize() - to run randomization on an object
- pre_randomize() function - automatically run before randomization
- post_randomize() function - automatically run after randomization
As an intro to the constraint block, we create a class to describe a die (as in gaming dice that are rolled). The value of the die can be random, but we constrain the value with a constraint block, allowing values of [1,2,3,4,5,6].
pre_randomize() and post_randomize() are functions that are automatically run whenever randomization is performed on the object.
rand variable and constraint - representing value of a rolling die (dice).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| module dice_game;
class a_die;
rand int value;
constraint six_sides { value>=1 && value<=6; }
function void pre_randomize();
$write(" die ready to be rolled ....");
endfunction
function void post_randomize();
$display(" die roll is now = %0d", value);
endfunction
endclass
initial begin
a_die my_die;
my_die = new();
repeat (4) begin
my_die.randomize();
end
end
endmodule // dice_game
|
.
//run command
Aside: We are intentionally ignoring the return value of randomize() in this example. Note the warning during compilation.