# Draw dice results in ASCII

Show the random result of a dice toss if done with a cube shaped die, in ASCII.

$dice  should result in one of ----- | | | o | | | ----- ----- |o | | | | o| ----- ----- |o | | o | | o| ----- ----- |o o| | | |o o| ----- ----- |o o| | o | |o o| ----- ----- |o o| |o o| |o o| -----  • You have not defined the metric here. Is this meant to be a code golf? It is always worth discussing possible tasks in the puzzle lab chat or the sand box on meta so that you can address these kinds of questions before you go live. – dmckee --- ex-moderator kitten May 18 '11 at 19:13 • Sorry, I thought the metric always is the number of characters? Thanks for pointing me to the chat and then sand box on meta. If this question falls flat on it face then I will delete it. I hate to do it right now, just in case someone already started working on it. – Jonas Elfström May 18 '11 at 19:18 • Ah...note the site name "Programming puzzles and code golf" (and yeah, I thought it scanned better the other way round, too). You will also find one-liners, king-of-the-hill tournaments, and code-challenges (everything else, but you are still supposed to establish an objective metric for winning), so it is necessary to say and to apply the appropriate tag. – dmckee --- ex-moderator kitten May 18 '11 at 19:35 • According to XKCD #221, alert('-----\n|o o|\n| |\n|o o|\n-----'); is a correct program. – JiminP Sep 3 '11 at 0:08 • If you remove the ascii-art tag, I can offer my 39char-solution print("⚀⚁⚂⚃⚄⚅"(util.Random.nextInt(6))) (utf-art). – user unknown Jun 14 '12 at 22:40 ## 31 Answers ## Golfscript, 56 characters "-"5*n"|":|"o "1/:&6rand:§1<=" "&§3<=|n|&§5<=]&§2%=1$-1%


The solution can be tested here.

## Python, 112 110 chars

from random import*
r=randrange(6)
C='o '
s='-----\n|'+C[r<1]+' '+C[r<3]+'|\n|'+C[r<5]
print s+C[r&1]+s[::-1]

• Those compares in the array indexer are totally impressive! – Jonas Elfström May 18 '11 at 20:33
• Ditto! I like how you used the symmetry of the die as well :) – System Down May 18 '11 at 20:50
• Could you use something like id(0)%7%6? It's not going to be a uniform distribution, but it's significantly shorter... – Nabb May 22 '11 at 4:43
• @Nabb: that isn't very random. In particular, it is often the same from run to run, so it wouldn't be very useful in generating random dice rolls. – Keith Randall May 22 '11 at 7:18

z=" o";$><<(s=?-*5+" |#{z[2/~a=rand(6)]} #{z[a/3]}| |"+z[a/5])+z[~a%2]+s.reverse  • I liked the +s.reverse – Jonas Elfström May 19 '11 at 10:55 ## Windows PowerShell, 89 939697101119 characters -join('----- |{0} {1}| |{2}{3}'-f'o '[$(!($x=random 6);$x-lt3;$x-ne5;$x%2)])[0..14+13..0]


### Python, 109 unicode characters

#coding:u8
print u"鱸헓ȅ᪮ԅ᪅餠☏汁끝鐸즪聗K糉툜㣹뫡燳闣≆뤀⩚".encode("u16")[2:].decode("zlib").split("\n\n")[id(list())%7-1]


Note: This does not used random function, so it will be not so random like others does.

## Perl, 74 chars

Run with perl -M5.010.

$-=rand 6;$_="-----
|0 2|
|4";s/\d/$->$&?o:$"/ge;say$_,$-&1?$":o,~~reverse


(Note that the newlines in the listing are part of the string, and not just inserted for legibility.)

If you find yourself wondering what the heck the $->$ operation does, the following reading notes may be helpful:

• The variable $- automatically truncates its assigned value to an integer. • The variable $" is preset to a single space.

• o is a bareword (representing "o").

First time golfer

## Python, 161 chars

from random import*
n=randint(1,7)
o,x='o '
a='-'*5
b=(x,o)[n>3]
d=(x,o)[n>5]
c=(x,o)[n>1]
print a+'\n|'+c+x+b+'|\n|'+d+(x,o)[n%2]+d+'|\n|'+b+x+c+'|\n'+a


# Common Lisp 170

(let*((r(random 6))(a "-----
|")(c "o")(d " ")(e "|
|")(f(concatenate 'string a(if(< r 1)d c)d(if(< r 3)d c)e(if(> r 4)c ))))(concatenate 'string f(if(evenp r)c d)(reverse f)))


Note that the newlines are significant. Unlike these silly "modern" languages, Common Lisp favors readability over succinctness, so we have the cumbersome "concatenate 'string..." construct and no succinct way to reference a character in a string.

## JavaScript (169168141 137)

r=Math.random()*6|0;s='-----\n|'+(r>0?'o ':'  ')+(r>2?'o':' ')+'|\n|'+(r-5?' ':'o');alert(s+(r%2?' ':'o')+s.split('').reverse().join(''))


Doesn't look quite right in alert because it's not fixed-width font, but rest assured it is correct, or test by emitting a <pre> tag and doing writeln :-)

Proof: http://jsfiddle.net/d4YTn/3/ (only works in JS 1.7-compliant browsers, such as FF2+)

Credits: Hacked Math trick from @minitech and die print logic from @Keith.

Edit: Remove Math trick from @minitech because it actually made it longer :-)

Edit 2: Save 17 chars. Borrow trick from @Keith for taking advantage of dice symmetry. Use trick for simplifying converting random number to int.

Edit 3: Remove 1+ to shift random number from 1-6 to 0-5 and save 2 chars. As a result, I can also change r%2-1 to r%2 and save another 2 chars.

Edit 4: jsfiddle is working again. Updated :-)

• E4X! And I can't believe Chrome won't support it! – Ry- May 19 '11 at 18:15
• Heh, I beat you finally :) – Ry- May 19 '11 at 19:31
• Two characters, now, using your |0 trick :-) – Ry- May 19 '11 at 20:13
• It works in Chrome for me. – pimvdb May 25 '11 at 15:42

# JavaScript, 215213212145 135

r=Math.random()*6|0;alert('-----\n|'+[r>2?'o o':r?'o  ':'   ',r%2?r>3?'o o':'   ':' o ',r>2?'o o':r?'  o':'   '].join('|\n|')+'|\n-----');


Beat mellamokb, but I changed my original solution completely. If you want this to look good, use Google Chrome or something, change alert to console.log, and voilà.

Edit: borrowed mellamokb's |0 trick to save some characters.

• @minitech: BTW, your M=Math trick that I tried to steal actually ends up being one character longer – mellamokb May 19 '11 at 18:12
• @mellamokb: I know, I thought originally that I would use it more... – Ry- May 19 '11 at 18:16
• @minitech: You can save two chars with [s.substr(0,3),s.substr(3,3),s.substr(6,3)].join('|\n|') – mellamokb May 19 '11 at 18:19
• @mellamokb: Nope; s is an array. I'm going to restart and try again. – Ry- May 19 '11 at 19:20
• @minitech: Here we go again :-) Evolution of the best answer by competition. Now I'm down to 137, but you can borrow one of my tricks and save possibly 10 chars. – mellamokb May 19 '11 at 20:01

PHP 119 126 128 131 188 201 213 234 239

<?$c=($r=rand()%6)%2?$r>4?'o ':' ':' o';$b=$r>0?$r<3?'o  ':'o o':'   ';echo$a="-----\n|$b|\n|$c",substr(strrev($a),1);

• The closing ?> can be omitted, saving you 2 characters. – Ry- May 19 '11 at 18:14
• You can inline the declaration for $r, saving another character. The space after echo can be omitted as well. You can inline the initialization of $a too, bringing you to 128. Putting line breaks directly into the string instead of escaping them with \n saves another two characters, then. – Joey May 20 '11 at 9:25

C - 215

#include <time.h>
#include <stdlib.h>
main(){char a[]=A,b[]=B,c=3,d=(srand(time(0)),rand()%6+1),e=d-2;if(d==1)a[5]=C;else{while(--e>-1)a[b[D[d-3]-48+e]-48]=C;a[0]=a[10]=C;}p(E);while(--c>-1)p("|%s|\n",a+c*4);p(E);}


Compiles with:

cl /DA="\"   \0   \0   \"" /DB="\"5282582468\"" /DC='o' /DD="\"0136\"" /DE="\"+---+\n\"" /Dp=printf dice.c

• Is that sorta cheating with all those flags on the command-line? I don't understand it the /DA /DB /DC.. thing. – mellamokb May 26 '11 at 21:03
• My compiler does not understand the /D switch... Please don't cheat by putting random defines into the compilation command. – FUZxxl Jul 26 '12 at 11:48

Python 133

import random as R
i=R.randint(1,6)
a='   ';b='0 0'
A='-----\n|'+((a,'0  ')[i>1],b)[i>3]+'|\n|'
print A+((a,' 0 ')[i%2],b)[i>5]+A[::-1]


## F# - 165 161 characters

(System.Random()).Next 6|>fun x->[for y in[x>0;x%2=0;x>2;x=5]->if y then"o"else" "]|>fun[a;b;c;d]->printf"-----\n|%s %s|\n|%s%s%s|\n|%s %s|\n-----"a c d b d c a


Python 108 114 119 121 122 129

wtf! looks like 1st solution ?! but iam not ... cheater

108

import random as R
i=R.randint(1,6)
X=' 0'
A='-----\n|%s %s|\n|'%(X[i>1],X[i>3])+X[i>5]
print A+X[i%2]+A[::-1]


119

import random as R
i=R.randint(1,6)
X=' 0';a=X[i>5]
A='-----\n|%s %s|\n|%s|'%(X[i>1],X[i>3],a+X[i%2]+a)
print A+A[-6::-1]


### perl - 111103 101

$n=int rand 6; ($t="-----\n|0 1|\n|232|\n|1 0|\n-----\n")=~s/(\d)/5639742>>6*$1>>$n&1?o:$"/eg; die$t;

• +1 for using die instead of print/say – mbx Jun 6 '11 at 16:26

## APL (69)

5 5⍴(5⍴'-'),{⊃⍵↓' o|'}¨2,(⌽M),2,2,(N∊¨6(1 3 5)6),2,2,2,⍨M←3 6 1>⍨N←?6


import System.Random
main=randomRIO(1::Int,6)>>=putStrLn. \x->let{h="-----\n|"++c(>1):' ':c(>3):"|\n|"++[c(>5)];c f|f x='o'|True=' '}in h++c odd:reverse h


It uses roughly the same idea as the Python one.

import System.Random

main = do
x <- randomRIO (1 :: Int, 6)
putStrLn (render x)

render x = str ++ check odd ++ reverse str
where
str = concat
[ "-----\n|"
, check (> 1)
, " "
, check (> 3)
, "|\n|"
, check (> 5)
]
check f = if f x then "o" else " "


### Golfscript 80 65

6rand):^;'-'5*n+:_[^6&0^4&^6=].^1&+-1%+3/{'|'\{'o'' 'if+}/'|'n}/_


The program can be tested here

PHP 126 127 179

<?$x=($r=rand(1,6))>3?"o o":($r<2?" ":"o ");$z=$r>5?"o o":($r%2==0?"   ":" o ");$v="-----\n|$x|\n";echo"$v|$z|".strrev($v);  Another PHP solution. I came to the almost same solution by Oleg. ## Python (153) This is by far not the smallest submission, i just thought it looked nice :) import random as r print"""----- |%c %c| |%c%c%c| |%c %c| -----"""%tuple( r.choice([ " o ", "o o", "o o o", "oo oo", "oo o oo", "ooo ooo"]))  # Q (120 chars) dice:{(telcrw!5 cut"-----| ||o || o || o||o o|")(,/)(t;(ece;ler;lcr;wew;wcw;www)(*)1?6;t)}  Usage: dice[]  # C, 168164 163 chars Sorry if I'm a bit late to the party, but since no answer has been accepted yet, and the only other C solution was somewhat longer, here goes... #include<stdio.h> main(){srand(time(0));char*o="O ",r=rand()%6,i=o[r<1],j=o[r<3],k=o[r<5];printf("-----\n|%c %c|\n|%c%c%c|\n|%c %c|\n-----\n",i,j,k,o[r&1],k,j,i);}  You can remove the include and save another 18 chars, but then it doesn't compile without warnings. Edit: using user23241's command-line trick, the shortest C code that produces the result (without compiler warnings) is only 12 chars: #include I M  At least if you cheat and use the following command line to compile: gcc -DI="<stdio.h>" -DM="main(){srand(time(0));char*o=\"O \",r=rand()%6,i=o[r<1],j=o[r<3],k=o[r<5];printf(\"-----\n|%c %c|\n|%c%c%c|\n|%c %c|\n-----\n\",i,j,k,o[r&1],k,j,i);}" dice.c -o dice  # c, 140 chars r,i,s;main(){srand(time(i=0));r=rand()%6;for(s=-1;i-=s;)putchar("\n| |-o"[i>5?i==8&&r||i==10&&2<r||i==14&&4<r||i==15&&(s=1)&~r?7:i%6:6]);}  ## PHP:1284 This is my second CodeGolf, and I wasn't really aiming for shortness as much as code mutability and matching the gaming criteria. You can generate 4 sided dice as well as 6 sided. Maybe later I will shorten it and make it a little more dynamic. function draw_dice($numdice=1,$sides=4) { /* Verify acceptable parameters. */ if($sides<4){die("You must choose 4 sides or greater.");}
if($numdice<1){die("You must have at least one dice.");} /* End verification */$a=' ';
$b=' ';$c=' ';
$d=' ';$e=' ';
$f=' ';$g=' ';
$h=' ';$i=' ';
$j=' '; switch($sides)
{
case $sides%2==0: if($sides==4)
{
$ran=rand(1,$sides);
switch($ran) { case 1:$e="o";
break;
case 2:
$a="o";$j="o";
break;
case 3:
$b="o";$g="o";
$j="o"; break; case 4:$a="o";
$c="o";$g="o";
j="o"; break; } echo "<div style='text-align:center;display:inline-block;'>"; echo " - <br/>"; echo "| |<br/>"; echo "|a$b$c|<br/>";
echo "| $d$e$f |<br/>"; echo "|$g$h$i$j |<br/>"; echo "---------<br/>"; echo "</div>"; } if($sides==6)
{
$ran=rand(1,$sides);
switch($ran) { case 1:$e="o";
break;
case 2:
$a="o";$i="o";
break;
case 3:
$a="o";$i="o";
$e="o"; break; case 4:$a="o";
$c="o";$g="o";
$i="o"; break; case 5:$a="o";
$c="o";$g="o";
$i="o";$e="o";
break;
case 6:
$a="o";$c="o";
$d="o";$f="o";
$g="o";$i="o";
break;
}
echo "-----<br/>";
echo "|$a$b$c|<br/>"; echo "|$d$e$f|<br/>";
echo "|$g$h$i|<br/>"; echo "-----<br/>"; } if($sides!==4&&$sides!==6) { die("Only 4 and 6 sided are supported at this time."); } break; case$sides%2==1:
die("Must have even number of sides.");
break;
}

}

draw_dice(1,4);


## Output 4 sided:

    -
| |
|o o|
|     |
|  o  o  |
---------


## Output 6 sided:

-----
|o  |
| o |
|  o|
-----


## JavaScript 220 bytes

r=(1+Math.random()*6|0).toString(2).split("").reverse();b=r[1];c=r[2];s=[[b|c,0,c],[b&c,1&r[0],b&c],[c,0,b|c]];"-----\n|"+s.map(function(v){return v.map(function(w){return w?"o":" "}).join("")}).join("|\n|")+"|\n-----";


### Ruby , 134 132 119 118 117 112 111 chars,

My second golf in life. I've used magic numbers. Any advises please?

r=?-*5+"
|"+((a=:ghklm[rand 6])?a.to_i(36).to_s(2).tr("10","o "):"    o").insert(3,"|
|")
$><<r+r[0,14].reverse  Outputs: ice@distantstar ~/virt % ruby ./golf.rb ----- |o o| | | |o o| ----- ice@distantstar ~/virt % ruby ./golf.rb ----- |o o| |o o| |o o| ----- ice@distantstar ~/virt % ruby ./golf.rb ----- | | | o | | | ----- ice@distantstar ~/virt %  ## VimScript – 169 chararacters Note that this is not pure Vim since Vim has no builtin random number generator. There are extensions that can be downloaded for it of course, but since I am a diehard Linux man, I thought, why not just rely on the shell environment instead. ### Code norm5a-^[YPo| |^[YPP let x=system('echo$RANDOM')%6+1
if x<2
norm jllro
el
norm lrolljj.k
if x>3
norm k.hjj
en
if x>2
norm h.k
en
if x>5
norm .l
en
if x>4
norm l.
en
en


### Explanation

• The first line generators the "box" that represents the die.
• The second line fetches a random number from the environment and using modular arithmetic forces it to be a valid number for a dice.
• The remaining lines move around the die face filling in the o 's. Note that this is meant to be optimized for the least number of characters, not the least number of movements (i.e. there would be faster ways in turns of keystrokes if I was doing it manually—doing the ifs all in my head).
• As always, ^ is not a literal ^ but an indication of an escape sequence.

### Testing

Change RANDOM to DICEVALUE, save the VimScript code into dice.vim, then run this shell script on it, giving as arguments whatever numbers you want to test:

#!/bin/sh
for DICEVALUE in $@; do export DICEVALUE vim -S dice.vim done  # Mathematica 166161 146 143 chars a="O ";b=" O ";c=" O";d=" ";e="O O";RandomInteger@{1, 6}/.Thread@Rule[Range@6,{{d,b,d},{a,d,c},{a,b,c},{e,d,e},{e,b,e}, {e,e,e}}]//MatrixForm  Sample Output: If the matrix braces offend, you may replace MatrixForm with TableForm in the code. # PHP 5.4, 107 bytes <?$r=rand(1,6);$d=[' ','o'];$o='+---+
|'.$d[$r>1].' '.$d[$r>3].'|
|'.$d[$r>5];echo$o.$d[$r%2].strrev($o);


102 bytes*

<?$r=rand(1,6);$d=' o';$o='+---+ |'.$d[$r>1].' '.$d[$r>3].'| |'.$d[$r>5];echo$o.$d[$r%2].strrev($o);  **Unfortunately, the 102 byte version issues notices due to the casting of bool to int when indexing the string $d. Other than that, it works fine.*

• The byte counts seem to be 105 and 100, respectively. – 12Me21 May 2 '18 at 22:45
• Ah, I must've accounted for the newlines. – Dan Lugg May 8 '18 at 4:19