Python 提问游戏

0 投票
2 回答
697 浏览
提问于 2025-04-18 00:45

我正在制作一个问答游戏(类似于20个问题),但我希望我的程序每个问题只问一次。我尝试过使用enumerate给每个问题字符串一个值,然后用一个if语句来判断,如果i等于i,那么i不等于1,希望这样能把i的值改成其他的,这样就不会重复提问了,但这并没有成功。如果能得到一些帮助就太好了,这是我第一次编写问答游戏,我对它充满期待,只要能把它做到稳定就行。

import sys, random
keepGoing = True
ques = ['What does it eat?', 
        'How big is it?', 
        'What color is it?', 
        'How many letters are in it?',
        'Does it have scales?',
        'Does it swim?',
        'How many legs does it have?'
        ]

ask = raw_input("Want to play a game?")
while keepGoing:
    if ask == "yes":
        nextQ = raw_input(random.choice(ques))
    else:
        keepGoing = False

2 个回答

3

像这样做:

for question in random.shuffle(ques):
    #your code here, for each question

顺便说一下,如果你的代码保持不变,就像你写的那样,它会产生一个无限循环。试着重新组织一下代码。

2

我建议你在问题列表上使用 random.sample;这样可以得到你想要的随机问题数量,而且不会重复。

下面是一些整理过的代码:

# assumes Python 2.x
from random import sample
from time import sleep

NUM_QUESTIONS = 4

questions = [
    'What does it eat?', 
    'How big is it?', 
    'What color is it?', 
    'How many letters are in it?',
    'Does it have scales?',
    'Does it swim?',
    'How many legs does it have?'
    # etc
]

def get_yn(prompt):
    while True:
        val = raw_input(prompt).strip().lower()
        if val in {'y', 'yes'}:
            return True
        elif val in {'n', 'no'}:
            return False

def play():
    for q in random.sample(questions, NUM_QUESTIONS):
        print(q)
        sleep(2.)

def main():
    while True:
        play()
        if not get_yn("Play again? "):
            break

if __name__=="__main__":
    main()

撰写回答