Python - 从main()函数调用函数返回零

时间:2014-06-06 03:33:29

标签: python python-2.7

我正在编写一个模拟辐射3中发现的黑客迷你游戏的程序。用户应该选择一个难度级别,并根据程序将返回一个字符串列表,然后用户有4次尝试正确猜出程序随机选择了哪个单词。

我面临的问题是,当我调用我编写的各种函数来处理游戏的不同方面时,不会返回任何值。如果我单独调用每个函数并传递它所需的参数我得到正确的输出,但由于某种原因,当我从main()函数调用它时它将不起作用。这是我的代码:

import operator
import random


def difficulty_level(difficulty_choice):
    num_choices = 0
    word_length = 0
    if difficulty_choice == 1:
        num_choices = 5
        word_length = 5
    elif difficulty_choice == 2:
        num_choices = 8
        word_length = 9
    elif difficulty_choice == 3:
        num_choices = 10
        word_length = 13
    elif difficulty_choice == 4:
        num_choices = 12
        word_length = 17
    elif difficulty_choice == 5:
        num_choices = 15
        word_length = 21
    return num_choices, word_length


def generate_word_list(num_choices, word_length):
    matching_words = []
    word_choice_list = []
    word_source = open("enable1.txt", 'r')
    for word in word_source:
        if len(word) == word_length + 1:
            matching_words.append(word.rstrip())
    for i in range(num_choices):
        word_choice_list.append(random.choice(matching_words))
    return word_choice_list


def user_guesses(word_choice_list):
    guesses = 4
    game_over = False

    for word in word_choice_list:
        print word.upper()

    selected_word = random.choice(word_choice_list)
    selected_word_length = len(selected_word)

    while not game_over:
        guess_word = (raw_input("Guess (%s left)? " % guesses)).lower()
        if guess_word == selected_word:
            game_over = True
            print("You win!")
        else:
            num_correct_letters = map(operator.eq, guess_word, selected_word).count(True)
            guesses -= 1
            print("%s/%s correct" % (num_correct_letters, selected_word_length))


def main():
    game_level = raw_input("Difficulty (1-5)? ")
    main_num_choices, main_word_length = difficulty_level(game_level)
    word_list = generate_word_list(main_num_choices, main_word_length)
    user_guesses(word_list)

main()

我不知道为什么它不起作用。我在PyCharm中写这个并使用2.7.6作为编译器。感谢。

1 个答案:

答案 0 :(得分:2)

这对我来说很好。我想也许你的问题是你希望game_level成为int,但它实际上是str。这使得difficulty_level返回错误的东西(它总是返回(0, 0)),并抛出整个程序。你可以很容易地解决这个问题:

game_level = int(raw_input("Difficulty (1-5)? "))

此外,打开后,您没有关闭“enable1.txt”。我建议像这样打开它,以便它自动关闭:

with open("enable1.txt", 'r') as word_source:
    for word in word_source:
        if len(word) == word_length + 1:
            matching_words.append(word.rstrip())