Reputation: 41
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()
Upvotes: 4
Views: 10889
Reputation: 26157
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))
I've removed the unrelated stuff. Just to show the context of where to add it.
Upvotes: 5