-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser_input.py
92 lines (73 loc) · 2.97 KB
/
user_input.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#############################################################################
# Author: Griffin Della Grotte (gdellagr@andrew.cmu.edu)
# Inspiration from inputbox.py example module online with heavy modification
#
# This module houses user input classes, of which there is currently only
# a pop-up text box
#############################################################################
import pygame
from mapcmu_data import *
class TextInputBox(object):
def __init__(self, pos=(0,0), color=(180,255,180)):
self.enabled = False
self.pos = pos
self.size = 400,150
self.bSize = 360,40
self.bOffset = 20
self.color = color
self.text = ""
self.prompt = ""
self.callback = None
def doPopup(self, question, callback, args=()):
self.prompt = question
self.callback = callback
self.callArgs = args
self.enabled = True
def drawBox(self, surface):
surfSize = surface.get_size()
xMid, yMid = surfSize[0]//2-self.pos[0], surfSize[1]//2-self.pos[1]
pygame.draw.rect(surface,self.color,
(xMid-self.size[0]//2, yMid-self.size[1]//2,
self.size[0], self.size[1]))
pygame.draw.rect(surface,(255,255,255),
(xMid-self.bSize[0]//2, yMid-self.bSize[1]//2 + self.bOffset,
self.bSize[0], self.bSize[1]))
pygame.draw.rect(surface,(0,0,0),
(xMid-self.bSize[0]//2, yMid-self.bSize[1]//2 + self.bOffset,
self.bSize[0], self.bSize[1]), 1)
fSize = 20
buf = (self.bSize[1] - fSize)/2
dfont = pygame.font.SysFont("monospace", fSize)
xText = xMid - self.bSize[0]//2 + buf
yText = yMid - self.bSize[1]//2 + self.bOffset + fSize / 2
# Center text in box
label = dfont.render(
"%s: %s" % (self.prompt,self.text),
1, Constants.steel)
surface.blit(label, (xText,yText))
fSize = 20
buf = 10
instr = "Please type your response"
dfont = pygame.font.SysFont("monospace", fSize)
xText = xMid - dfont.size(instr)[0]/2
yText = yMid - self.bSize[1]//2 - self.bOffset
label = dfont.render(
instr,
1, Constants.steel)
surface.blit(label, (xText,yText))
def doCallback(self):
args = (self.text,) + self.callArgs
self.callback(*args)
self.text = ""
self.prompt = ""
self.enabled = False
def keyPressed(self, event):
shift = pygame.key.get_mods() & pygame.KMOD_SHIFT
if event.key == pygame.K_BACKSPACE:
self.text = self.text[:-1]
elif event.key == pygame.K_RETURN:
self.doCallback()
elif event.key < 127: # This is an alphabet key, put it in the box
char = event.key
if shift: char -= 32
self.text += chr(char) # Capital letters