DICE

Return to main page




# DICE

# A utility to convert results of dice throwing to a hexadecimal sequence.
# Delivers a hex sequence (any remaining bits are discard).
# Assumption: Dices are numbered 1 to nface, excepting the 10-faced ones which
# are numbered 0-9.
# For simplicity, no optimization is done, i.e. computation is performed on
# single dice throw values.


# A list of present author's software that are currently directly maintained by
# himself is available at http://mok-kong-shen.de. Users are advised to
# download such software from that home page only.


# Code written by M. K. Shen on 24.11.2013.

def dice(nface,seq):
  assert(nface in [6,8,10,12,20,30])
  bittab2=['0','1']
  bittab4=['00','01','10','11']
  bittab8=[]
  for i in range(8):
    st=bin(i)[2:]
    df=3-len(st)
    if df>0:
      bittab8+=[df*'0'+st]
    else:
      bittab8+=[st]
  bittab16=[]
  for i in range(16):
    st=bin(i)[2:]
    df=4-len(st)
    if df>0:
      bittab16+=[df*'0'+st]
    else:
      bittab16+=[st]
  hextab=[]
  for i in range(16):
    st=hex(i)[2:]
    hextab+=[st]
  leng=len(seq)
  q=nface-1
  bits=""
  for i in range(leng):
    s=seq[i]
    if nface!=10:
      s-=1
    if s<0 or s>q:
      print("Error dice: Input symbol out of range:",seq[i],"*********")
      return
    if nface==6:
      if s<4:
        bits+=bittab4[s]
      else:
        bits+=bittab2[s-4]
    elif nface==8:
      bits+=bittab8[s]
    elif nface==10:
      if s<8:
        bits+=bittab8[s]
      else:
        bits+=bittab2[s-8]
    elif nface==12:
      if s<8:
        bits+=bittab8[s]
      else:
        bits+=bittab4[s-8]
    elif nface==20:
      if s<16:
        bits+=bittab16[s]
      else:
        bits+=bittab4[s-16]
    elif nface==30:
      if s<16:
        bits+=bittab16[s]
      elif s<24:
        bits+=bittab8[s-16]
      elif s<28:
        bits+=bittab4[s-24]
      else:
        bits+=bittab2[s-28]
  leng=len(bits)//4
  hexs=""
  k=0
  for i in range(leng):
    k1=k+4
    c=bittab16.index(bits[k:k1])
    hexs+=hextab[c]
    k=k1
  return(hexs)

# An example with 30-faced dice:

diceseq=[18,22,10,6,26,22,20,8,6,1,27,16,23,7,30,23,13,2,19,11,1,25,\
         13,6,26,13,16,23,21,29,18,30,21,6,2,24,10,12,24,27,20]
hexseq=dice(30,diceseq)
print(hexseq)



Return to main page