python中的4x4网格?

时间:2015-03-19 12:06:31

标签: python grid

我一直在制作一款需要显示3x3网格和4x4网格的游戏。 这是我用于3x3网格的代码,它起作用:

try:
    with open('Words.txt', "r") as f:#opens the text file
        words = f.read().split()
        random.shuffle(words)#shuffles the words in the grid
        replacement = words[0]
        removed = words[1]
        words.remove(replacement)

grid = [words[i:i + 3] for i in range(0, len(words), 3)]
for x,y,z in grid:
    print(x,y,z)#displays grid

但是,我不知道如何为4x4网格做到这一点。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

我想在你的文件中:len(words)%4!= 0

试试这个:

import random

with open('Words.txt', "r") as f:#opens the text file
    words = f.read().split()
    random.shuffle(words)#shuffles the words in the grid
    replacement = words[0]
    removed = words[1]
    words.remove(replacement)

grid = [words[i:i + 4] for i in range(0, len(words), 4)]
r = len(words)%4

if r==0:
    for x,y,z,k in grid:
        print(x,y,z,k) #displays grid
else:
    grid = grid[: -1]
    for x,y,z,k in grid:
        print(x,y,z,k) #displays grid