12 Rand and Constraint Block +2
randomize() of a single variable in a class.inline constraints: "randomize() with"
*randomize() to randomize an individual variable in a class
*inline constraints with randomize()
Continuing to look at constraints, we will use randomize() to randomize just a single class variable. We will show examples of inline constraints with randomize().
randomize single variable in class. inline constraint(randomize() with).
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
29
30
31
32
33
34
35
36
37
38
39
module dice_game;
class dice;
rand int value, value2;
constraint six_sides { value>=1 && value<=6;
value2>=1 && value2<=6;
}
constraint seven_eleven { ((value+value2)==7) || ((value+value2)==11); }
function void pre_randomize();
$write(" dice ready to be rolled ....");
endfunction
function void post_randomize();
$display(" dice roll is now = %0d %0d", value, value2);
endfunction
endclass
initial begin
dice my_dice;
my_dice = new();
my_dice.constraint_mode(0);
my_dice.six_sides.constraint_mode(1);
repeat (5) begin
assert (my_dice.randomize() with { ((value+value2)==2) || ((value+value2)==12); }) else
$fatal(" ERROR: Mister SVS, randomization failed, miserably.");
$display(" ..going to reroll the second die.");
my_dice.randomize(value2);
$display(" ..going to reroll the first die with inline constraint of >=5.");
my_dice.randomize(value) with {value>=5;};
$display("\n");
end
end
endmodule // dice_game
.
//run command
1
irun -sv dice_roll.sv
Aside: While I've neglected to cover it for too long (and show bad coding in that regard), to throw away the return value from randomize() and avoid the warnings my code generated, you can do this:
``` throw away return value of randomize function (cast it to void)
void'(my_dice.randomize(value2));
1
However, it is safer (particularly with non-whimsical examples) to check the return value and to take appropriate action based upon its value; such as using an assert statement.