Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/util.py
blob: 778d2e9651a161d9551db08f946bb966aaffcb55 (plain)
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import pygame
import pygame.font
from pygame.locals import *
import random, os.path
import math
import string

def load_image(file, trans = 0):
    "loads an image, prepares it for play"
    file = os.path.join('data', file)
    try:
        surface = pygame.image.load(file)
        if trans == 1:        
            surface.set_colorkey(surface.get_at((0, 0)))     
    except pygame.error:
        raise SystemExit, 'Could not load image "%s" %s'%(file, pygame.get_error())
    return surface.convert()
	
def ok_box(string, location, width, height, screen):
    clock = pygame.time.Clock() 
    pygame.init()
    font = pygame.font.Font(None, 24)
    intro_string = string
    text_rect = pygame.Rect(location,(width,height+40))
    text_box = render_textrect(intro_string,font,text_rect,(255,255,255),0,0)
    screen.blit(text_box,text_rect.topleft)
    (x_coord,y_coord) = location
    ok_box = pygame.Rect((x_coord+width/2-15,y_coord+height+5),(30,30))
    ok_box_surf = pygame.Surface(ok_box.size)
    ok_box_surf.fill((255,255,255))
    screen.blit(ok_box_surf,ok_box.topleft)
    ok_text = font.render("OK",1,(0,0,0))
    (x,y) = ok_box.topleft
    x += 3
    y += 5
    screen.blit(ok_text,(x,y))
    run = 1
    while run:
        events = pygame.event.get()
        for event in events: 
            if event.type == QUIT:              
               run = 0 #stop running
               pygame.quit()
            if event.type == pygame.MOUSEBUTTONDOWN:
               (x, y) = pygame.mouse.get_pos()
               if x > x_coord+width/2-15 and x < x_coord+width/2+15 and y > y_coord+height+5 and y < y_coord+height+35:
                   run = 0
                   return 1
        pygame.display.flip()
        clock.tick(20)

    
def render_textrect(string, font, rect, text_color, background_color, trans, justification=0):
    """Returns a surface containing the passed text string, reformatted
    to fit within the given rect, word-wrapping as necessary. The text
    will be anti-aliased.

    Takes the following arguments:

    string - the text you wish to render. \n begins a new line.
    font - a Font object
    rect - a rectstyle giving the size of the surface requested.
    text_color - a three-byte tuple of the rgb value of the
                 text color. ex (0, 0, 0) = BLACK
    background_color - a three-byte tuple of the rgb value of the surface.
    trans - set to 0 if you want the background to be shown
    justification - 0 (default) left-justified
                    1 horizontally centered
                    2 right-justified

    Returns the following values:

    Success - a surface object with the text rendered onto it.
    Failure - raises a TextRectException if the text won't fit onto the surface.
    """

    import pygame
    
    final_lines = []

    requested_lines = string.splitlines()

    # Create a series of lines that will fit on the provided
    # rectangle.

    for requested_line in requested_lines:
        if font.size(requested_line)[0] > rect.width:
            words = requested_line.split(' ')
            # if any of our words are too long to fit, return.
            for word in words:
                if font.size(word)[0] >= rect.width:
                    raise TextRectException, "The word " + word + " is too long to fit in the rect passed."
            # Start a new line
            accumulated_line = ""
            for word in words:
                test_line = accumulated_line + word + " "
                # Build the line while the words fit.    
                if font.size(test_line)[0] < rect.width:
                    accumulated_line = test_line
                else:
                    final_lines.append(accumulated_line)
                    accumulated_line = word + " "
            final_lines.append(accumulated_line)
        else:
            final_lines.append(requested_line)

    # Let's try to write the text out on the surface.

    surface = pygame.Surface(rect.size)
    if trans == 0:
        surface.fill(background_color)
    # CHANGED HERE, this make the BG transparent XXXXXXXXXXXXXXXXXXXXXXXXX transparent stuff here XXXXXXXXXX
    #surface.set_colorkey(background_color)
    # CHANGED
    
    accumulated_height = 0
    for line in final_lines:
        if accumulated_height + font.size(line)[1] >= rect.height:
            raise TextRectException, "Once word-wrapped, the text string was too tall to fit in the rect."
        if line != "":
            tempsurface = font.render(line, 1, text_color)
            if justification == 0:
                surface.blit(tempsurface, (5, accumulated_height+5))
            elif justification == 1:
                surface.blit(tempsurface, ((rect.width - tempsurface.get_width()) / 2, accumulated_height))
            elif justification == 2:
                surface.blit(tempsurface, (rect.width - tempsurface.get_width(), accumulated_height))
            else:
                raise TextRectException, "Invalid justification argument: " + str(justification)
        accumulated_height += font.size(line)[1]

    return surface

	     

#Takes two lists as arguments, returns list with both merged         
def merge(list1, list2):
    for element in list2:
        list1.append(element)
    return list1

def get_key():
    while 1:
        clock = pygame.time.Clock() 
        event = pygame.event.poll()
        if event.type == QUIT:              
               run = 0 #stop running
               pygame.quit()
        if event.type == KEYDOWN:
            keys = (event.key,event.unicode)
            return keys
        else:
            pass
        clock.tick(20)
        

def display_box(screen, message,x,y,length):
    "Print a message in a box in the middle of the screen"
    fontobject = pygame.font.Font(None,18)
    #pygame.draw.rect(screen, (0,0,0),((screen.get_width() / 2) - 100,(screen.get_height() / 2) - 10, 200,20), 0)
    #pygame.draw.rect(screen, (255,255,255), ((screen.get_width() / 2) - 102,(screen.get_height() / 2) - 12, 204,24), 1)
    pygame.draw.rect(screen, (0,0,0),(x,y, length,20), 0)
    pygame.draw.rect(screen, (255,255,255), (x-2,y-2, length+4,24), 1)
    if len(message) != 0:
        screen.blit(fontobject.render(message, 1, (255,255,255)),(x+2,y+3))
    pygame.display.flip()

def ask(screen, question,x,y,length):
    clock = pygame.time.Clock() 
    "ask(screen, question) -> answer"
    pygame.font.init()
    current_string = []
    display_box(screen, question + ": " + string.join(current_string,""),x,y,length)
    while 1:
        events = pygame.event.get()
        for event in events: 
            if event.type == QUIT:              
               run = 0 #stop running
               pygame.quit()
        inkey = get_key()
        if inkey[0] == K_BACKSPACE:
        #if inkey == u"\u2408":
            #print "back space"
            current_string = current_string[0:-1]
        elif inkey[0] == K_RETURN:
            #print "enter"
            break
        elif inkey == K_MINUS:
            current_string.append("_")
        #elif inkey <= 127:
        else:
            #current_string.append(chr(inkey))
            current_string.append(inkey[1])
        display_box(screen, question + ": " + string.join(current_string,""),x,y,length)
        clock.tick(20)
    return string.join(current_string,"")