【发布时间】:2020-11-23 10:19:10
【问题描述】:
我正在使用 pygame 创建一个游戏,当您键入该字母时,该字母的颜色会发生变化。像nitrotype.com。但是问题是我不知道如何更改单个字母的颜色。 我无法清除屏幕然后执行此操作,因为那样会改变整行的颜色。 因此,要么我需要一种方法来更改单个字母的颜色,要么需要一种方法一次只在屏幕上放置一个字母。但是我不知道如何统一放置字母(使得结尾句居中)。请有人可以在这里帮助我。要么告诉我如何改变单个字母的颜色,要么告诉我如何以完美的方式放置单个字母然后改变它们的颜色。
import pygame as pg
import pygame
pg.init()
screenHeight, screenWidth = 600, 800
gameDisplay = pg.display.set_mode((screenWidth, screenHeight))
pg.display.set_caption("Nitrotype")
black = (255, 255, 255)
white = (0, 0, 0)
gameDisplay.fill(white)
pg.display.update()
gameOn = True
with open("text.txt", "r") as f:
contents = f.read()
def msgToScreen(msg, color, size):
cur = []
strings = []
words = msg.split(" ")
for i in words:
cur.append(i)
if len(" ".join(cur)) >= 35:
strings.append(" ".join(cur))
cur = []
if cur != []:strings.append(" ".join(cur))
curY = 20
for string in strings:
font = pg.font.SysFont(None, size)
text = font.render(string, True, color)
text_rect = text.get_rect(center=(screenWidth/2, curY))
gameDisplay.blit(text, text_rect)
curY += 40
return text
textOnScreen = msgToScreen(contents, black, 50)
pg.display.update()
curIdx = 0
keyCombination = {"a":pg.K_a, "b":pg.K_b, "c":pg.K_c, "d":pg.K_d, "e":pg.K_e, "f":pg.K_f,
"g":pg.K_g, "h":pg.K_h, "i":pg.K_i, "j":pg.K_j, "k":pg.K_k, "l":pg.K_l,
"m":pg.K_m, "n":pg.K_n, "o":pg.K_o, "p":pg.K_p, "q":pg.K_q, "r":pg.K_r,
"s":pg.K_s, "t":pg.K_t, "u":pg.K_u, "v":pg.K_v, "w":pg.K_w, "x":pg.K_x,
"y":pg.K_y, "z":pg.K_z}
while gameOn:
for event in pygame.event.get():
if event.type == pg.QUIT:
gameOn = False
if event.type == pg.KEYDOWN:
if event.key == keyCombination[contents[curIdx].lower()]:
#Here is where the color of the current letter should change
curIdx += 1
pg.quit()
【问题讨论】:
标签: python pygame textcolor text-formatting