def textCrystal(font, message, bevel=5, fontcolor=(64, 128, 255), contrast=70):
    """Renders text with a 'crystal' style apperance."""
    base = font.render(message, 0, fontcolor)
    size = base.get_width() + bevel * 2, base.get_height() + bevel * 2 + 2
    img = pygame.Surface(size)

    # Set background color to be transparent
    img.set_colorkey(pygame.Color('black'))

    tl = (-1, -1)
    tc = (0, -1)
    tr = (1, -1)
    cr = (1, 0)
    br = (1, 1)
    bc = (0, 1)
    bl = (-1, 1)
    cl = (-1, 0)

    for x in range(-bevel, 1, 1):
        for position in (tl, tr, br, bl, tc, cr, bc, cl):
            for location in (tl, tr, br, bl, tc, cr, bc, cl):
                shade = ((-location[0]) - location[1]) * contrast
                img.blit(font.render(message, 1, shadeColor(fontcolor, shade)),
                         (bevel + location[0] + (x * position[0]), bevel + location[1] + (x * position[1])))
        img.blit(font.render(message, 1, fontcolor), (bevel, bevel))
    return img
Exemple #2
0
def __pygame(title, message):
    try:
        import pygame, pygame.font
        pygame.quit() #clean out anything running
        pygame.display.init()
        pygame.font.init()
        screen = pygame.display.set_mode((460, 140))
        pygame.display.set_caption(title)
        font = pygame.font.Font(None, 18)
        foreg = 0, 0, 0
        backg = 200, 200, 200
        liteg = 255, 255, 255
        ok = font.render('Ok', 1, foreg)
        screen.fill(backg)
        okbox = ok.get_rect().inflate(20, 10)
        okbox.centerx = screen.get_rect().centerx
        okbox.bottom = screen.get_rect().bottom - 10
        screen.fill(liteg, okbox)
        screen.blit(ok, okbox.inflate(-20, -10))
        pos = [20, 20]
        for text in message.split('\n'):
            msg = font.render(text, 1, foreg)
            screen.blit(msg, pos)
            pos[1] += font.get_height()

        pygame.display.flip()
        while 1:
            e = pygame.event.wait()
            if (e.type == pygame.QUIT or e.type == pygame.MOUSEBUTTONDOWN or
                        pygame.KEYDOWN and e.key
                        in (pygame.K_ESCAPE, pygame.K_SPACE, pygame.K_RETURN)):
                break
        pygame.quit()
    except pygame.error:
        raise ImportError
Exemple #3
0
def renderText(text, font, antialias, color, size, autosize, wordwrap):
    lines = text.split('\n')
    if wordwrap and not autosize:
        for i in xrange(len(lines)):
            line = lines[i]
            del lines[i]
            lines[i:i] = wrapText(line, font, size[0]).split('\n')

    if len(lines) == 1:
        return font.render(text, antialias, color)
    else:
        lineHeight = font.get_linesize()
        height = lineHeight * len(lines)
        width = 0
        lineSurfs = []
        for line in lines:
            linesurf = font.render(line, antialias, color)
            lineSurfs.append(linesurf)
            if linesurf.get_width() > width:
                width = linesurf.get_width()

        surf = pygame.Surface((width, height), pygame.SRCALPHA)
        for i in xrange(len(lineSurfs)):
            surf.blit(lineSurfs[i], (0, i * lineHeight))

        return surf
Exemple #4
0
def _token_builder(interpreted_txt):
    # build a token from interpreted text
    # accepts an interpreted text list
    # returns a token object
    iswhitespace = _iswhitespace
    Token = _Token

    links = defaultdict(list)

    token_iswhitespace = True

    surfs, x, y = [], 0, 0
    for (envs, chars) in interpreted_txt:
        bkg, color, font = envs["bkg"], envs["color"], envs["font"]
        strbuff, surfbuff = [], []
        for char in chars:
            if not iswhitespace(char):
                token_iswhitespace = False

            if char == "\n":
                char = Surface((0, font.get_linesize()))

            if isinstance(char, unicode):
                if iswhitespace(char):
                    char = " "
                strbuff.append(char)
            elif isinstance(char, str):
                if iswhitespace(char):
                    char = " "
                strbuff.append(char)
            else:
                if strbuff:
                    surfbuff.append(font.render("".join(strbuff), 1, color, bkg))
                surfbuff.append(char)
                strbuff = []

        if strbuff:
            surfbuff.append(font.render("".join(strbuff), 1, color, bkg))

        if surfbuff:
            # calculate link rects
            link = envs["link"]
            surfbuff_w = sum(surf.get_width() for surf in surfbuff)
            surfbuff_h = max(surf.get_height() for surf in surfbuff)
            links[link].append(Rect(x, 0, surfbuff_w, surfbuff_h))
            x += surfbuff_w
            # extend surfbuff to surfs and reset surfbuff
            surfs.extend(surfbuff)
            surfbuff = []

    # get token width and height
    width = sum(surf.get_width() for surf in surfs)
    height = max(surf.get_height() for surf in surfs)

    # given token height, modify link rect y
    for rect in [rect for v in links.values() for rect in v]:
        rect.y += height - rect.h
    token_str = "".join(unicode(char) for (envs, chars) in interpreted_txt for char in chars)

    return Token((width, height), links, surfs, token_iswhitespace, token_str)
def drawTree(tree):
	screen = gameglobals.screen
	global offset, font, balanceYOffset, graphics

	centerX = gameglobals.cameraCenter[0] + offset[0]
	centerY = gameglobals.cameraCenter[1] + offset[1]

	for edgeLine in tree.edgeLines:
		fromPos = [centerX + edgeLine.fromPosition[0],
			centerY + edgeLine.fromPosition[1]]
		toPos = [centerX + edgeLine.toPosition[0], 
			centerY + edgeLine.toPosition[1]]
		pygame.draw.line(screen, LINE_COLOUR, fromPos, toPos, 3)
		

	drawPos = [0,0] #ignore this statement. I just need a 2-element list.
	arrowIndex = None
	for nodeCircle in tree.nodeCircles:
		balance = tree.balanceOf(nodeCircle)

		positionX = centerX + nodeCircle.position[0]
		positionY = centerY + nodeCircle.position[1]

		if (abs(balance) >= 2):
			drawPos[0] = positionX - graphics.nodeGlowHalfSize
			drawPos[1] = positionY - graphics.nodeGlowHalfSize
			image = graphics.nodeGlow
			screen.blit(image, drawPos)
			if (abs(balance) > 2):
				screen.blit(image, drawPos)


		drawPos[0] = positionX - graphics.nodeHalfSize
		drawPos[1] = positionY - graphics.nodeHalfSize
		if gameglobals.player.isSelected(nodeCircle.index):
			image = graphics.node_selected
			arrowX = positionX
			arrowY = positionY
			arrowIndex = nodeCircle.index
		else:
			image = graphics.node_unselected
		screen.blit(image, drawPos)
		#pygame.draw.circle(screen, colour, position, nodeCircle.radius)

		if (nodeCircle.renderedText == None):
			nodeCircle.renderedText = font.render(
				str(tree.valueOf(nodeCircle)), True, NODE_TEXT_COLOUR)
		drawPos[0] = positionX-nodeCircle.renderedText.get_width()//2
		drawPos[1] = positionY-nodeCircle.renderedText.get_height()//2
		screen.blit(nodeCircle.renderedText, drawPos)

		if (nodeCircle.renderedBalance == None):
			nodeCircle.renderedBalance = font.render(str(balance), True, TEXT_COLOUR)
		drawPos[0] = positionX-nodeCircle.renderedBalance.get_width()//2
		drawPos[1] = positionY-nodeCircle.renderedBalance.get_height()//2 - balanceYOffset
		screen.blit(nodeCircle.renderedBalance, drawPos)

	if arrowIndex != None:
		drawArrow(arrowX, arrowY, arrowIndex)
Exemple #6
0
def blitText(size,color, text, pos, shaOff = None):
		font = pygame.font.Font(FONT_FILENAME, size)
		
		if shaOff != None:
				txt = font.render(text, True, (0,0,0))
				screen.blit(txt, (pos[0] + shaOff[0],pos[1] + shaOff[1]))
		
		txt = font.render(text, True, color)
		screen.blit(txt, pos)
Exemple #7
0
def imgv_button(screen, msg, x, y, where):
    font = pygame.font.Font(gl.FONT_NAME, 10)
    if gl.BEING_HOVERED:
        ren = font.render(msg, 1, gl.BUTTON_TEXTHOVERCOLOR, gl.BUTTON_HOVERCOLOR)
        ren_rect = do_button(screen, ren, where, x, y)
    else:
        ren = font.render(msg, 1, gl.BUTTON_TEXTCOLOR, gl.BUTTON_BGCOLOR)
        ren_rect = do_button(screen, ren, where, x, y)
    return ren_rect
Exemple #8
0
def textOutline(font, message, fontcolor, outlinecolor):
    borde = font.render(message, 1, outlinecolor)
    base = font.render(message, 1, fontcolor)
    img = pygame.Surface( base.get_rect().inflate(2,2).size, 0, base )
    for x in 0,2:
        for y in 0,2:
            img.blit(borde, (x,y) )
    img.blit(base, (1, 1))
    return img
Exemple #9
0
def file_master(screen, file_names, place, marker, menu_items, msg, down, button_op):
    paint_screen(gl.BLACK)
    show_message(msg, down, 10, ("bold", "transparent"))
    font = pygame.font.Font(gl.FONT_NAME, 9)
    font.set_bold(1)
    (esc_rect, esc_font) = close_button(screen)
    font_height = font.size(file_names[0])[1]
    screen_height = screen.get_height()
    name_max = 16
    max_file_width = 116
    line = 65 # leave room at top of screen for other stuff
    col = 5
    count = 0
    back_rect = forward_rect = sort_rect = junk_rect()
    for name in file_names[place:]:
        count = count + 1
        place = place + 1
        marker = marker + 1
        if count >= gl.MAX_SCREEN_FILES or place >= len(file_names):
            ren_name = os.path.basename(name)
            if len(ren_name) > name_max:
                ren_name = ren_name[:name_max] + '...' # truncate
                if ren_name[-4:] == '....':
                    ren_name = ren_name[:-1] # 3 .'s are enough
            ren = font.render(ren_name, 1, gl.MSG_COLOR, gl.BLACK)
            if (place + 1) < len(file_names):
                forward_rect = imgv_button(screen, " Next ", 10, 18, "topright")
            if (((place + 1) - gl.MAX_SCREEN_FILES) > 1):
                back_rect = imgv_button(screen, " Previous ", 10, 18, "topleft")
            if not gl.SORT_HIT:
                sort_rect = imgv_button(screen, " Sort ", 13, 42, "midtop")
            ren_rect = ren.get_rect()
            ren_rect[0] = col
            ren_rect[1] = line
            menu_items.append((ren_rect, name))
            screen.blit(ren, ren_rect)
            update(ren_rect)
            return (file_names, menu_items, 1, place, marker, forward_rect, back_rect, sort_rect)
        ren_name = os.path.basename(name)
        if len(ren_name) > name_max:
            ren_name = ren_name[:name_max] + '...'
            if ren_name[-4:] == '....':
                ren_name = ren_name[:-1]
        ren = font.render(ren_name, 1, gl.MSG_COLOR, gl.BLACK)
        ren_rect = ren.get_rect()
        ren_rect[0] = col
        ren_rect[1] = line
        menu_items.append((ren_rect, name))
        screen.blit(ren, ren_rect)
        line = line + 12
        if (line + font_height) >= (screen_height - 15):
            line = 65
            col = col + max_file_width
        update(ren_rect)
    return (file_names, menu_items, 0, place, marker, forward_rect, back_rect, sort_rect)
Exemple #10
0
 def __init__(self, text, font, width, fgcolor, bgcolor=None):
     self.text = text
     self.font = font
     self.fgcolor = fgcolor
     self.bgcolor = bgcolor
     if bgcolor is None:
         self.image = font.render(text, 1, fgcolor)
         self.shadow = font.render(text, 1, (0, 0, 0))
     else:
         self.image = font.render(text, 1, fgcolor, bgcolor)
         self.shadow = None
Exemple #11
0
 def set_text(self, text):
     self.text = text
     font = self.font
     font.set_underline(self.underline)
     font.set_bold(self.bold)
     font.set_italic(self.italic)
     
     # required for font.render to function properly when None is
     # given for background
     if self.background == None:
         self.surface = font.render(text, self.antialias, self.color).convert_alpha()
     else:
         self.surface = font.render(text, self.antialias, self.color, self.background).convert()
Exemple #12
0
    def _update(self, l):
        bkg, color, font = self.bkg, self.color, self.font
        spacing, dest, rect_w = self.spacing, self._dest, self.rect.w
        bkg_img, image = self._image, self.image
        lines, txt, wraps = self._lines, self.txt, self._wraps
        tokenize = self._tokenize
        Line = _Line

        tokens = tokenize(txt[wraps[l]:])
        dest.y = sum(line.image.get_height() + spacing for line in lines[:l])
        wraps = wraps[:l + 1]
        k = wraps[-1]
        linebuff = []
        L = [l] # a list of updated lines
        for token in tokens:
            if token == '\n':
                k += 1 # increment k (so the \n will be on this line)
                wraps.append(k)
                # a space is the visual representation of the \n character
                linebuff.append(' ')
                _linebuff = []

            elif font.size(''.join(linebuff + [token]))[0] < rect_w:
                k += len(token)
                linebuff.append(token)
                continue

            else:
                wraps.append(k) # k is the position of the previous space token
                k += len(token)
                _linebuff = [token]
                lines.insert(l + 1, Line(Surface((0, 0)), Rect(0, 0, 0, 0)))

            line = font.render(''.join(linebuff), 0, color, bkg)
            line = Line(line, Rect(dest.topleft, line.get_size()))
            lines[l].clear(image, bkg_img)
            lines[l] = line

            dest.y += line.image.get_height() + spacing
            linebuff = _linebuff
            l += 1
            L.append(l)

        line = font.render(''.join(linebuff), 0, color, bkg)
        line = Line(line, Rect(dest.topleft, line.get_size()))
        lines[l].clear(image, bkg_img)
        lines[l] = line

        for line in [lines[l] for l in L]: image.blit(line.image, line.rect)

        self._wraps = wraps
Exemple #13
0
def display_game_screen(difficulty):
    """Displays the playing screen at the beginning of a game"""
    global cell_size, field_coord
    display_clear()

    font = pygame.font.SysFont(POLICE, TXT_SIZE)
    # Displaying difficulty
    text_diff = font.render("Difficulty: ", 1, (0, 0, 0))
    if difficulty == "easy":
        text_diff_2 = font.render("Easy", 1, (0, 255, 0))
        show_mines_left(NB_MINES_EASY)
        cell_size = min(WINDOW_SIZE[0]//FIELD_SIZE_EASY[0], (WINDOW_SIZE[1] - HEADER_SIZE)//FIELD_SIZE_EASY[1])
        field_coord = (((WINDOW_SIZE[0] - cell_size * FIELD_SIZE_EASY[0])//2,
                        (WINDOW_SIZE[1] + HEADER_SIZE - cell_size * FIELD_SIZE_EASY[1])//2),
                       ((WINDOW_SIZE[0] + cell_size * FIELD_SIZE_EASY[0])//2,
                        (HEADER_SIZE + WINDOW_SIZE[1] + cell_size * FIELD_SIZE_EASY[1])//2))
        resize_cell_img()
        for x in range(FIELD_SIZE_EASY[0]):
            for y in range(FIELD_SIZE_EASY[1]):
                WINDOW.blit(cell_img, cell_to_pixel((x, y)))

    elif difficulty == "medium":
        text_diff_2 = font.render("Medium", 1, (255, 255, 0))
        show_mines_left(NB_MINES_MEDIUM)
        cell_size = min(WINDOW_SIZE[0]//FIELD_SIZE_MEDIUM[0], (WINDOW_SIZE[1] - HEADER_SIZE)//FIELD_SIZE_MEDIUM[1])
        field_coord = (((WINDOW_SIZE[0] - cell_size * FIELD_SIZE_MEDIUM[0])//2,
                       (WINDOW_SIZE[1] + HEADER_SIZE - cell_size * FIELD_SIZE_MEDIUM[1])//2),
                       ((WINDOW_SIZE[0] + cell_size * FIELD_SIZE_MEDIUM[0])//2,
                        (HEADER_SIZE + WINDOW_SIZE[1] + cell_size * FIELD_SIZE_MEDIUM[1])//2))
        resize_cell_img()
        for x in range(FIELD_SIZE_MEDIUM[0]):
            for y in range(FIELD_SIZE_MEDIUM[1]):
                WINDOW.blit(cell_img, cell_to_pixel((x, y)))

    else:
        text_diff_2 = font.render("Hard", 1, (255, 0, 0))
        show_mines_left(NB_MINES_HARD)
        cell_size = min(WINDOW_SIZE[0]//FIELD_SIZE_HARD[0], (WINDOW_SIZE[1] - HEADER_SIZE)//FIELD_SIZE_HARD[1])
        field_coord = (((WINDOW_SIZE[0] - cell_size * FIELD_SIZE_HARD[0])//2,
                        (WINDOW_SIZE[1] + HEADER_SIZE - cell_size * FIELD_SIZE_HARD[1])//2),
                       ((WINDOW_SIZE[0] + cell_size * FIELD_SIZE_HARD[0])//2,
                        (HEADER_SIZE + WINDOW_SIZE[1] + cell_size * FIELD_SIZE_HARD[1])//2))
        resize_cell_img()
        for x in range(FIELD_SIZE_HARD[0]):
            for y in range(FIELD_SIZE_HARD[1]):
                WINDOW.blit(cell_img, cell_to_pixel((x, y)))

    WINDOW.blit(text_diff, (10, (HEADER_SIZE - TXT_SIZE)/2))
    WINDOW.blit(text_diff_2, (153, (HEADER_SIZE - TXT_SIZE)/2))

    pygame.display.flip()
Exemple #14
0
    def show(self, SCREEN, posx):
        
        if (self.posicao[0]-posx < 620 and self.posicao[0]-posx > -160):
            font = pygame.font.Font("comic.ttf", 25)
            self.rect = SCREEN.blit(self.imagem, (self.posicao[0]-posx, self.posicao[1]))

            if self.opcoes[0] == True:
                texto = font.render("Liga", True, (0, 0, 0))
                SCREEN.blit(texto, (self.posicao[0]-posx + 20, self.posicao[1] + 25))
            else:
                texto = font.render("Desliga", True, (0, 0, 0))
                SCREEN.blit(texto, (self.posicao[0]-posx + 4, self.posicao[1] + 25))
            
            font = pygame.font.Font("comic.ttf", 20)

            if self.leds[0] == True and self.leds[1] == True and self.leds[2] == True :
                texto = font.render("1,2 e 3", True, (0, 0, 0))
                SCREEN.blit(texto, (self.posicao[0]-posx + 10, self.posicao[1] + 60))

            elif self.leds[0] == True and self.leds[1] == True:
                texto = font.render("1 e 2", True, (0, 0, 0))
                SCREEN.blit(texto, (self.posicao[0]-posx + 20, self.posicao[1] + 60))

            elif self.leds[0] == True and self.leds[2] == True:
                texto = font.render("1 e 3", True, (0, 0, 0))
                SCREEN.blit(texto, (self.posicao[0]-posx + 33, self.posicao[1] + 60))

            elif self.leds[1] == True and self.leds[2] == True:
                texto = font.render("2 e 3", True, (0, 0, 0))
                SCREEN.blit(texto, (self.posicao[0]-posx + 33, self.posicao[1] + 60))

            elif self.leds[0] == True:
                texto = font.render("1", True, (0, 0, 0))
                SCREEN.blit(texto, (self.posicao[0]-posx + 40, self.posicao[1] + 60))
            
            elif self.leds[1] == True:
                texto = font.render("2", True, (0, 0, 0))
                SCREEN.blit(texto, (self.posicao[0]-posx + 40, self.posicao[1] + 60))
            
            elif self.leds[2] == True:
                texto = font.render("3", True, (0, 0, 0))
                SCREEN.blit(texto, (self.posicao[0]-posx + 40, self.posicao[1] + 60))
            
            

            pygame.draw.line(SCREEN, (0, 0, 0, 0),
                             (self.posicao[0]-posx + 100, self.posicao[1] + 50),
                             (self.posicao[0]-posx + 125, self.posicao[1] + 50), 15)

            pygame.draw.polygon(SCREEN, (0, 0, 0, 0),
                                ((self.posicao[0]-posx + 125, self.posicao[1] + 25), (self.posicao[0]-posx + 125, self.posicao[1] + 75),
                                (self.posicao[0]-posx + 150, self.posicao[1] + 50)))
        else:
            self.rect = 0
        pass
Exemple #15
0
    def drow(self):
        self.current_stage.draw(screen)
        self.active_sprite_list.draw(screen)
        self.text = font.render("Total Life    : " + str(self.life), True, BLACK)
        self.text_rect = self.text.get_rect()
        self.text_x = screen.get_width() - self.text_rect.width * 1.2
        self.text_y = 20
        screen.blit(self.text, [self.text_x, self.text_y])

        self.text =font.render("Total Credit: " + str(self.score), True, BLACK)
        self.text_rect = self.text.get_rect()
        self.text_x = screen.get_width() - self.text_rect.width * 1.2
        self.text_y = 50
        screen.blit(self.text, [self.text_x, self.text_y])
def drawUIPanel():
	screen = gameglobals.screen
	global graphics
	size = gameglobals.size

	# Draw Frame
	drawPos = [0,0]
	screen.blit(graphics.uiBar, drawPos)

	# Draw Queue
	queue = gameglobals.opQueue
	operations = queue.nextFewOperations

	queueDistance = 60
	queueSize = len(operations)
	queueLeft = (size[0] - (queueSize-1)*queueDistance)//2
	posX = queueLeft
	posY = 75

	if (queue.renderedText == None):
		queue.renderedText = []
		for i in range(0, queueSize):
			text = font.render(str(operations[i][0]), True, TEXT_COLOUR)
			queue.renderedText.append(text)

	for i in range (0,queueSize):
		text = queue.renderedText[i]
		if (operations[i][1] == True): # add
			image = graphics.addSquare
		else: # delete
			image = graphics.deleteSquare
		drawPos[0] = posX-graphics.squareHalfSize
		drawPos[1] = posY-graphics.squareHalfSize
		screen.blit(image, drawPos)

		drawPos[0] = posX-text.get_width()//2
		drawPos[1] = posY-text.get_height()//2
		screen.blit(text, drawPos)

		if i == 0:
			if graphics.nextText == None:
				graphics.nextText = font.render("NEXT", True, TEXT_COLOUR)
			drawPos[0] = posX-graphics.nextText.get_width()//2
			drawPos[1] = posY-graphics.nextText.get_height()//2+27
			screen.blit(graphics.nextText, drawPos)

		posX += queueDistance

	drawText()
Exemple #17
0
def display_help_screen():
    """Displays the help screen"""
    display_clear()

    font = pygame.font.SysFont(POLICE, TXT_SIZE)
    text_title = font.render("HOW TO PLAY", 1, (0, 0, 0))
    text_help = font.render("Left click to reveal a cell.", 1, (0, 0, 0))
    text_help_2 = font.render("Right click to flag a cell.", 1, (0, 0, 0))
    text_help_3 = font.render("Click to go back.", 1, (0, 0, 0))

    WINDOW.blit(text_title, (WINDOW_SIZE[0]//2 - text_title.get_width()//2, TXT_SIZE + 10))
    WINDOW.blit(text_help, (10, 2 * TXT_SIZE + 70))
    WINDOW.blit(text_help_2, (10, 3 * TXT_SIZE + 130))
    WINDOW.blit(text_help_3, (WINDOW_SIZE[0]//2 - text_help_3.get_width()//2, 4 * TXT_SIZE + 240))
    pygame.display.flip()
Exemple #18
0
 def make_planets(self):
     font_size = max(8, int(round(self.surface.get_height() * PLANET_FRAC)))
     font = pygame.font.Font('ASTRO.TTF', font_size)
     planets = []
     for char, color in zip(planet_font, planet_color):
         planet_surface = font.render(char, True, color)
         planet_shadow = font.render(char, True, (0, 0, 0, 96))
         surface = pygame.Surface(
             (planet_surface.get_width() + 1,
              planet_surface.get_height() + 1)).convert_alpha()
         surface.fill((0, 0, 0, 0))
         surface.blit(planet_shadow, (1, 1))
         surface.blit(planet_surface, (0, 0))
         planets.append(surface)
     self.planets = planets
def Buyer(game, index, pp):
    building_position = game.current_position()
    font = pygame.font.Font(None, 30)
    textImg = font.render(
        "   Buy building " + game.at(building_position)[0], 1, (255, 0, 0))
    textImg1 = font.render(
        "   building name is " + game.at(building_position)[1], 1, (255, 0, 0))
    catImg1 = pygame.image.load('pictures/bG.jpg')
    pp.blit(catImg1, blue_bg)
    bg_color = (255, 255, 255)
    text_color = (255,   0,   0)

    x_position = 120
    y_position = 350
    text_lenght = 100
    x_text_border = 30
    y_text_border = 30

    Buy = Button()
    Buy.create_button(pp, bg_color, x_position, y_position,
                      text_lenght, x_text_border, y_text_border, 'Buy', text_color)
    Auction = Button()
    Auction.create_button(pp, bg_color, x_position + 200, y_position,
                          text_lenght, x_text_border, y_text_border, 'Auction', text_color)
    pp.blit(textImg, center)  # za da e nai otgore
    pp.blit(textImg1, (120, 200))  # za da e nai otgore
    pygame.display.update()

    mousex = 0
    mousey = 0
    player_index = game.current_player_index()
    time.sleep(2)
    for event in pygame.event.get():  # event handling loop
        if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
            pygame.quit()
            sys.exit()
        elif event.type == MOUSEMOTION:
            mousex, mousey = event.pos
        elif event.type == MOUSEBUTTONUP:
            mousex, mousey = event.pos
            if Buy.pressed([mousex, mousey]):
                print('buy')
                a = game.buy_building(building_position, 0)
                if a:
                    return 'buy'
            if Auction.pressed([mousex, mousey]):
                return 'auction'
    return 1
Exemple #20
0
 def screen(self,surface,pos,fgcolor=(128,128,125),font=None,interline=0):
     fgcolor = [fgcolor]
     px,y = pos
     mono = True
     if not font: font = Text.defaultfont
     if font.size('i')!=font.size('x'): mono = False
     char_w,char_h = font.size(' ')
     char_h += interline
     style_cmd = {'+':True,'-':False,'b':font.set_bold,'i':font.set_italic,'u':font.set_underline}
     bz = self.baliz
     def set_style(pos):
         while True:
             if bz and pos == bz[0][0]: 
                 _,mode,style,color,value = bz.pop(0)
                 if mode: style_cmd[style](style_cmd[mode])
                 elif color:
                     if value: fgcolor.append(Color(int(value,16)<<8))
                     else: fgcolor.pop()
             else: break
     rec = Rect(pos,(0,0))
     pos = 0
     set_style(pos)
     if mono:
         for lines in self:
             for line in lines:
                 x = px
                 for char in line:
                     rec = rec.unionall([(surface.blit(font.render(char,1,fgcolor[-1]),(x,y))),rec])
                     x += char_w
                     pos += 1
                     set_style(pos)
                 y += char_h
             pos += 1
             set_style(pos)
         return rec
     for lines in self:
         for line in lines:
             x = px
             for char in line:
                 x = surface.blit(font.render(char,1,fgcolor[-1]),(x,y))
                 rec = rec.unionall([x,rec])
                 x = x.right
                 pos += 1
                 set_style(pos)
             y += char_h
         pos += 1
         set_style(pos)
     return rec
def DrawScore(value):
    screen = pygame.display.get_surface()
    font = pygame.font.Font(None, 50)
    screen_width, screen_height = screen.get_size()
    pos = (screen_width - 50, 0)
    text = font.render(str(value), 1, (0, 80, 10))
    screen.blit(text, pos)
Exemple #22
0
     text_sprite=self.get_view_entity(eid)
     text_sprite.kill()
     self.delete_view_entity(eid)
     
 def add_text_entity(self, text, position , filename=None, size=10, color=(0,0,0)):
     '''
     Adds text with top left corner located at position.
     If filename is None, default font will be used.
     Size is in view units. 
     
     returns: View entity entity id
     '''
     import os
     from pygame import font, sprite
     
     if filename==None:
         filename=os.path.join(path, "Font", DEFAULT_FONT)
     
     font=font.Font(filename, size)
     rendered_text=font.render(text, True, color)
     
     text_sprite=sprite.Sprite()
     text_sprite.image=rendered_text
     text_sprite.rect=rendered_text.get_rect()
     text_sprite.rect.topleft=position
     text_sprite.font=font
     text_sprite.color=color
	def display_box(self, screen,message):
		font = pygame.font.SysFont("Default", 35)
		font_write = font.render(message, 1, (255,255,255))
		pygame.draw.rect(screen, (0,0,65), (188, 412, 230, 50))
		if len(message) != 0:
			screen.blit(font_write, (188, 422))
		pygame.display.flip()
Exemple #24
0
def do_view_tagged(screen, num_imgs, file):
    "show all tagged dir names"
    paint_screen(screen, gl.BLACK)
    (esc_rect, close_font) = close_button(screen)
    line = 5
    if len(gl.MULT_DIRS) == 0:
        show_message(screen, "[No directories are currently tagged]", "bottom", 12)
    for d in gl.MULT_DIRS:
        font = pygame.font.Font(gl.FONT_NAME, 9)
        ren = font.render(d, 1, (255, 255, 255), (0, 0, 0))
        ren_rect = ren.get_rect()
        ren_rect[0] = 5
        ren_rect[1] = line
        screen.blit(ren, ren_rect)
        line = line + 12
        update(ren_rect)
    pygame.event.set_allowed(MOUSEMOTION)
    while 1:
        ev = pygame.event.wait()
        check_quit(ev)
        hover_cursor(pygame.mouse.get_pos(), (esc_rect,))
        if ev.type == KEYDOWN and ev.key not in (K_LALT, K_RALT, K_TAB, K_LCTRL, K_RCTRL) or ev.type == MOUSEBUTTONDOWN:
            gl.ADDED_DIR_NUMS = 0
            (num_imgs, file) = show_dirs(screen, num_imgs, file)
            break # break event loop
Exemple #25
0
 def render(self, camera, crh, srh, crv, srv, width, height, screen):
     camera_x, camera_y, camera_z = camera
     dx = self.x - camera_x
     dy = self.y - camera_y
     dz = self.z - camera_z
     squared_distance = dx**2 + dy**2 + dz**2
     dx, dz = (dx * crh - dz * srh, dx * srh + dz * crh)
     dy, dz = (dy * crv - dz * srv, dy * srv + dz * crv)
     if (squared_distance < 0.00000001 or
         dz < 0.00000001 or dz < dy or dz < dx):
         return
     screen_x = int((dx * width / dz + width) / 2)
     screen_y = int(height - (dy * height / dz + height) / 2)
     if (screen_x < 0 or screen_x > width or
         screen_y < 0 or screen_y > height):
         return
     brightness = 18 * 1000.0 * self.luminosity / squared_distance
     brightness = min(brightness, 5)
     #if self.apparent_magnitude_from_earth < 7:
     #    print self.apparent_magnitude_from_earth, brightness
     self.draw_star_shape(screen, screen_x, screen_y, brightness)
     if self.hipparcos_id in star_names:
         font = pygame.font.Font(None, 18)
         b = min(brightness * 100, 255)
         color = b, b, b
         text = font.render(star_names[self.hipparcos_id], 1, color)
         location = text.get_rect(centerx=screen_x, top=screen_y)
         screen.blit(text, location)
Exemple #26
0
    def show(self, SCREEN, posx):
        """
        Só mostra se houver alguma parte vísivel para o usuário ou seja, se a posição ficar entre -100 e 620
        """
        if (self.posicao[0]-posx < 620 and self.posicao[0]-posx > -160):
            font = pygame.font.Font("comic.ttf", 30)

            self.rect = SCREEN.blit(self.imagem, (self.posicao[0]-posx, self.posicao[1]))

            fonte = pygame.font.Font("comic.ttf", config_caixa.data['caixa_tempo'][self.lingua]['tamanho'])
            texto = fonte.render(config_caixa.data['caixa_tempo'][self.lingua]['texto'], True, (0, 0, 0))
            SCREEN.blit(texto, (self.posicao[0]-posx +50 - texto.get_width()/2, self.posicao[1]))

            #Texto do tempo centralizado
            texto = font.render(self.escreve[1:]+"s", True, (0, 0, 0))
            SCREEN.blit(texto, (self.posicao[0]- posx + 50 - texto.get_width()/2 , self.posicao[1] + 50))

            pygame.draw.line(SCREEN, (0, 0, 0, 0),
                             (self.posicao[0]-posx + 100, self.posicao[1] + 50),
                             (self.posicao[0]-posx + 125, self.posicao[1] + 50), 15)

            pygame.draw.polygon(SCREEN, (0, 0, 0, 0),
                                ((self.posicao[0]-posx + 125, self.posicao[1] + 25), (self.posicao[0]-posx + 125, self.posicao[1] + 75),
                                (self.posicao[0]-posx + 150, self.posicao[1] + 50)))
            #pygame.display.update((self.posicao[0]-posx,self.posicao[1],300-posx,300))

        else:
            self.rect = 0
        """
Exemple #27
0
def displayMessage( message, screen, background ):
   font = pygame.font.Font( None, 48 )
   text = font.render( message, 1, ( 250, 250, 250 ) )
   textPosition = text.get_rect()
   textPosition.centerx = background.get_rect().centerx
   textPosition.centery = background.get_rect().centery
   return screen.blit( text, textPosition )
Exemple #28
0
def create_date_img(): #{{{
    now = time.strftime('%Y-%m-%d %X',time.localtime(time.time()))
    pygame.font.init()
    font = pygame.font.SysFont("wenquanyizenhei", 20)
    image = font.render(now, True, (255, 255, 255))
    #pygame.image.save(image, IMG)
    return image
Exemple #29
0
    def getImage(self):
        backsurf = pygame.Surface(self.background.get_size())
        
        menusurf = pygame.Surface(self.getMenuSize())
        menusurf.fill(self.getMenuColor())

        font = self.getFont()

        for i in range(len(self.choices)):
            text, callable = self.choices[i]
            if i == self.mouseover:
                color = self.getOverColor()
            else:
                color = self.getTextColor()
            linesurf = font.render(text, 1, color)
            menusurf.blit(linesurf, (0, i * self.getTextSkip()))

        pos = self.getMenuPos()
        if pos == None:
            pos = (
                (backsurf.get_width() - menusurf.get_width()) / 2,
                (backsurf.get_height() - menusurf.get_height()) / 2
            )

        menusurf.set_alpha(200)

        backsurf.fill((0,0,0))
        backsurf.blit(self.background, (0,0))
        backsurf.blit(menusurf, pos)
        self.pos = pos
        return backsurf
    def drawResults(self):
        """Output results after game play finish"""
        pygame.font.init()

        # popup result
    	font = pygame.font.Font(None, 36)
        self.screen.fill((130,174,202),(50,50,700,500))
        text = "Test Results"
        text_rendered = font.render(text,1,self.WHITE)
        self.screen.blit(text_rendered,(250,100))
        
        font1 = pygame.font.Font(None, 25)
        if self.auto2:
            result = self.auto2.switchResultText + ["break"] + self.auto2.notSwitchText
        elif self.auto1:
            result = self.auto1.switchResultText+["break"] +  self.auto1.notSwitchText
        else:
            pass
        
        n = 0
        while result:
            text = result[0]
            if text == "break":
                n+=4
            else:
                display = font1.render(text, 1, self.WHITE)
                self.screen.blit(display, (150, 200+n*15))
                n+=2
                
            result = result[1:]
        pygame.display.flip()

        # After game is finished, player is presented oppotunity to
        # play again.
        self.playAgain()
Exemple #31
0
 def update_text(self, text=None, font=None, text_to_width_factor=None):
     assert self.text is not None or text is not None, \
         'Cannot show text with no text passed as argument and no text in object!'
     assert self.font is not None or font is not None, \
         'Cannot create text with no font passed as argument and no font in object!'
     if text is not None:
         self.text = text
     if font is not None:
         self.font = font
         self.text_render = font.render(text, True, (255, 255, 255))
     else:
         self.text_render = self.font.render(self.text, True, (255, 255, 255))
     self.text_rect = self.text_render.get_rect()
     self.text_rect.center = self.center
     if text_to_width_factor is not None:
         expected_width = int(text_to_width_factor * len(self.text) + 30)
         width_diff = expected_width - copy(self.width)
         self.widen(width_diff)
         self.update_shapes()
Exemple #32
0
def RenderText(text, font, color=Color.White, alignRight=False):

    lines = text.splitlines()
    surfaces = [font.render(line, True, color) for line in lines]

    width = max([surface.get_width() for surface in surfaces])
    height = sum([surface.get_height() for surface in surfaces])

    destination = Surface([width, height], SRCALPHA, 32)
    verticalCursor = 0

    for surface in surfaces:

        horizontalCursor = (width - surface.get_width()) if alignRight else 0

        destination.blit(surface, (horizontalCursor, verticalCursor))
        verticalCursor += surface.get_height()

    return destination
Exemple #33
0
    def blitstats(self):
        self.screen.blit(self.Livestext, self.Livespos)
        if (self.num_lives == 3):
            self.screen.blit(self.pacmanimage, self.pacpos)
            self.screen.blit(self.pacmanimage, self.pacpos2)
            self.screen.blit(self.pacmanimage, self.pacpos3)
        elif (self.num_lives == 2):
            self.screen.blit(self.pacmanimage, self.pacpos2)
            self.screen.blit(self.pacmanimage, self.pacpos3)
        elif (self.num_lives == 1):
            self.screen.blit(self.pacmanimage, self.pacpos3)
        self.screen.blit(self.scores, self.scorespos)
        self.screen.blit(self.number, self.numberpos)

        # Update scoreboard
        font = pygame.font.Font(None, 72)
        self.number = font.render(str(self.score), 2, WHITE)

        self.level = 1
Exemple #34
0
def game_over(background, paddle, ball, bricks, message):
    """Displays the win/loss message and ends the game.

    Args:
        background (pygame.Surface): The game background.
        paddle (Paddle): The game paddle.
        ball (Ball): The game ball.
        bricks (List(Brick)): List of game bricks.
        message (str): The end game display message.
    """
    paddle.kill()
    ball.kill()
    for brick in bricks:
        brick.kill()
    font = pygame.font.Font(None, 100)
    text = font.render(message, 1, (255, 255, 255))
    textpos = text.get_rect(centerx=background.get_width() / 2,
                            centery=background.get_height() / 2)
    background.blit(text, textpos)
Exemple #35
0
def display_box(screen, message):
    "Print a message in a box in the middle of the screen"
    font = pygame.font.Font(None, 18)
    rect = pygame.Rect([0, 0, 435, 20])
    offset = (3, 3)

    center = screen.get_rect().center
    rect.center = (500, 140)

    pygame.draw.rect(screen, (0, 0, 0), rect, 0)
    pygame.draw.rect(screen, (255, 255, 255), rect, 1)

    rect.left += offset[0]
    rect.top += offset[1]

    if len(message) != 0:
        screen.blit(font.render(message, 1, (255, 255, 255)), rect.topleft)

    pygame.display.flip()
Exemple #36
0
def drawTextColored(surface, fontsize, message, location, color):
    font = pygame.font.Font(FONT_FILENAME, fontsize)
    fontcolor = color
    orig = font.render(message, 1, fontcolor)

    ##		shadowcolor = 100, 100, 100
    ##		offset = 2
    ##		orig = orig.convert()
    ##		size = orig.get_width() + offset, orig.get_height() + offset
    ##		img = pygame.Surface(size, 16)
    ##		img = img.convert()
    ##		img.set_colorkey((0, 0, 0))
    ##		orig.set_palette_at(1, shadowcolor)
    ##		img.blit(orig, (offset, offset))
    ##		orig.set_palette_at(1, fontcolor)
    ##		img.blit(orig, (0, 0))
    ##		surface.blit(img, location)

    surface.blit(orig, location)
Exemple #37
0
    def draw(self, win: surface, outline: Tuple[int, int, int]) -> None:
        """draws the button on the surface that is passed in

        Preconditions:
            - 0 <= outline[0] <= 255
            - 0 <= outline[1] <= 255
            - 0 <= outline[2] <= 255
        """
        pygame.draw.rect(
            win, outline,
            (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)

        pygame.draw.rect(win, self.colour,
                         (self.x, self.y, self.width, self.height), 0)

        font = pygame.font.SysFont('timesnewromanms', 60)
        text = font.render(self.text, True, (0, 0, 0))
        win.blit(text,
                 (self.x + (self.width / 2 - text.get_width() / 2), self.y +
                  (self.height / 2 - text.get_height() / 2)))
Exemple #38
0
    def draw_board(self):
        row_number = 0
        column_number = 0

        text_surface = font.render("Board", True, text_color)
        self.screen.blit(text_surface,
                         (buffer_zone + 6 * tile_size, buffer_zone))

        for row in self.board:
            for tile in row:
                # _ is empty, X is barrier, O is player.
                rectangle = pygame.Surface((tile_size, tile_size))
                rectangle.fill(board_color_dict[tile])
                self.screen.blit(rectangle, (row_number + buffer_zone,
                                             column_number + 2 * buffer_zone))

                column_number = column_number + tile_size

            row_number = row_number + tile_size
            column_number = 0
def showAnswer(imgNote, selNote, background, screen):
    imgNote_rect = imgNote.get_rect()
    selFretPath = "/Users/kaldrich/Documents/Files/Development/Python/GuitarNoteTester/FretboardImages/" + selNote + ".png"

    # Display note name
    font = pygame.font.Font(None, 36)
    text = font.render(selNote, 1, (10, 10, 10))
    textpos = text.get_rect()
    textpos.centerx = background.get_rect().centerx
    textpos.centery = background.get_rect().centery

    # Display fretboard image
    imgFret = pygame.image.load(selFretPath)
    imgFret_rect = imgFret.get_rect()

    screen.blit(text, textpos)
    screen.blit(imgFret,
                (background.get_rect().centerx - imgFret_rect.width / 2,
                 background.get_rect().centery + textpos.height + 30))
    pygame.display.update([textpos, imgFret_rect])
Exemple #40
0
def drawLives(screen, lives, font, color, windowWidth, windowHeight):
    # create a text suface object, 
    # on which text is drawn on it.
    txt = str(lives)
    text = font.render(txt, True, color)
    text_width, text_height = text.get_width(), text.get_height()
    
    # create a rectangular object for the 
    # text surface object 
    x = (windowWidth - text_width) / 2
    y = (windowHeight - text_height) / 2

    # copying the text surface object 
    # to the display surface object  
    # at the center coordinate.
    if (len(color) > 3):
        alpha_img = pygame.Surface(text.get_rect().size, pygame.SRCALPHA)
        alpha_img.fill((255, 255, 255, color[3] / 255 * 100))
        text.blit(alpha_img, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)
    screen.blit(text, [x, y]) 
def playUfoScore(ai_settings, screen, entity):
    now = time.time()
    sec = now % 60

    width, height = 200, 50
    button_color = (0, 0, 0)
    text_color = (0, 255, 0)
    font = pygame.font.SysFont(None, 48)

    rect = pygame.Rect(0, 0, width, height)
    rect.centery = entity.rect.centery
    rect.centerx = entity.rect.centerx

    msg_image = font.render(str(ai_settings.ufo_points), True, text_color,
                            button_color)
    msg_image_rect = msg_image.get_rect()
    msg_image_rect.center = rect.center
    for i in range(120):
        screen.blit(msg_image, msg_image_rect)
        pygame.display.flip()
    def draw_text(self, position, text, size):
        """Draw text on screen

        Args:
            position (tuple(int, int, int)): 3D position of the text
            text (string): String to display
            size (int): Font size in pt
        """
        font = self.get_font(size)

        surface = font.render(text, True, (255, 255, 255, 255), (0, 0, 0, 255))
        text_data = pygame.image.tostring(surface, "RGBA", True)
        glRasterPos3d(*position)
        glDrawPixels(
            surface.get_width(),
            surface.get_height(),
            GL_RGBA,
            GL_UNSIGNED_BYTE,
            text_data,
        )
Exemple #43
0
def display_box(screen, message):
  ###added by joel###
  font = pygame.font.SysFont("comicsansms", 50)
  text = font.render("New High Score!", True, yellow)
  screen.blit(text,((screen.get_width()/3),20))
  ###end of added by joel###
  
  fontobject = pygame.font.SysFont("comicsansms",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)
  if len(message) != 0:
    screen.blit(fontobject.render(message, 1, (255,255,255)),
                ((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10))
  pygame.display.flip()
Exemple #44
0
def draw_tile(x, y, offsetx=0, offsety=0, scale=100):
    local_scale = int(scale * scale_factor) #The scale for individual tiles is affected by the main scale factor
    padding = int(SCALE / 20)
    width = SCALE + padding
    height = SCALE + padding
    r = int(0.1 * SCALE) # Radius of the rounded corners
    color = COLORS[board.get(x, y) % len(COLORS)]

    rounded_rect = pygame.Surface((width, height))
    rounded_rect.fill(BG_COLOR)

    circle_centers = [
        (r, r),
        (r, height - r),
        (width - r, r),
        (width - r, height - r),
    ]

    rects = [
        (r, 0.5, width - (2 * r), height),
        (0.5, r, width, height - (2 * r)),
    ]

    for center in circle_centers:
        pygame.gfxdraw.aacircle(rounded_rect, center[0], center[1], r - 0, color)
        pygame.gfxdraw.filled_circle(rounded_rect, center[0], center[1], r - 0, color)

    for rect in rects:
        pygame.draw.rect(rounded_rect, color, rect)

    font_size = SCALE / 3 * scale / 100
    font = pygame.font.Font(pygame.font.get_default_font(), font_size)
    text = font.render(str(2 ** board.get(x, y)), True, (255, 255, 255))
    text_rect = text.get_rect(center=(width / 2, height / 2))
    rounded_rect.blit(text, text_rect)

    screen.blit(
            pygame.transform.smoothscale(
                rounded_rect,
                (local_scale * 90 / 100, local_scale * 90 / 100)),
            (((x * 100 + .5 * ((100 - scale) * scale_factor) + 5) + offsetx) * scale_factor, ((y * 100 + .5 * ((100 - scale) * scale_factor) + 5) + offsety) * scale_factor))
    def record(self, st, nd, rd):
        font = pygame.font.SysFont("Consolas", 70)
        st = "{:,}".format(int(st))
        nd = "{:,}".format(int(nd))
        rd = "{:,}".format(int(rd))
        padding = len(st)
        if len(nd) < padding:
            nd = ' ' * (padding - len(nd)) + nd
        if len(rd) < padding:
            rd = ' ' * (padding - len(rd)) + rd

        segment = ["1st: " + st, "2nd: " + nd, "3rd: " + rd]
        shift = -1
        for sen in segment:
            Surface = font.render(sen, True, (30, 30, 30))
            TextRect = Surface.get_rect()
            TextRect.center = (self.screen.get_rect().centerx,
                               self.screen.get_rect().centery +
                               2.5 * shift * self.height)
            shift += 1
            self.screen.blit(Surface, TextRect)
Exemple #46
0
 def handle_event(self, event):
     if event.type == pygame.MOUSEBUTTONDOWN:
         # If the user clicked on the input_box rect.
         if self.rect.collidepoint(event.pos):
             # Toggle the active variable.
             self.active = not self.active
         else:
             self.active = False
         # Change the current color of the input box.
         self.color = textbox_active_color if self.active else textbox_inactive_color
     if event.type == pygame.KEYDOWN:
         if self.active:
             if event.key == pygame.K_RETURN:
                 print(self.text)
                 self.text = ''
             elif event.key == pygame.K_BACKSPACE:
                 self.text = self.text[:-1]
             else:
                 self.text += event.unicode
             # Re-render the text.
             self.txt_surface = font.render(self.text, True, self.color)
Exemple #47
0
    def __init__(self, filename, size,
                 charset='abcdefghijklmnopqrstuvwxyz' +\
                         'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +\
                         '1234567890;:,.!?%&"\' '):
        filename = os.path.join('fonts', filename)
        self.filename = filename
        self.charset = charset
        self.charmap = {}

        font = pygame.font.Font(filename, size)
        self.descent = font.get_descent()
        self.w, self.h = font.size(self.charset)
        self.w += len(self.charset) * self.characterSpacing
        self.lineSize = self.h
        if self.w > self.maxTextureWidth:
            self.h = (self.w / self.maxTextureWidth + 1) * self.h
            self.w = self.maxTextureWidth
        self.tw, self.th = res.pow2(self.w), res.pow2(self.h)
        data = chr(0) * self.tw * self.th * 4
        surface = pygame.image.fromstring(data, (self.tw, self.th), 'RGBA')

        x, y = 0.0, 0.0
        for c in charset:
            render = font.render(c, True, (255, 255, 255))
            cw, ch = font.size(c)
            if x + cw >= self.tw:
                x = 0.0
                y += self.lineSize
            surface.blit(render, (x, y))
            self.charmap[c] = (x / self.tw,
                               (self.th - y - self.lineSize) / self.th,
                               (x + cw) / self.tw, (self.th - y) / self.th), cw
            x += cw + self.characterSpacing
        self.tex = glGenTextures(1)
        glBindTexture(GL_TEXTURE_2D, self.tex)
        glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameter(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexImage2D(GL_TEXTURE_2D, 0, 4, self.tw, self.th, 0, GL_RGBA,
                     GL_UNSIGNED_BYTE,
                     pygame.image.tostring(surface, 'RGBA', True))
Exemple #48
0
def start_screen():
    intro_text = [
        "Проект выполнили: Зайцева Екатерина, Барабанова Анастасия", "",
        "Правила игры:",
        "В этой игре Вам необходимо попасть в птиц из рогатки с помощью мячей",
        "Для выстрела используйте пробел, а для перемещения рогатки клавиши вправо и влево",
        "При нажатии на клавишу 'P'  игра останавливается, при повторном нажатии возобновляется",
        "При попадании в птиц Вы получаете баллы, которые выводятся в правом верхнем углу",
        "Под результатом расположен уровень, который увеличивается при уничтожении всех птиц",
        "С каждым разом птицы, рогатка и мячи ускоряются, усложняя игру",
        "В левом верхнем углу находятся жизни",
        "Их количество сокращается при столкновении птиц с землёй или рогаткой",
        "Когда последняя жизнь исчезла, игра заканчивается"
    ]

    fon = pygame.transform.scale(load_image('fon.jpg'), (width, height))
    screen.blit(fon, (0, 0))
    pygame.mixer.music.load('data/fon.mp3')
    pygame.mixer.music.play(loops=-1)
    pygame.display.set_caption('Bad birds')
    font = pygame.font.SysFont('serif', 25)
    text_coord = 20

    for line in intro_text:
        string_rendered = font.render(line, 1, (0, 33, 55))
        intro_rect = string_rendered.get_rect()
        text_coord += 10
        intro_rect.top = text_coord
        intro_rect.x = 10
        text_coord += intro_rect.height
        screen.blit(string_rendered, intro_rect)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                terminate()
            elif (event.type == pygame.KEYDOWN
                  or event.type == pygame.MOUSEBUTTONDOWN):
                return
        pygame.display.flip()
        clock.tick(FPS)
Exemple #49
0
    def enterNode(self, node):
        """Handle the logic of entering a node"""

        if self.debug:
            print "Entering %s" % (node)

        self.safeApply(node.onEnter, self)

        # Get the image to display
        img = self.safeApply(node.getImage, self)

        # Let the old node specify a transition
        if self.transitions:
            tc = self.safeApply(self.node.getTransitionClass, node)
            if tc:
                if self.debug:
                    print "Using transition", tc
                t = tc(self)
                t.setImages(self.view, img)
                t.run()

        self.view.fill(self.safeApply(node.getBackColor, self))
        vx, vy = self.view.get_size()
        pos = ((vx - img.get_width()) / 2, (vy - img.get_height()) / 2)
        #if self.debug:
        #    print "Positioning at %d, %d" % pos
        self.updateView(img, pos)

        if self.caption:
            font = pygame.font.Font(None, self.viewRect.height / 20)
            text = font.render(str(node), 1, white, black)
            textpos = text.get_rect()
            textpos.midbottom = self.view.get_rect().midbottom
            self.updateView(text, textpos)

        self.node = node

        # Fake a mousemotion event to get the cursor right.
        ev = pygame.event.Event(MOUSEMOTION, pos=pygame.mouse.get_pos())
        self.doEvent(ev)
Exemple #50
0
def check_bullet_ufo_collisions(stats, sb, ai_settings, bullets_ship,
                                ufo_group, alien_exp):
    # respond to bullet ufo collisions
    # remove any bullets and ufo that have collided
    for ufo in ufo_group:
        if ufo.explode is False:
            collision = pygame.sprite.groupcollide(bullets_ship, ufo_group,
                                                   True, False)
            if collision:
                for ufo_group in collision.values():
                    for x in ufo_group:
                        pygame.mixer.Channel(2).play(alien_exp)
                        stats.score = int(round(stats.score + x.point_value))
                        sb.prep_score()
                        ufo.explode = True
                        rounded_points = int(round(ufo.point_value, -1))
                        points_str = str(rounded_points)
                        font = pygame.font.SysFont(None, 48)
                        points_img = font.render(points_str, True,
                                                 (255, 255, 255),
                                                 ai_settings.bg_color)
                        ufo.image = points_img
Exemple #51
0
    def updateMenu(self, wa):
        backsurf = pygame.Surface(self.background.get_size(), 0, 16)
        
        menusurf = pygame.Surface(self.getMenuSize(wa), 0, 16)
        menusurf.fill(self.getMenuColor())

        font = self.getFont(wa)

        for i in range(len(self.choices)):
            text, callable = self.choices[i][:2]
            if i == self.mouseover:
                color = self.getOverColor()
            else:
                color = self.getTextColor()
            linesurf = font.render(text, 1, color)
            menusurf.blit(linesurf, (0, i * self.getTextSkip(wa)))

        menusurf.set_alpha(200)

        backsurf.blit(self.background, (0,0))
        backsurf.blit(menusurf, self.pos)
        wa.updateView(backsurf)
Exemple #52
0
    def __init__(self,
                 deminsions,
                 ident=None,
                 text=None,
                 image=None,
                 colors=(colordefs.WHITE, colordefs.GREY_BLUE)):
        super().__init__()

        self.deminsions = deminsions

        self.image = None
        if ident == None and text != None:
            self.id = text
        else:
            self.id = ident

        if text is not None:
            font = pygame.font.SysFont('', 16)
            self.image_not_selected = pygame.Surface(
                (deminsions[2], deminsions[3]))
            self.image_not_selected.fill(colors[1])
            buttonpane = font.render(text, False, colors[0])
            self.image_not_selected.blit(
                buttonpane, (5, self.image_not_selected.get_rect()[3] / 2 -
                             buttonpane.get_rect()[3] / 2))
        if image is not None:
            print("button with image")
            self.image_not_selected = image

        self.image = self.image_not_selected
        self.rect = self.image.get_rect()
        self.rect = self.rect.move(deminsions[0], deminsions[1])

        self.image_selected = pygame.Surface((deminsions[2], deminsions[3]))
        salpha = pygame.Surface((deminsions[2], deminsions[3]))
        salpha.fill(colordefs.WHITE)
        salpha.set_alpha(90)
        self.image_selected.blit(self.image_not_selected, (0, 0))
        self.image_selected.blit(salpha, (0, 0))
Exemple #53
0
def menu():
    white = (255, 255, 255)

    #width1 = 1280
    #height1 = 720

    width2 = 1366
    height2 = 768

    clock = pygame.time.Clock()
    size2 = ((width2, height2))

    dip1 = pygame.display.set_mode(size2, pygame.FULLSCREEN)
    font = pygame.font.Font(
        "C:/Users/dgome/Documents/source/Py/Test/Pixellari.ttf", 36)
    text = font.render("Punch Girl!", True, (0, 0, 0))
    ingame = True

    pygame.display.set_caption("Punch Girl")

    #Screen Loop
    while ingame:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                ingame = False
            #Key Mapping
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    ingame = False

        dip1.fill(white)
        dip1.blit(text,
                  (620 - text.get_width() // 2, 240 - text.get_height() // 2))
        pygame.display.update()

        clock.tick(60)

    pygame.quit()
 def help(self):
     font = pygame.font.SysFont("Consolas", 30)
     segment = [
         "In Alien Invasion, the player controls a rocket ship that appears",
         "at the bottom center of the screen. The player can move the ship",
         "right and left using the arrow keys and shoot bullets using the",
         "spacebar. When the game begins, a fleet of aliens fills the sky",
         "and moves across and down the screen. The player shoots and",
         "destroys the aliens. If the player shoots all the aliens, a new fleet",
         "appears that moves faster than the previous fleet. If any alien hits",
         "the player’s ship or reaches the bottom of the screen, the player",
         "loses a ship. If the player loses three ships, the game ends.",
         "", "spacebar — fire       z/c — fire anterolaterally (level>3)",
         "arrow — move       q/esc — quit       p — pause"
     ]
     shift = 1
     for sen in segment:
         Surface = font.render(sen, True, (30, 30, 30))
         TextRect = Surface.get_rect()
         TextRect.center = (self.screen.get_rect().centerx,
                            shift * self.height)
         shift += 1
         self.screen.blit(Surface, TextRect)
Exemple #55
0
def outlineText(font, char, color):
    """This outline text function is based on code by Pete Shinners"""
    offcolor = [c ^ 40 for c in color]
    notcolor = [c ^ 0xFF for c in color]

    base = font.render(char, 0, color, notcolor)
    if len(char) == 1 and ord(char) == 32:
        size = base.get_width() + 10, base.get_height() - 10
    else:
        size = base.get_width() + 2, base.get_height() + 2

    img = pygame.Surface(size, 16)
    img.fill(notcolor)
    base.set_colorkey(0)
    img.blit(base, (0, 0))
    img.blit(base, (2, 0))
    img.blit(base, (0, 2))
    img.blit(base, (2, 2))
    base.set_colorkey(0)
    base.set_palette_at(1, notcolor)
    img.blit(base, (1, 1))
    img.set_colorkey(notcolor)
    return img
Exemple #56
0
    def get_lines(self, string, break_char, width, scale, color):
        """
        Wraps text and renders text as font
        Returns list of font renders
        """

        # Font Size
        font_size = TextConstants.TEXTFONTSIZE * scale
        font, line_width = self.font(font_size)

        # Get wrapped text
        if width:
            lines = self.wrap(string, width // line_width, break_char)
        else:
            lines = [string]

        # Render font
        labels = []
        for line in lines:
            render = font.render(line, 1, color)
            labels.append(render)

        return labels
Exemple #57
0
def game_info():
    check = True
    while check:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    gaming_loop()

        screen.blit(background, (0, 0))
        message1 = font.render("INFO BAR", True, (255, 255, 255))
        message2 = intro_font.render(
            "The Space invader game is to shoot the enemies", True,
            (255, 255, 255))
        message3 = intro_font.render("Press the R button to start the game ",
                                     True, (255, 255, 255))
        message4 = intro_font.render("Press P to Pause the game at any time",
                                     True, (255, 255, 255))
        screen.blit(message1, (450, 100))
        screen.blit(message2, (250, 250))
        screen.blit(message3, (250, 370))
        screen.blit(message4, (250, 490))

        show_button("Play",
                    250,
                    650,
                    150,
                    100,
                    green,
                    light_green,
                    action="Play")
        show_button("Quit", 950, 650, 150, 100, red, light_red, action="Quit")

        pygame.display.update()
Exemple #58
0
def name():
    name = ""
    font = pygame.font.Font(None, 32)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_BACKSPACE:
                    name = name[:-1]
                elif event.key == pygame.K_RETURN:
                    return name
                    break
                else:
                    name += event.unicode
            tela.fill((0, 0, 0))
            tela.blit(background_user, (0, 0))
            block = font.render(name, True, (255, 255, 255))
            rect = block.get_rect()
            rect.center = tela.get_rect().center
            tela.blit(block, rect)
            pygame.display.flip()
Exemple #59
0
    def showHUD(self):
        font = pg.font.Font(TEXT_FONT, 18)
        text_surface = font.render("SCORE:", True, WHITE)
        text_rect = text_surface.get_rect()
        text_width1, text_height = font.size("SCORE:")
        text_rect.topleft = (0, SCREEN_HEIGHT - text_height)
        self.screen.blit(text_surface, text_rect)

        text_surface = font.render(str(player.Player.score), True, RED)
        text_rect = text_surface.get_rect()
        text_width, text_height = font.size("txt")
        text_rect.topleft = (text_width1, SCREEN_HEIGHT - text_height)
        self.screen.blit(text_surface, text_rect)

        text_surface = font.render("Round:", True, WHITE)
        text_rect = text_surface.get_rect()
        text_width2, text_height2 = font.size("txt")
        text_rect.topleft = (SCREEN_WIDTH // 2 - text_width1 + 50,
                             SCREEN_HEIGHT - text_height2)
        self.screen.blit(text_surface, text_rect)

        text_surface = font.render(str(self.Level), True, RED)
        text_rect = text_surface.get_rect()
        text_width2, text_height2 = font.size("txt")
        text_rect.topleft = (SCREEN_WIDTH // 2 + 50,
                             SCREEN_HEIGHT - text_height2)
        self.screen.blit(text_surface, text_rect)

        text_surface = font.render("Lives:", True, WHITE)
        text_rect = text_surface.get_rect()
        text_width3, text_height2 = font.size("txt")
        text_rect.topleft = (SCREEN_WIDTH - text_width3 - 100,
                             SCREEN_HEIGHT - text_height2)
        self.screen.blit(text_surface, text_rect)

        text_surface = font.render(str(self.NoOfLives), True, RED)
        text_rect = text_surface.get_rect()
        text_width2, text_height2 = font.size("txt")
        text_rect.topleft = (SCREEN_WIDTH - 45, SCREEN_HEIGHT - text_height2)
        self.screen.blit(text_surface, text_rect)
Exemple #60
0
def choose_character():
    img_choose = pygame.image.load('choose_character.png')
    text1 = font.render(
        "1.  Nombre:  Alice Nonomura, Vida: 100, Ataque: 100,  Defensa: 100 ",
        1, white)
    text2 = font.render(
        "2.  Nombre:  Alan Gado, Vida: 80, Ataque: 100,  Defensa: 120 ", 1,
        white)
    text3 = font.render(
        "3.  Nombre:  Yugo Ogami, Vida: 120, Ataque: 80,  Defensa: 100 ", 1,
        white)
    text4 = font.render(
        "4.  Nombre:  Jenny Burtory, Vida: 100, Ataque: 120,  Defensa: 80 ", 1,
        white)
    intro = True
    while intro:
        gamedisplay.blit(img_choose, (0, 0))
        gamedisplay.blit(text1, (200, 200))
        gamedisplay.blit(text2, (200, 250))
        gamedisplay.blit(text3, (200, 300))
        gamedisplay.blit(text4, (200, 350))
        pygame.display.update()
        clock.tick(60)

        for evento in pygame.event.get():
            if evento.type == pygame.QUIT:
                pygame.quit
                quit()
            elif evento.type == KEYDOWN and evento.key == evento.key == K_1:
                print('click - choose chatacter NUBER 1')
                player = peleadores[0]
                #player.stats()
                peleadores.pop(0)
                gamedisplay.fill(black)
                set_players(player, peleadores)
                exit()
            elif evento.type == KEYDOWN and evento.key == evento.key == K_2:
                print('click - choose chatacter NUBER 2')
                player = peleadores[1]
                peleadores.pop(1)
                gamedisplay.fill(black)
                set_players(player, peleadores)
                exit()
            elif evento.type == KEYDOWN and evento.key == evento.key == K_3:
                print('click - choose chatacter NUBER 3')
                player = peleadores[2]
                peleadores.pop(2)
                gamedisplay.fill(black)
                set_players(player, peleadores)
                exit()
            elif evento.type == KEYDOWN and evento.key == evento.key == K_4:
                print('click - choose chatacter NUBER 4')
                player = peleadores[3]
                peleadores.pop(3)
                gamedisplay.fill(black)
                set_players(player, peleadores)
                exit()
            elif evento.type == KEYDOWN:
                print("nada")
                pass
            else:
                pass