【发布时间】:2023-04-06 23:17:01
【问题描述】:
我正在创建一个游戏的基础,当一行文本在屏幕上移到很远时,它将具有滚动文本和文本换行。
一切正常(到目前为止),但在使用我的default_display_text 功能时,pygame 停止响应。当我使用 default_display_text 函数并将问候语作为变量时,它总是在“打破,打一些花哨的词”部分停止。
我已经能够用谷歌解决我所有的其他问题,但这个问题让我真的卡住了!我很乐意提供任何其他信息,希望您能在 cmets 的帮助下理解我的代码的作用。
import pygame, math, pygame.display, time, pygame.mouse
from pygame.locals import *
pygame.init()
pygame.font.init()
infoObject = pygame.display.Info()
window_height = infoObject.current_w
window_width = infoObject.current_h
gameDisplay = pygame.display.set_mode((window_height, window_width), pygame.RESIZABLE)
pygame.display.set_caption('Aperture_Game')
pygame.mouse.set_visible(False)
c_font = 'C:\Windows\Fonts\Courier Regular.fon'
background = (10,10,10)
black = (0,0,0)
white = (255,255,255)
text_color = (39, 167, 216)
clock = pygame.time.Clock()
loop = True
default_font_size = 26
greeting = "Greetings! My name is Cave Johnson, CEO of Aperture Science. Our motto here is \"If it ain't broke, slap some fancy words on it and sell it for profit!\""
'''
def message_display(text,x,y,font,color,size):
fontObj = pygame.font.SysFont(font, size)
label = fontObj.render(text, 1, color)
gameDisplay.blit(label, (x,y))
'''
def default_display_text(string,x,y):
text = ''
#a tracks i's value.
a = 0
#newline helps determine when to wrap the text.
newline = 0
#ref is a reference for when to wrap the text (I only want to wrap text after a space so the wrapping doesn't split words in half).
ref = ' '
fontObj = pygame.font.SysFont(c_font, default_font_size)
text_surface = fontObj.render(text, True, text_color)
text_rect = text_surface.get_rect()
#this for loop is what displays the text one character at a time and wraps it.
for i in range(len(string)):
gameDisplay.fill(background)
if newline == 0:
gameDisplay.blit(text_surface, (x,y))
#if the text goes to far to the right and a word is complete, I want to start a new line.
if pygame.Surface.get_width(text_surface) > 1000:
#makes sure that its not in the middle of a word.
if string[a] == ref:
#making sure its not a double space
if string[a+1] != ref:
newline = 1
text = text[a:]
else:
newline = 0
#adds another character of the string to the text variable
if newline == 0:
text += string[i]
# if newline is not 0 then the start of the text is shifted down and all the previous text is deleted.
else:
y += 25
newline = 0
text += string[a:a+1]
text = text[a:]
a = 0
a += 1
pygame.display.update()
pygame.time.wait(50)
#Just your average main loop
def main():
loop = True
while loop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
loop = False
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
loop = False
#add controls here later
gameDisplay.fill(background)
default_display_text(greeting, 50, 50)
pygame.display.update()
clock.tick(60)
main()
pygame.quit()
quit()
【问题讨论】:
-
您在
default_display_text函数中花费了大量时间,因此您必须处理for 循环中的事件。看看this answer。