【问题标题】:msvcrt getch pauses script, has to continuemsvcrt getch 暂停脚本,必须继续
【发布时间】:2013-11-21 16:41:12
【问题描述】:

PYTHON 3.3,msvcrt

import sys, msvcrt
print("Please press a key to see its value")
while 1:
    key = msvcrt.getch()
    print("the key is")
    print(key)
    if ord(key) == 27: # key nr 27 is escape
        sys.exit()

这是我的代码,仅作为示例。 当代码到达key = msvcrt.getch()*, or *key = ord(getch()) 时,代码会暂停,在这里我使用了第一个。 我想让这段代码不断打印关键是 当我给出一个新的输入时(当我按下一个键时),而不是仅仅打印 key is

所以打印的输出看起来像这样:

the key is
the key is
the key is
the key is
the key is
the key is
77
the key is
the key is
the key is

如果你想制作类似 snake 的东西,你不希望每次想要 getch 时都暂停你的游戏,这是需要的,你不希望它暂停,等待输入。

【问题讨论】:

    标签: python msvcrt


    【解决方案1】:

    使用msvcrt.kbhit检查按键是否被按下:

    import sys, msvcrt
    import time
    
    print("Please press a key to see its value")
    while 1:
        print("the key is")
        if msvcrt.kbhit(): # <--------
            key = msvcrt.getch()
            print(key)
            if ord(key) == 27:
                sys.exit()
        time.sleep(0.1)
    

    【讨论】:

    • 先生,您太棒了,非常感谢您:D
    【解决方案2】:

    另一个例子可以让 Python 程序在某个级别停止,并等待用户按 Enter “Yes”和/或 Space for “No” 可以使用 pygame 生成。 例如,我使用 Space 表示“No”,但您可以使用 touche Escape 表示“No”。 您可能不需要一些导入的库。在制作井字游戏时需要它们。

    代码如下:

    import numpy as np
    import pygame as pg
    from math import floor
    import sys
    import time
    pg.init()
    
    black = (0, 0, 0)
    red = (255, 0, 0)
    blue = (0, 0, 255)
    yellow = (255, 255, 0)
    white = (255, 255, 255)
    gris = (192, 192, 192)
    cell = 100
    thickness =2
    
    window = pg.display.set_mode((300, 300))
    pg.display.set_caption("by @djilytech")
    for col in range(3):
        for row in range(3):
            pg.draw.rect(window, gris, (row * cell, col * cell, cell - 2, cell - 2), thickness)
            pg.time.delay(120)
            pg.display.update()
    
    run = False
    while not run:
        for ev in pg.event.get():
            if ev.type == pg.QUIT:
                pg.quit()
                sys.exit()
            if ev.type == pg.KEYDOWN:
                if ev.key == pg.K_RETURN:
                    print(" This mean the user wants to play again or said YES")
                    # So I can have some code here for what I want
    
                if ev.key == pg.K_SPACE:
                    print("User does not want to continue")
                    # Will exit the program
    
                run = True
    

    【讨论】:

      猜你喜欢
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      相关资源
      最近更新 更多