我已經為“誰想成為百萬富翁”型別的游戲定義了幾個帶有問題、答案和類別(獎金金額)的變數。然后我有這個功能,它根據這些問題、答案和諸如此類的東西運行。我嘗試通過shuffle、choice、choices來使用python的隨機函式,但沒有成功。
uj5u.com熱心網友回復:
您放入串列的不是函式,而是已經呼叫該函式的結果——questionnaire在您有機會從中挑選元素之前,構建串列的行為本身會呼叫三次。
將每個問題放入一個物件中而不是擁有一組唯一的命名變數,這樣可以更容易地將隨機問題作為一個單元。您可以dict為此使用 a ;我通常使用NamedTuple.
from random import choice
from typing import List, NamedTuple, Tuple
class Question(NamedTuple):
question: str
answers: List[str]
correct: str
amount: int
cat: int
questions = [
Question(
"QUESTION: What is the biggest currency in Europe?",
["A) Crown", "B) Peso", "C) Dolar", "D) Euro"],
"D", 25, 1
),
Question(
"QUESTION: What is the biggest mountain in the world?",
["A) Everest", "B) Montblanc", "C) Popocatepepl", "D) K2"],
"A", 25, 2
),
Question(
"QUESTION: What is the capital of Brasil?",
["A) Rio de Janeiro", "B) Brasilia", "C) Sao Paolo", "D) Recife"],
"B", 25, 3
),
]
def questionnaire(q: Question) -> Tuple[int, bool]:
"""Presents the user with the given question.
Returns winnings and whether to continue the game."""
print(q.question)
for answer in q.answers:
print(answer)
usr_input_answer = input(
" What's your answer? "
"Please select between A, B, C, D or R for Retirement. "
).upper()
if usr_input_answer == q.correct:
return q.amount, True
elif usr_input_answer == "R":
print("Congratulations on retirement!")
else:
print("Game over!")
return 0, False
money = 0
keep_playing = True
while keep_playing:
winnings, keep_playing = questionnaire(choice(questions))
money = winnings
uj5u.com熱心網友回復:
首先:我建議您將所有問題創建并保存在字典中。
其次:在rnd.choice = 您嘗試通過撰寫函式來覆寫函式,該函式=用于為等式標記之前的事物賦予價值。試試看這里。
最后:該函式questionnaire()不回傳值,所以你不想像這樣使用它rnd.choice=([questionnaire(question1,answers1,correct1,amount1,cat1), ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347926.html
