]> Creatis software - CreaPhase.git/blob - octave_packages/miscellaneous-1.1.0/rolldices.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / miscellaneous-1.1.0 / rolldices.m
1 ## Copyright (C) 2009 Jaroslav Hajek <highegg@gmail.com>
2 ##
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
6 ## version.
7 ##
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 ## details.
12 ##
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn{Function File} rolldices (@var{n})
18 ## @deftypefnx{Function File} rolldices (@var{n}, @var{nrep}, @var{delay})
19 ## Returns @var{n} random numbers from the 1:6 range, displaying a visual selection
20 ## effect.
21 ##
22 ## @var{nrep} sets the number of rolls, @var{delay} specifies time between
23 ## successive rolls in seconds. Default is nrep = 25 and delay = 0.1.
24 ##
25 ## Requires a terminal with ANSI escape sequences enabled.
26 ## @end deftypefn
27
28 function numbers = rolldices (n, nrep = 25, delay = .1)
29   if (nargin != 1)
30     print_usage ();
31   endif
32
33   persistent matrices = getmatrices ();
34
35   screen_cols = getenv ("COLUMNS");
36   if (isempty (screen_cols))
37     screen_cols = 80;
38   else
39     screen_cols = str2num (screen_cols);
40   endif
41
42   dices_per_row = floor ((screen_cols-1) / 7);
43
44   oldpso = page_screen_output (0);
45
46   numbers = [];
47
48   unwind_protect
49     while (n > 0)
50       m = min (n, dices_per_row);
51       for i = 1:nrep
52         if (i > 1)
53           puts (char ([27, 91, 51, 70])); 
54           sleep (delay);
55         endif
56         nums = ceil (6 * rand (1, m));
57         disp (matrices(:,:,nums)(:,:));
58       endfor
59       numbers = [numbers, nums];
60       n -= m;
61       puts ("\n");
62     endwhile
63   unwind_protect_cleanup
64     page_screen_output (oldpso);
65   end_unwind_protect
66
67 endfunction
68
69 function matrices = getmatrices ()
70   lbrk = [27, 91, 55, 109](ones (1, 3), :);
71   rbrk = [27, 91, 50, 55, 109](ones (1, 3), :);
72   spcs = [32, 32; 32, 32; 32, 32];
73   dchrs = reshape(
74   ["     @    @    @   @@   @@   @";
75    "  @         @         @  @   @";
76    "         @    @@   @@   @@   @"], [3, 5, 6]);
77
78   matrices = mat2cell (dchrs, 3, 5, ones (1, 6));
79   matrices = cellfun (@(mat) [spcs, lbrk, mat, rbrk], matrices, "UniformOutput", false);
80   matrices = cat (3, matrices{:});
81 endfunction