Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Pygame-使用转义字符或换行符快速显示文本_Python 3.x_Pygame - Fatal编程技术网

Python 3.x Pygame-使用转义字符或换行符快速显示文本

Python 3.x Pygame-使用转义字符或换行符快速显示文本,python-3.x,pygame,Python 3.x,Pygame,嗨,我想在pygame屏幕上显示一些文字。我的课文是在“推荐”一词后加一个新行 posX = (self.scrWidth * 1/8) posY = (self.scrHeight * 1/8) position = posX, posY font = pygame.font.SysFont(self.font, self.fontSize) if text == "INFO": text = """If you are learning to play, it is recommend

嗨,我想在pygame屏幕上显示一些文字。我的课文是在“推荐”一词后加一个新行

posX = (self.scrWidth * 1/8)
posY = (self.scrHeight * 1/8)
position = posX, posY
font = pygame.font.SysFont(self.font, self.fontSize)
if text == "INFO":
   text = """If you are learning to play, it is recommended
               you chose your own starting area."""
   label = font.render(text, True, self.fontColour)
   return label, position
返回
给出blit的表面和位置

我已尝试使用三重引号方法包含空格,\n。 我不知道我做错了什么。

pygame.font.font/SysFont().render()不支持多行文本

这在文件中有说明

文本只能是单行:不呈现换行符

解决此问题的一种方法是渲染单行字符串列表。每行一个,然后在另一行下一个

例如:

posX = (self.scrWidth * 1/8)
posY = (self.scrHeight * 1/8)
position = posX, posY
font = pygame.font.SysFont(self.font, self.fontSize)
if text == "INFO":
    text = ["If you are learning to play, it is recommended",
            "you chose your own starting area."]
    label = []
    for line in text: 
        label.append(font.render(text, True, self.fontColour))
    return label, position
然后,要blit图像,可以使用另一个for循环,如下所示:

for line in range(len(label)):
    surface.blit(label(line),(position[0],position[1]+(line*fontsize)+(15*line)))
在blit的Y值中,该值为:

position[1]+(line*fontsize)+(15*line)
它所做的就是获取位置[0],这是前面的posY变量,并将其用作blit的最左上方位置

然后将(line*fontsize)添加到该值。因为for循环使用一个范围而不是列表项本身,所以行将是1、2、3等,因此可以添加到另一行的正下方


最后,(15*行)被添加到该列表中。这就是我们如何得到空间之间的余量。常量(在本例中为15)表示边距应为多少像素。数字越大,差距越大;数字越小,差距越小。添加“行”的原因是为了补偿将上述行向下移动所述金额。如果您愿意,可以去掉“*行”,看看这将如何导致行开始重叠。

这是我在代码中找到并使用的anwser。这将生成一个可以正常使用的文本表面

class TextRectException:
    def __init__(self, message=None):
            self.message = message

    def __str__(self):
        return self.message


def multiLineSurface(string: str, font: pygame.font.Font, rect: pygame.rect.Rect, fontColour: tuple, BGColour: tuple, 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.

    Parameters
    ----------
    string - the text you wish to render. \n begins a new line.
    font - a Font object
    rect - a rect style giving the size of the surface requested.
    fontColour - a three-byte tuple of the rgb value of the
             text color. ex (0, 0, 0) = BLACK
    BGColour - a three-byte tuple of the rgb value of the surface.
    justification - 0 (default) left-justified
                1 horizontally centered
                2 right-justified

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

    finalLines = []
    requestedLines = string.splitlines()
    # Create a series of lines that will fit on the provided
    # rectangle.
    for requestedLine in requestedLines:
        if font.size(requestedLine)[0] > rect.width:
            words = requestedLine.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
            accumulatedLine = ""
            for word in words:
                testLine = accumulatedLine + word + " "
                # Build the line while the words fit.
                if font.size(testLine)[0] < rect.width:
                    accumulatedLine = testLine
                else:
                    finalLines.append(accumulatedLine)
                    accumulatedLine = word + " "
            finalLines.append(accumulatedLine)
        else:
            finalLines.append(requestedLine)

    # Let's try to write the text out on the surface.
    surface = pygame.Surface(rect.size)
    surface.fill(BGColour)
    accumulatedHeight = 0
    for line in finalLines:
        if accumulatedHeight + 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, fontColour)
        if justification == 0:
            surface.blit(tempSurface, (0, accumulatedHeight))
        elif justification == 1:
            surface.blit(tempSurface, ((rect.width - tempSurface.get_width()) / 2, accumulatedHeight))
        elif justification == 2:
            surface.blit(tempSurface, (rect.width - tempSurface.get_width(), accumulatedHeight))
        else:
            raise TextRectException("Invalid justification argument: " + str(justification))
        accumulatedHeight += font.size(line)[1]
    return surface
class TextRectException:
定义初始化(self,message=None):
self.message=消息
定义(自我):
返回自我信息
def multileSurface(字符串:str,字体:pygame.font.font,rect:pygame.rect.rect,fontColour:tuple,BGColour:tuple,对正=0):
“”“返回一个包含已重新格式化的传递文本字符串的表面
为了适应给定的矩形,根据需要换行。文本
将进行抗锯齿处理。
参数
----------
字符串-要呈现的文本。\n从新行开始。
字体-字体对象
rect-提供所需曲面大小的rect样式。
fontColour-的rgb值的三字节元组
文本颜色.ex(0,0,0)=黑色
BGCOLOR-表面rgb值的三字节元组。
对齐-0(默认值)左对齐
1水平居中
2右对齐
退换商品
-------
成功-一个表面对象,其上呈现文本。
失败-如果文本不适合曲面,则引发TextRectException。
"""
最终结果=[]
requestedLines=string.splitlines()
#创建一系列适合所提供设备的线条
#矩形。
对于requestedLines中的requestedLine:
如果font.size(requestedLine)[0]>rect.width:
words=requestedLine.split(“”)
#如果我们的任何一句话太长而不合适,请返回。
用文字表示:
如果font.size(word)[0]>=rect.width:
raise TextRectException(“单词“+word+”太长,无法放入已传递的rect中。”)
#开行
累计行=“”
用文字表示:
测试线=累计线+字+“”
#在词语合适的时候构建线条。
如果font.size(testLine)[0]=rect.height:
raise TextRectException(“单词包装后,文本字符串太高,无法放入rect。”)
如果行!="":
tempSurface=font.render(线条、1、FontColor)
如果对正==0:
表面。blit(表面温度,(0,累计高度))
elif对正==1:
blit(tempSurface,((rect.width-tempSurface.get_width())/2,累计高度))
elif对正==2:
blit(tempSurface,(rect.width-tempSurface.get_width(),累计高度))
其他:
引发TextRectException(“无效的对齐参数:+str(对齐))
累计高度+=字体大小(行)[1]
返回面

谢谢您的回复,我忘了在找到答案后我问了这个问题。我还将张贴我使用的答案。