gpt4 book ai didi

python - 如何从选定列表中选择一个项目?

转载 作者:行者123 更新时间:2023-12-02 02:07:05 28 4
gpt4 key购买 nike

玩家输入字母 (a-z)。该程序从以输入字母开头的列表中随机生成一个单词,并显示绘制的单词。如何使输入的键成为列表的名称,可以从中随机选择以输入字符开头的单词?可能还有什么其他方法可以做到这一点?谢谢。

代码:随机导入

import pygame
# list of letters (a-z)
a = ["ananas", "arbuz", "agrest"]
b = ["banan", "balon", "beton"]
c = ["cytryna", "cebula", "candy"]
# ...
z = ["zebra", "zombie", "zonk"]

pygame.init()
screen = pygame.display.set_mode((0, 0))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

if event.type == pygame.KEYDOWN :
if event.key == pygame.K_ESCAPE:
running = False
else:
print(event.unicode)

pygame.quit()

最佳答案

我使用字典实现了以下功能,尽管这不是必需的。根据您想要对单词列表执行的操作,您可以使用或不使用字典来编写脚本。 (两者都应该很容易直接实现到您的 pygame 脚本中)

import keyboard
import random

a = ["ananas", "arbuz", "agrest"]
b = ["banan", "balon", "beton"]
c = ["cytryna", "cebula", "candy"]
# ...

words_dict = {}
words_dict['a'] = a
words_dict['b'] = b
words_dict['c'] = c
# ...

while True:
try:
if keyboard.is_pressed('a'):
print(random.choice(words_dict['a']))
break
elif keyboard.is_pressed('b'):
print(random.choice(words_dict['b']))
break
elif keyboard.is_pressed('c'):
print(random.choice(words_dict['c']))
break
# implement more elif here
except:
break

您也可以直接创建一个包含所有内容的字典,而不是像我上面那样为每个列表分配一个键到字典中:

words_dict = {
'a': ["ananas", "arbuz", "agrest"],
'b': ["banan", "balon", "beton"],
# and so on
}

不使用字典:

import keyboard
import random

a = ["ananas", "arbuz", "agrest"]
b = ["banan", "balon", "beton"]
c = ["cytryna", "cebula", "candy"]
# ...

while True:
try:
if keyboard.is_pressed('a'):
print(random.choice(a))
break
elif keyboard.is_pressed('b'):
print(random.choice(b))
break
elif keyboard.is_pressed('c'):
print(random.choice(c))
break
# implement more elif here
except:
break

================================================== =============

更新:以下脚本检测用户的按键点击并检索/显示正确的信息,而无需使用案例来检查用户输入的按键。

import random
import msvcrt

words_dict = {
'a': ["ananas", "arbuz", "agrest"],
'b': ["banan", "balon", "beton"],
'c': ["cytryna", "cebula", "candy"]
# ...
}

while True:
if msvcrt.kbhit():
key_pressed = msvcrt.getch()

try:
if words_dict.__contains__(key_pressed.decode('utf-8')):
print(random.choice(words_dict[key_pressed.decode('utf-8')]))
break
else:
print(f'Input "{key_pressed.decode("utf-8")}" is not recognized. Please try again!')
except:
break

请注意,变量 key_pressed 的类型为 bytes,在使用之前需要像上面一样进行解码。

关于python - 如何从选定列表中选择一个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68292407/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com