Выводный класс Pygame для рисования не получается

Вопрос:

У меня есть класс, который представляет собой немного текста, который можно нарисовать на экране. Этот класс предназначен для использования в отношении объекта Window который при его рисовании пропускает подповерхность поверхности, которую она передавала функции draw() текстового элемента.

Окно рисует, но текст нет. Он также не рисует, когда я вызываю функцию DrawE() TextElement напрямую. Я изучил код с отладчиком, и blit определенно делается. Я также попытался переключить шрифт на "Arial" вместо того, чтобы позволить Pygame захватить значение по умолчанию.

import pygame

#Background and edge color of windows
global bgcolor
global bordercolor
global txtcolor
#Pygame font object that most text will be drawn in
global mainfont

#Defaults; code that imports us can change these.
#Black background with white borders & text
bgcolor=(0,0,0)
txtcolor=(255,255,255)
bordercolor=(255,255,255)
#This will give us whatever font Pygame is set up to use as default
if not __name__== "__main__":
#Font module needs to be initialized for this to work; it should be if we're imported, but won't if
#we're being executed directly.
mainfont=pygame.font.SysFont(None,12)
else:
mainfont=None


class Window:
"""The base UI class. Is more-or-less a way to draw an empty square onto the screen. Other things are derived from this.
Also usable in its own right as a way to manage groups of more complex elements by defining them as children of
a basic window."""

def __init__(self, rect):

self.rect=rect

#'children' of a window are drawn whenever it is drawn, unless their positions are outside the area of the window.
self.children=[]

def draw(self, surface):
"Draw this window to the given surface."

pygame.draw.rect(surface, bgcolor, self.rect)
#Draw non-filled rect with line width 4 as the border
pygame.draw.rect(surface, bordercolor, self.rect, 4)

self._draw_children(surface)

def _draw_children(self,surface):
"Call draw() on each of the children of this window. Intended to be called as part of an element draw() function."
for thechild in self.children:
#We use a subsurface because we only want our child elements to be able to access the area inside this window.
thechild.draw(surface.subsurface(self.rect))

class TextElement(str):
"""A bit of static text that can be drawn to the screen. Intended to be used inside a Window, but can be drawn
straight to a surface. Immutable; use DynamicTextElement for text that can change and move."""

def __new__(cls,text,font,rect=pygame.Rect((0,0),(0,0))):
self=super().__new__(cls,text)
self.image=font.render(text,True,txtcolor)
self.rect=rect
return self

def __repr__(self):
return str.join("",("TextElement('",self,"')"))

def draw(self,surface):
self.image.blit(surface,self.rect.topleft)

class DynamicTextElement():
"""A bit of text whose text can be changed and that can be moved. Slower than TextElement."""

def __init__(self,text,font,rect):
self.text, self.font, self.rect = text, font, rect

def __repr__(self):
return str.join("",("DynamicTextElement('",self.text,"')"))

def draw(self,surface):
image=self.font.render(self.text,True,txtcolor)
image.blit(surface,self.rect.topleft)

if __name__ == '__main__':
pygame.init()
mainfont=pygame.font.SysFont(None,12)
screen=pygame.display.set_mode((800,600))
mywindow=Window(pygame.Rect(150,150,600,300))
mytext=TextElement("Hello world! This is static, immutable text!",mainfont,pygame.Rect((200,200),(100,100)))
mydyntext=DynamicTextElement("And this is dnyamic, movable text!",mainfont,pygame.Rect((200,230),(100,100)))
print(mytext.image)
mywindow.children.append(mytext)

clock=pygame.time.Clock()

while True:
pygame.event.pump()
clock.tick(60)
screen.fill((55,55,55))
mywindow.draw(screen)
mytext.draw(screen)
pygame.display.flip()

Есть идеи?

Лучший ответ:

Ты используешь

    self.image.blit(surface, self.rect.topleft)

но должно быть

    surface.blit(self.image, self.rect.topleft)

surface и self.image в неправильных местах.

Вы пытались нарисовать поверхность по тексту.

У вас такая же проблема в DynamicTextElement()


BTW: Я использую Python 2, поэтому мне пришлось использовать str

self = str.__new__(cls,text)

вместо super()

self = super().__new__(cls,text)

Оцените статью
TechArks.Ru
Добавить комментарий