简体   繁体   English

Python 3:如何使用用户输入并从词典列表中检索答案来制作游戏,然后使用积分系统?

[英]Python 3: How do I make a game using user input and retrieving answer from a list of dictionaries, then use a point system?

I'm trying to make a game where the user is asked to guess a country based on it's capital which is selected at random from a list of dictionaries (similar to the link at bottom). 我正在尝试制作一个游戏,要求用户根据其首都来猜测一个国家,该国家是从词典列表中随机选择的(类似于底部的链接)。

Guessing 10 countries in total, if they guess correctly they get 1 point, with 10 points in total. 总共猜测10个国家/地区,如果他们猜对了,则得到1分,共10分。

I've imported a variable 'countries' that contains a list of dictionaries like the following: 我导入了一个变量“国家”,其中包含字典列表,如下所示:

[{'capital': 'Andorra la Vella',
  'code': 'AD',
  'continent': 'Europe',
  'name': 'Andorra',
  'timezones': ['Europe/Andorra']},
 {'capital': 'Kabul',
  'code': 'AF',
  'continent': 'Asia',
  'name': 'Afghanistan',
  'timezones': ['Asia/Kabul']},

So how do I print a random choice from a specific key name? 那么,如何从特定的键名中打印随机选择呢? In this case, any 'capital' from any of the dictionaries. 在这种情况下,来自任何词典的任何“资本”。

Python-Dictionary states and capital game Python-字典状态和资本博弈

You can use below two options. 您可以使用以下两个选项。

  1. random.choice to select a random element from a the list. random.choice从列表中选择一个随机元素。

Sample code. 样例代码。

from random import choice
country_dict = [{'capital': 'Andorra la Vella',     'code': 'AD',  continent': 'Europe',      'name': 'Andorra',      'timezones': 'Europe/Andorra']},
                {'capital': 'Kabul',      'code': 'AF',      'continent': 'Asia',      ame': 'Afghanistan',      'timezones': ['Asia/Kabul']}
               ]
country = choice(country_dict)
capital = input("Please enter the captial for country "+country['name'])
if capital == country['capital']:
    print("Correct answer")
  1. random.ranint to select random integer between 0 and length of list. random.ranint选择0到列表长度之间的随机整数。

Sample code: 样例代码:

from random import randint
country_dict = [{'capital': 'Andorra la Vella',      'code': 'AD',      'continent': 'Europe',      'name': 'Andorra',      'timezones': ['Europe/Andorra']},
                {'capital': 'Kabul',      'code': 'AF',      'continent': 'Asia',      'name': 'Afghanistan',      'timezones': ['Asia/Kabul']}
               ]
ind = randint(0,len(country_dict)-1)
capital = input("Please enter the captial for country "+country_dict[ind]['name'])
if capital == country_dict[ind]['capital']:
    print("Correct answer")

You can fetch a random sample with randomCountry = random.choice(countries) 您可以使用randomCountry = random.choice(countries)获取随机样本

However, if you do this multiple times, you may get the same country multiple times. 但是,如果您多次执行此操作,则可能会多次访问同一国家。 To combat this, you could sample 10 distinct elements with randomCountries = random.sample(countries, 10) and then iterate with those. 为了解决这个问题,您可以使用randomCountries = random.sample(countries, 10) 10个不同的元素进行randomCountries = random.sample(countries, 10) ,然后对其进行迭代。

Note that random.sample throws an error if you attempt to sample more elements than there exists in the collection. 请注意,如果您尝试采样的元素数量超过集合中的元素数量, random.sample会引发错误。

Your game could thus look like this: 因此,您的游戏可能如下所示:

import random

countries = [
    {'capital': 'Andorra la Vella', 'code': 'AD', 'continent': 'Europe', 'name': 'Andorra', 'timezones': ['Europe/Andorra']}, 
    {'capital': 'Kabul', 'code': 'AF', 'continent': 'Asia', 'name': 'Afghanistan', 'timezones': ['Asia/Kabul']},
    ...
]

rounds = 10
random_countries = random.sample(countries, rounds) # returns 10 random elements (no duplicates)

score = 0
for country in random_countries:
    print("Score: %d / %d | Which country has the capital: %s?" % (score, rounds, country['capital']))
    country_response = input()
    if country_response == country['name']:
        score += 1
        print("Correct")
    else:
        print("Incorrect")

random.choice is very good for this use case :) random.choice对于这个用例非常有用:)

import random


country_dlist = [{'capital': 'Andorra la Vella',
  'code': 'AD',
  'continent': 'Europe',
  'name': 'Andorra',
  'timezones': ['Europe/Andorra']},
 {'capital': 'Kabul',
  'code': 'AF',
  'continent': 'Asia',
  'name': 'Afghanistan',
  'timezones': ['Asia/Kabul']}
 ]

def run():
    tot_points = 0
    num_of_ques = len(country_dlist)
    for i in range(num_of_ques):
        choice = random.choice(country_dlist)
        que = country_dlist.remove(choice)
        capital = raw_input("Please enter the captial for country {}: ".format(choice['name']))
        if capital.lower() == choice['capital'].lower(): # case insensitive match :)
            tot_points += 1
    return tot_points

points = run()
print("You scored {} points".format(points))

like this? 像这样?

import random
place_list = [{'capital': 'Andorra la Vella', 'code': 'AD', 'continent': 'Europe', 'name': 'Andorra', 'timezones': ['Europe/Andorra']}, {'capital': 'Kabul', 'code': 'AF', 'continent': 'Asia', 'name': 'Afghanistan', 'timezones': ['Asia/Kabul']}]
quiz_length = 10
points = 0
for q in random.sample(place_list, quiz_length):
    guess = input(f'this place has {q['capital']} in it')
    if guess == q['name']:
        points += 1
print(f'you got {points}/{quiz_length}')

edit: the rest of the code... 编辑:其余代码...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从列表中随机生成 python select 某些内容,如果在输入提示中键入,它将按预期显示确切答案 - How do I make python randomly select something from a list and if typed in the input prompt, it will show the exact answer as intended 使用来自用户的输入从嵌套字典中检索字典列表 - Retrieving a list of Dictionaries from Nested Dictionary with an Input from User 如何使用 append 将答案添加到数组以从输入中注册,以便我可以使用输入中的答案登录? - How do I use append to add the answer to an array for registration from input so I can log in using the answer from the input? 如何让我的 Discord Bot 对列表中的不同单词回复相同的答案? Python - How do I make my Discord Bot reply a same answer to different words from a list? Python 如果回答:BLAH导入脚本,如何创建一个像answer = raw_input()的python脚本 - How do I make a python script like answer = raw_input() if answer: BLAH import script 如何从用户输入更新字典列表? - How to update a list of dictionaries from a user input? 如何根据用户的输入创建列表? 带Python - How do I create a list from the input of a user? w/Python 如何使用列表中的用户输入 - How do i use User input in a list 如果没有使用pygame的python 2.7用户输入,我无法使对象从A点移动到B点 - I am unable to make an object move from point A to point B without user input using python 2.7 with pygame 如何在词典列表中检查用户名和关联的密码以与用户输入进行比较 - how do I check for a user name and associated password in a list of dictionaries to compare to user input
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM