Boggle游戏 - 在4x4网格中放置16个数组中随机选择的字母(Python)

时间:2014-01-20 17:25:51

标签: python arrays for-loop random boggle

因此,对于一个学校项目,我们被要求在Python上编写一个boggle游戏(我使用的是2.7.3),我陷入了两难境地。我试图从16个假设的“立方体”数组中随机选择的字母以4x4格式出现(这样就有一个有16个随机字母的正方形)。

代码可以在这里看到:

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

正如您所看到的,我使用for循环从DICE数组中的每一行中选择随机字母,现在我希望显示这16个随机选择的字母以创建4x4网格。

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

提前致谢!

2 个答案:

答案 0 :(得分:2)

我会做类似的事情:

#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

答案 1 :(得分:1)

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