2015-10-07 2 views
-1

У меня возникли проблемы со словной игрой, которую я пытаюсь сделать, царапать.Scrabble wordgame error in python

Часть моего кода, где он в конечном итоге дает ошибку, является:

def is_valid_word(word, hand, word_list): 
""" 
Returns True if word is in the word_list and is entirely 
composed of letters in the hand. Otherwise, returns False. 
Does not mutate hand or word_list. 

word: string 
hand: dictionary (string -> int) 
word_list: list of lowercase strings 
""" 
hand_copy = hand.copy() 
if word not in wordList: 
    return False 
for char in word: 
    if char not in hand_copy: 
     return False 
    else: 
     hand_copy[char] -= 1 
    if hand_copy[char] < 0: 
     return False 
return True 


def play_hand(hand, words): 
""" 
Allows the user to play the given hand, as follows: 

* The hand is displayed. 
* The user may input a word. 
* An invalid word is rejected, and a message is displayed asking 
    the user to choose another word. 
* When a valid word is entered, it uses up letters from the hand. 
* After every valid word: the score for that word is displayed, 
    the remaining letters in the hand are displayed, and the user 
    is asked to input another word. 
* The sum of the word scores is displayed when the hand finishes. 
* The hand finishes when there are no more unused letters. 
    The user can also finish playing the hand by inputing a single 
    period (the string '.') instead of a word. 

hand: dictionary (string -> int) 
words: list of lowercase strings 
""" 
n = HAND_SIZE 
display_hand(hand) 
print "You may enter '.' if you cannot create a word." 
word = raw_input("Please enter a word:") 
score = 0 
totalscore = 0 
while not len(hand) == 0 and not word == ".": 
    print word 
    if is_valid_word(word, hand, load_words()) == False: 
     print "That is not a valid word" 
     word = raw_input("Please enter a word:") 
    elif is_valid_word(word, hand, load_words()) == True: 
     score = get_word_score(word, n) 
     print "You word was worth " + str(score) + " points." 
     totalscore = totalscore + score 
     print "Your total score is: " + str(totalscore) + "." 
     print "Here is your updated hand." 
     hand = update_hand(hand,word) 
     display_hand(hand) 
     if len(hand) != 0: 
      word = raw_input("Please enter a word:") 
print "Your total score is: " + str(totalscore) + "." 
return 

def play_game(words): 
""" 
Allow the user to play an arbitrary number of hands. 

* Asks the user to input 'n' or 'r' or 'e'. 
* If the user inputs 'n', let the user play a new (random) hand. 
    When done playing the hand, ask the 'n' or 'e' question again. 
* If the user inputs 'r', let the user play the last hand again. 
* If the user inputs 'e', exit the game. 
* If the user inputs anything else, ask them again. 
""" 
hand = deal_hand(HAND_SIZE) 
while True: 
    cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ') 
    if cmd == 'n': 
     hand = deal_hand(HAND_SIZE) 
     play_hand(hand, words) 
     print 
    elif cmd == 'r': 
     play_hand(hand, words) 
     print 
    elif cmd == 'e': 
     break 
    else: 
     print "Invalid command." 

В моем opninion это должно работать. Я могу начать игру, разыграть новую руку, переиграть последнюю руку или закончить игру. Но когда я пытаюсь сделать слово из заданных букв дает эту ошибку:

Traceback (most recent call last): 
File "wordgames.py", line 257, in <module> 
    play_game(words) 
File "wordgames.py", line 241, in play_game 
    play_hand(hand, words) 
File "wordgames.py", line 204, in play_hand 
if is_valid_word(word, hand, load_words()) == False: 
File "wordgames.py", line 163, in is_valid_word 
    if word not in wordList: 
NameError: global name 'wordlist' is not defined 

Я пытался много, но ничего не помогает ... Пожалуйста, кто-нибудь может помочь мне исправить эту проблему?

Заранее благодарен!

+4

Ваш отслеживающий не соответствует ... себе! 'если слово не в wordList:' будет ** не **, потому что ошибка 'name 'wordlist' не определена'. Отступ также нарушен в коде, который вы опубликовали. Пожалуйста, предоставьте [mcve]. – jonrsharpe

+0

Вы не должны удалить оригинальный вопрос! Одним из основных пунктов stackoverflow является то, что * другие люди * также извлекают выгоду из ответов ... – jmetz

+0

О, извините, я буду помнить об этом в будущем :). –

ответ

2

Ошибка четко указано в нижней части TRACEBACK:

File "wordgames.py", line 163, in is_valid_word 
    if word not in wordList: 
NameError: global name 'wordlist' is not defined 

т.е. вы не определяете wordList - входная переменная называется word_list.

Также вы должны исправить отступы в своем вопросе, чтобы дать понять, где заканчивается определение функции, и вы вернетесь в глобальную область.

Как jonsharpe указывает, ваш отслеживающий также противоречивы (wordlist вместо wordList)

+0

Спасибо! Я отредактировал его, ошибка исчезла. Но теперь, когда каждое слово я вхожу, оно говорит, что это неправдоподобное слово .... –

+0

@ Mr.X - если это ответило на ваш первоначальный вопрос, вы должны принять ответ и задать новый вопрос, если он у вас есть. – jmetz