Question

So for a school project we've been asked to code a boggle game on Python (I'm using 2.7.3), and I've come to a dilemma. I'm trying to get my randomly selected letters from an array of 16 hypothetical "cubes" to appear in a 4x4 format (so that there is a square with 16 random letters).

The code can be seen here:

#Boggle array within an array (array of each letter on each cube placed within another array of 16 cube arrays)

DICE = [
["A", "A", "E", "E", "G", "N"],
["A", "B", "B", "J", "O", "O"],
["A", "C", "H", "O", "P", "S"],
["A", "F", "F", "K", "P", "S"],
["A", "O", "O", "T", "T", "W"],
["C", "I", "M", "O", "T", "V"],
["D", "E", "I", "L", "R", "X"],
["H", "L", "N", "N", "R", "Z"],
["D", "I", "S", "T", "T", "Y"],
["E", "E", "G", "H", "N", "W"],
["E", "E", "I", "N", "S", "U"],
["E", "H", "R", "T", "V", "W"],
["E", "I", "O", "S", "S", "T"],
["E", "L", "R", "T", "T", "Y"],
["H", "A", "E", "E", "G", "N"],
["A", "I", "M", "N", "Q", "U"]]



#Code to randomly select letters from the array defined in DICE

from random import choice
for d in DICE:
    print choice(d)

As you can see I've used a for loop to select random letters from each line in the DICE array, now I want those 16 randomly selected letters to display as to create the 4x4 grid.

I.e.

a b c d
e f g h
i j k l
m n o p

Thanks in advance!

Was it helpful?

Solution 2

for i, d in enumerate(DICE):
    print choice(d),   # comma prevents newline
    if not (i+1) % 4:  # i+1 modulus 4 will evaluate to [1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0]
        print ''       # empty string forces new line, when above was 0

OTHER TIPS

I'd do something like:

#this will make it so the first die isn't always in the top left
from random import shuffle
shuffle(dice)

#create four rows of dice and store them in a list
from random import choice
rows = []
for i in range(4):
    #we want the next four dice in the list
    newRow = [choice(dice[i*4 + 0]),
              choice(dice[i*4 + 1]),
              choice(dice[i*4 + 2]),
              choice(dice[i*4 + 3])
             ]
    rows.append(newRow)

#display each row on its own line
for row in rows:
    print row
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top