Python - Word争夺游戏

时间:2015-03-17 22:49:52

标签: python python-3.x dictionary

虽然这项任务已经过期(我很遗憾地加入了课程)但我仍然需要弄清楚。我有以下单词列表:

憎恶:讨厌
偏执狂:偏见,偏见的人 假冒:假的;假
enfranchise:赋予投票权 阻碍:阻碍;阻碍
点燃:开火 有毒:有害的;有毒;致命
平静:平静;和平
报酬:已完成工作的报酬
护身符:幸运符 磨料:粗糙;粗;恶劣
诈骗:骗子;诈骗

我需要将此文件读入字典,选择随机密钥,对其进行加密,然后要求用户解决。与此处的其他解决方案不同,它不会迭代三次,而是一直运行直到用户输入' n'。如果用户想要继续游戏,代码将在每轮之后询问用户。用户还可以输入提示'得到这个词的定义 这里有一个类似的问题:(http://www.dreamincode.net/forums/topic/302146-python-school-project-write-a-word-scramble-game-status-complete/)或者更确切地说是一个问题的结果,但我不足以弥合差距并使其适用于我的目的。我在堆栈溢出时看到的这种变化都没有足够接近我,以弥合差距,可能是因为我还不够了解。在我们开始之前,这段代码还没有真正起作用,我现在很失落,所以请保持温和。到目前为止我的代码如下:

import random
from random import shuffle

#Reads the words.txt file into a dictionary with keys and definitions
myfile = open("words.txt", "r")
wordDict = dict([(line[:line.index(":")], line[line.index(":") +1 : -1]) 
    for line in myfile.readlines()])

#print (b)

def intro():
    print('Welcome to the scramble game\n')
    print('I will show you a scrambled word, and you will have to guess the word\n')
    print('If you need a hint, type "Hint"\n')

#Picks a random key from the dictionary b
def shuffle_word():
    wordKey = random.choice(list(wordDict.keys()))
    return wordKey

#Gives a hint to the user    
def giveHint(wordKey):
    hint = wordDict[wordKey]
    return hint

#Below - Retrieves answer from user, rejects it if the answer is not alpha    
def getAnswer():
    answer = input('\nEnter your first guess: ')
    while True:
            if answer.isalpha():
                return answer
            else:
                answer = input('\nPlease enter a letter: ')

def keepPlaying():
    iContinue = input("\nWould you like to continue? ")
    return iContinue    

def scramble():
    theList = list(shuffle_word())
    random.shuffle(theList)
    return(''.join(theList))


#Main Program

if keepPlaying() == 'y':
    intro()
    shuffle_word()
    randomW = shuffle_word()
    #scramKey = list(randomW)
    thisWord = scramble()
    print ("\nThe scrambled word is " +thisWord)
    solution = getAnswer()
    if solution == thisWord:
        print("\nCongratulations")
    if solution == 'Hint' or solution == 'hint':
        myHint = giveHint(wordKey)
        print(myHint)

else: 
    print("\nThanks for playing")

我已编辑此帖子以询问新信息,但我不确定这是否正确完成。感谢以下人士的帮助,我取得了进步,但我没有抓住具体的一块 我有两个问题。 1:如何让giveHint()函数返回shuffle_wprd()函数选择的随机密钥的定义。我知道上面的内容不起作用,因为它只是返回一个字符串,但似乎只是使用dict.get()函数无法获得所选随机字的正确定义。
2:如何让程序不要求用户继续第一次通过,然后从那时开始询问。我考虑过使用while循环并在迭代过程中重新定义变量,但我不太了解它以使其正常工作。
不管怎样,谢谢那些已经帮助过我的人。

2 个答案:

答案 0 :(得分:2)

这应该会帮助你一点,长度似乎没有任何好处,因为你可以看到加扰字的长度,所以我用定义作为提示,我想你也想问用户猜单词不是单个字母:

from random import shuffle, choice

#Reads the words.txt file into a dictionary with keys and definitions
with open("words.txt") as f:
    word_dict = {}
    for line in f:
        # split into two parts, word and description
        word, hint = line.split(":")
        word_dict[word] = hint


def intro():
    print('Welcome to the scramble game\n')
    print('I will show you a scrambled word, and you will have to guess the word\n')


#Picks a random key from the dictionary b
def pick_word():
    word = choice(list(word_dict.keys()))
    return word


#Gives a hint to the user
def give_hint(word):
    # return the definition of the word
    descrip = word_dict[word]
    return descrip


#Below - Retrieves answer from user, rejects it if the answer is not alpha
def get_answer():
    while True:
        answer = input('Please enter a guess: ')
        if answer.isalpha():
            return answer
        else:
            print("Only letters in the word")


def main():
    intro()
    word = pick_word()
    # give user lives/tries
    tries = 3
    shffled_word = list(word)
    # shuffle the word 
    shuffle(shffled_word)
    # rejoin shuffled word
    shffled_word = "".join(shffled_word)
    # keep going for three tries as most
    while tries > 0:
        inp = input("Your scrambled word is {}\nEnter h if you want to see your hint or any key to continue".format(shffled_word))
        if inp == "h":
            print("The word definition is {}".format(give_hint(word)))
        ans = get_answer()
        if ans == word:
            print("Congratulations you win!")
            break
        tries -= 1
    # ask user if they want to play again, restarting main if they do
    play_again = input("Press 'y'  to play again or any key to exit")
    if play_again == "y":
        main()
    # else the user did not press y so say goodbye
    print("Goodbye")
main()

还有一些要添加的内容,但我会将其留给您。

答案 1 :(得分:1)

感谢所有帮助过的人。对于任何后来出现的人来说,最终的产品就在这里。类似于Padraic Cunningham所提出的,但没有三个答案限制,并且没有他将主程序包装成一个被调用函数的更优雅的解决方案。

import random
from random import shuffle, choice

#Reads the words.txt file into a dictionary with keys and definitions
with open("words.txt") as f:
    wordDict = {}
    for line in f:
        # split into two parts, word and description
        word, hint = line.split(":")
        wordDict[word] = hint


#print (b)

def intro():
    print('Welcome to the scramble game\n')
    print('I will show you a scrambled word, and you will have to guess the word\n')
    print('If you need a hint, type "Hint"\n')

#Picks a random key from the dictionary b
def shuffle_word():
    wordKey = choice(list(wordDict.keys()))
    return wordKey

#Gives a hint to the user    
def giveHint(wordKey):
    descrip = wordDict[word]
    return descrip

#Below - Retrieves answer from user, rejects it if the answer is not alpha    
def getAnswer():
    answer = input('\nEnter a guess: ')
    while True:
            if answer.isalpha():
                return answer
            else:
                answer = input('\nPlease enter a letter: ')

def getAnswer2():
    answer2 = input('\nEnter another guess: ')
    while True:
            if answer2.isalpha():
                return answer2
            else:
                answer2 = input('\nPlease enter a letter: ')

def keepPlaying():
    iContinue = input("\nWould you like to continue? ")
    return iContinue    

#def scramble():
#    theList = list(shuffle_word())
#    random.shuffle(theList)
#    return(''.join(theList))


#Main Program

while keepPlaying() == 'y':
    intro()
    #shuffle_word()
    randomW = shuffle_word()
    cheatCode = giveHint(randomW)
    #scramKey = list(randomW)
    thisWord = list(randomW)
    print(thisWord)
    random.shuffle(thisWord)
    print(thisWord)
    thisRWord = ''.join(thisWord)
    print ("\nThe scrambled word is " +thisRWord)
    solution = getAnswer()
    loopMe = False
    while loopMe == False:
        if solution == randomW:
            print("\nCongratulations")
            loopMe = True
        if solution == 'Hint' or solution == 'hint':
            print(cheatCode)
        if solution != randomW:
            loopMe = False
            solution = getAnswer2()