2016-09-20 2 views
0

Я в процессе создания своей первой игры и хочу, чтобы пользователь вводил информацию, например, свое имя. Я потратил последние 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() 
+0

просто удалить 'в allowed_chars' состоянии, и на KeyUp печать' event.key', запустите вашу программу получить один для шапок-замка, а затем вы можете добавить его в свой файл 'allowed_chars' –

+0

уже сделано , http://stackoverflow.com/questions/23475858/how-to-allow-caps-in-this-input-box-program-for-pygame –

+0

А, спасибо. Я нашел оригинальное сообщение, которое цитировал парень, но не тот. –

ответ

0

Ниже переработанный код с верхним входом корпуса обслужены. Я также добавил мигающий знак подчеркивания. Не уверен, что это самый эффективный способ сделать это, но это так. Мне было весело это делать.

import pygame 
from pygame.locals import * 
import sys 
from itertools import cycle 

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 using ascii values 
    # numbers 1-9, letters a-z 
    allowed_values = [i for i in range(97, 123)] +\ 
        [i for i in range(48,58)] 

    # create blinking underscore 
    BLINK_EVENT = pygame.USEREVENT + 0 
    pygame.time.set_timer(BLINK_EVENT, 800) 
    blinky = cycle(["_", " "]) 
    next_blink = next(blinky) 

    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 event.type == BLINK_EVENT: 
       next_blink = next(blinky) 
      # if input is in list of allowed characters, add to variable 
      elif event.type == KEYUP and event.key in allowed_values \ 
       and len(pressed) < max_length: 
       # caps entry? 
       if pygame.key.get_mods() & KMOD_SHIFT or pygame.key.get_mods()\ 
        & KMOD_CAPS: 
        pressed += chr(event.key).upper() 
       # lowercase entry 
       else: 
        pressed += chr(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 
     # only draw underscore if input is not at max character length 
     if len(pressed) < max_length: 
      print_text(font, 130, 180, pressed + next_blink) 
     else: 
      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(10) 

    print_text(font, 130, 180, name) 
    pygame.display.update() 
Смежные вопросы