Reputation: 101
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()
this is my code, just as an example.
the code pauses when it gets to the key = msvcrt.getch()*, or *key = ord(getch())
for that matter, right here i used the first one.
I'd like to have this code constantly print the key is
instead of just printing the key is when i give a new input (when i press a key).
so the printed output would look something like this:
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
which is needed if you want to make something like snake, where you don't want your game to be paused everytime you want to getch, you don't want it to pause, waiting for an input.
Upvotes: 2
Views: 3608
Reputation: 11
Another example to make Python program stop at a certain level, and wait for the user to press Enter "Yes" and/ or Space for "No" can be generated using pygame. As an example I used Space for "No", but you could use the touche Escape for "No". You might not need some imported librairies. Needed them while making tic toc toe game.
The code is below :
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
Upvotes: 0
Reputation: 369224
Use msvcrt.kbhit
to check whether key was pressed:
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)
Upvotes: 1