[英]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.
在这种情况下,来自任何词典的任何“资本”。
You can use below two options. 您可以使用以下两个选项。
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")
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.