首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >msvcrt getch暂停脚本,必须继续

msvcrt getch暂停脚本,必须继续
EN

Stack Overflow用户
提问于 2013-11-21 16:41:12
回答 2查看 3.2K关注 0票数 1

Python3.3,msvcrt

代码语言:javascript
复制
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())时,代码就会暂停,就在这里,我使用了第一个。我想让这段代码不断地打印,键不是仅仅打印,而是当我给出一个新的输入时(当我按下一个键)。

所以打印的输出应该是这样的:

代码语言:javascript
复制
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

这是必要的,如果你想做一些像蛇,你不想让你的游戏暂停,每次你想要的时候,你不想让它暂停,等待输入。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-21 16:44:32

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

代码语言:javascript
复制
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)
票数 1
EN

Stack Overflow用户

发布于 2020-04-28 04:53:44

另一个使Python程序停止在一定级别,并等待用户按Enter "Yes“和/或Space表示"No”的示例可以使用pygame生成。例如,我在"No“中使用了Space,但您可以使用touche Escape来表示"No”。你可能不需要进口的librairies。在做抽搐脚趾游戏时需要他们。

守则如下:

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20126833

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档