如何将删除的单词放入变量?

时间:2015-03-09 15:16:10

标签: python

所以我一直在制作一个显示3x3网格的记忆游戏,并在30秒后删除。之后,显示另一个3x3网格,但第一个网格中的一个单词已被另一个单词替换。用户必须猜测已替换的原始单词。但是我不确定如何编码。 这是我的代码:

import random # imports the random module, to generate the words
import time  # imports the time module, used for the countdown
try:
    with open ('patrick star.txt') as f: # opens the text file
    words = random.sample([x.rstrip() for x in f], 9)
    grid = [words[i:i + 3] for i in range(0, len(words), 3)] # puts the words into a 3x3 grid
    for x,y,z in grid:
        print (x,y,z) # prints the 3x3 grid
except IOError:
    print("The code does not seem to be working")
time.sleep(30) # displays it for 30 seconds
import os
os.system('cls') # this function clears the screen after countdown

print("Time's up!")


try:
    with open ('patrick star.txt') as f: # opens the text file
    words = random.sample([x.rstrip() for x in f], 9)
    grid = [words[i:i + 3] for i in range(0, len(words), 3)] # puts the words into a 3x3 grid
    for x,y,z in grid:
        print (x,y,z) # prints the 3x3 grid

2 个答案:

答案 0 :(得分:0)

试试这个。您必须更改从文件中读取文字的部分,并清除' /' cls'

import random
import time, os
from string import ascii_letters

os.system('clear')
# make twenty random words
random_words = [''.join(random.sample(ascii_letters, 5)) for i in range(20)]

# select 9 from the random words and make grid
words = random.sample(random_words, 9)
grid = [words[i:i+3] for i in range(0, len(words), 3)]

for x,y,z in grid:
    print x, y, z

time.sleep(5)
os.system('clear')

ri = random.randint(0, 8)  # random index

# save the old word
old_word = grid[ri // 3][ri % 3]

# replace with new random word
grid[ri // 3][ri % 3] = random.sample(random_words, 1)[0]

# print again
for x, y, z in grid:
    print x, y, z

g = raw_input(">> Enter old word that changed:\n")
if g == old_word:
    print "You won!"
else:
    print "No!"

答案 1 :(得分:0)

我首先会在类似于此的骨架中稍微重写一下:

import random

class Board(object):
    board = [[[""],[""],[""]],[[""],[""],[""]],[[""],[""],[""]]]
    hide = ()
    guess = ()

    _size = 0
    _words = []

    def __init__(self, words, size = 3):
        self._size = size
        self._words = words

    def populateBoard(self):
        sample = random.sample(self._words,self._size**2)
        i = 0
        for x in range(self._size):
            for y in range(self._size):
                self.board[x][y] = sample[i]
                i += 1

    def guessWord(self,x,y,word):
        return board[x][y] == word

    def hideWord(self):
        pass

    def displayBoard(self):
        pass

    def awaitAnswer(self):
        pass


with open ('patrick star.txt') as f:
    words = f.readlines()

b = Board(words)