Я в процессе создания своей первой игры и хочу, чтобы пользователь вводил информацию, например, свое имя. Я потратил последние 3,5 часа на запись функции, ниже которой я намерен использовать (слегка измененный с помощью мигающего значка подчеркивания, чтобы назвать его) в моих играх, продвигающихся вперед.Пользовательский ввод клавиатуры в pygame, как получить вход CAPS
Поскольку мой код в настоящее время написан, я не могу получить вход CAPS от пользователя, хотя я разрешил использовать такие символы. Как я могу это сделать?
Любые другие предложения также приветствуются.
Код:
import pygame
from pygame.locals import *
import sys
def enter_text(max_length, lower = False, upper = False, title = False):
"""
returns user name input of max length "max length and with optional
string operation performed
"""
BLUE = (0,0,255)
pressed = ""
finished = False
# create list of allowed characters by converting ascii values
# numbers 1-9, letters a-z(lower/upper)
allowed_chars = [chr(i) for i in range(97, 123)] +\
[chr(i) for i in range(48,58)] +\
[chr(i) for i in range(65,90)]
while not finished:
screen.fill((0,0,0))
pygame.draw.rect(screen, BLUE, (125,175,150,50))
print_text(font, 125, 150, "Enter Name:")
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# if input is in list of allowed characters, add to variable
elif event.type == KEYUP and pygame.key.name(event.key) in \
allowed_chars and len(pressed) < max_length:
pressed += pygame.key.name(event.key)
# otherwise, only the following are valid inputs
elif event.type == KEYUP:
if event.key == K_BACKSPACE:
pressed = pressed[:-1]
elif event.key == K_SPACE:
pressed += " "
elif event.key == K_RETURN:
finished = True
print_text(font, 130, 180, pressed)
pygame.display.update()
# perform any selected string operations
if lower: pressed = pressed.lower()
if upper: pressed = pressed.upper()
if title: pressed = pressed.title()
return pressed
def print_text(font, x, y, text, color = (255,255,255)):
"""Draws a text image to display surface"""
text_image = font.render(text, True, color)
screen.blit(text_image, (x,y))
pygame.init()
screen = pygame.display.set_mode((400,400))
font = pygame.font.SysFont(None, 25)
fpsclock = pygame.time.Clock()
fps = 30
BLUE = (0,0,255)
# name entered?
name = False
while True:
fpsclock.tick(fps)
pressed = None
for event in pygame.event.get():
if event.type == KEYUP:
print(pygame.key.name(event.key))
print(ord(pygame.key.name(event.key)))
if event.type == QUIT:
pygame.quit()
sys.exit()
# key polling
keys = pygame.key.get_pressed()
screen.fill((0,0,0))
if not name:
name = enter_text(4, title = True)
print_text(font, 130, 180, name)
pygame.display.update()
просто удалить 'в allowed_chars' состоянии, и на KeyUp печать' event.key', запустите вашу программу получить один для шапок-замка, а затем вы можете добавить его в свой файл 'allowed_chars' –
уже сделано , http://stackoverflow.com/questions/23475858/how-to-allow-caps-in-this-input-box-program-for-pygame –
А, спасибо. Я нашел оригинальное сообщение, которое цитировал парень, но не тот. –