Guest User

inputbox.py

a guest
Mar 20th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. # by Timothy Downs, inputbox written for my map editor
  2.  
  3. # This program needs a little cleaning up
  4. # It ignores the shift key
  5. # And, for reasons of my own, this program converts "-" to "_"
  6.  
  7. # A program to get user input, allowing backspace etc
  8. # shown in a box in the middle of the screen
  9. # Called by:
  10. # import inputbox
  11. # answer = inputbox.ask(screen, "Your name")
  12. #
  13. # Only near the center of the screen is blitted to
  14.  
  15. import pygame, pygame.font, pygame.event, pygame.draw, string
  16. from pygame.locals import *
  17.  
  18. def get_key():
  19. while 1:
  20. event = pygame.event.poll()
  21. if event.type == KEYDOWN:
  22. return event.key
  23. else:
  24. pass
  25.  
  26. def display_box(screen, message):
  27. "Print a message in a box in the middle of the screen"
  28. fontobject = pygame.font.Font(None,18)
  29. pygame.draw.rect(screen, (0,0,0),
  30. ((screen.get_width() / 2) - 100,
  31. (screen.get_height() / 2) - 10,
  32. 200,20), 0)
  33. pygame.draw.rect(screen, (255,255,255),
  34. ((screen.get_width() / 2) - 102,
  35. (screen.get_height() / 2) - 12,
  36. 204,24), 1)
  37. if len(message) != 0:
  38. screen.blit(fontobject.render(message, 1, (255,255,255)),
  39. ((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10))
  40. pygame.display.flip()
  41.  
  42. def ask(screen, question):
  43. "ask(screen, question) -> answer"
  44. pygame.font.init()
  45. current_string = ""
  46. display_box(screen, question + ": " + current_string)
  47. while 1:
  48. inkey = get_key()
  49. if inkey == K_BACKSPACE:
  50. current_string = current_string[0:-1]
  51. elif inkey == K_RETURN:
  52. break
  53. elif inkey <= 127:
  54. current_string+=chr(inkey)
  55. display_box(screen, question + ": " + "".join(current_string))
  56. return float(current_string)
Add Comment
Please, Sign In to add comment