如何在按键上的pygame中更改文本的颜色? [英] How can you change the colour of text in pygame on keypress?

查看:333
本文介绍了如何在按键上的pygame中更改文本的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在pygame方面,我是一个完全的业余爱好者,我需要制作一个程序,当文本沿不同的方向传播时,该程序将更改文本的颜色。这意味着每次按键(上,下,左,右)的颜色都会不同。到目前为止,我已经能够使文本向各个方向移动,但是我不知道如何改变颜色!

I'm a complete amateur when it comes to pygame, and I need to make a program that will change the colour of the text when the text travels in a different direction. Meaning that on each keypress, (up, down, left, right) the colour will be different. So far I've been able to get the text moving in each direction, however I don't understand how to get the colour to change! Any help would be so greatly appreciated.

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()


推荐答案

您需要再次渲染文本。因此,毕竟您在if语句中更改了颜色。毕竟,您需要再次调用 font.render()

You need to render the text again. So after all your if statements where you change colour. After all those you need to call font.render() again.

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))

我已经删除了无关的内容。只是为了显示添加位置的上下文。

这篇关于如何在按键上的pygame中更改文本的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆