【问题标题】:Pygame- Check to see if word is typedPygame-检查是否输入了单词
【发布时间】:2015-10-24 08:13:19
【问题描述】:

我正在创建一个打字游戏,我希望有人输入显示的单词,事情就是这样。我不知道该怎么做。这些词来自一个 .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()

【问题讨论】:

    标签: python keyboard pygame key


    【解决方案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.)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-10
      • 2010-11-29
      • 2020-07-01
      相关资源
      最近更新 更多