понедельник, 3 сентября 2018 г.

Майкл Доусон - Программируем на Python, ответ на 1-ое задание 7-ой главы...

Доработайте игру "Викторина" таким образом, чтобы у каждого вопроса появился свой "номинал" - уникальное количество очков. В конце игры сумма очков пользователя должна стать равной сумме номиналов вопросов, на которые он ответил верно.

В начале я очень запутался.
Меня очень долго вводила в смущение фраза "В конце игры сумма очков пользователя должна стать равной сумме номиналов вопросов, на которые он ответил верно." Тогда просто ставим счетчик после значения score, который так же будет считать + 1 каждый раз, когда ответили верно. Будет выполняться одно условие, но тогда не будет уникальности номиналов.
Если же номинал будет разный, то мы не сможем сделать равное кол-во с очками.
В общем пришлось поломать голову.
Достал оригинал, там написано: "the players score should be the total of all the points values of the questions he or she answers correctly", то есть "очки игроков должны быть суммой очков, на которые он правильно ответил".
Интересно, я условие первоначальное один так интерпретировал, или здесь перевод на самом деле неккоректный?

По поводу номиналов. Можете убрать очки, чтобы не путаться, а можете просто добавить номиналы  в первоначальное тело программы.
Я сделал так, что после каждого ответа рандомилось число от 1 до 4 - это и будет номинал, добавляемый в общую копилку.
import sys, random

def open_file(file_name, mode):
    """Open a file."""
    try:
        the_file = open(file_name, mode)
    except IOError as e:
        print("Unable to open the file", file_name, "Ending program.\n", e)
        input("\n\nPress the enter key to exit.")
        sys.exit()
    else:
        return the_file

def next_line(the_file):
    """Return next line from the trivia file, formatted."""
    line = the_file.readline()
    line = line.replace("/", "\n")
    return line

def next_block(the_file):
    """Return the next block of data from the trivia file."""
    category = next_line(the_file)

    question = next_line(the_file)

    answers = []
    for i in range(4):
        answers.append(next_line(the_file))

    correct = next_line(the_file)
    if correct:
        correct = correct[0]

    explanation = next_line(the_file)
    return category, question, answers, correct, explanation

def welcome(title):
    """Welcome the player and get his/her name."""
    print("\t\tWelcome to Trivia Challenge!\n")
    print("\t\t", title, "\n")

def main():
    trivia_file = open_file("trivia.txt", "r")
    title = next_line(trivia_file)
    welcome(title)
    score = 0
    nominal = 0

    # get first block
    category, question, answers, correct, explanation = next_block(trivia_file)
    while category:
        # ask a question
        print(category)
        print(question)
        for i in range(4):
            print("\t", i + 1, "-", answers[i])

        # get answer
        answer = input("What's your answer?: ")

        # check answer
        if answer == correct:
            print("\nRight!", end=" ")
            score += 1
            random_nominal = random.randint(0, 4)
            nominal += random_nominal
        else:
            print("\nWrong.", end=" ")
        print(explanation)
        print("Score:", score, "\n")
        print("Nominal that question: ", random_nominal)
        print("Nominal:", nominal, "\n\n")

        # get next block
        category, question, answers, correct, explanation = next_block(trivia_file)

    trivia_file.close()

    print("That was the last question!")
    print("You're final score is", score)
    print("You're final nominal is", nominal)

main()
input("\n\nPress the enter key to exit.")

Комментариев нет:

Отправить комментарий