我正在创建一个打字游戏,我希望有人输入显示的单词,事情是。我不知道怎么做。单词来自.txt文件,每个单词都在它自己的行上。随机数生成器生成一个数字,并枚举文本文件,并将相应插槽中的单词转换为随机数。然后该字显示在屏幕上。希望这是有道理的。有办法吗?如果这还不够,将会给出更多代码。以下是使用的代码:
def text_objects(text, color, size):
if size == "small":
textSurf = smallFont.render(text, True, color)
elif size == "medium":
textSurf = medFont.render(text, True, color)
elif size == "large":
textSurf = largeFont.render(text, True, color)
elif size == "verySmall":
textSurf = vSmallFont.render(text, True, color)
return textSurf, textSurf.get_rect()
def messageToScreen(msg, color, y_displace = 0, size = "small"):
textSurface, textRect = text_objects(msg, color, size)
textRect.center = (display_width/2), (display_height/2) + y_displace
gameDisplay.blit(textSurface, textRect)
def randWord():
rand = random.randint(0,996)
fp = open("1.txt")
for i, line in enumerate(fp):
if i == rand:
line = line.strip()
messageToScreen(line,black,-200,size = "large")
for char in line:
global chars
chars = []
chars.append(char)
print(str(chars))
fp.close()
答案 0 :(得分:1)
您需要在主事件循环中处理关键事件,如下所示:
triggerNewWord = False
currentWord = "opitit"
uString = u"" # Unicode string
# This is the main loop
while True:
# 1. Process events and update current state (ie: uString)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
sys.exit()
else:
uString += event.unicode
if triggerNewWord:
triggerNewWord = False # Some event could change it to True again if you need a new word
currentWord = randWord() # This should choose a new work but not draw it
# Here you are updating the state, not drawing anything
# 2. Paint current state
gameDisplay.fill((160, 160, 160)) # First clean the screen
# Draw every element
# The Current word
messageToScreen(currentWord, black, -100, size = "large")
# What the user it's typing
messageToScreen(uString, black, 100, size = "large")
# 3. Update display
pygame.display.flip()
可能你想添加一些控制选项,比如退格键,你可以在事件循环中添加更多ifs
(1。)