对于pygame,我是一个完全的业余爱好者,我需要制作一个程序,当文本以不同的方向传播时,它会改变文本的颜色。这意味着在每个按键上(上,下,左,右)颜色会有所不同。到目前为止,我已经能够让文字向各个方向移动,但是我不知道如何让颜色发生变化!任何帮助都会非常感激。
import pygame
import sys
pygame.init()
screenSize = (800,600)
screen = pygame.display.set_mode((screenSize),0)
go = True
#Define Colours
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
FUCHSIA = (255, 0, 255)
GRAY = (128, 128, 128)
LIME = (0, 128, 0)
MAROON = (128, 0, 0)
NAVYBLUE = (0, 0, 128)
OLIVE = (128, 128, 0)
PURPLE = (128, 0, 128)
TEAL = (0,128,128)
x = 25
y = 25
dx = 0
dy = 0
colour = RED
font = pygame.font.SysFont ("Arial", 72)
text = font.render ("Hello!", True, (colour))
while go:
for event in pygame.event.get():
if event.type == pygame.QUIT:
go = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
dx = -5
colour = GRAY
elif event.key == pygame.K_RIGHT:
dx = 5
colour = MAROON
elif event.key == pygame.K_UP:
dy = -5
colour = BLACK
elif event.key == pygame.K_DOWN:
dy = 5
colour = NAVYBLUE
elif event.key == pygame.K_c:
x = (400 - (text.get_width()) // 2)
y = (300 - (text.get_height()) // 2)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
dx = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
dy = 0
x = x + dx
y = y + dy
screen.fill(WHITE)
screen.blit (text, (x,y))
pygame.display.update()
答案 0 :(得分:3)
您需要再次渲染文本。因此,在您更改colour
的所有if语句之后。完成所有操作后,您需要再次拨打font.render()
。
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
colour = GRAY
elif event.key == pygame.K_RIGHT:
colour = MAROON
elif event.key == pygame.K_UP:
colour = BLACK
elif event.key == pygame.K_DOWN:
colour = NAVYBLUE
text = font.render("Hello!", True, (colour))
我删除了无关的内容。只是为了显示添加位置的上下文。