【发布时间】:2014-07-06 06:47:27
【问题描述】:
我试图让对话框一次出现一个角色(就像在口袋妖怪游戏和其他类似游戏中一样)。
我在互联网上进行了搜索,但没有找到任何有用的东西。
我知道另一个这样的问题,但它并没有解决我想要做的事情。我知道这是可以做到的,因为我见过用 python 制作的游戏已经做到了。
【问题讨论】:
-
出现在控制台或pygame窗口?
-
在 pygame 窗口中。
我试图让对话框一次出现一个角色(就像在口袋妖怪游戏和其他类似游戏中一样)。
我在互联网上进行了搜索,但没有找到任何有用的东西。
我知道另一个这样的问题,但它并没有解决我想要做的事情。我知道这是可以做到的,因为我见过用 python 制作的游戏已经做到了。
【问题讨论】:
import pygame, sys
from pygame.locals import *
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
pygame.init()
DISPLAYSURF = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
def display_text_animation(string):
text = ''
for i in range(len(string)):
DISPLAYSURF.fill(WHITE)
text += string[i]
text_surface = font.render(text, True, BLACK)
text_rect = text_surface.get_rect()
text_rect.center = (WINDOW_WIDTH/2, WINDOW_HEIGHT/2)
DISPLAYSURF.blit(text_surface, text_rect)
pygame.display.update()
pygame.time.wait(100)
def main():
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
display_text_animation('Hello World!')
main()
注意:我之前没有使用过 pygame,所以这可能不起作用。
【讨论】:
下面的效果很好。并停止事件队列的任何重载(因此多行或大量文本不会停止动画)。如果嵌入在不以其他方式处理事件队列的简单应用程序中,这是必要的。
line_space = 16
basicfont = pygame.font.SysFont('MorePerfectDOSVGA', 16)
def text_ani(str, tuple):
x, y = tuple
y = y*line_space ##shift text down by one line
char = '' ##new string that will take text one char at a time. Not the best variable name I know.
letter = 0
count = 0
for i in range(len(str)):
pygame.event.clear() ## this is very important if your event queue is not handled properly elsewhere. Alternativly pygame.event.pump() would work.
time.sleep(0.05) ##change this for faster or slower text animation
char = char + str[letter]
text = basicfont.render(char, False, (2, 241, 16), (0, 0, 0)) #First tuple is text color, second tuple is background color
textrect = text.get_rect(topleft=(x, y)) ## x, y's provided in function call. y coordinate amended by line height where needed
screen.blit(text, textrect)
pygame.display.update(textrect) ## update only the text just added without removing previous lines.
count += 1
letter += 1
print char ## for debugging in console, comment out or delete.
text_ani('this is line number 1 ', (0, 1)) # text string and x, y coordinate tuple.
text_ani('this is line number 2', (0, 2))
text_ani('this is line number 3', (0, 3))
text_ani('', (0, 3)) # this is a blank line
【讨论】:
这有点简单,它创建了一个你可以随时使用的函数。在此示例中,我将我的函数称为“慢”并使其在调用时需要输入一个字符串。无论输入什么,都会一个字一个字地显示。速度取决于“睡眠”附近的值。希望这会有所帮助。
from time import * #imports all the time functions
def slow(text): #function which displays characters one at a time
for letters in text: #the variable goes through each character at a time
print(letters, end = "") #current character is printed
sleep(0.02) #insert the time between each character shown
#the for loop will move onto the next character
slow("insert text here") #instead of print, use the name of the function
如果按原样运行,它应该一次输出一个字符“在此处插入文本”。
【讨论】: