Draw dice results in ASCII

25

2

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|
-----

Jonas Elfström

Posted 2011-05-18T16:25:40.803

Reputation: 373

9If you remove the ascii-art tag, I can offer my 39char-solution print("⚀⚁⚂⚃⚄⚅"(util.Random.nextInt(6))) (utf-art). – user unknown – 2012-06-14T22:40:22.070

4

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 – 2011-05-18T19:13:42.437

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 – 2011-05-18T19:18:37.767

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 – 2011-05-18T19:35:20.077

13

According to XKCD #221, alert('-----\n|o o|\n| |\n|o o|\n-----'); is a correct program.

– JiminP – 2011-09-03T00:08:30.970

Answers

7

Golfscript, 56 characters

"-"5*n"|":|"o "1/:&6rand:§1<=" "&§3<=|n|&§5<=]&§2%=1$-1%

The solution can be tested here.

Ventero

Posted 2011-05-18T16:25:40.803

Reputation: 9 842

25

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]

Keith Randall

Posted 2011-05-18T16:25:40.803

Reputation: 19 865

6Those compares in the array indexer are totally impressive! – Jonas Elfström – 2011-05-18T20:33:40.823

2Ditto! I like how you used the symmetry of the die as well :) – System Down – 2011-05-18T20:50:38.417

Could you use something like id(0)%7%6? It's not going to be a uniform distribution, but it's significantly shorter... – Nabb – 2011-05-22T04:43:37.730

@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 – 2011-05-22T07:18:45.533

11

Ruby 1.9, 80 84 characters

z=" o";$><<(s=?-*5+"
|#{z[2/~a=rand(6)]} #{z[a/3]}|
|"+z[a/5])+z[~a%2]+s.reverse

Ventero

Posted 2011-05-18T16:25:40.803

Reputation: 9 842

I liked the +s.reverse – Jonas Elfström – 2011-05-19T10:55:00.047

7

Windows PowerShell, 89 93 96 97 101 119 characters

-join('-----
|{0} {1}|
|{2}{3}'-f'o '[$(!($x=random 6);$x-lt3;$x-ne5;$x%2)])[0..14+13..0]

Joey

Posted 2011-05-18T16:25:40.803

Reputation: 12 260

5

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.

YOU

Posted 2011-05-18T16:25:40.803

Reputation: 4 321

5

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").

breadbox

Posted 2011-05-18T16:25:40.803

Reputation: 6 893

4

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

System Down

Posted 2011-05-18T16:25:40.803

Reputation: 191

4

JavaScript, 215 213 212 145 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.

Ry-

Posted 2011-05-18T16:25:40.803

Reputation: 5 283

@minitech: BTW, your M=Math trick that I tried to steal actually ends up being one character longer – mellamokb – 2011-05-19T18:12:15.973

@mellamokb: I know, I thought originally that I would use it more... – Ry- – 2011-05-19T18:16:06.093

@minitech: You can save two chars with [s.substr(0,3),s.substr(3,3),s.substr(6,3)].join('|\n|') – mellamokb – 2011-05-19T18:19:28.010

1@mellamokb: Nope; s is an array. I'm going to restart and try again. – Ry- – 2011-05-19T19:20:30.983

@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 – 2011-05-19T20:01:49.093

@minitech: Love the x?x?x:x:x. Didn't know you could do that without any parens, lol! Wow and x?x:x?x:x? Impressive and creative. I'm learning so much through these exercises :-) – mellamokb – 2011-05-19T20:02:40.480

@minitech: pssst. mutual up-vote? – mellamokb – 2011-05-19T20:09:51.207

@minitech: Wow are you really only 13 years old?? lol... – mellamokb – 2011-05-19T20:11:55.107

@mellamokb: Sure, mutual up-vote :-) Yes, I'm 13 also. – Ry- – 2011-05-19T20:13:59.863

I know this thread is old, but... any time you have a 3-char constant string that you use at least 3 times (' ' in this case) it is better to put it into a variable. Doing that and changing how the join is done will knock 9 chars off the above (I see 137 for the above if you ignore the ; at the end, but this version is 128 chars): r=Math.random(d='-----',z='| |',t='|o o|')*6|0;alert([d,r>2?t:r?'|o |':z,r%2?r>3?t:z:'| o |',r>2?t:r?'| o|':z,d].join('\n')). – DocMax – 2011-06-24T01:50:33.340

4

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.

Dr. Pain

Posted 2011-05-18T16:25:40.803

Reputation: 261

4

JavaScript (169 168 141 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 :-)

mellamokb

Posted 2011-05-18T16:25:40.803

Reputation: 5 544

E4X! And I can't believe Chrome won't support it! – Ry- – 2011-05-19T18:15:06.470

Heh, I beat you finally :) – Ry- – 2011-05-19T19:31:08.480

Two characters, now, using your |0 trick :-) – Ry- – 2011-05-19T20:13:14.433

It works in Chrome for me. – pimvdb – 2011-05-25T15:42:04.393

3

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);

Oleg

Posted 2011-05-18T16:25:40.803

Reputation: 31

The closing ?> can be omitted, saving you 2 characters. – Ry- – 2011-05-19T18:14:20.073

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 – 2011-05-20T09:25:45.670

3

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]

0b1t

Posted 2011-05-18T16:25:40.803

Reputation: 91

3

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

user23241

Posted 2011-05-18T16:25:40.803

Reputation: 31

My compiler does not understand the /D switch... Please don't cheat by putting random defines into the compilation command. – FUZxxl – 2012-07-26T11:48:16.160

1Is that sorta cheating with all those flags on the command-line? I don't understand it the /DA /DB /DC.. thing. – mellamokb – 2011-05-26T21:03:37.307

3

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]

0b1t

Posted 2011-05-18T16:25:40.803

Reputation: 91

3

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

nharren

Posted 2011-05-18T16:25:40.803

Reputation: 383

3

perl - 111 103 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;

swilliams

Posted 2011-05-18T16:25:40.803

Reputation: 476

1+1 for using die instead of print/say – mbx – 2011-06-06T16:26:54.400

3

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

marinus

Posted 2011-05-18T16:25:40.803

Reputation: 30 224

3

Golfscript 80 65

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

The program can be tested here

Cristian Lupascu

Posted 2011-05-18T16:25:40.803

Reputation: 8 369

3

Haskell, 154 162 167 172 chars

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.

Readable version:

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 " "

Lambda Fairy

Posted 2011-05-18T16:25:40.803

Reputation: 311

2

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.

Alberto Fernández

Posted 2011-05-18T16:25:40.803

Reputation: 131

2

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"]))

quasimodo

Posted 2011-05-18T16:25:40.803

Reputation: 985

2

Q (120 chars)

dice:{(`t`e`l`c`r`w!5 cut"-----|   ||o  || o ||  o||o o|")(,/)(`t;(`e`c`e;`l`e`r;`l`c`r;`w`e`w;`w`c`w;`w`w`w)(*)1?6;`t)}

Usage:

dice[]

skeevey

Posted 2011-05-18T16:25:40.803

Reputation: 4 139

2

C, 168 164 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

Mr Lister

Posted 2011-05-18T16:25:40.803

Reputation: 3 668

2

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]);}

baby-rabbit

Posted 2011-05-18T16:25:40.803

Reputation: 1 623

1

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|
-----

Event_Horizon

Posted 2011-05-18T16:25:40.803

Reputation: 287

1

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-----";

eikes

Posted 2011-05-18T16:25:40.803

Reputation: 221

1

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.*

Dan Lugg

Posted 2011-05-18T16:25:40.803

Reputation: 121

The byte counts seem to be 105 and 100, respectively. – 12Me21 – 2018-05-02T22:45:07.603

Ah, I must've accounted for the newlines. – Dan Lugg – 2018-05-08T04:19:04.227

1

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 % 

defhlt

Posted 2011-05-18T16:25:40.803

Reputation: 1 717

1

Mathematica 166 161 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:

five


If the matrix braces offend, you may replace MatrixForm with TableForm in the code.

DavidC

Posted 2011-05-18T16:25:40.803

Reputation: 24 524

1

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

Kazark

Posted 2011-05-18T16:25:40.803

Reputation: 289

0

SmileBASIC, 117 99 bytes

N=RND(6)B=N>2?"-"*5L!!N*5-B*2L!(N<<31)*4-(N>4)L!!N+B*2?"-"*5DEF L I?"|";MID$("   o o  ",I,3);"|
END

Output

Cheating version: ?""[RND(6)] (What it looks like in SmileBASIC's font)

12Me21

Posted 2011-05-18T16:25:40.803

Reputation: 6 110