3
$\begingroup$

I'd like to make a simple dice roller to be used in board games. A simple way to simulate a roll is:

d[n_] := RandomChoice[Range[n]]

Now, calling d[6] will roll a 6-sided die, and d[20] a 20 sided-die. To avoid typing the command each time, it can be made into a button:

Button["d20", Echo@d[20]]

I wanted to build a Button table to simulate the classic range of d4, d6, d8, d10, d12 and d20. My initial try of:

Table[Button["d" <> ToString[k], Echo@d[k]], {k, {4, 6, 8, 10, 12, 20}}]

fails to run. I got no better result with:

ButtonBar[Table["d" <> ToString[k] :> d[k], {k, {4, 6, 8, 10, 12, 20}}]]

How can I generate this list ?

$\endgroup$

2 Answers 2

4
$\begingroup$

Try this:

buttons = Button["d" <> ToString[#], Echo@d[#]] & /@ {4, 6, 8, 10, 12, 20};

Column[buttons]

or

ButtonBar["d" <> ToString[#] :> Echo@d[#] & /@ {4, 6, 8, 10, 12, 20}]

Of course, from this example it's easy to customise the style.

For example, I would change d[n)] as follows:

d[n_] := "d" <> ToString[n] <> ": " <> ToString[RandomChoice[Range[n]]]

so that the output tells you which dice you rolled.

$\endgroup$
2
  • $\begingroup$ Is there any reason why you prefer to use string expressions (~~) as opposed to concatenation (<>) ? $\endgroup$
    – Whelp
    Commented Jan 29, 2020 at 17:11
  • $\begingroup$ No, actually I think StringJoin (<>) would be more appropriate here :) I'll edit the answer with that! $\endgroup$
    – Fraccalo
    Commented Jan 29, 2020 at 17:13
4
$\begingroup$

You can use With[{k = k}, ...] to inject the iterator values in the first argument in Table:

Table[With[{k = k}, Button["d" <> ToString[k], Echo@d[k]]], {k, {4, 6, 8, 10, 12, 20}}]

Alternatively, define a function outside Table and use it as the first argument in Table:

btn[x_] := Button["d" <> ToString[x], Echo@d[x]]
Table[btn[k], {k, {4, 6, 8, 10, 12, 20}}]

Similarly, for ButtonBar:

ButtonBar[Table[With[{k = k}, "d" <> ToString[k] :> Echo@d[k]], {k, {4, 6, 8, 10, 12, 20}}]]

or

rule[x_] := "d" <> ToString[x] :> Echo@d[x];
ButtonBar[Table[rule[k], {k, {4, 6, 8, 10, 12, 20}}]]
$\endgroup$
1
  • $\begingroup$ Interesting. I was wondering how it could be done that way, thanks. $\endgroup$
    – Whelp
    Commented Jan 29, 2020 at 17:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.